Beispiel #1
0
 /**
  * @param string $api_key     API ключ UserEcho
  * @param string $project_key Ключ UserEcho
  * @param array  $user_info
  *
  * @return SSO KEY
  */
 public static function get_sso_token($api_key, $project_key, $user_info)
 {
     $sso_key = '';
     if ($uid = get_uid(false)) {
         $user = new users();
         $user->GetUserByUID($uid);
         $iv = str_shuffle('memoKomo1234QWER');
         $message = array('guid' => $uid, 'expires_date' => gmdate('Y-m-d H:i:s', time() + 86400), 'display_name' => $user->login, 'email' => $user->email, 'locale' => 'ru', 'verified_email' => true);
         // key hash, length = 16
         $key_hash = substr(hash('sha1', $api_key . $project_key, true), 0, 16);
         $message_json = json_encode(encodeCharset('CP1251', 'UTF-8', $message));
         // double XOR first block message_json
         for ($i = 0; $i < 16; ++$i) {
             $message_json[$i] = $message_json[$i] ^ $iv[$i];
         }
         // fill tail of message_json by bytes equaled count empty bytes (to 16)
         $pad = 16 - strlen($message_json) % 16;
         $message_json = $message_json . str_repeat(chr($pad), $pad);
         // encode json
         $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', '');
         mcrypt_generic_init($cipher, $key_hash, $iv);
         $encrypted_bytes = mcrypt_generic($cipher, $message_json);
         mcrypt_generic_deinit($cipher);
         // encode bytes to url safe string
         $sso_key = urlencode(base64_encode($encrypted_bytes));
     }
     return $sso_key;
 }
Beispiel #2
0
 /**
  * Добавить пользователя в избарнное
  *
  * @param integer $user_id       ИД пользователя, к которому добавляем
  * @param string  $target_login  Логин или uid добавляемого пользователя
  * @return string Сообщение об ошибке
  */
 function teamsAddFavorites($user_id, $target, $by_login = true)
 {
     $DB = new DB();
     $error = '';
     $user = new users();
     if ($by_login) {
         $user->GetUser($target);
         $target = $user->uid;
     } else {
         $user->GetUserByUID($target);
     }
     if ($user_id && $target && $user_id != $target) {
         if ($DB->val("SELECT teams_check(?i, ?i)", $user_id, $target)) {
             $error = 'Пользователь уже добавлен';
         } else {
             $DB->val("SELECT teams_add(?i, ?i)", $user_id, $target);
             if ($user->subscr[9]) {
                 require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/pmail.php";
                 $mail = new pmail();
                 $mail->addTeamPeople($user_id, $target);
             }
         }
     } else {
         $error = "Пользователь не определен";
     }
     return $error;
 }
Beispiel #3
0
    /**
     * Добавляет сообщение в обратную связь и отсылает письмо в необходимый отдел.
     * 
     * @param int    $uid   uid пользователя, если он авторизован
     * @param string $login имя пользователя, если он не авторизован
     * @param string $email email пользователя, если он не авторизован
     * @param int    $kind  id отдела (1-общие вопросы, 2-ошибки на сайте, 3-финансовый вопрос, 4-лич.менеджер, 5-сбр)
     * @param string $msg   сообщение
     * @param CFile  $files прикрепленный файл
     *
     * @return string возможная ошибка
     */
    public function Add($uid, $login, $email, $kind, $msg, $files, $additional = false)
    {
        global $DB;
        mt_srand();
        $uc = md5(microtime(1) . mt_rand());
        $uc = substr($uc, 0, 6) . substr($uc, 12, 6);
        $login = substr($login, 0, 64);
        $uid = intval($uid);
        $kind = intval($kind);
        if (intval($uid)) {
            $user = new users();
            $user->GetUserByUID($uid);
            $login = $user->login;
            $email = $user->email;
        }
        $sql = 'INSERT INTO feedback 
				( uc, dept_id, user_id, user_login, email, question, request_time ) 
			VALUES
				( ?, ?, ?, ?, ?, ?, NOW() ) RETURNING id';
        if (strtolower(mb_detect_encoding($login, array('utf-8'))) == 'utf-8') {
            $login = iconv('UTF-8', 'WINDOWS-1251//IGNORE', $login);
        }
        $sId = $DB->val($sql, $uc, $kind, $uid, $login, $email, $msg);
        if ($DB->error) {
            return 'Ошибка при отправке сообщения (db)';
        }
        $mail = new smail();
        if (count($files)) {
            foreach ($files as $attach) {
                $msg .= "\n\n=============================================\n";
                $msg .= 'К этому письму прикреплен файл ' . WDCPREFIX . "/upload/about/feedback/{$attach->name}";
                $msg .= "\n=============================================\n";
            }
        }
        if ($kind == 2) {
            $msg .= "\n\n=============================================\n";
            $msg .= 'Дополнительная информация: браузер: ' . (!empty($additional['browser']) ? $additional['browser'] : 'N/A') . ' ОС: ' . (!empty($additional['os']) ? $additional['os'] : 'N/A');
            $msg .= "\n=============================================\n";
        }
        $mail->FeedbackPost($login, $email, $kind, $msg, $uc, $sId);
        // Пишем статистику ображений в feedback
        $date = date('Y-m-d H:01:00');
        $sql = 'SELECT date FROM stat_feedback WHERE date=? AND type=?';
        $exist = $DB->val($sql, $date, $kind);
        if ($exist) {
            $sql = 'UPDATE stat_feedback SET count=count+1 WHERE date = ? AND type = ?';
        } else {
            $sql = 'INSERT INTO stat_feedback(date,type,count) VALUES( ?, ?, 1 )';
        }
        $DB->query($sql, $date, $kind);
        return '';
    }
Beispiel #4
0
 /**
  * показывает сплэшскрин, предварительно сделав проверку: нужно ли его показывать
  * @param type $type код сплэша
  * @param type $debug - принудительно показать сплэш, даже если не прошел проверку
  * @param type $setViewed если true - отметить как просмотренный
  * @return boolean
  */
 function show($type, $debug = false, $setViewed = true)
 {
     $need_show = false;
     if (self::SPLASH_EMPLOYER & $type || self::SPLASH_FREELANCER & $type) {
         $need_show = self::checkEmpFrlSplashShow($type);
     }
     if (self::SPLASH_MESSAGES & $type) {
         $need_show = self::checkContactsSplashShow();
     }
     if (self::SPLASH_MONEY & $type) {
         $need_show = !self::isViewed($type);
     }
     if (self::SPLASH_PROEMP_NOTPROFRL & $type || self::SPLASH_NOTPROEMP_NOTPROFRL & $type) {
         $need_show = true;
     }
     if (self::SPLASH_REAL_NAMES & $type && !self::isViewed($type) || $debug) {
         require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/attachedfiles.php";
         require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/users.php";
         require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/rating.php";
         $attachedFiles = new attachedfiles();
         $user = new users();
         $user->GetUserByUID(get_uid(0));
         $userpicSrc = $user->photo ? WDCPREFIX . '/users/' . $user->login . '/foto/' . $user->photo : WDCPREFIX . '/images/no_foto.png';
         $rating = new rating($user->uid, $user->is_pro, $user->is_verify, $user->is_profi);
         $r_data = $rating->data;
         $need_show = true;
     }
     if (self::SPLASH_NO_SPEC & $type && !self::isViewed($type) || $debug) {
         require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/freelancer.php";
         $frl = new freelancer();
         $frl->GetUserByUID(get_uid(0));
         if (!$frl->spec) {
             $need_show = true;
         }
     }
     // Проверяем не показывали уже этот тип
     if ($need_show || $debug || self::SPLASH_KONKURS == $type) {
         $tpl_splash = $_SERVER['DOCUMENT_ROOT'] . self::SPLASH_DIR . self::getTemplateSplash($type);
         if ($tpl_splash != '') {
             include $tpl_splash;
             if ($debug) {
                 return true;
             }
             // Отмечаем как просмотренный
             if ($type != self::SPLASH_MESSAGES && $setViewed) {
                 self::setViewed($type);
             }
             return true;
         }
     }
 }
