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

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

$error = 0;
$errorMsg = '';

$mode_options = array('register' => 'register', 'edit' => 'edit', 'sendpassword' => 'sendpassword', 'confirm' => 'confirm', 'thankyou' => 'thankyou', 'confirmed' => 'confirmed', 'logged' => 'logged');
$agreed_options = array('true' => 'true', 'false' => 'false');

if (array_key_exists($_REQUEST['mode'], $mode_options))
    $mode = $_REQUEST['mode'];
else
    $mode = 'register';

if (!empty($_REQUEST['agreed'])) {
    if (!empty($_REQUEST['agreed']) && array_key_exists($_REQUEST['agreed'], $agreed_options))
        $agreed = $_REQUEST['agreed'];
    else
        $agreed = 'false';
}

$tpl->assign('load_Javascript', 'true');

$exclude_user_id = 0;

switch ($mode) {
    case 'thankyou' :
        $tpl->assign('thank_you', 1);
        break;
    case 'confirmed':
        $tpl->assign('confirmed', 1);
        break;
    case 'confirm' :
        $tpl->assign('confirm', 1);
        if (empty($_SESSION['phpld']['user']['id'])) {
            $user_id = (!empty($_REQUEST['uid']) ? clean_string_paranoia($_REQUEST['uid']) : 0);
            $confirm_key = (!empty($_REQUEST['key']) ? clean_string_paranoia($_REQUEST['key']) : 0);

            if (!empty($user_id) && !empty($confirm_key)) {
                $data = $db->GetRow("SELECT * FROM `{$tables['user']['name']}` WHERE `ID` = " . $db->qstr($user_id) . " AND `CONFIRM` = " . $db->qstr($confirm_key));
                if (!empty($data)) {
                    $data['PASSWORD'] = $data['NEW_PASSWORD'];
                    $data['NEW_PASSWORD'] = '';
                    $data['CONFIRM'] = '';

                    $where = " `ID` = " . $db->qstr($user_id);

                    if ($db->AutoExecute($tables['user']['name'], $data, 'UPDATE', $where))
                        $tpl->assign('password_recovered', 1);
                    else
                        $tpl->assign('password_recovered', 0);
                } else
                    die("!! ERROR !!\n<br />\n<br />\nSeems like an attack! Your access has been blocked.\n");
            }
        }
        break;
    case 'logged':
        $tpl->assign('user_logged', 1);
        $profileUpdate = (!empty($_SESSION['phpld']['user']['profileUpdate']) ? $_SESSION['phpld']['user']['profileUpdate'] : 0);
        $tpl->assign('profileUpdate', $profileUpdate);
        $_SESSION['phpld']['user']['profileUpdate'] = 0;
        break;
    case 'sendpassword' :
        //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);
        }
        $tpl->assign('send_password', 1);

        //RALUCA: JQuery validation related
        $validators = array(
            'rules' => array(
                'LOGIN' => array(
                    'required' => true,
                    'minlength' => USER_LOGIN_MIN_LENGTH,
                    'maxlength' => USER_LOGIN_MAX_LENGTH,
                    'remote' => array(
                        'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
                        'type' => "post",
                        'data' => array(
                            'action' => "isUsername",
                            'table' => "user",
                            'field' => "LOGIN"
                        )
                    )
                ),
                'EMAIL' => array(
                    'email' => true,
                    'required' => true,
                    'remote' => array(
                        'url' =>  DIRECTORY_ROOT . "/include/validation_functions.php",
                        'type' => "post",
                        'data' => array(
                            'action' => "isBannedEmail",
                            'table' => "user",
                            'field' => "EMAIL"
                        )
                    )
                )
            ),
            'messages' => array(
                'EMAIL' => array(
                    'remote' => _L("This email is already in our database or banned.")
                ),
                'LOGIN' => array(
                    'remote' => _L("This is not a valid username.")
                ),
                'CAPTCHA' => array(
                    'remote' => _L("Incorrect code.")
                )
            )
        );

        if (VISUAL_CONFIRM == 1) {
            $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) {
    $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

        if (empty($_POST['submit'])) {
			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
	}

        } else {
            $data = get_table_data('user');

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

            //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)) {
                $user = $db->GetRow("SELECT `ID`, `LOGIN`, `NAME`, `EMAIL` FROM `{$tables['user']['name']}` WHERE `LOGIN` LIKE " . $db->qstr($data['LOGIN']) . " AND `EMAIL` LIKE " . $db->qstr($data['EMAIL']) . " AND `ACTIVE` = '1'");

                if (is_array($user) && !empty($user)) {
                    $data['ID'] = $user['ID'];

               $new_password         = create_password(8);
               $data['CONFIRM']      = create_password(6);
               $data['NEW_PASSWORD'] = encrypt_password($new_password);
               unset ($data['user'], $data['email']);
                    $dbUpdate = $db->Replace($tables['user']['name'], $data, 'ID', true);

                  if ($dbUpdate == 1)
                  {
                        $user['PASSWORD'] = $new_password;
                        $passwordRecoverUrl = (substr(SITE_URL, -1) == "/" ? SITE_URL : SITE_URL . "/");
                        $passwordRecoverUrl .= "profile.php?mode=confirm&uid={$user['ID']}&key={$data['CONFIRM']}";

                        $loginURL = (substr(SITE_URL, -1, 1) == '/' ? SITE_URL : SITE_URL . '/') . 'login.php';


                        //Get email template
                        $emailTpl = get_email_template('NTF_USER_PASSWORD_TPL');

                        //$tplSql = "SELECT `TITLE`, `SUBJECT`, `BODY` FROM `{$tables['email_tpl']['name']}` WHERE `ID` = " . $db->qstr(NTF_USER_PASSWORD_TPL);
                        //$emailTpl = $db->GetRow($tplSql);

                        //if email tpl is available
                        if (is_array($emailTpl) && !empty($emailTpl)) {
                            $mail = get_emailer_admin();
                            $mail->AddAddress($user['EMAIL'], $user['NAME']);

                            //Add email subject
                            $emailSubject = $emailTpl['SUBJECT'];
                            $emailSubject = str_replace('{PASSWORD_RECOVER_URL}', $passwordRecoverUrl, $emailSubject);
                            $emailSubject = str_replace('{USER_LOGIN_PAGE}', $loginURL, $emailSubject);
                            $emailSubject = replace_email_vars($emailSubject, $user, 6);
                            $emailSubject = replace_email_vars($emailSubject, $user, 5);
                            $mail->Subject = trim($emailSubject);

                            //Add email body
                            $emailBody = $emailTpl['BODY'];
                            $emailBody = str_replace('{PASSWORD_RECOVER_URL}', $passwordRecoverUrl, $emailBody);
                            $emailBody = str_replace('{USER_LOGIN_PAGE}', $loginURL, $emailBody);
                            $emailBody = replace_email_vars($emailBody, $user, 6);
                            $emailBody = replace_email_vars($emailBody, $user, 5);
                            $mail->Body = trim($emailBody);

                            //Send email
                            if (!$mail->Send()) {
                                //An error occured while sending email
                                $tpl->assign('email_sent', 'error');
                                $tpl->assign('email_error_msg', $mail->ErrorInfo);
                            } else {
                                //Email sent successfully
                                $tpl->assign('email_sent', 'sent');
                            }
                            $tpl->assign('email_status', 1);

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

                            //Free memory
                            unset($user, $data, $mail, $emailTpl, $emailSubject, $emailBody, $passwordRecoverUrl, $loginURL, $new_password);
                        }
                    }

                    //Free memory
                    unset($data, $new_password);
                } else {
                    $tpl->assign('wrong_user_details', 1);
                    unset($data, $_POST, $_GET, $_REQUEST);
                }

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

        if (isset($data)) {
            $tpl->assign($data);
            unset($data);
        }
        break;

    case 'register' :
        if ($agreed == "false")
            http_custom_redirect('index.php');
        elseif (empty($agreed))
            $tpl->assign('agreement_terms', 1);

        elseif ($agreed == "true")
            $tpl->assign('user_registration', 1);

    case 'edit' :
        //count user links
        $sqlCountUsersLinks = "SELECT COUNT(*) Total FROM {$tables['link']['name']} WHERE OWNER_ID = {$_SESSION['phpld']['user']['id']}";
        $totalUserLinksPosted = (int) $db->GetOne($sqlCountUsersLinks);

        //count ALLOWED_NEWSLETTER links
        if ($totalUserLinksPosted) {
            $sqlAllowedNewsletterLinks = "SELECT COUNT(*) Total FROM {$tables['link']['name']} WHERE OWNER_NEWSLETTER_ALLOW = 1 AND OWNER_ID = {$_SESSION['phpld']['user']['id']}";
            $OWNER_NEWSLETTER_ALLOW = (int) $db->GetOne($sqlAllowedNewsletterLinks);
            $tpl->assign('OWNER_NEWSLETTER_ALLOW', $OWNER_NEWSLETTER_ALLOW);
        }

        $tpl->assign('hasLinks', $totalUserLinksPosted);
        $tpl->assign('user_edit', 1);
        $exclude_user_id = (!empty($_SESSION['phpld']['user']['id']) ? $_SESSION['phpld']['user']['id'] : 0);

    default :
        //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);
        }
        $tpl->assign('languages', select_lang('lang/'));

        //RALUCA: JQuery validation related
        $validators = array(
            'rules' => array(
                'NAME' => array(
                    'required' => true,
                    'minlength' => USER_NAME_MIN_LENGTH,
                    'maxlength' => USER_NAME_MAX_LENGTH
                ),
                'LANGUAGE' => array(
                    'required' => true
                ),
                'EMAIL' => array(
                    'required' => true,
                    'email' => true,
                    'remote' => array(
                        'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
                        'type' => "post",
                        'data' => array(
                            'action' => "isRegistrationEmail",
                            'table' => "user",
                            'field' => "EMAIL"
                        )
                    )
                ),
                'PASSWORDC' => array(
                    'required' => true,
                    'equalTo' => "#PASSWORD"
                ),
            ),
            'messages' => array(
                'EMAIL' => array(
                    'remote' => _L("This email is already in our database or banned.")
                ),
                'LOGIN' => array(
                    'remote' => _L("This is not a valid username.")
                ),
                'CAPTCHA' => array(
                    'remote' => _L("Incorrect code.")
                ),
                'PASSWORDC' => array(
                    'remote' => _L("Passwords do not match.")
                )
            )
        );
        if ($mode == "register") {
            $validators['rules']['LOGIN'] = array(
                'required' => true,
                'minlength' => USER_LOGIN_MIN_LENGTH,
                'maxlength' => USER_LOGIN_MAX_LENGTH,
                'remote' => array(
                    'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
                    'type' => "post",
                    'data' => array(
                        'action' => "isRegistrationUsername",
                        'table' => "user",
                        'field' => "LOGIN"
                    )
                )
            );
            $validators['rules']['PASSWORD'] = array(
                'required' => true,
                'minlength' => USER_PASSWORD_MIN_LENGTH,
                'maxlength' => USER_PASSWORD_MAX_LENGTH
            );
        }
        if ($mode == "edit") {
            $validators['rules']['URL'] = array(
                'remote' => array(
                    'url' => DIRECTORY_ROOT . "/include/validation_functions.php",
                    'type' => "post",
                    'data' => array(
                        'action' => "isDomainBanned",
                        'table' => "link",
                        'field' => "url"
                    )
                )
            );
            $validators['rules']['INFO'] = array(
                'minlength' => 0,
                'maxlength' => 255
            );
        }
