Location: PHPKode > projects > Cynus > cynus/admin_user_func.php
<?php
/**
 * @file admin_user_func.php -- Provides user functions
 * @Id $Id: admin_user_func.php,v 1.26 2004/07/29 23:43:50 jason Exp $
 *
 * Cynus - a web-based content manager
 * Copyright (C) 2003 Brett and Jason Profitt
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

cynus_debug ("Loaded admin_user_func.php.", 3);

/**********************************
Admin User Nav: string admin_user_nav()
This returns the user navigation for the admin.php
page. 
**********************************/
function admin_user_nav() {
	#create the menu
	$menu=array(
		"base:Add a User:admin.php?action=users&op=add:images/add_user.png",
		"base:View/Modify User Accounts:admin.php?action=users&op=list:images/view_accounts.png"
	);
	$submenu=array(
		'Home' => 'index.php',
		'User Administration' => ''
	);
	set_page_title('User Administration');
	$content .= cynus_submenu($submenu);
	$content .= cynus_menu($menu, 'base');
	
	cynus_debug ("Created admin user nav menu");
	#we're done now, return...
	return $content;
}


/********************************
Admin User Add: string admin_user_add()
Creates the form for adding a new user. 
This does not do the adding, that is done by
admin_user_create_account() which reads from
$_POST
********************************/
function admin_user_add() {
	global $user_config, $config;
	cynus_debug ("Adding new user.", 3);

	$submenu=array(
		'Home' => 'index.php',
		'User Administration' => 'admin.php?action=users',
		'Add User' => ''
	);
	$content .= cynus_submenu($submenu, 'base');
	
	if($_POST['sent']==1) {
		cynus_debug ("Request received, checking variables...");
		#Now we need to check everything
		$fields = array(
					'username' => 'Username',
					'password1' => 'First Password',
					'password2' => 'Confirm Password',
					'real_name' => 'Real Name',
					'email' => 'Email Address',
					'level' => 'Access Level'
				);
		foreach($fields as $field => $link) {
			if($_POST[$field] == "") {
				cynus_debug ("$link is empty", 2);
				$errors .= "You forgot to fill out the $link field!<br />\n";
			}
		}
		if($_POST['username'] != "") {
			$query="SELECT * from `$config[sql_prefix]users` WHERE `username`='$_POST[username]'";
			$user_check=mysql_request($query);
			if($user_check['id'] != "") {
				cynus_debug ("Username already exists", 2);
				$errors .= 'A user already exists with this username!<br />' . "\n";
			}
		}
		
		if($_POST['password1'] != "" || $_POST['password2'] != "") {
			if($_POST['password1'] != $_POST['password2']) {
				cynus_debug ("Password mismatch", 2);
				$errors .= 'Your passwords do not match!<br />' . "\n";
			}
		}
		
		if($_POST['level'] > $user_config['level']) {
			cynus_debug ("Attempting to add user with higher access than current user", 2);
			$errors .= 'You cannot add a user with a high access level than yourself!<br />' . "\n";
		}
		
		if($errors != '') {
			cynus_debug ("Error processing request.  Reprinting form", 2);
			$_POST['sent']="";
			$content .= '<div class="form-error">There were errors in your form:</div>' . "\n";
			$content .= $errors;
			$content .= admin_user_add();
		}
		else{
			admin_user_create_account();
			$content .= 'Successfully created a new account.<br />';
			#Let's get the user's info now so we can create a link for them to 
			#change the user's permissions
			$query="SELECT * from `$config[sql_prefix]users` WHERE `username`='$_POST[username]'";
			$new_user=mysql_request($query);
			$content .= "Click <a href=\"admin.php?action=users&op=permissions&id=$new_user[id]\">here</a> to edit the new user's permissions.<br />\n";
			
			#Clear everything so we can come back where we were and not have
			#stuff in the form already
			$_POST['sent']=$_POST['username']=$_POST['level']=$_POST['email']=$_POST['real_name']='';
			
			$content .= admin_user_add();
		}
		return $content;
	}
	else{	
		set_page_title("Adding a New User");
		$content .= <<<___eofh
<form method="POST" action="admin.php?action=users&op=add">
<input type="hidden" name="sent" value="1">
<table>
	<tr>
		<td>Username</td>
		<td><input type="text" name="username" value="$_POST[username]" maxlength="20"></td>
	</tr>
	<tr>
		<td>Password</td>
		<td><input type="password" name="password1" value="" maxlength="50"></td>
	</tr>
	<tr>
		<td>Confirm</td>
		<td><input type="password" name="password2" value="" maxlength="50"></td>
	</tr>
	<tr>
		<td>Real Name</td>
		<td><input type="text" name="real_name" value="$_POST[real_name]" maxlength="50"></td>
	</tr>
	<tr>
		<td>Email Address</td>
		<td><input type="text" name="email" value="$_POST[email]" maxlength="75"></td>
	</tr>
	<tr>
		<td>Access Level</td>
		<td>
			<select name="level">
				<option value="">Access Level</option>\n
___eofh;
		for($x=2;$x<=$user_config['level'];$x++) {
			if($_POST['level'] == $x) {$selected=' selected';}
			else{$selected='';}
			$content .= "\t\t\t\t<option value=\"$x\"" . $selected . '>' . convert_access_level($x) . "</option>\n";
		}
		$content .= <<<___eofh
			</select>
		</td>
	</tr>
</table>
<input type="submit" value="Add User" class="button"/>
</form>
___eofh;
	}
	return $content;
}


