Location: PHPKode > projects > Atom PhotoBlog > install.php
<?  
/*
Atom PhotoBlog (Installer Script) - PHP5 based photo-blogger
Copyright (C) 2007 by Sascha Tayefeh

http://www.ilenvo.de

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/


$path=dirname(__FILE__);
$url="http://".$_SERVER["SERVER_NAME"].substr_replace($_SERVER['PHP_SELF'],"",strrpos($_SERVER['PHP_SELF'],'/'));


$replaceWrong=array( '\"'=>'"', "\'"=>"'"); //! All chars that are going to be replaced in crucial strings to save.

/*!
Replace strings
*/
function recodeWrong($string) 
{
   global $replaceWrong;
   return str_replace(array_keys($replaceWrong),array_values($replaceWrong),$string);
}

/*!
Create a salten hash and save the login and password to a file.
*/

function savePw($lg,$paw)
{
   global $salt;
   $pwfile='./apbData/apbpw.php';
   $fp=fopen($pwfile,"w+") or die("<p class=\"apb setup form error\">*** ERROR: Could not create password file ".$pwfile.". Check your directory and permission settings for ./apbData</p>");

   $writeString="<?php\n";
      $writeString.='$lg=\''.$lg."';\n";
      $writeString.='$pw=\''.md5($salt.$paw)."';\n";
   $writeString.='?>'."\n";

   fwrite($fp, $writeString);
   fclose($fp);
}


/*!
Create a salten hash and save the login and password to a file.
*/