if (VISUAL_CONFIRM == 2) {
    $validators['rules']['DO_MATH'] = array(
   'required' => true
    );
   
}
        if (VISUAL_CONFIRM == 1) {
            $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
                    )
                )
            );
        }
        $vld = json_custom_encode($validators);
        $tpl->assign('validators', $vld);
        $validator = new Validator($validators);
        //RALUCA: end of JQuery validation related


        if (empty($_POST['submit'])) {
			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 ($mode == "edit") {
                if (empty($_POST['submit']) && !empty($_SESSION['phpld']['user']['id']))
                    $user_info = $db->GetRow("SELECT * FROM `{$tables['user']['name']}` WHERE `ID` = " . $db->qstr($_SESSION['phpld']['user']['id']));

                $tpl->assign($user_info);
            }
        } else {
            $data = get_table_data('user');

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

            if (VISUAL_CONFIRM == 1)
                $data = array_merge($data, array('CAPTCHA' => $_POST['CAPTCHA'], 'IMAGEHASH' => $_POST['IMAGEHASH']));

            //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 ($mode == "edit" && !empty($_SESSION['phpld']['user']['id']))
                    $id = $_SESSION['phpld']['user']['id'];
                else
                    $id = $db->GenID($tables['user']['name'] . '_SEQ');
                if ($mode == "register") {
                    $data['REGISTRATION_DATE'] = $timenow;
                    $data['EMAIL_CONFIRMED'] = '0';
                }
                if (isset($data['CAPTCHA']))
                    unset($data['CAPTCHA']);
                if (isset($data['IMAGEHASH']))
                    unset($data['IMAGEHASH']);

                $unhashedPassword = (!empty($data['PASSWORD']) ? $data['PASSWORD'] : '');

                if (empty($data['PASSWORD']) && $mode == "edit")
                    $data['PASSWORD'] = $db->GetOne("SELECT `PASSWORD` FROM `{$tables['user']['name']}` WHERE `ID` = " . $db->qstr($id));
                else
                    $data['PASSWORD'] = encrypt_password($data['PASSWORD']);
                if ($mode == "edit" && !empty($_SESSION['phpld']['user']['level']))
                    $data['LEVEL'] = $_SESSION['phpld']['user']['level'];
                else
                    $data['LEVEL'] = 0;
                //author avatar related
                if ($mode == "edit" && !empty($_FILES['IMG']['name'])) {
                    $img = $_FILES['IMG']['name'];
                    $ext = substr($img, strrpos($img, '.'));
                    //make sure this directory is writable!
                    //the new width of the resized image, in pixels.
                    $img_thumb_width_small = 50; // thumb max width
                    $img_thumb_width = 200; // image max width
                    $imgname = $id;

                    /////////////////////////////////
                    // CREATE THE THUMBNAIL //
                    ////////////////////////////////
                    $file_type = $_FILES['IMG']['type'];
                    $file_name = $_FILES['IMG']['name'];
                    $file_size = $_FILES['IMG']['size'];
                    $file_tmp = $_FILES['IMG']['tmp_name'];
                    $ThumbWidth = $img_thumb_width;
                    $ThumbWidthSmall = $img_thumb_width_small;

                    //keep image type
                    $getExt = explode('.', $file_name);
                    $file_ext = $getExt[count($getExt) - 1];

                    if ($file_size) {
                        if ($file_type == "image/pjpeg" || $file_type == "image/jpeg") {
                            $new_img = imagecreatefromjpeg($file_tmp);
                            $new_img2 = imagecreatefromjpeg($file_tmp);
                        } elseif ($file_type == "image/x-png" || $file_type == "image/png") {
                            $new_img = imagecreatefrompng($file_tmp);
                            $new_img2 = imagecreatefrompng($file_tmp);
                        } elseif ($file_type == "image/gif") {
                            $new_img = imagecreatefromgif($file_tmp);
                            $new_img2 = imagecreatefromgif($file_tmp);
                        }

                        //list the width and height and keep the height ratio.
                        list($width, $height) = getimagesize($file_tmp);
                        //calculate the image ratio
                        $imgratio = $width / $height;
                        if ($imgratio > 1) {
                            $newwidth = $ThumbWidth;
                            $newheight = $ThumbWidth / $imgratio;
                            $newwidth2 = $ThumbWidthSmall;
                            $newheight2 = $ThumbWidthSmall / $imgratio;
                        } else {
                            $newheight = $ThumbWidth;
                            $newwidth = $ThumbWidth * $imgratio;
                            $newwidth2 = $ThumbWidthSmall;
                            $newheight2 = $ThumbWidthSmall / $imgratio;
                        }

                        //function for resize image.
                        if (function_exists(imagecreatetruecolor)) {
                            $resized_img = imagecreatetruecolor($newwidth, $newheight);
                            $resized_img2 = imagecreatetruecolor($newwidth2, $newheight2);
                        } else {
                            die("Error: Please make sure you have GD library ver 2+");
                        }

                        //the resizing is going on here!
                        imagealphablending($resized_img, false);
                        imagecopyresized($resized_img, $new_img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
                        imagealphablending($resized_img2, false);
                        imagecopyresized($resized_img2, $new_img2, 0, 0, 0, 0, $newwidth2, $newheight2, $width, $height);
                        //finally, save the images
                        if (file_exists(INSTALL_PATH . '/images/author/' . $imgname . '.' . $file_ext)) {
                            unlink(INSTALL_PATH . '/images/author/' . $imgname . '.' . $file_ext);
                            unlink(INSTALL_PATH . '/images/author/thumb/' . $imgname . '.' . $file_ext);
                        }

                        echo INSTALL_PATH . '/images/author/' . $imgname . '.' . $file_ext;

                        if ($file_type == "image/pjpeg" || $file_type == "image/jpeg") {
                            ImageJpeg($resized_img, INSTALL_PATH . '/images/author/' . $imgname . '.' . $file_ext);
                            ImageJpeg($resized_img2, INSTALL_PATH . '/images/author/thumb/' . $imgname . '.' . $file_ext);
                        } elseif ($file_type == "image/x-png" || $file_type == "image/png") {
                            imagesavealpha($resized_img, true);
                            imagesavealpha($resized_img2, true);
                            ImagePng($resized_img, INSTALL_PATH . '/images/author/' . $imgname . '.' . $file_ext);
                            ImagePng($resized_img2, INSTALL_PATH . '/images/author/thumb/' . $imgname . '.' . $file_ext);
                        } elseif ($file_type == "image/gif") {
                            ImageGIf($resized_img, INSTALL_PATH . '/images/author/' . $imgname . '.' . $file_ext);
                            ImageGIf($resized_img2, INSTALL_PATH . '/images/author/thumb/' . $imgname . '.' . $file_ext);
                        }

                        ImageDestroy($resized_img);
                        ImageDestroy($new_img);
                        ImageDestroy($resized_img2);
                        ImageDestroy($new_img2);
                    }
                    //ok copy the finished file to the thumbnail directory
                    //move_uploaded_file ($file_tmp, INSTALL_PATH.'imgs/'.$imgname.'.'.$file_ext);
                    $data['AUTH_IMG'] = SITE_URL . 'images/author/' . $imgname . '.' . $file_ext;
                    $data['AUTH_IMGTN'] = SITE_URL . 'images/author/thumb/' . $imgname . '.' . $file_ext;
                }

                //end

                $data['ID'] = $id;
                $data['RANK'] = 0;
                $data['ACTIVE'] = 1;
                $data['SUBMIT_NOTIF'] = 0;
                $data['PAYMENT_NOTIF'] = 0;

                if ($mode == "edit") {
                    $data['LOGIN'] = $db->GetOne("SELECT `LOGIN` FROM `{$tables['user']['name']}` WHERE `ID` = " . $db->qstr($id));
                    $mode = "UPDATE";
                    $where = " `ID` = " . $db->qstr($id);
                } else {
                    $mode = "INSERT";
                    $where = false;
                }

                //print_array($data);
                if ($db->AutoExecute($tables['user']['name'], $data, $mode, $where)) {

                    //update newsletter send flag(OWNER_NEWSLETTER_ALLOW) from table pld_link
                    if ($mode == 'UPDATE') {
                        $OWNER_NEWSLETTER_ALLOW = isset($_POST['OWNER_NEWSLETTER_ALLOW']) && $_POST['OWNER_NEWSLETTER_ALLOW'] == 'on' ? 1 : 0;
                        $db->AutoExecute($tables['link']['name'], array('OWNER_NEWSLETTER_ALLOW' => $OWNER_NEWSLETTER_ALLOW), "UPDATE", " OWNER_ID = " . $db->qstr($id));
                    }

                    //Send user settings confirmation email
                    //Get email template
                    $emailTpl = get_email_template('NTF_USER_DETAILS_TPL');

                    $tplSql = "SELECT `SUBJECT`, `BODY` FROM `{$tables['email_tpl']['name']}` WHERE `ID` = " . $db->qstr(NTF_USER_DETAILS_TPL);
                    $emailTpl = $db->GetRow($tplSql);

                    //if password changed on edit and an email tpl is available
                    if (!empty($unhashedPassword) && is_array($emailTpl) && !empty($emailTpl)) {
                        //Send unhashed password
                        $data['PASSWORD'] = $unhashedPassword;

                        $mail = get_emailer_admin();

                        //Add email subject
                        $emailSubject = $emailTpl['SUBJECT'];
                        $emailSubject = replace_email_vars($emailSubject, $data, 5);
                        $mail->Subject = trim($emailSubject);

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

                        //Add email body
                        $emailBody = $emailTpl['BODY'];
                        $emailBody = replace_email_vars($emailBody, $data, 5);
                        $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);
                    }



                    $_SESSION['phpld']['user']['language'] = $data['LANGUAGE'];
                    $_SESSION['user_language'] = $data['LANGUAGE'];

                    if ($mode == "edit" || !empty($_SESSION['phpld']['user']['id'])) {

                        $_SESSION['phpld']['user']['profileUpdate'] = 1;
                        http_custom_redirect(DOC_ROOT . '/profile.php?mode=logged');
                    } else {
                        if ($error < 1) {
                            //user has registered successfully, send confirmation mail (IF NEEDED)
                            if (EMAIL_CONFIRMATION == 1) {
                                $mail = get_emailer_admin();

                                //Add email subject
                                $emailSubject = "Email Confirmation";
                                $mail->Subject = trim($emailSubject);

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

                                //Add email body
                                $emailBody = "Please confirm email address here: " . SITE_URL . "confirm_email.php?uid=" . $data['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);

                                //end of confirmation email
                            }
                            http_custom_redirect(DOC_ROOT . '/profile.php?mode=thankyou');
                        }
                    }
                    //Free memory
                    unset($data, $emailTpl);
                }
                //Remove unhashed password (if still available)
                unset($unhashedPassword);
            }
        }
        break;
}