Beispiel #5
0
/**
 * Выводит дерево комментариев. Используется здесь и в xajax/contest.server.php
 * @param  integer   $pid            id проекта
 * @param  string    $name           название проекта
 * @param  array     $comments       массив с деревом комментариев (подробнее в classes/contest.php)
 * @param  boolean   $comm_blocked   автор отключил возможность оставлять комментарии?
 * @param  boolean   $project_end    проект закрыт?
 * @param  integer   $s_level        уровень вложенности комментария
 * @return string                    HTML с кнопками управления
 */
function comments($pid, $name, &$comments, $comm_blocked, $project_end, $s_level = 0)
{
    global $stop_words, $contest, $project, $session;
    static $level = 0;
    $level = ($s_level ? $s_level : $level) + 1;
    $html = '';
    $set_branch_as_read = false;
    for ($i = 0, $c = count($comments); $i < $c; $i++) {
        if (($comments[$i]['is_banned'] || $comments[$i]['usr_banned'] || $comments[$i]['user_blocked'] === 't') && !hasPermissions('projects') && !$contest->is_owner) {
            $msg = $msg2 = 'Ответ от заблокированного пользователя';
        } else {
            if (!trim($comments[$i]['deleted'])) {
                $sMsg = $comments[$i]['moderator_status'] === '0' ? $stop_words->replace($comments[$i]['msg']) : $comments[$i]['msg'];
                $msg = reformat($sMsg, 30, 0, 0, 1);
                $msg2 = reformat($comments[$i]['msg'], 30, 0, 0, 1);
            } else {
                $msg2 = $msg = "Комментарий удален модератором";
                if (hasPermissions("comments")) {
                    $moderator = '';
                    $moderatorData = new users();
                    $moderatorData->GetUserByUID($comments[$i]['deluser_id']);
                    if ($moderatorData->login) {
                        $moderator = ' ' . $moderatorData->login . ' (' . $moderatorData->uname . ' ' . $moderatorData->usurname . ') ';
                    }
                    $msg2 = $msg = $msg . " {$moderator}";
                }
                if ($comments[$i]['deluser_id'] == $comments[$i]['user_id']) {
                    $msg2 = $msg = "Комментарий удален автором";
                } else {
                    if (trim($comments[$i]['deleted_reason']) && (hasPermissions("comments") || $comments[$i]['user_id'] == get_uid(false))) {
                        $msg2 = $msg = $msg . "<div style='color:#ff0000'>Причина: " . $comments[$i]['deleted_reason'] . "</div>";
                    }
                }
            }
        }
        $a_is_banned = ($comments[$i]['is_banned'] || $comments[$i]['usr_banned']) && hasPermissions('projects');
        $html .= "\n\t\t\t<li class='thread' id='thread-{$comments[$i]['id']}'" . ($level >= 9 ? " style='margin-left: 0'" : "") . ">\n\t\t\t\t<a name='c-comment-{$comments[$i]['id']}'></a>\n\t\t\t\t<div class='comment-one" . ($comments[$i]['deleted'] || $comments[$i]['hidden'] ? " comment-deleted" : "") . "' id='comment-{$comments[$i]['id']}'>\n\t\t\t\t\t<div class='contest-ea'>" . view_avatar($comments[$i]['login'], $comments[$i]['photo'], 1) . "</div>\n\t\t\t\t\t<div class='comment-body'>\n\t\t\t\t\t\t<h3 class='username'>" . $session->view_online_status($comments[$i]['login']) . "\n\t\t\t\t\t\t\t<a href='/users/{$comments[$i]['login']}' class='" . (is_emp($comments[$i]['role']) ? 'employer-name' : 'freelancer-name') . "'>{$comments[$i]['uname']} {$comments[$i]['usurname']} [{$comments[$i]['login']}]</a>&nbsp;" . view_mark_user($comments[$i]) . "&nbsp;" . ($comments[$i]['completed_cnt'] > 0 ? '<a href="/promo/bezopasnaya-sdelka/" title="Пользователь работал через Безопасную Сделку" target="_blank"><span class="b-icon b-icon__shield b-icon_top_1"></span></a>' : '') . "\n\t\t\t\t\t\t\t<span>[" . dateFormat('d.m.Y | H:i', $comments[$i]['post_date']) . "]</span>\n\t\t\t\t\t\t\t<span id='comment-modified-{$comments[$i]['id']}'>" . ($comments[$i]['modified'] ? "[изменен " . dateFormat('d.m.Y | H:i', $comments[$i]['modified']) . "]" : '&nbsp;') . "</span>\n\t\t\t\t\t\t\t" . ($a_is_banned ? "<b style=\"color:#ff0000\">Пользователь забанен</b>" : "") . "\n\t\t\t\t\t\t</h3>\n\t\t\t\t\t\t" . ($_SESSION['uid'] && $comments[$i]['is_new'] ? "<p><img src='/images/mark-new.png' width='53' height='12' alt='новое' class='mark-new' /></p>" : "") . "\n\t\t\t\t\t\t<div id='comment-change-{$comments[$i]['id']}'>\n\t\t\t\t\t\t<p id='comment-msg-{$comments[$i]['id']}' " . ($a_is_banned ? "style='color:silver'" : "") . ".>" . $msg . "</p>\n\t\t\t\t\t\t<div id='comment-msg-original-{$comments[$i]['id']}' style='display:none'>" . $msg2 . "</div>\n\t\t\t\t\t\t<script type=\"text/javascript\">\n                        banned.addContext( 'p{$pid}c{$comments[$i]['id']}', 3, '" . HTTP_PREFIX . "{$_SERVER['HTTP_HOST']}" . getFriendlyURL("project", $pid) . "?comm={$comments[$i]['id']}#comment-{$comments[$i]['id']}', \"" . htmlspecialchars($name) . "\" );\n                        </script>\n\t\t\t\t\t\t<ul class='thread-options' id='comment-options-{$comments[$i]['id']}'>\n\t\t\t\t\t\t\t" . comment_options($pid, $comments[$i], $comm_blocked, $project_end, $level, $name) . "\n\t\t\t\t\t\t</ul>\n                        <div id='warnreason-" . $comments[$i]['id'] . "-" . $comments[$i]['user_id'] . "' style='display:none; padding: 0 0 5px 0px;'>&nbsp;</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t" . (empty($comments[$i]['comments']) ? '' : '<ul>' . comments($pid, $name, $comments[$i]['comments'], $comm_blocked, $project_end) . '</ul>') . "\n\t\t\t</li>\n\t\t";
        if ($comments[$i]['is_new']) {
            $set_branch_as_read = true;
        }
    }
    if ($set_branch_as_read) {
        $p = new projects();
        $data = array("id" => $pid, "kind" => 7, "user_id" => $project["user_id"]);
        $p->SetRead($data, get_uid(false), true);
    }
    --$level;
    return $html;
}
Beispiel #6
0
 protected function sendFromTemplateByUserId($template, $uid)
 {
     $user = new users();
     $user->GetUserByUID($uid);
     if ($user->uid <= 0) {
         return false;
     }
     $is_emp = is_emp($user->role);
     $sufix = $is_emp ? 'emp' : 'frl';
     $template = sprintf($this->template_format, $template, $sufix);
     $this->recipient = $this->_formatFullname($user, true);
     $content = Template::render(FINANCE_TPL_MAIL_PATH . $template, array('smail' => &$this, 'data' => $this->data, 'params' => $this->_addUrlParams($is_emp ? 'e' : 'f'), 'user' => (array) $user));
     $message = Template::render(FINANCE_TPL_MAIL_PATH . FINANCE_TPL_BASE_LAYOUT, array('content' => $content));
     $this->message = nl2br($message);
     return array('ret' => $this->send('text/html'), 'message' => $message);
 }
