<?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';

$error = 0;
$range = (preg_match ('`^[\d]+$`', $_REQUEST['range']) && $_REQUEST['range'] > 0 ? intval ($_REQUEST['range']) : 200);

if ($_REQUEST['action'] == "update_RSS") {
	$result = saveRSS_feeds();// ? "RSS feed updated." : "There was an error updating the RSS feeds";
	$url = DOC_ROOT."/dir_categs.php?r=1";
	
	//http_custom_redirect($url);
	$tpl->assign('succesMsg', 'RSS feeds updated');
	$tpl->assign('errMsg', 'There was a problem updating the RSS feeds');
	$tpl->assign('err', $result);
	
}

if ($_REQUEST['action'] == "rebuild_cache" ) : //Load just cache rebuilding and not complete page

   $start_query     = (!empty ($_REQUEST['start']) ? intval ($_REQUEST['start']) : 0);
    
   $total_processed = (!empty ($_REQUEST['total_processed']) ? intval ($_REQUEST['total_processed']) : 0);
   
   $total           = (!empty ($_REQUEST['total']) ? intval ($_REQUEST['total']) : 0);

   $processes = 0;

   //Recalculate total links to be processed
   //in case it could be not determined from the URL
   if (empty ($total))
      $total = $db->GetOne("SELECT COUNT(*) FROM `{$tables['category']['name']}`");

   $categIDs = $db->GetAll("SELECT `ID`, `DATE_ADDED` FROM `{$tables['category']['name']}` ORDER BY `ID` ASC LIMIT {$start_query}, {$range}");

   foreach($categIDs as $key => $categ)
   {
      $data = array (
                  'CACHE_TITLE' => trim (buildCategUrlTitle($categ['ID'])) ,
                  'CACHE_URL'   => trim (buildCategUrl($categ['ID']))      ,
                  'DATE_ADDED'  => $categ['DATE_ADDED']
               );

      $where = " `ID` = ".$db->qstr($categ['ID']);

      if ($db->AutoExecute($tables['category']['name'], $data, 'UPDATE', $where))
         $processes++;

      $total_processed++;

      //Free Memory
      unset ($categIDs[$key], $categ, $data, $where);
   }

   // Building redirect
   $next_start_query = $start_query + $range;
   
   if ($next_start_query <= $total)
   {
       
      $url  = DOC_ROOT."/dir_categs.php?action=rebuild_cache";
      $url .= "&range={$range}";
      $url .= "&start={$next_start_query}";
      $url .= "&total_processed={$total_processed}";
      $url .= "&total={$total}";

      $build_type = _L('Rebuild Category Cache');

      $title_msg  = $build_type;

      $cust_msg   = '<p>';
      $cust_msg  .= $build_type;
      $cust_msg  .= '</p>';

      $cust_msg  .= '<p>'._L('Starting at link').': <span class="important">'.$start_query.'</span></p>';
      $cust_msg  .= '<p>'._L('Stopping at link').': <span class="important">'.$next_start_query.'</span></p>';
      $cust_msg  .= '<p>'._L('Queries performed (this session/total sessions)').': <span class="important">'.$processes.'/'.$total_processed.'</span></p>';
      $cust_msg  .= '<p>'._L('Total queries to process').': <span class="important">'.$total.'</span></p>';
      $cust_msg  .= '<p>'._L('Number of processes per cycle').': <span class="important">'.$range.'</span></p>';

      $cust_msg  .= '<p class="notice">'._L('Depending on the size of information to be processed, this action can take some time.').'</p>';

      $redirect = javascript_redirect($url, ADMIN_REDIRECT_TIMEOUT, $title_msg, $cust_msg);
      $tpl->assign('redirect', $redirect);
   }
   else
   {
      $url = DOC_ROOT."/dir_categs.php?r=1";
      $title_msg = _L('Category cache rebuild status').': '._L('Complete');
      $redirect  = javascript_redirect($url, ADMIN_REDIRECT_TIMEOUT, $title_msg, $cust_msg, 1);
      $tpl->assign('redirect', $redirect);
   }

else : //Regular Category page

$error = 0;

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

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

//Load and run multiple link actions
require_once 'categ_multi_action.php';

$tpl->assign('stats'  , array (0       => _L('Inactive'), 1           => _L('Pending')  , 2             => _L('Active'),));
$tpl->assign('symb'   , array (0       => _L('Normal')  , 1           => _L('Symbolic'),));

//Determine columns
$columns = array ('TITLE' => _L('Title')   , 'TITLE_URL' => _L('URL Title'), 'PARENT' => _L('Parent'), 'SYMBOLIC' => _L('Type'), 'STATUS' => _L('Status'), 'HITS' => _L('Hits'), 'DATE_ADDED' => _L('Date Added'));
$tpl->assign('columns', $columns);

//Determine column sorting URLs
$columnURLs = GetColSortUrls($columns, $current_item);
$tpl->assign('columnURLs', $columnURLs);

