<?php
/**
# ################################################################################
# Project:   PHP Link Directory: Version 3.1
#
# **********************************************************************
# Copyright (C) 2004-2006 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.0 branch of the software
# as they are made available at ttp://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-2006 NetCreated, Inc. (http://www.netcreated.com/)
# @projectManager David DuVal <david@david-duval.com>
# @package        PHPLinkDirectory
# @version        3.1 (=3.0.7)
# ################################################################################
*/

require_once 'init.php';
// Show main categories on all pages
require_once 'maincat.php';
// End of show main categories on all pages include
require_once 'statistic.php';

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 Link'), 'TITLE_URL' => ''      , 'DESCRIPTION' => _L('Submit a new link to the directory '));
$tpl->assign('path', $path);

//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_unauthorised = check_post_rules($_POST);

// Evaluate payment options
if (PAY_ENABLE == 1 && PAYPAL_ACCOUNT != '')
{
   $price = array ();
   if (FTR_ENABLE == 1 && PAY_FEATURED > 0)
      $price['featured'] = PAY_FEATURED;

   if (PAY_NORMAL > 0)
   {
      $price['normal'] = PAY_NORMAL;
      if (PAY_ENABLE_FREE)
         $price['free'] = 0;
   }
   if (PAY_RECPR > 0)
      $price['reciprocal'] = PAY_RECPR;

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

   if (isset ($_POST['LINK_TYPE']))
   {
      $link_type = $_POST['LINK_TYPE'];
      switch (strtolower ($link_type))
      {
         case 'reciprocal' :
            $recpr_required = 1;
            break;
         case 'free' :
            $recpr_required = REQUIRE_RECIPROCAL;
            break;
         default :
            $recpr_required = 0;
            break;
      }
   }
   else
      $recpr_required = 0;

   $_SESSION['SmartyValidate']['submit_link']['validators'][6]['empty'] = ($recpr_required ? false : true);
   $_SESSION['SmartyValidate']['submit_link']['validators'][7]['empty'] = ($recpr_required ? false : true);
   $_SESSION['SmartyValidate']['submit_link']['validators'][8]['empty'] = ($recpr_required ? false : true);
   $_SESSION['SmartyValidate']['submit_link']['validators'][9]['empty'] = ($recpr_required ? false : true);
}
else
   $recpr_required = REQUIRE_RECIPROCAL;

$ShowReciprField = ($recpr_required == 0 && SHOW_RECIPROCAL_FIELD == 0 ? 0 : 1);

if (isset ($price) && !empty ($price) && is_array ($price))
{
   foreach ($price as $value)
   {
      if ($value > 0)
         $ShowReciprField = 1;
   }
}

$tpl->assign('recpr_required' , $recpr_required);
$tpl->assign('ShowReciprField', $ShowReciprField);

$link_id = (!empty ($_REQUEST['linkid']) ? clean_string_paranoia($_REQUEST['linkid']) : 0);

$remove_link  = 0;
$review_link  = 0;
$EditRedirect = 0;

//Determine category
$CategoryID = (!empty($_REQUEST['c']) && preg_match ('`^[\d]+$`', $_REQUEST['c']) ? intval ($_REQUEST['c']) :
               (!empty ($_SERVER['HTTP_REFERER']) ? get_category($_SERVER['HTTP_REFERER']) : 0));
$CategoryID = ($CategoryID > 0 ? $CategoryID : 0); //Make sure the category ID is valid
$CategoryTitle = '';

if (!empty ($link_id))
{
   $link_id = intval ($link_id);
   if (REQUIRE_REGISTERED_USER == 1 && !empty ($_SESSION['regular_user_id']))
   {
      $check_user = $db->GetOne("SELECT COUNT(*) FROM `{$tables['link']['name']}` WHERE `ID` = ".$db->qstr($link_id)." AND `OWNER_ID` = ".$db->qstr($_SESSION['regular_user_id']));

      $check_double_review = $db->GetOne("SELECT COUNT(*) FROM `{$tables['link_review']['name']}` WHERE `LINK_ID` = ".$db->qstr($link_id));
      if ($check_double_review > 0)
         $tpl->assign('double_review', _L('This entry is already marked for review and was not approved yet. New modifications will overwrite older reviews.'));

   }
   if ($check_user < 1)
   {
      http_redirect(DOC_ROOT.'/unauthorised.php');
   }

   $remove_link = 1;
   $review_link = 1;
}