Beispiel #7
0
 /**
  * Активирует аккаунт юзера по $code, возвращает логин и пароль пользователя.
  *
  * @param string $code		Код активации
  * @param string $login		Возвращает логин пользователя
  * @param string $pass		Возвращает пароль пользователя
  *
  * @return integer			1 - активация прошла успешно, 0 - активация не прошла
  */
 public function Activate($code, &$login, &$pass)
 {
     define('IS_USER_ACTION', 1);
     /**
      * Подлючаем файл для работы с пользователем.
      */
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/wizard/wizard_registration.php';
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/wizard/step_employer.php';
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/wizard/step_freelancer.php';
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/smail.php';
     global $DB;
     $sql = 'SELECT user_id, login, passwd FROM activate_code LEFT JOIN users ON user_id=uid WHERE code = ?';
     $res = $DB->query($sql, $code);
     list($fid, $login, $pass) = pg_fetch_row($res);
     if ($fid) {
         $usr = new users();
         $usr->active = 1;
         $usr->Update($fid, $res);
         $usr->GetUserByUID($fid);
         // #0017513
         if ($usr->role[0] == 1) {
             $wiz_user = wizard::isUserWizard($fid, step_employer::STEP_REGISTRATION_CONFIRM, wizard_registration::REG_EMP_ID);
         } else {
             $wiz_user = wizard::isUserWizard($fid, step_freelancer::STEP_REGISTRATION_CONFIRM, wizard_registration::REG_FRL_ID);
         }
         $out = 1;
         $this->Delete($fid);
         if ($wiz_user['id'] > 0) {
             $mail = new smail();
             if ($usr->role[0] == 1) {
                 $mail->employerQuickStartGuide($fid);
             } else {
                 $mail->freelancerQuickStartGuide($fid);
             }
             step_wizard::setStatusStepAdmin(step_wizard::STATUS_COMPLITED, $fid, $wiz_user['id']);
             $role = $usr->role[0] == 1 ? wizard_registration::REG_EMP_ID : wizard_registration::REG_FRL_ID;
             login($login, $pass, 0, true);
             header('Location: /registration/activated.php?role=' . $role);
             exit;
         }
     } else {
         $out = 0;
     }
     return $out;
 }
Beispiel #8
0
/**
 * Создание токена для защиты от CSRF
 * Токен уникален для всего цикла авторизации
 *
 * @return string  токен
 */
function csrf_token()
{
    if (!empty($_SESSION['rand'])) {
        return $_SESSION['rand'];
    }
    if (empty($_SESSION['uid'])) {
        mt_srand();
        return md5(uniqid(mt_rand(), true));
    }
    $user = new users();
    $user->GetUserByUID($_SESSION['uid']);
    if ($user->solt) {
        return md5(md5($user->email) . $user->solt);
    } else {
        mt_srand();
        return md5(uniqid(mt_rand(), true));
    }
}
Beispiel #9
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('&', '&amp;', $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;
}
Beispiel #10
0
/**
 * Проверка статуса верификации и обновление фио.
 *
 * @todo: обновление фио подвопросом так как при верификации банковсой карточкой тоже это происходит
 * 
 * @param type $fname
 * @param type $lname
 * @param type $type
 *
 * @return \xajaxResponse
 */
function checkIsVerify($fname, $lname, $type)
{
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
    $objResponse = new xajaxResponse();
    $uid = get_uid(false);
    if ($uid <= 0) {
        return $objResponse;
    }
    $user = new users();
    $user->GetUserByUID($uid);
    if ($user->uid > 0 && $user->IsVerified()) {
        $update_fio = false;
        $fname = change_q(substr(trim($fname), 0, 21));
        if ($fname) {
            $user->uname = $fname;
            $update_fio = true;
        }
        $lname = change_q(substr(trim($lname), 0, 21));
        if ($lname) {
            $user->usurname = $lname;
            $update_fio = true;
        }
        if ($update_fio) {
            $user->Update($user->uid, $err);
        }
        $_SESSION['is_verify'] = 't';
        unset($_SESSION['quick_ver_fname']);
        unset($_SESSION['quick_ver_lname']);
        $objResponse->script("window.location = '?vok=1" . ($type == 'card' ? '&vuse=card' : '') . "';");
    } else {
        $error = session::getFlashMessages('verify_error');
        $error = empty($error) ? Verification::ERROR_DEFAULT : $error;
        $objResponse->script("window.verification_popup.showError('{$error}');");
    }
    return $objResponse;
}
Beispiel #11
0
 /**
  * Формирует Excel отчет по действиям всех админов
  * 
  * @param array $actions список возможных действий
  * @param array $filter фильтр
  * @param string order тип сортировки
  * @param int $direction порядок сортировки: 0 - по убыванию, не 0 - по возрастанию
  */
 function printReportAll($actions = array(), $filter = array(), $order = 'general', $direction = 1)
 {
     $sCurrDate = date('Y-m-d');
     // данные
     $this->filter = $filter;
     $stat = $this->getAllStat($filter, $order, $direction);
     $sDateInterval = '';
     $sModerator = '';
     // admin
     if (self::isFilter('admin_id')) {
         require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
         $oUser = new users();
         $oUser->GetUserByUID($this->filter['admin_id']);
         $sModerator = $oUser->uname . ' ' . $oUser->usurname . ' [' . $oUser->login . ']';
     }
     // Период
     if (self::isFilter('date_from')) {
         $sDateInterval .= 'c' . $this->filter['date_from'];
     }
     if (self::isFilter('date_to') && $this->filter['date_to'] < $sCurrDate) {
         $sDateInterval .= ($sDateInterval ? ' ' : '') . 'по ' . $this->filter['date_to'];
     }
     if (!$sDateInterval) {
         $sDateInterval = 'За все время';
     }
     // имя итогового файла
     $sWorkTitle = 'moderators.' . $sCurrDate . '.xls';
     // подключаем pear
     require_once 'Spreadsheet/Excel/Writer.php';
     // создаем документ
     $workbook = new Spreadsheet_Excel_Writer();
     $workbook->setVersion(8);
     // создаем лист
     $worksheet =& $workbook->addWorksheet('1');
     $worksheet->setInputEncoding('CP1251');
     $th_sty = array('FontFamily' => 'Arial', 'Size' => 10, 'Align' => 'center', 'Border' => 1, 'BorderColor' => 'black', 'Bold' => 1);
     $format_top =& $workbook->addFormat($th_sty);
     $total_sty = array('FontFamily' => 'Arial', 'Size' => 10, 'Bold' => 1);
     $format_tot =& $workbook->addFormat($total_sty);
     $worksheet->write(0, 0, $sDateInterval);
     $worksheet->write(1, 0, 'Модератор: ' . ($sModerator ? $sModerator : 'Все'));
     // смены
     if (self::isFilter('time')) {
         $col = 1;
         foreach ($this->filter['time'] as $sTime) {
             $worksheet->write(1, $col, $sTime);
             $col++;
         }
     }
     $row = 3;
     // шапка - действия
     if (self::isFilter('act_id')) {
         $col = 1;
         $worksheet->write($row, 0, 'Модератор', $format_top);
         foreach ($this->filter['act_id'] as $idx) {
             foreach ($actions as $aOne) {
                 if ($aOne['id'] == $idx) {
                     $sName = 'nCnt' . $idx;
                     ${$sName} = 0;
                     $worksheet->write($row, $col, preg_replace('~<br ?/?>~', ' ', $aOne['act_short_name']), $format_top);
                     $col++;
                 }
             }
         }
         $row++;
     }
     // действия
     if ($stat) {
         foreach ($stat as $aOne) {
             $col = 1;
             $sModerator = $aOne['login'] ? "{$aOne['uname']} {$aOne['usurname']} [{$aOne['login']}]" : '[не известно]';
             $worksheet->write($row, 0, $sModerator);
             if (self::isFilter('act_id')) {
                 foreach ($this->filter['act_id'] as $idx) {
                     $sName = 'nCnt' . $idx;
                     ${$sName} += $aOne['cnt' . $idx];
                     $worksheet->write($row, $col, $aOne['cnt' . $idx]);
                     $col++;
                 }
             }
             $row++;
         }
     }
     // Итого
     $worksheet->write($row, 0, 'Итого', $format_tot);
     if (self::isFilter('act_id')) {
         $col = 1;
         foreach ($this->filter['act_id'] as $idx) {
             $sName = 'nCnt' . $idx;
             $worksheet->write($row, $col, ${$sName}, $format_tot);
             $col++;
         }
     }
     // отправляем на скачивание
     $workbook->send($sWorkTitle);
     // закрываем документ
     $workbook->close();
 }