if (empty ($_POST['submit']))
{
   SmartyValidate :: connect($tpl);

   SmartyValidate :: register_form('rebuild_cache', true);
   SmartyValidate :: register_validator("v_range", "range", "isNumber", false, false, 'trim', 'rebuild_cache');
}
else
{
   SmartyValidate :: connect($tpl);
   if (SmartyValidate :: is_valid($_POST, 'rebuild_cache') && !empty ($_POST['submit']))
   {
      $total    = $db->GetOne("SELECT COUNT(*) FROM `{$tables['category']['name']}`");
      $url      = DOC_ROOT."/dir_categs.php?action=rebuild_cache&start=0&range={$_POST['range']}&total={$total}";

      $cust_msg = '<p class="notice">'._L('Depending on the size of information to be processed, this action can take some time.').'</p>';

      $redirect = javascript_redirect($url, ADMIN_REDIRECT_TIMEOUT, '', $cust_msg);
      $tpl->assign('redirect', $redirect);
   }
}

// Determine current index
$page  = ceil ($current_item / LINKS_PER_PAGE); // Determine page
$limit = ' LIMIT '.($current_item <= 1 ? '0' : $current_item).', '.LINKS_PER_PAGE;

$where = '';
if (isset ($_REQUEST['parent']))
{
   $_REQUEST['parent'] = urldecode ($_REQUEST['parent']);

   //Clean multiple spaces, commas, etc
   $pattern  = array ( '/\s/', '`[,]+`', '`^[,]*`', '`[,]+$`' );
   $replace  = array ( ''    , ','     , ''       , ''        );
   $_REQUEST['parent'] = preg_replace ($pattern, $replace, $_REQUEST['parent']);

   $parentsArray = explode (',', $_REQUEST['parent']);
   $parentsArray = array_unique ($parentsArray);

   if (is_array ($parentsArray) && !empty ($parentsArray))
      $where .= " AND C.PARENT_ID IN ('".implode ("', '", $parentsArray)."')";
    $wherea .= " AND PARENT_ID IN ('".implode ("', '", $parentsArray)."')";

   $_REQUEST['parent'] = implode (',', $parentsArray);
}

if (isset ($_REQUEST['category']))
{
   $_REQUEST['category'] = urldecode ($_REQUEST['category']);

   //Clean multiple spaces, commas, etc
   $pattern  = array ( '/\s/', '`[,]+`', '`^[,]*`', '`[,]+$`' );
   $replace  = array ( ''    , ','     , ''       , ''        );
   $_REQUEST['category'] = preg_replace ($pattern, $replace, $_REQUEST['category']);

   $categoriesArray = explode (',', $_REQUEST['category']);
   $categoriesArray = array_unique ($categoriesArray);

   if (is_array ($categoriesArray) && !empty ($categoriesArray))
      $where .= " AND C.ID IN ('".implode ("', '", $categoriesArray)."')";

   $_REQUEST['category'] = implode (',', $categoriesArray);

   $category = (!empty ($_REQUEST['category']) ? $_REQUEST['category'] : '');
   $tpl->assign('category', $category);
}

////Search by ID
//$searchByID = (!empty ($_REQUEST['searchbyid']) && preg_match ('`^[\d]+$`', $_REQUEST['searchbyid']) ? intval ($_REQUEST['searchbyid']) : '');
//$tpl->assign('searchbyid', $searchByID);
//if (!empty ($searchByID))
//{
//   $where .= " AND C.ID LIKE ".$db->qstr('%'.$searchByID.'%');
//   $_REQUEST['searchbyid'] = $searchByID;
//}

if (isset ($_REQUEST['status']) && preg_match ('`^[\d]+$`', $_REQUEST['status']))
{
   $_REQUEST['status'] = intval ($_REQUEST['status']);
   $where .= " AND C.STATUS = ".$db->qstr($_REQUEST['status']);
}

$orderBy = ' ORDER BY ';
if (defined ('SORT_FIELD') && SORT_FIELD != '')
{
   $orderBy .= (SORT_FIELD == 'PARENT' ? 'P.TITLE' : 'C.' . SORT_FIELD) . ' ' . (defined ('SORT_ORDER') ? SORT_ORDER : 'ASC') . ', ';
}
$orderBy .= 'C.PARENT_ID ASC';

require_once '../search.php';
$search_preferences = array ();
$search_preferences['Select_Options']  = array ();
$search_preferences['Where_Options']   = array ();
$search_preferences['Order_Options']   = array ();
$search_preferences['Search_Location'] = array ( "C.TITLE_URL" ,
                                                 "C.TITLE",
                                                 "C.DESCRIPTION",
                                                 "C.ID"
                                                 );
//$search_preferences['BooleanSearchActive'] = 1;
                                                 
$LinksResults = search($search_preferences);

$search       = (!empty ($LinksResults['search']) ? $LinksResults['search'] : '');
$tpl->assign('search', $search);

