<?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 required email confirmation add this to sql queries
if (EMAIL_CONFIRMATION == 1) {
    $email_conf = " AND `OWNER_EMAIL_CONFIRMED` = '1' ";
}


// Check page request, if not valid a http header 404 is sent
$http_status = (!empty ($_REQUEST['httpstatus']) ? intval ($_REQUEST['httpstatus']) : request_status());
httpstatus($http_status);
$uid = '';
$user_where = '';



// Determine user ID to search for, but only if valid user
if (!empty ($_SESSION['phpld']['user']['id']))
{
   if (get_user_level($_SESSION['phpld']['user']['id']) == 1 || get_user_level($_SESSION['phpld']['user']['id']) == 3 ) {
          $permission_links_arts = "1 ";
          $permission_cats = "1 ";
          $permission_cats_parents = "1 ";
          
          $uid = (!empty ($_REQUEST['uid']) && preg_match ('`^[\d]+$`', $_REQUEST['uid']) ? intval ($_REQUEST['uid']) : 0);
   } else {
       $uid = (!empty ($_REQUEST['uid']) && preg_match ('`^[\d]+$`', $_REQUEST['uid']) ? intval ($_REQUEST['uid']) : 0);
       
       //raluca
       
       $permissions = get_user_permissions($_SESSION['phpld']['user']['id']);
       
       $permission_links_arts = "`CATEGORY_ID` IN (";
       $permission_cats = "`ID` IN (";
       $permission_cats_parents = "`PARENT_ID` IN (";
       if (count($permissions) >0) {
           for ($i=0; $i<count($permissions); $i++) {
               
                   if ($i<count($permissions)-1) {
                        $permission_links_arts .= "'".$permissions[$i]['CATEGORY_ID']."', ";
                        $permission_cats .= "'".$permissions[$i]['CATEGORY_ID']."', ";
                        $permission_cats_parents .= "'".$permissions[$i]['CATEGORY_ID']."', ";
                   } else {
                        $permission_links_arts .= "'".$permissions[$i]['CATEGORY_ID']."') ";
                        $permission_cats .= "'".$permissions[$i]['CATEGORY_ID']."') ";
                        $permission_cats_parents .= "'".$permissions[$i]['CATEGORY_ID']."') ";
                   }
           }
       } else {
           $permission_links_arts = "0 ";
           $permission_cats = "0 ";
           $permission_cats_parents = "0 ";
       }
    
       //raluca
  
   }
   
   if ($uid > 0 && $uid == $_SESSION['phpld']['user']['id']) {
        $user_where = " AND `OWNER_ID` = ".$db->qstr($uid);
   } else
        unset ($uid);
} else {
   $permission_links_arts = "0 ";
   $permission_cats = "0 ";
   $permission_cats_parents = "0 ";
}

  if ($user_level == 1) $tpl->assign('edit_link', 1);
// Determine page number and current page index
if (ENABLE_REWRITE == 1 && !isset ($_REQUEST['search'])) // Rewrited page links
{
   preg_match ("/page-(\d+)\.htm[l]?([?]?.*)$/", request_uri(), $matches);
   // Determine current index
   $page         = (!empty($matches[1]) ? intval ($matches[1]) : 1);
   // Determine page
   $current_item = PAGER_LPP * $page - PAGER_LPP;
   unset ($matches);
}
else // Regular page links
{
   // Determine current index
   $current_item = (!empty ($_REQUEST['p']) && preg_match ('`^[\d]+$`', $_REQUEST['p']) ? intval ($_REQUEST['p']) : 1);
   $current_item--;
   // Determine page
   $page         = ceil ($current_item / PAGER_LPP);
}

$page = ($page < 1 ? 1 : $page); // Check again for negative page

// Remove rewrite page link
//$_SERVER['REQUEST_URI'] = preg_replace("/page-(\d+)\.htm[l]?$/", "", $_SERVER['REQUEST_URI']);
$pattern = array ("/page-(\d+)\.htm[l]?/", '`([?]|[&])(p=)+[\d]*`', '`([?]|[&])(cat_page=)+[\d]*`', '`([?]|[&])(article_page=)+[\d]*`');
$_SERVER['REQUEST_URI'] = preg_replace ($pattern, '', request_uri());

// Define sorting options
define ('DIR_LPP', 20);
$sort_cols = array ('P' => 'PAGERANK', 'H' => 'HITS', 'A' => 'TITLE', 'D' => 'DATE_ADDED');
$sort_ord  = array ('P' => 'DESC'    , 'H' => 'DESC', 'A' => 'ASC'  , 'D' => 'DESC'  );
// Build limit query

//below used to be like this:
//$limit = ' LIMIT '.($current_item <= 1 ? '0' : $current_item).', '.PAGER_LPP;

$limit = ' LIMIT '.($current_item < 1 ? '0' : $current_item).', '.PAGER_LPP;
$getSort = (!empty ($_REQUEST['s']) ? trim ($_REQUEST['s']) : (!empty ($URLvariables['s']) ? $URLvariables['s'] : ''));

if (array_key_exists ($getSort, $sort_cols))
   $sort = $getSort;
else
   $sort = DEFAULT_SORT;

if ((ENABLE_PAGERANK != 1 || SHOW_PAGERANK != 1) && $sort == 'P')
   $sort = 'H';