//Determine length of author's info field
$INFO_limit = (isset($data['INFO']) && strlen(trim($data['INFO'])) > 0 ? 255 - strlen(trim($data['INFO'])) : '255');
$tpl->assign('InfoLimit', $INFO_limit);

$tpl->assign('yesno', array("1" => "Yes", "0" => "No"));

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

if (!empty($registration_errors))
    $tpl->assign('registration_errors', $registration_errors);
if (!empty($validator_res))
		//do the math get error
		  $tpl->assign('error_list', $validator_res);
		  // end do the math
	


$path = array();
$path[] = array('ID' => '0', 'TITLE' => _L(DIRECTORY_TITLE), 'TITLE_URL' => DOC_ROOT, 'DESCRIPTION' => SITE_DESC);
$path[] = array('ID' => '0', 'TITLE' => _L('User Management'), 'TITLE_URL' => '', 'DESCRIPTION' => '');

$tpl->assign('path', $path);
$tpl->assign('SITE_NAME', SITE_NAME);
$tpl->assign('ALLOW_AUTHOR_INFO', ALLOW_AUTHOR_INFO);
//$tpl->assign('ALLOW_AVATARS'      , ALLOW_AVATARS);

$tpl->assign($data);
unset($data);

//Clean whitespace
$tpl->load_filter('output', 'trimwhitespace');
	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('profile.tpl', $id);
?>