Example #1
0
 public function saveLog($xml)
 {
     // !!!
     // @todo Вот не знаю стоит ли тут делать так, или все же легче вызвать self::initReqXml(); но там у нас сессия инициализируется
     $this->_clientXml = new DOMDocument();
     libxml_use_internal_errors(true);
     if (!$this->_clientXml->loadXML($xml)) {
         $this->_debug = 1;
         $xe_levels = array(LIBXML_ERR_WARNING => 'WARNING', LIBXML_ERR_ERROR => 'ERROR', LIBXML_ERR_FATAL => 'FATAL');
         foreach (libxml_get_errors() as $xe) {
             $err .= $xe_levels[$xe->level] . ": (line: {$xe->line}, column: {$xe->column}): {$xe->message}";
         }
         libxml_clear_errors();
         $this->error(EXTERNAL_ERR_WRONG_REQ, $err);
     }
     $ns_name = basename($this->_clientXml->documentElement->getAttribute('xmlns:f'));
     if ($ns_name == '') {
         $ns_name = basename($this->_clientXml->documentElement->getAttribute('xmlns:hh'));
     } else {
         $ns_name = 'freetray';
     }
     if ($ns_name == '') {
         $ns_name = 'other';
     }
     $log = new log("external/{$ns_name}-%d%m%Y.log");
     $log->writeln('--------------' . getRemoteIP() . '--------------');
     $log->writeln($xml);
 }
Example #2
0
 /**
  * Создать анонима
  *
  * @param char $error
  * @return integer		идентификатор анонима
  */
 function Create(&$error)
 {
     global $DB;
     $id = 0;
     if (!$error) {
         $data = array('icq' => $this->icq, 'mail' => $this->mail, 'phone' => $this->phone, 'ip' => getRemoteIP());
         $DB->insert('anonymous', $data);
         $id = $DB->val("SELECT currval('anonymous_id_seq');");
         $error = $DB->error;
     }
     return $id;
 }
Example #3
0
 public function _request($url, $xml, $scope = '')
 {
     if (!$this->_log) {
         $this->_log = new log('wm_payments/wm_payments-%d%m%Y.log');
     }
     $this->_log->linePrefix = '%d.%m.%Y %H:%M:%S : ' . getRemoteIP() . " : {$scope} : ";
     $res = parent::_request($url, $xml, $scope);
     $this->_log->writeln('REQUEST:');
     $this->_log->writeln($res->GetRequest());
     $this->_log->writeln('RESPONSE:');
     $this->_log->writeln($res->GetResponse());
     return $res;
 }
Example #4
0
function EditOpinion($op_id, $message, $rating, $counter, $from = 'frl')
{
    @session_start();
    $objResponse = new xajaxResponse();
    $message = trim($message);
    if (!in_array($rating, array(-1, 0, 1))) {
        $objResponse->assign('rating_error', 'innerHTML', 'Вы не выбрали категорию отзыва');
    } elseif ($message == '') {
        $objResponse->script("opinionFormError('error_edit_msg_{$op_id}');");
    } elseif (strlen($message) > opinions::$opinion_max_length) {
        $objResponse->script("opinionMaxLengthError('edit_msg_{$op_id}', " . opinions::$opinion_max_length . ');');
    } else {
        $message = str_replace('&', '&', $message);
        $message = stripslashes($message);
        $message = change_q_x($message, FALSE, TRUE, '', false, false);
        $msg = opinions::GetMessageById($op_id);
        $old_rating = $msg['rating'];
        if (get_uid(0) == $msg['fromuser_id'] || hasPermissions('users')) {
            $error = opinions::Edit($msg['fromuser_id'], $op_id, $message, $rating, getRemoteIP(), hasPermissions('users'), get_uid(0));
        } else {
            $error = 'Ошибка';
        }
        if (!$error) {
            $msg = opinions::GetMessageById($op_id);
            if ($msg) {
                $user = new users();
                $user->GetUserByUID($_SESSION['page_user_id']);
                $objResponse->assign('opid_' . $op_id, 'innerHTML', opinions::printTheme($msg, $from, $counter, false));
                $ot = $old_rating == 1 ? 'plus' : ($old_rating == -1 ? 'minus' : 'neitral');
                $nt = $rating == 1 ? 'plus' : ($rating == -1 ? 'minus' : 'neitral');
                $objResponse->call('opinionChConuters', 'ops-' . $from . $ot, 'ops-' . $from . $nt);
                $block_class = 'ops-one-' . $nt;
                $objResponse->script("\$('opid_{$op_id}').removeClass('ops-one-plus').removeClass('ops-one-neitral').removeClass('ops-one-minus');");
                $objResponse->script("\$('opid_{$op_id}').addClass('{$block_class}')");
                $objResponse->script("opinionCheckMaxLengthStop('edit_msg_{$op_id}');");
            } else {
                $objResponse->script("alert('" . serialize($msg) . "')");
            }
        } else {
            $objResponse->script("alert('" . $error . "')");
        }
    }
    return $objResponse;
}
Example #5
0
function processForm($aFormValues)
{
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/smail.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/blogs.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
    global $session;
    session_start();
    get_uid(false);
    $objResponse = new xajaxResponse();
    //$pname = change_q($_POST['name'], true);
    $msg = change_q($aFormValues['calltext'], false, 0);
    //$mail = trim($_POST['mail']);
    //$attach = $_FILES['attach'];
    $login = $_SESSION['login'] ? $_SESSION['login'] : '******';
    $tn = 0;
    $f_name = '';
    $uid = get_uid(false);
    $usr = new users($uid);
    $pname = $_SESSION['name'] . ' ' . $_SESSION['surname'];
    $mail = $usr->GetField($uid, $error, 'email');
    if (!$msg) {
        $alert['msg'] = 'Поле заполнено некорректно';
        $error_flag = 1;
    }
    if (!$error_flag) {
        $error .= blogs::NewThread($uid, 3, 0, $name, $msg, $f_name, getRemoteIP(), 1, $tn);
    }
    if (!$error && !$error_flag) {
        $sm = new smail();
        $error .= $sm->NewFeedbackPost($pname, $msg, $mail, $_SESSION['login'], 4);
        $msg = $name = $mail = '';
        $info_msg = '<br><center><table class="view_info" border="0" cellpadding="2" cellspacing="0"><tbody><tr class="n_qpr"><td height="20"><img src="/images/ico_ok.gif" alt="" border="0" height="18" width="19"></td><td nowrap>Ваше сообщение отправлено</td></tr></tbody></table>';
        $objResponse->assign('calltext', 'value', '');
        $objResponse->assign('cbok', 'innerHTML', $info_msg);
        //$objResponse->assign("submitButton","disabled",false);
        $objResponse->assign('submitButton', 'value', 'Отправить');
    }
    return $objResponse;
}
Example #6
0
 /**
  * Проверяем фиксируем UTM метки.
  * 
  * @return bool
  */
 public function checkUtm()
 {
     $sess_id = session_id();
     //После авторизации обновляем UID пользователя
     if (!isset($_SESSION['ga_stat_updated']) && isset($_SESSION['uid']) && $_SESSION['uid'] > 0) {
         $this->db()->update(self::TABLE, array('user_id' => $_SESSION['uid']), 'user_id IS NULL AND sess_id = ?', $sess_id);
         $_SESSION['ga_stat_updated'] = true;
     }
     if (!isset($_GET['utm_source'], $_GET['utm_medium'], $_GET['utm_campaign'])) {
         return false;
     }
     $utm_source = __paramInit('string', 'utm_source', null, null, 150);
     $utm_medium = __paramInit('string', 'utm_medium', null, null, 150);
     $utm_campaign = __paramInit('string', 'utm_campaign', null, null, 150);
     if (empty($utm_source) && empty($utm_medium) && empty($utm_campaign)) {
         return false;
     }
     //Хеш на ссылку живет 30 минут в течении жизни сессии
     $hash = md5($_SERVER['REQUEST_URI'] . date('d.m.Y H') . (date('i') > 30));
     //Не фиксируем метки на одинаковые страницы и исключаем накрутку
     if (isset($_SESSION['ga_stat_url_hash'][$hash])) {
         return false;
     }
     $_SESSION['ga_stat_url_hash'][$hash] = true;
     //Храним максимум до 100 разных хеш-ссылок в сессии и старые выбрасываем
     if (count($_SESSION['ga_stat_url_hash']) > 100) {
         $_SESSION['ga_stat_url_hash'] = array_slice($_SESSION['ga_stat_url_hash'], -100);
     }
     //Фиксируем метку
     $data = array('utm_source' => $utm_source, 'utm_medium' => $utm_medium, 'utm_campaign' => $utm_campaign, 'ip' => getRemoteIP(), 'url' => parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), 'sess_id' => $sess_id);
     if (isset($_SESSION['uid']) && $_SESSION['uid'] > 0) {
         $data['user_id'] = $_SESSION['uid'];
     }
     $ret = $this->db()->insert(self::TABLE, $data);
     return $ret;
 }
