<?php 
/*#################################################################*\
|# Licence Number 0DT7-0122-0NW1-0210
|# -------------------------------------------------------------   #|
|# Copyright (c)2010 PHP Link Directory.                           #|
|# http://www.phplinkdirectory.com                                 #|
\*#################################################################*/
	
/**
# ################################################################################
# Project:   PHP Link Directory
#
# **********************************************************************
# Copyright (C) 2004-2009 NetCreated, Inc. (http://www.netcreated.com/)
#
# This software is for use only to those who have purchased a license.
# A license must be purchased for EACH installation of the software.
#
# By using the software you agree to the terms:
#
#    - You may not redistribute, sell or otherwise share this software
#      in whole or in part without the consent of the the ownership
#      of PHP Link Directory. Please contact david@david-duval.com
#      if you need more information.
#
#    - You agree to retain a link back to http://www.phplinkdirectory.com/
#      on all pages of your directory in you purchased the $25 version
#      of the software.
#
# License holders are entitled to upgrades to the 3.4 branch of the software
# as they are made available at http://www.phplinkdirectory.com/
#
# In some cases, license holders may be required to agree to changes
# in the software license before receiving updates to the software.
# **********************************************************************
#
# For questions, help, comments, discussion, etc., please join the
# PHP Link Directory Forum http://www.phplinkdirectory.com/forum/
#
# @link           http://www.phplinkdirectory.com/
# @copyright      2004-2009 NetCreated, Inc. (http://www.netcreated.com/)
# @projectManager David DuVal <david@david-duval.com>
# @package        PHPLinkDirectory
# @version        4.0.0
# ################################################################################
*/

require_once 'init.php';

if (empty ($_REQUEST['submit']) && !empty ($_SERVER['HTTP_REFERER']))
   $_SESSION['return'] = $_SERVER['HTTP_REFERER'];

$tpl->assign('ENABLE_REWRITE', ENABLE_REWRITE);

$error = 0;
$errorMsg = '';

if ($_REQUEST['action'])
{
   list ($action, $id) = split(':', $_REQUEST['action']);

   $action = strtoupper (trim ($action));
   $tpl->assign('action', strtoupper ($action));
}

//If editor, check if he/she is allowed to take an action on current category
if (!$_SESSION['phpld']['adminpanel']['is_admin'])
{
//   if (!in_array ($id, $_SESSION['phpld']['adminpanel']['permission_array']))
    if (($_SESSION['phpld']['adminpanel']['rights']['addCat'] != 1 && $action == 'N') 
	|| ($_SESSION['phpld']['adminpanel']['rights']['editCat'] != 1 && ($action == 'E' || $action == 'M'))
	|| ($_SESSION['phpld']['adminpanel']['rights']['delCat'] != 1 && ($action == 'D'))
	|| !($_REQUEST['action']))
   {
      //Editor is on unallowed page, block access
      http_custom_redirect("unauthorized.php");
      exit();
   }
}

//Correct value for ID
$id = (isset ($id) ? intval ($id) : 0);
$id = ($id < 0 ? 0 : $id);

$currentCategory = $db->GetRow("SELECT C.*, ".$db->IfNull('P.TITLE', "'Top'")." AS `PARENT` FROM `{$tables['category']['name']}` AS `C` LEFT OUTER JOIN `{$tables['category']['name']}` AS `P` ON (C.PARENT_ID = P.ID) WHERE C.ID = ".$db->qstr($id)." LIMIT 1");
$tpl->assign('currentCategory', $currentCategory);


$tpl->assign('stats', array (0 => _L('Inactive'), 1 => _L('Pending'), 2 => _L('Active'),));
$tpl->assign('symbolic', $_REQUEST['s'] == '1');

