<?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 (isset($_REQUEST['mode']) && $_REQUEST['mode'] == 'confirmed') {
    $tpl->assign('confirmed', 1);
}

if(isset($_SESSION['phpld']['user']['level']) && $_SESSION['phpld']['user']['level'] == 1) {
	$tpl->assign('is_admin', 1);
}

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

$rights =  user_needs_approval($_SESSION['phpld']['user']['id'], 0);

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

if ($rights['addPage']<1) {
    $reason = _L('You are not allowed to submit pages').'! ';
    gotoUnauthorized($reason);
}

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

if (defined ('FORCE_SUBMIT_SESSION') && FORCE_SUBMIT_SESSION == 1)
{
   require_once 'include/submit_session.php';
}

//Disable any caching by the browser
disable_browser_cache();

//Generate unique imagehash for visual confirmation
if (VISUAL_CONFIRM == 1)
{
   require_once 'include/functions_imgverif.php';
   $imagehash = fetch_captcha_hash();
   $tpl->assign('imagehash', $imagehash);
   unset ($imagehash);
}

$path   = array ();
$path[] = array ('ID' => '0', 'TITLE' => _L(SITE_NAME)    , 'TITLE_URL' => DOC_ROOT, 'DESCRIPTION' => SITE_DESC);
$path[] = array ('ID' => '0', 'TITLE' => _L('Submit Page'), 'TITLE_URL' => ''      , 'DESCRIPTION' => _L('Submit a new page to the directory '));
$tpl->assign('path', $path);

//Check if using RTE (Rich Text Editor)
$useRTE = (defined ('LINK_SUBMIT_USE_RTE') && LINK_SUBMIT_USE_RTE == 1 ? 1 : 0);
$tpl->assign('useRTE', $useRTE);


//If current user is banned, show a custom error message
//and stop the rest of the script
check_if_banned();

//Make an additional check if client is allowed to post/submit
//[Spam] protection
require_once 'include/check_post_rules.php';
$post_rules_unauthorized = check_post_rules($_POST);


//$cat_id = (!empty ($_REQUEST['catid']) ? clean_string_paranoia($_REQUEST['catid']) : 0);

//$remove_cat  = 0;
//$review_cat  = 0;
//$EditRedirect = 0;

//$EditUnique    = '';
//$MoveToPayment = true;
$action        = 'submit'; //Default action
//if (!empty ($_SESSION['phpld']['user']['id']) && $review_cat == 1)
//   $action = 'edit';

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