if ($_SESSION['phpld']['adminpanel']['is_admin'])
{
	if (isset ($_REQUEST['parent'])){
		$list_total = $db->GetOne("SELECT COUNT(*) FROM `{$tables['category']['name']}` WHERE 1 ".(!empty ($LinksResults['Search_Query']) ? " AND ".$LinksResults['Search_Query'] : '')." {$wherea}");
	}else{
   $list_total = $db->GetOne("SELECT COUNT(*) FROM `{$tables['category']['name']}` WHERE 1 ".(!empty ($LinksResults['Search_Query']) ? " AND ".$LinksResults['Search_Query'] : '')." {$where}");
	}
   $tpl->assign('list_total', $list_total);

   $sql = "SELECT C.* ".(!empty ($LinksResults['Select_Relevancy']) ? ", ".$LinksResults['Select_Relevancy'] : '').", ".$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 1 {$where} ".(!empty ($LinksResults['Search_Query']) ? " AND  ".$LinksResults['Search_Query'] : '').(!empty ($LinksResults['Relevancy_Tuning']) ? $LinksResults['Relevancy_Tuning'] : '').$orderBy;
   
   $rs = $db->SelectLimit($sql, LINKS_PER_PAGE, ($current_item <= 1 ? '0' : $current_item - 1));

   if ($rs === false)
      $list = array ();
   else
      $list = $rs->GetAssoc(true);
}
else
{
	$list_total = $db->GetOne("SELECT COUNT(*) FROM `{$tables['category']['name']}` WHERE ".$_SESSION['phpld']['adminpanel']['permission'].(!empty ($LinksResults['Search_Query']) ? " AND ".$LinksResults['Search_Query'] : '')." {$where}");
	$tpl->assign('list_total', $list_total);

    $sql = "SELECT C.* ".(!empty ($LinksResults['Select_Relevancy']) ? ", ".$LinksResults['Select_Relevancy'] : '').", ".$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 1 ".(!empty ($LinksResults['Search_Query']) ? " AND  ".$LinksResults['Search_Query'] : '').(!empty ($LinksResults['Relevancy_Tuning']) ? $LinksResults['Relevancy_Tuning'] : '').$where.$orderBy;

	$rs = $db->SelectLimit($sql, LINKS_PER_PAGE, ($current_item <= 1 ? '0' : $current_item - 1));

	if ($rs === false)
      $list = array ();
   else
      $list = $rs->GetAssoc(true);
}

//Get Title and description for symbolic categories
foreach ($list as $category => $category_row)
{
   if ($list[$category]['SYMBOLIC'] == 1)
   {
      $tempcat = $db->GetRow("SELECT * FROM `{$tables['category']['name']}` WHERE ID = ".$db->qstr($list[$category]['SYMBOLIC_ID']));
      if (empty ($list[$category]['TITLE']))
         $list[$category]['TITLE'] = $tempcat['TITLE'];

      $list[$category]['TITLE'] = '@' . $list[$category]['TITLE'];
      $list[$category]['DESCRIPTION'] = $tempcat['DESCRIPTION'];
   }
}

// Start Paging
SmartyPaginate :: connect(); // Connect Paging
SmartyPaginate :: setPageLimit(LINKS_PER_PAGE); // Set default number of page groupings

// Build Paging
if ($page < 2)
{
   SmartyPaginate :: disconnect();
   SmartyPaginate :: reset     ();
}

$list_total     = (!empty ($list_total) && $list_total >= 0      ? intval ($list_total)     : 0);
$PagerGroupings = (PAGER_GROUPINGS      && PAGER_GROUPINGS > 0   ? intval (PAGER_GROUPINGS) : 20);
$LinksPerPage   = (LINKS_PER_PAGE       && LINKS_PER_PAGE  > 0   ? intval (LINKS_PER_PAGE)  : 10);

SmartyPaginate :: setPrevText    ('Previous'             );
SmartyPaginate :: setNextText    ('Next'                 );
SmartyPaginate :: setFirstText   ('First'                );
SmartyPaginate :: setLastText    ('Last'                 );
SmartyPaginate :: setTotal       ($list_total            );
SmartyPaginate :: setUrlVar      ('p'                    );
SmartyPaginate :: setUrl         ($_SERVER['REQUEST_URI']);
SmartyPaginate :: setCurrentItem ($current_item          );
SmartyPaginate :: setLimit       ($LinksPerPage          );
SmartyPaginate :: setPageLimit   ($PagerGroupings        );
SmartyPaginate :: assign         ($tpl                   );

unset ($list_total, $PagerGroupings, $LinksPerPage);

//$min_keyword_length_comment = _L("Keywords shorter than #MIN_WORD_LENGTH# characters are ignored because of MySQL server settings.");
$min_keyword_length_comment = _L("Type in the keyword(s) or category id you're searching for.");
$min_keyword_length         = (!empty ($LinksResults['Min_Word_Length']) ? $LinksResults['Min_Word_Length'] : '4');
$min_keyword_length_comment = str_replace ('#MIN_WORD_LENGTH#', $min_keyword_length, $min_keyword_length_comment);
$tpl->assign('min_keyword_length_comment', $min_keyword_length_comment);

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

endif;

$tpl->assign('range', $range);
$tpl->assign('error', $error);
$tpl->assign('action', (!empty ($_REQUEST['action']) ? $_REQUEST['action'] : ''));


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

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

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