//if($db->GetOne("SELECT COUNT(*) FROM `{$tables['category']['name']}` WHERE `SORT_ORDER` <> '1000' AND `PARENT_ID` = '0'"))
//{
//   $CATEG_FIELD_SORT        = 'SORT_ORDER';
//   $CATEG_FIELD_SORT_ORDER  = 'DESC';
//}
//else
//{
   $CATEG_FIELD_SORT           = CATEG_FIELD_SORT;
   $CATEG_FIELD_SORT_ORDER     = CATEG_FIELD_SORT_ORDER;
//}
//if($db->GetOne("SELECT COUNT(*) FROM `{$tables['category']['name']}` WHERE `SORT_ORDER` <> '1000' AND `PARENT_ID` <> '0'"))
//{
//   $SUBCATEG_FIELD_SORT        = 'SORT_ORDER';
//   $SUBCATEG_FIELD_SORT_ORDER  = 'DESC';
//}
//else
//{
   $SUBCATEG_FIELD_SORT        = SUBCATEG_FIELD_SORT;
   $SUBCATEG_FIELD_SORT_ORDER  = SUBCATEG_FIELD_SORT_ORDER;
//}


$tpl->assign('sort', $sort);
$path    = array ();
$path[]  = array ('ID' => '0', 'TITLE' => _L(SITE_NAME), 'TITLE_URL' => DOC_ROOT, 'DESCRIPTION' => SITE_DESC);

// Query to not have feat. links in results
if (FTR_ENABLE == 1)
   $feat_where = "AND (`FEATURED` = '0')";

// Query for not exprired links
$expire_where = "AND (`EXPIRY_DATE` >= ".$db->DBDate(time())." OR `EXPIRY_DATE` IS NULL)";

// Option to turn link hits increment On/Off
$StopLinkHits = 0;

/**
 * @author Darius Tumas
 * For link editing we need to know user permisions.
 * We take them here and assign for variable, which we will provide to smarty.
 *
 */

//var_dump($_SESSION['phpld']);
//By default user does not have any permission.
$ito_user_permission = '0';
//if user is logged...
if (isset($_SESSION['phpld']['user']['id'])) {
	//...from session we take its level
	$ito_user_permission = $_SESSION['phpld']['user']['level'];
	$tpl->assign('load_Javascript',  'true');

}

