<?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';
// Check page request, if not valid a http header 404 is sent
$http_status = (!empty ($_REQUEST['httpstatus']) ? intval ($_REQUEST['httpstatus']) : article_status());
httpstatus($http_status);
//var_dump($widgets);

//Determine article ID
if (ENABLE_REWRITE == 1)
{
	/*preg_match ('#(.*)article(_|-)(\d+)\.htm[l]?$#i', request_uri(), $matches);

	$id = (!empty ($matches[3]) ? intval ($matches[3]) : 0);
    if(empty($matches[3])){
		$id = (!empty ($_REQUEST['id']) ? intval ($_REQUEST['id']) : 0);
		}
	*/
   // Know extensions
   $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 (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_COMMENTS == 1 && VISUAL_CONFIRM == 1) {
    require_once 'include/functions_imgverif.php';
    $imagehash = fetch_captcha_hash();
    $tpl->assign('imagehash', $imagehash);
    unset ($imagehash);
}
 if (empty($_POST['submit'])) {
			
if (VISUAL_CONFIRM_COMMENTS == 1 && VISUAL_CONFIRM == 2) {
	// do the math
	$n1 = rand(1,9);
	$n2 = rand(1,9);
	$hash = do_math($n1, $n2);

	$_SESSION['DO_MATH_N1'] = $n1;
	$_SESSION['DO_MATH_N2'] = $n2;

	// end do the math
	}
 }

/**
 * @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.
 *
 */

//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'];
	
    if (get_user_level($_SESSION['phpld']['user']['id']) == 1 || get_user_level($_SESSION['phpld']['user']['id']) == 3 ) {
          $permission_links_arts = "1 ";
   } else {
       //raluca
       $permissions = get_user_permissions($_SESSION['phpld']['user']['id']);
       $permission_links_arts = "`CATEGORY_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']."', ";
               } else {
                    $permission_links_arts .= "'".$permissions[$i]['CATEGORY_ID']."') ";
               }
           }
       } else {
           $permission_links_arts = "0 ";
        }
       //raluca
   }
} else {
    $permission_links_arts = "0 ";
}

