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


//Determine link ID
if(!empty($action))
{
   $id = $action[1];
}
elseif (ENABLE_REWRITE == 1)
{
      // Know extensions
   $ext = array('.htm', '.html', '.php', '/');

   $id = explode('-', $_REQUEST['id']);
   $el = count($id) - 1;
   $id = intval(str_replace($ext, '', $id[$el]));
   /*preg_match ('#(.*)link(_|-)(\d+)\.htm[l]?$#i', request_uri(), $matches);

   $id = (!empty ($matches[3]) ? intval ($matches[3]) : 0);*/
}
else
{
   $id = (!empty ($_REQUEST['id']) ? $_REQUEST['id'] : 0);
}

if (isset($_SESSION['comm_posted']) && $_SESSION['comm_posted'] == 1) {
	$tpl->assign('comm_posted', 1);
	unset($_SESSION['comm_posted']);
}

  //Generate unique imagehash for visual confirmation
  if (VISUAL_CONFIRM_LINK_COMMENTS == 1)
  {
      require_once 'include/functions_imgverif.php';
      $imagehash = fetch_captcha_hash();
      $tpl->assign('imagehash', $imagehash);
      unset ($imagehash);
  }
  // Check for comment subscription
  $tpl->assign('subscribe', $db->GetOne("SELECT COUNT(*) FROM `{$tables['link_subscribe']['name']}` WHERE `USER_ID` = '{$_SESSION['phpld']['user']['id']}' AND `LINK_ID` = ".$db->qstr($id)));
  if (isset($_REQUEST['action'])) {
          $action = explode(":", $_REQUEST['action']);
  
      $action = explode(":", $_REQUEST['action']);
      
      //comment related
      
      if ($action[0] == "C") {
          
          if (REQUIRE_REGISTERED_USER_LINK_COMMENT == 1){
              if (empty($_SESSION['phpld']['user']['id'])) {
                  http_custom_redirect(DOC_ROOT.'/login.php');
              }
          }

          $rdata = $db->CacheGetRow("SELECT *, DATE_FORMAT(DATE_ADDED, '%M %d, %Y %r') AS `DAT` FROM `{$tables['link']['name']}` WHERE `ID` = ".$db->qstr($action[1]));
          $data['CATEGORY_ID'] = $rdata['CATEGORY_ID'];
          
          $data['rights'] =  user_needs_approval($_SESSION['phpld']['user']['id'], $data['CATEGORY_ID']);
          // Assign values
          $cdata['LINK_ID']   = $action[1];
          $cdata['USER_ID']    = $_SESSION['phpld']['user']['id'];
          $cdata['USER_NAME'] = $_SESSION['phpld']['user']['name'];
          $cdata['COMMENT']    = $_POST['comment'];
          $cdata['DATE_ADDED'] = date("Y-m-d H:i:s");
          $cdata['IPADDRESS']  = $_SERVER['REMOTE_ADDR'];
          //echo $cdata['LINK_ID'].'<br>';
          $tpl->assign('COMMENT', $cdata['COMMENT']);
          if (empty($_SESSION['phpld']['user']['id'])) {
                $count = '0';
                $cdata['USER_ID']    = '0';
          } else {
              // Count Approved Comments for the user
              $count = $db->GetOne("SELECT COUNT(*) FROM `{$tables['linkcomment']['name']}` WHERE `STATUS` = '2' AND `USER_ID` = ".$db->qstr($cdata[USER_ID]));
          }
          
          if (empty($_SESSION['phpld']['user']['name'])) {
                $cdata['USER_NAME'] = 'Guest';
          }
          if ($count < AUTO_APPROVE_LINK_COMMENTS || AUTO_APPROVE_LINK_COMMENTS_ONOFF == 0) {
                $cdata['STATUS'] = 1;
                $tpl->assign('needs_approval_msg', 1);
     	 } else
                $cdata['STATUS'] = 2;
 
          if ($data['rights']['addLink'] == 1 || $data['rights']['editLink'] == 1 || $data['rights']['delLink'] == 1) {
                $cdata['STATUS'] = 2;
          }
             
          if(!empty($_POST['comment'])) {
          // Image Verification
             if (VISUAL_CONFIRM_LINK_COMMENTS == 1) {
             	
                 if ($data['rights']['addLink'] == 1 || $data['rights']['editLink'] == 1 || $data['rights']['delLink'] == 1) {
                     $imgCheck = 1;
                 } else {
                     $imgCheck = $db->GetOne("SELECT COUNT(*) FROM `{$tables['img_verification']['name']}` WHERE `IMGHASH` = ".$db->qstr($_POST[IMAGEHASH])." AND `IMGPHRASE` = ".$db->qstr($_POST[CAPTCHA]));
                 }
                 if ($imgCheck == 1) {
                         $db->Execute("UPDATE `{$tables['link']['name']}` SET `COMMENT_COUNT` = `COMMENT_COUNT` + 1 WHERE `ID` = ".$db->qstr($cdata['LINK_ID'])) or die(mysql_error());
                         db_replace('linkcomment', $cdata, 'ID');
                         //print_r($db->ErrorMsg());
                         
                         $_SESSION['comm_posted'] = 1;
                         
                         http_custom_redirect($_SERVER['HTTP_REFERER']);
                 } else {
                         $tpl->assign('img_verification_error', true);
                 }
             } else {
                 // Write to DB
                 $db->Execute("UPDATE `{$tables['link']['name']}` SET `COMMENT_COUNT` = `COMMENT_COUNT` + 1 WHERE `ID` = ".$db->qstr($cdata['LINK_ID'])) or die(mysql_error());
                 db_replace('linkcomment', $cdata, 'ID');
                 //print_r($db->ErrorMsg());
                 
                 $_SESSION['comm_posted'] = 1;
                 
                 http_custom_redirect($_SERVER['HTTP_REFERER']);
             }
         } else
             $tpl->assign('commentError', 1);
     }
     //and of comment
     elseif ($action[0] == "R") {
 if (REQUIRE_REGISTERED_USER_LINK_RATING == 1){
         if (empty($_SESSION['phpld']['user']['id'])) {
                         http_custom_redirect(DOC_ROOT.'/login.php');
                 }
 }
 if($_POST[RATING] == '')
                 {
                    $tpl->assign('ratingError', 1);
                 }
                 else{
                 $db->Execute("UPDATE `{$tables['link']['name']}` SET `RATING` = `RATING` + $_POST[RATING], `VOTES` = `VOTES` + 1 WHERE `ID` = ".$db->qstr($action[1])) or die(mysql_error());
                 $rating['LINK_ID']  = $action[1];
                 $rating['IPADDRESS'] = $_SERVER['REMOTE_ADDR'];
 
                 db_replace('linkrating', $rating);
 
                http_custom_redirect($_SERVER['HTTP_REFERER']);
                 }
         }
 }
 if(!empty($action))
 {
    $id = $action[1];
 }
 elseif (ENABLE_REWRITE == 1)
 {
 	/*
    preg_match ('#(.*)link(_|-)(\d+)\.htm[l]?$#i', request_uri(), $matches);
    $id = (!empty ($matches[3]) ? intval ($matches[3]) : 0);*/
   $ext = array('.htm', '.html', '.php', '/');

   $id = explode('-', $_REQUEST['id']);
   $el = count($id) - 1;
   $id = intval(str_replace($ext, '', $id[$el]));
 	
 }
 else
 {
    $id = (!empty ($_REQUEST['id']) ? intval ($_REQUEST['id']) : 0);
 }