if (isset ($_REQUEST['list'])) // Top pages listings
{
   $StopLinkHits = 1; // Disable link hits
   switch (strtolower ($_REQUEST['list']))
   {
      case 'latestlinks' :
      case 'latest':
         $links = $db->CacheGetAll ("SELECT * FROM `{$tables['link']['name']}` WHERE (`STATUS` = '2' OR {$permission_links_arts}){$email_conf} {$expire_where} ORDER BY `DATE_ADDED` DESC LIMIT 0, ".LINKS_TOP);
       
  
         
         $path[] = array ('ID' => '0', 'TITLE' => _L('Latest Links'), 'TITLE_URL' => '', 'DESCRIPTION' => '');
         break;
      case 'toplinks' :
      case 'top':
         $links = $db->CacheGetAll ("SELECT * FROM `{$tables['link']['name']}` WHERE (`STATUS` = '2' OR {$permission_links_arts}) {$email_conf} {$expire_where} ORDER BY `HITS` DESC LIMIT 0, ".LINKS_TOP);
         $path[] = array ('ID' => '0', 'TITLE' => _L('Top Hits'), 'TITLE_URL' => '', 'DESCRIPTION' => '');
         break;
      case 'latestarticles':
         $articles = $db->CacheGetAll ("SELECT * FROM `{$tables['article']['name']}` WHERE (`RELEASE_DATE`<= now() OR {$permission_links_arts}) AND (`STATUS` = '2' OR {$permission_links_arts}) {$email_conf} ORDER BY `FEATURED_MAIN` DESC, `FEATURED` DESC, `DATE_ADDED` DESC LIMIT 0, ".LINKS_TOP);
         $path[] = array ('ID' => '0', 'TITLE' => _L('Latest Articles'), 'TITLE_URL' => '', 'DESCRIPTION' => '');
         break;
      default:
         http_custom_redirect(DOC_ROOT);
         break;
   }
   $tpl->assign('list', $_REQUEST['list']);
}
elseif (!empty ($user_where) && !empty ($uid)) // Registered user links listings
{
      if (FTR_ENABLE == 1)
      {
         $feat_links = $db->CacheGetAll("SELECT * FROM `{$tables['link']['name']}` WHERE (`STATUS` = '2' OR {$permission_links_arts}) AND `FEATURED` = '1' {$email_conf} {$expire_where} {$user_where} ORDER BY `EXPIRY_DATE` DESC");
      }

      $count = $db->CacheGetOne("SELECT COUNT(*) FROM `{$tables['link']['name']}` WHERE (`STATUS` = '2' OR {$permission_links_arts}) {$email_conf} {$expire_where} {$user_where} ORDER BY `{$sort_cols[$sort]}` {$sort_ord[$sort]}");
      
      $links = $db->CacheGetAll("SELECT * FROM `{$tables['link']['name']}` WHERE (`STATUS` = '2' OR {$permission_links_arts}) {$email_conf} {$feat_where} {$expire_where} {$user_where} ORDER BY `{$sort_cols[$sort]}` {$sort_ord[$sort]}");
      
      $articles = $db->CacheGetAll("SELECT * FROM `{$tables['article']['name']}` WHERE (`RELEASE_DATE`<= now() OR {$permission_links_arts}) AND (`STATUS` = '2' OR {$permission_links_arts}) {$email_conf} {$user_where}");


      $tpl->assign('have_search_results', 1);
      $tpl->assign('uid', $uid);

      $path[] = array ('ID' => '0', 'TITLE' => _L('Personal links'), 'TITLE_URL' => '', 'DESCRIPTION' => _L('Search results for personal links'));
}
elseif (!empty ($_REQUEST['search'])) // Search results
{
   require_once 'search.php';

   $search_preferences = array ();
   $search_preferences['Select_Options']  = array ( '`ID`'                      ,
                                                    '`TITLE`'                   ,
                                                    '`CACHE_TITLE`'             ,
                                                    '`CACHE_URL`'
                                                    );
   $search_preferences['Where_Options']   = array ( "`(`STATUS` = '2' OR {$permission_cats} OR {$permission_cats_parents})"            ,
                                                    "`CACHE_TITLE` IS NOT NULL" ,
                                                    "`CACHE_URL` IS NOT NULL"
                                                    );
   $search_preferences['Order_Options']   = array ( "`ID` ASC"                  ,
                                                    "`PARENT_ID` ASC"           ,
                                                    "`TITLE` ASC"               ,
                                                    "`CACHE_TITLE` ASC"
                                                    );
   $search_preferences['Search_Location'] = array ( 'TITLE' );
   $search_preferences['From_Table']      = $tables['category']['name'];
   $search_preferences['BooleanSearchActive'] = 0;

   $CategorySearchResults = search($search_preferences);

   $tpl->assign('search'      , $CategorySearchResults['search']);
   $tpl->assign('search_terms', $CategorySearchResults['search']);

   if (empty ($CategorySearchResults['errors']['empty_search']))
   {

      $num_categs_per_page = 5;
      $categs_page_limit   = 3;

      $CountCategResults = $db->GetOne($CategorySearchResults['SQL_Count_All']);
      $CountCategResults = (empty ($CountCategResults) || $CountCategResults < 0 ? 0 : intval ($CountCategResults));

      if (!empty ($CountCategResults))
      {
         $start_query = (!empty($_REQUEST['cat_page']) && preg_match('`^[\d]+$`', $_REQUEST['cat_page']) ? intval ($_REQUEST['cat_page']) : 1);

         $ListCategs = $db->GetAll($CategorySearchResults['SQL_Query']." LIMIT ".($start_query <= 1 ? '0' : $start_query).", {$num_categs_per_page}");

         // Start category paging
         SmartyPaginate :: connect('CategoryPaging'); // Connect Paging
         if ($CountCategResults < 2)
         {
            SmartyPaginate :: disconnect('CategoryPaging');
            SmartyPaginate :: reset     ('CategoryPaging');
         }

         SmartyPaginate :: setPrevText    ('['._L('...less') .']' , 'CategoryPaging');
         SmartyPaginate :: setNextText    ('['._L('more...').']'  , 'CategoryPaging');
         SmartyPaginate :: setFirstText   ('['._L('First').']'    , 'CategoryPaging');
         SmartyPaginate :: setLastText    ('['._L('Last').']'     , 'CategoryPaging');
         SmartyPaginate :: setTotal       ($CountCategResults     , 'CategoryPaging');
         SmartyPaginate :: setUrlVar      ('cat_page'             , 'CategoryPaging');
         SmartyPaginate :: setUrl         ($_SERVER['REQUEST_URI'], 'CategoryPaging');
         SmartyPaginate :: setCurrentItem ($start_query           , 'CategoryPaging');
         SmartyPaginate :: setLimit       ($num_categs_per_page   , 'CategoryPaging');
         SmartyPaginate :: setPageLimit   ($categs_page_limit     , 'CategoryPaging');
         SmartyPaginate :: assign         ($tpl                   , 'CategoryPaging', 'CategoryPaging');

            $tpl->assign('list_cat', $ListCategs);
            if (!empty ($ListCategs))
            {
               $search_cat = $tpl->fetch('category_search.tpl');
               $tpl->assign('search_category', $search_cat);
            }
      }
   } // End category search
   unset ($CategorySearchResults, $search_preferences, $ListCategs, $categs_page_limit, $num_categs_per_page, $start_query, $search_cat);

   
   //News search

   $search_preferences = array ();
   $search_preferences['Select_Options']  = array ( '`ID`'                      ,
                                                    '`TITLE`'                   ,
                                                    '`DESCRIPTION`'             ,
                                                    '`URL`'		                ,
                                                    '`CATEGORY_ID`'
                                                    );
   $search_preferences['Where_Options']   = array ( '' );
   $search_preferences['Order_Options']   = array ( "`ID` ASC"                  ,
                                                    "`TITLE` ASC"               ,
                                                    );
   $search_preferences['Search_Location'] = array ( 'TITLE' , 'DESCRIPTION', 'URL' );
   $search_preferences['From_Table']      = $tables['news']['name'];
   $search_preferences['BooleanSearchActive'] = 0;
   
   $newsSearchResults = search($search_preferences);
   $tpl->assign('search'      , $newsSearchResults['search']);
   $tpl->assign('search_terms', $newsSearchResults['search']);
   if (empty ($newsSearchResults['errors']['empty_search']))
   {
      $num_news_per_page = 10;
      $news_page_limit   = 3;

      $CountNewsResults = $db->GetOne($newsSearchResults['SQL_Count_All']);
      $CountNewsResults = (empty ($CountNewsResults) || $CountNewsResults < 0 ? 0 : intval ($CountNewsResults));

      if (!empty ($CountNewsResults))
      {
         $start_query = (!empty($_REQUEST['article_page']) && preg_match('`^[\d]+$`', $_REQUEST['article_page']) ? intval ($_REQUEST['article_page']) : 1);

         $ListNews = $db->GetAll($newsSearchResults['SQL_Query']." LIMIT ".($start_query <= 1 ? '0' : $start_query).", {$num_news_per_page}");
         // Start article paging
         SmartyPaginate :: connect('NewsPaging'); // Connect Paging
         if ($CountNewsResults < 2)
         {
            SmartyPaginate :: disconnect('NewsPaging');
            SmartyPaginate :: reset     ('NewsPaging');
         }

         SmartyPaginate :: setPrevText    ('['._L('...less') .']' , 'NewsPaging');
         SmartyPaginate :: setNextText    ('['._L('more...').']'  , 'NewsPaging');
         SmartyPaginate :: setFirstText   ('['._L('First').']'    , 'NewsPaging');
         SmartyPaginate :: setLastText    ('['._L('Last').']'     , 'NewsPaging');
         SmartyPaginate :: setTotal       ($CountNewsResults   , 'NewsPaging');
         SmartyPaginate :: setUrlVar      ('article_page'         , 'NewsPaging');
         SmartyPaginate :: setUrl         ($_SERVER['REQUEST_URI'], 'NewsPaging');
         SmartyPaginate :: setCurrentItem ($start_query           , 'NewsPaging');
         SmartyPaginate :: setLimit       ($num_news_per_page , 'NewsPaging');
         SmartyPaginate :: setPageLimit   ($news_page_limit   , 'NewsPaging');
         SmartyPaginate :: assign         ($tpl                   , 'NewsPaging', 'NewsPaging');

            $tpl->assign('list_news', $ListNews);
            if (!empty ($ListNews))
            {
               $search_news = $tpl->fetch('news_search.tpl');
               $tpl->assign('search_news', $search_news);
            }
      }
      unset ($NewsResults, $search_preferences);
   }
   
   

   //Article search
   $search_preferences = array ();
   $search_preferences['Select_Options']  = array ( '`ID`'                      ,
                                                    '`TITLE`'                   ,
                                                    '`DESCRIPTION`'             ,
                                                    '`ARTICLE`'                 ,
                                                    '`CATEGORY_ID`'
                                                    );
   if (EMAIL_CONFIRMATION == 1) {
   $search_preferences['Where_Options']   = array ( "(`RELEASE_DATE`<= now() OR {$permission_links_arts}) AND (`STATUS` = '2' OR {$permission_links_arts})" );
   } else {
   $search_preferences['Where_Options']   = array ( "(`RELEASE_DATE`<= now() OR {$permission_links_arts}) AND (`STATUS` = '2' OR {$permission_links_arts})",
                                                    "`OWNER_EMAIL_CONFIRMED` = '1'" );
   }
   $search_preferences['Order_Options']   = array ( "`ID` ASC"                  ,
                                                    "`TITLE` ASC"               ,
                                                    );
   $search_preferences['Search_Location'] = array ( 'TITLE' , 'DESCRIPTION', 'ARTICLE' );
   $search_preferences['From_Table']      = $tables['article']['name'];
   $search_preferences['BooleanSearchActive'] = 0;

   $ArticleSearchResults = search($search_preferences);

   $tpl->assign('search'      , $ArticleSearchResults['search']);
   $tpl->assign('search_terms', $ArticleSearchResults['search']);

   if (empty ($ArticleSearchResults['errors']['empty_search']))
   {
      $num_articles_per_page = 10;
      $articles_page_limit   = 3;

      $CountArticleResults = $db->GetOne($ArticleSearchResults['SQL_Count_All']);
      $CountArticleResults = (empty ($CountArticleResults) || $CountArticleResults < 0 ? 0 : intval ($CountArticleResults));

      if (!empty ($CountArticleResults))
      {
         $start_query = (!empty($_REQUEST['article_page']) && preg_match('`^[\d]+$`', $_REQUEST['article_page']) ? intval ($_REQUEST['article_page']) : 1);

         $ListArticles = $db->GetAll($ArticleSearchResults['SQL_Query']." LIMIT ".($start_query <= 1 ? '0' : $start_query).", {$num_articles_per_page}");

         // Start article paging
         SmartyPaginate :: connect('ArticlePaging'); // Connect Paging
         if ($CountArticleResults < 2)
         {
            SmartyPaginate :: disconnect('ArticlePaging');
            SmartyPaginate :: reset     ('ArticlePaging');
         }

         SmartyPaginate :: setPrevText    ('['._L('...less') .']' , 'ArticlePaging');
         SmartyPaginate :: setNextText    ('['._L('more...').']'  , 'ArticlePaging');
         SmartyPaginate :: setFirstText   ('['._L('First').']'    , 'ArticlePaging');
         SmartyPaginate :: setLastText    ('['._L('Last').']'     , 'ArticlePaging');
         SmartyPaginate :: setTotal       ($CountArticleResults   , 'ArticlePaging');
         SmartyPaginate :: setUrlVar      ('article_page'         , 'ArticlePaging');
         SmartyPaginate :: setUrl         ($_SERVER['REQUEST_URI'], 'ArticlePaging');
         SmartyPaginate :: setCurrentItem ($start_query           , 'ArticlePaging');
         SmartyPaginate :: setLimit       ($num_articles_per_page , 'ArticlePaging');
         SmartyPaginate :: setPageLimit   ($articles_page_limit   , 'ArticlePaging');
         SmartyPaginate :: assign         ($tpl                   , 'ArticlePaging', 'ArticlePaging');

         
            if (!empty($ListArticles)) {
                for ($i =0; $i< count($ListArticles); $i++) {
                   $ListArticles[$i]['rights'] =  user_needs_approval($_SESSION['phpld']['user']['id'], $ListArticles[$i]['CATEGORY_ID']);
                   $ListArticles[$i]['has_payment'] = article_has_payment($ListArticles[$i]['ID']);
                }
            }
            foreach($ListArticles as $k => $v)
   $ListArticles[$k]['SEO_URL'] = seo_url($v['ID'], $v['TITLE'], REWRITE_TYPE, REWRITE_EXT, 2);              

            $tpl->assign('list_articles', $ListArticles);
            
            if (!empty ($ListArticles))
            {
               $search_article = $tpl->fetch('article_search.tpl');
               $tpl->assign('search_article', $search_article);
            }
      }
   } // End article search
   unset ($ArticleSearchResults, $search_preferences, $ListArticles, $article_page_limit, $num_articles_per_page, $start_query, $search_article);

   if (FTR_ENABLE) {
      $search_preferences = array ();
      $search_preferences['Select_Options']  = array ( '*' );
       if (EMAIL_CONFIRMATION == 1) {
       $search_preferences['Where_Options']   = array ( "(`STATUS` = '2' OR {$permission_links_arts})"   ,
                                                       "`FEATURED` = '1'" ,
                                                       "(`EXPIRY_DATE` >= ".$db->DBDate(time())." OR `EXPIRY_DATE` IS NULL)"
                                                       );
       } else {
       $search_preferences['Where_Options']   = array ( "(`STATUS` = '2' OR {$permission_links_arts})"   ,
                                                       "`FEATURED` = '1'" ,
                                                       "(`EXPIRY_DATE` >= ".$db->DBDate(time())." OR `EXPIRY_DATE` IS NULL)",
                                                       "`OWNER_EMAIL_CONFIRMED` = '1'"
                                                       );
       }
      
     
      $search_preferences['Order_Options']   = array ( "`EXPIRY_DATE` DESC"
                                                       );
      $search_preferences['Search_Location'] = array ( 'URL'               ,
                                                       'TITLE'             ,
                                                       'DESCRIPTION',
													   'META_DESCRIPTION',
													   'META_KEYWORDS',
													   'ADDRESS',
													   'CITY',
												       'STATE',
													   'ZIP'
													);
      $search_preferences['From_Table']      = $tables['link']['name'];
      //$search_preferences['BooleanSearchActive'] = 1; // Default to regular search

      $FeatLinksResults = search($search_preferences);

      if (empty ($FeatLinksResults['errors']['empty_search']))
      {
         $feat_links = $db->GetAll($FeatLinksResults['SQL_Query']);
         $CountFeatLinksResults = $db->Affected_Rows();
         if (empty ($CountFeatLinksResults))
            unset ($feat_links);
      }
   } // End featured links search
   unset ($search_preferences, $FeatLinksResults);

   $search_preferences = array();
   $search_preferences['Select_Options']  = array ( '*' );
   
   if (EMAIL_CONFIRMATION == 1) {
       $search_preferences['Where_Options']   = array ( "(`STATUS` = '2' OR {$permission_links_arts})"   ,
                                                       "`FEATURED` = '0'" ,
                                                       "(`EXPIRY_DATE` >= ".$db->DBDate(time())." OR `EXPIRY_DATE` IS NULL)"
                                                       );
       } else {
       $search_preferences['Where_Options']   = array ( "(`STATUS` = '2' OR {$permission_links_arts})"   ,
                                                       "`FEATURED` = '0'" ,
                                                       "(`EXPIRY_DATE` >= ".$db->DBDate(time())." OR `EXPIRY_DATE` IS NULL)",
                                                       "`OWNER_EMAIL_CONFIRMED` = '1'"
                                                       );
       }

   $search_preferences['Order_Options']   = array ( '`'.$sort_cols[$sort].'` '.$sort_ord[$sort]
                                                       );

   $search_preferences['Search_Location'] = array ( 'URL'               ,
                                                    'TITLE'             ,
                                                    'DESCRIPTION'      ,
													'META_DESCRIPTION',
													'META_KEYWORDS',
													'ADDRESS',
													'CITY',
												    'STATE',
													'ZIP'
													);
                                                     

   $search_preferences['From_Table']      = $tables['link']['name'];
   //$search_preferences['BooleanSearchActive'] = 0;

   $LinksResults = search($search_preferences);

   $count = $db->GetOne($LinksResults['SQL_Count_All']);

   if (!empty ($count))
      $links = $db->GetAll($LinksResults['SQL_Query'].$limit);

   if (!empty ($count) || !empty ($CountFeatLinksResults) || !empty ($CountCategResults) || !empty($CountArticleResults) || !empty($CountNewsResults))
      $tpl->assign('have_search_results', 1);
   else
      $tpl->assign('have_search_results', 0);

   unset ($LinksResults, $search_preferences, $CountFeatLinksResults, $CountCategResults);

   $categs = array ();
   $path[] = array ('ID' => '0', 'TITLE' => _L('Search Results'), 'TITLE_URL' => '', 'DESCRIPTION' => _L('Search results for: ').$_REQUEST['search']);
}
else // Regular listing, categories and links
{
   $id = get_category();

   if ($id > 0)
      $meta_tags = $db->GetRow("SELECT `META_KEYWORDS`, `META_DESCRIPTION` FROM `{$tables['category']['name']}` WHERE `ID` = ".$db->qstr($id));

   if (!$tpl->is_cached('main.tpl', $id))
   {
      $path = get_path($id);
      
      if (FTR_ENABLE == 1)
      {
         $feat_links = $db->CacheGetAll("SELECT * FROM `{$tables['link']['name']}` WHERE (`STATUS` = '2' OR {$permission_links_arts}) {$bydate} {$email_conf} AND `CATEGORY_ID` = ".$db->qstr($id)." AND `FEATURED` = 1 {$expire_where} ORDER BY `EXPIRY_DATE` DESC");
        
       }

      $link_count    = $db->CacheGetOne("SELECT COUNT(*) FROM `{$tables['link']['name']}` WHERE (`STATUS` = '2' OR {$permission_links_arts}) {$bydate} {$email_conf} AND `CATEGORY_ID` = ".$db->qstr($id)." {$feat_where} {$expire_where}");
      $article_count = $db->CacheGetOne("SELECT COUNT(*) FROM `{$tables['article']['name']}` WHERE (`RELEASE_DATE`<= now() OR {$permission_links_arts}) AND (`STATUS` = '2' OR {$permission_links_arts}) {$email_conf} AND `CATEGORY_ID` = ".$db->qstr($id));
	  $feed_count    = $db->CacheGetOne("SELECT COUNT(*) FROM `{$tables['news']['name']}` WHERE CATEGORY_ID=".$db->qstr($id));
	  $count = max($link_count, $article_count, $feed_count);
      
      $links = $db->CacheGetAll("SELECT * FROM `{$tables['link']['name']}` WHERE (`STATUS` = '2' OR {$permission_links_arts}) {$bydate} {$email_conf} AND `CATEGORY_ID` = ".$db->qstr($id)." {$feat_where} {$expire_where} ORDER BY `{$sort_cols[$sort]}` {$sort_ord[$sort]} {$limit}");
 
      $feeds = $db->CacheGetAll("SELECT * FROM `{$tables['news']['name']}` WHERE CATEGORY_ID=".$db->qstr($id). " ORDER BY `DATE_ADDED` DESC ".$limit);


      
      $feat_articles = $db->CacheGetAll("SELECT * FROM `{$tables['article']['name']}` WHERE (`RELEASE_DATE`<= now() OR {$permission_links_arts}) AND `STATUS` = '2' {$bydate} AND `CATEGORY_ID` = ".$db->qstr($id)." AND `FEATURED` = 1 AND (`EXPIRY_DATE` >= ".$db->DBDate(time())." OR `EXPIRY_DATE` IS NULL) ORDER BY `DATE_ADDED` DESC");

      $articles = $db->CacheGetAll("SELECT * FROM `{$tables['article']['name']}` WHERE (`RELEASE_DATE`<= now() AND `STATUS` = '2' OR {$permission_links_arts}) AND `CATEGORY_ID` = ".$db->qstr($id)." AND ((`FEATURED` = 0) OR (`FEATURED` = 1 AND `EXPIRY_DATE`<" .$db->DBDate(time()) .")) ORDER BY `DATE_ADDED` DESC {$limit}");

      $rs = $db->CacheExecute("SELECT * FROM `{$tables['category']['name']}` WHERE (`STATUS` = '2' OR {$permission_cats} OR {$permission_cats_parents}) AND `PARENT_ID` = ".$db->qstr($id)." ORDER BY `$CATEG_FIELD_SORT` $CATEG_FIELD_SORT_ORDER");

      while (!$rs->EOF)
      {
         $row = $rs->FetchRow();
         if ($id == 0 && CATS_PREVIEW > 0)
         {
            $rs2 = $db->CacheSelectLimit("SELECT * FROM `{$tables['category']['name']}` WHERE (`STATUS` = '2' OR {$permission_cats} OR {$permission_cats_parents}) AND `SYMBOLIC` <> '1' AND `PARENT_ID` = ".$db->qstr($row['ID'])." ORDER BY `$SUBCATEG_FIELD_SORT` $SUBCATEG_FIELD_SORT_ORDER, `TITLE` ", CATS_PREVIEW);
            $row['SUBCATS'] = $rs2->GetRows();
            $rs2->Close();
         }
         if (ENABLE_REWRITE == 1 && empty ($row['TITLE_URL']))
         {
            $row['TITLE_URL'] = preg_replace ('`[^\w_-]`', '_', $row['TITLE']);
            $row['TITLE_URL'] = str_replace ('__', '_', $row['TITLE_URL']);
         }

         if ($row['SYMBOLIC'] == 1)
         {
            $row['ID'] = $row['SYMBOLIC_ID'];
            $tempcat = $db->CacheGetRow("SELECT * FROM `{$tables['category']['name']}` WHERE `ID` = ".$db->qstr($row['SYMBOLIC_ID']));
            if (empty ($row['TITLE']))
               $row['TITLE'] = $tempcat['TITLE'];

            $row['TITLE'] = '@' . $row['TITLE'];

            if (ENABLE_REWRITE == 1)
               $row['TITLE_URL'] = construct_mod_rewrite_path($row['SYMBOLIC_ID']);

            $row['COUNT'] = $db->CacheGetOne("SELECT COUNT(*) FROM `{$tables['category']['name']}` WHERE (`STATUS` = '2' OR {$permission_cats} OR {$permission_cats_parents}) AND `PARENT_ID` = ".$db->qstr($row['SYMBOLIC_ID']));
            $row['COUNT'] += $db->CacheGetOne("SELECT COUNT(*) FROM `{$tables['link']['name']}` WHERE (`STATUS` = '2' OR {$permission_cats} OR {$permission_cats_parents}) {$email_conf} AND `CATEGORY_ID` = ".$db->qstr($row['SYMBOLIC_ID']));
         }
         else
         {
            $row['COUNT'] = $db->CacheGetOne("SELECT COUNT(*) FROM `{$tables['category']['name']}` WHERE (`STATUS` = '2' OR {$permission_cats} OR {$permission_cats_parents}) AND `PARENT_ID` = ".$db->qstr($row['ID']));
            $row['COUNT'] += $db->CacheGetOne("SELECT COUNT(*) FROM `{$tables['link']['name']}` WHERE (`STATUS` = '2' OR {$permission_links_arts} OR {$permission_cats_parents}) {$email_conf} AND `CATEGORY_ID` = ".$db->qstr($row['ID']));
         }
         
         $categs[] = $row;
      }
      $rs->Close();
   }
   if ($id > 0)
   {
      $HitInfo = $db->GetRow("SELECT * FROM `{$tables['hitcount']['name']}` WHERE `CATEGORY_ID` = ".$db->qstr($id)." AND `IP` = ".$db->qstr($client_info['IP']));

      if (!empty ($HitInfo))
      {
         $current_time = date ('Y-m-d H:i:s');
         $SecondsDiff  = dateTimeDifference($current_time, $HitInfo['LAST_HIT']);
         $Diff         = second2hour($SecondsDiff);

         if ($Diff > LIMIT_HITS_TIME)
         {
            $db->Execute("UPDATE `{$tables['category']['name']}` SET `HITS` = `HITS` + 1 WHERE `ID` = ".$db->qstr($id));
            $where = '`ID` = '.$db->qstr($HitInfo['ID']);
            $HitInfo['LAST_HIT'] = $current_time;
            $db->AutoExecute($tables['hitcount']['name'], $HitInfo, 'UPDATE', $where);
         }
      }
      else
      {
         $db->Execute("UPDATE `{$tables['category']['name']}` SET `HITS` = `HITS` + 1 WHERE `ID` = ".$db->qstr($id));
         $HitInfo['CATEGORY_ID'] = $id;
         $HitInfo['IP']         = $client_info['IP'];
         $db->AutoExecute($tables['hitcount']['name'], $HitInfo, 'INSERT', false);
      }

      unset ($HitInfo, $current_time, $Diff, $SecondsDiff);
   }

   /*$tpl->assign('title_prefix', $path[count($path) - 1]['TITLE']." - ");*/

   if ($page > 1)
      $path[] = array ('ID' => $id, 'TITLE' => _L('Page ') . $page, 'TITLE_URL' => '', 'DESCRIPTION' => '');
}