Beispiel #12
0
 public function InvoiceCreate($userID, $clientID, $amount)
 {
     global $DB;
     $user = new users();
     $user->GetUserByUID($userID);
     if (empty($user->uid) || empty($clientID) || !is_string($clientID) || intval($amount) < 0) {
         $this->_error();
         return false;
     }
     $amount = intval($amount);
     $endDate = date('Y-m-d', time() + self::INVOICE_TTL);
     $id = $DB->insert('alphaclick', array('user_id' => $userID, 'amount' => intval($amount), 'client_id' => $clientID, 'end_date' => $endDate), 'id');
     $shortDesc = str_replace(array('%LOGIN%', '%UNAME%', '%USURNAME%'), array($user->login, $user->uname, $user->usurname), self::INVOICE_SHORT_DESC);
     $fullDesc = str_replace(array('%LOGIN%', '%UNAME%', '%USURNAME%'), array($user->login, $user->uname, $user->usurname), self::INVOICE_FULL_DESC);
     $client = $this->_soapClient(self::WSInvoiceCreate_Location, self::WSInvoiceCreate_URI);
     $var1 = new stdclass();
     $var1->externalSystemCode = new SoapVar("GRCHK14", XSD_STRING);
     $var1->externalUserCode = new SoapVar("GRCHK14", XSD_STRING);
     $param1 = new SoapParam($var1, "inCommonParms");
     $var2 = new stdclass();
     $var2->ID_invtype = new SoapVar(self::INVOICE_TYPE, XSD_INTEGER);
     $var2->ID_client = new SoapVar($clientID, XSD_STRING);
     $var2->ID_statement = new SoapVar($id, XSD_STRING);
     $var2->Amount = new SoapVar($amount, XSD_INTEGER);
     $var2->End_date = new SoapVar($endDate . 'Z', XSD_STRING);
     $var2->Short_desc = new SoapVar(iconv('CP1251', 'UTF-8', $shortDesc), XSD_STRING);
     $var2->Full_desc = new SoapVar(iconv('CP1251', 'UTF-8', $fullDesc), XSD_STRING);
     $param2 = new SoapParam($var2, "inParms");
     try {
         $result = $client->__soapCall(self::WSInvoiceCreate_Func, array($param1, $param2));
         if (empty($result->ID_invoice)) {
             $this->_error();
         } else {
             $DB->update('alphaclick', array('invoice_id' => $result->ID_invoice), 'id = ?', $id);
             return $result->ID_invoice;
         }
     } catch (SoapFault $fault) {
         echo 'Request : <br/><xmp>', $client->__getLastRequest(), '</xmp><br/><br/> Error Message : <br/>', $fault->getMessage();
         if (!empty($fault->detail->WSAppException->errorCode)) {
             $DB->update('alphaclick', array('error_num' => $fault->detail->WSAppException->errorCode), 'id = ?', $id);
         }
         $this->_error($fault);
     }
     echo $client->__getLastResponseHeaders();
     return 0;
 }
Beispiel #13
0
            $alert[1] = "Поле заполнено некорректно";
        }
        if ($surname && !preg_match("/^[-a-zA-Zа-яёА-ЯЁ]+\$/", $surname)) {
            $error_flag = 1;
            $alert[2] = "Поле заполнено некорректно";
        }
        if (!$error_flag) {
            if ($name) {
                $userObj->uname = $name;
            }
            if ($surname) {
                $userObj->usurname = $surname;
            }
            if ($name || $surname || $userpic) {
                $userObj->Update($userID, $res);
            }
            $info = "Изменения внесены";
        }
        // делаем так как будто сохранение было не из сплэша а из обычной формы в профиле пользователя
        $action = 'main_change';
        $userObj->GetUserByUID($userID);
        $email = $userObj->email;
        $pname = $userObj->pname;
        $promo_block_hide = (bool) $_COOKIE['nfastpromo_open'];
        $direct_links = $_SESSION['direct_external_links'];
        break;
}
$body_class = $is_pro ? 'p-pro' : 'p-nopro';
$header = $rpath . "header.php";
$footer = $rpath . "footer.html";
include $rpath . $template;
Beispiel #14
0
 /**
  * Перенос всех данных введнных в мастере на боевые таблицы
  * должен запускаться синхронно с завершением работы мастера
  * 
  * @return type 
  */
 public function transferWizardContent()
 {
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/users.php";
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/log.php";
     $this->log = new log('wizard/transfer-' . SERVER . '-%d.log', 'a', '%d.%m.%Y %H:%M:%S : ');
     $user = new users();
     $user->GetUserByUID(wizard::getUserIDReg());
     $this->user = $user;
     // Чистим ответы на заблокированные проекты
     $this->clearOffers();
     // некоторые ответы могут остатся в этой таблице поэтому обновляем им Ид пользователя (при завершении мастера все данные по Ид пользователя мастера удаляются)
     $this->updateOffers(array('reg_uid' => wizard::getUserIDReg()));
     // пользователь может быть уже PRO (если он ранее был авторизован) - учитываем это
     $pro = is_pro();
     $limit = $pro ? "all" : 3;
     // Берем все конкурсы + 3 обычных проекта для публикации ответов (без конкурсов и проектов для ПРО)
     $offers = $this->getWizardOffers(false, $limit, !$pro);
     if ($offers) {
         $error = $this->transferOffers($offers);
     }
     // Пишем данные пользователя введенные в шаге портфолио
     $field = $this->parent->getFieldsUser();
     $data = unserialize($field['portfolio']);
     if ($data) {
         $error = $this->transferUserInformation($data);
     }
     //Перенос порфтолио
     $works = $this->getWorks();
     if ($works) {
         $error = $this->transferWorks($works);
     }
     return $error;
 }
Beispiel #15
0
<?php

$g_page_id = '0|37';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/stdf.php';
$rpath = '../../';
include $rpath . '404.php';
exit;
$stretch_page = true;
$showMainDiv = true;
$page_title = 'Поднятие закрепленного проекта - фриланс, удаленная работа на FL.ru';
$header = "{$rpath}/header.php";
$content = 'content.php';
$footer = "{$rpath}/footer.html";
$template = 'template2.php';
$uid = get_uid();
$user = null;
if (is_emp()) {
    $user = new users();
    $user->GetUserByUID($uid);
}
include $rpath . $template;
Beispiel #16
0
/**
 * Удаляет рекомендацию.
 *
 * @param type $stage_id
 * @param type $feedback_id
 * @param type $deleteOpinion удалить мнение
 * @param type $reloadPage    перезагрузить страницу
 *
 * @return \xajaxResponse
 */