if (isset($_REQUEST['action'])) {
		$action = explode(":", $_REQUEST['action']);


	$action = explode(":", $_REQUEST['action']);
	
	//comments starting here
	
	
	if ($action[0] == "C") {
	   if (REQUIRE_REGISTERED_USER_ARTICLE_COMMENT == 1){
	       if (empty($_SESSION['phpld']['user']['id'])) {
		      http_custom_redirect(DOC_ROOT.'/login.php');
		   }
	   }
	   // Assign values
	   $rdata = $db->CacheGetRow("SELECT *, DATE_FORMAT(DATE_ADDED, '%M %d, %Y %r') AS `DAT` FROM `{$tables['article']['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']);
	   
	   $cdata['ITEM_ID']	= $action[1];
	   // Type: 1 - Links Comments, 2 - Articles Comments
      $cdata['TYPE'] = '2';
	   $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'];

	   $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['comment']['name']}` WHERE `TYPE` = '2' AND `STATUS` = '2' AND `USER_ID` = ".$db->qstr($cdata[USER_ID]));
	   }
       if (empty($_SESSION['phpld']['user']['name'])) {
		   $cdata['USER_NAME'] = 'Guest';
	   }
	   if ($count < AUTO_APPROVE_COMMENTS || AUTO_APPROVE_COMMENTS_ONOFF == 0) {
           $cdata['STATUS'] = 1;
           $tpl->assign('needs_approval_msg', 1);
	   } else
	       $cdata['STATUS'] = 2;
	   
	   if ($data['rights']['addArt'] == 1 || $data['rights']['editArt'] == 1 || $data['rights']['delArt'] == 1) {
           $cdata['STATUS'] = 2;
       }
	       
	   if(!empty($_POST['comment'])) {

          

 // Image Verification
            if (VISUAL_CONFIRM_COMMENTS == 1 && VISUAL_CONFIRM == 1) {
           if ($data['rights']['addArt'] == 1 || $data['rights']['editArt'] == 1 || $data['rights']['delArt'] == 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['article']['name']}` SET `COMMENT_COUNT` = `COMMENT_COUNT` + 1 WHERE `ID` = ".$db->qstr($cdata['ARTICLE_ID'])) or die(mysql_error());
                    db_replace('comment', $cdata, 'ID');
                    $_SESSION['comm_posted'] = 1;
                    http_custom_redirect($_SERVER['HTTP_REFERER']);
                } else {
                    $tpl->assign('img_verification_error', true);
                }
			}
 if (VISUAL_CONFIRM_COMMENTS == 1 && VISUAL_CONFIRM == 2) {
               
                   //do the math
if (!isset($_SESSION['DO_MATH_N1']) || !isset($_SESSION['DO_MATH_N2']))
					{
	$imgCheck = 0;
	$validator_res['DO_MATH'] = 'Not a legitimate submit';
		
					}
					elseif ($_REQUEST['DO_MATH'] != $_SESSION['DO_MATH_N1']+$_SESSION['DO_MATH_N2'])
					{
						$imgCheck = 0;
						$validator_res['DO_MATH'] = 'Please Check Your Math Below';
					}
					else
					{
						$imgCheck = 1;
					}
		
// end do math
                
 
                if ($imgCheck == 1) {
                    $db->Execute("UPDATE `{$tables['article']['name']}` SET `COMMENT_COUNT` = `COMMENT_COUNT` + 1 WHERE `ID` = ".$db->qstr($cdata['ARTICLE_ID'])) or die(mysql_error());
                    db_replace('comment', $cdata, 'ID');
                    $_SESSION['comm_posted'] = 1;
                    http_custom_redirect($_SERVER['HTTP_REFERER']);
                } else {
                    $tpl->assign('error_list', $validator_res);
                }
           
      } else {
                // Write to DB
                $db->Execute("UPDATE `{$tables['article']['name']}` SET `COMMENT_COUNT` = `COMMENT_COUNT` + 1 WHERE `ID` = ".$db->qstr($cdata['ARTICLE_ID'])) or die(mysql_error());
                db_replace('comment', $cdata, 'ID');
                $_SESSION['comm_posted'] = 1;
                http_custom_redirect($_SERVER['HTTP_REFERER']);
          }
	  } else
              if (!empty($_POST['submit']))
                $tpl->assign('commentError', 1);

	
	} elseif ($action[0] == "R") {
if (REQUIRE_REGISTERED_USER_ARTICLE_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['article']['name']}` SET `RATING` = `RATING` + $_POST[RATING], `VOTES` = `VOTES` + 1 WHERE `ID` = ".$db->qstr($action[1])) or die(mysql_error());
                $rating['ARTICLE_ID']  = $action[1];
                $rating['IPADDRESS'] = $_SERVER['REMOTE_ADDR'];

                db_replace('articlerating', $rating);

               http_custom_redirect($_SERVER['HTTP_REFERER']);
                }
        }
}

// Determine  ID
if(!empty($action))
{
   $id = $action[1];
}
elseif (ENABLE_REWRITE == 1)
{
  /* preg_match ('#(.*)article(_|-)(\d+)\.htm[l]?$#i', request_uri(), $matches);
   $id = (!empty ($matches[3]) ? intval ($matches[3]) : 0);
*/
   // Know extensions
   $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 Article ID");
	} else {
		$rdata = $db->GetRow("SELECT *, DATE_FORMAT(DATE_ADDED, '%M %d, %Y %r') AS `DAT` FROM `{$tables['article']['name']}` WHERE (`STATUS` = '2' OR {$permission_links_arts}) AND `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['ARTICLE']        = stripslashes ($rdata['ARTICLE']);
			$data['ARTICLE']        = parse_article_units($rdata['ARTICLE']);
			$data['CATEGORY_ID']    = $rdata['CATEGORY_ID'];
			$data['DATE_MODIFIED']  = $rdata['DATE_MODIFIED'];
			$data['DATE_ADDED']     = $rdata['DAT'];
			$data['IPADRESS']       = $rdata['IPADRESS'];
			$data['META_KEYWORDS'] = $rdata['META_KEYWORDS'];
			$data['META_DESCRIPTION'] = $rdata['META_DESCRIPTION'];
			$data['STATUS']        = $rdata['STATUS'];
			$cdata = $db->GetRow("SELECT `TITLE` AS `CATEGORY_TITLE`, `CACHE_TITLE`, `CACHE_URL` FROM `{$tables['category']['name']}` WHERE `ID` = ".$db->qstr($rdata['CATEGORY_ID'])." LIMIT 1");
			$data['CATEGORY_TITLE'] = $cdata['CATEGORY_TITLE'];
			$data['CACHE_TITLE'] = $cdata['CACHE_TITLE'];
			$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['OWNER_ID']       = $rdata['OWNER_ID'];
			$data['CANONICAL'] = seo_url($data['ID'], $data['TITLE'], REWRITE_TYPE, REWRITE_EXT, 1);
			if (isset($_SESSION['phpld']['user']['id'])) {
			 $data['rights'] =  user_needs_approval($_SESSION['phpld']['user']['id'], $data['CATEGORY_ID']);
			 $data['has_payment'] = article_has_payment($data['ID']);
if('articles/'.$_REQUEST['id'] != seo_url($data['ID'], $data['TITLE'], REWRITE_TYPE, REWRITE_EXT, 1)){
  httpstatus('404');
$tpl->assign('error', "Bad Rewrite URL");
}
			 //hits modification
			 $HitInfo = $db->GetRow("SELECT * FROM `{$tables['hitcount']['name']}` WHERE `ARTICLE_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['article']['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['article']['name']}` SET `HITS` = `HITS` + 1 WHERE `ID` = ".$db->qstr($id));
      $HitInfo['ARTICLE_ID'] = $id;
      $HitInfo['IP']      = $client_info['IP'];
      $db->AutoExecute($tables['hitcount']['name'], $HitInfo, 'INSERT', false);
   }

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

   //end of hits mod
			}
			
			if ($rdata['OWNER_ID']) {
				$odata = $db->GetRow("SELECT * FROM `{$tables['user']['name']}` WHERE `ACTIVE` = '1' AND `ID` = ".$db->qstr($rdata['OWNER_ID']));
				$data['ANONYMOUS']    = $odata['ANONYMOUS'];
				if ($odata['ANONYMOUS'] == 0 || ALLOW_ANONYMOUS == 0) {
					if (ALLOW_AUTHOR_INFO == 1) {
						$data['NAME']     = "<a href=\"".DOC_ROOT."/";
						if (ENABLE_REWRITE) {
							$data['NAME']  .= "authors/author-".$data['OWNER_ID'].".html";
						} else {
							$data['NAME']  .= "author.php?id=".$data['OWNER_ID'];
						}
						$data['NAME']  .= "\" title=\"".htmlspecialchars($odata['NAME'])."\">".htmlspecialchars($odata['NAME'])."</a>";
					} else {
						$data['NAME']     = $odata['NAME'];
					}
					$data['WEBSITE']    = $odata['WEBSITE'];
					$data['INFO']       = $odata['INFO'];
				} else {
					$data['NAME']       = "Anonymous";
					$data['ANONYMOUS']  = 1;
				}
			} else {
				$data['NAME']       = $rdata['OWNER_NAME'];
				$data['ANONYMOUS']  = 1;
			}
			$RATING                 = $rdata['RATING'] / $rdata['VOTES'];
			$data['RATING']         = substr($RATING, 0, 3);
			$data['VOTES']          = $rdata['VOTES'];
			$data['LEFT_RATING'] = 10 - intval($rdata['RATING'] / $rdata['VOTES']);
			unset ($cdata, $site_url);
		}
		
		// get approved Comments
		$comments = $db->GetAll("SELECT * FROM `{$tables['comment']['name']}` WHERE `TYPE` = '2' AND `STATUS` = '2' AND `ITEM_ID` = ".$db->qstr($id));
		$tpl->assign('comments', $comments);

		// Check for 24 Hour Exprice for RATINGS
		$prevTime = time() - ARTICLE_RATING_TIME;
		$date = date("Y-m-d H:i:s", $prevTime);
		$rating = $db->GetOne("SELECT COUNT(*) FROM `{$tables['articlerating']['name']}` WHERE `ARTICLE_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_ARTICLE_COMMENT == 0 || !empty ($_SESSION['phpld']['user']['id'])) {
	$tpl->assign('logged_comment', 1);
}

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

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

if (VISUAL_CONFIRM_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('ratings_on', ARTICLE_RATING);
$tpl->assign('comments_on', ARTICLE_COMMENT);
$tpl->assign('SITE_NAME'      , SITE_NAME);
//Darius Tumas assign
//we send here to template system variable with user level.
$tpl->assign('uLevel'		  , $ito_user_permission);
$tpl->assign('load_Javascript',  'true');
$tpl->assign('load_mce', 'true');

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

//Compress output for faster loading
if (COMPRESS_OUTPUT == 1)
	$tpl->load_filter('output', 'CompressOutput');
	if (VISUAL_CONFIRM_COMMENTS == 1 && VISUAL_CONFIRM == 2) {
// do the math
$n1 = $_SESSION['DO_MATH_N1'];
$n2 = $_SESSION['DO_MATH_N2'];

$tpl->assign('DO_MATH_N1', $n1);
$tpl->assign('DO_MATH_N2', $n2);
// end do math
	}
//Make output
	
echo $tpl->fetch('article.tpl', $id);

unset ($data);

?>