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

if (defined('REQUIRE_REGISTERED_USER') && (REQUIRE_REGISTERED_USER == 1) && (EMAIL_CONFIRMATION == 1)) {
	if (isset($_SESSION['phpld']['user']['id'])) {
		$uid = $_SESSION['phpld']['user']['id'];
		if (!has_confirmed_email($uid)) {
			$reason = _L('You have not confirmed your email address yet').'! '._L('Please check your email for the confirmation link').'.';
			gotoUnauthorized($reason);
		}
	}
} 

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


define ('FORCE_SUBMIT_SESSION', "0");// Remove submit session for now

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

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

$article_id = (!empty ($_REQUEST['articleid']) ? clean_string_paranoia($_REQUEST['articleid']) : 0);
$tpl->assign('article_id', $article_id);

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

//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'     => $article_id
   						)
   					)
				),
		'CATEGORY_ID' => array('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
				),
		'ARTICLE_TYPE' => array(
						'remote' => array(
								'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
								'type'=> "post",
					        		'data'=> array (
					        			'action' => "isArticleType",
					        			'table' => "article",
					        			'field' => "ARTICLE_TYPE"
					        		)
   						),
				),
		'AGREERULES' => array(
					'required' => true
				),
	),
	'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.")
		),
		'CAPTCHA'=> array(
			'remote'  	=> _L("Incorrect code.")
		)
	)
);

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"
			        ))
	);	
}
if (VISUAL_CONFIRM == 1 && !(has_rights_on_all_cats($_SESSION['phpld']['user']['level']))) {
	$validators['rules']['CAPTCHA'] = array(
		'required' => true,
	    'remote' => array(
					'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
					'type'=> "post",
                                        'data'=> array (
                                                'action' => "isCaptchaValid",
                                                'table' => "img_verification",
                                                'field' => "CAPTCHA",
                                                'IMAGEHASH' => $imagehash
                                        )
		  )
	);	
}
if (VISUAL_CONFIRM == 2 && !(has_rights_on_all_cats($_SESSION['phpld']['user']['level']))) {
    $validators['rules']['DO_MATH'] = array(
   'required' => true
    );
   
}
$vld = json_custom_encode($validators);
$tpl->assign('validators', $vld);

$validator = new Validator($validators);
//RALUCA: end of JQuery validation related


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

//Check if using RTE (Rich Text Editor)
    $useRTE = (defined ('SUBMIT_USE_RTE') ? SUBMIT_USE_RTE : 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();
if (BOT_CHECK == 1)
check_botscout($client_info['IP'],$_REQUEST['EMAIL'],BOT_KEY);
//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);

// Evaluate payment options

if (ARTICLE_PAY_ENABLE == 1 && PAYPAL_ACCOUNT != '')
{
   $price = array ();
   if (ARTICLE_PAY_FEATURED > 0)
      $price['featured'] = ARTICLE_PAY_FEATURED;

   if (ARTICLE_PAY_NORMAL > 0)
   {
      $price['normal'] = ARTICLE_PAY_NORMAL;
      if (ARTICLE_PAY_ENABLE_FREE)
         $price['free'] = 0;
   }

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

   if (isset ($_POST['ARTICLE_TYPE']))
   {
      $article_type = $_POST['ARTICLE_TYPE'];
      switch (strtolower ($article_type))
      {
         case 'free' :
            break;
         default :
            $recpr_required = 0;
            break;
      }
   }
   else
      $recpr_required = 0;
}

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





$remove_article  = 0;
$review_article  = 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($CategoryID))
    check_if_closed_to_articles($CategoryID);


