Location: PHPKode > scripts > SelectaPix Image Gallery > classes/admin_user.php
<?php
/* +----------------------------------------------------------------------+
   |SelectaPix Open Source Gallery	                                      |
   +----------------------------------------------------------------------+
   | Copyright (c) 2004 OutOfTheTrees			                          |
   |                                                                      |
   | http://www.outofthetrees.co.uk/index.php                             |
   | 												                      |
   +----------------------------------------------------------------------+
   | This source file is subject to version 2.0 of the GPL license,       |
   | that is bundled with this package in the file LICENSE, and is        |
   | available through the world-wide-web at the following url:           |
   | http://www.outofthetrees.co.uk/license/2_0.txt.                      |
   | If you did not receive a copy of the SelectaPix license and are 	  |
   | unable to obtain it through the world-wide-web, please send a note   |
   | to hide@address.com so we can mail you a copy immediately.|
   +----------------------------------------------------------------------+ */
if (!defined("ACCESS")) {
    die ("Direct request denied");
}

class admin_user {

	var $f, $username, $passwd, $logged_on;

	function admin_user($f) {
		$this->f =& $f;
		$this->get_logged_on();
	}

	function login($username, $passwd) {
		if ($this->logged_on) {
			return true;
		}
		$username = $this->f->util->FormatStringForDatabaseInput(htmlspecialchars(trim(stripslashes(str_replace ("--", "", $username)))), 1);
		$passwd = $this->f->util->FormatStringForDatabaseInput(stripslashes(str_replace ("--", "", $passwd)), 1);
		$row = $this->f->conn->query("SELECT * FROM user
		                     		  WHERE username='$username'
		                     		  AND passwd = password('$passwd')");

		if (!$this->f->conn->result) {
			$this->set_logged_on(false);
			return false;
		}
		elseif ($row[0][barred] == 'yes') {
			$this->set_logged_on(false);
			return '<p class="badnews">Your account has been disabled by the site administrator</p>';;
		}
		elseif (count($row)>0) {
			$this->set_logged_on(true);
			$_SESSION['valid_user'] = $username;
      		$this->get_role($username);
			return true;
		}
		else {
			$this->set_logged_on(false);
			return false;
		}
	}

	function get_role($username) {
	    $username = $this->f->util->FormatStringForDatabaseInput($username, 1);
		$RoleLevel = $this->f->conn->query("SELECT r.RoleLevel
				                            FROM role AS r
			    						    LEFT JOIN user AS u ON r.RoleID = u.RoleID
				                            WHERE u.username = '$username'", 'index');
	    if (!$RoleLevel) {
	        $_SESSION['RoleLevel'] = 1;
	        return false;
	    }
	    else {
	        $_SESSION['RoleLevel'] = $RoleLevel;
	        return true;
	    }
	}

	function check_first_logon($username, $passwd) {
		$username = $this->f->util->FormatStringForDatabaseInput(str_replace ("--", "", $username), 1);
		$passwd = $this->f->util->FormatStringForDatabaseInput(str_replace("--", "", $passwd), 1);
		$this->change_passwd = $this->f->conn->query("SELECT change_passwd
								                      FROM user
								                      WHERE username = '$this->username' AND
								                      passwd = password('$this->passwd')", 'index');
		if (!$this->f->conn->result) {
			return false;
		}
		elseif ($this->change_passwd == 'yes') {
			return true;
		}
		else {
			return false;
		}
	}

	function get_logged_on() {
		return $this->logged_on;
	}

	function set_logged_on($status) {
		$this->logged_on = $status;
	}

	function check_valid_user($RoleLevel) {
		if (isset($_SESSION['valid_user']) && ($_SESSION['RoleLevel'] >= $RoleLevel)) {
	        echo "<p>Logged in as <strong>".$_SESSION['valid_user']."</strong>&nbsp;&gt;&gt;&nbsp;<a href=\"logout.php\" onmouseover=\"return showStatus('End admin session and log out of system')\" onmouseout=\"return clearStatus()\">Logout</a></p>\n";
	    }
	    elseif (isset($_SESSION['valid_user']) && ($_SESSION['RoleLevel'] < $RoleLevel)) {
	    	echo "<p>Logged in as <strong>".$_SESSION['valid_user']."</strong>&nbsp;&gt;&gt;&nbsp;<a href=\"logout.php\" onmouseover=\"return showStatus('End admin session and log out of system')\" onmouseout=\"return clearStatus()\">Logout</a></p>\n";
		    do_html_heading("Problem - Authorisation Required");
		    echo '<div id="breadcrumbtrail"><a href="member.php">Main Admin Area</a></div>';
		    echo '<p class="badnews">You are not authorised to view this page.<br />';
		    echo 'Please click <a href="member.php">here</a> and try another link.<br />';
		    echo 'If you believe that you should have access please contact the site administrator.</p>';
		    do_html_footer('1');
	        exit;
	    }
	    else {
	    	// they are not logged in
	       	do_html_heading("Problem - Authorisation Required");
	       	echo '<p class="badnews">You must be authorised to view this page.<br />If you you were logged in, it may be that you were automatically logged out after a period of inactivity.<br />';
	       	echo 'Please follow the link below to log in</p>';
	       	do_html_url("login.php", "Login");
	       	do_html_footer('1', 'nokwikenav');
	       	exit;
	    }
	}

	function change_password($username, $old_password, $new_password) {
		$username = $this->f->util->FormatStringForDatabaseInput(str_replace ("--", "", $username), 1);
		$old_password = $this->f->util->FormatStringForDatabaseInput(str_replace("--", "", $old_password), 1);
		$new_password = $this->f->util->FormatStringForDatabaseInput(str_replace("--", "", $new_password), 1);
		$this->f->conn->query("SELECT * FROM user
				               WHERE username='$username'
				               AND passwd = password('$passwd')", 'none');
		if($this->f->conn->result) {
			$this->f->conn->query( "UPDATE user
		               	   			SET passwd = password('$new_password')
		               	   			WHERE username = '$username'");
			if (!$this->f->conn->result) {
				return false;  // not changed
			}
			else {
				$this->f->conn->query("UPDATE user
		                      			SET change_passwd = 'NO'
		                      			WHERE username = '$username'");
				return true;  // changed successfully
			}
		}
		else {
			return false; // old password was wrong
		}
	}

	function valid_email($address) {
	  // check an email address is possibly valid
	  if (ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $address))
	    return true;
	  else
	    return false;
	}

	function filled_out($form_vars) {
	  // test that each variable has a value
	  foreach ($form_vars as $key => $value) {
	     if (!isset($key) || ($value == "")) {
	        return false;
	     }
	  }
	  return true;
	}

	function reset_password($username) {
		$username = $this->f->util->FormatStringForDatabaseInput(str_replace("--", "", $username), 1);
		// check if user really exists
		$this->user_exists = $this->f->conn->query("SELECT COUNT(*)
										   			FROM user
										   			WHERE username = '$username'", 'index');
		if (!$this->user_exists) {
			return '<p class="badnews">There is a technical problem&#8212;Please try again later</p>';
		}
		if ($this->user_exists != 1) {
			return '<p class="badnews">Please check your spelling and hit your browsers back button.</p>';
		}

		$salt = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
		srand((double)microtime()*1000000);
		$new_password = '';
		for ($i=0; $i<8; $i++) {
			$new_password = $new_password.substr($salt, rand() % strlen($salt), 1);
		}
		$this->f->conn->query( "UPDATE user
							    SET passwd = password('$new_password'),
							    change_passwd = 'yes'
							    WHERE username = '$username'", 'none');
		if ($this->f->conn->getNumRows() == 1) {
			return $new_password;  // changed successfully
		}
		else {
			return false;  // not changed
		}
	}

	function notify_password($username, $password) {
		$username = $this->f->util->FormatStringForDatabaseInput(str_replace("--", "", $username), 1);
		$email = $this->f->conn->query("SELECT email
									    FROM user
				                        WHERE username = '$username'", 'index');
		if (!$email) {
			return false;  // not changed
		}
		elseif ($email == '') {
			return false; // username not in db
		}
		else {
			$from = "From: SelectaPix Admin\r\n";
			$from .= "Reply-To: <" . ADMIN_EMAIL . ">\r\n";
			$from .= "Return-Path: " . ADMIN_EMAIL . ">\r\n";
			$from .= "MIME-Version: 1.0\r\n";
			$from .= "Content-type: text/plain; charset=iso-8859-1\r\n";
			$from .= "X-Mailer: SelectaPix\r\n";
			$from .= "X-Priority: 3\r\n";
			$from .= "X-MSMail-Priority: Normal";
			$mesg = "Your admin password has been changed to $password \r\n"
					."Please change it next time you log in.\r\n";
			if (mail($email, "Admin login information", $mesg, $from)) {
				return true;
			}
			else {
				return false;
			}
		}
	}

	function list_role_levels($selected = '') {
	    $row = $this->f->conn->query("SELECT RoleID, Role
	                         		  FROM role");
	    if (empty($row)) {
	        echo '<p class="badnews">There is a technical problem&#8212;Please try again later</p>';
	        exit;
	    }
	    echo "\n<select name=\"RoleID\" id=\"RoleID\">\n";
	    for ($i=0; $i<count($row); $i++) {
	    	if ($selected == $row[$i][RoleID]) {
	        	echo "<option value=\"".$row[$i][RoleID]."\" selected=\"selected\">".$row[$i][Role]."</option>\n";
	    	}
	    	else {
	    		echo "<option value=\"".$row[$i][RoleID]."\">".$row[$i][Role]."</option>\n";
	    	}
	    }
	    echo "</select>\n";
	}

	function register($username, $email, $password, $roleID) {
		$username = $this->f->util->FormatStringForDatabaseInput(str_replace("--", "", $username), 1);
		$email = $this->f->util->FormatStringForDatabaseInput(str_replace("--", "", $email), 1);
		$password = $this->f->util->FormatStringForDatabaseInput(str_replace("--", "", $password), 1);
		$roleID = $this->f->util->ForceInt($roleID, 1);
		$this->username = @$this->f->conn->query("SELECT username
												  FROM user
												  WHERE username = '$username'", 'index');
		if (!$this->f->conn->result) {
			return '<p class="badnews">There is a technical problem&#8212;Please try again later</p>';
		}
		if ($this->username != '') {
			return '<p class="badnews">That username is taken&#8212;please choose a different one.</p>';
		}
		$this->result = $this->f->conn->query("INSERT INTO user VALUES
									  			('', '$username', password('$password'), '$email', 'yes', 'no', $roleID)", 'none');
		if (!$this->f->conn->result) {
			return "<p class=\"badnews\">Could not register new user in database&#8212;please try again later.</p>\n";
		}
		$adminsubject = "New ".SITE_NAME." admin user";
		$adminmesage = "A new user has registered for the administration area\r\n\r\n";
		$adminmesage .= "Username: ".stripslashes($username)."\r\nEmail: ".stripslashes($email)."\r\n";
		$adminmesage .= "It is safe to delete this email if this is acceptable.\r\n";

		$from = "From: SelectaPix Admin\r\n";
		$from .= "Reply-To: <".ADMIN_EMAIL.">\r\n";
		$from .= "Return-Path: ".ADMIN_EMAIL.">\r\n";
		$from .= "MIME-Version: 1.0\r\n";
		$from .= "Content-type: text/plain; charset=iso-8859-1\r\n";
		$from .= "X-Mailer: SelectaPix\r\n";
		$from .= "X-Priority: 3\r\n";
		$from .= "X-MSMail-Priority: Normal";

		mail(ADMIN_EMAIL, $adminsubject, $adminmesage, $from);

		$mesg = "Your registration for the Admin Area has been successfull.\r\n"
				."Your registration details are as follows:\r\n"
				."Username: ".stripslashes($username)."\r\n"
				."Password: ".stripslashes($password)."\r\n"
				."For security reasons you will be required to change your password after your first login.";
		if (mail($email, "Admin registration information", $mesg, $from)) {
			return true;
		}
		else {
			return "<p class=\"badnews\">New user has been registered in database, however a confirmation email could not be sent&#8212; please try again later.</p>\n";
		}
		return true;
	}

	function admin_list_users() {
		echo '<div id="breadcrumbtrail"><a href="member.php">Main Admin Area</a> &gt;&gt; User Manager</div>';
		if ($_POST && ($_SESSION['RoleLevel'] < 127)) {
			echo '<p class="badnews">You do not have sufficient administrative rights to perform this action.</p>';
		}
		elseif ($_POST && ($_SESSION['RoleLevel'] >= 127)) {
			$this->amend_users();
		}
		$row = $this->f->conn->query("SELECT u.userID, u.username, u.email, u.change_passwd, u.barred, r.roleID, r.role
			                       	   FROM user AS u
									   LEFT JOIN role AS r ON u.roleID = r.roleID
			                           ORDER BY userID asc");
		if (empty($row)) {
			echo '<p class="badnews">Could not find any users</p>';
			return;
		}

		if (count($row) == 0) {
			echo '<p class="badnews">You have not created any users. Use the <a href="register_form.php" title="Add a new administrator">Add New User form</a> to create one.</p>';
			return;
		}
		else {
			echo "\n\n<div class=\"iecentrehack\">\n";
			for($i = 0; $i < count($row); $i ++) {
				echo "\n\n<form action=\"user.php\" method=\"post\" class=\"bottomline\">\n";
				echo "<table class=\"userdetails\" cellspacing=\"0\" summary=\"User details for ".$row[$i][username]."\">\n<tr>\n\t<td>";
				echo "<input type=\"hidden\" name=\"userID\" value=\"".$row[$i][userID]."\" />\n";
				echo "<input type=\"hidden\" name=\"submitted\" value=\"true\" />\n";
				echo 'User: <input type="text" name="username"';
				echo " value=\"".$row[$i][username]."\" size=\"15\" />\n</td>\n\t";
				echo "<td>Role: \n\t";
				$this->list_role_levels($row[$i][roleID]);
				echo "\n</td>\n";
				echo "<td>\n\tEmail: <input type=\"text\" name=\"email";
				echo "\" value=\"".$row[$i][email]."\" size=\"25\" />\n";
				echo "</td>\n<td>\n\t";
				echo '<input type="submit" class="button" name="edit_user" value="Save Changes" />';
				echo "\n</td>\n</tr>\n\n<tr>\n<td>&nbsp;</td>\n<td>\n\t";
				echo "Change Password? \n\t<select name=\"change_passwd\">\n";
				if ($row[$i][change_passwd] == 'yes') {
					echo "\t\t<option value=\"yes\" selected=\"selected\">YES</option>\n\t<option value=\"no\">NO</option>\n";
				}
				else {
					echo "\t\t<option value=\"no\" selected=\"selected\">NO</option>\n\t<option value=\"yes\">YES</option>\n";
				}
				echo "\t</select>\n</td>\n<td title=\"Prevent user from entering admin area?\">\n";
				echo "\tBarred? \n\t<select name=\"barred\">\n";
				if ($row[$i][barred] == 'yes') {
					echo "\t\t<option value=\"yes\" selected=\"selected\">YES</option>\n<option value=\"no\">NO</option>\n";
				}
				else {
					echo "\t\t<option value=\"no\" selected=\"selected\">NO</option>\n<option value=\"yes\">YES</option>\n";
				}
				echo "\t</select>\n</td>\n<td>\n";
				echo "\t<input type=\"submit\" class=\"warning\" name=\"delete_user\" value=\"Delete User\" />\n";
				echo "</td>\n</tr>\n</table>\n</form>\n\n";
			}
			echo "</div>\n\n";
		}
	}

	function amend_users() {
		$this->userID = $this->f->util->ForceInt($_POST['userID'], 0);
		$this->email = $this->f->util->FormatStringForDatabaseInput($_POST['email'], 1);
		$this->username = $this->f->util->FormatStringForDatabaseInput($_POST['username'], 1);
		$this->change_passwd = $this->f->util->FormatStringForDatabaseInput($_POST['change_passwd'], 1);
		$this->barred = $this->f->util->FormatStringForDatabaseInput($_POST['barred'], 1);
		$this->roleID = $this->f->util->ForceInt($_POST['RoleID'], 1);
		if ($_POST['edit_user']) {
			$this->f->conn->query("UPDATE user
			                       SET username = '$this->username',
			                       email = '$this->email',
			                       change_passwd = '$this->change_passwd',
			                       barred = '$this->barred',
			                       RoleID = $this->roleID
			                       WHERE userID = '$this->userID'", 'none');
			if (!$this->f->conn->result) {
				echo '<p class="badnews">Could not update user&#8212;please try again later.</p>';
			}
			else {
				echo "<p class=\"goodnews\">User <em>".htmlspecialchars(stripslashes($this->username))."</em> updated.</p>\n";
			}
		}
		if ($_POST['delete_user']) {
			$this->f->conn->query("DELETE FROM user
	                      		   WHERE userID = '$this->userID'");
			if (!$this->f->conn->result) {
				echo '<p class="badnews">Could not delete user&#8212;please try again later.</p>';
			}
			else {
				echo "<p class=\"goodnews\">User <em>".htmlspecialchars(stripslashes($this->username))."</em> deleted.</p>\n";
			}
		}
	}
}
?>
Return current item: SelectaPix Image Gallery