/****************************
Admin User Create Account: admin_user_create_account()
This reads from $_POST and adds into the users table
username
password (read from password1)
real_name
email
level
****************************/
function admin_user_create_account() {
	global $config;
	cynus_debug ("Adding new user to MySQL database.", 3);
	$enc_pass=crypt($_POST['password1']);
	$query="INSERT into `$config[sql_prefix]users` (`username`, `password`, `real_name`, `email`, `level`) " .
		     "VALUES ('$_POST[username]', '$enc_pass', '$_POST[real_name]', '$_POST[email]', '$_POST[level]')";
	mysql_query($query);
	
	$new_user_id=mysql_insert_id();
	//$query="SELECT * from `users` WHERE `username`='$_POST[username]'";
	//$user=mysql_request($query);
	
	cynus_debug('Sending the new user the default messages.', 3);
	#now let's send the user a message telling them welcome and to change their password
	$message=<<<___eofh
You should be sure to change your password at this time if it is one that is not difficult to guess. 
Mixing cases (AbCdeFG) and adding numbers (PasSWoRd23) to your password make it harder for someone to 
guess. If you ever forget your password, contact an administrator or super user to change it for you.
___eofh;
	add_message($new_user_id, 0, 'Change your password.', $message);
	$message=<<<___eofh
Welcome to Cynus. Please take the time to look around and please report any problems
to your system administrator, whose email address can be found at the bottom of any page.
___eofh;
	add_message($new_user_id, 0, 'Welcome to Cynus!', $message);
	
	#and now let's issue a signal telling the world we've added a user
	cynus_debug('Issuing CYNUS_USER_ADDED signal.');
	issue_signal('CYNUS_USER_ADDED', $new_user_id);
}