//Add cached category URL and title for featured links
if (FTR_ENABLE == 1 && isset ($feat_links))
{
   $feat_links = addCategPathToLinks($feat_links);
   $tpl->assign('feat_links', $feat_links);
}
//Add cached category URL and title for regular links
if (isset ($links))
{
   $links = addCategPathToLinks($links);
}

$count          = (empty ($count) || $count < 0 ? 0 : intval ($count));
$PagerGroupings = (PAGER_GROUPINGS && PAGER_GROUPINGS > 0 ? intval (PAGER_GROUPINGS) : 20);
$LinksPerPage   = (PAGER_LPP       && PAGER_LPP       > 0 ? intval (PAGER_LPP)       : 10);


//raluca	
if ((!empty($current_item) || $current_item == 0) && !empty($count) && ENABLE_REWRITE == 1)
{
	$lastPage = ceil ($current_item / $LinksPerPage) +1;
	$tpl->assign('lp', $lastPage);	
}
//raluca

if (!empty($current_item) && !empty($count) && ($current_item + 1 > $count))
{
   //Send HTTP header status "404/Not Found"
   httpstatus('404');

   //Build new URL (it will calculate the last valid page)
   $redirectURL  = trim ($_SERVER['REQUEST_URI']);

   //Regular redirect
   if (ENABLE_REWRITE == 1 && empty ($_REQUEST['search']))
   {
      //calculate last page possible
      $lastPage = ceil ($count / $LinksPerPage);

      if ($lastPage > 1)
      {
         //append "page-XYZ.html" except "page-1.html"
         $redirectURL .= (substr ($_SERVER['REQUEST_URI'], -1) == '/') ? '' : '/';
         $redirectURL .= ($lastPage > 1 ? 'page-' . $lastPage . '.html' : '');
      }

   }
   else
   {
      //calculate last page possible except for first page
      $lastPage = ($count % $LinksPerPage > 0) ? $count - ($count % $LinksPerPage) + 1 : $count - $LinksPerPage + 1;

      if ($lastPage > $LinksPerPage)
      {
         //append "&p=XYZ" or "?p=XYZ"
         $redirectURL .= (strpos ($_SERVER['REQUEST_URI'], '?') === false) ? '?' : '&';
         $redirectURL .= ($lastPage > $LinksPerPage ? 'p=' . intval ($lastPage) : '');
      }
   }
   //Redirect to last page
 http_custom_redirect($redirectURL,'',0,'',301);
}

