<?php
// The source code packaged with this file is Free Software, Copyright (C) 2005 by
// Ricardo Galli <gallir at uib dot es>.
// It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
// You can get copies of the licenses here:
// 		http://www.affero.org/oagpl.html
// AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".

include_once('Smarty.class.php');
$main_smarty = new Smarty;

include('config.php');
include(mnminclude.'html1.php');
include(mnminclude.'ts.php');
include(mnminclude.'link.php');
include(mnminclude.'smartyvariables.php');
include_once(mnminclude.'dbtree.php');
include(mnminclude.'qeip_0_3.php');

// require user to log in
force_authentication();

// restrict access to god only
$canIhaveAccess = 0;
$canIhaveAccess = $canIhaveAccess + checklevel('god');

if($canIhaveAccess == 0){	
	$main_smarty->assign('tpl_center', $the_template . '/admin_templates/admin_access_denied');
	$main_smarty->display($the_template . '/pligg.tpl');		
	die();
}

if(caching == 1){
	// this is to clear the cache and reload it for settings_from_db.php
	$db->cache_dir = mnmpath.'cache';
	$db->use_disk_cache = true;
	$db->cache_queries = true;
	$db->cache_timeout = 0;
	// if this query is changed, be sure to also change it in config.php
	$the_cats = $db->get_results("select category_id, category__auto_id, lft, rgt, category_name, category_safe_name, category_lang, category_desc, category_keywords from ".table_categories." ORDER BY lft ASC;");
	$db->cache_queries = false;
	global $cached_categories;
	$cached_categories = $the_cats;

}

// breadcrumbs and page title
$navwhere['text1'] = $main_smarty->get_config_vars('PLIGG_Visual_Header_AdminPanel');
$navwhere['link1'] = getmyurl('admin', '');
$navwhere['text2'] = $main_smarty->get_config_vars('PLIGG_Visual_Header_AdminPanel_2');
$navwhere['link2'] = my_pligg_base . "/admin_categories.php";
$main_smarty->assign('navbar_where', $navwhere);
$main_smarty->assign('posttitle', " / " . $main_smarty->get_config_vars('PLIGG_Visual_Header_AdminPanel'));