/****************************
Admin User View Acounts: string admin_user_view_accounts()
Returns a formatted list of the user accounts with buttons
to edit or delete, depending on the user's level.
****************************/
function admin_user_view_accounts() {
	global $user_config, $config;
	cynus_debug ("Viewing user accounts.",3 );
	$submenu=array(
		'Home' => 'index.php',
		'User Administration' => 'admin.php?action=users',
		'View User Accounts' => ''
	);
	$content .= cynus_submenu($submenu, 'base');
	set_page_title('View User Accounts');
	$query="SELECT * from `$config[sql_prefix]users` ORDER by `real_name`";
	$result=mysql_query($query);
	$content .=<<<___eofh
<table class="user-list" cellspacing="0" cellpadding="3" class="table-general">
	<tr class="table-header">
		<td colspan="3" class="center">User Functions</td>
		<td>Real Name</td>
		<td>Username</td>
		<td>Email Address</td>
		<td>Access Level</td>
	</tr>\n
___eofh;
	$row='row1';
	$next_row='row2';
	while($each_user=mysql_fetch_assoc($result)) {
		cynus_debug('Creating row for ' . $each_user['username'] . '.', 3);
		$access_level=convert_access_level($each_user['level']);
		if($each_user['level']<=$user_config['level']) {
			$edit="<a href=\"admin.php?action=users&op=edit&id=$each_user[id]\">Edit</a>";
			if($each_user['id'] != $user_config['id']) {
				$delete="<a href=\"admin.php?action=users&op=delete&id=$each_user[id]\">Delete</a>";
			}
			$permissions="<a href=\"admin.php?action=users&op=permissions&id=$each_user[id]\">Permissions</a>";
		}
		$content .= <<<___eofh
	<tr class="$row">
		<td>$delete</td>
		<td>$edit</td>
		<td>$permissions</td>
		<td>$each_user[real_name]</td>
		<td>$each_user[username]</td>
		<td><a href="mailto:$each_user[email]">$each_user[email]</a></td>
		<td>$access_level</td>
	</tr>\n
___eofh;
		swap($row, $next_row);
		$edit=$delete=$permissions="";
	}
	$content .="</table>\n";
	return $content;
}


/*****************************
Admin User Edit: string admin_user_edit()
Displays the user's information by the $_GET[id]
and allows you to change it.
*****************************/
function admin_user_edit() {
	global $user_config, $config;
	cynus_debug ("Editing user info.", 3);
	
	$submenu=array(
		'Home' => 'index.php',
		'User Administration' => 'admin.php?action=users',
		'View User Accounts' => 'admin.php?action=users&op=list',
		'Edit a User' => ''
	);
	
	if($_GET['id'] == "") {
		cynus_debug ("\$_GET[id] empty.", 2);
		cynus_error("You did not select a user to edit.");
	}
	else{
		$query="SELECT * from `$config[sql_prefix]users` WHERE `id`='$_GET[id]'";
		$user_info=mysql_request($query);
		#Random check on one of the columns to make sure we have a real user
		if($user_info['username'] == "") {
			cynus_debug ("`username` doesn't exist in MySQL row.", 2);
			cynus_error("A user does not exist with that ID number, please select a valid account.");
		}
		elseif($user_info['level'] > $user_config['level']) {
			cynus_debug ("Insufficient permissions", 2);
			cynus_error("You do not have the proper access level to modify this user.");
		}
		elseif($_POST['sent']==1) {
			#now we need to check all of the information sent
			cynus_debug ("Recieved new information.  Checking..");
			$fields = array(
						'username' => 'Username',
						'real_name' => 'Real Name',
						'email' => 'Email Address',
						'level' => 'Access Level'
					);
			foreach($fields as $field => $link) {
				if($_POST[$field] == "") {
					cynus_debug ("$link field empty.", 2);
					$errors .= "The $link field cannot be left blank!<br />\n";
				}
			}
			
			if(($_POST['username'] != "") && ($_POST['username'] != $user_info['username'])) {
				$query="SELECT * from `$config[sql_prefix]users` WHERE `username`='$_POST[username]'";
				$user_check=mysql_request($query);
				if($user_check['id'] != "") {
					cynus_debug ("User already exists with specified username: {$_POST['username']}.", 2);
					$errors .= 'A user already exists with this username!<br />' . "\n";
				}
			}
			
			if($_POST['password1'] != "" || $_POST['password2'] != "") {
				if($_POST['password1'] != $_POST['password2']) {
					cynus_debug ("Password missmatch", 2);
					$errors .= 'Your passwords do not match!<br />' . "\n";
				}
			}
			
			if($_POST['level'] > $user_config['level']) {
				cynus_debug ("Attempting to raise level above operator's.", 2);
				$errors .= 'You cannot add a user with a high access level than yourself!<br />' . "\n";
			}
			
			if($errors != "" ){
				cynus_debug ("Error in checking form.  Reprinting.", 2);
				$_POST['sent']="";
				set_page_title("Edit a User");
				$content .= cynus_submenu($submenu, 'base');;
				$content .= '<div class="form-error">There were errors in your form:</div>' . "\n";
				$content.=$errors;
				$content.=admin_user_edit();
			}
			else{
				admin_user_edit_account();
				$content .= "Successfully editted $user_info[real_name]'s account.";
				$content .= admin_user_view_accounts();
			}
		}
		else{
			set_page_title("Edit a User");
			$content .= cynus_submenu($submenu, 'base');;
			$username=set_default($user_info['username'], $_POST['username']);
			$real_name=set_default($user_info['real_name'], $_POST['real_name']);
			$email=set_default($user_info['email'], $_POST['email']);
			$level=set_default($user_info['level'], $_POST['level']);
			$content .= <<<___eofh
<form method="POST" action="admin.php?action=users&op=edit&id=$_GET[id]">
<input type="hidden" name="sent" value="1">
<table>
	<tr>
		<td>Username</td>
		<td><input type="text" name="username" value="$username" maxlength="20"></td>
	</tr>
	<tr>
		<td>Password</td>
		<td><input type="password" name="password1" value="" maxlength="50"></td>
	</tr>
	<tr>
		<td>Confirm</td>
		<td><input type="password" name="password2" value="" maxlength="50"></td>
	</tr>
	<tr>
		<td>Real Name</td>
		<td><input type="text" name="real_name" value="$real_name" maxlength="50"></td>
	</tr>
	<tr>
		<td>Email Address</td>
		<td><input type="text" name="email" value="$email" maxlength="75"></td>
	</tr>
	<tr>
		<td>Access Level</td>
		<td>
			<select name="level">
				<option value="">Access Level</option>\n
___eofh;
		for($x=2;$x<=$user_config['level'];$x++) {
			if($level == $x) {$selected=' selected';}
			else{$selected='';}
			$content .= "\t\t\t\t<option value=\"$x\"" . $selected . '>' . convert_access_level($x) . "</option>\n";
		}
		$content .= <<<___eofh
			</select>
		</td>
	</tr>
</table>
<input type="submit" value="Edit User" class="button"/>
</form>
Password will change only if you enter a new one.
___eofh;
		}
		return $content;
	}
}