if (empty ($_REQUEST['list'])) //Build paging options
{
   SmartyPaginate :: connect('MainPaging'); //Connect Paging

   // Build Paging
   if ($page < 2)
   {
      SmartyPaginate :: disconnect('MainPaging');
      SmartyPaginate :: reset     ('MainPaging');
   }
   SmartyPaginate :: setPrevText    ('Previous'              , 'MainPaging');
   SmartyPaginate :: setNextText    ('Next'                  , 'MainPaging');
   SmartyPaginate :: setFirstText   ('First'                 , 'MainPaging');
   SmartyPaginate :: setLastText    ('Last'                  , 'MainPaging');
   SmartyPaginate :: setTotal       ($count                  , 'MainPaging');
   SmartyPaginate :: setUrlVar      ('p'                     , 'MainPaging');
   SmartyPaginate :: setUrl         ($_SERVER['REQUEST_URI'] , 'MainPaging');
   SmartyPaginate :: setCurrentItem ($current_item + 1       , 'MainPaging');
   SmartyPaginate :: setLimit       ($LinksPerPage           , 'MainPaging');
   SmartyPaginate :: setPageLimit   ($PagerGroupings         , 'MainPaging');
   SmartyPaginate :: assign         ($tpl                    , 'MainPaging', 'MainPaging');
}