function DeleteFeedback($stage_id, $feedback_id, $reloadPage = false)
{
    session_start();
    $objResponse = new xajaxResponse();
    $stage_id = intval($stage_id);
    $feedback_id = intval($feedback_id);
    $uid = get_uid(false);
    if (!hasPermissions('sbr')) {
        return;
    }
    $feedback = sbr_meta::getFeedback($feedback_id);
    if (!$feedback) {
        return;
    }
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
    $user = new users();
    $user->GetUserByUID($uid);
    if (!$user->uid) {
        $err = 'Ошибка';
    }
    $sbr = sbr_meta::getInstance(sbr_meta::ADMIN_ACCESS, $user, is_emp($user->role));
    if (!$sbr) {
        return;
    }
    $stage = $sbr->getStage($stage_id);
    if (!$stage) {
        return;
    }
    //$res = sbr_meta::deleteFeedback($feedback_id);
    $res = sbr_meta::setDeletedFeedback($feedback_id);
    if (!$res) {
        return;
    }
    $ot = $feedback['rating'] == 0 ? 'neitral' : ($feedback['rating'] == 1 ? 'plus' : 'minus');
    $objResponse->call('opinionChConuters', 'ops-norisk' . $ot);
    $objResponse->script("\$('cont_{$feedback_id}').getParent('div.ops-one').dispose();");
    $objResponse->script("if(\$\$('.page-ops div.ops-one').length == 0) \$('no_messages').show();");
    if ($reloadPage) {
        $objResponse->script('window.location.reload()');
    }
    return $objResponse;
}
Beispiel #17
0
/**
 * Активирует пользователей.
 * 
 * @param string $sUsers  JSON строка с массивом UID пользователей
 * @param int    $nReload 1 - если нужно перезагрузить страницу
 *
 * @return object xajaxResponse
 */
function activateUser($sUsers = '', $nReload = 0)
{
    session_start();
    $objResponse = new xajaxResponse();
    if (hasPermissions('users')) {
        $aUsers = _jsonArray($sUsers);
        if ($aUsers) {
            require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
            require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/wizard/wizard_registration.php';
            require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/wizard/step_employer.php';
            require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/wizard/step_freelancer.php';
            foreach ($aUsers as $sUid) {
                if (users::SetActiveByUid($sUid)) {
                    $user = new users();
                    $user->GetUserByUID($sUid);
                    if ($user->role[0] == 1) {
                        $wiz_user = wizard::isUserWizard($sUid, step_employer::STEP_REGISTRATION_CONFIRM, wizard_registration::REG_EMP_ID);
                    } else {
                        $wiz_user = wizard::isUserWizard($sUid, step_freelancer::STEP_REGISTRATION_CONFIRM, wizard_registration::REG_FRL_ID);
                    }
                    step_wizard::setStatusStepAdmin(step_wizard::STATUS_COMPLITED, $sUid, $wiz_user['id']);
                    $objResponse->script("\$('activate_{$sUid}').set('html','');");
                }
            }
            $objResponse->script('adminLogCheckUsers(false)');
            $objResponse->script('$("chk_all").checked=false;');
        }
        if ($nReload) {
            $objResponse->script('window.location.reload(true)');
        }
    }
    return $objResponse;
}
Beispiel #18
0
 /**
  * Перевод денег на другой аккаунт
  *
  * @param integer $uid					UID переводящего
  * @param integer $gid					UID кому переводят
  * @param integer $sum					сумма
  * @param integer $transaction_id		идентификатор транзакции
  * @param string  $comments				комментарии переводящего
  * @return integer						1 - все ок, 0 - иначе
  */
 function transfer($uid, $gid, $sum, $transaction_id, $comments, $commit = true, $trs_sum = 0)
 {
     global $DB;
     $user_transfer = $gid;
     if (!$transaction_id || $transaction_id != $this->check_transaction($transaction_id, $uid)) {
         $this->view_error("Невозможно завершить транзакцию");
     } else {
         $res = $DB->query("SELECT account.sum, account.id FROM account WHERE account.uid=?", $uid);
         if ($DB->error) {
             return "Ошибка при получении информации о счете!";
         }
         list($ac_sum, $bill_id) = pg_fetch_row($res);
         if ($sum > $ac_sum) {
             return "Недостаточно средств на счету!";
         }
         $ok = $this->GetInfo($gid);
         if (!$ok) {
             $this->CreateNew($gid);
             $this->GetInfo($gid);
         }
         if ($sum < 0) {
             return "Перевод на отрицательную сумму!";
         }
         $descr = '';
         $res = $DB->query("SELECT gid, id FROM MakeGift(?, ?, ?, ?, ?, ?, ?, ?, ?, ?) as (gid integer, id integer)", $bill_id, $this->id, 23, $sum, $descr, $comments, $uid, $gid, $sum, $trs_sum);
         if ($DB->error) {
             return "Ошибка при записи счета!";
         } else {
             $_SESSION['ac_sum'] = $_SESSION['ac_sum'] - $sum;
         }
         list($gid, $id) = pg_fetch_row($res);
         if ($commit) {
             $this->commit_transaction($transaction_id, $uid, $id);
         }
         // для счетчика everesttech.net (см. engine/templates/footer.tpl)
         if ($sum > 0) {
             $_SESSION['everesttech_conter'] = 1;
         }
         $user = new users();
         $user->GetUserByUID($user_transfer);
         // Обновляем сессию пользователю сразу при поступлении денежных средств
         $session = new session();
         $session->UpdateAccountSum($user->login);
         // уведомление в юзербаре
         require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/bar_notify.php";
         $bar_notify = new bar_notify($user->uid);
         $bar_notify->addNotify('bill', null, "На счет зачислено {$sum} руб.");
         return 1;
     }
     return 0;
 }
 public function actionIndex()
 {
     $limit = 20;
     $do = __paramInit('string', 'do', 'do', '');
     $page = __paramInit('int', 'page', 'page', 1);
     $filter = array();
     $filter_default = array('date' => date('d.m.Y', strtotime('-1 month')) . ' - ' . date('d.m.Y'));
     switch ($do) {
         case 'factura_delete':
             $nums = __paramInit('array', NULL, 'num', null);
             $this->billInvoicesAdminModel->deleteFactura($nums);
             break;
         case 'factura_update':
             $invoice_id = __paramInit('int', NULL, 'invoice_id', null);
             $file = $_FILES['new_file'];
             $this->billInvoicesAdminModel->updateFactura($invoice_id, $file);
             break;
         case 'factura':
             $nums = __paramInit('array', NULL, 'num', null);
             $dates = __paramInit('array', NULL, 'date', null);
             $this->billInvoicesAdminModel->addFactura($nums, $dates);
             break;
         case 'filter':
             $filter['do'] = $do;
             $filter['login'] = __paramInit('string', 'login', 'login', '');
             $filter['date'] = __paramInit('string', 'date', 'date', null);
             break;
             //Операция зачисления средств по счету
         //Операция зачисления средств по счету
         case 'pay':
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/account.php';
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/billing.php';
             $sums = __paramInit('array', NULL, 'sum', null);
             //@todo: слишком толстый контроллер
             //все ниже нужно было определить в модель
             $account = new account();
             $user = new users();
             if ($sums) {
                 $sAdmin = 'Запись добавил: ' . @$_SESSION['login'];
                 $sDate = date('c');
                 foreach ($sums as $user_id => $invoices) {
                     $user->GetUserByUID($user_id);
                     if (!$user->uid || !$account->GetInfo($user->uid, true) || empty($invoices)) {
                         continue;
                     }
                     $bill = new billing($user->uid);
                     foreach ($invoices as $invoice_id => $sum) {
                         $account_sum = $account->sum;
                         if (!is_numeric($sum) || $sum <= 0 || $account->sum + $sum < 0) {
                             continue;
                         }
                         $comments = sprintf("Безналичный перевод по счету Б-%06d", $invoice_id);
                         if (!$account->depositEx2($acc_op_id, $account->id, $sum, $sAdmin, $comments, 12, $sum, 4, $sDate)) {
                             $this->billInvoicesAdminModel->update($invoice_id, array('acc_op_id' => $acc_op_id));
                             //Автоматическая покупка услуги погашения задолженности
                             if ($account_sum < 0) {
                                 $payed_sum = abs($account_sum);
                                 $option = array('acc_sum' => $payed_sum);
                                 $billReserveId = $bill->addServiceAndCheckout(135, $option);
                                 if ($billReserveId) {
                                     $bill->buyOrder($billReserveId);
                                 }
                             }
                         }
                     }
                 }
                 $this->redirect('.');
             }
             break;
     }
     $this->billInvoicesAdminModel->setPage($limit, $page);
     $list = $this->billInvoicesAdminModel->setFilter($filter)->getInvoices();
     $count = $this->billInvoicesAdminModel->getInvoicesCnt();
     $filter_query = '';
     if (empty($filter)) {
         $filter = $filter_default;
     } else {
         $filter_query = http_build_query($filter) . '&';
     }
     $this->render('index', array('list' => $list, 'limit' => $limit, 'page' => $page, 'page_count' => $count, 'filter_query' => $filter_query, 'filter' => $filter));
 }