/***************************
Admin User Edit Account: admin_user_edit_account()
This is quite similar to admin_user_add_account() in that
it reads the $_POST array to get the information needed
to edit the account.
***************************/
function admin_user_edit_account() {
	global $user_config, $config;
	cynus_debug ("Editing user account.", 3);
	
	if($_POST['password1'] != "") {
		$enc_pass=crypt($_POST['password1']);
		$password_query="`password` = '$enc_pass', ";
	}
	
	#Another thing we need to do is make sure that anything
	#the user had permission to previously, they still have permissions
	#to if they're level got changed (makes sure they haven't went below
	#the min_level for a module).
	if($_POST['level'] < 4) {
		cynus_debug('Beginning to check user\'s permissions.', 3);
		$user_info=user_convert($_GET['id']);
		if($_POST['level'] < $user_info['level']) {
			
			$permissions=split(':', $user_info['permissions']);
			$new_permissions=array();
			foreach($permissions as $module) {
				$query="SELECT * from `$config[sql_prefix]modules` WHERE `id`='$module'";
				$module_info=mysql_request($query);
				if($module_info['min_level'] <= $_POST['level']) {
					array_push($new_permissions, $module);
				}
			}
			$new_perm_string=implode(':', $new_permissions);
			if($new_perm_string != '') {
				$new_perm_string = ", `permissions`='$new_perm_string' ";
			}
			
		}
	}

	#let's issue our signal before we actually change them
	cynus_debug('Issuing CYNUS_USER_EDITTED signal.');
	issue_signal('CYNUS_USER_EDITTED', $_GET['id']);
	
	cynus_debug('Updating the user\'s information.', 3);
	#compile a query and then execute
	$query="UPDATE `$config[sql_prefix]users` SET `username`='$_POST[username]', " . $password_query . "`real_name`='$_POST[real_name]', ".
		     "`email` = '$_POST[email]', `level` = '$_POST[level]'" . $new_perm_string . " WHERE `id`='$_GET[id]'";
	mysql_query($query);
	
	#if the user editted their own info, we might need to change some information
	if(($user_config['id']==$_GET['id']) && (($user_config['username'] != $_POST['username']) || ($enc_pass != ""))) {
		setcookie('username', $_POST['username'], (time() + 604800), '/');
		setcookie('password', $enc_pass, (time() + 604800), '/');
		cynus_debug('Password was changed for the logged in user, updating cookie.', 3);
	}
}