if($canIhaveAccess == 1)
{
	// clear the category sidebar module from the cache so it can regenerate in case we make changes
	$main_smarty->cache = 2; 
	$main_smarty->cache_dir = "cache";
	$main_smarty->clear_cache();
	$main_smarty->cache = false; 

	$main_smarty = do_sidebar($main_smarty);

	$QEIPA = array('table_name' => table_categories,  // the name of the table to use
			          'field_name' => 'category_name',  // the name of the field in the table
			          'key' => 'category__auto_id');  // a unique identifier for the row
	$main_smarty->assign('qeip_CatName', $QEIPA);

	$QEIPA = array('table_name' => table_categories,  // the name of the table to use
			          'field_name' => 'category_parent',  // the name of the field in the table
			          'key' => 'category__auto_id');  // a unique identifier for the row
	$main_smarty->assign('qeip_CatParent', $QEIPA);

	$QEIPA = array('table_name' => table_categories,  // the name of the table to use
			          'field_name' => 'category_order',  // the name of the field in the table
			          'key' => 'category__auto_id');  // a unique identifier for the row
	$main_smarty->assign('qeip_CatOrder', $QEIPA);

	$QEIPA = array('table_name' => table_categories,  // the name of the table to use
			          'field_name' => 'category_desc',  // the name of the field in the table
			          'key' => 'category__auto_id');  // a unique identifier for the row
	$main_smarty->assign('qeip_CatDesc', $QEIPA);

	$QEIPA = array('table_name' => table_categories,  // the name of the table to use
			          'field_name' => 'category_keywords',  // the name of the field in the table
			          'key' => 'category__auto_id');  // a unique identifier for the row
	$main_smarty->assign('qeip_CatMeta', $QEIPA);
	
	$smarty = $main_smarty;
	$QEIP = new QuickEIP();
	$main_smarty = $smarty;	

	// pagename
	define('pagename', 'admin_categories'); 
	$main_smarty->assign('pagename', pagename);

	rebuild_the_tree();
	ordernew();

// put the category tree into an array for use in the qeip dropdown

	if(isset($_REQUEST['action'])){
		$action = $_REQUEST['action'];
	} else {
		$action = "view";
	}	
	
	if($action == "save"){
		echo $QEIP->save_field();
		Cat_Safe_Names();
	}

	if($action == "add"){
		$sql = "insert into `" . table_categories . "` (`category_name`) VALUES ('new category');";
		$db->query($sql);
		rebuild_the_tree();
		ordernew();
		Cat_Safe_Names();
		header("Location: admin_categories.php");
	}

	if($action == "changecolor"){
		$id = $_REQUEST['id'];
		$color = $_REQUEST['color'];
		$color = utf8_str_replace('#', '', $color);
	
		$sql = "update ".table_categories." set category_color = '" . $color . "' where category__auto_id=" . $id . ";";
		echo $sql;
		$db->query($sql);

		Cat_Safe_Names();
	}

	if($action == "remove"){
		$id = $_REQUEST['id'];
		$sql = "delete from ".table_categories." where category__auto_id=" . $id . ";";
		$db->query($sql);
		header("Location: admin_categories.php");
	}

	if($action == "changeparent"){
		$id = utf8_substr($_REQUEST['id'], 9, 100);
		$parent = utf8_substr($_REQUEST['parent'], 9, 100);
		
		children_id_to_array($array, table_categories, $id);
		if(is_array($array)){
			if(in_array($parent, $array)){
				die('You cannot move a category into it\'s own subcategory. Click <a href = "admin_categories.php">here</a> to reload.');
			}
		}
		
		if($id == $parent) {header("Location: admin_categories.php");die();}

		$sql = "update ".table_categories." set category_parent = " . $parent . " where category__auto_id=" . $id . ";";
		$db->query($sql);
		header("Location: admin_categories.php");
	}

	if($action == "move_above"){
		$id = utf8_substr($_REQUEST['id_to_move'], 9, 100);
		$move_id = utf8_substr($_REQUEST['moveabove_id'], 6, 100);

		if($id == $move_id) {header("Location: admin_categories.php");}

		$array = "";
		children_id_to_array($array, table_categories, $id);
		if(is_array($array)){
			if(!in_array($move_id, $array))
			{
				$sql = "Select * from ".table_categories." where category__auto_id=" . $move_id . ";";
				$results = $db->get_row($sql);
				$move_sort = $results->category_order;
				
				$sql = "update ".table_categories." set category_parent = ".$results->category_parent.", category_order = " . ($move_sort - 1) . " where category__auto_id=" . $id . ";";
				$db->query($sql);
				rebuild_the_tree();
				header("Location: admin_categories.php");
			}else{
				die('You cannot move a category into it\'s own subcategory. Click <a href = "admin_categories.php">here</a> to reload.');
			}
		}else{
			$sql = "Select * from ".table_categories." where category__auto_id=" . $move_id . ";";
			$results = $db->get_row($sql);
			$move_sort = $results->category_order;
			
			$sql = "update ".table_categories." set category_parent = ".$results->category_parent.", category_order = " . ($move_sort - 1) . " where category__auto_id=" . $id . ";";
			$db->query($sql);
			rebuild_the_tree();
			header("Location: admin_categories.php");
		}
	}

	if($action == "move_below"){
		$id = utf8_substr($_REQUEST['id_to_move'], 9, 100);
		$move_id = utf8_substr($_REQUEST['movebelow_id'], 6, 100);
		
		if($id == $move_id) {header("Location: admin_categories.php");}

		$array = "";
		children_id_to_array($array, table_categories, $id);
		if(is_array($array)){
			if(!in_array($move_id, $array))
			{
				$sql = "Select * from ".table_categories." where category__auto_id=" . $move_id . ";";
				$results = $db->get_row($sql);
				$move_sort = $results->category_order;
				
				$sql = "update ".table_categories." set category_parent = ".$results->category_parent.", category_order = " . ($move_sort + 1) . " where category__auto_id=" . $id . ";";
				$db->query($sql);
				rebuild_the_tree();
				header("Location: admin_categories.php");
			}else{
				die('You cannot move a category into it\'s own subcategory. Click <a href = "admin_categories.php">here</a> to reload.');
			}
		}else{
			$sql = "Select * from ".table_categories." where category__auto_id=" . $move_id . ";";
			$results = $db->get_row($sql);
			$move_sort = $results->category_order;
			
			$sql = "update ".table_categories." set category_parent = ".$results->category_parent.", category_order = " . ($move_sort + 1) . " where category__auto_id=" . $id . ";";
			$db->query($sql);
			rebuild_the_tree();
			header("Location: admin_categories.php");
		}
	}
					
	if($action == "view"){
	
		$array = tree_to_array(0, table_categories, true);
		$main_smarty->assign('cat_count', count($array));
		$main_smarty->assign('cat_array', $array);
		$main_smarty->assign('tpl_center', The_Template . '/admin_templates/category_manager');
		$main_smarty->display(The_Template . '/pligg.tpl');
		echo $QEIP->ShowOnloadJS();
	}

}else	{
	echo 'not for you! go away!';
}


function makeCategoryFriendly($input) {
	// this was moved out of utils.php because it's only needed when changing
	// category information

	$input = utf8_substr($input, 0, 240);
	$output = utf8_strtolower($output);
	
	$output = trim($input);

	$output = str_replace(" ", "-", $output);
	$output = str_replace("_", "-", $output);
	$output = str_replace("'", "", $output);
	$output = str_replace('"', '', $output);
	$output = str_replace('&', '-', $output);
	$output = str_replace('/', '-', $output);
	$output = str_replace('!', '', $output);
	$output = str_replace('?', '', $output);
	$output = str_replace('$', '', $output);
	$output = str_replace("--", "-", $output);
	
	if(function_exists('utils_makeUrlFriendly')) {
		$output = utils_makeUrlFriendly($output);
	}
	
	return urlencode($output);	   
}

function Cat_Safe_Names(){
	// this was moved out of dbtree.php because it's only needed when changing
	// category information
	
	global $db;
	$cats = $db->get_col("Select category_name from " . table_categories . ";");
	if ($cats) {
		foreach($cats as $catname) {
			$db->query("UPDATE `" . table_categories . '` SET `category_name` = "'.safeAddSlashes($catname).'"' . ", `category_safe_name` = '".makeCategoryFriendly($catname)."' WHERE `category_name` =".'"'.safeAddSlashes($catname).'";');
		}
	}
	$cats = $db->get_col("Select category__auto_id from " . table_categories . ";");
	if ($cats) {
		foreach($cats as $catid) {
			$db->query("UPDATE `" . table_categories . "` SET `category_id` = ".$catid." WHERE `category__auto_id` ='".$catid."';");
		}
	}
}

?>
