<?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 ($_SESSION['phpld']['user']['id']))
{
   $f = $_SERVER['SCRIPT_NAME'];
   if (($p = strrpos ($f, '/')) !== false)
      $f = substr ($f, $p + 1);

   if ($f != 'login.php')
   {
      if (empty ($_SESSION['return']))
         $_SESSION['return'] = request_uri();

      http_custom_redirect('login.php');
   }
}

if (empty($_REQUEST['linkid']))
  http_custom_redirect('index.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);
}

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 (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();
    $_SESSION['imagehash'] = $imagehash;
    $tpl->assign('imagehash', $imagehash);
    //unset($imagehash);
}

//----link types, selected link type -----------------------------------------------------------
$linktypeid = 0;
if (isset($_REQUEST['LINK_TYPE']) && !empty($_REQUEST['LINK_TYPE'])) {
    $linktypeid = intval($_REQUEST['LINK_TYPE']);
}

if (!empty($_REQUEST['linkid']) && !$linktypeid) {
$linktypeid = $db->GetOne("SELECT `LINK_TYPE` FROM `{$tables['link']['name']}` WHERE `ID` = " . $_REQUEST['linkid']);
}

$add_categ_sql = $CategoryID ? " `ID` IN (SELECT `LINK_TYPE` FROM `{$tables['category_link_type']['name']}` WHERE `CATEGORY_ID` = '{$CategoryID}') AND " : '';

$link_types = $db->GetAssoc("SELECT * FROM `{$tables['link_type']['name']}` WHERE {$add_categ_sql} `STATUS` = '2'  ORDER BY `ORDER_ID` ASC");

foreach ($link_types as $link_type_id => $link_type) {
    if ($linktypeid == 0) {
        $linktypeid = $link_type_id;
    }
    $link_types[$link_type_id]['FIELDS'] = $db->GetAssoc("SELECT submit_item.ID, submit_item.FIELD_NAME FROM `{$tables['submit_item']['name']}` AS submit_item, `{$tables['submit_item_status']['name']}` AS item_status WHERE item_status.LINK_TYPE_ID = '{$link_type_id}' AND item_status.ITEM_ID = submit_item.ID AND item_status.STATUS = '2' AND submit_item.IS_DEFAULT = '0'");
}
if (!empty($_REQUEST['linkid'])&& !empty($_REQUEST['LINK_TYPE'])) {
 $linktypeid= $_REQUEST['LINK_TYPE'];
}
$tpl->assign('linktypeid', $linktypeid);
$tpl->assign('link_types', $link_types);

$link_type_details = $db->GetRow("SELECT * FROM `{$tables['link_type']['name']}` WHERE `ID` = '{$linktypeid}'");
$tpl->assign('link_type_details', $link_type_details);

$link_price = $link_type_details['PRICE'];
//----/link types, selected link type ----------------------------------------------------------
//----submit items -----------------------------------------------------------------------------
$sqlSubmitItems = "
	SELECT submit_item.*, item_status.STATUS, item_status.LINK_TYPE_ID 
	FROM `{$tables['submit_item']['name']}` AS submit_item, `{$tables['submit_item_status']['name']}` AS item_status 
	WHERE item_status.ITEM_ID = submit_item.ID 
		AND item_status.LINK_TYPE_ID = '{$linktypeid}'
		AND item_status.STATUS = '2' 
	ORDER BY `ORDER_ID` ASC
";
$submit_items = $db->GetAll($sqlSubmitItems);

foreach ($submit_items as $submit_item_id => $submit_item) {
	if ($submit_item['TYPE'] == 'DROPDOWN') {
		$submit_items[$submit_item_id]['OPTIONS'] = get_submit_item_list($submit_item['ID']);
	}
}

$tpl->assign("submit_items", $submit_items);
//----/submit items ----------------------------------------------------------------------------
//----validation -------------------------------------------------------------------------------
$submit_items_vld = get_submit_items_validators($linktypeid);