function writeIndexPhp($path)
{
   global $salt;
   $indexFile=$path.'/index.php';
   $fp=fopen($indexFile,"w+") or die("<p class=\"apb setup form error\">*** ERROR: Could not create password file ".$indexFile.". Check your directory
   and permission settings for $path</p>");

   $writeString="<?php header('Location: ../index.php'); \n";
   $writeString.='?>'."\n";

   fwrite($fp, $writeString);
   fclose($fp);
}



/*!
Check conditions: Are certain directories writeable? PHP>5.0 available? Libraries?
*/
function checkCondition()
{
   $error['dataDir']=$error['blogDir']= $error['phpVersion']= FALSE;
   $good=TRUE;
   $phpMainVersion=(int) substr(phpversion(),0,1);
   $gd="";
   if(function_exists('gd_info'))
   {
	   $gdArray=gd_info();
	   $gd=$gdArray['GD Version'];
   } 

   if(!is_Writable("./apbData")) { $error['dataDir']=TRUE; $good=FALSE; }
   if(!is_Writable("./blog")) { $error['blogDir']=TRUE; $good=FALSE; }
   if($phpMainVersion <5) { $error['phpVersion']=TRUE; $good=FALSE;}
   if($gd=="") { $error['gd']=TRUE; }


   echo "<ul class=\"apb setup form left\">";

   // Are dirs writeable?
   if(!$error['dataDir']) echo "<li class=\"apb setup form success block \">./apbData is writeable-> GOOD</li>"; 
   else echo "<li class=\"apb setup form error block \">ERROR: ./apbData is NOT WRITABLE!!!</li>";

   if(!$error['blogDir']) echo "<li class=\"apb setup form  success block \">./blog is writeable-> GOOD</li>";
   else echo "<li class=\"apb setup form error block \">ERROR: ./blog is NOT WRITABLE!!!</li>";

   // Is PHP-Version sufficiant?
   if(!$error['phpVersion']) echo "<li class=\"apb setup form success block \">PHP-Version ".phpversion()." -> GOOD</li>";
   else echo "<li class=\"apb setup form error block \">ERROR: PHP-Version is &lt; 5 (Current Version: ".phpversion()."). I cannot proceed, get yourself more up-to-date php-version</li>";

   // Is PHP-Version sufficiant?
   if(!$error['phpVersion']) echo "<li class=\"apb setup form success block \">GD seems to be installed -> GOOD</li>";
   else echo "<li class=\"apb setup form error block \">WARNING: I could not locate GD-Library. Maybe I am wrong, so I will continue anyway. In case I am right and GD is NOT installed, you will NOT be able to use this script. Solution: Install the PHP Gd-Library. </li>";



   echo "</li>"; 
   echo "</ul>";

   return $good; 
}


/*!
Actually, create the vars.php file that contains all runtime variables.
*/
function saveVars($apbPara)
{
   $apbPara['picUrl']=$apbPara['rootUrl']."/blog";
   $apbPara['picPath']=$apbPara['rootPath']."/blog";
   $apbPara['blogOwner']=recodeWrong($apbPara['blogOwner']);
   $apbPara['blogTitle']=recodeWrong($apbPara['blogTitle']);
   $apbPara['blogSubTitle']=recodeWrong($apbPara['blogSubTitle']);
   $apbPata['styleSheet']='./apbCss/atomPB.css';

   $fp=fopen('./apbData/vars.php',"w+") or die("Could not write Logfile");
   $buf ='<?php'."\n\n";
      $buf .='$apbPara=array('."\n";
      $c=count($apbPara); $i=0;
      foreach( $apbPara as $key => $value) 
      {
	 $value=str_replace('"','\"',$value);
	 $buf .= "\t\"$key\"\t=>\"$value\"";
	 $buf .=",\n"; 
      } 
      $buf.= "\t".'"embedCopyright"=> FALSE'."\n";
      $buf.= ");\n";
   $buf.= "\n?>\n";

   fwrite($fp,$buf);
   fclose($fp);
}

/*!
Clean up the blog-dir.
*/
function rmAll($dir) 
{
   if (substr($dir,-1) != "/") $dir .= "/";
   if (!is_dir($dir)) return false;

   if (($dh = opendir($dir)) !== false) 
   {
      while (($entry = readdir($dh)) !== false) 
      {
	 if ($entry != "." && $entry != "..") 
	 {
	    if (is_file($dir . $entry) || is_link($dir . $entry)) unlink($dir . $entry);
	 }
      }
      closedir($dh);
      return true;
   }
   return false;
}

/*!
Get the charset-encoding from the client.
*/
function getEncoding()
{
   $defEnc="ISO-8559-1";
   if(isset($_SERVER["HTTP_ACCEPT_CHARSET"])) 
   {
      $enc=explode(";",$_SERVER["HTTP_ACCEPT_CHARSET"]);
      $enc=explode(",",$enc[0]);
      if(isset($enc[0]) && preg_match('/^rtf|ISO/i',$enc[0]))   { $encoding=$enc[0]; }
      else  { $encoding=$defEnd; }
   }
   else  { $encoding=$defEnd; }
   return $encoding;
}

/*!
If form was posted, find out what to 'do', otherwise choose to print the form
*/
if(isset($_POST['do'])) $getDo=$_POST['do']; else $getDo="default";

/*
Out HTML-Here-code
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=<? echo $encoding; ?>" />
<link rel="stylesheet" href="./apbCss/atomPB.css"
type="text/css" media="all" />
</head>
<body class="apb setup form">
<div id="workbench" class="apb setup form">
<div id="setupForm" class="apb setup form">
<h1 class="apb setup form">Atom Photo Blog Installation Script</h1>


<?
/*
In case, form was sent, check and save the vars
*/
if($getDo=="save")
{
   echo "<h1 class=\"apb setup form\" >Storing Data</h1>";
   echo "<ul class=\"apb setup form\">";

   // *** ERROR-CHECK
   if ( (isset($_POST['name']) && trim($_POST['name'])=="") )
   $error['name']="Invalid name: Name is empty?!";
   elseif (preg_match('/[^a-zA-Z ]/',trim($_POST['name'])))
   $error['name']="Invalid name: Only letters allowed";

   if ( (isset($_POST['email']) && trim($_POST['email'])=="") )
   $error['email']="Invalid email: Email is empty?!";
   elseif (!preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i',trim($_POST['email'])))
   $error['email']="Invalid email: ".$_POST['email']." is no proper syntax for an e-mal address.";

   if (preg_match('/[^a-z0-9 ]/i',trim($_POST['adLg'])))
   $error['adLg']="Invalid name: Only letters and numbers allowed";
   elseif ( (isset($_POST['adLg']) && trim($_POST['adLg'])=="") )
   $error['adLg']="Invalid name: Admin LoginName is empty?!";

   if ( (isset($_POST['adPw']) && trim($_POST['adPw'])=="") )
   $error['adPw']="Invalid admin password: password is empty?!";
   elseif ( $_POST['adPw'] != $_POST['adPwRep'] )
   $error['adPwRep']="Invalid admin password: Passwords do not equal!";

   if ( (isset($_POST['myPw']) && trim($_POST['myPw'])=="") )
   $error['myPw']="Invalid MySQL password: password is empty?!";
   elseif ( $_POST['myPw'] != $_POST['myPwRep'] )
   $error['myPwRep']="Invalid MySQL password: Passwords do not equal!";

   if ( (isset($_POST['title']) && trim($_POST['title'])=="") )
   $error['title']="Invalid title: Title is empty?!";

   if ( (isset($_POST['mySrv']) && trim($_POST['mySrv'])=="") )
   $error['mySrv']="Invalid Mysql-Server: Mysql-Server MUST NOT BE EMPTY!";

   if ( (isset($_POST['myDb']) && trim($_POST['myDb'])=="") )
   $error['myDb']="Invalid Mysql-Database: Mysql-Database MUST NOT BE EMPTY!";

   if ( (isset($_POST['myLg']) && trim($_POST['myLg'])=="") )
   $error['myDb']="Invalid Mysql-Login: Mysql-Loginname MUST NOT BE EMPTY!";

   if(isset($error))
   {
      echo "<ul class=\"apb setup form error\">";
      foreach ($error as $key => $value)
      echo "<li class=\"apb setup form error\">*** ERROR: $value</li>";

      echo "</ul>";
      die;
   } else
   {
	   $error['rights']=FALSE;
   }
   // *** SAVE vars.php
   $apbPara=array(
      "blogOwner"	=> trim($_POST['name']),
      "blogOwnerEmail"	=> trim($_POST['email']),
      "blogSubTitle"	=> trim($_POST['subTitle']),
      "blogTitle"	=> trim($_POST['title']),
      "htmlEncoding"	=> getEncoding(),
      "rootPath"	=> $_POST['rootPath'],
      "rootUrl"		=> $_POST['rootUrl'],
      "mysqlServer"	=> trim($_POST['mySrv']),
      "mysqlLogin"	=> trim($_POST['myLg']),
      "mysqlPasswd"	=> trim($_POST['myPw']),
      "mysqlDb"		=> trim($_POST['myDb'])
   );

   echo "<li class=\"apb setup form\">Saving Common Vars</li>";
   saveVars($apbPara);

   // ***** Create Random Salt
   echo "<li class=\"apb setup form\">Saving Salt</li>";
   $mySalt="";

   for($i=0; $i<15; $i++)
   {
      $a[1]=rand(48,57); // Chose a number
      $a[2]=rand(65,90); // Chose a capital letter
      $a[3]=rand(97,122); // Chose a small letter
      $mySalt.=chr($a[rand(1,3)]); //  Terminal choice
   }

   $fp=fopen('./apbData/salt.php',"w+") or die("<p class=\"apb setup form error\">*** ERROR: Could not create salt file.  Check your directory and permission settings for ./apbData</p>");

   fwrite($fp,'<?php $salt="'.$mySalt.'"; ?>'."\n");
   fclose($fp);

   // ***** Re-read vars
   include "./apbData/vars.php";
   require_once('./apbData/salt.php');
   require_once "./apbClasses/AtomPhotoBlog.class.php";


   // ***** Store Admin Password
   echo "<li class=\"apb setup form\">Saving Admin Password</li>";
   savePw($_POST['adLg'],$_POST['adPw']);

   // Set and store user-defined variables
   // MySQL Access Data
   echo "<li class=\"apb setup form\">Creating MySQL-Tables</li>";

   // ***** Create MySQL Tables
   $apbPara['doSession']=FALSE; // Don't start session to avoid 'header already sent' blabla
   $mysql=new AtomPhotoBlog($apbPara);
   $mysql->mysqlServer=$apbPara['mysqlServer'];
   $mysql->mysqlLogin=$apbPara['mysqlLogin'];
   $mysql->mysqlPasswd=$apbPara['mysqlPasswd'];
   $mysql->mysqlDb=$apbPara['mysqlDb'];
   $mysql->mysqlConnect();
   $mysql->mysqlDeleteTables();
   $mysql->mysqlCreateTables();
   $mysql->mysqlDisconnect();

   // ***** cleanup blogdir

   echo "<li class=\"apb setup form\">Proceeding Blogdir</li>";
   rmAll($apbPara['picPath']);

   writeIndexPhp("./blog/");

   // ***** Send an e-mail to admin

   $message = "This is an automatic email from the atomPhotoBlog install-script.\n\n";
   $message.= "You (or someone else using this email) has proceeded this script and";
   $message.= "submitted following login-data:\n\n";
   $message.= "Login:".$_POST['adLg']."\n";
   $message.= "PassWord:".$_POST['adPw']."\n\n";
   $message.= "For security reasons, this password cannot be retrieved when lost.";
   $message.= "So take care of it!\n\n"; 
   $message=wordwrap($message);

   echo "<li class=\"apb setup form\">E-mail sent</li>";
   echo "</ul>";
   mail($_POST['email'],"atomPhotoBlog Messenger",$message);

   // ****** CHMOD 755 ON DATADIRS ******
   if(!chmod("./apbData",0755))  { echo "<p class=\"apb setup form warning\">*** WARNING: Could not change access rights of ./apbData! The installation way <span class=\"success\">successful</span>, anyway, you can continue. Still: Please, change the rights manually to 0755!</p>"; $error['rights']=TRUE; }
   if(!chmod("./blog",0755)) { echo "<p class=\"apb setup form warning\">*** WARNING: Could not change access rights of ./blog! The installation way <span class=\"success\">successful</span>, anyway, you can continue. Still: Please, change the rights manually to 0755!</p>";$error['rights']=TRUE; }


   echo '<p class="apb setup warning form" style="margin-top: 0.5em;" >For security reasons, DELETE the script &quot;./install.php&quot; from your server!  I have already changes access rights to 0000, so it cannot be executed anymore. If you want to re-run this script, do something like chmod 0644 ./install.php or use your ftp-client to give this script read-rights</p>';



   echo "<p class=\"apb setup form success\" style=\"margin-top: 1em; font-size: xx-large;\">SUCCESS!!!</p>";
   echo "<p class=\"apb setup form success\" style=\"font-size: large;\">Goto <a href=\"./atomPhotoBlog.php?do=login\">admin-login</a> to proceed with uploading and further configuration.</p>";


   if(!$error['rights'])
   if(!chmod("./install.php",0000)) echo "<p class=\"apb setup form warning\">*** WARNING: Could not change access rights of install.php! Please, change the rights manually!</p>";

} else {
?>
<p class="apb setup form">This seems to be the first time you enter
this directory. I will try and install &apos;Atom Photo Blog&apos;
for you. Before proceeding, you should know that:</p>

<ol class="apb setup form">
<li>PHP Version > 5 must be installed.</li>
<li>GD-Library must be installed.</li>
<li>DOM-Library must be installed.</li>
<li>Directories ./apbData and ./blog must be writeable.</li>
</ol>

<p class="apb setup form">
This program is free software; you can redistribute it and/or
modify it under the terms of the 
<a target="_blank" href="http://www.gnu.org/copyleft/gpl.html">
GNU General Public License</a> as published by the Free 
Software Foundation; either version 2 of the License, or 
(at your option) any later version.
</p>

<p class="apb setup form">
I will now test your server. If &apos;checking conditions&apos; returns solely green
results, installation should work perfectly. If not, visit the 
<a href="http://www.ilenvo.de/apb/" target="_blank">Homepage of Atom Photo Blog</a> to
read the manual, F.A.Q., or to send a question via e-mail.
</p>

<h2 class="apb setup form">Checking conditions</h2>
<? 
if(checkCondition()) // Only print form, if server conditions are o.k.
{
?>
<form method="post" action="<?	 echo $_SERVER['PHP_SELF']; ?>">

<hr class="form"/>
<h2 class="apb setup form">Personal Information</h2>
<dl class="apb setup form">
<dt class="apb setup form">Your full Name (letters allowed only!):</dt><dd class="apb"> <input type="text" class="abp inputbox" name="name" size="40" /></dd>
<dt class="apb setup form">Your Email:</dt><dd class="apb setup form"><input  type="text"class="abp inputbox" name="email" size="40" /></dd>
<dt class="apb setup form">Title of this blog:</dt><dd class="apb setup form"><input type="text" class="abp inputbox" name="title" size="40" /></dd>
<dt class="apb setup form">SubTitle of this blog:</dt><dd class="apb setup form"><input type="text" class="abp inputbox" name="subTitle" size="40" /></dd>
</dl>

<hr class="form"/>
<h2 class="apb setup form">Login Information for ADMIN</h2>
<dl>
<dt class="apb setup form">LoginName (letters and digits only):</dt><dd class="apb setup form"> <input  type="text" class="abp inputbox" name="adLg" size="40" /></dd>
<dt class="apb setup form">Password:</dt>
<dd class="apb setup form"><input  type="text" class="abp inputbox" name="adPw" size="10" /></dd>
<dd class="apb setup form">Repeat: <input type="text" class="abp inputbox" name="adPwRep" size="10" /></dd>
</dl>

<hr class="form"/>
<h2 class="apb setup form">MySQL Information</h2>
<dl class="apb setup form">
<dt class="apb setup form">MySQL <span class="important" style="font-weight: bold;">Server</span>:</dt><dd class="apb setup form"> <input  type="text" class="abp inputbox" name="mySrv" size="40" /></dd>
<dt class="apb setup form">MySQL <span class="important" style="font-weight: bold;">Database:</span></dt><dd class="apb setup form"><input  type="text" class="abp inputbox" name="myDb" size="40" /></dd>
<dt class="apb setup form">MySQL <span class="important" style="font-weight: bold;">Login</span>:</dt><dd class="apb setup form"> <input  type="text" class="abp inputbox" name="myLg" size="40" /></dd>

<dt class="apb setup form">MySQL <span class="important" style="font-weight: bold;">Password</span>: </dt>
<dd class="apb setup form"><input  type="text" class="abp inputbox" name="myPw" size="10" /></dd>
<dd class="apb setup form">Repeat: <input type="text" class="abp inputbox" name="myPwRep" size="10" /></dd>


</dl>
<hr class="form"/>

<h2 class="apb setup form">Server Path &amp; Url</h2>
<p class="apb setup form">These should have been identified automatically. In case, something went wrong or you are not satisfied, feel free to
change this path/url. Otherwise, you are advised to leave this as it is.</p>
<dl class="apb setup form">
<dt class="apb setup form">Server Path:</dt><dd class="apb setup form"> <input  type="text" class="abp inputbox" name="rootPath" size="60" 
value = "<? echo $path; ?>"/></dd>
<dt class="apb setup form">Server Url:</dt><dd class="apb setup form"> <input  type="text" class="abp inputbox" name="rootUrl" size="60" 
value = "<? echo $url; ?>" /></dd>
</dl>


<dl class="apb setup form">
<dt class="apb setup form">Please CHECK all your entries before </dt><dd class="apb setup form"><input class="inputbox"  type="submit" value="Submit" />
<input type="hidden" name="do" value="save" />
</dd>
</dl>

</form>
<? 
} // End If CheckCondition
else  // If check conditions failed, print error
{
?>

<p>I will not continue until you have made those directories writeable for me or you have installed PHP>5. If your problem
concerns unwriteable directories, try something like chmod 0777. 
Don't be afraid of doing so, I will chmod to 0755 (blogdir: ./blog) and to 0750 (datadir: ./apbData) when I'm finished. 
If you are an expert, you are encouraged to improve the security of these rights.</p>
<?
} // End Else Check Condition
?>

<? 
} // End If Save
?>


</div> <!-- end div setup form -->
</div> <!-- end div workbench -->
</body>
</html>
Return current item: Atom PhotoBlog