<?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('CATMGR_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__);
new_cache();
// Fix categories that have an invalid parent
function fix_cat_table(){
	$result = $GLOBALS['db']->sql_query("SELECT `cid` FROM `".TABLE_CPG_CATEGORIES."` WHERE 1");
	if ($GLOBALS['db']->sql_numrows($result) > 0){
		$set = '';
		while($row = $GLOBALS['db']->sql_fetchrow($result)) $set .= $row['cid'] . ',';
		$set = '('.substr($set, 0, -1).')';
		$sql = "UPDATE `".TABLE_CPG_CATEGORIES."` ".
			   "SET `parent` = '0' ".
			   "WHERE `parent`='cid' OR `parent` NOT IN $set";
		$result = $GLOBALS['db']->sql_query($sql);
	}
}

function get_subcat_data($parent, $ident='') {
    global $CAT_LIST;
	$parent = secure( $parent, 'num', 1, 'sec' );
	$sql = "SELECT `cid`, `namee`, `description` ".
		   "FROM `".TABLE_CPG_CATEGORIES."` ".
		   "WHERE `parent` = '$parent' ".
		   "ORDER BY `pos`";
	$result = $GLOBALS['db']->sql_query($sql);

	if (($cat_count = $GLOBALS['db']->sql_numrows($result)) > 0){
		$rowset = $GLOBALS['db']->sql_fetch_rowset($result);
		$pos=0;
		foreach ($rowset as $subcat){
			if($pos>0){
				$CAT_LIST[]=array(
					'cid' => $subcat['cid'],
					'parent' => $parent,
					'pos' => $pos++,
					'prev' => $prev_cid,
					'cat_count' => $cat_count,
					'namee' => $ident.$subcat['namee']);
				$CAT_LIST[$last_index]['next'] = $subcat['cid'];
			} else {
				$CAT_LIST[]=array(
					'cid' => $subcat['cid'],
					'parent' => $parent,
					'pos' => $pos++,
					'cat_count' => $cat_count,
					'namee' => $ident.$subcat['namee']);
			}
			$prev_cid = $subcat['cid'];
			$last_index = count($CAT_LIST)	-1;
			get_subcat_data($subcat['cid'], $ident.'&nbsp;&nbsp;&nbsp;');
		}
	}
}

function update_cat_order(){
	global $CAT_LIST;

	foreach ($CAT_LIST as $category)
		$GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_CATEGORIES."` SET `pos`='{$category['pos']}' WHERE `cid` = '{$category['cid']}' LIMIT 1");
}

function cat_list_box($highlight=0, $curr_cat, $on_change_refresh = true)
{
	global $CAT_LIST, $PHP_SELF;

	if($on_change_refresh){
		$lb = <<< EOT
			<select onChange="if(this.options[this.selectedIndex].value) window.location.href='modules.php?name=Coppermine&op=catmgr&oppe=setparent&cid=$curr_cat&parent='+this.options[this.selectedIndex].value;" name="parent" class="listbox">

EOT;
	} else {
		$lb = <<< EOT
			<select name="parent" class="listbox">

EOT;
	}
	$lb .= '<option value="0"'.($highlight == 0 ? ' selected': '').">* No Category *</option>\n";
	foreach($CAT_LIST as $category) if ($category['cid'] != 1 && $category['cid'] != $curr_cat) {
		$lb .= '			<option value="'.$category['cid'].'"'.($highlight == $category['cid'] ? ' selected': '').">".$category['namee']."</option>\n";
	} elseif ($category['cid'] != 1 && $category['cid'] == $curr_cat){
		$lb .= '<option value="'.$category['parent'].'"'.($highlight == $category['cid'] ? ' selected': '').">".$category['namee']."</option>\n";
	}

	$lb .= <<<EOT
			</select>

EOT;

	return $lb;
}

