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

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


if ($_REQUEST['action'])
{
   list($action, $id, $val) = explode(':', $_REQUEST['action']);

   $action = strtoupper (trim ($action));

   $val    = ($val < 0 ? 0 : intval ($val));
   $tpl->assign('action', strtoupper ($action));
}

$articleId = $id;

//RALUCA: JQuery validation related
$validators = array(
	'rules' => array(
		'TITLE' => array(
			'required' => true,
			'minlength' => ARTICLE_TITLE_MIN_LENGTH,
			'maxlength' => ARTICLE_TITLE_MAX_LENGTH,
			'remote' => array(
					'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
					'type'=> "post",
		        		'data'=> array (
		        			'action' => "isTitle",
		        			'table'  => "article",
		        			'field'  => "TITLE",
							'id'     => $id
		        		)
		    )
		),
		'CATEGORY_ID' => array(
			'required' => true,
			'remote' => array(
					'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
					'type'=> "post",
					'data'=> array (
						'action' => "isNotTopCat",
						'table' => "category",
						'field' => "CATEGORY_ID"
						)
			)
		),
		'EXPIRY_DATE' => array(
			'remote' => array(
					'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
					'type'=> "post",
					'data'=> array (
						'action' => "isDate",
						'table' => "article",
						'field' => "EXPIRY_DATE"
						)
			)
		),
		'DESCRIPTION' => array(
			'required' => true,
			'minlength' => ARTICLE_DESCRIPTION_MIN_LENGTH,
			'maxlength' => ARTICLE_DESCRIPTION_MAX_LENGTH
		),
		'ARTICLE' => array(
					'minlength' => ARTICLE_MIN_LENGTH,
					'maxlength' => ARTICLE_MAX_LENGTH
		),
		'META_DESCRIPTION' => array(
					'minlength' => META_DESCRIPTION_MIN_LENGTH,
					'maxlength' => META_DESCRIPTION_MAX_LENGTH
		),
		'META_KEYWORDS' => array(
					'minlength' => META_KEYWORDS_MIN_LENGTH,
					'maxlength' => META_KEYWORDS_MAX_LENGTH
		)
	),
	'messages' => array(
		'CATEGORY_ID'=> array(
			'remote'  	=>_L("Please select a category.")
		),
		'TITLE'=> array(
			'remote'  	=>_L("Title is not valid: most likely, not unique in parent category.")
		),
		'ARTICLE_TYPE'=> array(
			'remote'  	=>_L("Please select article type.")
		),
		'OWNER_EMAIL'=> array(
			'remote'  	=>_L("This email is banned.")
		),
		'EXPIRY_DATE'=> array(
			'remote'  	=>_L("Expiry date is not valid: please check the format.")
		)
	)
);

//if (REQUIRE_REGISTERED_USER_ARTICLE == 0 || empty ($_SESSION['phpld']['user']['id'])) {
$validators['rules']['OWNER_NAME'] = array(
	'required' => true,
	'minlength' => USER_NAME_MIN_LENGTH,
	'maxlength' => USER_NAME_MAX_LENGTH
);
$validators['rules']['OWNER_EMAIL'] = array(
	'required' => true,
	'email' => true,
	'remote' => array(
				'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
				'type'=> "post",
		        'data'=> array (
		        	'action' => "isBannedEmail",
		        	'table' => "user",
		        	'field' => "OWNER_EMAIL"
		        ))
);	
//}
$vld = json_custom_encode($validators);
$tpl->assign('validators', $vld);

$validator = new Validator($validators);
//RALUCA: end of JQuery validation related

//If editor, check if he/she is allowed to take an action on current article
if (!$_SESSION['phpld']['adminpanel']['is_admin'] && isset ($id))
{
   //Get categ ID of requested article
   $categID = $db->GetOne("SELECT `CATEGORY_ID` FROM `{$tables['article']['name']}` WHERE `ID` = ".$db->qstr($id));

   if (!in_array ($categID, $_SESSION['phpld']['adminpanel']['permission_array']))
   {
      //Editor is on unallowed page, block access
      http_custom_redirect("unauthorized.php");
      exit();
   }
}

//Correct value for ID
$id = (isset ($id) ? intval ($id) : 0);
$id = ($id < 0 ? 0 : $id);

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