$validators = array(
    'rules' => array(
        'TITLE' => array(
            'required' => true,
            'minlength' => TITLE_MIN_LENGTH,
            'maxlength' => TITLE_MAX_LENGTH,
            'remote' => array(
                'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
                'type' => "post",
                'data' => array(
                    'action' => "isTitle",
                    'table' => "link",
                    'field' => "TITLE",
                    'id' => (!empty($_REQUEST['linkid']) ? clean_string_paranoia($_REQUEST['linkid']) : 0)
                )
            )
        ),
        '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"
                )
            )
        ),
        'EXPIRY_DATE' => array(
            'remote' => array(
                'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
                'type' => "post",
                'data' => array(
                    'action' => "isDate",
                    'table' => "link",
                    'field' => "EXPIRY_DATE"
                )
            )
        ),
        'HITS' => array(
            'number' => true
        ),
        'PAGERANK' => array(
            'min' => -1,
            'max' => 10
        )
        
    ),
    '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.")
        )
    )
);

if (SUBMIT_USE_RTE === 0) {
    $validators['rules']['DESCRIPTION'] = array(
        'minlength' => DESCRIPTION_MIN_LENGTH,
        'maxlength' => DESCRIPTION_MAX_LENGTH
    );
}
if (ENABLE_META_TAGS == 1){
    $validators['rules']['META_DESCRIPTION'] = array(
     	'required' => true,
            'minlength' => META_DESCRIPTION_MIN_LENGTH,
            'maxlength' => META_DESCRIPTION_MAX_LENGTH
    );
	}
	if (ENABLE_META_TAGS == 1){
    $validators['rules']['META_KEYWORDS'] = array(
   'required' => true,
            'minlength' => META_KEYWORDS_MIN_LENGTH,
            'maxlength' => META_KEYWORDS_MAX_LENGTH
    );
	}

if (VISUAL_CONFIRM == 2) {
    $validators['rules']['DO_MATH'] = array(
   'required' => true
    );
   
}

if (VISUAL_CONFIRM == 1) {
    $validators['rules']['CAPTCHA'] = array(
        'remote' => array(
            'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
            'type' => "post",
            'data' => array(
                'action' => "isCaptchaValid",
                'table' => "img_verification",
                'field' => "CAPTCHA",
                'IMAGEHASH' => $imagehash
        ))
    );
    $validators['messages']['CAPTCHA'] = array('remote' => _L("Incorrect code."));
}
$recpr_required = 0;

foreach ($submit_items_vld as $k => $v) {
    switch ($k) {
        case 'TITLE':
        case 'CATEGORY_ID':
        case 'EXPIRY_DATE':
        case 'HITS':
        case 'PAGERANK':
        case 'META_DESCRIPTION':
      //  case 'DESCRIPTION':
            break;
        case 'RECPR_URL':
            if(isset($v['required']) && $v['required'] === true ) {
           		 $recpr_required = 1;
                $validators['rules']['RECPR_URL'] = array(
                    'required' => true,
                    'remote' => array(
                        'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
                        'type' => 'post',
                        'data' => array(
                            'action' => 'isRecprOnline',
                            'table'  => "link",
                            'field'  => "RECPR_URL",
                            'URL' => "function() { return $('#URL').val(); }"
                        )
                    )
                );
                $validators['messages']['RECPR_URL'] = array('remote' => 'Invalid reciprocal link');
                
            } else {
            	$recpr_required = 0;
            }
            break;
        default:
            $validators['rules'][$k] = $v;
            foreach ($v as $kk => $vv) {
                if (($vv['data']['action'] == 'isURLOnline')) {
                    $validators['rules'][$k][$kk]['data']['id'] = (!empty($_REQUEST['linkid']) ? clean_string_paranoia($_REQUEST['linkid']) : 0);
                }
            }
    }
}



$validators['rules']['AGREERULES'] = array('required' => true);

$vld = json_custom_encode($validators);

$tpl->assign('valid', $validators);
$tpl->assign('validators', $vld);

$validator = new Validator($validators);
//----/validation ------------------------------------------------------------------------------
//----path--------------------------------------------------------------------------------------
$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);
//----/path-------------------------------------------------------------------------------------
//Array usually for radio buttons with answers yes/no
$tpl->assign('yes_no', array(1 => _L('Yes'), 0 => _L('No')));

//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
$recpr_required = (in_array('RECPR_URL', $link_types[$_REQUEST['LINK_TYPE']]['FIELDS'])) ? '1' : '0';
$ShowReciprField = ($recpr_required == 0 ? 0 : 1);

$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($CategoryID)) {
    check_if_closed_to_links($CategoryID);
}