function display_cat_list()
{
	global $CAT_LIST, $PHP_SELF,$opp;

	$CAT_LIST3 = $CAT_LIST;

	foreach ($CAT_LIST3 as $key => $category){
		echo "<tr>\n";
		echo '<td class="tableb" width="80%"><b>'.$category['namee'].'</b></td>'."\n";

		if ($category['pos']>0) {
			echo '<td class="tableb" width="4%"><a href="modules.php?name=Coppermine&amp;op=catmgr&amp;oppe=move&amp;cid1='.$category['cid'].'&amp;pos1='.($category['pos']-1).'&amp;cid2='.$category['prev'].'&amp;pos2='.($category['pos']).'">'.'<img src="modules/Coppermine/images/up.gif"  border="0" alt="UP" title="UP" />'.'</a></td>'."\n";
		} else {
			echo '<td class="tableb" width="4%">'.'&nbsp;'.'</td>'."\n";
		}

		if ($category['pos'] < $category['cat_count']-1) {
			echo '<td class="tableb" width="4%"><a href="modules.php?name=Coppermine&amp;op=catmgr&amp;oppe=move&amp;cid1='.$category['cid'].'&amp;pos1='.($category['pos']+1).'&amp;cid2='.$category['next'].'&amp;pos2='.($category['pos']).'">'.'<img src="modules/Coppermine/images/down.gif" border="0" alt="DOWN" title="DOWN" />'.'</a></td>'."\n";
		} else {
			echo '<td class="tableb" width="4%">'.'&nbsp;'.'</td>'."\n";
		}

		if ($category['cid'] != 1) {
			echo '<td class="tableb" width="4%"><a href="modules.php?name=Coppermine&amp;op=catmgr&amp;oppe=deletecat&amp;cid='.$category['cid'].'" onClick="return confirmDel(\''.addslashes(str_replace('&nbsp;','', $category['namee'])).'\')">'.'<img src="modules/Coppermine/images/delete.gif"  border="0">'.'</a></td>'."\n";
		} else {
			echo '<td class="tableb" width="4%">'.'&nbsp;'.'</td>'."\n";
		}

		echo '<td class="tableb" width="4%">'.'<a href="modules.php?name=Coppermine&amp;op=catmgr&amp;oppe=editcat&amp;cid='.$category['cid'].'">'.'<img src="modules/Coppermine/images/edit.gif" border="0">'.'</a></td>'."\n";
		echo '<td class="tableb" width="4%">'."\n".cat_list_box($category['parent'], $category['cid'])."\n".'</td>'."\n";
		echo "	</tr>\n";
	}
}

$opp = isset($_POST['opp']) ? $_POST['opp'] : '';

$current_category = array('cid' => '0', 'namee'=>'', 'parent' => '0', 'description'=>'');
switch($opp){
	case 'move':
	if (!isset($_GET['cid1']) || !isset($_GET['cid2']) || !isset($_GET['pos1']) || !isset($_GET['pos2'])) cpg_die(CRITICAL_ERROR, sprintf($lang_catmgr_php['miss_param'], 'move'), __FILE__, __LINE__);

	$cid1 = secure( $_GET['cid1'], 'num', 1, 'sec' );
	$cid2 = secure( $_GET['cid2'], 'num', 1, 'sec' );
	$pos1 = secure( $_GET['pos1'], 'num', 1, 'sec' );
	$pos2 = secure( $_GET['pos2'], 'num', 1, 'sec' );

	$GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_CATEGORIES."` SET `pos`='$pos1' WHERE `cid` = '$cid1' LIMIT 1");
	$GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_CATEGORIES."` SET `pos`='$pos2' WHERE `cid` = '$cid2' LIMIT 1");
	break;

	case 'setparent':
	if (!isset($_GET['cid']) || !isset($_GET['parent'])) cpg_die(CRITICAL_ERROR, sprintf($lang_catmgr_php['miss_param'], 'setparent'), __FILE__, __LINE__);

	$cid    = secure( $_GET['cid'], 'num', 1, 'sec' );
	$parent = secure( $_GET['parent'], 'num', 1, 'sec' );

	$GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_CATEGORIES."` SET `parent`='$parent', `pos`='-1' WHERE `cid` = '$cid' LIMIT 1");
	break;

	case 'editcat':
	if (!isset($_GET['cid'])) cpg_die(CRITICAL_ERROR, sprintf($lang_catmgr_php['miss_param'], 'editcat'), __FILE__, __LINE__);

	$cid    = secure( $_GET['cid'], 'num', 1, 'sec' );
	$result = $GLOBALS['db']->sql_query("SELECT `cid`, `namee`, `parent`, `description` FROM `".TABLE_CPG_CATEGORIES."` WHERE `cid` = '$cid' LIMIT 1");

	if(!$GLOBALS['db']->sql_numrows($result)) cpg_die(ERROR, $lang_catmgr_php['unknown_cat'], __FILE__, __LINE__);
	$current_category = $GLOBALS['db']->sql_fetchrow($result);
	break;

	case 'updatecat':
	if (!isset($_POST['cid']) || !isset($_POST['parent']) || !isset($_POST['namee']) || !isset($_POST['description'])) cpg_die(CRITICAL_ERROR, sprintf($lang_catmgr_php['miss_param'], 'updatecat'), __FILE__, __LINE__);

	$cid    = secure( $_POST['cid'], 'num', 1, 'sec' );
	$parent = secure( $_POST['parent'], 'num', 1, 'sec' );
	$namee = trim($_POST['namee']) ? addslashes($_POST['namee']) : '&lt;???&gt;';
	$description = addslashes($_POST['description']);

	$GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_CATEGORIES."` SET `parent`='$parent', `namee`='$namee', description='$description' WHERE `cid`='$cid' LIMIT 1");
	break;

	case 'createcat':
	if (!isset($_POST['parent']) || !isset($_POST['namee']) || !isset($_POST['description'])) cpg_die(CRITICAL_ERROR, sprintf($lang_catmgr_php['miss_param'], 'createcat'), __FILE__, __LINE__);

	$parent = secure( $_POST['parent'], 'num', 1, 'sec' );
	$namee = trim($_POST['namee']) ? addslashes($_POST['namee']) : '&lt;???&gt;';
	$description = secure( $_POST['description'], '', 1, 'sec' );

	$GLOBALS['db']->sql_query("INSERT INTO `".TABLE_CPG_CATEGORIES."` (pos, parent, namee, description) VALUES ('10000', '$parent', '$namee', '$description')");
	break;


}