switch($action)
{
	case 'C' :
		if (isset ($_SESSION['return']))
         http_custom_redirect($_SESSION['return']);

		break;
	case 'A' :
      $ActionStatus = SetNewCategoryStatus($id, 2);
      $error = ($ActionStatus['status'] == 1 ? false : true);

      if ($ActionStatus['status'] != 1)
         $tpl->assign('sql_error', $ActionStatus['errorMsg']);

      if (!$error && isset ($_SESSION['return']))
         http_custom_redirect($_SESSION['return']);
		break;
	case 'D' :
      $error = 0;

      if (isset ($_REQUEST['cancel']) && !empty ($_REQUEST['cancel']))
      {
         //If canceled, redirect to category list
         http_custom_redirect(DOC_ROOT.'/dir_categs.php?r=1');
      }
      else
      {
         //Count links and subcategories of this category
         $count_links    = $db->GetOne("SELECT COUNT(*) FROM `{$tables['link']['name']}` WHERE `CATEGORY_ID` = ".$db->qstr($id));
         $count_articles = $db->GetOne("SELECT COUNT(*) FROM `{$tables['article']['name']}` WHERE `CATEGORY_ID` = ".$db->qstr($id));
         $count_categs   = $db->GetOne("SELECT COUNT(*) FROM `{$tables['category']['name']}` WHERE `PARENT_ID` = ".$db->qstr($id));

         if ($count_links > 0 || $count_articles > 0 || $count_categs > 0)
         {
            //Get action
            $DO = (isset ($_REQUEST['do']) ? strtolower (trim ($_REQUEST['do'])) : 'move');

            if (isset ($_REQUEST['delete']) && !empty ($_REQUEST['delete']))
            {
               switch ($DO)
               {
                  //All subcategories, links and articles of this category are removed
                  case 'delete' :
                     if (!$db->Execute("DELETE FROM `{$tables['link']['name']}` WHERE `CATEGORY_ID` = ".$db->qstr($id)))
                     {
                        $error++;
                        $tpl->assign('sql_error', $db->ErrorMsg());
                     }
                     if (!$db->Execute("DELETE FROM `{$tables['article']['name']}` WHERE `CATEGORY_ID` = ".$db->qstr($id)))
                     {
                        $error++;
                        $tpl->assign('sql_error', $db->ErrorMsg());
                     }
                     if (!$db->Execute("DELETE FROM `{$tables['category']['name']}` WHERE `PARENT_ID` = ".$db->qstr($id)))
                     {
                        $error++;
                        $tpl->assign('sql_error', $db->ErrorMsg());
                     }
                     break;
                  //Subcategories and links are moved first to another category
                  case 'move'   :
                     //Determine category where we should move everything
                     $newCategID = (isset ($_REQUEST['CATEGORY_ID']) ? intval ($_REQUEST['CATEGORY_ID']) : '-1');

                     //Check if removing category is not the same as where everything has to be moved
                     if ($newCategID >= 0 && $newCategID != $id)
                     {
                        //Move links
                        if (!$db->Execute("UPDATE `{$tables['link']['name']}` SET `CATEGORY_ID` = ".$db->qstr($newCategID)." WHERE `CATEGORY_ID` = ".$db->qstr($id)))
                        {
                           $error++;
                           $tpl->assign('sql_error', $db->ErrorMsg());
                        }
                        //Move articles
                        if (!$db->Execute("UPDATE `{$tables['article']['name']}` SET `CATEGORY_ID` = ".$db->qstr($newCategID)." WHERE `CATEGORY_ID` = ".$db->qstr($id)))
                        {
                           $error++;
                           $tpl->assign('sql_error', $db->ErrorMsg());
                        }
                        //Move subcategories
                        if (!$db->Execute("UPDATE `{$tables['category']['name']}` SET `PARENT_ID` = ".$db->qstr($newCategID)." WHERE `PARENT_ID` = ".$db->qstr($id)))
                        {
                           $error++;
                           $tpl->assign('sql_error', $db->ErrorMsg());
                        }
                     }
                     else
                     {
                        $error++;
                        $tpl->assign('errorMsg', _L('Invalid or same category selected!'));
                     }

                     break;

                  default :
                     break;
               }

               if ($error == 0)
               {
                  $count_links    = $db->GetOne("SELECT COUNT(*) FROM `{$tables['link']['name']}` WHERE `CATEGORY_ID` = ".$db->qstr($id));
                  $count_articles = $db->GetOne("SELECT COUNT(*) FROM `{$tables['article']['name']}` WHERE `CATEGORY_ID` = ".$db->qstr($id));
                  $count_categs   = $db->GetOne("SELECT COUNT(*) FROM `{$tables['category']['name']}` WHERE `PARENT_ID` = ".$db->qstr($id));
               }
            }
         }

         if ($count_links == 0 && $count_articles == 0 && $count_categs == 0 && $error == 0)
         {
            $rm = $db->Execute("DELETE FROM `{$tables['category']['name']}` WHERE `ID` = ".$db->qstr($id));
            if ($rm)
            {
               http_custom_redirect(DOC_ROOT.'/dir_categs.php?r=1');
            }
            else
            {
               $error++;
               $tpl->assign('sql_error', $db->ErrorMsg());
            }
         }
      }

      if (AJAX_CAT_SELECTION_METHOD == 0)
      {
         $categs = get_categs_tree();
         $tpl->assign('categs'      , $categs);
      }

      $tpl->assign('id'            , $id);
      $tpl->assign('error'         , $error);
      $tpl->assign('do'            , $DO);
      $tpl->assign('count_links'   , $count_links);
      $tpl->assign('count_articles', $count_articles);
      $tpl->assign('count_categs'  , $count_categs);
		break;

   case 'M' :
      $quickAdded = 0;
      $multicategs = (isset ($_POST['multicategs']) ? clean_str_white_space($_POST['multicategs']) : '');

      if (!empty ($_REQUEST['submit']) && !empty ($multicategs))
      {
         $multiCategsArray = explode ("\n", $multicategs);

         if (is_array ($multiCategsArray) && !empty ($multiCategsArray))
         {
            $currDate = gmdate ('Y-m-d H:i:s');

            //Loop through each category
            foreach ($multiCategsArray as $key => $singleCateg)
            {
               //Clean each category title
               $singleCateg = $multiCategsArray[$key] = strip_white_space($singleCateg);
               $checkSQL = "SELECT COUNT(*) FROM `{$tables['category']['name']}` WHERE `TITLE` LIKE ".$db->qstr($singleCateg)." AND `PARENT_ID` = ".$db->qstr($id);

               if (!empty ($singleCateg) && $db->GetOne($checkSQL) < 1)
               {
                  $data = array();

                  //Generate ID
                  $data['ID'] = intval ($db->GenID($tables['category']['name'].'_SEQ'));

                  //Add parent ID
                  $data['PARENT_ID'] = $id;

                  $data['TITLE'] = $singleCateg;

                  //Build URL
                  $data['TITLE_URL'] = preg_replace('`[^\w_-]`', '_', $data['TITLE']);

                  //Build cache
                  $data['CACHE_TITLE'] = trim (buildCategUrlTitle($data['ID']));
                  $data['CACHE_URL']   = trim (buildCategUrl($data['ID']));

                  //Add current date
                  $data['DATE_ADDED'] = $currDate;

                  //Make category active
                  $data['STATUS'] = 2;

                  if (!$db->Replace($tables['category']['name'], $data, 'ID', true) > 0)
                  {
                     $error++;
                     $tpl->assign('sql_error', $db->ErrorMsg());
                  }
                  else
                  {
                     $quickAdded++;
                     unset ($multiCategsArray[$key]);
                  }
               }
               else
               {
                  unset ($multiCategsArray[$key]);
               }
            }

            //Refresh editor permissions
            if (!$_SESSION['phpld']['adminpanel']['is_admin'])
            {
               $user_permission             = "";
               $user_grant_permission       = "";
					$user_permission_array       = array();
					$user_grant_permission_array = array();

					get_editor_permission($_SESSION['phpld']['adminpanel']['id']);
					$_SESSION['phpld']['adminpanel']['permission']             = $user_permission;
					$_SESSION['phpld']['adminpanel']['grant_permission']       = $user_grant_permission;
					$_SESSION['phpld']['adminpanel']['permission_array']       = $user_permission_array;
					$_SESSION['phpld']['adminpanel']['grant_permission_array'] = $user_grant_permission_array;
            }

            $multicategs = implode ("\n", $multiCategsArray);
         }
      }

      $tpl->assign('multicategs', $multicategs);
      $tpl->assign('quickAdded', $quickAdded);
	case 'E' :
		if (empty ($_REQUEST['submit']))
			$data = $db->GetRow("SELECT * FROM `{$tables['category']['name']}` WHERE `ID` = ".$db->qstr($id));

	case 'N' :
	default :
	  $SORT_ORDER ='1000';
	  $tpl->assign('SORT_ORDER', $SORT_ORDER); 	
      //Determine length of description field
      $DescriptionLimit = (isset ($data['DESCRIPTION']) && strlen (trim ($data['DESCRIPTION'])) > 0 ? CAT_DESCRIPTION_MAX_LENGTH - strlen (trim ($data['DESCRIPTION'])) : CAT_DESCRIPTION_MAX_LENGTH);
      $tpl->assign('DescriptionLimit', $DescriptionLimit);
      //Determine length of meta description field
      $MetaDescriptionLimit = (isset ($data['META_DESCRIPTION']) && strlen (trim ($data['META_DESCRIPTION'])) > 0 ? META_DESCRIPTION_MAX_LENGTH - strlen (trim ($data['META_DESCRIPTION'])) : META_DESCRIPTION_MAX_LENGTH);
      $tpl->assign('MetaDescriptionLimit', $MetaDescriptionLimit);

		if ((empty ($_REQUEST['submit']))   || (!SmartyValidate :: is_registered_form('dir_categs_edit')))
		{
			if ($action == 'N')
			{
				$data = array ();
				$data['STATUS'] = 2;
			}
			SmartyValidate :: connect($tpl);
			SmartyValidate :: register_form('dir_categs_edit', true);
			if ($_REQUEST['s'] != '1')
			{
				SmartyValidate :: register_criteria('isValueUnique', 'validate_unique', 'dir_categs_edit');

				SmartyValidate :: register_validator('v_TITLE'           , 'TITLE'                 , 'notEmpty', false, false, 'trim', 'dir_categs_edit');
				SmartyValidate :: register_validator('v_TITLE_U'         , 'TITLE:category:'.$id.':PARENT_ID', 'isValueUnique', false, false, null, 'dir_categs_edit');
            SmartyValidate :: register_validator('v_TITLE_LENGTH'    , 'TITLE:'.CAT_TITLE_MIN_LENGTH.':'.CAT_TITLE_MAX_LENGTH, 'isLength', false, false, 'trim', 'dir_categs_edit');

				SmartyValidate :: register_validator('v_DESCRIPTION_LENGTH', 'DESCRIPTION:'.CAT_DESCRIPTION_MIN_LENGTH.':'.CAT_DESCRIPTION_MAX_LENGTH, 'isLength'  , true, false, 'trim', 'dir_categs_edit');
				SmartyValidate :: register_validator('v_META_DESCRIPTION_LENGTH', 'META_DESCRIPTION:'.META_DESCRIPTION_MIN_LENGTH.':'.META_DESCRIPTION_MAX_LENGTH, 'isLength'  , true, false, 'trim', 'dir_categs_edit');

            //SmartyValidate :: register_validator('v_META_KEYWORDS', 'META_KEYWORDS:'.META_KEYWORDS_MIN_LENGTH.':'.META_KEYWORDS_MAX_LENGTH, 'isLength', true , false, 'trim', 'dir_categs_edit');

				if (ENABLE_REWRITE == 1)
				{
					SmartyValidate :: register_validator('v_TITLE_URL'  , 'TITLE_URL:!^[\w_-]+$!', 'isRegExp', false, false, 'trim', 'dir_categs_edit');
					SmartyValidate :: register_validator('v_TITLE_URL_U', 'TITLE_URL:category:'.$id.':PARENT_ID', 'isValueUnique', false, false, null, 'dir_categs_edit');
				}
			}
			else
			{
				SmartyValidate :: register_criteria('isNotEqual'        , 'validate_not_equal'      , 'dir_categs_edit');
				SmartyValidate :: register_criteria('isNotEqualVariable', 'validate_not_equal_var'  , 'dir_categs_edit');
				SmartyValidate :: register_criteria('isSymbolicUnique'  , 'validate_symbolic_unique', 'dir_categs_edit');
				SmartyValidate :: register_criteria('isParentValid'     , 'validate_symbolic_parent', 'dir_categs_edit');

				SmartyValidate :: register_validator('v_SYMBOLIC_ID'  , 'SYMBOLIC_ID:0'        , 'isNotEqual'        , true , false, null, 'dir_categs_edit');
				SmartyValidate :: register_validator('v_SYMBOLIC_ID_E', 'SYMBOLIC_ID:PARENT_ID', 'isNotEqualVariable', true , false, null, 'dir_categs_edit');
				SmartyValidate :: register_validator('v_SYMBOLIC_ID_U', 'SYMBOLIC_ID'          , 'isSymbolicUnique'  , false, false, null, 'dir_categs_edit');
				SmartyValidate :: register_validator('v_SYMBOLIC_ID_P', 'SYMBOLIC_ID'          , 'isParentValid'     , false, false, null, 'dir_categs_edit');
			}
		}
      else
      {
			SmartyValidate :: connect($tpl);
			$data = get_table_data('category');

         $data['SYMBOLIC'] = (isset ($_REQUEST['s']) && $_REQUEST['s'] == 1 ? 1 : 0);

			if (strlen (trim ($data['TITLE_URL'])) == 0)
				$data['TITLE_URL'] = preg_replace('`[^\w_-]`', '_', $data['TITLE']);

         //If editor, check if he/she is allowed to take an action on current category
         if (!$_SESSION['phpld']['adminpanel']['is_admin'] &&
             !empty ($data['PARENT_ID']) &&
             (($_SESSION['phpld']['adminpanel']['rights']['addCat'] != 1 && $action == 'N') || ($_SESSION['phpld']['adminpanel']['rights']['editCat']!=1 && ($action == 'E' || $action == 'M')))
         )
         {
            //Editor is on unallowed page, block access
            http_custom_redirect("unauthorized.php");
            exit();
         }

			if (SmartyValidate :: is_valid($data, 'dir_categs_edit'))
			{
				if ($action == 'N')
					$data['DATE_ADDED'] = gmdate ('Y-m-d H:i:s');

				if (empty ($id))
					$id = $db->GenID($tables['category']['name'].'_SEQ');

				$data['ID'] = intval ($id);

            $data['CACHE_TITLE'] = trim (buildCategUrlTitle($id));
            $data['CACHE_URL']   = trim (buildCategUrl($id));

            if ($db->Replace($tables['category']['name'], $data, 'ID', true) > 0)
            {
               saveRSS_feeds($data['ID']);
               //Build CACHE
               $cache_data = array ();
               $cache_data['ID']          = $data['ID'];
               $cache_data['CACHE_TITLE'] = trim (buildCategUrlTitle($id));
               $cache_data['CACHE_URL']   = trim (buildCategUrl($id));
               $db->Replace($tables['category']['name'], $cache_data, 'ID', true);

               if (ENABLE_REWRITE)
               {
                  //Re-build cache for subcategories,
                  //only if URL rewriting is enabled
                  $subcategs = get_sub_categories($data['ID']);
                  if (is_array ($subcategs) && !empty ($subcategs))
                  {
                     //Loop through each subcategory
                     foreach ($subcategs as $sKey => $subcatID)
                     {
                        //Build cache
                        $subcat_cache_data = array ();
                        $subcat_cache_data['ID']          = $subcatID;
                        $subcat_cache_data['CACHE_TITLE'] = trim (buildCategUrlTitle($subcatID));
                        $subcat_cache_data['CACHE_URL']   = trim (buildCategUrl($subcatID));

                        //Write new cache
                        $db->Replace($tables['category']['name'], $subcat_cache_data, 'ID', true);

                        //Free memory
                        unset ($subcat_cache_data[$sKey], $subcatID);
                     }
                  }
                  unset ($subcategs);
               }
               unset ($cache_data);

               // Refresh editor permissions
					if (!$_SESSION['phpld']['adminpanel']['is_admin'])
					{
						$user_permission             = "";
						$user_grant_permission       = "";
						$user_permission_array       = array();
						$user_grant_permission_array = array();

						get_editor_permission($_SESSION['phpld']['adminpanel']['id']);
						$_SESSION['phpld']['adminpanel']['permission']             = $user_permission;
						$_SESSION['phpld']['adminpanel']['grant_permission']       = $user_grant_permission;
						$_SESSION['phpld']['adminpanel']['permission_array']       = $user_permission_array;
						$_SESSION['phpld']['adminpanel']['grant_permission_array'] = $user_grant_permission_array;
					}

					$tpl->assign('posted', true);
					if ($action == 'N')
               {
                  $oldStatus = $data['STATUS'];
						$data = array ();
                  $data['STATUS'] = $oldStatus;
                  unset ($oldStatus);
               }
					else
						if (isset ($_SESSION['return']))
							http_custom_redirect($_SESSION['return']);
				}
				else
					$tpl->assign('sql_error', $db->ErrorMsg());
			}
		}

      if (AJAX_CAT_SELECTION_METHOD == 0 || $_REQUEST['s'] == 1)
      {
      	 if ($action == 'N') {
      	 	$categs = get_categs_tree();
      	 } else {
      		$categs = get_categs_tree_backend(0, intval($id));
      	 }
         $tpl->assign('categs', $categs);
      }
      break;
}

$tpl->assign('error', $error);
$tpl->assign('errorMsg', $errorMsg);

$tpl->assign($data);

$content = $tpl->fetch(ADMIN_TEMPLATE.'/dir_categs_edit.tpl');
$tpl->assign('content', $content);

//Clean whitespace
$tpl->load_filter('output', 'trimwhitespace');

//Make output
echo $tpl->fetch(ADMIN_TEMPLATE.'/main.tpl');
?>