Beispiel #20
0
 /**
  * Пользовательский иммунитет у команды, топики нельзя заблокировать.
  * 
  * @staticvar array $is_immunity
  *
  * @param int   $uid    Ид Пользователя
  * @param array $data   Данные пользователя если имеются
  * @param int   $msg_id ID сообщения
  *
  * @return bool
  */
 public static function isImmunity($uid, $data = array(), $msg_id = null)
 {
     static $is_immunity;
     if (isset($is_immunity[$uid])) {
         return $is_immunity[$uid];
     }
     $commune_id = commune::getCommuneIDByMessageID($msg_id);
     $status = commune::GetUserCommuneRel($commune_id, $uid);
     if (empty($data)) {
         require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
         $user = new users();
         $user->GetUserByUID($uid);
         $is_immunity[$uid] = $user->is_team == 't' || strtolower($user->login) == 'admin' || $status['is_moderator'] == 1 || $status['is_admin'] == 1 || $status['is_author'] == 1;
     } else {
         $is_immunity[$uid] = $data['is_team'] == 't' || strtolower($data['login']) == 'admin' || $status['is_moderator'] == 1 || $status['is_admin'] == 1 || $status['is_author'] == 1;
     }
     return $is_immunity[$uid];
 }
Beispiel #21
0
function BanMemberNewComment($member_id, $uid, $commune_id)
{
    $objResponse = new xajaxResponse();
    $commune_id = intval($commune_id);
    $member_id = intval($member_id);
    $uid = intval($uid);
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/commune.php';
    $admin = commune::GetUserCommuneRel($commune_id, get_uid());
    if ($admin['is_moderator'] || $admin['is_author']) {
        $warncount = 0;
        $r = commune::BanMemberForComment($member_id, $commune_id, $warncount);
        if ($warncount < 3) {
            $objResponse->script("\$\$('.warncount-{$uid}').set('html','{$warncount}');");
        } else {
            require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
            $u = new users();
            $u->GetUserByUID($uid);
            $objResponse->script("\$\$('.warnlink-{$uid}').set('html','<a class=\"id-ban-member{$member_id}\" style=\"color:red\" href=\"javascript:void(0)\" onclick=\"xajax_BanNewMember({$member_id})\">Забанить!</a>');");
        }
        $sm = new smail();
        $comm = commune::GetCommuneByMember($member_id);
        $sm->CommuneMemberAction($comm['member_user_id'], 'WarnMember', $comm);
    }
    return $objResponse;
}
Beispiel #22
0
 /**
  * Вывод страницы по платежным системам WebMoney /bill/webmoney/.
  */
 public function webmoneyAction()
 {
     front::og('tpl')->page = 'index';
     front::og('tpl')->type = 'webmoney';
     front::og('tpl')->script = array('/scripts/bill2.js', 'md5.js');
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/pmpay.php';
     $wmpay = new wmpay();
     $pmpay = new pmpay();
     mt_srand();
     $user = new users();
     $user->GetUserByUID(get_uid(0));
     if (date('Ymd') >= 20130301) {
         // #0022399
         $wm_paymaster = 2;
     } else {
         $wm_paymaster = $user->wm_paymaster;
         $is_weekend = in_array(date('w'), array(0, 6));
         if ($wm_paymaster === null || $wm_paymaster == 2 && $is_weekend) {
             // 1:wmr, 2:paymaster
             $wm_paymaster = 1;
             if (!$is_weekend) {
                 $wm_paymaster += mt_rand(1, 100) > 50;
             }
             $user->setWmPaymaster($user->uid, $wm_paymaster);
         }
     }
     front::og('tpl')->_user = $user;
     front::og('tpl')->payment_number = mt_rand(1, 500000);
     front::og('tpl')->wmr_purse = $wmpay->wmzr[1];
     if ($is_paymaster = $wm_paymaster == 2) {
         front::og('tpl')->payment_number = $pmpay->genPaymentNo();
         front::og('tpl')->wmr_purse = $pmpay->merchants[pmpay::MERCHANT_BILL];
     }
     front::og('tpl')->is_paymaster = $is_paymaster;
     front::og('tpl')->display('bill/bill_paysys.tpl');
 }
Beispiel #23
0
 /**
  * Инициализирует все данные в сессии.
  *
  * @param int $uid ид. пользователя.
  */
 public function fill($uid)
 {
     require_once ABS_PATH . '/classes/users.php';
     $user = new users();
     $user->GetUserByUID($uid);
     $this->fillU($user);
 }