Example #7
0
function checkLogin($mode = 'REDIRECT')
{
    $sql = "UPDATE " . DB_PREPEND . "phpwcms_userlog SET logged_in=0, logged_change='" . time() . "' ";
    $sql .= "WHERE logged_in=1 AND (" . time() . "-logged_change) > " . intval($GLOBALS['phpwcms']["max_time"]);
    _dbQuery($sql, 'UPDATE');
    checkLoginCount();
    if (empty($_SESSION["wcs_user"])) {
        @session_destroy();
        $ref_url = '';
        if (!empty($_SERVER['QUERY_STRING'])) {
            $ref_url = '?ref=' . rawurlencode(PHPWCMS_URL . 'phpwcms.php?' . xss_clean($_SERVER['QUERY_STRING']));
        }
        if ($mode == 'REDIRECT') {
            // check again if user was logged in and this is a valid redirect request
            $sql = 'SELECT COUNT(*)  FROM ' . DB_PREPEND . 'phpwcms_userlog WHERE ';
            $sql .= "logged_ip=" . _dbEscape(getRemoteIP()) . " AND ";
            $sql .= '( ' . time() . ' - logged_change ) < 3600';
            $ref_url = _dbCount($sql) > 0 ? get_login_file() . $ref_url : '';
            headerRedirect(PHPWCMS_URL . $ref_url);
        } else {
            return false;
        }
    }
    return true;
}
Example #8
0
 /**
  * Серый список IP
  * 
  * @param users $user
  */
 function checkGrayIp($user)
 {
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/gray_ip.php';
     $aGrayList = gray_ip::getGrayListByRegIp(getRemoteIP());
     if ($aGrayList) {
         // есть записи в списке первичных IP
         gray_ip::addSecondaryIp($user->uid, $user->login, $user->role, $aGrayList);
     }
 }
