Location: PHPKode > projects > Atom PhotoBlog > apbClasses/Admin.class.php
<?php
   /*
   Admin.class.php (Atom PhotoBlog Version) - A php-class distri-
   buted with Atom PhotoBlog.
   Copyright (C) 2007 by Sascha Tayefeh

   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.
   */

   /*!
   The Admin-class. 

   PARAMETERS:
      private $n // Number of times that the client has tried to login today.
      protected $accessGranted  // BOOL: Access granted=TRUE, Access denied=FALSE
      protected $remoteAddr // The adress of the client for whom the cookie was set
      public $cookieLifeTime // How long shall the cookie be stored?
      private $pw=array // Assoc. array that has to be set at construction time
      (
	 "FILE"=>"./data/apbpw.php",   	// The path to the password file
	 "FAILLOG"=>"./data/apb.log",  	// The path to the the logfile
	 "SESSIONNAME"=>"apb",		// name of the session/cookies
	 "LOGOUTURL"=>"", 		// Where to forward on successul login
	 "LOGINURL=>"",	 		// Where to forward on successul logout
	 "MAXTRIES"=>10,		// How many times can a single session try to login?
	 "SALT"=>""			// The salt (randomly generated by install.php) for the password-hash
      );

 
   METHODS:
      private function countFailures()  // Count failed login-attempts
      private function failExceed()  // React on exceeded login-failures 
      protected function readPw() // Read password from password-file
      public function savePw($lg,$paw)  // save new Password and Login to file
      public function checkPw($lg,$paw)  // test if login and password are ok (errorcheck)
      public function getLoginName() // returns the login-name
      public function Admin($pw) // The constructor
      public function login() // Print login-form
      public function logout()  //  Destroy session and logout
      public function checkAccess() // Check if access is granted

   */

   class Admin
   {
      protected $accessGranted=FALSE; //! BOOL: Access granted=TRUE, Access denied=FALSE
      protected $remoteAddr="";  //! The adress of the client for whom the cookie was set
      public $cookieLifeTime=60000;  //! How long shall the cookie be stored?
      private $n=0;  //! Number of times that the client has tried to login today.

      private $pw=array
      (
	 "FILE"=>"./data/apbpw.php",
	 "FAILLOG"=>"./data/apb.log",
	 "SESSIONNAME"=>"apb",
	 "LOGOUTURL"=>"",
	 "LOGINURL"=>"",
	 "MAXTRIES"=>10,
	 "SALT"=>"uiwq4f8eu"
      );

      public function Admin($pw)
      {
	 foreach(array_keys($pw) as $key)
	 {
	    $this->pw[$key]=$pw[$key];
	 }
      }

      public function logout()
      {
	 $this->accessGranted=FALSE;
	 session_destroy();
	 echo "<h2 class=\"apb form  success\">Logout Successfull</h2>";
	 echo '<p  class=\"apb form \" style="font-size: large;"> Click <a href="'.$this->pw['LOGOUTURL'].'">';
	 echo 'here</a> to continue </p>';
      }

      public function checkAccess()
      {
	 session_name ($this->pw['SESSIONNAME']); // Set the session-name
	 session_set_cookie_params($this->cookieLifeTime); // and its life-time
	 session_start();
	 if (!isset($_SESSION['passed']) || !$_SESSION['passed'])
	 {
	    $this->accessGranted=FALSE;
	 } else {
	    $this->accessGranted=TRUE;
	 }
	 return $this->accessGranted;
      }

      private function countFailures()
      {
	 $date[0]=date("Y-m-d",time()); // Get current date
	 $failFile=$this->pw['FAILLOG'];

	 if(!file_exists(($failFile)))
	 {
	    $fp=fopen($failFile,"w+") or die("Could not write Logfile");
	    fclose($fp);
	 }

	 $fp    = fopen($failFile, "r")  or die("Could not read Logfile"); // open failure log-file

	 while (!feof($fp))
	 {
	    $buffer= explode(";",fgets($fp, 500)); // import line and store in buffer-array
	    if(isset($buffer[1])) // Don't proceed blank lines
	    {
	       $date[1]=date("Y-m-d",$buffer[1]); // convert timeStamp from file

	       // Find out how many times this IP has failed to login today
	       if ($buffer[0] == $this->remoteAddr &&  $date[1]==$date[0])
	       {
		  $this->n++;
	       }
	    }
	 }
	 fclose($fp);
      }

      private function failExceed()
      {
	 echo "<h1 class=\"apb form warning\">Access denied!</h1>";
	 echo "<p class=\"apb form warning\">ERROR: ";
	 echo "Your IP Adress (".$this->remoteAddr.") has exceeded maximum attempts for today. Keep trying tommorrow.";
	 echo "</p>";
      }

      public function savePw($lg,$paw)
      {
	 if($this->accessGranted)
	 {
	    $pwfile=$this->pw['FILE'];
	    $fp=fopen($pwfile,"w+") or die("<p class=\"apb form error\">*** ERROR: Could not create password file ".$pwfile.". Check your directory and permission settings for the datadir</p>");

	    $writeString="<?php\n";
	       $writeString.='$lg='.$lg;
	       $writeString.="\n";
	       $writeString.='$pw='.md5($this->pw['SALT'].$paw);
	       $writeString.="\n";
	    $writeString.='?>'.$lg;

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

	    echo "<p class=\"apb form \" >Login was updated successfully.</p><p class=\"apb form\" >New Login: ".$lg."<br />New Password: ".$paw."</p>";
	 } else {
	    die("<p class=\"apb form error\">*** ERROR: Permission to change Login Data denied</p>");
	 }
      }

      public function login()
      {
	 $this->remoteAddr=$_SERVER['REMOTE_ADDR'];// Get current remote ip
	 $this->countFailures(); // Get number of failures for this ip and for today
	 $pwfile=$this->pw['FILE'];

	 // Check if passwordfile exists. If not, create one with standard password
	 if(!file_exists(($pwfile)))
	 {
	    echo "<h2 class=\"apb form\" >ATTENTION: No Passwordfile found!</h2>";
	    echo "<p class=\"apb form\" >You cannot login without a password-file. Please, proceed the installation";
	    echo "procedure as described in the manual in order to get this going.</p>";
	    return;
	 }

	 // Deny Access, if failures exeed three for today
	 if($this->n >= $this->pw['MAXTRIES'])
	 {
	    $this->failExceed();
	 } else {
	 ?>
      <form action="<?echo $_SERVER['PHP_SELF']; ?> " method="post">
      <table id="apbAdminLogin" class="apb admin form">
      <tr class="apb admin form "><td class="apb admin form">Login: </td><td class="apb admin form"><input type="text" name="username" /></td></tr>
      <tr class="apb form admin"><td class="apb form admin">Password: </td><td class="apb form admin"><input type="password" name="password" /></td></tr>
      <tr class="apb form admin"><td class="apb form admin">&nbsp;</td><td class="apb form admin"><input type="submit" value="Submit" /></td></tr>
      </table>
      <input type="hidden" name="do" value="pwDone" />
      </form>
      <?
	 }
      }

      protected function readPw()
      {
	 $pwfile=$this->pw['FILE'];

	 $fp=fopen($pwfile,"r") or die("Could not read password file");

	 while(! feof($fp))
	 {
	    $l=explode('=',fgets($fp, 1048576)); // import line and store in buffer-array
	    if(isset($l[0])) $key= trim(str_replace("$","",$l[0]));
	    if(isset($l[1])) $value= trim(preg_replace("/[;']/","",$l[1]));

	    if(isset($l[0]) && isset($l[1]))
	    {
	       $fileArray[$key]=$value;
	    }
	 }

	 return $fileArray;
      }

      public function getLoginName()
      {
	 $a=$this->readPw();
	 $lg=trim($a['lg']);
	 return $lg;
      }

      public function checkPw($lg,$paw)
      {
	 $failFile=$this->pw['FAILLOG'];
	 $this->remoteAddr=$_SERVER['REMOTE_ADDR'];
	 $this->countFailures(); // Get number of failures for this ip and for today
	 if($this->n > $this->pw['MAXTRIES'])
	 {
	    $this->failExceed();
	 } else
	 {
	    $pwfile = $this->readPw();

	    $pwpost['lg']=$lg;
	    $pwpost['pw']=md5($this->pw['SALT'].$paw);

	    if ( ($pwpost['lg'] != trim($pwfile['lg'])) || ($pwpost['pw'] != trim($pwfile['pw'])) )
	    {
	       $timeStamp=time();
	       $date=date("Y-m-d_H:i:s",$timeStamp);
	       $fp    = fopen($failFile, "a+")
	       or die("<p class=\"apb form  error\">*** ERROR: Could not modify admin logfile file. Check your directory and permission settings for the datadir</p>");

	       fwrite($fp, $this->remoteAddr.";".$timeStamp.";".$date.";".$_POST['username']."\n");
	       fclose($fp);

	       echo "<h1 class=\"apb form error admin\">Access denied!</h1>";
	       echo "<p class=\"apb form admin \">ERROR: Login does not match stored data! ";
	       echo "Your IP Adress (".$this->remoteAddr.") was logged.";
	       echo "</p>";

	       echo "<p class=\"apb form admin\">You may go <a href=\"".$_SERVER['PHP_SELF']."?do=login\">back and try again</a>";
	    } else
	    {
	       $_SESSION['passed'] = true;

	       echo "<h2 class=\"apb form  success\">Access granted</h2>";
	       echo '<p class=\"apb form \" >You may now make use of the admin-menu and of restricted items.</p>';
	       echo '<p  class=\"apb form \" style="font-size: large;"> Click <a href="'.$this->pw['LOGINURL'].'">';
	       echo 'here</a> to continue </p>';
	       exit;
	    }
	 }
      }
   }
?>
Return current item: Atom PhotoBlog