if (!empty ($article_id))
{
   $article_id = intval ($article_id);
   if (REQUIRE_REGISTERED_USER_ARTICLE == 1 && !empty ($_SESSION['phpld']['user']['id']))
   {
      $check_user = $db->GetOne("SELECT COUNT(*) FROM `{$tables['article']['name']}` WHERE `ID` = ".$db->qstr($article_id)." AND `OWNER_ID` = ".$db->qstr($_SESSION['phpld']['user']['id']));

      $check_double_review = $db->GetOne("SELECT COUNT(*) FROM `{$tables['article_review']['name']}` WHERE `ARTICLE_ID` = ".$db->qstr($article_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_custom_redirect(DOC_ROOT.'/unauthorized.php');
   }

   $remove_article = 1;
   $review_article = 1;
}

$EditUnique    = '';
$MoveToPayment = true;
$action        = 'submit'; //Default action
if (REQUIRE_REGISTERED_USER_ARTICLE == 1 && !empty ($_SESSION['phpld']['user']['id']) && $review_article == 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'])))
{
if (VISUAL_CONFIRM == 2) {
	// do the math
	$n1 = rand(1,9);
	$n2 = rand(1,9);
	$hash = do_math($n1, $n2);

	$_SESSION['DO_MATH_N1'] = $n1;
	$_SESSION['DO_MATH_N2'] = $n2;

	// end do the math
	}
   if (defined ('FORCE_SUBMIT_SESSION') && FORCE_SUBMIT_SESSION == 1)
   {
      generateSubmitSession();
   }

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

   if (REQUIRE_REGISTERED_USER_ARTICLE == 1 && !empty ($_SESSION['phpld']['user']['id']) && !empty ($article_id))
   {
      $sql = "SELECT * FROM `{$tables['article']['name']}` WHERE `ID` = ".$db->qstr($article_id)." AND `OWNER_ID` = ".$db->qstr($_SESSION['phpld']['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 != '')
      $article_type = determine_article_type($data['ARTICLE_TYPE']);

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

   if (has_rights_on_all_cats($_SESSION['phpld']['user']['level'])) {
         $dont_show_captch = 1;
         if (($_SESSION['phpld']['user']['level'] == 1) || ($_SESSION['phpld']['user']['level'] == 3)) {
             $dont_show_pay = 1;
         }
         $tpl->assign('dont_show_captch', $dont_show_captch);
         $tpl->assign('dont_show_pay', $dont_show_pay);
    }
}
else
{
   if (isset($_SESSION['article_submitted'])) {
        unset($_SESSION['article_submitted']);
   }

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

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

   if ($action == 'edit')
      $data = get_table_data('article_review');
   else
      $data = get_table_data('article');

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

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

   //check if user needs approval
   $rights = array();
   $rights = user_needs_approval($_SESSION['phpld']['user']['id'], $data['CATEGORY_ID']);
   if ($action == 'submit' && $rights['addArt'] == 1) {
       $data['STATUS']         = '2';
   } else {
       $data['STATUS']         = '1';
       $tpl->assign('waiting_approval', 1);
   }
   
   $data['IPADDRESS']      = $client_info['IP'];
   if (!empty ($client_info['HOSTNAME']))
      $data['DOMAIN']      = $client_info['HOSTNAME'];

   $data['VALID']          = '1';
    if (!isset ($_POST['ARTICLE_TYPE']))
   {
$article_type = 'normal';
   }
   $data['ARTICLE_TYPE']      = $article_type;

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

   $alreadyFeatured = 0;
   $SecondValidation = 1;

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

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

   //Rules check
   $data['AGREERULES'] = (isset ($_POST['AGREERULES']) && $_POST['AGREERULES'] == 'on' ? 0 : 1);
   
   //RALUCA: JQuery validation related - server side.
   $validator = new Validator($validators);
   $validator_res = $validator->validate($_POST);
   //RALUCA: end of JQuery validation related - server side.
   if (VISUAL_CONFIRM == 2) {
//do the math
if (!isset($_SESSION['DO_MATH_N1']) || !isset($_SESSION['DO_MATH_N2'])) $validator_res['DO_MATH'] = 'Not a legitimate submit';
	if ($_REQUEST['DO_MATH'] != $_SESSION['DO_MATH_N1']+$_SESSION['DO_MATH_N2'])
		$validator_res['DO_MATH'] = 'Please Check Your Math Below';
// end do math
}
   if (empty($validator_res))
   {
      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').'.';
            gotoUnauthorized($reason);
         }
      }

      //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 article directory, has banned words from your submission.');
         gotoUnauthorized($reason);
      }

      if (trim ($data['RELEASE_DATE']) == '')
      		$data['RELEASE_DATE'] = date ('Y-m-d H:i:s');
      
      //Remove variable as we don't need to write it to DB
      if (isset ($data['CAPTCHA']))
         unset ($data['CAPTCHA']);
      if (isset ($data['IMAGEHASH']))
         unset ($data['IMAGEHASH']);
      if (isset ($data['AGREERULES']))
         unset ($data['AGREERULES']);

      //email confirmed related
   
   //if email confirmation not required
   if(EMAIL_CONFIRMATION == 0) {
       $data['OWNER_EMAIL_CONFIRMED'] = '1';
   } else {
       //if has rights no longer requiring email confirmation
       if ($rights['addLink'] == 1) {
           $data['OWNER_EMAIL_CONFIRMED'] = '1';
       }
       //send confirmation email
       elseif (!email_is_confirmed($data['OWNER_EMAIL'])) {
           $data['OWNER_EMAIL_CONFIRMED'] = '0';
           $mail = get_emailer_admin();
    
           //Add email subject
           $emailSubject = "Email Confirmation";
           $mail->Subject = trim ($emailSubject);

           //Add owner email address
           $mail->AddAddress($data['OWNER_EMAIL'], $data['OWNER_NAME']);

           //Add email body
           $emailBody = "Please confirm email address here: ".SITE_URL."confirm_email.php?aid=".$id;
           $mail->Body = trim ($emailBody);

           //Send email
           if (!$mail->Send())
           {
              $error++;
              $tpl->assign('error', $error);
              $errorMsg = $mail->ErrorInfo;
              $tpl->assign('errorMsg', $errorMsg);
           }

           //Clear all addresses (and attachments) for next loop
           $mail->ClearAddresses();
           $mail->ClearAttachments();

           //Free memory
           unset ($unhashedPassword, $mail, $emailBody, $emailSubject);
           $tpl->assign("needs_confirmation", 1);
          //end of confirmation email
        } else {
            $data['OWNER_EMAIL_CONFIRMED'] = '1';
        }
      
   }
   //end of email confirmed
         
      
      $data['ID']        = (!empty ($id) ? intval ($id) : '');
      $data['ARTICLE_TYPE'] = $link_type_int[$article_type];

      switch (strtolower ($article_type))
      {
         case 'featured' :
            $data['FEATURED'] = 1;
            break;
         default :
            break;
      }
     
      if (!empty ($_SESSION['phpld']['user']['id']))
         $data['OWNER_ID'] = $_SESSION['phpld']['user']['id'];

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

      //raluca
         
      if (isset($_SESSION['phpld']['user']['id'])) {
          $rights = user_needs_approval($_SESSION['phpld']['user']['id'], $data['CATEGORY_ID']);
          if ((isset($data['CATEGORY_ID']) && $rights['addArt'] == 1)
            || (has_rights_on_all_cats($_SESSION['phpld']['user']['level']))) {
                $data['PAYED'] = 1;
                $dont_redir_topaypal = 1;
            }
      }
         
      //raluca
      
      $data['OWNER_NOTIF'] = ($price[$article_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']) > ARTICLE_TITLE_MAX_LENGTH ? substr ($data['TITLE'], 0, ARTICLE_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']) > ARTICLE_DESCRIPTION_MAX_LENGTH ? substr ($data['DESCRIPTION'], 0, ARTICLE_DESCRIPTION_MAX_LENGTH - 4).' ...' : trim ($data['DESCRIPTION'])) : '');
      $data['ARTICLE'] = (!empty ($data['ARTICLE']) ? (strlen ($data['ARTICLE']) > ARTICLE_MAX_LENGTH ? substr ($data['ARTICLE'], 0, ARTICLE_MAX_LENGTH - 4).' ...' : trim ($data['ARTICLE'])) : '');
      $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']) : '');

      $RegularArticle_notif = true;
         if ($action == 'edit')
         {

            $data['ARTICLE_ID']   = $article_id;
            $submit_notification = db_replace('article_review', $data, 'ID');
            $RegularArticle_notif   = false;
         }
         else
         {
            $payment_id = $data['ID'];
            unset ($data['MARK_REMOVE']);
            $submit_notification = db_replace('article', $data, 'ID');
         }
         if (!empty ($submit_notification))
         {
            $tpl->assign('posted', true);
            
            
            send_submit_notificationsa($data, $RegularArticle_notif, "article");

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

            //Loop throught each article 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($article_type == 'featured' && ARTICLE_PAY_FEATURED > 0 && $dont_redir_topaypal!=1)
               $payment_redirect = 1;
            elseif($article_type == 'normal' && ARTICLE_PAY_NORMAL > 0 && $dont_redir_topaypal!=1)
               $payment_redirect = 1;

            if ($payment_redirect == 1 && !empty ($payment_id) && $MoveToPayment == true)
            {
               //Move to payment page
               $_SESSION['PRIVACY'] = '1';
               http_custom_redirect(DOC_ROOT."/article_payment.php?id=".$payment_id.($action == 'edit' ? '&mode=review' : ''));
            }
            else
            {
               if (defined ('FORCE_SUBMIT_SESSION') && FORCE_SUBMIT_SESSION == 1)
               {
                  //Submission successfull, generate new submit session
                   
                   generateSubmitSession();
                   
                   //Raluca Nicula: need redirect for right& left side articles to be updated
                   $_SESSION['article_submitted'] = 1;
                   http_custom_redirect(DOC_ROOT."/submit_article.php");
               }
               unset ($_POST, $_GET, $_REQUEST);
            }

            
               if (defined ('FORCE_SUBMIT_SESSION') && FORCE_SUBMIT_SESSION == 1)
               {
                  //Submission successfull, generate new submit session
                  generateSubmitSession();
                  
                  //Raluca Nicula: need redirect for right& left side articles to be updated
                  $_SESSION['article_submitted'] = 1;
               }
               unset ($_POST, $_GET, $_REQUEST);

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

   }
   else
	    $tpl->assign('error', true);
      $tpl->assign($_POST);
   if (VISUAL_CONFIRM == 2) {
		//do the math get error
		  $tpl->assign('error_list', $validator_res);
		  // end do the math
		}
}

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

//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);
$disable_article_reason = DISABLE_ARTICLE_REASON;
$tpl->assign('disablearticlereason', $disable_article_reason);
if (VISUAL_CONFIRM == 1)
   $tpl->assign('captcha_length', CAPTCHA_PHRASE_LENGTH);

$tpl->assign('remove_article', $remove_article);
$tpl->assign('review_article', $review_article);

if (CAT_SELECTION_METHOD == 0)
{
//   $categs = get_regular_categs_tree(0);
   $categs = get_regular_categs_tree_opentoarticles(0);
   $tpl->assign('categs', $categs);
}

//Load Javascript libraries
$load_Javascript = 1;
$tpl->assign('load_Javascript', $load_Javascript);
// custom //
$prurl = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$tpl->assign('prurl', $prurl);
$CategoryTitle = getCategoryTitleByID($data['CATEGORY_ID']);
$tpl->assign('CategoryID', $CategoryID);
// end custom //
$tpl->assign('CategoryTitle', $CategoryTitle);

$tpl->assign($data);

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

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

if ($_SESSION['article_submitted'] == 1) {
    $tpl->assign('posted', true);
    unset($_SESSION['article_submitted']);
}

if ((isset($data['CATEGORY_ID']) && $rights['addArt'] == 1)
|| (has_rights_on_all_cats($_SESSION['phpld']['user']['level']))) {
     $dont_show_captch = 1;
     if (($_SESSION['phpld']['user']['level'] == 1) || ($_SESSION['phpld']['user']['level'] == 3)) {
         $dont_show_pay = 1;
     }
     $tpl->assign('dont_show_captch', $dont_show_captch);
     $tpl->assign('dont_show_pay', $dont_show_pay);
}

if (VISUAL_CONFIRM == 2) {
// do the math
$n1 = $_SESSION['DO_MATH_N1'];
$n2 = $_SESSION['DO_MATH_N2'];

$tpl->assign('DO_MATH_N1', $n1);
$tpl->assign('DO_MATH_N2', $n2);

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

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