/**************************
Admin User Delete: string admin_user_delete()
A lot of this will look very similar to adding and editting users.
This prints out the prompt to delete the user's account.
Poor user...
**************************/
function admin_user_delete() {
	global $user_config, $config;
	$submenu=array(
		'Home' => 'index.php',
		'User Administration' => 'admin.php?action=users',
		'View User Accounts' => 'admin.php?action=users&op=list',
		'Delete a User' => ''
	);
	set_page_title("Delete a User");
	if($_GET['id'] == "") {
		cynus_error("You must select a user to delete first.");
	}
	else{
		$query="SELECT * from `$config[sql_prefix]users` WHERE `id`='$_GET[id]'";
		$user_info=mysql_request($query);
		#check that the user exists
		if($user_info['username'] == "") {
			cynus_error("A user does not exist with that ID number, please select a valid account.");
		}
		elseif($user_info['id']==$user_config['id']) {
			cynus_error("You cannot delete yourself!");
		}
		elseif($user_info['level'] > $user_config['level']) {
			cynus_error("You do not have the proper access level to delete this user.");
		}
		elseif($_GET['flag']=="yes") {
			admin_user_delete_account();
			$content .= "Successfully deleted $user_info[real_name]'s account.<br>";
			$content .= admin_user_view_accounts();
		}
		else{
			$content .= cynus_submenu($submenu, 'base');
			$access=convert_access_level($user_info['level']);
			$content .= <<<___eofh
Are you sure you wish to delete $user_info[real_name]&#39s account?<br><br>
Real Name: $user_info[real_name]<br>
Username: $user_info[username]<br>
Email: $user_info[email]<br>
Access Level: $access<br><br><br>
<a href="admin.php?action=users&op=delete&id=$_GET[id]&flag=yes">Yes</a> /
<a href="admin.php?action=users&op=list">No</a>
___eofh;
		}
		return $content;
	}
}


/***************************
Admin User Delete Account: admin_user_delete_account()
Like admin_user_[edit/add]_account(), but this deletes
the account, derr...
***************************/
function admin_user_delete_account() {
	global $config;
	
	cynus_debug('Issuing CYNUS_USER_DELETED signal.');
	issue_signal('CYNUS_USER_DELETED', $_GET['id']);
	
	$query="DELETE from `$config[sql_prefix]users` WHERE `id`='$_GET[id]'";
	mysql_query($query);
}