$oppe = isset($_GET['oppe']) ? $_GET['oppe'] : '';

$current_category = array('cid' => '0', 'namee'=>'', 'parent' => '0', 'description'=>'');
switch($oppe){
	case 'move':
	if (!isset($_GET['cid1']) || !isset($_GET['cid2']) || !isset($_GET['pos1']) || !isset($_GET['pos2'])) cpg_die(CRITICAL_ERROR, sprintf($lang_catmgr_php['miss_param'], 'move'), __FILE__, __LINE__);

	$cid1 = secure( $_GET['cid1'], 'num', 1, 'sec' );
	$cid2 = secure( $_GET['cid2'], 'num', 1, 'sec' );
	$pos1 = secure( $_GET['pos1'], 'num', 1, 'sec' );
	$pos2 = secure( $_GET['pos2'], 'num', 1, 'sec' );

	$GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_CATEGORIES."` SET `pos`='$pos1' WHERE `cid` = '$cid1' LIMIT 1");
	$GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_CATEGORIES."` SET `pos`='$pos2' WHERE `cid` = '$cid2' LIMIT 1");
	break;

	case 'setparent':
	if (!isset($_GET['cid']) || !isset($_GET['parent'])) cpg_die(CRITICAL_ERROR, sprintf($lang_catmgr_php['miss_param'], 'setparent'), __FILE__, __LINE__);

	$cid    = secure( $_GET['cid'], 'num', 1, 'sec' );
	$parent = secure( $_GET['parent'], 'num', 1, 'sec' );

	$GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_CATEGORIES."` SET `parent`='$parent', `pos`='-1' WHERE `cid` = '$cid' LIMIT 1");
	break;

	case 'editcat':
	if (!isset($_GET['cid'])) cpg_die(CRITICAL_ERROR, sprintf($lang_catmgr_php['miss_param'], 'editcat'), __FILE__, __LINE__);

	$cid    = secure( $_GET['cid'], 'num', 1, 'sec' );
	$result = $GLOBALS['db']->sql_query("SELECT `cid`, `namee`, `parent`, `description` FROM `".TABLE_CPG_CATEGORIES."` WHERE `cid` = '$cid' LIMIT 1");

	if(!$GLOBALS['db']->sql_numrows($result)) cpg_die(ERROR, $lang_catmgr_php['unknown_cat'], __FILE__, __LINE__);
	$current_category = $GLOBALS['db']->sql_fetchrow($result);
	break;

	case 'updatecat':
	if (!isset($_POST['cid']) || !isset($_POST['parent']) || !isset($_POST['namee']) || !isset($_POST['description'])) cpg_die(CRITICAL_ERROR, sprintf($lang_catmgr_php['miss_param'], 'updatecat'), __FILE__, __LINE__);

	$cid    = secure( $_POST['cid'], 'num', 1, 'sec' );
	$parent = secure( $_POST['parent'], 'num', 1, 'sec' );
	$namee = trim($_POST['namee']) ? addslashes($_POST['namee']) : '&lt;???&gt;';
	$description = secure( $_POST['description'], '', 1, 'sec' );

	$GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_CATEGORIES."` SET `parent`='$parent', `namee`='$namee', `description`='$description' WHERE `cid` = '$cid' LIMIT 1");
	break;

	case 'createcat':
	if (!isset($_POST['parent']) || !isset($_POST['namee']) || !isset($_POST['description'])) cpg_die(CRITICAL_ERROR, sprintf($lang_catmgr_php['miss_param'], 'createcat'), __FILE__, __LINE__);

	$parent = secure( $_POST['parent'], 'num', 1, 'sec' );
	$namee = trim($_POST['namee']) ? addslashes($_POST['namee']) : '&lt;???&gt;';
	$description = secure( $_POST['description'], '', 1, 'sec' );

	$GLOBALS['db']->sql_query("INSERT INTO `".TABLE_CPG_CATEGORIES."` (pos, parent, namee, description) VALUES ('10000', '$parent', '$namee', '$description')");
	break;

	case 'deletecat':
	if (!isset($_GET['cid'])) cpg_die(CRITICAL_ERROR, sprintf($lang_catmgr_php['miss_param'], 'deletecat'), __FILE__, __LINE__);

	$cid    = secure( $_GET['cid'], 'num', 1, 'sec' );
	$parent = secure( $_POST['parent'], 'num', 1, 'sec' );

	$result = $GLOBALS['db']->sql_query("SELECT `parent` FROM `".TABLE_CPG_CATEGORIES."` WHERE `cid` = '$cid' LIMIT 1");
	if($cid == 1) cpg_die(ERROR,$lang_catmgr_php['usergal_cat_ro'], __FILE__, __LINE__);
	if(!$GLOBALS['db']->sql_numrows($result)) cpg_die(ERROR, $lang_catmgr_php['unknown_cat'], __FILE__, __LINE__);
	$del_category = $GLOBALS['db']->sql_fetchrow($result);
	$parent = secure( $del_category['parent'], 'strip', 1 );
	$result = $GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_CATEGORIES."` SET `parent`='$parent' WHERE `parent` = '$cid'");
	$result = $GLOBALS['db']->sql_query("UPDATE `".TABLE_CPG_ALBUMS."` SET `category`='$parent' WHERE `category` = '$cid'");
	$result = $GLOBALS['db']->sql_query("DELETE FROM `".TABLE_CPG_CATEGORIES."` WHERE `cid`='$cid' LIMIT 1");
	break;
}