// Assign template variables
if ($current_item > 0 && ENABLE_REWRITE == 1) {
	$category = $path[count ($path) - 2];
} else {
	$category = $path[count ($path) - 1];
}
$category['rights'] =  user_needs_approval($_SESSION['phpld']['user']['id'], $category['ID']);

$tpl->assign('rights'       , $category['rights']);


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





// Assign template variables

// Article Rewrite
foreach($articles as $k => $v) {
   $articles[$k]['SEO_URL'] = seo_url($v['ID'], $v['TITLE'], REWRITE_TYPE, REWRITE_EXT, 1);
}
foreach($feat_articles as $k => $v) {
   $feat_articles[$k]['SEO_URL'] = seo_url($v['ID'], $v['TITLE'], REWRITE_TYPE, REWRITE_EXT, 1);
}


// Links Rewrite
foreach($links as $k => $v) {
   $links[$k]['SEO_URL'] = seo_url($v['ID'], $v['TITLE'], REWRITE_TYPE, REWRITE_EXT, 2);
}

// Featured Links Rewrite
foreach($feat_links as $k => $v) {
   $feat_links[$k]['SEO_URL'] = seo_url($v['ID'], $v['TITLE'], REWRITE_TYPE, REWRITE_EXT, 2);
}
   
$tpl->assign('path'           , $path);
$tpl->assign('count'          , $count);