if ((empty ($_POST['submit']) && empty ($_POST['edit'])) || (!SmartyValidate :: is_registered_form('submit_page')))
{
   if (defined ('FORCE_SUBMIT_SESSION') && FORCE_SUBMIT_SESSION == 1)
   {
      generateSubmitSession();
   }

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

   if (!empty ($_SESSION['phpld']['user']['id']) && !empty ($cat_id))
   {
//      $sql = "SELECT * FROM `{$tables['page']['name']}` WHERE `ID` = ".$db->qstr($cat_id)." AND `OWNER_ID` = ".$db->qstr($_SESSION['phpld']['user']['id']);
//      $data = $db->GetRow($sql);
//      $EditUnique = ':TITLE:'.$data['TITLE'];
   }
   else
   {
      $data = array ();
   }


   // Clear some varialbles
   if (isset($_SESSION['SmartyPaginate']))
      unset ($_SESSION['SmartyPaginate']);
   if (isset($_SESSION['SmartyValidate']))
      unset ($_SESSION['SmartyValidate']);
   if (isset($_SESSION['values']))
      unset ($_SESSION['values']);

   SmartyValidate :: disconnect();
   SmartyValidate :: connect($tpl, true);

    //for login

    if (!SmartyValidate :: is_registered_form('login')) {
    
    SmartyValidate :: register_form('login', true);
    SmartyValidate :: register_validator('v_user', 'user', 'notEmpty', false, false, 'trim', 'login');
    SmartyValidate :: register_validator('v_pass', 'pass', 'notEmpty', false, false, 'trim', 'login');
    }
    //end for login
   
   SmartyValidate :: register_form('submit_page', true);

   SmartyValidate :: register_criteria('isValueUnique'    , 'validate_unique'         , 'submit_page');
	
   SmartyValidate :: register_criteria('isNotEqual'       , 'validate_not_equal'      , 'submit_page');

//   SmartyValidate :: register_criteria('isCaptchaValid'   , 'validate_captcha'        , 'submit_page');

   SmartyValidate :: register_validator('v_NAME'         , 'NAME', 'notEmpty'  , false, false, 'trim', 'submit_page');
   
   SmartyValidate :: register_validator('v_SEO_NAME'     , 'SEO_NAME', 'notEmpty'  , false, false, 'trim', 'submit_page');
   
   //SmartyValidate :: register_validator('v_DESCRIPTION'         , 'DESCRIPTION', 'notEmpty'  , false, false, 'trim', 'submit_link');
   SmartyValidate :: register_validator('v_NAME_LENGTH'  , 'NAME:'.TITLE_MIN_LENGTH.':'.TITLE_MAX_LENGTH, 'isLength', false, false, 'trim', 'submit_page');

//   if (VISUAL_CONFIRM == 1)
//      SmartyValidate :: register_validator('v_CAPTCHA'    , 'CAPTCHA:IMAGEHASH'  , 'isCaptchaValid', false, false, null, 'submit_page');

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

   //Not usually neccessary, keywords are trimmed to max allowed length automatically
   SmartyValidate :: register_validator('v_META_KEYWORDS_LENGTH' , 'META_KEYWORDS:'.META_KEYWORDS_MIN_LENGTH.':'.META_KEYWORDS_MAX_LENGTH, 'isLength', true , false, 'trim', 'submit_page');
}
else
{
   SmartyValidate :: connect($tpl);
   
//   $CategoryTitle = getCategoryTitleByID($data['PARENT_ID']);

   if (!empty ($_SESSION['phpld']['user']['id']) && !empty ($_POST['edit']))
      $action = 'edit';

   $data = get_table_data('page');

   //Take care of white-space chars
   $data = filter_white_space($data);
   
   $data['DATE_ADDED']     = gmdate ('Y-m-d H:i:s');
   
   if (VISUAL_CONFIRM == 1 && !empty ($_POST['CAPTCHA']))
   {
      $data = array_merge ($data, array ('CAPTCHA' => $_POST['CAPTCHA'], 'IMAGEHASH' => $_POST['IMAGEHASH']));
   }
   
   if (!isset ($_SESSION['SmartyValidate']['submit_page']) || empty ($_SESSION['SmartyValidate']['submit_page']))
   {
      //Invalid or expired submission,
      //Block access
      unset ($data);
      $reason = _L('Invalid or expired submit session').'! '._L('Please reload submit page and try again').'.';
      gotoUnauthorized($reason);
   }

   if (SmartyValidate :: is_valid($data, 'submit_page'))
   {
      //Validate for banned words
      //Pass all submition data as parameter
      $hasBannedWords = if_word_is_banned($data);
      if ($hasBannedWords == 1)
      {
         //Invalid or expired submission,
         //Block access
         unset ($data);
         $reason = _L('The administrator of this link directory has banned words from your submition.');
         gotoUnauthorized($reason);
      }

      if (isset ($data['CAPTCHA']))
         unset ($data['CAPTCHA']);
      if (isset ($data['IMAGEHASH']))
         unset ($data['IMAGEHASH']);

      //raluca
      $result = $db->GetRow("SELECT MAX(`ID`) AS `LAST` FROM `{$tables['page']['name']}`");
      if ($result['LAST'] == '') {
          $id = 0;
      } else {
          $id = $result['LAST']+1;
      }
         
      $data['ID']        = (!empty ($id) ? intval ($id) : '');
     // $data['LINK_TYPE'] = $link_type_int[$link_type];

      //Check again fields and truncate to maximum length,
      //auto-submitters can no more force longer text than allowed
      $data['NAME'] = (!empty ($data['NAME']) ? (strlen ($data['NAME']) > TITLE_MAX_LENGTH ? substr ($data['NAME'], 0, TITLE_MAX_LENGTH - 4).' ...' : trim ($data['NAME'])) : '');

      $data['CONTENT'] = (!empty ($data['CONTENT']) ? (strlen ($data['CONTENT']) > DESCRIPTION_MAX_LENGTH ? substr ($data['CONTENT'], 0, DESCRIPTION_MAX_LENGTH - 4).' ...' : trim ($data['CONTENT'])) : '');

      $data['META_DESCRIPTION'] = (!empty ($data['META_DESCRIPTION']) ? (strlen ($data['META_DESCRIPTION']) > META_DESCRIPTION_MAX_LENGTH ? substr ($data['META_DESCRIPTION'], 0, META_DESCRIPTION_MAX_LENGTH - 4).' ...' : trim ($data['META_DESCRIPTION'])) : '');
      $data['META_KEYWORDS'] = (!empty ($data['META_KEYWORDS']) ? clean_meta_keywords($data['META_KEYWORDS']) : '');
      
         if ($db->Replace($tables['page']['name'], $data, 'ID', true)) {
             $posted = true;
         } else {
             $error = true;
         }
      

   }
   else
      $tpl->assign($_POST);
}

$tpl->assign('error', $error);
$tpl->assign('posted', $posted);

//Determine length of description field
$DescriptionLimit = (isset ($data['CONTENT']) && strlen (trim ($data['CONTENT'])) > 0 ? DESCRIPTION_MAX_LENGTH - strlen (trim ($data['CONTENT'])) : 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);
// Disabled submit reason
$disable_reason = DISABLE_REASON;
$tpl->assign('disablereason', $disable_reason);

if (defined ('ALLOW_HTML') && ALLOW_HTML == 1) {
	//Set allowed tags for template to display
	//Clean up tag list
	$allowedTags = clean_string_paranoia(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);
	$allowedTags = preg_replace ("/,/",', ', $allowedTags);
	$tpl->assign('allowedTags', $allowedTags);
}
if (defined ('ALLOW_ATTR') && ALLOW_ATTR == 1) {
	//Set allowed tags for template to display
	//Clean up tag list
	$allowedAttr = clean_string_paranoia(ALLOWED_ATTR_TAGS);
	//Remove multiple commas, commast at begin and end of sting, multiple spaces
	$allowedAttr = preg_replace (array ('#^[,]*#i', '#[,]*$#i', '#[,]+#i', '#[\s]#'), array ('', '', ',', ''), $allowedAttr);
	$allowedAttr = preg_replace ("/,/",', ', $allowedAttr);
	$tpl->assign('allowedAttr', $allowedAttr);
}

if (VISUAL_CONFIRM == 1)
   $tpl->assign('captcha_length', CAPTCHA_PHRASE_LENGTH);

//Load Javascript libraries
$load_Javascript = 1;
$tpl->assign('load_Javascript', $load_Javascript);

$tpl->assign($data);

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

//Make output
echo $tpl->fetch('submit_page.tpl', $id);

if ($action == 'edit' && $EditRedirect == 1)
   http_custom_redirect('submit.php', 'html', 5, '');
?>