<?php 
/*#################################################################*\
|# Licence Number 0H6R-0808-0UVQ-0111
|# -------------------------------------------------------------   #|
|# Copyright (c)2012 PHP Link Directory.                           #|
|# http://www.phplinkdirectory.com                                 #|
\*#################################################################*/
	 
	
/**
 # ################################################################################
 # Project:   PHP Link Directory
 #
 # **********************************************************************
 # Copyright (C) 2004-2012 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 if you purchased any of our "link back" 
 #      versions of the software.
 #
 #
 # 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-2012 NetCreated, Inc. (http://www.netcreated.com/)
 # @projectManager David DuVal <david@david-duval.com>
 # @package        PHPLinkDirectory
 # @version        4.2.1
 # ################################################################################
 */
 
require_once 'init.php';

$error   = 0;
$expired = 0;

//Determine columns
$columns = array ('ID', 'TITLE' , 'DESCRIPTION', 'CATEGORY' , 'STATUS' , 'DATE_ADDED', 'OWNER_EMAIL_CONFIRMED', 'ACTION');

$stats = array (0 => _L('Inactive'), 1 => _L('Pending'), 2 => _L('Active'));
$yes_no = array (1 => _L('Yes'), 0 => _L('No'));

$where = '';

//Determine category ID
//Keep backwards compatibility with urlvariable "c"
$category = (isset ($_REQUEST['category']) ? $_REQUEST['category'] : (isset ($_REQUEST['c']) ? $_REQUEST['c'] : ''));

//Build where clause for category ID
if (!empty ($category))
{
   $category = urldecode ($category);

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

   $categsArray = explode (',', $category);
   $categsArray = array_unique ($categsArray);

   if (!empty ($categsArray))
   {
      $where .= " AND {$tables['article']['name']}.CATEGORY_ID IN ('".implode ("', '", $categsArray)."')";

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

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

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

if ( isset( $_GET['iSortCol_0'] ) ) {
	$sOrder = "ORDER BY  ";
	for ( $i=0 ; $i<mysql_real_escape_string( $_GET['iSortingCols'] ) ; $i++ ) {
		$sOrder .= $columns[mysql_real_escape_string( $_GET['iSortCol_'.$i] )]." ".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
	}
	$sOrder = substr_replace( $sOrder, "", -2 );
}

if ( $_GET['sSearch'] != "" ) {
	$search_text = mysql_real_escape_string( $_GET['sSearch'] );
	$where .= "AND ( {$tables['article']['name']}.ARTICLE LIKE '%{$search_text}%' OR ".
		                	"{$tables['article']['name']}.TITLE LIKE '%{$search_text}%' OR ".
		               	"{$tables['article']['name']}.DESCRIPTION LIKE '%{$search_text}%' OR ".
		               	"{$tables['article']['name']}.ID LIKE '%{$search_text}%') ";
}

$display_length = mysql_real_escape_string($_GET['iDisplayLength']);
$display_start = mysql_real_escape_string($_GET['iDisplayStart']);

$links_per_page = ($display_length > 0) ? $display_length : $links_per_page;
$current_item = ($display_start > 0) ? $display_start : '0';

$list_total = $db->GetOne("SELECT COUNT(*) FROM `{$tables['article']['name']}` WHERE 1 ".(!empty ($LinksResults['Search_Query']) ? " AND ".$LinksResults['Search_Query'] : '')." {$where}");
$tpl->assign('list_total', $list_total);
$sql = "SELECT SQL_CALC_FOUND_ROWS {$tables['article']['name']}.*, ".$db->IfNull("{$tables['category']['name']}.TITLE", "'Top'")." AS `CATEGORY` ".(!empty ($LinksResults['Select_Relevancy']) ? ", ".$LinksResults['Select_Relevancy'] : '')." FROM `{$tables['article']['name']}` LEFT JOIN `{$tables['category']['name']}` ON ({$tables['article']['name']}.CATEGORY_ID = {$tables['category']['name']}.ID) WHERE 1 ".(!empty ($LinksResults['Search_Query']) ? " AND ".$LinksResults['Search_Query'] : '').(!empty ($LinksResults['Relevancy_Tuning']) ? $LinksResults['Relevancy_Tuning'] : '')." {$where}  {$sOrder}";

$rs = $db->SelectLimit($sql, $links_per_page, $current_item);

$filtered_total = $db->GetOne("SELECT FOUND_ROWS()");

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

$json = link_json($list, $columns, $list_total, $filtered_total);

echo $json;

function link_json($links, $columns, $total_count, $display_count) {
	global $db, $tables, $yes_no, $link_types, $stats;
	$data = '';
	foreach ($links as $link_id => $link) {
		// First element should be a link ID that we will set as tr id
		$data .= '["'.$link_id.'",';
		foreach ($columns as $col_id => $col_name) {
			$val = $link[$col_name];
			switch ($col_name) {
				case 'STATUS':
					$val = $stats[$val];
					break;
				case 'DATE_ADDED':
					$val = strftime("%m/%d/%y");
					break;
				case 'OWNER_EMAIL_CONFIRMED':
					$val = $yes_no[$val];
					break;
				case 'ACTION':
					//$val = "<a href=\\\"".DOC_ROOT."/dir_links_edit.php?action=E:{$link_id}\\\" title=\\\"Edit Link: {$link['TITLE']}\\\" class=\\\"edit_dt\\\"><span>Edit</span></a><a href=\\\"".DOC_ROOT."/dir_links_edit.php?action=D:{$link_id}\\\" title=\\\"Remove Link: {$link['TITLE']}\\\" class=\\\"delete_dt\\\" ><span>Delete</span></a>";
					$val = $link['CATEGORY_ID'];				
					break;
			}
			$data .= ($col_name != 'ID') ? '"'.stripStrForDT($val).'",' : '';
		}
		$data = substr($data, 0, -1);
		$data .= '],';
	}
	$data = substr($data, 0, -1);
	$result = '{
    							"sEcho": '.intval($_GET['sEcho']).',
    							"iTotalRecords": '.$total_count.',
    							"iTotalDisplayRecords": '.$display_count.',
    							"aaData": [
    											'.$data.'
    							]
    						}';
    return $result;
}
?>