<?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';
 $tpl->assign('link_type_str', $link_type_str);
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 link
if (!$_SESSION['phpld']['adminpanel']['is_admin'])
{
   //Get categ ID of requested link
   $categID = $db->GetOne("SELECT `CATEGORY_ID` FROM `{$tables['link']['name']}` WHERE `ID` = ".$db->qstr($id));

//   if (!in_array ($categID, $_SESSION['phpld']['adminpanel']['permission_array']))
if (($_SESSION['phpld']['adminpanel']['rights']['addLink'] != 1 && $action == 'N') 
	|| ($_SESSION['phpld']['adminpanel']['rights']['editLink'] != 1 && ($action == 'E' || $action == 'M'))
	|| ($_SESSION['phpld']['adminpanel']['rights']['delLink'] != 1 && ($action == 'D'))
	|| !($action))
   {
      //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'),));
$tpl->assign('econfirm', array (0 => _L('No'), 1 => _L('Yes'),));

switch ($action)
{
   case 'S' : //Set Status
      $ActionStatus = SetNewLinkStatus($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 = SetNewLinkStatus($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 = RemoveLink($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['link']['name']}` WHERE `ID` = ".$db->qstr($id));
      }

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

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

      if ((empty ($_POST['submit']))   || (!SmartyValidate :: is_registered_form('dir_links_edit')))
      {
         SmartyValidate :: connect($tpl);
         SmartyValidate :: register_form('dir_links_edit', true);
         SmartyValidate :: register_criteria('isValueUnique' , 'validate_unique'   , 'dir_links_edit');
         SmartyValidate :: register_criteria('isNotEqual'    , 'validate_not_equal', 'dir_links_edit');

         SmartyValidate :: register_validator('v_TITLE'           , 'TITLE'                 , 'notEmpty'  , false, false, 'trim', 'dir_links_edit');
         SmartyValidate :: register_validator('v_TITLE_U'         , "TITLE:link:{$id}:CATEGORY_ID", 'isValueUnique', false, false, null, 'dir_links_edit');
         SmartyValidate :: register_validator('v_TITLE_LENGTH'    , 'TITLE:'.TITLE_MIN_LENGTH.':'.TITLE_MAX_LENGTH, 'isLength', false, false, 'trim', 'dir_links_edit');
 if (REQUIRE_URL == 1)
	{
         SmartyValidate :: register_validator('v_URL'             , 'URL'                   , 'isURL'     , false, false, 'trim', 'dir_links_edit');
         SmartyValidate :: register_validator('v_URL_U'           , 'URL:link:'.$id.(ALLOW_MULTIPLE ? ':CATEGORY_ID' : ''), 'isValueUnique', false, false, null, 'dir_links_edit');
	}
         SmartyValidate :: register_validator('v_DESCRIPTION_LENGTH', 'DESCRIPTION:'.DESCRIPTION_MIN_LENGTH.':'.DESCRIPTION_MAX_LENGTH, 'isLength'  , true, false, 'trim', 'dir_links_edit');

         SmartyValidate :: register_validator('v_CATEGORY_ID'     , 'CATEGORY_ID:0'         , 'isNotEqual', true , false,  null , 'dir_links_edit');
         SmartyValidate :: register_validator('v_RECPR_URL'       , 'RECPR_URL'             , 'isURL'     , true , false, 'trim', 'dir_links_edit');

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

         SmartyValidate :: register_validator('v_EXPIRY_DATE'     , 'EXPIRY_DATE'           , 'isDate'    , true , false, 'trim', 'dir_links_edit');
         SmartyValidate :: register_validator('v_HITS'            , 'HITS'                  , 'isNumber'  , true , false, 'trim', 'dir_links_edit');
         SmartyValidate :: register_validator('v_PAGERANK'        , 'PAGERANK:-1:10'        , 'isRange'   , true , false, 'trim', 'dir_links_edit');

         SmartyValidate :: register_validator('v_META_DESCRIPTION_LENGTH', 'META_DESCRIPTION:'.META_DESCRIPTION_MIN_LENGTH.':'.META_DESCRIPTION_MAX_LENGTH, 'isLength'  , true, false, 'trim', 'dir_links_edit');

         //SmartyValidate :: register_validator('v_META_KEYWORDS', 'META_KEYWORDS:'.META_KEYWORDS_MIN_LENGTH.':'.META_KEYWORDS_MAX_LENGTH, 'isLength'  , true , false, 'trim', 'dir_links_edit');
      }
      else
      {
         SmartyValidate :: connect($tpl);
         $data = get_table_data('link');

         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['OWNER_EMAIL_CONFIRMED'] = 1;
            
            $data['DATE_ADDED']    = gmdate ('Y-m-d H:i:s');
            $data['DATE_MODIFIED'] = gmdate ('Y-m-d H:i:s');
         }

         $data['NOFOLLOW']         = $_POST['NOFOLLOW']       == '1' ? '1' : '0';
         $data['RECPR_REQUIRED']   = $_POST['RECPR_REQUIRED'] == '1' ? '1' : '0';

         if (strlen (trim ($data['URL'])) > 0 && !preg_match ('#^http[s]?:\/\/#i', $data['URL']))
            $data['URL'] = "http://".$data['URL'];

         if (strlen (trim ($data['RECPR_URL'])) > 0 && !preg_match ('#^http[s]?:\/\/#i', $data['RECPR_URL']))
            $data['RECPR_URL'] = "http://".$data['RECPR_URL'];

         if (trim ($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 (FTR_ENABLE == 1)
            $data['FEATURED'] = ($_POST['FEATURED'] == '1' ? '1' : '0');

         //If editor, check if he/she is allowed to take an action on current category
         if (!$_SESSION['phpld']['adminpanel']['is_admin'] &&
             !empty ($data['CATEGORY_ID']) &&
             (($_SESSION['phpld']['adminpanel']['rights']['addLink'] != 1 && $action == 'N') || ($_SESSION['phpld']['adminpanel']['rights']['editLink']!=1 && ($action == 'E' || $action == 'M')))
         )
         {
            //Editor is on unallowed page, block access
            http_custom_redirect("unauthorized.php");
            exit();
         }

         if (SmartyValidate :: is_valid($data, 'dir_links_edit'))
         {
            if (empty ($id))
               $id = $db->GenID($tables['link']['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 (ENABLE_PAGERANK == 1)
            {
               $data['PAGERANK'] = trim ($data['PAGERANK']);
               if (strlen ($data['PAGERANK']) == 0)
               {
                  require_once 'include/pagerank.php';
                  $data['PAGERANK'] = get_page_rank($data['URL']);

                  if (!empty($data['RECPR_URL']))
                     $data['RECPR_PAGERANK'] = get_page_rank($data['RECPR_URL']);
               }
            }
            $data['HITS'] = ($data['HITS'] < 1 ? 0 : intval ($data['HITS']));

            $data['ID']   = $id;
            if (!isset ($data['RECPR_REQUIRED']))
               $data['RECPR_REQUIRED'] = 0;
			
                if (db_replace('link', $data, 'ID') > 0)
            {
               $tpl->assign('posted', true);
               if ($action == 'N')
               {
                  $cid = $data['CATEGORY_ID'];
                  $data = array ();
                  $data['STATUS'] = 2;
                  $data['CATEGORY_ID'] = $cid;
               }
			   elseif ($action == 'E')
			{
			if (isset($_REQUEST['semail'])){
			send_status_notificationse($id);
			}
			}
               else
               {
                  send_status_notifications($id);
                  if (isset ($_SESSION['return']))
                     http_custom_redirect($_SESSION['return']);
               }
            }
            else
               $tpl->assign('sql_error', $db->ErrorMsg());
         }
      }
      if ($action == 'E') {
      	$data['SEO_URL'] = seo_url($data['ID'], $data['TITLE'], REWRITE_TYPE, REWRITE_EXT, 2);
      }
      $tpl->assign($data);
      $content = $tpl->fetch(ADMIN_TEMPLATE.'/dir_links_edit.tpl');
      break;
}

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

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

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