if (!empty($link_id)) {
    $link_id = intval($link_id);
    $add_categs = $db->GetAll("SELECT * FROM `{$tables['additional_category']['name']}` WHERE `LINK_ID` = '{$link_id}'");
    $tpl->assign("add_categs", $add_categs);
	$add_links = $db->GetAll("SELECT * FROM `{$tables['additional_link']['name']}` WHERE `LINK_ID` = '{$link_id}'");
	 $tpl->assign("add_links", $add_links);
    if (!empty($_SESSION['phpld']['user']['id'])) {
        $check_user = $db->GetOne("SELECT COUNT(*) FROM `{$tables['link']['name']}` WHERE `ID` = " . $db->qstr($link_id) . " AND `OWNER_ID` = " . $db->qstr($_SESSION['phpld']['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_custom_redirect(DOC_ROOT . '/unauthorized.php');
    }

    $remove_link = 1;
    $review_link = 1;
}

$EditUnique = '';
$MoveToPayment = true;
$action = 'submit'; //Default action
if (!empty($_SESSION['phpld']['user']['id']) && $review_link == 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 (!empty($_SESSION['phpld']['user']['id']) && !empty($link_id)) {
        $sql = "SELECT * FROM `{$tables['link']['name']}` WHERE `ID` = " . $db->qstr($link_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']);
    // Melfel

    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'])) : $owner_details['OWNER_NAME']);
    }

    if ($action != 'edit') {
        $data['OWNER_EMAIL'] = (!empty($data['OWNER_EMAIL']) ? $data['OWNER_EMAIL'] : $owner_details['OWNER_EMAIL']);
    }
    $data['RECPR_REQUIRED'] = $recpr_required;
    $link_type = $_REQUEST['LINK_TYPE'];

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

    if ((isset($data['CATEGORY_ID']) && $rights['addLink'] == 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);
    }
} else {
    if (isset($_SESSION['link_submitted'])) {
        unset($_SESSION['link_submitted']);
    }

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

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

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

    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['addLink'] == 1) || (($link_type_details['REQUIRE_APPROVAL'] == 0) && (empty($link_type_details['PRICE']))))) {
        $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';
    $data['LINK_TYPE'] = $_REQUEST['LINK_TYPE'];
    $data['RECPR_REQUIRED'] = $recpr_required;
    if ($recpr_required) {
        $data['RECPR_VALID'] = '2'; // OK Status
        $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 (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' && $_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);
    $PageRank = 1;
    if (LIMIT_PR == '1') {
        require_once 'include/pagerank.php';
        $pr = get_page_rank($data['URL']);
        if ($pr <= PR_MIN) {
            $PageRank = 0;
            $tpl->assign('pr_error', 'Sorry Your Site\'s Pagerank is not greater than or equal to ' . PR_MIN);
        }
    }
    $tpl->assign('secondBanCheck', $secondBanCheck);

    //Rules check
    $data['AGREERULES'] = (isset($_POST['AGREERULES']) && $_POST['AGREERULES'] == 'on' ? 0 : 1);
    $data['OWNER_NEWSLETTER_ALLOW'] = (isset($_POST['OWNER_NEWSLETTER_ALLOW']) && $_POST['OWNER_NEWSLETTER_ALLOW'] == 'on' ? 1 : 0);

   $validator = new Validator($validators);
	$validator_res = $validator->validate($_POST);

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

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

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

        //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';
            } elseif (!email_is_confirmed($data['OWNER_EMAIL']) && $data['OWNER_EMAIL'] != '') {
                //send confirmation email
                //send only if email has not been confirmed already (exists in link table/user table and is confirmed

                $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?lid=" . $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['NOFOLLOW'] = $link_types[$_REQUEST['LINK_TYPE']]['NOFOLLOW'];
        $data['FEATURED'] = $link_types[$_REQUEST['LINK_TYPE']]['FEATURED'];

        if (!empty($_SESSION['phpld']['user']['id']))
            $data['OWNER_ID'] = $_SESSION['phpld']['user']['id'];

        //raluca

        if (isset($_SESSION['phpld']['user']['id'])) {
            $rights = user_needs_approval($_SESSION['phpld']['user']['id'], $data['CATEGORY_ID']);
            if ((isset($data['CATEGORY_ID']) && $rights['addLink'] == 1)
                    || (has_rights_on_all_cats($_SESSION['phpld']['user']['level']))) {
                $data['PAYED'] = 1;
                $dont_redir_topaypal = 1;
            }
        }

        //raluca


        $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'])) : '');
        }

        $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;

            foreach ($submit_items as $key_id => $submit_item) {
                   if ($submit_item['TYPE'] == 'IMAGE') {
                       $si_images[$key_id] = $submit_item;
                   } elseif ($submit_item['TYPE'] == 'FILE') {
                       $si_files[$key_id] = $submit_item;
                  } elseif ($submit_item['TYPE'] == 'VIDEO') {
                       $si_videos[$key_id] = $submit_item;
                   } else {
						$data[$submit_item['FIELD_NAME']] = $_REQUEST[$submit_item['FIELD_NAME']];
                   }
               }

            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'];

            $data['LINK_ID'] = $payment_id = $link_id;

            //RALUCA: replaced following line since zip codes starting with 0 were not inserted properly into the db
            //$submit_notification = $db->Replace($tables['link_review']['name'], $data, 'ID', true);
            $submit_notification = db_replace('link_review', $data, 'ID');

            $RegularLink_notif = false;
            // Start Additional Categories section
            if (isset($_REQUEST['ADD_CATEGORY_ID']) && is_array($_REQUEST['ADD_CATEGORY_ID']) && ($link_types[$_REQUEST['LINK_TYPE']]['MULTIPLE_CATEGORIES'] > 0)) {
                $add_cat_data['LINK_ID'] = $data['LINK_ID'];
                $db->Execute("DELETE FROM `{$tables['additional_category_review']['name']}` WHERE `LINK_ID` = " . $db->qstr($add_cat_data['LINK_ID']));
                for ($i = 0; $i < $link_types[$_REQUEST['LINK_TYPE']]['MULTIPLE_CATEGORIES'] - 1; $i++) {
                    $add_cat_id = trim($_REQUEST['ADD_CATEGORY_ID'][$i]);
                    if (!empty($add_cat_id)) {
                        $add_cat_data['CATEGORY_ID'] = $_REQUEST['ADD_CATEGORY_ID'][$i];
                        $db->Execute("INSERT INTO `{$tables['additional_category_review']['name']}` (`LINK_ID`, `CATEGORY_ID`)
                                            VALUES (" . $db->qstr($add_cat_data['LINK_ID']) . ", " . $db->qstr($add_cat_data['CATEGORY_ID']) . ")");
                    }
                }
            }
            // End Additional Categories section
            // Start Additional Links section
            if (isset($_REQUEST['ADD_LINK_URL']) && is_array($_REQUEST['ADD_LINK_URL']) && ($link_types[$_REQUEST['LINK_TYPE']]['DEEP_LINKS'] > 0)) {
                $add_link_data['LINK_ID'] = $data['LINK_ID'];
                $db->Execute("DELETE FROM `{$tables['additional_link_review']['name']}` WHERE `LINK_ID` = " . $db->qstr($add_link_data['LINK_ID']));
                for ($i = 0; $i < $link_types[$_REQUEST['LINK_TYPE']]['DEEP_LINKS']; $i++) {
                    $add_link_url = trim($_REQUEST['ADD_LINK_URL'][$i]);
                    if (!empty($add_link_url)) {
                        $add_link_url = urlencode($add_link_url);
                        $add_link_url = (substr($add_link_url, 0, 7) != 'http://' ? 'http://' . $add_link_url : $add_link_url);
                        $add_link_data['URL'] = $add_link_url;
                        $add_link_data['TITLE'] = $_REQUEST['ADD_LINK_TITLE'][$i] ? $_REQUEST['ADD_LINK_TITLE'][$i] : $_REQUEST['ADD_LINK_URL'][$i];
                        $db->Execute("INSERT INTO `{$tables['additional_link_review']['name']}` (`LINK_ID`, `TITLE`, `URL`)
                                            VALUES (" . $db->qstr($add_link_data['LINK_ID']) . ", " . $db->qstr($add_link_data['TITLE']) . ", " .
                                $db->qstr($add_link_data['URL']) . ")");
                    }
                }
            }
            // End Additional Links section
            //submit items: images
            foreach ($si_images as $key_id => $image) {
                if (!empty($_FILES[$image['FIELD_NAME']]['name'])) {
                    $ext = strtolower(end(explode('.', $_FILES[$image['FIELD_NAME']]['name'])));
                    $name = $data['LINK_ID'] . "_" . $key_id . "." . $ext;

                    if (file_exists(INSTALL_PATH . '/uploads/reviews/' . $name)) {
                        unlink(INSTALL_PATH . '/uploads/reviews/' . $name);
                    }
                    if (file_exists(INSTALL_PATH . '/uploads/reviews/thumb/' . $name)) {
                        unlink(INSTALL_PATH . '/uploads/reviews/thumb/' . $name);
                    }
                    resizeImg($_FILES[$image['FIELD_NAME']]['tmp_name'], INSTALL_PATH . 'uploads/reviews/' . $name, 400, 400);
                    resizeImg($_FILES[$image['FIELD_NAME']]['tmp_name'], INSTALL_PATH . 'uploads/reviews/thumb/' . $name, 150, 150);
                    $db->Execute("UPDATE `{$tables['link_review']['name']}` SET `" . $image['FIELD_NAME'] . "` = " . $db->qstr($name) . " WHERE `LINK_ID`=" . $db->qstr($data['LINK_ID']));
                } elseif ($_REQUEST["MARK_REMOVE_" . $image['FIELD_NAME']] == '1') {
                    $db->Execute("UPDATE `{$tables['link_review']['name']}` SET `" . $image['FIELD_NAME'] . "` = '' WHERE `LINK_ID`=" . $db->qstr($data['LINK_ID']));
                } else {
                    $link = getFullLinkInfo($data['LINK_ID']);
                    if (file_exists(INSTALL_PATH . '/uploads/' . $link[$image['FIELD_NAME']])) {
                        copy(INSTALL_PATH . '/uploads/' . $link[$image['FIELD_NAME']], INSTALL_PATH . '/uploads/reviews/' . $link[$image['FIELD_NAME']]);
                    }
                    if (file_exists(INSTALL_PATH . '/uploads/thumb/' . $link[$image['FIELD_NAME']])) {
                        copy(INSTALL_PATH . '/uploads/thumb/' . $link[$image['FIELD_NAME']], INSTALL_PATH . '/uploads/reviews/thumb/' . $link[$image['FIELD_NAME']]);
                    }

                    $db->Execute("UPDATE `{$tables['link_review']['name']}` SET `" . $image['FIELD_NAME'] . "` = " . $db->qstr($link[$image['FIELD_NAME']]) . " WHERE `LINK_ID`=" . $db->qstr($data['LINK_ID']));
                }
            }
            //end of submit items: images
            ////submit items: files
            foreach ($si_files as $key_id => $file) {
                if (!empty($_FILES[$file['FIELD_NAME']]['name'])) {
                    $allowed = array("pdf", "xls", "xlsx", "doc", "docx", "zip", "rar", "txt", "rtf", "csv");
                    $ext = strtolower(end(explode('.', $_FILES[$file['FIELD_NAME']]['name'])));
                    $name = $data['LINK_ID'] . "_" . $key_id . "." . $ext;

                    if (file_exists(INSTALL_PATH . '/uploads/reviews/' . $name)) {
                        unlink(INSTALL_PATH . '/uploads/reviews/' . $name);
                    }
                    if (in_array($ext, $allowed)) {
                        if (move_uploaded_file($_FILES[$file['FIELD_NAME']]['tmp_name'], INSTALL_PATH . 'uploads/reviews/' . $name)) {
                            $db->Execute("UPDATE `{$tables['link_review']['name']}` SET `" . $file['FIELD_NAME'] . "` = " . $db->qstr($name) . " WHERE `LINK_ID`=" . $db->qstr($data['LINK_ID']));
                        }
                    }
                } elseif ($_REQUEST["MARK_REMOVE_" . $file['FIELD_NAME']] == '1') {
                    $db->Execute("UPDATE `{$tables['link_review']['name']}` SET `" . $file['FIELD_NAME'] . "` = '' WHERE `LINK_ID`=" . $db->qstr($data['LINK_ID']));
                } else {
                    $link = getFullLinkInfo($data['LINK_ID']);
                    if (file_exists(INSTALL_PATH . '/uploads/' . $link[$file['FIELD_NAME']])) {
                        copy(INSTALL_PATH . '/uploads/' . $link[$file['FIELD_NAME']], INSTALL_PATH . '/uploads/reviews/' . $link[$file['FIELD_NAME']]);
                    }
                    $db->Execute("UPDATE `{$tables['link_review']['name']}` SET `" . $file['FIELD_NAME'] . "` = " . $db->qstr($link[$file['FIELD_NAME']]) . " WHERE `LINK_ID`=" . $db->qstr($data['LINK_ID']));
                }
            }
            //end of submit items: files
			//submit items: videos
			 foreach ($si_videos as $key => $file) {
                        if (!empty ($_FILES[$file['FIELD_NAME']]['name'])) {
                            $allowed = array("avi", "wmv", "mov", "mpg");
                            $ext = strtolower(end(explode('.', $_FILES[$file['FIELD_NAME']]['name'])));
                            $convertTo = 'flv';
                            $name = $data['ID']."_".$key_id.".".$ext;
                            $destName = $data['ID']."_".$key_id.".".$convertTo;

                            // Unlink existing file and thmb if exists
                            if (file_exists(INSTALL_PATH.'/uploads/'.$destName)) {
                                unlink(INSTALL_PATH.'/uploads/'.$destName);
                            }
                            if (file_exists(INSTALL_PATH.'/uploads/thumb/'.$destName.'.jpg')) {
                                unlink(INSTALL_PATH.'/uploads/thumb/'.$destName.'.jpg');
                            }
                            if (in_array($ext, $allowed)) {
                                thumbnailVideo($_FILES[$file['FIELD_NAME']]['tmp_name'], INSTALL_PATH.'uploads/thumb/'.$destName.'.jpg', '128x96', 1);
                                convertVideo($_FILES[$file['FIELD_NAME']]['tmp_name'], INSTALL_PATH.'uploads/'.$destName, $convertTo, '704x576');
                                $db->Execute("UPDATE `{$tables['link']['name']}` SET `".$file['FIELD_NAME']."` = ".$db->qstr($destName)." WHERE `ID`=".$db->qstr($data['ID']));
                                $data[$file['FIELD_NAME']] = $destName;
                            }
                        }
                    } //end of submit items: videos
        } else {
            $payment_id = $data['ID'];

            unset($data['MARK_REMOVE']);
            //RALUCA: replaced following line since zip codes starting with 0 were not inserted properly into the db
            //$submit_notification = $db->Replace($tables['link']['name'], $data, 'ID', true);
            // Add additional submit items to the LINK table

            foreach ($submit_items as $key_id => $submit_item) {
                $data[$submit_item['FIELD_NAME']] = $_REQUEST[$submit_item['FIELD_NAME']];
                if ($submit_item['TYPE'] == 'IMAGE') {
                    $si_images[$key_id] = $submit_item;
                }
                if ($submit_item['TYPE'] == 'FILE') {
                    $si_files[$key_id] = $submit_item;
                }
					if ($submit_item['TYPE'] == 'VIDEO') {
                       $si_videos[$key_id] = $submit_item;
					}
            }

            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'];

            $submit_notification = db_replace('link', $data, 'ID');

            // Start Additional Links section
            $new_id = $db->GetOne("SELECT MAX(`ID`) FROM `{$tables['link']['name']}`");
            
            // handle the submit item image groups.
            foreach ($submit_items as $key_id => $submit_item) {
                if ($submit_item['TYPE'] == "IMAGEGROUP") {
                        $imagegroupname = $submit_item['FIELD_NAME'];
                        $imagegroupid = $_REQUEST[$imagegroupname];
                        $groupdata = $_SESSION['imagegroups'][$imagegroupid];
                        $db->Execute("INSERT INTO `{$tables['imagegroup']['name']}` (DATE_MODIFIED, DATE_ADDED) VALUES (now(),now())");
                        $new_group_id = $db->GetOne("SELECT MAX(`GROUPID`) FROM `{$tables['imagegroup']['name']}`");
                        $db->Execute("UPDATE `{$tables['link']['name']}` SET `".$submit_item['FIELD_NAME']."` = ".$db->qstr($new_group_id)." WHERE `ID`=".$db->qstr($new_id));
                        foreach ($groupdata as $image) {
                                $ext = strtolower(end(explode('.', $image)));
                                $name = $new_id."_" . uniqid() . "." . $ext;
                                if (file_exists(INSTALL_PATH.'/uploads/'.$name)) {
                                        unlink(INSTALL_PATH.'/uploads/'.$name);
                                }
                                if (file_exists(INSTALL_PATH.'/uploads/thumb/'.$name)) {
                                        unlink(INSTALL_PATH.'/uploads/thumb/'.$name);
                                }
                                error_log("saving $image to " . INSTALL_PATH . "uploads/" . $name);
                                resizeImg($image, INSTALL_PATH.'uploads/'.$name, 400, 400);
                                resizeImg($image, INSTALL_PATH.'uploads/thumb/'.$name, 150, 150);
							
                                $db->Execute("INSERT INTO `{$tables['imagegroupfile']['name']}` (GROUPID,IMAGE) VALUES (" . $db->qstr($new_group_id) . "," .  $db->qstr($name) . ")");
                        }

                $dir =  INSTALL_PATH.'uploads/tmp/';
				unlinkRecursive($dir);
                }
            }            

            if (isset($_REQUEST['ADD_LINK_URL']) && is_array($_REQUEST['ADD_LINK_URL']) && ($link_types[$_REQUEST['LINK_TYPE']]['DEEP_LINKS'] > 0)) {
                for ($i = 0; $i < $link_types[$_REQUEST['LINK_TYPE']]['DEEP_LINKS']; $i++) {
                    $add_link_url = trim($_REQUEST['ADD_LINK_URL'][$i]);
                    if (!empty($add_link_url)) {
                        $add_link_url = (substr($add_link_url, 0, 7) != 'http://' ? 'http://' . $add_link_url : $add_link_url);
                        $add_link_data['URL'] = $add_link_url;

                        $add_link_data['LINK_ID'] = $new_id;
                        $add_link_data['TITLE'] = $_REQUEST['ADD_LINK_TITLE'][$i] ? $_REQUEST['ADD_LINK_TITLE'][$i] : $_REQUEST['ADD_LINK_URL'][$i];
                        db_replace('additional_link', $add_link_data, 'ID');
                    }
                }
            }
            // End Additional Links section
            //submit items: images
            foreach ($si_images as $key_id => $image) {
                if (!empty($_FILES[$image['FIELD_NAME']]['name'])) {
                    $ext = strtolower(end(explode('.', $_FILES[$image['FIELD_NAME']]['name'])));
                    $name = $new_id . "_" . $key_id . "." . $ext;

                    if (file_exists(INSTALL_PATH . '/uploads/' . $name)) {
                        unlink(INSTALL_PATH . '/uploads/' . $name);
                    }
                    if (file_exists(INSTALL_PATH . '/uploads/thumb/' . $name)) {
                        unlink(INSTALL_PATH . '/uploads/thumb/' . $name);
                    }
                    resizeImg($_FILES[$image['FIELD_NAME']]['tmp_name'], INSTALL_PATH . 'uploads/' . $name, 400, 400);
                    resizeImg($_FILES[$image['FIELD_NAME']]['tmp_name'], INSTALL_PATH . 'uploads/thumb/' . $name, 150, 150);
                    $db->Execute("UPDATE `{$tables['link']['name']}` SET `" . $image['FIELD_NAME'] . "` = " . $db->qstr($name) . " WHERE `ID`=" . $db->qstr($new_id));
                }
            }
            //end of submit items: images
            ////submit items: files
            foreach ($si_files as $key_id => $file) {
                if (!empty($_FILES[$file['FIELD_NAME']]['name'])) {
                    $allowed = array("pdf", "xls", "xlsx", "doc", "docx", "zip", "rar", "txt", "rtf", "csv");
                    $ext = strtolower(end(explode('.', $_FILES[$file['FIELD_NAME']]['name'])));
                    $name = $new_id . "_" . $key_id . "." . $ext;

                    if (file_exists(INSTALL_PATH . '/uploads/' . $name)) {
                        unlink(INSTALL_PATH . '/uploads/' . $name);
                    }
                    if (file_exists(INSTALL_PATH . '/uploads/thumb/' . $name)) {
                        unlink(INSTALL_PATH . '/uploads/thumb/' . $name);
                    }
                    if (in_array($ext, $allowed)) {
                        if (move_uploaded_file($_FILES[$file['FIELD_NAME']]['tmp_name'], INSTALL_PATH . 'uploads/' . $name)) {
                            $db->Execute("UPDATE `{$tables['link']['name']}` SET `" . $file['FIELD_NAME'] . "` = " . $db->qstr($name) . " WHERE `ID`=" . $db->qstr($new_id));
                        }
                    }
                }
            }
            //end of submit items: files
			//submit items: videos
			 foreach ($si_videos as $key => $file) {
                        if (!empty ($_FILES[$file['FIELD_NAME']]['name'])) {
                            $allowed = array("avi", "wmv", "mov", "mpg");
                            $ext = strtolower(end(explode('.', $_FILES[$file['FIELD_NAME']]['name'])));
                            $convertTo = 'flv';
                            $name = $data['ID']."_".$key_id.".".$ext;
                            $destName = $data['ID']."_".$key_id.".".$convertTo;

                            // Unlink existing file and thmb if exists
                            if (file_exists(INSTALL_PATH.'/uploads/'.$destName)) {
                                unlink(INSTALL_PATH.'/uploads/'.$destName);
                            }
                            if (file_exists(INSTALL_PATH.'/uploads/thumb/'.$destName.'.jpg')) {
                                unlink(INSTALL_PATH.'/uploads/thumb/'.$destName.'.jpg');
                            }
                            if (in_array($ext, $allowed)) {
                                thumbnailVideo($_FILES[$file['FIELD_NAME']]['tmp_name'], INSTALL_PATH.'uploads/thumb/'.$destName.'.jpg', '128x96', 1);
                                convertVideo($_FILES[$file['FIELD_NAME']]['tmp_name'], INSTALL_PATH.'uploads/'.$destName, $convertTo, '704x576');
                                $db->Execute("UPDATE `{$tables['link']['name']}` SET `".$file['FIELD_NAME']."` = ".$db->qstr($destName)." WHERE `ID`=".$db->qstr($data['ID']));
                                $data[$file['FIELD_NAME']] = $destName;
                            }
                        }
                    } //end of submit items: videos
            // Start Additional Categories section
            if (isset($_REQUEST['ADD_CATEGORY_ID']) && is_array($_REQUEST['ADD_CATEGORY_ID']) && ($link_types[$_REQUEST['LINK_TYPE']]['MULTIPLE_CATEGORIES'] > 0)) {
                for ($i = 0; $i < $link_types[$_REQUEST['LINK_TYPE']]['MULTIPLE_CATEGORIES'] - 1; $i++) {
                    $add_cat_id = trim($_REQUEST['ADD_CATEGORY_ID'][$i]);
                    if (!empty($add_cat_id)) {
                        $add_cat_data['LINK_ID'] = $new_id;
                        $add_cat_data['CATEGORY_ID'] = $_REQUEST['ADD_CATEGORY_ID'][$i];
                        $res = db_replace('additional_category', $add_cat_data);
                    }
                }
            }
            // End Additional Categories section
        }

        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) : '');

            // Payment redirection
            if ($link_price > 0 && !empty($payment_id) && $MoveToPayment == true && $dont_redir_topaypal != 1) {
                //Move to payment page
                //added 6-24-07
                $_SESSION['PRIVACY'] = '1';
                //end add
                http_custom_redirect(DOC_ROOT . "/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 links to be updated
                    $_SESSION['link_submitted'] = 1;
                    //http_custom_redirect(DOC_ROOT."/submit.php");
                }

                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
		}
    }
}

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

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

if (CAT_SELECTION_METHOD == 0 || $link_type_details['MULTIPLE_CATEGORIES'] != '')
{
   //$categs = get_regular_categs_tree(0);
   $categs = get_regular_categs_tree_opentolinks(0);
   $tpl->assign('categs', $categs);
}

$tpl->assign('SubscriptionEnabled', $SubscriptionEnabled);
$tpl->assign('payment_um', $payment_um);

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

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

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

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

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

if ((isset($data['CATEGORY_ID']) && $rights['addLink'] == 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);
// end do math
	}
//Make output
echo $tpl->fetch('submit_review.tpl', $id);

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