/*---------------------------------------------------------------------*/


if (!empty ($id))
{
   if (!preg_match ('`^[\d]+$`', $id))
   {
      $tpl->assign('error', "Invalid Link ID");
   } else {
      $rdata = $db->CacheGetRow("SELECT *, DATE_FORMAT(DATE_ADDED, '%M %d, %Y %r') AS `DAT` FROM `{$tables['link']['name']}` WHERE `ID` = ".$db->qstr($id));
      $data = array ();
      if (!$rdata)
         $tpl->assign('error', "Invalid ID [{$id}] passed - not found in database");
      else
      {
         $data['ID']           = $id;
         $data['TITLE']        = $rdata['TITLE'];
         $data['DESCRIPTION']  = $rdata['DESCRIPTION'];
         $data['URL']          = $rdata['URL'];
		 $data['ADDRESS']      = $rdata['ADDRESS'];
		 $data['CITY']         = $rdata['CITY'];
		 $data['STATE']        = $rdata['STATE'];
		 $data['ZIP']          = $rdata['ZIP'];
		 $data['PHONE_NUMBER'] = $rdata['PHONE_NUMBER'];
		 $data['NOFOLLOW']     = $rdata['NOFOLLOW'];
         $data['RECPR_URL']    = $rdata['RECPR_URL'];
		 $data['RECPR_VALID']  = $rdata['RECPR_VALID'];
         $data['RECPR_REQUIRED'] = $rdata['RECPR_REQUIRED'];
         $data['CATEGORY_ID']  = $rdata['CATEGORY_ID'];
         $data['OWNER_NAME']   = $rdata['OWNER_NAME'];
		 $data['FEATURED']   = $rdata['FEATURED'];
		 $data['LINK_TYPE']   = $rdata['LINK_TYPE'];
         $data['DATE_ADDED']   = $rdata['DAT'];
         $data['HITS']         = $rdata['HITS'];
         $data['PAGERANK']     = $rdata['PAGERANK'];
         $data['RATE_COUNT']   = $rdata['RATE_COUNT'];
         $data['RATE']         = $rdata['RATE'];
         $data['RATE_ENABLED'] = $rdata['RATE_ENABLED'];
         $data['STATUS']        = $rdata['STATUS'];
         
         $data['rights'] =  user_needs_approval($_SESSION['phpld']['user']['id'], $data['CATEGORY_ID']);
         
         $data['has_payment'] = link_has_payment($data['ID']);
         $cdata                = $db->CacheGetRow("SELECT `TITLE` AS `CATEGORY_TITLE`, `CACHE_TITLE`, `CACHE_URL` FROM `{$tables['category']['name']}` WHERE `ID` = '{$rdata['CATEGORY_ID']}' LIMIT 1");

         $data['CATEGORY_TITLE']  = $cdata['CATEGORY_TITLE'];
         $data['CACHE_TITLE']     = $cdata['CACHE_TITLE'];
         $odata = $db->CacheGetRow("SELECT * FROM `{$tables['user']['name']}` WHERE `ACTIVE` = '1' AND `ID` = ".$db->qstr($rdata['OWNER_ID']));
		 if (!empty($odata['NAME'])){
		 if (ALLOW_AUTHOR_INFO == 1) {
						$data['OWNER_NAME']     = "<a href=\"".DOC_ROOT."/";
						if (ENABLE_REWRITE) {
							$data['OWNER_NAME']  .= "owner/owner-".$rdata['OWNER_ID'].".html";
						} else {
							$data['OWNER_NAME']  .= "author.php?id=".$rdata['OWNER_ID'];
						}
						$data['OWNER_NAME']  .= "\" title=\"".htmlspecialchars($odata['NAME'])."\">".htmlspecialchars($odata['NAME'])."</a>";
					} else {
						$data['OWNER_NAME']     = $odata['NAME'];
					}
		 }
         $site_url = (substr (SITE_URL, -1) != '/' ? SITE_URL.'/' : SITE_URL);
         $data['CATEGORY_URL']    = $site_url;
         $data['CATEGORY_URL']   .= (ENABLE_REWRITE == 1 ? trim ($cdata['CACHE_URL']) : 'index.php?c='.$data['CATEGORY_ID']);

         $data['META_KEYWORDS']    = $rdata['META_KEYWORDS'];
         $data['META_DESCRIPTION'] = $rdata['META_DESCRIPTION'];
		 $data['GMAPKEY'] = GMAP_KEY;
		 $RATING                 = $rdata['RATING'] / $rdata['VOTES'];
         $data['RATING']         = substr($RATING, 0, 3);
         $data['VOTES']          = $rdata['VOTES'];
         unset ($cdata, $site_url);
         $odata = $db->GetAll("SELECT * FROM `{$tables['link']['name']}` WHERE `OWNER_EMAIL` LIKE ".$db->qstr($rdata['OWNER_EMAIL'])." LIMIT 0 , 30");
         usort ($odata, "cmp");
         $data['RELATED'] = "";
         foreach ($odata as $value)
            if ($value['ID'] !== $id)
            {
               if (preg_match ("/\/$/", SITE_URL))
                  $link = SITE_URL."details.php?id=".$value['ID'];
               else
                  $link = SITE_URL."/details.php?id=" . $value['ID'];

               $data['RELATED'] .= "<li><a class=\"special\" href=\"{$link}\">{$value['TITLE']}</a></li>\n";
            }
         if($data['RELATED'])
            $data['RELATED'] = "<ul>\n{$data['RELATED']}</ul>\n";

         unset ($odata);
      }
         // get approved Comments
         $comments = $db->GetAll("SELECT * FROM `{$tables['linkcomment']['name']}` WHERE `STATUS` = '2' AND `LINK_ID` = ".$db->qstr($id));
         $tpl->assign('comments', $comments);
         
         // Check for 24 Hour Exprice for RATINGS
         $prevTime = time() - LINK_RATING_TIME;
         $date = date("Y-m-d H:i:s", $prevTime);
         $rating = $db->GetOne("SELECT COUNT(*) FROM `{$tables['linkrating']['name']}` WHERE `LINK_ID` = ".$db->qstr($id)." AND `DATE_ADDED` > '$date'");
         if($rating >= 1) {
              $tpl->assign('rating_disabled', 'disabled');
         }
   }
   unset ($rdata);
}
else
   $tpl->assign('error', "No ID parameter");