$EditUnique    = '';
$MoveToPayment = true;
$action        = 'submit'; //Default action
if (REQUIRE_REGISTERED_USER == 1 && !empty ($_SESSION['regular_user_id']) && $review_link == 1)
   $action = 'edit';

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

if (empty ($_POST['submit']) && empty ($_POST['edit']))
{
   if (defined ('FORCE_SUBMIT_SESSION') && FORCE_SUBMIT_SESSION == 1)
   {
      generateSubmitSession();
   }

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

   if (REQUIRE_REGISTERED_USER == 1 && !empty ($_SESSION['regular_user_id']) && !empty ($link_id))
   {
      $sql = "SELECT * FROM `{$tables['link']['name']}` WHERE `ID` = ".$db->qstr($link_id)." AND `OWNER_ID` = ".$db->qstr($_SESSION['regular_user_id']);
      $data = $db->GetRow($sql);
      $EditUnique = ':TITLE:'.$data['TITLE'];
   }
   else
   {
      $data = array ();
      $data['CATEGORY_ID'] = $CategoryID;
   }

   $CategoryTitle = getCategoryTitleByID($data['CATEGORY_ID']);

   if (PAY_ENABLE == 1 && PAYPAL_ACCOUNT != '')
      $link_type = determine_link_type($data['LINK_TYPE']);

   $data['RECPR_REQUIRED'] = $recpr_required;

   // 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);

   SmartyValidate :: register_form('submit_link', true);

   SmartyValidate :: register_criteria('isValueUnique'    , 'validate_unique'         , 'submit_link');
   SmartyValidate :: register_criteria('isUrlUnique'      , 'validateUrlUnique'       , 'submit_link');
   SmartyValidate :: register_criteria('isNotEqual'       , 'validate_not_equal'      , 'submit_link');
   SmartyValidate :: register_criteria('isURLOnline'      , 'validate_url_online'     , 'submit_link');
   SmartyValidate :: register_criteria('isDomainBanned'   , 'validate_isBannedDomain' , 'submit_link');
   SmartyValidate :: register_criteria('isRecprOnline'    , 'validate_recpr_link'     , 'submit_link');
   SmartyValidate :: register_criteria('isCaptchaValid'   , 'validate_captcha'        , 'submit_link');
   SmartyValidate :: register_criteria('isBannedEmail'    , 'validate_is_banned_email', 'submit_link');

   SmartyValidate :: register_validator('v_TITLE'         , 'TITLE', 'notEmpty'  , false, false, 'trim', 'submit_link');
   SmartyValidate :: register_validator('v_TITLE_U'       , 'TITLE:link::CATEGORY_ID'.$EditUnique, 'isValueUnique', false, false, null, 'submit_link');
   SmartyValidate :: register_validator('v_TITLE_LENGTH'  , 'TITLE:'.TITLE_MIN_LENGTH.':'.TITLE_MAX_LENGTH, 'isLength', false, false, 'trim', 'submit_link');

   SmartyValidate :: register_validator('v_URL'           , 'URL', 'isURL'       , false, false, 'trim', 'submit_link');
   SmartyValidate :: register_validator('v_URL_BANNED'    , 'URL', 'isDomainBanned', false, false, 'trim', 'submit_link');
   SmartyValidate :: register_validator('v_URL_ONLINE'    , 'URL', 'isURLOnline' , false, false,  null , 'submit_link');
   SmartyValidate :: register_validator('v_URL_U'         , 'URL'.(REQUIRE_REGISTERED_USER == 0 || $action != 'edit' ? ':link' : ':').(ALLOW_MULTIPLE ? '::CATEGORY_ID' : ''), 'isUrlUnique', false, false, null, 'submit_link');

   SmartyValidate :: register_validator('v_DESCRIPTION_LENGTH', 'DESCRIPTION:'.DESCRIPTION_MIN_LENGTH.':'.DESCRIPTION_MAX_LENGTH, 'isLength'  , true, false, 'trim', 'submit_link');

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

   SmartyValidate :: register_validator('v_RECPR_URL'     , 'RECPR_URL'          , 'isURL'         , ($recpr_required ? false : true), false, 'trim', 'submit_link');
   SmartyValidate :: register_validator('v_RECPR_ONLINE'  , 'RECPR_URL'          , 'isURLOnline'   , ($recpr_required ? false : true), false, null, 'submit_link');
   SmartyValidate :: register_validator('v_RECPR_LINK'    , 'RECPR_URL'          , 'isRecprOnline' , ($recpr_required ? false : true), false, null, 'submit_link');

   if (REQUIRE_REGISTERED_USER == 0 || empty ($_SESSION['regular_user_id']))
   {
      SmartyValidate :: register_validator('v_OWNER_NAME' , 'OWNER_NAME'         , 'notEmpty'      , false, false, 'trim', 'submit_link');
      SmartyValidate :: register_validator('v_OWNER_NAME_LENGTH'  , 'OWNER_NAME:'.USER_NAME_MIN_LENGTH.':'.USER_NAME_MAX_LENGTH, 'isLength', false, false, 'trim', 'submit_link');
      SmartyValidate :: register_validator('v_OWNER_EMAIL', 'OWNER_EMAIL'        , 'isEmail'       , false, false, 'trim', 'submit_link');
   }
   SmartyValidate :: register_validator('v_OWNER_EMAIL_BANNED', 'OWNER_EMAIL', 'isBannedEmail', false, false, 'trim', 'submit_link');

   if (count ($price) > 0)
      SmartyValidate :: register_validator('v_LINK_TYPE'  , 'LINK_TYPE'          , 'notEmpty'      , false, false, 'trim', 'submit_link');

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

   SmartyValidate :: register_validator('v_META_DESCRIPTION_LENGTH', 'META_DESCRIPTION:'.DESCRIPTION_MIN_LENGTH.':'.DESCRIPTION_MAX_LENGTH, 'isLength'  , true, false, 'trim', 'submit_link');
   SmartyValidate :: register_validator('v_META_KEYWORDS' , 'META_KEYWORDS:0:1024', 'isLength', true , false, 'trim', 'submit_link');

}
else
{
   SmartyValidate :: connect($tpl);

   $CategoryTitle = getCategoryTitleByID($data['CATEGORY_ID']);

   if (REQUIRE_REGISTERED_USER == 1 && !empty ($_SESSION['regular_user_id']) && !empty ($_POST['edit']))
      $action = 'edit';

   if ($action == 'edit')
      $data = get_table_data('link_review');
   else
      $data = get_table_data('link');

   //Take care of white-space chars
   $data = filter_white_space($data);

   $data['STATUS']         = '1';
   $data['IPADDRESS']      = $client_info['IP'];
   if (!empty ($client_info['HOSTNAME']))
      $data['DOMAIN']      = $client_info['HOSTNAME'];

   $data['VALID']          = '1';
   $data['LINK_TYPE']      = $link_type;
   $data['RECPR_REQUIRED'] = $recpr_required;
   if ($recpr_required)
   {
      $data['RECPR_VALID']        = '1';
      $data['RECPR_LAST_CHECKED'] = gmdate ('Y-m-d H:i:s');
   }

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

   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 (VISUAL_CONFIRM == 1 && !empty ($_POST['CAPTCHA']))
   {
      $data = array_merge ($data, array ('CAPTCHA' => $_POST['CAPTCHA'], 'IMAGEHASH' => $_POST['IMAGEHASH']));
   }

   $alreadyFeatured = 0;
   $SecondValidation = 1;

   //On review, check if link is already a featured link
   if ($action == 'edit')
   {
      $alreadyFeatured = $db->GetOne("SELECT `FEATURED` FROM {$tables['link']['name']} WHERE `ID` = ".$db->qstr($link_id));
   }

   if (PAY_ENABLE == '1' && FTR_ENABLE == 1 && $_POST['LINK_TYPE'] == 'featured' && !empty ($data['CATEGORY_ID']) && $alreadyFeatured == 0)
   {
      $SecondValidation = $AllowedFeat = check_allowed_feat($data['CATEGORY_ID']);
      $tpl->assign('AllowedFeat', $AllowedFeat);
   }

   //Validate domain, if not banned
   $secondBanCheck = $db->GetOne("SELECT COUNT(*) FROM `{$tables['banlist']['name']}` WHERE `BAN_DOMAIN` LIKE ".$db->qstr(parseDomain($data['URL'])));
   $SecondValidation = ($secondBanCheck > 0 ? 0 : $SecondValidation);
   $tpl->assign('secondBanCheck', $secondBanCheck);

   if (SmartyValidate :: is_valid($data, 'submit_link') && $SecondValidation == 1)
   {
      if (defined ('FORCE_SUBMIT_SESSION') && FORCE_SUBMIT_SESSION == 1)
      {
         //Validate unique submit session
         $submitSessionValidation = validate_submit_session();

         if ($submitSessionValidation == 0)
         {
            //Invalid or expired submission,
            //Block access
            unset ($data);
            $reason = _L('Invalid or expired submit session').'! '._L('Please reload submit page and try again').'.';
            gotoUnauthorised($reason);
         }
      }

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

      if (ENABLE_PAGERANK == 1)
      {
         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']);
      }

      if ($action == 'edit')
      {
         $id = $db->GetOne("SELECT `ID` FROM `{$tables['link_review']['name']}` WHERE `LINK_ID` = ".$db->qstr($link_id));
         $id = (!empty ($id) ? intval ($id) : '');
      }
      else
         $id = $db->GenID($tables['link']['name'].'_SEQ');

      $data['ID']        = (!empty ($id) ? intval ($id) : '');
      $data['LINK_TYPE'] = $link_type_int[$link_type];

      switch (strtolower ($link_type))
      {
         case 'free' :
            $data['NOFOLLOW'] = 1;
            break;
         case 'featured' :
            $data['FEATURED'] = 1;
            break;
         default :
            break;
      }
      if (!empty ($_SESSION['regular_user_id']))
         $data['OWNER_ID'] = $_SESSION['regular_user_id'];

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

      $data['OWNER_NOTIF'] = ($price[$link_type] > 0         ? 0 : 1 );
      $data['PAYED']       = ($price[$link_type] > 0         ? 0 : -1);
      $data['MARK_REMOVE'] = (!empty ($_POST['MARK_REMOVE']) ? 1 : 0 );

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

      if ($action != 'edit')
      {
         $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'])) : '');
      }

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

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

      $RegularLink_notif = true;

         if ($action == 'edit')
         {
            $OldLinkType = $db->GetOne("SELECT `LINK_TYPE` FROM `{$tables['link']['name']}` WHERE `ID` = ".$db->qstr($link_id));
            if ($OldLinkType == $data['LINK_TYPE'])
               $MoveToPayment    = false;

            $data['LINK_ID']     = $payment_id = $link_id;
            $submit_notification = $db->Replace($tables['link_review']['name'], $data, 'ID', true);
            $RegularLink_notif   = false;
         }
         else
         {
            $payment_id = $data['ID'];
            unset ($data['MARK_REMOVE']);
            $submit_notification = $db->Replace($tables['link']['name'], $data, 'ID', true);
         }

         if (!empty ($submit_notification))
         {
            $tpl->assign('posted', true);
            send_submit_notifications($data, $RegularLink_notif);

            //Remind some fields
            $reminder = array ('CATEGORY_ID', 'OWNER_NAME', 'OWNER_EMAIL');

            //Loop throught each link field
            foreach ($data as $field => $value)
            {
               //Check if it's not in the reminder fields
               if (!in_array ($field, $reminder))
               {
                  //Remove data
                  unset ($data[$field]);
               }
            }

            $payment_id = (!empty ($payment_id) && preg_match('`^[\d]+$`', $payment_id) ? intval ($payment_id) : '');

            if ($price[$link_type] > 0 && !empty ($payment_id) && $MoveToPayment == true)
            {
               http_redirect("payment.php?id=".$payment_id.($action == 'edit' ? '&mode=review' : '')); // Move to payment page
            }
            else
            {
               if (defined ('FORCE_SUBMIT_SESSION') && FORCE_SUBMIT_SESSION == 1)
               {
                  //Submission successfull, generate new submit session
                  generateSubmitSession();
               }

               unset ($_POST, $_GET, $_REQUEST);
            }

            $EditRedirect = 1;
         }
         else
            $tpl->assign('error', true);
   }
   else
      $tpl->assign($_POST);
}

//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 ? DESCRIPTION_MAX_LENGTH - strlen (trim ($data['META_DESCRIPTION'])) : DESCRIPTION_MAX_LENGTH);
$tpl->assign('MetaDescriptionLimit', $MetaDescriptionLimit);

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

$tpl->assign('remove_link', $remove_link);
$tpl->assign('review_link', $review_link);

if (CAT_SELECTION_METHOD == 0)
{
   $categs = get_regular_categs_tree(0);
   $tpl->assign('categs', $categs);
}
echo $_SESSION[$sessionHash];

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

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

$tpl->assign($data);

$tpl->assign('LINK_TYPE', $link_type);

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

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

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