fix_cat_table();
get_subcat_data(0);
update_cat_order();

pageheader($lang_catmgr_php['manage_cat']);
echo <<<EOT

<script language="javascript">
function confirmDel(catName)
{
    return confirm("{$lang_catmgr_php['confirm_delete']} (" + catName + ") ?");
}
</script>


EOT;


starttable('100%');

echo <<<EOT
	<tr>
		<td class="tableh1"><b><span class="statlink">{$lang_catmgr_php['category']}</span></b></td>
		<td colspan="4" class="tableh1" align="center"><b><span class="statlink">{$lang_catmgr_php['operations']}</span></b></td>
		<td class="tableh1" align="center"><b><span class="statlink">{$lang_catmgr_php['move_into']}</span></b></td>
	</tr>
	<form method="get" action="modules.php?name=Coppermine&op=catmgr">

EOT;

display_cat_list();

echo <<<EOT
	</form>

EOT;

endtable();

br('1');

starttable('100%', $lang_catmgr_php['update_create'], 2);
$lb = cat_list_box($current_category['parent'], $current_category['cid'], false);
$opp = $current_category['cid'] ? 'updatecat' : 'createcat';
echo <<<EOT
	<form method="post" action="modules.php">

	<input type="hidden" name="cid" value ="{$current_category['cid']}" />

	<tr>
    	<td width="40%" class="tableb">
			{$lang_catmgr_php['parent_cat']}
        </td>
        <td width="60%" class="tableb" valign="top">
        	$lb
		</td>
	</tr>
	<tr>
    	<td width="40%" class="tableb">
			{$lang_catmgr_php['cat_title']}
        </td>
        <td width="60%" class="tableb" valign="top">
        	<input type="text" style="width: 100%" name="namee" value="{$current_category['namee']}" class="textinput" />
		</td>
	</tr>
	<tr>
		<td class="tableb" valign="top">
			{$lang_catmgr_php['cat_desc']}
		</td>
		<td class="tableb" valign="top">
			<textarea name="description" ROWS="5" COLS="40" SIZE="9"  WRAP="virtual" STYLE="WIDTH: 100%;" class="textinput">{$current_category['description']}</textarea>
		</td>
	</tr>
	<tr>
		<td colspan="2" align="center" class="tablef">
		<input type="submit" value="{$lang_catmgr_php['update_create']}" class="button" />


<input type="hidden" name="opp" value ="$opp" />
<input type="hidden" name="op" value ="catmgr" />
<input type="hidden" name="name" value ="Coppermine" />
		</td>
		</form>
	</tr>

EOT;

endtable();
pagefooter();
ob_end_flush();

incof();
break;
}