Example #9
0
        foreach ($cnt_form["target"] as $value) {
            if (strtolower($cnt_form['fromEmail']) == strtolower($value)) {
                $POST_ERR[] = '@@Sender&#8217;s email must be different from recipient&#8217;s email@@';
                break;
            }
        }
    }
}
// do $POST_ERR test again to handle possible duplicates
// in case 'checktofrom' = 1
if (!empty($POST_DO) && empty($POST_ERR)) {
    // check if there are form values which should be saved in db
    if (count($POST_savedb)) {
        $POST_savedb_sql = 'INSERT INTO ' . DB_PREPEND . 'phpwcms_formresult ';
        $POST_savedb_sql .= '(formresult_pid, formresult_ip, formresult_content) VALUES (';
        $POST_savedb_sql .= $crow['acontent_id'] . ", " . _dbEscape(getRemoteIP()) . ", ";
        $POST_savedb_sql .= _dbEscape(serialize($POST_savedb)) . ")";
        $POST_savedb_sql = _dbQuery($POST_savedb_sql, 'INSERT');
    }
    // send mail, include phpmailer class
    require_once PHPWCMS_ROOT . '/include/inc_ext/phpmailer/PHPMailerAutoload.php';
    // now run all CC -> but sent as full email to each CC recipient
    if (count($cnt_form['cc'])) {
        $mail = new PHPMailer();
        $mail->Mailer = $phpwcms['SMTP_MAILER'];
        $mail->Host = $phpwcms['SMTP_HOST'];
        $mail->Port = $phpwcms['SMTP_PORT'];
        if ($phpwcms['SMTP_AUTH']) {
            $mail->SMTPAuth = 1;
            $mail->Username = $phpwcms['SMTP_USER'];
            $mail->Password = $phpwcms['SMTP_PASS'];
Example #10
0
/**
 * Проверка на наши запросы POST, GET защита от CSRF
 *
 */
function csrf_magic()
{
    static $log;
    if (defined("NO_CSRF")) {
        return true;
    }
    // Не проеверяем если отключена проверка в скрипте
    if ($_POST['u_token_key'] != $_SESSION['rand']) {
        if (!$log) {
            require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/log.php";
            $log = new log('csrf/' . SERVER . '-%d%m%Y.log', 'a', '%d.%m.%Y %H:%M:%S - ' . getRemoteIP() . ' "' . $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI'] . '"' . ' "' . $_SERVER['HTTP_USER_AGENT'] . '"');
        }
        $log->writeln(" post_key: {$_POST['u_token_key']}, session_key: {$_SESSION['rand']}");
        $_POST = array();
        $_REQUEST = array();
    }
}
 public function registration($type_wizard = step_wizard_registration::TYPE_WIZARD_EMP)
 {
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/captcha.php";
     $action = __paramInit('string', null, 'action');
     if ($this->status == step_wizard::STATUS_CONFIRM) {
         if ($_SESSION['email'] == 0) {
             require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/users.php";
             $user = new users();
             $email = $user->GetField(wizard::getUserIDReg(), $error, "email");
             $_SESSION['email'] = $email;
         }
         if ($action == registration::ACTION_SEND_MAIL) {
             $send = registration::actionSendMail(false);
             if ($send) {
                 header("Location: /wizard/registration/");
                 exit;
             }
         }
     }
     $type_user = $type_wizard;
     if ($action == 'registration' && $this->status == 0) {
         $error = array();
         if (!$_SESSION["regform_captcha_entered"]) {
             session_start();
             $captchanum = __paramInit('string', null, 'captchanum');
             $num = __paramInit('string', null, 'rndnum');
             $_SESSION['w_reg_captcha_num'] = $captchanum;
             $captcha = new captcha($captchanum);
             if (!$captcha->checkNumber($num)) {
                 $error['captcha'] = 'Неверный код. Попробуйте еще раз';
                 unset($_SESSION['w_reg_captcha_num']);
             }
         }
         if ($type_wizard == step_wizard_registration::TYPE_WIZARD_EMP) {
             require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/employer.php";
         } else {
             require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/freelancer.php";
         }
         $login = trim(__paramInit('string', null, 'login'));
         $email = trim(__paramInit('string', null, 'email'));
         $agree = trim(__paramInit('string', null, 'agree'));
         $phone = trim(__paramInit('string', null, 'phone'));
         $smscode = trim(__paramInit('string', null, 'smscode'));
         // пароль берем напрямую из $_POST, а то __paramInit режет спецсимволы (пароль хешируется - SQL инъекция невозможна)
         $passwd = $_POST['password'];
         if (!$agree) {
             $error['agree'] = 'Прочтите и согласитесь с правилами';
         }
         if ($passwd == '') {
             $error['pwd'] = 'Введите пароль';
         }
         if (!preg_match("/^[a-zA-Z0-9]+[-a-zA-Z0-9_]{2,}\$/", $login)) {
             $error['login'] = '******';
         }
         if (in_array(strtolower($login), $GLOBALS['disallowUserLogins'])) {
             $error['login'] = '******';
         }
         if (!is_email($email)) {
             $error['email'] = 'Поле заполнено некорректно';
         }
         if ($smscode != $_SESSION["smsCode"]) {
             $error['smscode'] = 'Код не совпал';
         }
         if ($phone != $_SESSION["reg_phone"]) {
             $error['phone'] = 'Вы вводили другой номер при запросе кода';
         }
         $phone = preg_replace("#^\\+#", "", $_SESSION["reg_phone"]);
         if (empty($error['login'])) {
             $sql = "SELECT uid FROM users WHERE lower(login) = ?";
             if ($this->_db->val($sql, strtolower($login))) {
                 $error['login'] = '******';
             }
         }
         if (empty($error['email']) && empty($error['captcha'])) {
             require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/temp_email.php";
             if (temp_email::isTempEmail($email)) {
                 $error['email'] = 'К сожалению, регистрация аккаунта на указанный адрес электронной почты невозможна. Пожалуйста, для регистрации воспользуйтесь почтовым адресом другого домена';
             } else {
                 $sql = "SELECT uid FROM users WHERE lower(email) = ?";
                 if ($this->_db->val($sql, strtolower($email))) {
                     $error['email'] = 'Указанная вами электронная почта уже зарегистрирована. Авторизуйтесь на сайте или укажите другую электронную почту.';
                 }
             }
         }
         if (count($error) == 0) {
             if ($type_wizard == step_wizard_registration::TYPE_WIZARD_EMP) {
                 $newuser = new employer();
             } else {
                 $newuser = new freelancer();
             }
             $newuser->checked_name = false;
             if ($type_wizard == step_wizard_registration::TYPE_WIZARD_EMP) {
                 $newuser->role = 1;
             } else {
                 $newuser->role = 0;
             }
             $newuser->login = substr($login, 0, 15);
             $newuser->email = substr($email, 0, 64);
             $newuser->passwd = substr($passwd, 0, 24);
             $id = $newuser->Create($rerror, $error);
             if ($id && !$error) {
                 require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/activate_code.php";
                 $this->parent->saveActionWizard($this, step_wizard::STATUS_CONFIRM);
                 $this->parent->bindUserIDReg($id);
                 unset($_SESSION['ref_uri']);
                 require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/smail.php';
                 $smail = new smail();
                 $bSuspect = users::isSuspiciousUser($id, $newuser->login, '', $newuser->uname, '', $newuser->usurname, '');
                 $sPasswd = $bSuspect ? $newuser->passwd : '';
                 // чтобы из админки можно было выслать $smail->NewUser
                 $code = activate_code::Create($id, $newuser->login, $sPasswd, $error);
                 if (!$bSuspect) {
                     $_SESSION['suspect'] = false;
                     // юзер не подозрительный - сразу отпавляем юзеру письмо с кодом активации
                     $smail->NewUser($newuser->login, false, $code, $this->getWizardUserID(), $newuser->role ? 'emp' : 'frl');
                 } else {
                     $_SESSION['suspect'] = true;
                     // отправляем уведомление админу о том, что зарегистрировался подозрительный юзер
                     // если админ его одобрит - то письмо с кодом активации уйдет из админки
                     $smail->adminNewSuspectUser($newuser->login, $newuser->uname, $newuser->usurname);
                 }
                 //Записываем подтвержденный номер телефона в финансы
                 require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/sms_gate.php";
                 $phone = '+' . preg_replace("#^\\+#", "", $_SESSION["reg_phone"]);
                 unset($_SESSION["regform_captcha_entered"]);
                 sms_gate::saveSmsInfo($phone, $_SESSION["reg_sms_isnn"], $_SESSION["smsCode"], $_SESION["reg_sms_date_send"], $id);
                 // стираем куку, чтобы показался блок "Вы успешно зарегистрировались"
                 setcookie('master_auth', "", time() - 3600, '/');
                 // Серый список IP ----------------------
                 require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/gray_ip.php';
                 $aGrayList = gray_ip::getGrayListByRegIp(getRemoteIP());
                 if ($aGrayList) {
                     // есть записи в списке первичных IP
                     gray_ip::addSecondaryIp($id, $newuser->login, $newuser->role, $aGrayList);
                 }
                 //---------------------------------------
                 $_SESSION['email'] = $newuser->email;
                 header("Location: /wizard/registration/");
                 exit;
             }
         }
     } elseif ($action == 'authorization') {
         $auth_error = $this->authorization($auth_login);
     }
     include $_SERVER['DOCUMENT_ROOT'] . "/wizard/registration/steps/tpl.step.reg.php";
 }
Example #12
0
 /**
  * Конструктор принимает три обязательных параметра и восстанавливает сессию
  * подключения (или создает новую, если ее нет).
  * 
  * @param int    $uid  id пользователя
  * @param string $cid  id сессии
  * @param string $ckey ключ сессии
  */
 public function __construct($uid, $cid, $ckey)
 {
     if (!$uid || !$cid || !$ckey) {
         return;
     }
     $this->_uid = $uid;
     $this->_cid = $cid;
     $this->_ckey = md5($ckey . getRemoteIP() . $_SERVER['HTTP_USER_AGENT']);
     $this->_memBuff = new memBuff();
     $this->_loadConnect();
     if (empty($this->_connect)) {
         $this->_connect = array('evid' => $this->_counter('evid'), 'cid' => $this->_cid, 'ckey' => $this->_ckey, 'uptime' => time());
     }
     $this->_settings = array('chat' => (int) $_SESSION['chat'], 'sound' => (int) $_SESSION['chat_sound']);
 }
Example #13
0
 /**
  * Вставка записи.
  *
  * @param $fid            идентификатор файла
  * @param $file_name      имя файла
  * @param $old_file_name  имя файла, который был переименован при замене вновь загруженым
  *
  * @return int идентификатор записи
  **/
 public static function addRecord($fid, $file_name, $old_file_name)
 {
     global $DB;
     return $DB->insert(self::TABLE, array('filename' => $file_name, 'fid' => $fid, 'old_file_name' => $old_file_name, 'ip' => getRemoteIP(), 'admin_id' => get_uid(false)), 'id');
 }
Example #14
0
 /**
  * Конструктор. Инициализация переменных
  */
 function static_compress($enabled = COMPRESS_STATIC, $options = array())
 {
     if (isset($options['bem']) && $options['bem']) {
         $this->bem_src_path = $options['bem'];
     } else {
         $this->bem_src_path = self::BEM_SRC_PATH;
     }
     $this->_root = $options['root'];
     //		$this->memBuff = new memBuff();
     $this->enabled = $enabled;
     $this->_log = new log('static/' . SERVER . '-%d.log');
     $this->_log->linePrefix = '%d.%m.%Y %H:%M:%S : ' . str_pad(getRemoteIP(), 15) . ' ';
     $this->isMSIE = stripos($_SERVER['HTTP_USER_AGENT'], 'msie ') !== false;
 }
Example #15
0
     $files = array();
     $attach = $_FILES['attach'];
     if (is_array($attach) && !empty($attach['name'])) {
         foreach ($attach['name'] as $key => $v) {
             if (!$attach['name'][$key] || $key > articles_comments::MAX_FILE_COUNT) {
                 continue;
             }
             $files[] = new CFile(array('name' => $attach['name'][$key], 'type' => $attach['type'][$key], 'tmp_name' => $attach['tmp_name'][$key], 'error' => $attach['error'][$key], 'size' => $attach['size'][$key]));
         }
     }
     list($att, $uperr, $error_flag) = $comments->UploadFiles($files, array('width' => 390, 'height' => 1000, 'less' => 0));
     if ($uperr) {
         $alert[2] = $uperr;
     }
     if (!isset($alert)) {
         $new = $comments->Add($uid, $reply, $thread, $msg, $yt_link, $att, getRemoteIP(), $err, $tn);
     }
     if ($new) {
         $q = array();
         parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $q);
         $q['goto'] = $new;
         header('Location: ./' . url($GET, $q, true, '?'));
         //            echo "<script>document.location.href = '{$_SERVER['HTTP_REFERER']}#c_$new';</script>";
         exit;
     }
     break;
 case 'edit-comment':
     if (!$uid) {
         header('Location: /fbd.php');
         die;
     }
Example #16
0
// script contains everything necessary to track ad banner clicks and so on...
// ----------------------------------------------------------------
// obligate check for phpwcms constants
if (!defined('PHPWCMS_ROOT')) {
    die("You Cannot Access This Script Directly, Have a Nice Day.");
}
// ----------------------------------------------------------------
// first check
if (isset($_GET['u']) && $_GET['u'] == PHPWCMS_USER_KEY) {
    $ads_id = intval($_GET['adclickval']);
    $sql = 'SELECT * FROM ' . DB_PREPEND . 'phpwcms_ads_campaign ';
    $sql .= 'WHERE adcampaign_id=' . $ads_id . ' AND adcampaign_status=1 LIMIT 1';
    $ad_data = _dbQuery($sql);
    if (!empty($ad_data[0]['adcampaign_data'])) {
        $ad_data = @unserialize($ad_data[0]['adcampaign_data']);
        $ads_userip = getRemoteIP();
        $ads_useragent = $_SERVER['HTTP_USER_AGENT'];
        $ads_ref = isset($_GET['r']) ? trim($_GET['r']) : '';
        $ads_cat = empty($_GET['c']) ? 0 : intval($_GET['c']);
        $ads_article = empty($_GET['a']) ? 0 : intval($_GET['a']);
        if (empty($_COOKIE['phpwcmsAdsUserId']) || !preg_match('/^[0-9a-f]{32}$/', $ads_userid = $_COOKIE['phpwcmsAdsUserId'])) {
            $ads_userid = md5($ads_userip . microtime());
            setcookie('phpwcmsAdsUserId', $ads_userid, time() + 63072000, '/', getCookieDomain());
        }
        $sql = 'INSERT DELAYED INTO ' . DB_PREPEND . 'phpwcms_ads_tracking (';
        $sql .= 'adtracking_created, adtracking_campaignid, adtracking_ip, adtracking_cookieid, ';
        $sql .= 'adtracking_countclick, adtracking_countview, adtracking_useragent, adtracking_ref, ';
        $sql .= 'adtracking_catid, adtracking_articleid) VALUES (';
        $sql .= "NOW(), " . $ads_id . ", " . _dbEscape($ads_userip) . ", " . _dbEscape($ads_userid) . ", ";
        $sql .= "1, 0, " . _dbEscape($ads_useragent) . ", " . _dbEscape($ads_ref) . ", " . $ads_cat . ", " . $ads_article . ")";
        @_dbQuery($sql, 'INSERT');
Example #17
0
    /**
     * Создает комментарий.
     *
     * @param int    $oid     id предложения, который комментируют
     * @param string $comment комментарий
     * @param int    $reply   id комментария на который отвечают или 0, если комментарий 1-го уровня
     *
     * @return string сообщение об ошибке или пустая строка, если все нормально
     */
    public function CreateComment($oid, $comment, $reply = 0)
    {
        global $DB;
        $oid = intval($oid);
        $reply = intval($reply);
        //$comment = substr(change_q(trim($comment), true, 90), 0, 1000);
        if (!($offer = $this->GetOffer($oid))) {
            return 'Несуществующее предложение';
        }
        if ($offer['closed'] == 't') {
            return 'Проект завершен';
        }
        // пользователь забанен в текущем предложении?
        if ($this->is_banned) {
            return 'Забаненые пользователи не могут добавлять комментарии';
        }
        // пользователь запретил комментировать свое предложение?
        if ($offer['comm_blocked'] == 't') {
            return 'Автор предложения отключил возможность комментирования';
        }
        // добавляем комментарий
        $ip = getRemoteIP();
        $nStopWordsCnt = 0;
        if (!is_pro()) {
            require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/stop_words.php';
            $stop_words = new stop_words();
            $nStopWordsCnt = $stop_words->calculate($comment);
        }
        $sModVal = is_pro() || !$nStopWordsCnt ? 'NULL' : '0';
        $sql = '
			INSERT INTO projects_contest_msgs
				(offer_id, user_id, reply_to, from_ip, msg, post_date, moderator_status)
			VALUES
				(?i, ?i, ' . ($reply ? $reply : 'NULL') . ", ?, ?, NOW(), {$sModVal})\n\t\t\tRETURNING id\n\t\t";
        $this->new_cid = $DB->val($sql, $oid, $this->uid, $ip, $comment);
        if ($error = $DB->error) {
            return $error;
        }
        if (!is_pro() && $nStopWordsCnt) {
            require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/user_content.php';
            $DB->insert('moderation', array('rec_id' => $this->new_cid, 'rec_type' => user_content::MODER_CONTEST_COM, 'stop_words_cnt' => $nStopWordsCnt));
        }
        $sql = 'SELECT po.user_id AS frl, p.user_id AS emp, e.is_pro AS emp_is_pro, f.is_pro AS frl_is_pro 
                FROM projects_offers po
                LEFT JOIN projects p ON p.id = po.project_id 
                LEFT JOIN employer e ON e.uid = p.user_id 
                LEFT JOIN freelancer f ON f.uid = po.user_id 
                WHERE po.id = ?i LIMIT 1';
        $users = $DB->row($sql, $oid);
        // стираем мемкеш
        $memBuff = new memBuff();
        if ((int) $users['frl'] !== (int) $this->uid) {
            $memBuff->delete("prjMsgsCnt{$users['frl']}");
            $memBuff->delete("prjMsgsCntWst{$users['frl']}");
        } elseif ((int) $users['emp'] !== (int) $this->uid) {
            $memBuff->delete("prjMsgsCnt{$users['emp']}");
            $memBuff->delete("prjLastMess{$users['emp']}");
        }
        return '';
    }
Example #18
0
 /**
  * Сохраняет в сессии текущий ip адрес и страну-город для баннерки,
  * Если ip поменялся, страна город также обновляются.
  */
 public function CheckSessionCountryCity()
 {
     $DB = new DB('banner');
     @session_start();
     $ip = getRemoteIP();
     if (!isset($_SESSION['last_ip']) || isset($_SESSION['last_ip']) && $_SESSION['last_ip'] != $ip || !isset($_SESSION['banners_city']) && !isset($_SESSION['banners_country'])) {
         $_SESSION['last_ip'] = $ip;
         $sql = 'SELECT city_id, country
             FROM ban_netwoks
             INNER JOIN ban_city ON ban_city.id = ban_netwoks.city_id
             WHERE ? BETWEEN ip_from AND ip_to
             ORDER BY ip_to LIMIT 1';
         $res = $DB->row($sql, $ip);
         $_SESSION['banners_city'] = intval($res['city_id']);
         $_SESSION['banners_country'] = $res['country'];
     }
 }
Example #19
0
 private function _error($optype = null, $key = null)
 {
     if (!$this->_log->linePrefix) {
         $this->_log->linePrefix = '%d.%m.%Y %H:%M:%S - ' . getRemoteIP() . ' - "' . $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI'] . '" : ';
     }
     $rcode = $this->getResultCode();
     $rmsg = $this->getResultMessage();
     $ttime = $this->_log->getTotalTime('%H:%M:%S', 3);
     if ($rcode == Memcached::RES_NOTFOUND || $rcode == Memcached::RES_SUCCESS || $optype == 'add' && $rcode == Memcached::RES_NOTSTORED) {
         return;
     }
     $this->_log->writeln("[error: {$rcode}, method: {$optype}, key: {$key}, time: {$ttime}] {$rmsg}");
 }
Example #20
0
$footer = "../footer.html";
if (!$user->login) {
    include ABS_PATH . "/404.php";
    exit;
}
$obj_memcache = new memBuff();
if ($_SESSION['login']) {
    if ($_SESSION['login'] != $user->login) {
        if (!$obj_memcache->get('user_view_' . strtolower($user->login) . '_' . strtolower($_SESSION['login']))) {
            $obj_memcache->set('user_view_' . strtolower($user->login) . '_' . strtolower($_SESSION['login']), 1, 3600);
            $user->IncHits($user->login);
        }
    }
} else {
    if (!$obj_memcache->get('user_view_' . strtolower($user->login) . '_' . getRemoteIP())) {
        $obj_memcache->set('user_view_' . strtolower($user->login) . '_' . getRemoteIP(), 1, 3600);
        $user->IncHits($user->login);
    }
}
if ($user->is_banned && !hasPermissions('users')) {
    if (!$content) {
        $content = "ban.php";
    }
} else {
    if (!$content) {
        $content = $page == 'opinions' ? 'content_new.php' : 'content.php';
        // !!! проверить
        /*
          if ($_SESSION['login'] == $name) {
              $content = "content_setup.php";
              $fpath = $_SERVER['DOCUMENT_ROOT'] . "/user/employer/";
Example #21
0
     $asid = $attachedfiles->createSessionID();
     $attachedfiles->addNewSession($asid);
     $attachedfiles_session = $asid;
 } else {
     $attachedfiles = new attachedfiles($attachedfiles_session);
     $asid = $attachedfiles_session;
 }
 $attachedfiles_info = $attachedfiles->calcFiles();
 if ($attachedfiles_session) {
     $countfiles = 0;
 }
 if ($msg === '' && $question === '' && empty($alert[5]) && !($countfiles || $attachedfiles_info['count']) && $yt_link === '') {
     $error_flag = 1;
     $alert[2] = 'Ошибка. Сообщение не должно быть пустым!';
 } elseif (!$error && !$error_flag && ($msg !== '' || $attach['name'] || $attach_have || $attach_delete || $question || $yt_link || $attachedfiles_info['count'])) {
     $blog_obj->Edit($_SESSION['uid'], $thread, $msg, $msg_name, $files, getRemoteIP(), $err, $mod, NULL, $gr, $t, $attach_delete, $olduserlogin, $yt_link, $close_comments, $is_private, $ontop, null, $question, $answers, $answers_exists, $multiple);
     //$nStopWordsCnt = $stop_words->calculate( $msg, $msg_name, $question, $answers, $answers_exists );
     $attachedfiles_files = $attachedfiles->getFiles(array(1, 3, 4));
     $blog_obj->addAttachedFiles($attachedfiles_files, $thread, $olduserlogin, $draft_id ? true : false);
     $attachedfiles->clear();
     //$blog_obj->insertIntoModeration( $thread, $nStopWordsCnt ); // больше не модерируем
     if ($err) {
         $alert = $alert + $err;
     }
     if ($draft_id && !($alert || $error || $error_flag)) {
         require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/drafts.php';
         drafts::DeleteDraft($draft_id, get_uid(false), 3, true);
     }
 }
 if ($site == 'journal') {
     unset($_SESSION['user.journal.change.result']);
Example #22
0
 * $Id$
 * 
 * GeoGraph geographic photo archive project
 * This file copyright (C) 2008 Barry Hunter (geo@barryhunter.co.uk)
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
require_once 'geograph/global.inc.php';
init_session();
header("HTTP/1.0 204 No Content");
header("Status: 204 No Content");
header("Content-Length: 0");
flush();
$db = NewADOConnection($GLOBALS['DSN']);
if (!$db) {
    die('Database connection failed');
}
$ins = "INSERT INTO vote_log SET\r\n\ttype = " . $db->Quote(@$_GET['t']) . ",\r\n\tid = " . intval(@$_GET['id']) . ",\r\n\tvote = " . intval(@$_GET['v']) . ",\r\n\tipaddr = INET_ATON('" . getRemoteIP() . "'),\r\n\tuser_id = " . intval($USER->user_id);
$db->Execute($ins);
Example #23
0
function checkLoginCount()
{
    $check = 0;
    if (!empty($_SESSION["wcs_user"])) {
        $sql = "SELECT COUNT(*) FROM " . DB_PREPEND . "phpwcms_userlog WHERE logged_user="******"wcs_user"]) . " AND logged_in=1";
        if (!empty($phpwcms['Login_IPcheck'])) {
            $sql .= " AND logged_ip=" . _dbEscape(getRemoteIP());
        }
        $check = _dbCount($sql);
        if ($check) {
            $sql = "UPDATE " . DB_PREPEND . "phpwcms_userlog SET logged_change=" . time() . " WHERE ";
            $sql .= "logged_user="******"wcs_user"]) . " AND logged_in=1";
            _dbQuery($sql, 'UPDATE');
        } else {
            destroyBackendSessionData();
        }
    }
    return $check;
}
Example #24
0
            $table .= "<tr bgcolor=\"#F4F4F4\">";
            $table .= "<td class=\"error\">[" . $key . "]</td>";
            $table .= "<td class=\"error\">" . html($value) . "</td>";
            $table .= "</tr>\n";
        }
        $error_template = read_textfile(PHPWCMS_ROOT . '/include/inc_lang/formmailer/' . $lang . '_formmailer.error.html');
        $error_template = str_replace("<!-- RESULT //-->", $table, $error_template);
        echo $error_template;
    }
} else {
    $translate[$lang]["bodyLine1"] = str_replace("###date###", date($translate[$lang]["dateFormat"]), $translate[$lang]["bodyLine1"]);
    $translate[$lang]["bodyLine1"] = str_replace("###time###", date($translate[$lang]["timeFormat"]), $translate[$lang]["bodyLine1"]);
    $body = $translate[$lang]["bodyLine1"] . "\n";
    $body .= $translate[$lang]["bodyLine2"] . "\n";
    $body .= $_SERVER['HTTP_REFERER'] . " \n";
    $body .= "IP: " . getRemoteIP() . " \n\n";
    $body .= "====================================================================\n\n";
    $body .= $translate[$lang]["bodyRecipient"];
    if ($recipient_name) {
        $body .= $recipient_name . " (" . $recipient . ")\n\n";
    } else {
        $body .= $recipient . "\n\n";
    }
    $body .= "====================================================================\n\n";
    $body .= $subject . "\n";
    $body .= "--------------------------------------------------------------------\n";
    $l = 0;
    if (is_array($form) && count($form)) {
        foreach ($form as $key => $value) {
            $x = strlen($key);
            if ($x > $l) {
/**
 * Сохранение Блоги: посты и комментарии
 * 
 * @param object $objResponse xajaxResponse
 * @param string $rec_id идентификатор записи
 * @param string $rec_type тип записи
 * @param array $aForm массив данных
 * @param string $sDrawFunc имя функции для выполнения после сохранения
 */
function _admEditBlogsSaveForm(&$objResponse, $rec_id = '', $rec_type = '', $aForm = array(), $sDrawFunc = '')
{
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/attachedfiles.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/user_content.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/blogs.php';
    $mod = hasPermissions('blogs') ? 0 : 1;
    $alert = array();
    $olduserlogin = $aForm['olduserlogin'];
    // логин автора блога
    $close_comments = $aForm['close_comments'] ? 't' : 'f';
    // запретить комментирование
    $is_private = $aForm['is_private'] ? 't' : 'f';
    // показывать только мне
    $ontop = $aForm['ontop'] ? 't' : 'f';
    // закрепить тему наверху
    $categ = change_q_x($aForm['category'], true);
    // раздел
    $close_comments = $rec_type == 2 ? 'n' : $close_comments;
    $is_private = $rec_type == 2 ? 'n' : $is_private;
    list($gr, $t) = explode('|', $categ);
    // название, текст
    if (strlen($aForm['msg']) > blogs::MAX_DESC_CHARS) {
        $error_flag = 1;
        $alert[1] = 'Максимальный размер сообщения ' . blogs::MAX_DESC_CHARS . ' символов!';
    }
    $msg = change_q_x(antispam($aForm['msg']), false, false, 'b|br|i|p|ul|li|cut|s|h[1-6]{1}', false, false);
    $name = substr_entity(change_q_x(antispam($aForm['name']), true, false), 0, 96, true);
    // ссылка на youtube
    $yt_link = $aForm['yt_link'] ? $aForm['yt_link'] : '';
    if ($yt_link != '') {
        $v_yt_link = video_validate($yt_link);
        if (!$v_yt_link) {
            $alert[4] = 'Неверная ссылка.';
        } else {
            $yt_link = $v_yt_link;
        }
    }
    // опросы
    $question = substr_entity(change_q_x(antispam(trim((string) $aForm['question'])), false, false, ''), 0, blogs::MAX_POLL_CHARS, true);
    $multiple = (bool) $aForm['multiple'];
    $answers = array();
    $answers_exists = array();
    $i = 0;
    if (is_array($aForm['answers']) && !empty($aForm['answers'])) {
        foreach ($aForm['answers'] as $pa) {
            if (trim((string) $pa) !== '') {
                $answers[] = substr_entity(change_q_x(antispam(preg_replace('/&/', '&amp;', (string) trim($pa))), false, false, ''), 0, blogs::MAX_POLL_ANSWER_CHARS * 2, true);
                $i++;
            }
        }
    }
    if (is_array($aForm['answers_exists']) && !empty($aForm['answers_exists'])) {
        foreach ($aForm['answers_exists'] as $key => $pa) {
            if (trim((string) $pa) !== '') {
                $answers_exists[$key] = substr_entity(change_q_x(antispam(preg_replace('/&/', '&amp;', (string) trim($pa))), false, false, ''), 0, blogs::MAX_POLL_ANSWER_CHARS * 2, true);
                $i++;
            }
        }
    }
    if ($i > 0 && $question === '') {
        $alert[5] = 'Введите текст вопроса';
    } else {
        if ($i > blogs::MAX_POLL_ANSWERS) {
            $alert[5] = 'Вы можете указать максимум ' . blogs::MAX_POLL_ANSWERS . ' отетов';
        } else {
            if ($i < 2 && $question !== '') {
                $alert[5] = 'Нужно указать минимум 2 варианта ответа в голосовании';
            }
        }
    }
    // файлы
    $files_session = $aForm['attachedfiles_session'];
    if (!$files_session) {
        $attachedfiles = new attachedfiles('', true);
        $asid = $attachedfiles->createSessionID();
        $attachedfiles->addNewSession($asid);
        $files_session = $asid;
    } else {
        $attachedfiles = new attachedfiles($files_session);
        $asid = $files_session;
    }
    $files_info = $attachedfiles->calcFiles();
    if ($msg === '' && $question === '' && empty($alert[5]) && !$files_info['count'] && $yt_link === '') {
        $alert[1] = 'Сообщение не должно быть пустым';
    }
    if (!$alert) {
        require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/messages.php';
        $blogs = new blogs();
        $blogs->Edit($_SESSION['uid'], $rec_id, $msg, $name, array(), getRemoteIP(), $err, $mod, '', $gr, $t, array(), $olduserlogin, $yt_link, $close_comments, $is_private, $ontop, null, $question, $answers, $answers_exists, $multiple);
        $files = $attachedfiles->getFiles(array(1, 3, 4));
        $blogs->addAttachedFiles($files, $rec_id, $olduserlogin, false);
        $attachedfiles->clear();
        $sReason = _parseReason($aForm['user_id'], $aForm['adm_edit_text']);
        messages::blogModifiedNotification($rec_type, $aForm['oldusertitle'], $aForm['post_time'], $aForm['user_name'], $aForm['user_surname'], $olduserlogin, $sReason);
        $content_id = user_content::MODER_BLOGS;
        _admEditAfterAll($objResponse, $content_id, $rec_id, $rec_type, $sDrawFunc, $aForm);
    } else {
        _setErrors($objResponse, $alert, array(1 => 'msg', 4 => 'yt_link', 5 => 'question'), $sDrawFunc);
    }
}
                 sendEmail(array('recipient' => $guestbook['notify_email'], 'subject' => 'New guestbook/comment entry', 'isHTML' => 0, 'text' => $guestbook['notify'], 'from' => $phpwcms["admin_email"], 'sender' => $phpwcms["admin_email"]));
             }
             $GLOBALS['_getVar']['guestbookentry'] = $guestbook['new_entry_id'];
             // to avoid double Post
             headerRedirect(abs_url(array(), array(), '', 'urlencode'));
         } else {
             $guestbook['readform'] = 0;
             $CNT_TMP .= '<div style="color:#FF3300;">A technical problem occured while signing to the guestbook</div>';
         }
     }
 }
 // do this after new gb entry was created
 if (isset($GLOBALS['_getVar']['guestbookentry'])) {
     $guestbook['sql'] = 'SELECT * FROM ' . DB_PREPEND . 'phpwcms_guestbook ';
     $guestbook['sql'] .= 'WHERE guestbook_id=' . intval($GLOBALS['_getVar']['guestbookentry']);
     $guestbook['sql'] .= " AND guestbook_ip=" . _dbEscape(getRemoteIP());
     $guestbook['new_entry'] = _dbQuery($guestbook['sql']);
     if (!empty($guestbook['new_entry'][0])) {
         $guestbook['readform'] = 1;
         $guestbook['post']['email'] = $guestbook['new_entry'][0]['guestbook_email'];
         $guestbook['post']['name'] = $guestbook['new_entry'][0]['guestbook_name'];
         $guestbook['post']['url'] = $guestbook['new_entry'][0]['guestbook_url'];
         $guestbook['post']['msg'] = $guestbook['new_entry'][0]['guestbook_msg'];
     }
     unset($GLOBALS['_getVar']['guestbookentry']);
 }
 // start guestbook form
 if (empty($guestbook['gb_login_post'])) {
     $guestbook['show_postform'] = true;
 } elseif (_getFeUserLoginStatus()) {
     $guestbook['show_postform'] = true;
Example #27
0
}
if (isSpam($msg)) {
    $ok = false;
    $errors['msg'] = "Sorry, this looks like spam";
}
if (!$ok) {
    die("ERROR: " . implode('. ', $errors));
}
$smarty->assign_by_ref('msg', $msg);
$smarty->assign_by_ref('contactmail', $CONF['abuse_email']);
$enc_from_name = mb_encode_mimeheader($from_name, $CONF['mail_charset'], $CONF['mail_transferencoding']);
$smarty->assign('http_host', "{$_SERVER['HTTP_HOST']} on behalf of {$domain}");
$body = $smarty->fetch('email_usermsg.tpl');
$subject = "{$from_name} contacting you via {$domain}";
$encsubject = mb_encode_mimeheader($CONF['mail_subjectprefix'] . $subject, $CONF['mail_charset'], $CONF['mail_transferencoding']);
$ip = getRemoteIP();
$hostname = trim(`hostname -f`);
$received = "Received: from [{$ip}]" . " by {$hostname} " . "with HTTP;" . strftime("%d %b %Y %H:%M:%S -0000", time()) . "\n";
if (!empty($_REQUEST['client_ip']) && preg_match("/^[\\w\\.]+\$/", $_REQUEST['client_ip'])) {
    $received .= "Received: from [{$_REQUEST['client_ip']}]" . " by [{$id}] " . "with HTTP;" . strftime("%d %b %Y %H:%M:%S -0000", empty($_REQUEST['timestamp']) ? time() : intval($_REQUEST['timestamp'])) . "\n";
}
$mime = "MIME-Version: 1.0\n" . "Content-Type: text/plain; charset={$CONF['mail_charset']}\n" . "Content-Disposition: inline\n" . "Content-Transfer-Encoding: 8bit";
$from = "From: {$enc_from_name} <{$from_email}>\n";
$geofrom = "From: Geograph <{$CONF['mail_from']}>\n";
$envfrom = is_null($CONF['mail_envelopefrom']) ? null : "-f {$CONF['mail_envelopefrom']}";
if (preg_match('/(DORMANT|geograph\\.org\\.uk|geograph\\.co\\.uk|dev\\.null|deleted|localhost|127\\.0\\.0\\.1)/', $recipient->email)) {
    $email = $CONF['contact_email'];
    $body = "Sent as Geograph doesn't hold email address for this user [id {$recipient->user_id}]\n\n--\n\n" . $body;
} else {
    $email = $recipient->email;
}
Example #28
0
 /**
  * Сброс пароля пользователя в случайный пароль.
  *
  * @param    integer $uid    id пользователя
  * @param    string  $phone  телефон введенный в разделе безопасность
  *
  * @return   string          новый пароль, пусто если телефон не совпадает
  */
 public function ResetPasswordSMS($uid, $phone)
 {
     global $DB;
     $new_password = '';
     $phone = str_replace('+', '', $phone);
     $phone = '+' . $phone;
     $sql = 'SELECT u.uid FROM users u
             INNER JOIN sbr_reqv s ON s.user_id = u.uid
             WHERE u.uid=?i AND (s._1_mob_phone = ? OR s._2_mob_phone = ?)';
     if (pg_num_rows($DB->query($sql, $uid, $phone, $phone)) == 1) {
         mt_srand();
         $new_password = substr(md5(uniqid(mt_rand())), 0, self::MAX_NEW_PASSWORD_LENGTH);
         $sql = 'UPDATE users SET passwd=? WHERE uid=?i';
         $DB->query($sql, self::hashPasswd($new_password), $uid);
         // Пишем в лог смены паролей
         require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/restorepass_log.php';
         restorepass_log::SaveToLog($uid, getRemoteIP(), 2);
     }
     return $new_password;
 }
Example #29
0
    } elseif (strlen($pwd) < 6) {
        $error = 'Слишком короткий пароль (минимум — 6 символов)';
    } elseif (strlen($pwd) > 24) {
        $error = 'Слишком длинный пароль (максимум — 24 символа)';
    }
    if (!$error && $codes->user_id) {
        require_once ABS_PATH . '/classes/users.php';
        $user = new users();
        $user->passwd = $pwd;
        $err = $user->Update($codes->user_id, $res);
        $u_id = $codes->user_id;
        $codes->DelByUT($codes->user_id, 1);
        if (!$err) {
            $info = 'Изменения внесены';
            require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/smail.php';
            $smail = new smail();
            $smail->ChangePwd($codes->user_id, $pwd);
            // Пишем в лог смены паролей
            require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/restorepass_log.php';
            restorepass_log::SaveToLog($codes->user_id, getRemoteIP(), 1);
            $pwd = users::hashPasswd(trim(stripslashes($pwd)));
            $user->getUserByUID($u_id);
            login($user->login, $pwd);
            session_write_close();
            header('Location: /');
            exit;
        }
    }
}
$content = 'changepwd_inner.php';
include 'template3.php';
Example #30
0
         $alert[2] = "Слишком короткий пароль (минимум — 6 символов)";
     } elseif (strlen($pwd) > 24) {
         $error_flag = 1;
         $alert[2] = "Слишком длинный пароль (максимум — 24 символа)";
     }
     if (!$error_flag) {
         $frl = new users();
         $alert[1] = $frl->UpdatePwd($uid, $oldpwd, $pwd, 0);
         if (!$alert[1] && !$error_flag) {
             $info = "Изменения внесены";
             require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/smail.php";
             $smail = new smail();
             $smail->ChangePwd($uid, $pwd);
             // Пишем в лог смены паролей
             require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/restorepass_log.php";
             restorepass_log::SaveToLog($uid, getRemoteIP(), 3);
         }
     }
     break;
 case "foto_change":
     $foto = new CFile($_FILES['foto']);
     $del = trim($_POST['del']);
     $frl = new freelancer();
     if ($foto->name || $del == 1) {
         $error .= $frl->UpdateFoto($uid, $foto, $del);
         /*if (!$error) $info_msg = "Изменения внесены";
         		else $error = "Файл не удовлетворяет условиям загрузки";*/
         $nParam = !$error ? 1 : 2;
         if (!$error) {
             $_SESSION['photo'] = $frl->photo;
         }