<?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 (strpos($_SESSION['return'], 'article_list.php') === false && strpos($_SESSION['return'], 'article_reviewed.php') === false ) {
    unset($_SESSION['return']);
}


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

   $action = strtoupper (trim ($action));
   $id     = ($id < 0  ? 0 : intval ($id));
   $val    = ($val < 0 ? 0 : intval ($val));

   $tpl->assign('action', strtoupper ($action));
}

//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"
						)
			)
		),
		'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.")
		)
	)
);



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 link
if (!$_SESSION['phpld']['adminpanel']['is_admin'])
{
	if (($_SESSION['phpld']['adminpanel']['rights']['addArt'] != 1 && $action == 'N') 
	|| ($_SESSION['phpld']['adminpanel']['rights']['editArt'] != 1 && ($action == 'E' || $action == 'M'))
	|| ($_SESSION['phpld']['adminpanel']['rights']['delArt'] != 1 && ($action == 'D'))
	|| !($_REQUEST['action']))
   {
      //Editor is on unallowed page, block access
      http_custom_redirect("unauthorized.php");
      exit();
   }
}

$tpl->assign('stats', array (0 => _L('Inactive'), 1 => _L('Pending'), 2 => _L('Active'),));
$tpl->assign('types', array (0 => _L('None'), 1 => _L('Free'), 2 => _L('Normal'), 3 => _L('Reciprocal'), 4 => _L('Featured'),));
$tpl->assign('econfirm', array (0 => _L('No'), 1 => _L('Yes'),));

switch ($action)
{
   case 'S' : //Set Status
      $ActionStatus = SetNewArticleStatus($id, $val);
      $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 'A' : //Approve
      $ActionStatus = SetNewArticleStatus($id, 2, 0);
      $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' : //Delete
      $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' : //Edit
      if (empty ($_REQUEST['submit']))
      {
         $data = $db->GetRow("SELECT * FROM `{$tables['article']['name']}` WHERE `ID` = ".$db->qstr($id));
      }

   case 'N' : //New
   default :
      //Determine length of description field
      $DescriptionLimit = (isset ($data['DESCRIPTION']) && strlen (trim ($data['DESCRIPTION'])) > 0 ? ARTICLE_DESCRIPTION_MAX_LENGTH - strlen (trim ($data['DESCRIPTION'])) : ARTICLE_DESCRIPTION_MAX_LENGTH);
      $tpl->assign('DescriptionLimit', $DescriptionLimit);

      // 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 ($action == 'N')
      {
         $data['STATUS'] = 2;
//         if(FTR_ENABLE == 1)
            $data['FEATURED']    = $_REQUEST['f'] == '1';

           $def_rel_date = date('Y-m-d');;
           $tpl->assign('def_rel_date', $def_rel_date);
      }
      if (AJAX_CAT_SELECTION_METHOD == 0)
      {
         $categs = get_regular_categs_tree();
         $tpl->assign('categs', $categs);
      }

      if (!empty ($_SESSION['phpld']['adminpanel']['id']))
        $owner_details = $db->GetRow("SELECT `ID` AS `OWNER_ID`, `NAME` AS `OWNER_NAME`, `EMAIL` AS `OWNER_EMAIL` FROM `{$tables['user']['name']}` WHERE `ID` = ".$db->qstr($_SESSION['phpld']['adminpanel']['id']));

if ((empty($_POST['submit']) && empty($_POST['edit']))){
      if ($action != 'E') {
         $data['OWNER_NAME'] = (!empty ($data['OWNER_NAME']) ? (strlen ($data['OWNER_NAME']) > USER_NAME_MAX_LENGTH ? substr ($data['OWNER_NAME'], 0, USER_NAME_MAX_LENGTH - 4).' ...' : trim ($data['OWNER_NAME'])) : $owner_details['OWNER_NAME']);
         $data['OWNER_EMAIL'] = (!empty ($data['OWNER_EMAIL']) ? $data['OWNER_EMAIL']: $owner_details['OWNER_EMAIL']);
         $data['OWNER_ID'] = (!empty ($data['OWNER_ID']) ? $data['OWNER_ID']: $owner_details['OWNER_ID']);
      }
}

      if (empty ($_POST['submit'])) {
      	$tpl->assign('submit_session', registerAdminSubmitSession());
      } else {
      	  checkAdminSubmitSession(clean_string($_POST['submit_session']));
      	  $tpl->assign('submit_session', registerAdminSubmitSession());
      	
           $data = get_table_data('article');

//              if (!empty ($owner_details))
//                $data = array_merge ($data, $owner_details);

         $data['IPADDRESS']      = $client_info['IP'];

         if ($action == 'N')
         {
            $data['OWNER_EMAIL_CONFIRMED'] = 1;
            $data['DATE_ADDED']    = gmdate ('Y-m-d H:i:s');
         }

         $data['DATE_MODIFIED'] = gmdate ('Y-m-d H:i:s');

           //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 (FTR_ENABLE == 1)
            		$data['FEATURED'] = ($_POST['ARTICLE_TYPE'] == '4' ? '1' : '0');
         
           		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']);
              
           		if ($data['OWNER_ID'] == 0 && empty($data['OWNER_NAME'])) {
	            	$admin_details = $db->GetRow("SELECT `ID`, `NAME`, `EMAIL` FROM `{$tables['user']['name']}` WHERE `LEVEL` = '1' AND `ACTIVE` = '1' LIMIT 1");
	            	$data['OWNER_NAME'] = $admin_details['NAME'];
	            	$data['OWNER_EMAIL'] = $admin_details['EMAIL'];
	            	$data['OWNER_ID'] = $admin_details['ID'];
	            }

           		if (trim ($data['RELEASE_DATE']) == '')
            		$data['RELEASE_DATE'] = date ('Y-m-d H:i:s');
        
            	$data['ID']   = $id;

            	if (db_replace('article', $data, 'ID') > 0) {
               		$tpl->assign('posted', true);

               		if ($action == 'N') {
                  		$cid = $data['CATEGORY_ID'];
                  		$data = array ();
                  		$data['STATUS'] = 2;
                  		$data['CATEGORY_ID'] = $cid;
               		} else {
				    	send_status_notificationsa($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.'));
         }
      }
	  if ($action == 'E') {
      	$data['SEO_URL'] = seo_url($data['ID'], $data['TITLE'], REWRITE_TYPE, REWRITE_EXT, 1);
      }
      $tpl->assign($data);
      
      $inline_widgets = $db->GetAll("SELECT `ID`, `NAME` FROM `{$tables['inline_widget']['name']}` WHERE `STATUS` = '1'");
		$tpl->assign('inline_widgets', $inline_widgets);
      $content = $tpl->fetch(ADMIN_TEMPLATE.'/article_edit.tpl');
      break;
}


$tpl->assign('content', $content);

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

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