/**************************
Admin User Permissions: admin_user_permissions();
This lets you define what permissions certain users have.
It uses the modules table and the module's id number
to create a string formatted as 1:3:9:14 etc. to show
what modules a user has access to
**************************/
function admin_user_permissions() {
	global $user_config, $config;
	#check for an id...
	if($_GET['id']=='') {
		cynus_error('You must select a user to edit permissions.');
	}
	elseif($_POST['sent'] == 1) {
		$query="SELECT * from `$config[sql_prefix]users` WHERE id='$_GET[id]'";
		$user_info=mysql_request($query);
		#Now, we need to make an array out of the user's permissions
		$permissions=split(":", $user_info['permissions']);
		#we also need to get the editor's permissions so we know what he/she can
		$my_permissions=split(":", $user_config['permissions']);
		$new_permissions=array();
		//foreach($permissions as $module_id) {
		#we need to go through the values that were sent first to find
		#out what they're changing
		foreach($_POST['permissions'] as $module_id => $value) {
			if($value==1) {
				#we need to check if they're adding permissions for a user
				#and make sure that they aren't somehow giving them more rights
				#than what they have.
				if(!in_array($module_id, $permissions) && ($user_config['level'] != 4) && (!in_array($module_id, $my_permissions))){
					cynus_error("You cannot give a user access to an area you do not have permissions to.");
				}
				else{
					array_push($new_permissions, $module_id);
				}
			}
		}
		#so now we need to go through their existing permissions and add
		#those to the $new_permissions
		foreach($permissions as $module_id) {
			//print "$module_id:" . $_POST['permissions'][$module_id] . " ";
			if(!isset($_POST['permissions'][$module_id]) && ($module_id != '')) {
				array_push($new_permissions, $module_id);
			}
		}
		
		#just to make it organized...
		sort($new_permissions);
		#Now all we need to do is implode and update the table
		$new_permissions=implode(":", $new_permissions);
		$query="UPDATE `$config[sql_prefix]users` SET `permissions`='$new_permissions' WHERE `id`='$_GET[id]'";
		mysql_query($query);
		$content .= 'Successfully updated the user\'s permissions.<br />';
		$content .= admin_user_view_accounts();
	}
	else{
		$submenu=array(
			'Home' => 'index.php',
			'User Administration' => 'admin.php?action=users',
			'View User Accounts' => 'admin.php?action=users&op=list',
			'Edit User Permissions' => ''
		);
		$content .= cynus_submenu($submenu);
		set_page_title('Edit a User\'s Permissions');
		$query="SELECT * from `$config[sql_prefix]users` WHERE `id`='$_GET[id]'";
		$user_info=mysql_request($query);
		#Now, we need to make an array out of the user's permissions
		$permissions=split(":", $user_info['permissions']);
		
		#we also need to get the editor's permissions so we know what he/she can
		$my_permissions=split(":", $user_config['permissions']);
		if($user_info['username'] =='') {
			cynus_error('No user exists with that ID number.');
		}
		elseif($user_info['level'] > $user_config['level']) {
			cynus_error('You cannot edit the permission of a user with a higher level than yourself.');
		}
		else{
			$content .= <<<___eofh
Module Permissions for $user_info[real_name]:<br />
<form method="POST" action="admin.php?action=users&op=permissions&id=$_GET[id]">
<input type="hidden" name="sent" value="1" />
<table class="table-general">\n
___eofh;

			#Get all of the modules, print them out, and let's start comparing
			$row1='row1';
			$row2='row2';
			$query="SELECT * from `$config[sql_prefix]modules` ORDER by `friendly_name`";
			$result=mysql_query($query);
			while($each_module=mysql_fetch_assoc($result)) {
				if(in_array($each_module['id'], $permissions)) {$yes='checked';}
				else{$no='checked';}
				#if the editor doesn't have permission to the module, and isn't a super user
				#disable this option
				if(!in_array($each_module['id'], $my_permissions) && ($user_config['level'] != 4)) {$disabled='disabled';}
				#if the user being edited wouldn't have access to the module because of level
				#disable this option
				elseif($each_module['min_level'] > $user_info['level']) {$disabled='disabled';}
				#we also don't want the user to lock themself out of the users section
				elseif($user_config['id']==$user_info['id'] && $each_module['name']=='users') {$disabled='disabled';}
				else{$disabled='';}
				$content .= <<<___eofh
	<tr class="$row1">
		<td class="table-header">$each_module[friendly_name]</td>
		<td>
			<input type="radio" value="1" name="permissions[$each_module[id]]" $disabled $yes />Yes / 
			<input type="radio" value="0" name="permissions[$each_module[id]]" $disabled $no />No<br />
		</td>
	</tr>\n
___eofh;
				swap($row1, $row2);
				$yes=$no='';
			}
			$content .= <<<___eofh
</table>
<input type="submit" value="Edit User Permissions" class="button" />
</form>
___eofh;
		}
	}
	return $content;
}


?>
Return current item: Cynus