Beispiel #24
0
function GetRating($type, $login = null, $width = null)
{
    session_start();
    $objResponse = new xajaxResponse();
    $login = change_q_x($login, TRUE);
    $user = new users();
    $user->GetUser($login);
    $uid = $user->uid;
    if (!$uid) {
        $uid = get_uid(false);
    }
    if (!$uid) {
        $objResponse->script('this.document.location.reload();');
        return $objResponse;
    }
    $user->GetUserByUID($uid);
    $rating = new rating();
    switch ($type) {
        case 'year':
            $TIME = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $pro_periods_date = date('Y-01-01', $TIME);
            $res = $rating->getRatingByYear($uid, date('Y', $TIME));
            $periods = rating::getMonthParts(date('Y-01-01'));
            $data = array();
            if ($res) {
                foreach ($periods as $m => $mm) {
                    if ($m < date('m')) {
                        foreach ($mm as $d) {
                            if ($d > time() || $d < strtotime($user->reg_date)) {
                                continue;
                            }
                            $data[$m][date('Y-m-d', $d)] = null;
                            if ($d >= strtotime($user->reg_date)) {
                                $data[$m][date('Y-m-d', $d)] = 0;
                            }
                        }
                    }
                }
            }
            $start_r = null;
            if ($res) {
                if (date('Y', strtotime($res[0]['_date'])) == date('Y') - 1) {
                    $start_r = $res[0]['rating'];
                    if (isset($res[1]) && strtotime($res[1]['_date']) != $periods[0][0]) {
                        $res[0]['_date'] = date('Y-m-d', $periods[0][0]);
                    } else {
                        $res = array_slice($res, 1);
                    }
                }
            } else {
                $res = array();
            }
            $verify_factor = 0;
            $verify_date = rating::GetVerifyDate($uid);
            foreach ($res as $row) {
                $t = strtotime($row['_date']);
                $m = (int) date('m', $t);
                $verify_factor = 0;
                if ($row['is_verify'] == 't') {
                    if ($verify_date) {
                        if (strtotime($verify_date) < $t) {
                            $verify_factor = 0.2;
                        }
                    } else {
                        $verify_factor = 0.2;
                    }
                }
                $data[$m - 1][date('Y-m-d', $t)] = array('rating' => floatval($row['rating']), 'verify' => floatval($row['rating'] * $verify_factor), 'pro' => 0);
            }
            $lastval = null;
            foreach ($data as $i => $mon) {
                foreach ($mon as $d => $prt) {
                    $vl = !$prt ? $lastval : $prt;
                    $data[$i][$d] = $vl;
                    //                    if($prt !== null)
                    $lastval = $vl;
                }
            }
            $pro_periods = promotion::GetUserProPeriods($uid, $pro_periods_date, TRUE);
            if ($pro_periods) {
                $pro = array();
                foreach ($pro_periods as $p => $period) {
                    if (date('Y', strtotime($period['from_time'])) > date('Y', $TIME) && date('Y', strtotime($period['to_time']) > date('Y', $TIME))) {
                        continue;
                    }
                    $d1 = (int) date('z', strtotime($period['from_time']));
                    $d2 = (int) date('z', strtotime($period['to_time']));
                    if (date('Y', strtotime($period['from_time'])) < date('Y', $TIME)) {
                        $d1 = 0;
                    }
                    if (date('Y', strtotime($period['to_time'])) > date('Y', $TIME)) {
                        $d2 = (int) date('z', mktime(0, 0, 0, 12, 31, date('Y')));
                    }
                    $_factor = 0.2;
                    if ($period['is_profi'] == 1) {
                        $_factor = 0.4;
                    }
                    foreach ($data as $mon => $val) {
                        foreach ($val as $per => $r) {
                            $day = (int) date('z', strtotime($per));
                            if ($d1 < $day && $d2 >= $day) {
                                $data[$mon][$per]['pro'] = floatval($data[$mon][$per]['rating'] * $_factor);
                            }
                        }
                    }
                    $pro[$p] = $d1 != $d2 ? array($d1, $d2) : array($d1);
                }
                $config['pro'] = $pro;
            }
            $new_data = array();
            if ($data) {
                foreach ($data as $mon => $val) {
                    foreach ($val as $per => $r) {
                        $new_data[$mon][$per] = $r['rating'] + $r['verify'] + $r['pro'];
                    }
                }
            }
            $config['data'] = $new_data;
            $config['cur'] = intval(date('m', $TIME));
            $config['days'] = date('z', mktime(0, 0, 0, 12, 31, date('Y'))) + 1;
            $config['regdate'] = $user->reg_date;
            break;
        case 'prev':
        default:
            $config = array();
            $data = array();
            $config['hilight'] = array();
            if ($type == 'prev') {
                $TIME = mktime(0, 0, 0, date('m') - 1, 1, date('Y'));
                $res = $rating->getRatingByMonth($uid, date('Y-m-d', $TIME));
                if (!$res) {
                    $res = array();
                }
                $graphstart = strtotime($user->reg_date);
                if (count($res) && date('Ym', strtotime($res[0]['_date'])) == date('Ym', $TIME)) {
                    $graphstart = strtotime($res[0]['_date']);
                } else {
                    if (!count($res)) {
                        $graphstart = time();
                    }
                }
                $rating_data = array();
                $verify_date = null;
                $verify_factor = 0;
                $n = 0;
                foreach ($res as $d) {
                    if (date('Y-m', strtotime($d['_date'])) != date('Y-m', $TIME)) {
                        continue;
                    }
                    //$rating_data[intval(date('d', strtotime($d['_date'])))] = $d['rating'];
                    $verify_factor = 0;
                    if ($verify_date === null) {
                        $verify_date = rating::GetVerifyDate($d['user_id']);
                    }
                    if ($d['is_verify'] == 't') {
                        if ($verify_date) {
                            if (strtotime($verify_date) < strtotime($d['_date'])) {
                                $verify_factor = 0.2;
                            }
                        } else {
                            $verify_factor = 0.2;
                        }
                    }
                    if ($n == 0) {
                        $res[0]['verify_factor'] = $verify_factor;
                    }
                    $rating_data[intval(date('d', strtotime($d['_date'])))] = array('rating' => floatval($d['rating']), 'verify' => floatval($d['rating'] * $verify_factor), 'pro' => 0);
                    ++$n;
                }
                $last = null;
                for ($i = 0; $i < date('t', $TIME); ++$i) {
                    if (strtotime(date('Y-m-' . ($i + 1), $TIME)) < $graphstart) {
                        $last = null;
                    } else {
                        $last = $last !== null ? $last : 0;
                        if ($i == 0 && !isset($rating_data[$i + 1])) {
                            $last = array('rating' => floatval($res[0]['rating']), 'verify' => floatval($res[0]['rating'] * $res[0]['verify_factor']), 'pro' => 0);
                        }
                    }
                    if (isset($rating_data[$i + 1])) {
                        $last = $rating_data[$i + 1];
                    }
                    $data[$i] = $last;
                }
            } else {
                $TIME = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $res = $rating->getRatingByMonth($uid, date('Y-m-d', $TIME));
                if (!$res) {
                    $res = array();
                }
                $graphstart = strtotime($user->reg_date);
                if (count($res) && date('Ym', strtotime($res[0]['_date'])) == date('Ym', $TIME)) {
                    $graphstart = strtotime($res[0]['_date']);
                }
                $rating_data = array();
                $verify_date = null;
                $verify_factor = 0;
                $n = 0;
                foreach ($res as $d) {
                    if (date('Y-m', strtotime($d['_date'])) != date('Y-m', $TIME)) {
                        continue;
                    }
                    $verify_factor = 0;
                    if ($verify_date === null) {
                        $verify_date = rating::GetVerifyDate($d['user_id']);
                    }
                    if ($d['is_verify'] == 't') {
                        if ($verify_date) {
                            if (strtotime($verify_date) < strtotime($d['_date'])) {
                                $verify_factor = 0.2;
                            }
                        } else {
                            $verify_factor = 0.2;
                        }
                    }
                    if ($n == 0) {
                        $res[0]['verify_factor'] = $verify_factor;
                    }
                    $rating_data[intval(date('d', strtotime($d['_date'])))] = array('rating' => floatval($d['rating']), 'verify' => floatval($d['rating'] * $verify_factor), 'pro' => 0);
                    ++$n;
                }
                $config['cur'] = intval(date('d', $TIME));
                $last = 0;
                for ($i = 0; $i < date('d', $TIME); ++$i) {
                    if (strtotime(date('Y-m-' . ($i + 1), $TIME)) < $graphstart) {
                        $last = null;
                    } else {
                        $last = $last !== null ? $last : 0;
                        if ($i == 0 && !isset($rating_data[$i + 1])) {
                            $last = array('rating' => floatval($res[0]['rating']), 'verify' => floatval($res[0]['rating'] * $res[0]['verify_factor']), 'pro' => 0);
                        }
                    }
                    if (isset($rating_data[$i + 1])) {
                        $last = $rating_data[$i + 1];
                    }
                    $data[$i] = $last;
                }
            }
            $pro_periods_date = date('Y-01-01', $TIME);
            for ($i = 1; $i <= date('t', $TIME); ++$i) {
                $t = mktime(0, 0, 0, date('m', $TIME), $i, date('Y', $TIME));
                if (date('w', $t) == 0 || date('w', $t) == 6) {
                    $config['hilight'][] = $i;
                }
            }
            $pro_periods = promotion::GetUserProPeriods($uid, $pro_periods_date, TRUE);
            if ($pro_periods) {
                $pro = array();
                $tmp = array();
                foreach ($pro_periods as $p => $period) {
                    if (date('Ym', strtotime($period['from_time'])) > date('Ym', $TIME)) {
                        continue;
                    }
                    if (date('Ym', strtotime($period['to_time'])) < date('Ym', $TIME)) {
                        continue;
                    }
                    $d1 = (int) date('d', strtotime($period['from_time']));
                    $d2 = (int) date('d', strtotime($period['to_time']));
                    if (date('Ym', strtotime($period['from_time'])) < date('Ym', $TIME)) {
                        $d1 = 1;
                    }
                    if (date('Ym', strtotime($period['to_time'])) > date('Ym', $TIME)) {
                        $d2 = (int) date('t', $TIME);
                    }
                    $_factor = 0.2;
                    //PRO ONLY
                    if ($period['is_profi'] == 1) {
                        $_factor = 0.4;
                        //PROFI
                    }
                    foreach ($data as $day => $val) {
                        if (isset($tmp[$day]) || $val === null) {
                            continue;
                        }
                        if ($d1 <= $day + 1 && $d2 >= $day + 1) {
                            $data[$day]['pro'] = floatval($data[$day]['rating'] * $_factor);
                            //rating::PRO_FACTOR;
                            $tmp[$day] = 1;
                        }
                    }
                    $pro[$p] = $d1 != $d2 ? array($d1, $d2) : array($d1);
                }
                $config['pro'] = $pro;
            }
            if (strtotime($user->reg_date) > strtotime($pro_periods_date)) {
                $config['regdate'] = date('Y-m-d', strtotime($user->reg_date));
            }
            $new_data = array();
            if ($data) {
                foreach ($data as $day => $value) {
                    $new_data[$day] = $value['rating'] + $value['verify'] + $value['pro'];
                }
            }
            // сегодняшний рейтинг берем из $user - тут он актуальный и не зависит от кэша
            if ($type === 'month') {
                array_pop($new_data);
                $new_data[] = floatval($user->rating);
            }
            $config['data'] = $new_data;
            $config['days'] = date('t', $TIME);
            $config['startdate'] = date('Y-m-01', $TIME);
    }
    if ($width) {
        $config['w'] = (int) $width;
    }
    $config = json_encode($config);
    $objResponse->script("loadGraph('{$type}', {$config});");
    return $objResponse;
}
Beispiel #25
0
 /**
  * Возвращает информацию о пользователе.
  * 
  * @param stdClass $attr - список параметров
  *                       string uid: uid пользователя информацию о котором надо получить
  *                       если не указать, то вернет данные о текущем пользователе
  *
  * @return array - массив с данными пользователя
  */
 protected function _ceUser($attr)
 {
     $uid = empty($attr->uid) ? $this->_uid : intval($attr->uid);
     $user = new users();
     $user->GetUserByUID($uid);
     if (empty($user->login)) {
         return array();
     }
     return array('uid' => $user->uid, 'login' => $user->login, 'name' => $user->uname ? iconv('CP1251', 'UTF-8', $user->uname . ' ' . $user->usurname) : $user->login, 'avatar' => $user->photo ? WDCPREFIX . '/users/' . $user->login . '/foto/sm_' . $user->photo : '', 'pro' => (int) ($user->is_pro == 't'), 'emp' => (int) is_emp($user->role));
 }