switch ($action)
{
	case 'A' :
      $ActionStatus = SetNewReviewedArticleStatus($id, 2);
      $error = ($ActionStatus['status'] == 1 ? false : true);

      if ($ActionStatus['status'] != 1)
         $tpl->assign('sql_error', $ActionStatus['errorMsg']);

      if (!$error && isset ($_SESSION['return']))
         http_custom_redirect($_SESSION['return']);
		break;
	case 'R' :
      $ActionStatus = RemoveArticleReview($id);
      $error = ($ActionStatus['status'] == 1 ? false : true);

      if ($ActionStatus['status'] != 1)
         $tpl->assign('sql_error', $ActionStatus['errorMsg']);

      if (!$error && isset ($_SESSION['return']))
         http_custom_redirect($_SESSION['return']);
		break;
   case 'D' :
      $ActionStatus = RemoveArticle($id);
      $error = ($ActionStatus['status'] == 1 ? false : true);

      if ($ActionStatus['status'] != 1)
         $tpl->assign('sql_error', $ActionStatus['errorMsg']);

      if (!$error && isset ($_SESSION['return']))
         http_custom_redirect($_SESSION['return']);
      break;
	case 'E' :
		if (empty ($_REQUEST['submit']))
		{
			$data = $db->GetRow("SELECT * FROM `{$tables['article']['name']}` WHERE `ID` = ".$db->qstr($id));
			
         $revied_changes = $db->GetRow("SELECT * FROM `{$tables['article_review']['name']}` WHERE `ARTICLE_ID` = ".$db->qstr($id));
         unset ($revied_changes['ARTICLE_ID'], $revied_changes['META_KEYWORDS'], $revied_changes['META_DESCRIPTION']);
         if (!empty ($revied_changes)) {
            $data = array_merge($data, $revied_changes);
         }
		}

	default :
      //Determine length of description field
      $DescriptionLimit = (isset ($data['DESCRIPTION']) && strlen (trim ($data['DESCRIPTION'])) > 0 ? DESCRIPTION_MAX_LENGTH - strlen (trim ($data['DESCRIPTION'])) : DESCRIPTION_MAX_LENGTH);
      $tpl->assign('DescriptionLimit', $DescriptionLimit);
      //Determine length of article field
      $ArticleLimit = (isset ($data['ARTICLE']) && strlen (trim ($data['ARTICLE'])) > 0 ? ARTICLE_MAX_LENGTH - strlen (trim ($data['ARTICLE'])) : ARTICLE_MAX_LENGTH);
      $tpl->assign('ArticleLimit', $ArticleLimit);
      //Determine length of meta description field
      $MetaDescriptionLimit = (isset ($data['META_DESCRIPTION']) && strlen (trim ($data['META_DESCRIPTION'])) > 0 ? META_DESCRIPTION_MAX_LENGTH - strlen (trim ($data['META_DESCRIPTION'])) : META_DESCRIPTION_MAX_LENGTH);
      $tpl->assign('MetaDescriptionLimit', $MetaDescriptionLimit);

      // Get list of registered users
      $ActiveUsersList = $db->GetAssoc("SELECT `ID`, CONCAT(`LOGIN`, '  (', `NAME`, ' / ', `EMAIL`, ')') AS `USER` FROM `{$tables['user']['name']}` WHERE `ACTIVE` = '1'");
      $ActiveUsersList[0] = _L('Select username');
      ksort ($ActiveUsersList);
      $tpl->assign('ActiveUsersList', $ActiveUsersList);

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

		if ((empty ($_REQUEST['submit']))) {
        } else {
			$data = get_table_data('article');
			if ($action == 'N')
			{
				$data['IPADDRESS']      = $client_info['IP'];
            	if (!empty ($client_info['HOSTNAME']))
               		$data['DOMAIN']      = $client_info['HOSTNAME'];

				$data['VALID']         = 1;
				$data['RECPR_VALID']   = 1;
				$data['DATE_ADDED']    = gmdate ('Y-m-d H:i:s');
				$data['DATE_MODIFIED'] = gmdate ('Y-m-d H:i:s');
			}
//			if (FTR_ENABLE == 1)
				$data['FEATURED'] = $_REQUEST['FEATURED'] == '1'?'1':'0';

         	$data['EXPIRY_DATE'] = trim ($data['EXPIRY_DATE']);

			if (empty ($data['EXPIRY_DATE']))
				$data['EXPIRY_DATE'] = '';
         else
         {
				if (strtotime ($data['EXPIRY_DATE']) != -1)
					$data['EXPIRY_DATE'] = date ('Y-m-d H:i:s', (strtotime ($data['EXPIRY_DATE'])));
			}
			//RALUCA: JQuery validation related - server side.
			$validator = new Validator($validators);
			$validator_res = $validator->validate($_POST);
			//RALUCA: end of JQuery validation related - server side.
		   
		    if (empty($validator_res)) {
				if (empty ($id))
					$id = $db->GenID($tables['article']['name'].'_SEQ');

            if ($data['FEATURED'] == '1')
            {
               $AllowedFeat = check_allowed_feat($data['CATEGORY_ID']);
               $tpl->assign('AllowedFeat', $AllowedFeat);
            }

				if ($data['OWNER_ID'] > 0)
				{
               $user_details = $db->GetRow("SELECT `LOGIN`, `NAME`, `EMAIL` FROM `{$tables['user']['name']}` WHERE `ID` = ".$db->qstr($data['OWNER_ID']));
               if (!empty ($user_details))
               {
                  if (!empty ($user_details['NAME']))
                     $data['OWNER_NAME'] = $user_details['NAME'];

                  if (!empty ($user_details['EMAIL']))
                     $data['OWNER_EMAIL'] = $user_details['EMAIL'];
               }
               unset ($user_details);
			   }
				else
				  unset ($data['OWNER_ID']);

				$data['ID']   = $id;

				if (db_replace('article', $data, 'ID') > 0)
				{
					$tpl->assign('posted', true);
               		send_status_notifications($id, true, false);
               		$db->Execute("DELETE FROM `{$tables['article_review']['name']}` WHERE `ARTICLE_ID` = ".$db->qstr($id));
               		if (isset ($_SESSION['return']))
                  	http_custom_redirect($_SESSION['return']);
				}
            else
					$tpl->assign('sql_error', $db->ErrorMsg());
			} else {
				$tpl->assign('errorMsg', _L('Validation error: Please check your input data and try again.'));
			}
		}
		
		$tpl->assign($data);
		$tpl->assign('articleId', $articleId);
if (defined ('ARTICLE_ALLOW_HTML') && ARTICLE_ALLOW_HTML == 1) {
	//Set allowed tags for template to display
	//Clean up tag list
	$allowedTags = clean_string_paranoia(ARTICLE_ALLOWED_HTML_TAGS);
	//Remove multiple commas, commast at begin and end of sting, multiple spaces
	$allowedTags = preg_replace (array ('#^[,]*#i', '#[,]*$#i', '#[,]+#i', '#[\s]#'), array ('', '', ',', ''), $allowedTags);
	$tpl->assign('allowedTags', $allowedTags);
}

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

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

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