<?php/** * Index * @file index.php * @author Valentin Apostolov <valentin@netinfo.bg> * @since 07th of January 2009 */error_reporting(E_ERROR | E_WARNING | E_PARSE);//Includesrequire_once("/nidata/apps/new/passport.netinfo.bg/www/nipass" . "/includes/shared.inc.php");// function validateExtendedProfile()function validateExtendedProfile() {    global $tbl_profiles, $tbl_users, $dbh, $HTML, $SUBS, $aTown, $aPosition, $aEducation, $aIncome;    // Vars    $error_password = "";    $error_personal_data = "";    $error_contacts = "";    $aErrors = array(); // Array, that contains the error messages    // Templates    $sImageFilename = "#%USER_ID%#_#%MD5_SUM%#.#%EXT%#";    $sImageFilenameThumbnail = "#%USER_ID%#_#%MD5_SUM%#_thumbnail.#%EXT%#";    $sImageURL = getAdmSetting("SITE_URL") . "/" . getAdmSetting("UPLOADS_DIR") . "#%USER_ID%#/#%IMAGE_FILENAME%#";    // Nipass    $oNipassLogin = new NipassLogin($dbh, $tbl_users);    $oNipassVO = $oNipassLogin->getByPK($_SESSION['nipass_id']);    // 23-02-2011 - martin@netinfo    // Get profile data so new email can be compared to existing email    $currentProfile = new Profile($dbh, $tbl_profiles);    $currentProfileVO = $currentProfile->getProfileByUserID($_SESSION['nipass_id']);    // Get params and sanitize them    // $signature = strip_tags(stripslashes(trim($_POST['signature'])));    $public_email = strip_tags(stripslashes(trim($_POST['public_email'])));    $abvicq = strip_tags(stripslashes(trim($_POST['abvicq'])));    $personal_web_site = strip_tags(stripslashes(trim($_POST['personal_web_site'])));    $additional_information = strip_tags(stripslashes(trim($_POST['additional_information'])));    $real_name = strip_tags(stripslashes(trim($_POST['real_name'])));    $gender = strip_tags(stripslashes(trim($_POST['gender'])));    $income = strip_tags(stripslashes(trim($_POST['income'])));    $education = strip_tags(stripslashes(trim($_POST['education'])));    $town = strip_tags(stripslashes(trim($_POST['town'])));    $birthdate = strip_tags(stripslashes(trim($_POST['birthdate'])));    $password = strip_tags(stripslashes(trim($_POST['password'])));    $newpassword = strip_tags(stripslashes(trim($_POST['newpassword'])));    $renewpassword = strip_tags(stripslashes(trim($_POST['renewpassword'])));    $country = strip_tags(stripslashes(trim($_POST['country'])));    $position = strip_tags(stripslashes(trim($_POST['position'])));    // Cast variables    $abvicq = intval($abvicq);    $gender = intval($gender);    // Prepare Upload Directory    $upload_directory = getAdmSetting('UPLOADS_DIR') . strval($oNipassVO->id) . "/";    if (!is_dir($upload_directory)) {        @mkdir($upload_directory, 0777, true);    }    if (isset($_FILES['fupload']) && !empty($_FILES['fupload']['tmp_name'])) {        $upload_class = new Upload_Files;        $upload_class->temp_file_name = trim($_FILES['fupload']['tmp_name']);        // Generate Uploaded Image Filename        $ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $_FILES['fupload']['name']);        $filename = basename($_FILES['fupload']['name'], ".$ext");        $SUBS["USER_ID"] = strval($oNipassVO->id);        $SUBS["MD5_SUM"] = md5($filename);        $SUBS["EXT"] = strtolower($ext);        $uFilename = strParse($sImageFilename);        $uFilenameThumbnail = strParse($sImageFilenameThumbnail);        $upload_class->file_name = $uFilename;        $upload_class->upload_dir = $upload_directory;        $upload_class->upload_log_dir = getAdmSetting('UPLOAD_LOGS_DIR');        $upload_class->max_file_size = 5242880;        $upload_class->banned_array = array("");        $upload_class->ext_array = array(".jpg", ".gif", ".png");        // Delete file if it already exists        if (file_exists($upload_class->upload_dir . $uFilename)) {            @unlink($upload_class->upload_dir . $uFilename);            @unlink($upload_class->upload_dir . $uFilenameThumbnail);        }        $valid_ext = $upload_class->validate_extension();        $valid_size = $upload_class->validate_size();        $valid_user = $upload_class->validate_user();        $max_size = $upload_class->get_max_size();        $file_size = $upload_class->get_file_size();        $file_exists = $upload_class->existing_file();        $upload_file = $upload_class->upload_file_with_validation();        if ($upload_file) {            $imageTransform = new imageTransform();            $imageTransform->crop($upload_class->upload_dir . $uFilename, 79, 79, $upload_class->upload_dir . $uFilenameThumbnail);            $imageTransform->crop($upload_class->upload_dir . $uFilename, 160, 160, $upload_class->upload_dir . $uFilename);            chmod($upload_class->upload_dir . $uFilenameThumbnail, 0666);            chmod($upload_class->upload_dir . $uFilename, 0666);            $SUBS['IMAGE_FILENAME'] = $uFilenameThumbnail;            $sImageDBURL = strParse($sImageURL);        }    }    if (!(isset($_POST['request_by_client']) && (isset($_POST['just_change_pass']) || isset($_POST['just_change_avatar'])))) {        // Validate        if (!empty($public_email)) {            if (!validateEmail($public_email))                $aErrors["EMAIL_INVALID"] = "Моля, въведете валиден имейл.";        }        if (!empty($personal_web_site)) {            if (!validateURL($personal_web_site))                $aErrors["URL_INVALID"] = "Моля, въведете валиден уебсайт.";        }        if (!isValidDate($birthdate))            $aErrors["BIRTHDATE_INVALID"] = "Невалидна дата на раждане. Моля, въведете валидна дата.";        if(!isset($aTown[$town]) || !isset($aPosition[$position]) || !isset($aEducation[$education]) || !isset ($aIncome[$income]))            $aErrors["OPTIONS_INVALID"] = "Невалидна опция!";    }    if (!empty($password) && !empty($newpassword) && !empty($renewpassword)) {        if ($oNipassVO->password != md5($password))            $aErrors["PASSWORD_INVALID"] = "Грешна парола. Моля, опитайте пак.";        if ($newpassword != $renewpassword)            $aErrors["PASSWORDS_DO_NOT_MATCH"] = "Паролите на съвпадат. Моля, опитайте пак.";    }    // Errors found? Go to dialogue screen again    if (count($aErrors) > 0) {        if (isset($_POST['request_by_client'])) {            $aErrors['STATUS'] = -1;            echo rawurlencode(base64_encode(serialize($aErrors)));            die;        }        extendedProfile($aErrors);        die();    }    // Format date    $birthdate = reformat_date($birthdate, "Y-m-d");    // Get User ID from session    $user_id = $_SESSION['nipass_id'];    $oProfileVO = new ProfileVO();    $oProfileVO->user_id = $user_id;    $success = DBSelectProfileDataByUserID($tbl_profiles, $oProfileVO, $dbh);    // Insert/update new data    // $oProfileVO->signature = $signature;    //$oProfileVO->public_email = $public_email;    $oProfileVO->abvicq = $abvicq;    $oProfileVO->personal_web_site = $personal_web_site;    $oProfileVO->additional_information = $additional_information;    $oProfileVO->gender = $gender;    $oProfileVO->income = $income;    $oProfileVO->education = $education;    $oProfileVO->town = $town;    $oProfileVO->birthdate = $birthdate;    $oProfileVO->country = $country;    $oProfileVO->position = $position;    if (isset($_FILES['fupload']) && !empty($_FILES['fupload']['tmp_name'])) {        $oProfileVO->public_avatar_url = $sImageDBURL;    }    if (!(isset($_POST['request_by_client']) && isset($_POST['just_change_pass']))) {        // Save Profile Value Object        $oProfile = new Profile($dbh, $tbl_profiles);        if(isset($_POST['just_change_avatar'])){            if($oProfileVO->public_avatar_url != "")                $currentProfileVO->public_avatar_url = $oProfileVO->public_avatar_url;            $oProfileVO = $currentProfileVO;        }        $success = $oProfile->save($oProfileVO);    }    // Nipass    if (!(isset($_POST['request_by_client']) && (isset($_POST['just_change_pass']) || isset($_POST['just_change_avatar'])))) {        $oNipassVO->real_name = $real_name;    }    if (!empty($password) && !empty($newpassword) && !empty($renewpassword)) {        $oNipassVO->password = md5($newpassword);    }    $success = $oNipassLogin->save($oNipassVO);    if (isset($_POST['request_by_client'])) {        if(!$success)            $result_status = -2;        else            $result_status = 1;        if(isset($_POST['just_change_avatar']) && isset($_POST['redirect'])){            if($oProfileVO->public_avatar_url != "")                $result_status = 1;            else                $result_status = -2;            header("location: " . urldecode($_POST['redirect'] . "?status=" . $result_status));        }else            echo rawurlencode(base64_encode(serialize(array('STATUS' => $result_status))));        die;    }    home();}// function extendedProfile($error_password = "", $error_personal_data = "", $error_contacts = "")function extendedProfile($aErrors = array()) {    global $tbl_profiles, $tbl_users, $dbh, $HTML;    // Get user's data    $oNipassLogin = new NipassLogin($dbh, $tbl_users);    $oNipassVO = $oNipassLogin->getByPK($_SESSION['nipass_id']);    // Get profile data    $oProfile = new Profile($dbh, $tbl_profiles);    $oProfileVO = $oProfile->getProfileByUserID($_SESSION['nipass_id']);    $subs = array();    $msgs = array();    // Error    if (isset($aErrors["EMAIL_INVALID"])) {        $subs['ERROR_MESSAGE'] = $aErrors["EMAIL_INVALID"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['EMAIL_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['EMAIL_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    if (isset($aErrors["CAPTCHA_INVALID"])) {        $subs['ERROR_MESSAGE'] = $aErrors["CAPTCHA_INVALID"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['CAPTCHA_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['CAPTCHA_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    if (isset($aErrors["PASSWORDS_DO_NOT_MATCH"])) {        $subs['ERROR_MESSAGE'] = $aErrors["PASSWORDS_DO_NOT_MATCH"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['NEW_PASSWORD_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['NEW_PASSWORD_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    if (isset($aErrors["PASSWORD_INVALID"])) {        $subs['ERROR_MESSAGE'] = $aErrors["PASSWORD_INVALID"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['PASSWORD_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['PASSWORD_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    if (isset($aErrors["URL_INVALID"])) {        $subs['ERROR_MESSAGE'] = $aErrors["URL_INVALID"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['URL_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['URL_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    if (isset($aErrors["BIRTHDATE_INVALID"])) {        $subs['ERROR_MESSAGE'] = $aErrors["BIRTHDATE_INVALID"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['BIRTHDATE_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['BIRTHDATE_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    // Subs    $subs['REAL_NAME'] = $oNipassVO->real_name;    $subs['BIRTHDATE'] = reformat_date($oProfileVO->birthdate, "d.m.Y");    $subs['TOWN'] = $oProfileVO->town;    $subs['INCOME'] = $oProfileVO->income;    $subs['EDUCATION'] = $oProfileVO->education;    $subs['PUBLIC_EMAIL'] = $oProfileVO->public_email;    $subs['ABVICQ'] = $oProfileVO->abvicq == 0 ? "" : $oProfileVO->abvicq;    $subs['PERSONAL_WEB_SITE'] = $oProfileVO->personal_web_site;    $subs['ADDITIONAL_INFORMATION'] = $oProfileVO->additional_information;    $subs["GENDER_MALE_CHECKED"] = ($oProfileVO->gender == 1) ? $HTML["checked"] : "";    $subs["GENDER_FEMALE_CHECKED"] = ($oProfileVO->gender == 2) ? $HTML["checked"] : "";    $income = $oProfileVO->income;    $subs["INCOME_SELECTED_$income"] = $HTML["selected"];    $education = $oProfileVO->education;    $subs["EDUCATION_SELECTED_$education"] = $HTML["selected"];    $position = $oProfileVO->position;    $subs["POSITION_SELECTED_$position"] = $HTML["selected"];    $country = $oProfileVO->country;    $subs["COUNTRY_SELECTED_$country"] = $HTML["selected"];    $town = $oProfileVO->town;    $subs["TOWN_SELECTED_$town"] = $HTML["selected"];    if (!empty($oProfileVO->public_avatar_url)) {        $subs["PUBLIC_AVATAR_URL"] = $oProfileVO->public_avatar_url;    } else {        $subs["PUBLIC_AVATAR_URL"] = "../images/changeProfilePhoto.jpg";    }    // Set Action    $subs['ACTION'] = $_SERVER['PHP_SELF'];    $subs["COUNTERS"] = @file_get_contents("templates/counters.html");    // Set Error    if (!empty($error_password)) {        $subs['ERROR'] = $error_password;        $page_template = new Template("templates/particle_error.html", $subs, $msgs);        $subs['ERROR_PASSWORD'] = $page_template->fileParse();        unset($page_template);    }    if (!empty($error_personal_data)) {        $subs['ERROR'] = $error_personal_data;        $page_template = new Template("templates/particle_error.html", $subs, $msgs);        $subs['ERROR_PERSONAL_DATA'] = $page_template->fileParse();        unset($page_template);    }    if (!empty($error_contacts)) {        $subs['ERROR'] = $error_contacts;        $page_template = new Template("templates/particle_error.html", $subs, $msgs);        $subs['ERROR_CONTACTS'] = $page_template->fileParse();        unset($page_template);    }    // YEAR    $subs['YEAR'] = date('Y');    //Display    $page_template = new Template("templates/changeProfile.html", $subs, $msgs);    echo $page_template->fileParse();}// function forgottenPasswordProcessEmail()function forgottenPasswordProcessEmail() {    global $tbl_users, $dbh;    mb_internal_encoding('UTF-8');    // Vars    $error = "";    // Get Params    $email = strip_tags(stripslashes(trim($_POST['email'])));    // Validate    if (!validateEmail($email))        $error .= "Моля, въведете валиден имейл.<br />";    if (!empty($error)) {        if(isset($_POST['request_by_client'])){            echo rawurlencode(base64_encode(serialize(array('STATUS' => -1))));            die;        }        forgottenPassword($error);        die();    }    $nipass_login = new NipassLogin($dbh, $tbl_users);    $nipass_vo = $nipass_login->getByEmail($email);    if (is_null($nipass_vo->id)) {        if(isset($_POST['request_by_client'])){            echo rawurlencode(base64_encode(serialize(array('STATUS' => -2))));            die;        }        header("location: http://www.vesti.bg");        die();    }    // Generate new password    $pwd = Password::getInstance()->generate(7, 1);    $nipass_vo->password = $pwd;    $success = $nipass_login->save($nipass_vo);    if ($success === true) {        // Send email        $subs = array();        $msgs = array();        $subs['PASSWORD'] = $pwd;        $subs['ALIAS'] = $nipass_vo->alias;        $email_template = new Template("emails/_etpl_reset_password.html", $subs, $msgs);        $message_body = $email_template->fileParse();        $from = "noreply@netinfo.bg";        $to = $email;        $smtp = new smtp_class;        $smtp->host_name = "localhost";       /* Change this variable to the address of the SMTP server to relay, like "smtp.myisp.com" */        $smtp->host_port = 25;                /* Change this variable to the port of the SMTP server to use, like 465 */        $smtp->ssl = 0;                       /* Change this variable if the SMTP server requires an secure connection using SSL */        $smtp->localhost = "vesti.bg";       /* Your computer address */        $smtp->direct_delivery = 0;           /* Set to 1 to deliver directly to the recepient SMTP server */        $smtp->timeout = 10;                  /* Set to the number of seconds wait for a successful connection to the SMTP server */        $smtp->data_timeout = 0;              /* Set to the number seconds wait for sending or retrieving data from the SMTP server.          Set to 0 to use the same defined in the timeout variable */        $smtp->debug = 0;                     /* Set to 1 to output the communication with the SMTP server */        $smtp->html_debug = 1;                /* Set to 1 to format the debug output as HTML */        $smtp->pop3_auth_host = "";           /* Set to the POP3 authentication host if your SMTP server requires prior POP3 authentication */        $smtp->user = "";                     /* Set to the user name if the server requires authetication */        $smtp->realm = "";                    /* Set to the authetication realm, usually the authentication user e-mail domain */        $smtp->password = "";                 /* Set to the authetication password */        $smtp->workstation = "";              /* Workstation name for NTLM authentication */        $smtp->authentication_mechanism = ""; /* Specify a SASL authentication method like LOGIN, PLAIN, CRAM-MD5, NTLM, etc..          Leave it empty to make the class negotiate if necessary */        /*         * If you need to use the direct delivery mode and this is running under         * Windows or any other platform that does not have enabled the MX         * resolution function GetMXRR() , you need to include code that emulates         * that function so the class knows which SMTP server it should connect         * to deliver the message directly to the recipient SMTP server.         */        if ($smtp->direct_delivery) {            if (!function_exists("GetMXRR")) {                /*                 * If possible specify in this array the address of at least on local                 * DNS that may be queried from your network.                 */                $_NAMESERVERS = array();                include("getmxrr.php");            }            /*             * If GetMXRR function is available but it is not functional, to use             * the direct delivery mode, you may use a replacement function.             */            /*              else              {              $_NAMESERVERS=array();              if(count($_NAMESERVERS)==0)              Unset($_NAMESERVERS);              include("rrcompat.php");              $smtp->getmxrr="_getmxrr";              }             */        }        if ($smtp->SendMessage(            $from, array(            $to        ), array(            "MIME-Version: 1.0",            "Content-type: text/html; charset=utf-8",            "From: $from",            "To: $to",            "Subject: " . encode_mimeheader("Нетинфо - Нова парола"),            "Date: " . strftime("%a, %d %b %Y %H:%M:%S %Z")        ), $message_body)) {            if(isset($_POST['request_by_client'])){                echo rawurlencode(base64_encode(serialize(array('STATUS' => 1))));                die;            }            login();            die();        } else {            if(isset($_POST['request_by_client'])){                echo rawurlencode(base64_encode(serialize(array('STATUS' => -3))));                die;            }            echo "Cound not send the message to $to.\nError: " . $smtp->error . "\n";            return false;        }    }else{        if(isset($_POST['request_by_client'])){            echo rawurlencode(base64_encode(serialize(array('STATUS' => -3))));            die;        }    }}// function forgottenPassword($error = "")function forgottenPassword($error = "") {    $subs = array();    $msgs = array();    // Set Action    $subs['ACTION'] = $_SERVER['PHP_SELF'];    $subs["COUNTERS"] = @file_get_contents("templates/counters.html");    // Set Error    $subs['ERROR'] = $error;    // YEAR    $subs['YEAR'] = date('Y');    // Display    $page_template = new Template("templates/forgottenPass.html", $subs, $msgs);    echo $page_template->fileParse();}function loginByConfirmationString($cs, $failure_redirect = "") {    global $dbh, $tbl_users;    if (isUserLogged()) {        logOut();    }    //Try to login by confirmation string    $nipass_vo = new NipassVO();    $nipass_login = new NipassLogin($dbh, $tbl_users);    $success = $nipass_login->login_by_cs($cs, $nipass_vo);    $getLoginParams = "";    if ($success) {        //Authorization successful, log user        logUser($nipass_vo);        $getLoginParams .= "&authorized=true";        $getLoginParams .= "&session_id=" . session_id();        $getLoginParams .= "&user_id=" . $nipass_vo->id;        $getLoginParams .= "&user_alias=" . $nipass_vo->alias;        $getLoginParams .= "&user_role=" . $nipass_vo->role;        $getLoginParams .= "&redirect=" . urlencode($failure_redirect);        $getLoginParams .= "&welcome_email=" . $nipass_vo->email;    } else {        //"Кодът за потвърждаване на Вашата регистрация е невалиден! Възможно е вече да сте потвърдили Вашата регистрация."        if ($failure_redirect != "")            header("location: " . ($failure_redirect) . "?status=-3");        die();    }    return $getLoginParams;}// function confirmRegistration()function confirmRegistration() {    global $tbl_profiles, $dbh, $tbl_users;    // Get params    $cs = $_GET["cs"];    // Check confirmation string    if (!is_md5($cs)) {        if (isset($_GET['confirmation_redirect']) && isset($_GET['confirmation_return'])) {            //Кодът за потвърждаване на Вашата регистрация е невалиден!            header("location: " . $_GET['confirmation_redirect'] . "?status=-2");            die();        }        die();    }    // Vars    $subs = array();    $msgs = array();    // Subs    $subs['ACTION'] = $_SERVER['PHP_SELF'];    $subs["COUNTERS"] = @file_get_contents("templates/counters.html");    $getLoginParams = "";    $success = FALSE;    if (isset($_GET['confirmation_redirect']) && isset($_GET['confirmation_return'])) {        $getLoginParams = loginByConfirmationString($cs, urldecode($_GET['confirmation_redirect']));    }    // Confirm registration    $profile = new Profile($dbh, $tbl_profiles);    $success = $profile->confirmRegistration($cs);    if (isset($_GET['confirmation_redirect']) && isset($_GET['confirmation_return'])) {        if ($success)            //"Вие успешно потвърдихте Вашата регистрация!"            header("location: " . urldecode($_GET['confirmation_return']) . "?" . $getLoginParams);        else {            //"Кодът за потвърждаване на Вашата регистрация е невалиден!"            logOut();            header("location: " . urldecode($_GET['confirmation_redirect']) . "?status=-1");        }        die();    }    // YEAR    $subs['YEAR'] = date('Y');    // Display    $page_template = new Template("templates/confirmationSuccessful.html", $subs, $msgs);    echo $page_template->fileParse();}function subscribeUser(&$just_subscribe, $user_id, $birthdate = '') {    global $dbh;    if (isset($_POST['just_subscribe']) && (int) $_POST['just_subscribe'] == 1 &&        isset($_POST['newsletter_type_ids']) &&        is_array($_POST['newsletter_type_ids']) && count($_POST['newsletter_type_ids']) > 0    ) {        $just_subscribe = TRUE;        $result = FALSE;        //Subscribe user and return        foreach ($_POST['newsletter_type_ids'] as $newsletter_type_id) {            if((int) $newsletter_type_id > 0){                $subscribeRes = DBUserSubscribe($user_id, (int) $newsletter_type_id, $birthdate, $dbh);                if ($subscribeRes)                    $result = TRUE;            }        }        return $result;    }    $just_subscribe = FALSE;    return TRUE;}function subscribeLoggedUser(){    global $dbh, $tbl_profiles;    if(isUserLogged()){        $resultArr = array();        if(isset($_POST['just_subscribe']) && (int) $_POST['just_subscribe'] == 1 &&            isset($_POST['app_id']) && (int) $_POST['app_id'] > 0){            $not_newsletter_type_ids_list = "";            if(isset($_POST['newsletter_type_ids']) && is_array($_POST['newsletter_type_ids']) && count($_POST['newsletter_type_ids']) > 0){                foreach($_POST['newsletter_type_ids'] as $v){                    $not_newsletter_type_ids_list .= ((int)$v).",";                }            }            $not_newsletter_type_ids_list = rtrim($not_newsletter_type_ids_list, ",");            DBUnsubscribeUserByAppId($_POST['app_id'], $_SESSION['nipass_id'], $dbh, $not_newsletter_type_ids_list);        }        if(isset($_POST['just_subscribe']) && (int) $_POST['just_subscribe'] == 1            && isset($_POST['netinfoemails']) && isset($_POST['netinfopartnersemails'])){            $currentProfile = new Profile($dbh, $tbl_profiles);            $currentProfileVO = $currentProfile->getProfileByUserID($_SESSION['nipass_id']);            $_POST['news']['newsletter'] = ($_POST['netinfoemails'] == 1) ? "on" : FALSE;            $currentProfileVO->netinfoemails = newsletter(TRUE);            $currentProfileVO->netinfopartnersemails = ($_POST['netinfopartnersemails'] == 1) ? TRUE : FALSE;            $netinfoEmailsRes = $currentProfile->save($currentProfileVO);        }        $just_subscribe = FALSE;        $subscribeRes = subscribeUser($just_subscribe, $_SESSION['nipass_id']);        if ($netinfoEmailsRes) {            $resultArr['STATUS'] = 1;        } else {            $resultArr['STATUS'] = -2;        }        if(isset($_POST['app_id']) && (int) $_POST['app_id'] > 0){            $subscribedMails = DBGetSubscribedMailsOfUserByAppId((int) $_POST['app_id'], $_SESSION['nipass_id'], $dbh);            $resultArr['PROFILE_SUBSCRIBE_INFO']['NEWSLETTERS'] = array();            if(is_array($subscribedMails) && count($subscribedMails) > 0){                $resultArr['PROFILE_SUBSCRIBE_INFO']['NEWSLETTERS'] = $subscribedMails;            }            $currentProfile = new Profile($dbh, $tbl_profiles);            $currentProfileVO = $currentProfile->getProfileByUserID($_SESSION['nipass_id']);            unset($_POST);            $resultArr['PROFILE_SUBSCRIBE_INFO']['NETINFOEMAILS'] = newsletter(TRUE);            $resultArr['PROFILE_SUBSCRIBE_INFO']['NETINFOPARTNERSEMAILS'] = $currentProfileVO->netinfopartnersemails;        }        echo rawurlencode(base64_encode(serialize($resultArr)));    }    die();}// function insertRegisteredUser($alias, $password, $real_name, $email, $birthdate, $gender, $netinfoemails, $netinfopartnersemails, $income, $education, $town, $country, $position)function insertRegisteredUser($alias, $password, $real_name, $email, $birthdate, $gender, $netinfoemails, $netinfopartnersemails, $income, $education, $town, $country, $position, $user_id = NULL, $app_id = NULL) {    global $tbl_users, $tbl_profiles, $dbh;    // Create Nipass record    $nipass_vo = new NipassVO();    $nipass_vo->id = ($user_id > 0) ? $user_id : NULL;    $nipass_vo->alias = $alias;    $nipass_vo->password = $password;    $nipass_vo->role = (isset($_POST['just_subscribe']) && (int) $_POST['just_subscribe'] == 1) ? -1 : 0;    $nipass_vo->real_name = $real_name;    $nipass_vo->email = $email;    $nipass_vo->user_rating = RatingComments::$max_user_rating - 2; //Important - 2, because his first 2 comments must go for moderator's decision;    $nipass_vo->app_id = $app_id;    $nipass_login = new NipassLogin($dbh, $tbl_users);    $success = $nipass_login->save($nipass_vo);    $nipass_login->login($nipass_vo);    if (!$success) {        return false;    }    $just_subscribe = FALSE;    $birthdate_subscribe = date("Y-m-d", strtotime($birthdate));    $subscribeRes = subscribeUser($just_subscribe, $nipass_vo->id,$birthdate_subscribe);    if ($just_subscribe)        return $subscribeRes;    // Vars    if ($netinfoemails == 0) {        $netinfoemails = false;    } else {        $netinfoemails = true;    }    if ($netinfopartnersemails == 0) {        $netinfopartnersemails = false;    } else {        $netinfopartnersemails = true;    }    // Create Profile record    $profile_vo = new ProfileVO();    $profile_vo->user_id = $nipass_vo->id;    $profile_vo->date_registered = date("Y-m-d");    $profile_vo->public_email = $email;    $profile_vo->birthdate = $birthdate;    $profile_vo->public_avatar_url = $public_avatar_url = NULL; // For now    $profile_vo->gender = $gender;    $profile_vo->netinfoemails = $netinfoemails;    $profile_vo->netinfopartnersemails = $netinfopartnersemails;    $profile_vo->income = $income;    $profile_vo->education = $education;    $profile_vo->town = $town;    $profile_vo->country = $country;    $profile_vo->position = $position;    $profile = new Profile($dbh, $tbl_profiles);    $success = $profile->save($profile_vo);    return $success;}//function validateRegistration()function validateRegistration() {    global $dbh, $HTML;    // Vars    $error_user_data = "";    $error_personal_data = "";    $aErrors = array(); // Array, that contains the error messages    $aValues = array();    // Get params and sanitize them    $alias = strip_tags(stripslashes(trim($_POST['alias'])));    $password1 = $_POST['password1'];    $password2 = $_POST['password2'];    $real_name = strip_tags(stripslashes(trim($_POST['real_name'])));    $email = mb_strtolower(strip_tags(stripslashes(trim($_POST['email']))), "utf-8");    // $birthdate = strip_tags(stripslashes(trim($_POST['birthdate'])));    $birthDay = strip_tags(stripslashes(trim($_POST['birthDay'])));    $birthMonth = strip_tags(stripslashes(trim($_POST['birthMonth'])));    $birthYear = strip_tags(stripslashes(trim($_POST['birthYear'])));    $birthdate = "$birthDay.$birthMonth.$birthYear";    if (isset($_POST['captcha'])) {        $captcha = strval(strip_tags(stripslashes(trim($_POST['captcha']))));    } else {        $captcha = '';    }    if (isset($_POST['gender'])) {        $gender = intval(strip_tags(stripslashes(trim($_POST['gender']))));    } else {        $gender = 0;    }    if (isset($_POST['netinfoemails'])) {        $netinfoemails = strip_tags(stripslashes(trim($_POST['netinfoemails'])));    } else {        $netinfoemails = 0;    }    if (isset($_POST['netinfopartnersemails'])) {        $netinfopartnersemails = strip_tags(stripslashes(trim($_POST['netinfopartnersemails'])));    } else {        $netinfopartnersemails = 0;    }    $netinfoemails = intval($netinfoemails);    $netinfopartnersemails = intval($netinfopartnersemails);    if (isset($_POST['agreedterms'])) {        $agreedterms = strip_tags(stripslashes(trim($_POST['agreedterms'])));        $agreedterms = intval($agreedterms);    } else {        $agreedterms = 0;    }    if (isset($_POST['income'])) {        $income = strip_tags(stripslashes(trim($_POST['income'])));        $income = intval($income);    } else {        $income = 0;    }    if (isset($_POST['education'])) {        $education = strip_tags(stripslashes(trim($_POST['education'])));        $education = intval($education);    } else {        $education = 0;    }    if (isset($_POST['town'])) {        $town = $_POST['town'];        $town = strval($town);    } else {        $town = 0;    }    if (isset($_POST['country'])) {        $country = strip_tags(stripslashes(trim($_POST['country'])));    } else {        $country = "";    }    if (isset($_POST['position'])) {        $position = $_POST['position'];        $position = intval($position);    } else {        $position = 0;    }    if(isset($_POST['nipass_app_id'])){        $app_id = (int) $_POST['nipass_app_id'];    }else{        $app_id = 0;    }    // Set Values    $aValues["ALIAS"] = $alias;    $aValues["EMAIL"] = $email;    $aValues["REAL_NAME"] = $real_name;    $aValues["TOWN_SELECTED_$town"] = $HTML["selected"];    $aValues["COUNTRY_SELECTED_$country"] = $HTML["selected"];    $aValues["INCOME_SELECTED_$income"] = $HTML["selected"];    $aValues["EDUCATION_SELECTED_$education"] = $HTML["selected"];    $aValues["POSITION_SELECTED_$position"] = $HTML["selected"];    $aValues["GENDER_MALE_CHECKED"] = ($gender == 1) ? $HTML["checked"] : "";    $aValues["GENDER_FEMALE_CHECKED"] = ($gender == 2) ? $HTML["checked"] : "";    $aValues["BIRTHDAY"] = $birthDay;    $aValues["BIRTHMONTH"] = $birthMonth;    $aValues["BIRTHYEAR"] = $birthYear;    $userInfo = array();    // Validate    $oCheckBanned = new RatingComments($dbh);    if (!$oCheckBanned->checkBannedUser())        $aErrors["BANNED"] = "За определен период от време Ви е забранено да се регистрирате, тъй като Вие сте наказан потребител!";    if ($agreedterms == 0)        $aErrors["TERMS_NOT_ACCEPTED"] = "Моля потвърдете, че приемате общите условия на сайта.";    if (empty($captcha) and $_SERVER['HTTP_REFERER'] == 'http://passport.netinfo.bg/nipass/index.php') {        $aErrors["CAPTCHA_INVALID"] = "Моля, въведете кода от картинката.";    }    if (!empty($captcha) and strtoupper($captcha) != strtoupper($_COOKIE['captcha'])){        $aErrors["CAPTCHA_INVALID"] = "Въведеният код е неправилен.";    }    if (empty($alias)) {        $aErrors["USERNAME_INVALID"] = "Въведеното от Вас потребителско име е грешно.";    } else {        if (!preg_match("/^(?:\p{Cyrillic}+|\p{Latin}+)$/u", $alias))            $aErrors["USERNAME_INVALID"] = "Потребителското име трябва да съдържа символи само на латиница или само на кирилица.";        if (DBUserExists($alias, $dbh))            $aErrors["USERNAME_INVALID"] = "Потребителското име е заето. Моля, въведете друго.";    }    if ($password1 != $password2)        $aErrors["PASSWORDS_DO_NOT_MATCH"] = "Паролите на съвпадат. Моля, опитайте пак.";    if (mb_strlen($password1) < 6 || mb_strlen($password1) > 30 || mb_strlen($password2) < 6 || mb_strlen($password2) > 30) {        $aErrors["PASSWORD_LENGTH_INVALID"] = "Моля, въведете парола между 6 и 30 символа.";    }    if (empty($real_name))        $aErrors["REAL_NAME_INVALID"] = "Моля, въведете Вашето име.";    if (!isValidDate($birthdate))        $aErrors["BIRTHDATE_INVALID"] = "Въведената от Вас дата на раждане е грешна.";    if (!validateEmail($email)) {        $aErrors["EMAIL_INVALID"] = "Въведеният от Вас e-mail е грешен.";    } else {        if (DBUserEmailExists($email, $dbh, $userInfo)) {            $just_subscribe = FALSE;            $birthdate_subscribe = date("Y-m-d", strtotime($birthdate));            $res = subscribeUser($just_subscribe, $userInfo['id'], $birthdate_subscribe);            if ($just_subscribe) {                $status = ($res) ? 1 : -2;                echo rawurlencode(base64_encode(serialize(array('STATUS' => $status))));                die;            }            if ($userInfo['role'] != -1)                $aErrors["EMAIL_ALREADY_EXISTS"] = "Потребител с такъв email вече съществува. Моля, въведете друг email.<br />";        }    }    // Go to registration again if an error has occured    if (count($aErrors)) {        if (isset($_POST['request_by_client']) && $_POST['request_by_client'] != "") {            $aErrors['STATUS'] = -1;            echo rawurlencode(base64_encode(serialize($aErrors)));        } else {            register($aErrors, $aValues);        }        die();    }    // Convert birthdate to SQL compatible date    $birthdate = date("Y-m-d", strtotime($birthdate));    //Is Subscribed user?    $user_id = (isset($userInfo['id'])) ? $userInfo['id'] : NULL;    $success = insertRegisteredUser($alias, $password1, $real_name, $email, $birthdate, $gender, $netinfoemails, $netinfopartnersemails, $income, $education, $town, $country, $position, $user_id, $app_id);    if ($success) {        if (isset($_POST['request_by_client']) && $_POST['request_by_client'] != "") {            echo rawurlencode(base64_encode(serialize(array('STATUS' => 1))));            die;        }        // Display        $subs = array();        $msgs = array();        $subs['ACTION'] = $_SERVER['PHP_SELF'];        $subs["COUNTERS"] = @file_get_contents("templates/counters.html");        // YEAR        $subs['YEAR'] = date('Y');        $page_template = new Template("templates/registrationSuccessful.html", $subs, $msgs);        echo $page_template->fileParse();        die();    } else {        if (isset($_POST['request_by_client']) && $_POST['request_by_client'] != "") {            echo rawurlencode(base64_encode(serialize(array('STATUS' => -2))));        } else {            register($error);        }        die();    }}//function register()function register($aErrors = array(), $aValues = array()) {    // Vars    $subs = $aValues;    $msgs = array();    // Set Action    $subs['ACTION'] = $_SERVER['PHP_SELF'];    $subs["COUNTERS"] = @file_get_contents("templates/counters.html");    // Error    if (isset($aErrors["BANNED"])) {        $subs['ERROR_MESSAGE'] = $aErrors["BANNED"];        $page_template = new Template("templates/particle_reg_ban_error.html", $subs, $msgs);        $subs['BANNED_ERROR_MESSAGE'] = $page_template->fileParse();        unset($page_template);    }    if (isset($aErrors["USERNAME_INVALID"])) {        $subs['ERROR_MESSAGE'] = $aErrors["USERNAME_INVALID"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['USERNAME_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['USERNAME_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    if (isset($aErrors["CAPTCHA_INVALID"])) {        $subs['ERROR_MESSAGE'] = $aErrors["CAPTCHA_INVALID"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['CAPTCHA_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['CAPTCHA_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    if (isset($aErrors["EMAIL_INVALID"])) {        $subs['ERROR_MESSAGE'] = $aErrors["EMAIL_INVALID"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['EMAIL_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['EMAIL_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    if (isset($aErrors["EMAIL_ALREADY_EXISTS"])) {        $subs['ERROR_MESSAGE'] = $aErrors["EMAIL_ALREADY_EXISTS"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['EMAIL_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['EMAIL_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    if (isset($aErrors["PASSWORDS_DO_NOT_MATCH"])) {        $subs['ERROR_MESSAGE'] = $aErrors["PASSWORDS_DO_NOT_MATCH"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['PASSWORD_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['PASSWORD_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    if (isset($aErrors["PASSWORD_LENGTH_INVALID"])) {        $subs['ERROR_MESSAGE'] = $aErrors["PASSWORD_LENGTH_INVALID"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['PASSWORD_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['PASSWORD_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    if (isset($aErrors["REAL_NAME_INVALID"])) {        $subs['ERROR_MESSAGE'] = $aErrors["REAL_NAME_INVALID"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['REAL_NAME_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['REAL_NAME_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    if (isset($aErrors["BIRTHDATE_INVALID"])) {        $subs['ERROR_MESSAGE'] = $aErrors["BIRTHDATE_INVALID"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['BIRTHDATE_ERROR_MESSAGE'] = $page_template->fileParse();        $subs['BIRTHDATE_INPUT_ERROR_CLASS'] = "inputError";        unset($page_template);    }    if (isset($aErrors["TERMS_NOT_ACCEPTED"])) {        $subs['ERROR_MESSAGE'] = $aErrors["TERMS_NOT_ACCEPTED"];        $page_template = new Template("templates/particle_registration_error.html", $subs, $msgs);        $subs['TERMS_ERROR_MESSAGE'] = $page_template->fileParse();        unset($page_template);    }    // Generate date select boxes    // DAY    $aDays = array();    $aDays[""] = 0;    for ($i = 1; $i <= 31; $i++) {        if ($i < 10) {            $i = "0" . strval($i); // Leading zero        }        $aDays["$i"] = strval($i);    }    $FormSelect = new FormSelect();    $FormSelect->id = "birthDay";    $FormSelect->name = "birthDay";    $FormSelect->class = '#%BIRTHDATE_INPUT_ERROR_CLASS%#';    $FormSelect->values = $aDays;    $FormSelect->type = 1;    $FormSelect->sort = 1;    if (isset($aErrors["BIRTHDATE_INVALID"])) {        $FormSelect->default = $aValues["BIRTHDAY"];    } else {        $FormSelect->default = $aValues["BIRTHDAY"];    }    $subs["BIRTHDATE_SELECT_BOX"] = $FormSelect->create();    unset($aDays, $FormSelect);    // MONTH    $aMonths = array("" => "0", "Януари" => "01", "Февруари" => "02", "Март" => "03", "Април" => "04", "Май" => "05", "Юни" => "06", "Юли" => "07", "Август" => "08", "Септември" => "09", "Октомври" => "10", "Ноември" => "11", "Декември" => "12");    $FormSelect = new FormSelect();    $FormSelect->id = "birthMonth";    $FormSelect->name = "birthMonth";    $FormSelect->class = '#%BIRTHDATE_INPUT_ERROR_CLASS%#';    $FormSelect->values = $aMonths;    $FormSelect->type = 1;    $FormSelect->sort = 1;    if (isset($aErrors["BIRTHDATE_INVALID"])) {        $FormSelect->default = $aValues["BIRTHMONTH"];    } else {        $FormSelect->default = $aValues["BIRTHMONTH"];    }    $subs["BIRTHMONTH_SELECT_BOX"] = $FormSelect->create();    unset($aMonths, $FormSelect);    // YEAR    $year_start = 1920;    $year_end = date("Y") - 16; // The user must be at least 16 years old    $aYears = array();    $aYears[""] = 0;    for ($i = $year_end; $i >= $year_start; $i--) {        $aYears["$i"] = $i;    }    $FormSelect = new FormSelect();    $FormSelect->id = "birthYear";    $FormSelect->name = "birthYear";    $FormSelect->class = '#%BIRTHDATE_INPUT_ERROR_CLASS%#';    $FormSelect->values = $aYears;    $FormSelect->type = 1;    $FormSelect->sort = 0;    if (isset($aErrors["BIRTHDATE_INVALID"])) {        $FormSelect->default = $aValues["BIRTHYEAR"];    } else {        $FormSelect->default = $aValues["BIRTHYEAR"];    }    $subs["BIRTHYEAR_SELECT_BOX"] = $FormSelect->create();    unset($aYears, $FormSelect);    // YEAR    $subs['YEAR'] = date('Y');    // Display    $page_template = new Template("templates/registration.html", $subs, $msgs);    echo $page_template->fileParse();}//function getUserXMLData()function getUserXMLData() {    global $dbh, $tbl_users, $tbl_profiles;    // Vars    $id = NULL;    $alias = NULL;    $role = NULL;    $real_name = NULL;    // Get session id    $session_id = $_REQUEST['session_id'];    // Query    $sql = "SELECT id, alias, role, real_name, email          FROM $tbl_users          WHERE session_id = :session_id";    $stmt = $dbh->prepare($sql);    $stmt->bindParam(":session_id", $session_id, PDO::PARAM_STR);    $success = $stmt->execute();    if (!$success) {        //TO DO: write error to log file        if (defined('DEBUG') && (DEBUG == 1)) {            $arr = $stmt->errorInfo();            print_r($arr);        }        return false;    }    while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {        $id = $result["id"];        $alias = $result["alias"];        $role = $result["role"];        $real_name = $result["real_name"];        $email = $result["email"];    }    $stmt->closeCursor();    //DBUpdateUserSession($id, "", $dbh);    // Return XML    if (is_null($id) && is_null($alias) && is_null($role) && is_null($real_name)) {        echo "";        die();    } else {        // get avatar url        $avatar_url = '';        $sql = "SELECT public_avatar_url              FROM $tbl_profiles              WHERE user_id = :user_id";        $stmt = $dbh->prepare($sql);        $stmt->bindParam(":user_id", $id, PDO::PARAM_INT);        $success = $stmt->execute();        if ($success) {            while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {                $avatar_url = $result["public_avatar_url"];            }        }        // end get avatar url        $subs = array();        $msgs = array();        $subs['ID'] = $id;        $subs['ALIAS'] = $alias;        $subs['ROLE'] = $role;        $subs['REAL_NAME'] = $real_name;        $subs['EMAIL'] = $email;        $subs['AVATAR_URL'] = $avatar_url;        $page_template = new Template("templates/_tpl_user_data.xml", $subs, $msgs);        header('Content-Type: application/xml');        echo $page_template->fileParse();        die();    }}//function validateLoginDetails()function validateLoginDetails() {    global $SUBS;    logOutForLogin();    // Get params    $alias = $_POST["alias"];    $alias = strip_tags(stripslashes($alias));    $password = $_POST["password"];    $password = strip_tags(stripslashes($password));    if (isset($_POST["remember_me"]) && trim($_POST["remember_me"]) == "true") {        $remember_me = true;    } else {        $remember_me = false;    }    $redirect = $_REQUEST['redirect'];    if (validateLogin($alias, '', $password, $remember_me)) {        if (isset($_REQUEST["cmd"])) {            $cmd = $_REQUEST["cmd"];        } else {            $cmd = "";        }        if ($cmd == "newsletter") {            header("location: http://passport.netinfo.bg/nipass/index.php?cmd=newsletter");            die();        }        header("location: $redirect");        die();        // header("location: $redirect");    } else {        $_SERVER["HTTP_REFERER"] = $redirect;        login("Въведените от Вас потребителско име или парола са грешни.");        die();    }}//function remote()function remote() {    global $SUBS, $dbh;    // Var    $logged = false;    if (isset($_REQUEST["return"]) && whitelist($_REQUEST["return"])) {        $return = $_REQUEST["return"];        $return = urldecode($return);    } else {        header("location: http://passport.netinfo.bg/nipass/");        die();    }    if (isset($_REQUEST["redirect"]) && whitelist($_REQUEST["redirect"])) {        $redirect = $_REQUEST["redirect"];        $redirect = urldecode($redirect);    } else {        header("location: http://passport.netinfo.bg/nipass/");        die();    }    // Templates    $strAuthorized = "&authorized=true";    $strNotAuthorized = "&authorized=false";    $strSession = "&session_id=#%SESSION_ID%#";    $strUserID = "&user_id=#%USER_ID%#";    $strUserAlias = "&user_alias=#%USER_ALIAS%#";    $strUserRole = "&user_role=#%USER_ROLE%#";    $strRedirect = "&redirect=#%REDIRECT%#";    $strLoginDetails = "";    $strInitSessId = "";    // Get params    if (isset($_REQUEST["alias"])) {        $alias = $_REQUEST["alias"];        if($_REQUEST["alias"] != ""){            $strLoginDetails = "&login_alias=" . urlencode(base64_encode($_REQUEST["alias"]));        }    } else {        $alias = "";    }    $alias = strip_tags(stripslashes($alias));    //marto    if (isset($_REQUEST["email"])) {        $email = $_REQUEST["email"];        if($_REQUEST['email'] != ""){            $strLoginDetails .= "&login_email=" . urlencode(base64_encode($_REQUEST["email"]));        }    } else {        $email = "";    }    $email = strip_tags(stripslashes($email));    if(isset($_REQUEST["alias"]) || isset($_REQUEST["email"])){        $strLoginDetails .= "&from_login_form=true";    }    if(isset($_REQUEST["init_sess_id"])){        $strInitSessId .= "&init_sess_id=" . $_REQUEST["init_sess_id"];    }    if (isset($_REQUEST["password"])) {        $password = $_REQUEST["password"];    } else {        $password = "";    }    $password = strip_tags(stripslashes($password));    if (isset($_REQUEST["return"])) {        $return = $_REQUEST["return"];    } else {        $return = "";    }    $return = urldecode($return);    if (isset($_REQUEST["redirect"])) {        $redirect = $_REQUEST["redirect"];    } else {        $redirect = "";    }    if (isset($_REQUEST["remember_me"]) && trim($_REQUEST["remember_me"]) == "true") {        $remember_me = true;    } else {        $remember_me = false;    }    $redirect = urldecode($redirect);    if (isset($_GET["passive"])) {        $passive = strval($_GET["passive"]);    } else {        $passive = "";    }    // Validate input    if ((empty($alias) || empty($email)) && empty($password) && empty($return) && empty($redirect) && empty($passive)) {        logOut();        die();    }    // Check passive login    // It may be true or false or blank    if ($passive === "true") {        if (isUserLogged()) {            $logged = true;            DBUpdateUserSession(intval($_SESSION["nipass_id"]), session_id(), $dbh);            //$a = new NipassLogin();if($a->getIp() == '194.153.145.235'){ print $alias;print 'web8';print session_id();print_r($_SESSION);die;}        }else{            if(tryLoginByRemCookie()){                $logged = true;            }        }    }else{        // Check whether the user is already logged        if (isUserLogged() && $alias == $_SESSION['nipass_alias']) {            $logged = true;        }else{            logOutForLogin();        }    }    // Validate user login details    if (!$logged) {        $success = validateLogin($alias, $email, $password, $remember_me);    }    // Redirect    $SUBS["REDIRECT"] = urlencode($redirect);    $strRedirect = strParse($strRedirect);    $SUBS["SESSION_ID"] = session_id();    $strSession = strParse($strSession);    if ($logged || $success) {        $SUBS["USER_ID"] = $_SESSION["nipass_id"];        $SUBS["USER_ALIAS"] = $_SESSION["nipass_alias"];        $SUBS["USER_ROLE"] = $_SESSION["nipass_role"];        $strUserID = strParse($strUserID);        $strUserAlias = strParse($strUserAlias);        $strUserRole = strParse($strUserRole);        $url = $return . $strAuthorized . $strSession . $strUserID . $strUserAlias . $strUserRole . $strRedirect . $strInitSessId;        header("location: $url");        die();    } else {        $url = $return . $strNotAuthorized . $strSession . $strLoginDetails . $strRedirect . $strInitSessId;        //$a = new NipassLogin();if($a->getIp() == '194.153.145.235'){ print $alias;print 'web8';print $url;die;}        if($passive == "" && !isset($_REQUEST['force_return'])){            login("Въведените от Вас потребителско име или парола са грешни.");        }else{            header("location: $url");        }        die();    }}//function demoUser()function demoUser() {    global $tbl_users, $dbh;    // Insert Demo User    $nipass_vo = new NipassVO();    $nipass_vo->alias = "demo";    $nipass_vo->password = "demo";    $nipass_login = new NipassLogin($dbh, $tbl_users);    $success = $nipass_login->save($nipass_vo);    $nipass_login->login($nipass_vo);    // Insert Demo Profile    $profile_vo = new ProfileVO();    $profile_vo->user_id = $nipass_vo->id;    $profile_vo->date_registered = date("Y-m-d");    $profile_vo->birthdate = date("Y-m-d");    $profile = new Profile($dbh, $tbl_users);    $profile->save($profile_vo);}//function userLogout()function userLogout() {    logOut();    if(isset($_GET['r']) && $_GET['r'] != ''){        $redirect = rawurldecode(base64_decode($_GET['r']));        header("location: $redirect");        die();    }    if (isset($_SERVER["HTTP_REFERER"])) {        $http_referer = $_SERVER["HTTP_REFERER"];        header("location: $http_referer");        die();    } else {        login();    }}//function validateLogin($alias = NULL, $password = NULL)function validateLogin($alias = NULL, $email = NULL, $password = NULL, $remember_me = FALSE) {    global $tbl_users, $dbh;    if (is_null($alias)) {        $alias = $_POST["alias"];    }    if (is_null($email)) {        $email = $_POST["email"];    }    if (is_null($password)) {        $password = $_POST["password"];    }    //Sanitize    $alias = strip_tags(stripslashes($alias));    $email = strip_tags(stripslashes($email));    $password = strip_tags(stripslashes($password));    //Check login    $nipass_vo = new NipassVO();    $nipass_vo->alias = $alias;    $nipass_vo->email = $email;    $nipass_vo->password = $password;    $nipass_login = new NipassLogin($dbh, $tbl_users);    $success = $nipass_login->login($nipass_vo, $remember_me);    if ($success) {        $is_active = $nipass_login->isActive($nipass_vo->id);        if (!$is_active)            return false;        //Authorization successful, log user        logUser($nipass_vo);//$a = new NipassLogin();if($a->getIp() == '194.153.145.235'){print 'web8';print session_id();print_r($_SESSION);die;}        return true;    } else {        //Authorization failed, try again        return false;    }}//function login($error = "")function login($error = "", $redirect_internal = "") {    $subs = array();    $msgs = array();    // Set Action    if (empty($_SERVER["HTTP_REFERER"])) {        $subs['ACTION_REDIRECT'] = getAdmSetting("SITE_URL");    } else {        $subs['ACTION_REDIRECT'] = $_SERVER["HTTP_REFERER"];    }    if (!empty($redirect_internal)) {        $subs['ACTION_REDIRECT'] = getAdmSetting("SITE_URL") . "/index.php?cmd=$redirect_internal";    }    $subs['ACTION'] = basename($_SERVER['PHP_SELF']);    $subs["COUNTERS"] = @file_get_contents("templates/counters.html");    // Error    if (!empty($error)) {        $subs['ERROR'] = $error;        $page_template = new Template("templates/particle_error.html", $subs, $msgs);        $subs['ERROR_LOGIN'] = $page_template->fileParse();        unset($page_template);    }    // YEAR    $subs['YEAR'] = date('Y');    //Display    $page_template = new Template("templates/login.html", $subs, $msgs);    echo $page_template->fileParse();}//function home()function home() {    // Globals    global $tbl_profiles, $tbl_users, $dbh, $aIncome, $aEducation, $aPosition;    $subs = array();    $msgs = array();    // Get user's data    $oNipassLogin = new NipassLogin($dbh, $tbl_users);    $oNipassVO = $oNipassLogin->getByPK($_SESSION['nipass_id']);    // Get profile data    $oProfile = new Profile($dbh, $tbl_profiles);    $oProfileVO = $oProfile->getProfileByUserID($_SESSION['nipass_id']);    //    $enter_link = @file_get_contents("templates/enter_link.html");    // Subs    $subs["COUNTERS"] = @file_get_contents("templates/counters.html");    $subs['LOGGED'] = $_SESSION['nipass_alias'];    $subs['REAL_NAME'] = $oNipassVO->real_name;    $subs['TOWN'] = (empty($oProfileVO->town) && !isset($_POST['request_by_client'])) ? @file_get_contents("templates/enter_town_link.html") : $oProfileVO->town;    $subs['INCOME'] = $aIncome[$oProfileVO->income];    $subs['EDUCATION'] = $aEducation[$oProfileVO->education];    $subs['PUBLIC_EMAIL'] = $oProfileVO->public_email;    $subs['ABVICQ'] = ($oProfileVO->abvicq > 0) ? $oProfileVO->abvicq : $enter_link;    $subs['PERSONAL_WEB_SITE'] = $oProfileVO->personal_web_site;    $subs['ADDITIONAL_INFORMATION'] = empty($oProfileVO->additional_information) ? $enter_link : $oProfileVO->additional_information;    $subs['COUNTRY'] = (empty($oProfileVO->country) && !isset($_POST['request_by_client'])) ? @file_get_contents("templates/enter_country_link.html") : $oProfileVO->country;    $birthdate = strtotime($oProfileVO->birthdate);    $today = strtotime(date("Y-m-d"));    $age = $today - $birthdate;    $subs['AGE'] = intval($age / 31556926);    $subs['BIRTHDATE'] = $birthdate;    $subs['SEX'] = $oProfileVO->gender;    $subs['POSITION'] = ($oProfileVO->position > 0) ? $aPosition[$oProfileVO->position] : NULL;    if (!empty($oProfileVO->public_avatar_url)) {        $subs['PUBLIC_AVATAR_URL'] = str_replace('_thumbnail', '', $oProfileVO->public_avatar_url);    } elseif (isset($_POST['request_by_client'])) {        $subs['PUBLIC_AVATAR_URL'] = "";    } else {        $subs['PUBLIC_AVATAR_URL'] = "../images/profilePhoto.jpg";    }    if (isset($_POST['request_by_client'])) {        echo rawurlencode(base64_encode(serialize($subs)));        die;    }    // YEAR    $subs['YEAR'] = date('Y');    //Display    $page_template = new Template("templates/profile.html", $subs, $msgs);    echo $page_template->fileParse();}function termscookie(){    // YEAR    $subs['YEAR'] = date('Y');    //Display    $page_template = new Template("templates/termscookie.html");    echo $page_template->fileParse();}function unsubscribe() {    // Globals    global $tbl_profiles, $tbl_users, $dbh, $aIncome, $aEducation;    $subs = array();    $msgs = array();    $userInfo = base64_decode($_GET['s']);    $userInfo = explode('|', $userInfo);    // connect to newsletter db    $conn = new PDO('pgsql:host=vestidb.ni.bg;dbname=sympa', 'sympa_user', 's09qw');    $sql = "delete from subscriber_table where user_subscriber = :userSubscriber and list_subscriber = :listSubscriber";    $stm = $conn->prepare($sql);    $stm->bindParam(":userSubscriber", $userInfo[0]);    $stm->bindParam(":listSubscriber", $userInfo[1]);    $stm->execute();    $subs['EMAIL'] = $userInfo[0];    $subs['LIST'] = $userInfo[1];    // YEAR    $subs['YEAR'] = date('Y');    //Display    $page_template = new Template("templates/unsubscribe.html", $subs, $msgs);    echo $page_template->fileParse();}// function newsletter();function newsletter($request_by_client = FALSE) {    // Globals    global $tbl_profiles, $tbl_users, $dbh, $aIncome, $aEducation;    $subs = array();    $msgs = array();    // Get user's data    $oNipassLogin = new NipassLogin($dbh, $tbl_users);    $oNipassVO = $oNipassLogin->getByPK($_SESSION['nipass_id']);    $email = $oNipassVO->email;    // connect to newsletter db    try{        $conn = new PDO('pgsql:host=vestidb.ni.bg;dbname=sympa', 'sympa_user', 's09qw');    }catch(PDOException $e){        var_dump($e);    }    if ($_POST) {        if ($_POST['news']) {            foreach ($_POST['news'] as $list => $val) {                $sql = "select * from subscriber_table where user_subscriber = '$email' and list_subscriber = '$list'";                $stm = $conn->prepare($sql);                $stm->execute();                $userData = $stm->fetch();                if (!$userData['user_subscriber']) {                    // insert                    $sql = "insert into subscriber_table                       (list_subscriber, user_subscriber, custom_attribute_subscriber, robot_subscriber, date_subscriber, update_subscriber, visibility_subscriber, reception_subscriber, subscribed_subscriber, included_subscriber)                      values (                        '$list',                        '$email',                        '<?xml version=\"1.0\" encoding=\"UTF-8\" ?><custom_attributes></custom_attributes>',                        'news.netinfo.bg',                        '" . date('Y-m-d h:i:s') . "',                        '" . date('Y-m-d h:i:s') . "',                        'noconceal',                        'html',                        1,                        0                      )";                    $stm = $conn->prepare($sql);                    $stm->execute();                }            }            $is_checked = TRUE;        }        if (!$_POST['news']['newsletter']) {            $sql = "delete from subscriber_table where user_subscriber = '$email' and list_subscriber = 'newsletter'";            $stm = $conn->prepare($sql);            $stm->execute();            $is_checked = FALSE;        }        if (!$_POST['news']['worldcup2010']) {            $sql = "delete from subscriber_table where user_subscriber = '$email' and list_subscriber = 'worldcup2010'";            $stm = $conn->prepare($sql);            $stm->execute();        }        $thanks = '<div id="thanks" class="changeFields" style="background: #57AF71 !important; padding:17px 0 8px 26px;">                                <p class="clearfix">                                    Промените в настройките на бюлетините бяха запазени!                                </p>                            </div>              <script type="text/javascript">setTimeout ( "$(\"#thanks\").slideUp(1000);", 5000 )</script>              ';        if($request_by_client){            return $is_checked;        }    }    $sql = "select * from subscriber_table where user_subscriber = '$email' and list_subscriber = 'newsletter'";    $stm = $conn->prepare($sql);    $stm->execute();    $userData = $stm->fetch();    $subs['CHECKED'] = ($userData['user_subscriber'] != '') ? 'checked="yes"' : '';    if($request_by_client){        return ($userData['user_subscriber'] != '') ? TRUE : FALSE;    }    /*      $sql = "select * from subscriber_table where user_subscriber = '$email' and list_subscriber = 'worldcup2010'";      $stm = $conn->prepare($sql);      $stm->execute();      $userData = $stm->fetch();      $subs['CHECKED2'] = ($userData['user_subscriber'] != '') ? 'checked="yes"' : '';     */    $subs["COUNTERS"] = @file_get_contents("templates/counters.html");    $subs['THANKS'] = $thanks;    // YEAR    $subs['YEAR'] = date('Y');    //Display    $page_template = new Template("templates/newsletter.html", $subs, $msgs);    echo $page_template->fileParse();}function getFormOptionsArray(){    if(isset ($_POST['request_by_client'])){        global $aEducation, $aIncome, $aPosition, $aTown, $dbh, $tbl_users, $tbl_profiles;        $options['POSITIONS'] = $aPosition;        $options['INCOME'] = $aIncome;        $options['EDUCATION'] = $aEducation;        $options['TOWN'] = $aTown;        $oNipassLogin = new NipassLogin($dbh, $tbl_users);        $oNipassVO = $oNipassLogin->getByPK($_SESSION['nipass_id']);        if($oNipassVO){            $options['PROFILE']['REAL_NAME'] = $oNipassVO->real_name;            $currentProfile = new Profile($dbh, $tbl_profiles);            $currentProfileVO = $currentProfile->getProfileByUserID($_SESSION['nipass_id']);            if($currentProfileVO){                $options['PROFILE']['GENDER'] = $currentProfileVO->gender;                $options['PROFILE']['BIRTHDATE'] = $currentProfileVO->birthdate;                $options['PROFILE']['INCOME'] = $currentProfileVO->income;                $options['PROFILE']['EDUCATION'] = $currentProfileVO->education;                $options['PROFILE']['POSITIONS'] = $currentProfileVO->position;                $options['PROFILE']['TOWN'] = $currentProfileVO->town;                echo rawurlencode(base64_encode(serialize($options)));            }            die;        }    }else{        home();    }}function unsubscribeByClient(){    global $dbh;    $resultArr['STATUS'] = -1;    if(isset($_POST['request_by_client']) && isset($_POST['unsubscribe_key'])){        if(is_md5($_POST['unsubscribe_key'])){            $resultArr = DBGetUserInfoByUnsubscribeKey($_POST['unsubscribe_key'], $dbh);            $resultArr['STATUS'] = -1;            if($resultArr['EMAIL'] != ''){                $res = DBUnsubscribeUserByKey($_POST['unsubscribe_key'], $dbh);                if($res)                    $resultArr['STATUS'] = 1;            }        }    }    echo rawurlencode(base64_encode(serialize($resultArr)));    die;}// Voidif (!init()) {    halt();}// Dispatcherif (isset($_REQUEST["cmd"])) {    $cmd = $_REQUEST["cmd"];} else {    $cmd = "";}if (isUserLogged()) {    //user logged    switch ($cmd) {        case 'home':            home();            break;        case 'logout':            userLogout();            break;        case 'remote':            remote();            break;        case 'getuserxmldata':            getUserXMLData();            break;        case 'extendedprofile':            extendedProfile();            break;        case 'validateextendedprofile':            validateExtendedProfile();            break;        case 'newsletter':            newsletter();            break;        case 'unsubscribe':            unsubscribe();            break;        case 'confirmregistration':            confirmRegistration();            break;        case 'validateregistration':            if (isset($_POST['just_subscribe']) && (int) $_POST['just_subscribe'] == 1)                validateRegistration();            else                home();            break;        case 'termscookie':            termscookie();            break;        case 'getformoptionsarray' :            if(isset ($_POST['request_by_client'])){                getFormOptionsArray();            }else{                home();            }            break;        case 'subscribeloggeduser' :            if(isset ($_POST['request_by_client'])){                subscribeLoggedUser();            }else{                home();            }            break;        case 'unsubscribebyclient' :            if(isset ($_POST['request_by_client'])){                unsubscribeByClient();            }else{                home();            }            break;        default:            home();            break;    }} else {    //user not logged    switch ($cmd) {//       case 'home'://         home();//         break;        case 'login':            login();            break;        case 'validatelogindetails':            validateLoginDetails();            break;        case 'logout':            userLogout();            break;        case 'demouser':            demoUser();            break;        case 'remote':            remote();            break;        case 'getuserxmldata':            getUserXMLData();            break;        case 'register':            register();            break;        case 'confirmregistration':            confirmRegistration();            break;        case 'validateregistration':            validateRegistration();            break;        case 'forgottenpassword':            forgottenPassword();            break;        case 'forgottenpasswordprocessemail':            forgottenPasswordProcessEmail();            break;        case 'termscookie':            termscookie();            break;        case 'newsletter':            login("", "newsletter");            break;        case 'unsubscribebyclient' :            if(isset ($_POST['request_by_client'])){                unsubscribeByClient();            }else{                home();            }            break;        default:            if(!tryLoginByRemCookie()){                login();            }else{                home();            }            break;    }}?>