Beispiel #26
0
    /**
     * Отправляет уведомления об изменении админом сообщения в личке ("Мои контакты").
     * 
     * @param int    $from_uid UID отправителя
     * @param int    $prof_id  ID профессии
     * @param string $reason   причина редактирования
     *
     * @return bool true - успех, false - провал
     */
    public function portfChoiceModifiedNotification($from_uid = 0, $prof_id = 0, $reason = '')
    {
        require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/professions.php';
        $from = new users();
        $from->GetUserByUID($from_uid);
        $prj = professions::GetProfDesc($from_uid, $prof_id);
        $sLink = getAbsUrl('/users/' . $from->login . '/setup/#prof' . $prof_id);
        $sRason = $reason ? "\n\nПричина: " . $reason : '';
        $sFeedback = str_replace('//', '/{службу поддержки}/', $GLOBALS['host'] . '/about/feedback/');
        $message = 'Здравствуйте, ' . $from->uname . ' ' . $from->usurname . '

Модераторы нашего ресурса отредактировали ваши уточнения к разделу &laquo;' . $prj['profname'] . '&raquo;

' . $sLink . $sRason . '

Вы можете обратиться в ' . $sFeedback . '.

Надеемся на понимание, Команда Free-lance.ru
';
        self::Add(users::GetUid($err, 'admin'), $from->login, $message, '', 1);
    }
/**
 * Парсит текст причины редактирования для отравки уведомления
 * 
 * @param  int $user_id UID пользователя
 * @param  string $adm_edit_text текст причины
 * @return string 
 */
function _parseReason($user_id = 0, $adm_edit_text = '')
{
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
    $objUser = new users();
    $objUser->GetUserByUID($user_id);
    $sReason = str_replace('%USERNAME%', $objUser->uname . ' ' . $objUser->usurname, $adm_edit_text);
    $sReason = change_q($sReason, FALSE, 0, TRUE);
    return $sReason;
}
Beispiel #28
0
ini_set('max_execution_time', 0);
ini_set('memory_limit', '512M');
if (!isset($_SERVER['DOCUMENT_ROOT']) || !strlen($_SERVER['DOCUMENT_ROOT'])) {
    $_SERVER['DOCUMENT_ROOT'] = rtrim(realpath(pathinfo(__FILE__, PATHINFO_DIRNAME) . '/../../'), '/');
}
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/stdf.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/admin_log.php';
//------------------------------------------------------------------------------
//успешные сделки
$uids = $DB->col("\n    SELECT u.uid\n    FROM account AS a\n    INNER JOIN freelancer AS u ON u.uid = a.uid\n    WHERE a.sum < -30 AND u.is_banned = B'0'\n    LIMIT 1\n");
$logins = array();
if ($uids) {
    $objUser = new users();
    foreach ($uids as $uid) {
        $objUser->GetUserByUID($uid);
        if (!$objUser->uid) {
            continue;
        }
        $sReason = 'Приостановка аккаунта до погашения задолженности. Обратитесь в поддержку <a href="mailto:support@fl.ru">support@fl.ru</a> когда будете готовы погасить задолженность за услуги сайта.';
        $sBanId = $objUser->setUserBan($uid, 0, $sReason, null);
        // пишем лог админских действий
        $sObjName = $objUser->uname . ' ' . $objUser->usurname . '[' . $objUser->login . ']';
        $sObjLink = '/users/' . $objUser->login;
        admin_log::addLog(admin_log::OBJ_CODE_USER, 3, $uid, $uid, $sObjName, $sObjLink, 0, '', null, $sReason, $sBanId, '', 103);
        //admin
        $logins[] = $objUser->login;
        //sleep(20);
    }
}
print_r($logins);
Beispiel #29
0
$stc = new static_compress();
// общий.
$stc2 = new static_compress();
// для подключаемых модулей.
$stc_js = new static_compress();
// JS-файлы
$stc2_js = new static_compress();
// JS-файлы для подключаемых модулей
if (!isset($promo)) {
    $promo = true;
}
//Глобальные переменные которые могут несуществовать и нужно это проверить
$main_page = isset($main_page) ? $main_page : false;
$freelancers_catalog = isset($freelancers_catalog) ? $freelancers_catalog : false;
$_user = new users();
$_user->GetUserByUID(get_uid(false));
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head><?php 
$yaBaseTestpage = "/interview/86/";
if (strpos($_SERVER['REQUEST_URI'], $yaBaseTestpage) !== false) {
    ?>
            <?php 
    $pattern = "#Mozilla/5.0 \\(compatible; Yandex[\\w]*/?([0-9]+\\.[0-9]+)?;(\\srobot|\\sDyatel|\\s?);? \\+http://yandex.com/bots\\)#";
    // http://help.yandex.ru/webmaster/?id=995329
    if (preg_match($pattern, $_SERVER['HTTP_USER_AGENT'])) {
        ?>
<base href="http://<?php 
        echo $_SERVER['HTTP_HOST'];
        ?>
Beispiel #30
0
banned.zero = true;
</script>
<?php 
include_once 'comments.php';
?>

<?php 
if ($sUid) {
    // просмотр истории конкретного пользователя старт
    $sObjName = hyphen_words(reformat($user['uname'] . ' ' . $user['usurname'] . ' [' . $user['login'] . ']', 60), true);
    $sObjLink = "/users/{$user['login']}";
    $sLoginSt = $session->view_online_status($user['login'], false, '');
    $ago = $session->ago;
    if (!$session->is_active) {
        $oUser = new users();
        $oUser->GetUserByUID($user['uid']);
        if ($oUser->last_time) {
            $fmt = 'ynjGi';
            if (time() - ($lt = strtotime($oUser->last_time)) > 24 * 3600) {
                $fmt = 'ynjG';
                if (time() - $lt > 30 * 24 * 3600) {
                    $fmt = 'ynj';
                }
            }
            $ago = ago_pub($lt, $fmt);
        }
    }
    $ago = $ago ? $ago : 'меньше минуты';
    if ($user['safety_bind_ip']) {
        $safety_ip = users::GetSafetyIP($user['uid']);
    }