<?php
/************************************************************************/
/* Maximus CMS: Web Portal System                                       */
/* ==============================                                       */
/*                                                                      */
/* Copyright (c) 2002 - 2007                                            */
/* http://www.php-maximus.org                                           */
/* dev@php-maximus.org                                                  */
/*                                                                      */
/* 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.       */
/************************************************************************/
/* Based on PHP-NUKE: Web Portal System                                 */
/************************************************************************/
/* Portage Coppermine Photo Gallery                                     */
/************************************************************************/
defined('MAXIMUS') or require_once("mainfile.php");

if ( !defined('ADMIN_ALLOW') ) {
	redirect_url('modules.php?name=Coppermine');
}

$pagetitle = "- Coppermine";


define('IN_COPPERMINE', true);
define('USERMGR_PHP', true);
define('PROFILE_PHP', true);
switch($func) {
default:
incoh();


require('modules/Coppermine/include/init.inc.php');

if (!GALLERY_ADMIN_MODE) cpg_die(ERROR, $lang_errors['access_denied'], __FILE__, __LINE__);

function list_users()
{
	global $CONFIG, $PHP_SELF, $HTTP_GET_VARS;
	global $lang_usermgr_php, $lang_byte_units, $register_date_fmt;

	$sort_codes = array(
		'name_a' => 'username ASC',
		'name_d' => 'username DESC',
		'group_a' => 'group_name ASC',
		'group_d' => 'group_name DESC',
		'reg_a' => 'user_regdate_cp ASC',
		'reg_d' => 'user_regdate_cp DESC',
		'pic_a' => 'pic_count ASC',
		'pic_d' => 'pic_count DESC',
		'disku_a' => 'disk_usage ASC',
		'disku_d' => 'disk_usage DESC',
	);

	$sort = (!isset($HTTP_GET_VARS['sort']) || !isset($sort_codes[$HTTP_GET_VARS['sort']])) ? 'reg_d' : $HTTP_GET_VARS['sort'];

	$tab_tmpl = array(
			'left_text' => '<td width="100%%" align="left" valign="middle" class="tableh1_compact" style="white-space: nowrap"><b>'.$lang_usermgr_php['u_user_on_p_pages'].'</b></td>'."\n",
			'tab_header' => '',
			'tab_trailer' => '',
			'active_tab' => '<td><img src="modules/Coppermine/images/spacer.gif" width="1" height="1" alt="" /></td>'."\n".'<td align="center" valign="middle" class="tableb_compact"><b>%d</b></td>',
			'inactive_tab' => '<td><img src="modules/Coppermine/images/spacer.gif" width="1" height="1" alt="" /></td>'."\n".'<td align="center" valign="middle" class="navmenu"><a href="modules.php?name=Coppermine&amp;op=usermgr&amp;page=%d&amp;sort='.$sort.'"<b>%d</b></a></td>'."\n"
	);

	$result= $GLOBALS['db']->sql_query("SELECT count(*) FROM `".TABLE_USERS."` WHERE 1");
	$nbEnr = $GLOBALS['db']->sql_fetchrow($result);
	$user_count = $nbEnr[0];
	$GLOBALS['db']->sql_free($result);

	if (!$user_count) cpg_die(CRITICAL_ERROR, $lang_usermgr_php['err_no_users'], __FILE__, __LINE__);

	$user_per_page = 25;
	$page = isset($HTTP_GET_VARS['page']) ? (int)$HTTP_GET_VARS['page'] : 1;
	$lower_limit = ($page-1) * $user_per_page;
	$total_pages = ceil($user_count / $user_per_page);

	$sql =  "SELECT `user_id`, `username`, `user_email`, UNIX_TIMESTAMP(user_regdate) as user_regdate_cp, `group_name`, `user_active_cp`, ".
			"COUNT(pid) as pic_count, ROUND(SUM(total_filesize)/1024) as disk_usage, `group_quota` ".
			"FROM `".TABLE_USERS."` AS u ".
			"INNER JOIN `".TABLE_CPG_USERGROUPS."` AS g ON user_group_cp = group_id ".
			"LEFT JOIN `".TABLE_CPG_ALBUMS."` AS a ON category = ".FIRST_USER_CAT." + user_id ".
			"LEFT JOIN `".TABLE_CPG_PICTURES."` AS p ON p.aid = a.aid ".
			"GROUP BY `user_id` ".
			"ORDER BY ".$sort_codes[$sort]." ".
			"LIMIT $lower_limit, $user_per_page";

	$result = $GLOBALS['db']->sql_query($sql);

	$tabs = create_tabs($user_count, $page, $total_pages, $tab_tmpl);

	starttable('100%');
	echo <<< EOT

	<tr>
		<td class="tableh1"><b><span class="statlink">{$lang_usermgr_php['name']}</span></b></td>
		<td class="tableh1"><b><span class="statlink">{$lang_usermgr_php['group']}</span></b></td>

		<td class="tableh1" colspan="2" align="center"><b><span class="statlink">{$lang_usermgr_php['operations']}</span></b></td>
		<td class="tableh1" align="center"><b><span class="statlink">{$lang_usermgr_php['pictures']}</span></b></td>
		<td class="tableh1" colspan="2" align="center"><b><span class="statlink">{$lang_usermgr_php['disk_space']}</span></b></td>
	</tr>
EOT;

	while($user = $GLOBALS['db']->sql_fetchrow($result)){
		if($user['user_active_cp'] == 'NO') $user['group_name'] = '<i>'.$lang_usermgr_php['inactive'].'</i>';
		$user['user_regdate_cp'] = localised_date($user['user_regdate_cp'], $register_date_fmt);
		if ($user['pic_count']) {
		    $usr_link_start = '<a href="modules.php?name=Coppermine&cat='.($user['user_id']+FIRST_USER_CAT).'" target="_blank">';
			$usr_link_end = '</a>';
		} else {
			$usr_link_start = '';
			$usr_link_end = '';
		}

		echo <<< EOT
	<tr>
		<td class="tableb">$usr_link_start{$user['username']}$usr_link_end</td>
		<td class="tableb">{$user['group_name']}</td>

		<td class="tableb" align="center"><div class="admin_menu"><a href="modules.php?name=Coppermine&amp;op=usermgr&amp;op2=edit&amp;user_id={$user['user_id']}">{$lang_usermgr_php['edit']}</a></div></td>
		<td class="tableb"  align="center"><div class="admin_menu"><a href="modules.php?name=Coppermine&amp;op=delete&amp;id={$user['user_id']}&amp;what=user"  onclick="return confirm('{$lang_usermgr_php['confirm_del']}');">{$lang_usermgr_php['delete']}</a></div></td>
		<td class="tableb" align="center">{$user['pic_count']}</td>
		<td class="tableb" align="right">{$user['disk_usage']} {$lang_byte_units[1]}</td>
		<td class="tableb" align="right">{$user['group_quota']} {$lang_byte_units[1]}</td>
	</tr>

EOT;
	} // while
	$GLOBALS['db']->sql_free( $result);


	$lb = "<select name=\"album_listbox\" class=\"listbox\" onChange=\"if(this.options[this.selectedIndex].value) window.location.href='modules.php?name=Coppermine&op=usermgr&page=$page&sort='+this.options[this.selectedIndex].value;\">\n";
	foreach($sort_codes as $key => $value){
		$selected = ($key == $sort) ? "SELECTED" : "";
		$lb .= "	<option value=\"" . $key . "\" $selected>" . $lang_usermgr_php[$key] . "</option>\n";
	}
	$lb.= "</select>\n";

	echo <<<EOT
	<tr>
		<form method="post" action="modules.php?name=Your_Account&op=new_user">
		<td colspan="8" align="center" class="tablef">
		<table cellpadding="0" cellspacing="0">
		<tr>
			<td><input type="submit" value="{$lang_usermgr_php['create_new_user']}" class="button"></td>
			<td><img src="modules/Coppermine/images/spacer.gif" width="50" height="1" alt="" /></td>
			<td><b>{$lang_usermgr_php['sort_by']}</b></td>
			<td><img src="modules/Coppermine/images/spacer.gif" width="10" height="1" alt="" /></td>
			<td>$lb</td>
		</tr>
		</table>
		</td>
		</form>
	</tr>
	<tr>
		<td colspan="8" style="padding: 0px;">
			<table width="100%" cellspacing="0" cellpadding="0">
				<tr>
					$tabs
				</tr>
			</table>
		</td>
	</tr>

EOT;

	endtable();
}

function edit_user($user_id)
{
	global $CONFIG, $PHP_SELF;
	global $lang_usermgr_php, $lang_yes, $lang_no;
	$user_id = secure( $user_id, 'num', 1, 'sec' );
	$form_data = array(
		array('input', 'username', $lang_usermgr_php['name'], 25),
		array('yesno', 'user_active_cp', $lang_usermgr_php['user_active_cp']),
		array('group_list', 'user_group_cp', $lang_usermgr_php['user_group_cp'])
	);

	$sql = "SELECT * FROM `".TABLE_USERS."` WHERE `user_id` = '$user_id'";
	$result = $GLOBALS['db']->sql_query($sql);
	if(!$GLOBALS['db']->sql_numrows($result)) cpg_die(CRITICAL_ERROR, $lang_usermgr_php['err_unknown_user'], __FILE__, __LINE__);
	$user_data = $GLOBALS['db']->sql_fetchrow($result);
	$GLOBALS['db']->sql_free($result);

	starttable(500, $lang_usermgr_php['modify_user'], 2);
	echo <<<EOT
	<form method="post" action="modules.php?name=Coppermine&op=usermgr&op2=update&user_id=$user_id">

EOT;

	foreach ($form_data as $element) switch($element[0]) {
		case 'input' :
		$user_data[$element[1]] = $user_data[$element[1]];
		echo <<<EOT
	<tr>
    	<td width="40%" class="tableb">
			{$element[2]}
        </td>
        <td width="60%" class="tableb" valign="top">
        	<input type="text" style="width: 100%" name="{$element[1]}" maxlength="{$element[3]}" value="{$user_data[$element[1]]}" class="textinput">
		</td>
	</tr>

EOT;
		break;

		case 'password' :

		break;

		case 'yesno' :
		$value = $user_data[$element[1]];
		$yes_selected = ($value == 'YES') ? 'selected' : '';
		$no_selected  = ($value == 'NO') ? 'selected' : '';
		echo <<< EOT
	<tr>
    	<td class="tableb">
			{$element[2]}
        </td>
		<td class="tableb">
			<select name="{$element[1]}" class="listbox">
				<option value="YES" $yes_selected>$lang_yes</option>
				<option value="NO" $no_selected>$lang_no</option>
			</select>
		</td>
	</tr>

EOT;
		break;

		case 'group_list' :
		$sql = "SELECT `group_id`, `group_name` FROM `".TABLE_CPG_USERGROUPS."` ORDER BY `group_name`";
		$result = $GLOBALS['db']->sql_query($sql);
		$group_list = $GLOBALS['db']->sql_fetch_rowset($result);
		$GLOBALS['db']->sql_free($result);
		$sel_group = $user_data[$element[1]];

		echo <<<EOT
	<tr>
    	<td class="tableb">
			{$element[2]}
        </td>
        <td class="tableb" valign="top">
        	<select name="{$element[1]}" class="listbox">

EOT;
		foreach($group_list as $group){
			echo '        		<option value="'.$group['group_id'].'"'.($group['group_id'] == $sel_group ? ' selected' : '').'>'.$group['group_name'] . "</option>\n";
		}
	echo <<<EOT
			</select>
		</td>
	</tr>

EOT;
		break;

    	default:
			cpg_die(CRITICAL_ERROR, 'Invalid action for form creation '.$element[0], __FILE__, __LINE__);
	}

	echo <<<EOT

	<tr>
		<td colspan="2" align="center" class="tablef">
			<input type="submit" value="{$lang_usermgr_php['modify_user']}" class="button">
		</td>
		</form>
	</tr>

EOT;

	endtable();

}

function update_user($user_id)
{
	global $CONFIG, $PHP_SELF, $HTTP_POST_VARS;
	global $lang_usermgr_php, $lang_register_php;
	$user_id        = secure( $user_id, 'num', 1, 'sec' );
	$username 	= secure( $HTTP_POST_VARS['username'], '', 1, 'sec' );
 	$user_password 	= secure( $HTTP_POST_VARS['user_password'], '', 1, 'sec' );
 	$user_email 	= secure( $HTTP_POST_VARS['user_email'], '', 1, 'sec' );
	$user_from	= secure( $HTTP_POST_VARS['user_from'], '', 1, 'sec' );
	$user_interests	= secure( $HTTP_POST_VARS['user_interests'], '', 1, 'sec' );
	$user_website	= secure( $HTTP_POST_VARS['user_website'], '', 1, 'sec' );
	$user_occ       = secure( $HTTP_POST_VARS['user_occ'], '', 1, 'sec' );
	$user_active_cp = secure( $HTTP_POST_VARS['user_active_cp'], '', 1, 'sec' );
	$user_group_cp 	= secure( $HTTP_POST_VARS['user_group_cp'], '', 1, 'sec' );


$sql = "SELECT `user_id` ".
		   "FROM `".TABLE_USERS."` ".
 		   "WHERE `username` = '".addslashes($username)."' AND `user_id` != $user_id";
 	$result = $GLOBALS['db']->sql_query($sql);

 	if ($GLOBALS['db']->sql_numrows($result)) {
 		cpg_die(ERROR, $lang_register_php['err_user_exists'], __FILE__, __LINE__);
 		return false;
 	}
 	$GLOBALS['db']->sql_free($result);

	$sql_update = "UPDATE `".TABLE_USERS."` ".
				  "SET ".
				  "`username` 	  = '$username', ".
				  "`user_email`	  = '$user_email', ".
				  "`user_active_cp`    = '$user_active_cp', ".
				  "`user_group_cp` 	  = '$user_group_cp', ".
				  "`user_from`  = '$user_from', ".
				  "`user_interests` = '$user_interests', ".
				  "`user_website`	 = '$user_website', ".
				  "`user_occ`= '$user_occ'";
	if($user_password) $sql_update .= ", `user_password` = '$user_password'";
	$sql_update .= " WHERE `user_id` = '$user_id'";

	$GLOBALS['db']->sql_query($sql_update);
}

$op2 = isset($HTTP_GET_VARS['op2']) ? $HTTP_GET_VARS['op2'] : '';

switch($op2){
	case 'edit' :
	$user_id = isset($HTTP_GET_VARS['user_id']) ? (int)$HTTP_GET_VARS['user_id'] : -1;

	if(USER_ID == $user_id) cpg_die(ERROR, $lang_usermgr_php['err_edit_self'], __FILE__, __LINE__);

	pageheader($lang_usermgr_php['title']);
	edit_user($user_id);
	pagefooter();
	ob_end_flush();
	break;

	case 'update' :
	$user_id = isset($HTTP_GET_VARS['user_id']) ? (int)$HTTP_GET_VARS['user_id'] : -1;

	update_user($user_id);

	pageheader($lang_usermgr_php['title']);
	list_users();
	pagefooter();
	ob_end_flush();
	break;

	case 'new_user' :
	$GLOBALS['db']->sql_query("INSERT INTO `".TABLE_USERS."` (user_regdate_cp, user_active_cp) VALUES (NOW(), 'YES')");

	$user_id = mysql_insert_id();

	pageheader($lang_usermgr_php['title']);
	edit_user($user_id);
	pagefooter();
	ob_end_flush();
	break;

	default :
	pageheader($lang_usermgr_php['title']);
	list_users();
	pagefooter();
	ob_end_flush();
	break;
}
incof();
break;
}