// Check if user is logged in
if (REQUIRE_REGISTERED_USER_LINK_COMMENT == 0 || !empty ($_SESSION['phpld']['user']['id'])) {
    $tpl->assign('logged_comment', 1);
}

if (REQUIRE_REGISTERED_USER_LINK_RATING == 0 || !empty ($_SESSION['phpld']['user']['id'])) {
    $tpl->assign('logged_rating', 1);
}
   $URL =  $data['URL'];

$path   = array ();
$path[] = array ('ID' => '0', 'TITLE' => _L(SITE_NAME)        , 'TITLE_URL' => DOC_ROOT, 'DESCRIPTION' => SITE_DESC);
$path[] = array ('ID' => '0', 'TITLE' => _L('Listing Details'), 'TITLE_URL' => ''      , 'DESCRIPTION' => _L('Listing Details'));

if (VISUAL_CONFIRM_LINK_COMMENTS == 1)
   $tpl->assign('captcha_length', CAPTCHA_PHRASE_LENGTH);

$tpl->assign('path', $path);
$tpl->assign($data);

$tpl->assign('MetaKeywords'   , (!empty ($data['META_KEYWORDS'])    ? trim ($data['META_KEYWORDS'])    : trim ($MetaKeywords)));
$tpl->assign('MetaDescription', (!empty ($data['META_DESCRIPTION']) ? trim ($data['META_DESCRIPTION']) : trim ($MetaDescription)));


$tpl->assign('SITE_NAME'      , SITE_NAME);
$tpl->assign('load_Javascript',  'true');
//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('detail.tpl', $id);
unset ($data);

function cmp($a, $b) {
   return strcmp ($a["TITLE"], $b["TITLE"]);
}
?>