//user rights on links && featured links

if (!empty($links)) {
    for ($i =0; $i< count($links); $i++) {
       $links[$i]['rights'] =  user_needs_approval($_SESSION['phpld']['user']['id'], $links[$i]['CATEGORY_ID']);
       $links[$i]['has_payment'] = link_has_payment($links[$i]['ID']);
    }
}

if (!empty($feat_links)) {
    for ($i =0; $i< count($feat_links); $i++) {
       $feat_links[$i]['rights'] =  user_needs_approval($_SESSION['phpld']['user']['id'], $feat_links[$i]['CATEGORY_ID']);
       $feat_links[$i]['has_payment'] = link_has_payment($feat_links[$i]['ID']);
    }
}

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

//user rights on articles

if (!empty($articles)) {
    for ($i =0; $i< count($articles); $i++) {
       $articles[$i]['rights'] =  user_needs_approval($_SESSION['phpld']['user']['id'], $articles[$i]['CATEGORY_ID']);
       $articles[$i]['has_payment'] = article_has_payment($articles[$i]['ID']);
    }
}
	if (!empty($feat_articles)) {
    for ($i =0; $i< count($feat_articles); $i++) {
       $feat_articles[$i]['rights'] =  user_needs_approval($_SESSION['phpld']['user']['id'], $feat_articles[$i]['CATEGORY_ID']);
       $feat_articles[$i]['has_payment'] = article_has_payment($feat_articles[$i]['ID']);
    }

}

$tpl->assign('links'          , $links);
$tpl->assign('feat_articles', $feat_articles);
$tpl->assign('articles'       , $articles);

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

//
$tpl->assign('categs'         , $categs);
$tpl->assign('p'              , $current_item + 1);
$tpl->assign('StopLinkHits'   , $StopLinkHits);
//Darius Tumas assign
//we send here to template system variable with user level.
$tpl->assign('uLevel'		  , $ito_user_permission);
$tpl->assign('MetaKeywords'   , (!empty ($meta_tags['META_KEYWORDS'])    ? trim ($meta_tags['META_KEYWORDS'])    : trim ($MetaKeywords)));
$tpl->assign('MetaDescription', (!empty ($meta_tags['META_DESCRIPTION']) ? trim ($meta_tags['META_DESCRIPTION']) : trim ($MetaDescription)));


//Rewrite Paging links
if (ENABLE_REWRITE == 1)
   $tpl->load_filter('output', 'RewritePageLinks');

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

//Compress output for faster loading
if (COMPRESS_OUTPUT == 1)
   $tpl->load_filter('output', 'CompressOutput');


//Make output

echo $tpl->fetch('main.tpl', $id);



?>