<?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 (empty ($_REQUEST['submit']) && !empty ($_SERVER['HTTP_REFERER']))
   $_SESSION['return'] = $_SERVER['HTTP_REFERER'];


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

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

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

//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']))   || (!SmartyValidate :: is_registered_form('dir_articles_edit')))
      {
         SmartyValidate :: connect($tpl);
         SmartyValidate :: register_form('dir_articles_edit', true);
         SmartyValidate :: register_criteria('isValueUnique' , 'validate_unique'   , 'dir_articles_edit');
         SmartyValidate :: register_criteria('isNotEqual'    , 'validate_not_equal', 'dir_articles_edit');

         SmartyValidate :: register_validator('v_ARTICLE_TITLE'           , 'TITLE'                 , 'notEmpty'  , false, false, 'trim', 'dir_articles_edit');
         SmartyValidate :: register_validator('v_ARTICLE_TITLE_U'         , "TITLE:article:{$id}:CATEGORY_ID", 'isValueUnique', false, false, null, 'dir_articles_edit');
         SmartyValidate :: register_validator('v_ARTICLE_TITLE_LENGTH'    , 'TITLE:'.ARTICLE_TITLE_MIN_LENGTH.':'.ARTICLE_TITLE_MAX_LENGTH, 'isLength', false, false, 'trim', 'dir_articles_edit');

         SmartyValidate :: register_validator('v_ARTICLE_DESCRIPTION_LENGTH', 'DESCRIPTION:'.ARTICLE_DESCRIPTION_MIN_LENGTH.':'.ARTICLE_DESCRIPTION_MAX_LENGTH, 'isLength'  , true, false, 'trim', 'dir_articles_edit');

         SmartyValidate :: register_validator('v_ARTICLE_LENGTH', 'DESCRIPTION:'.ARTICLE_MIN_LENGTH.':'.ARTICLE_MAX_LENGTH, 'isLength'  , true, false, 'trim', 'dir_articles_edit');

         SmartyValidate :: register_validator('v_CATEGORY_ID'     , 'CATEGORY_ID:0'         , 'isNotEqual', true , false,  null , 'dir_articles_edit');

         SmartyValidate :: register_validator('v_OWNER_ID'        , 'OWNER_ID'              , 'notEmpty'  , true , false, 'trim', 'dir_articles_edit');
         SmartyValidate :: register_validator('v_OWNER_NAME'      , 'OWNER_NAME'            , 'notEmpty'  , true , false, 'trim', 'dir_articles_edit');
         SmartyValidate :: register_validator('v_OWNER_NAME_LENGTH', 'OWNER_NAME:'.USER_NAME_MIN_LENGTH.':'.USER_NAME_MAX_LENGTH, 'isLength', true, false, 'trim', 'dir_articles_edit');
         SmartyValidate :: register_validator('v_OWNER_EMAIL'     , 'OWNER_EMAIL'           , 'isEmail'   , true , false, 'trim', 'dir_articles_edit');

         SmartyValidate :: register_validator('v_EXPIRY_DATE'     , 'EXPIRY_DATE'           , 'isDate'    , true , false, 'trim', 'dir_articles_edit');

         SmartyValidate :: register_validator('v_META_DESCRIPTION_LENGTH', 'META_DESCRIPTION:'.DESCRIPTION_MIN_LENGTH.':'.DESCRIPTION_MAX_LENGTH, 'isLength'  , true, false, 'trim', 'dir_articles_edit');
         SmartyValidate :: register_validator('v_META_KEYWORDS'   , 'META_KEYWORDS:0:1024'         , 'isLength'  , true , false, 'trim', 'dir_articles_edit');
      }
      else
      {
			SmartyValidate :: connect($tpl);
			$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'])));
			}
			if (SmartyValidate :: is_valid($data, 'dir_articles_edit'))
			{
				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());
			}
		}
		$tpl->assign($data);
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');
?>
