php intvalPgSql类(方法)实例源码

php
阅读 12 收藏 0 点赞 0 评论 0

项目: 作者:
作者:Nikitia    项目:fl-ru-dam   
$prof_link = htmlspecialchars($_GET['prof']);
        $prof_id = professions::GetProfId($_GET['prof']);
        $prof_group_parent_id = professions::GetProfGroupParentId($_GET['prof']);
        if (!$prof_id) {
            $prof_group_id = professions::GetProfGroupId($_GET['prof']);
        }
    }
    if (!$prof_id && !$prof_group_id) {
        $prof_link = '';
        $_GET['region_filter_city'] = $_GET['region_filter_country'];
        $_GET['region_filter_country'] = $_GET['prof'];
    }
} else {
    if (isset($_POST['prof'])) {
        if (preg_match("/^[0-9]+\$/", $_GET['prof'])) {
            $prof_id = intvalPgSql(trim($_POST['prof']));
        } else {
            $prof_link = $_POST['prof'];
            $prof_id = professions::GetProfId($_POST['prof']);
        }
    }
}
//------------------------------------------------------------------------------
if (isset($_GET['profession_db_id']) && !($prof_id > 0 && $prof_id == $_GET['profession_db_id'] || $prof_group_id > 0 && $prof_group_id == $_GET['profession_db_id'])) {
    $link = null;
    if ($_GET['profession_db_id'] > 0) {
        if ($_GET['profession_column_id'] > 0) {
            $link = professions::GetProfLink($_GET['profession_db_id']);
        } else {
            $link = professions::GetGroupLink($_GET['profession_db_id']);
        }

作者:kapai6    项目:fl-ru-dam   
<?php

$rpath = '../';
$header = '../header.php';
$footer = '../footer.html';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/projects.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/projects_offers.php';
session_start();
$uid = get_uid();
$pid = intvalPgSql((int) trim($_GET['pid']));
$wid = intvalPgSql((int) trim($_GET['wid']));
$name = trim($_GET['user']);
$user_obj = new users();
$user_obj->GetUser($name);
$uid = $user_obj->GetUid($error, $name);
$proj = array();
$proj = (array) $user_obj;
// Проект.
$obj_project = new projects();
$project = $obj_project->GetPrjCust($pid);
if (!$project || !$user_obj->uid) {
    $fpath = '../';
    include '../404.php';
    exit;
} else {
    // Предложения по данному проекту.
    $obj_offer = new projects_offers();
    $offer = $obj_offer->GetPrjOffer($pid, $user_obj->uid);
    $width = $height = 0;
    if (!$offer) {

作者:amag    项目:fl-ru-dam   
/**
  * Возвращает список проектов.
  * 
  * @param integer $num_prjs		возвращает кол-во проектов
  * @param integer|array $kind   тип проектов (-1=5=Все проекты; 2=Конкурсы; 4=В офис; 6=Только для про)
  *                              если массив, то: array(тип, tops_only), где
  *                              tops_only: true, если нужно получить только закрепленные проекты.
  * @param integer $page			страница проектов (кол-во проектов на странице PAGE_SIZE)
  * @param boolean $comments		возвращать ли комментарии к проектам (проекты без Кандидат-Исполнитель)				
  * @param array   $filter		массив с фильтром проектов				
  * @param integer $prj_id       ID проекта, если не NULL то берется тинформация только об одном проекте
  * @param integer $is_closed    Конкурс или проект закрыт или нет
  * @param integer $to_date      Брать проекты только до этой даты.
  * @param boolean $withouttop   возвращать ли проекты не учитывая их закрепление
  * @return array				массив с информацией о проектах
  */
 function getProjects(&$num_prjs, $kind = -1, $page = 1, $comments = false, $filter = NULL, $is_blocked = true, $is_ajax = false, $prj_id = NULL, $is_closed = false, $to_date = NULL, $withouttop = false)
 {
     global $DB;
     list($kind, $tops_only) = (array) $kind;
     $is_emp = is_emp();
     $is_moder = hasPermissions('projects');
     $uid = $_SESSION['uid'];
     if ($uid && !$_SESSION['ph'] && !$is_ajax) {
         projects_filters::initClosedProjects();
     }
     $phidd = $_SESSION['ph'];
     $filterSql = new_projects::createFilterSql($filter, $kind);
     $ret = NULL;
     $limit = $this->page_size;
     if ((int) $page < 1) {
         $page = 1;
     }
     $offset = $to_date ? 0 : ($page - 1) * $limit;
     $slimit = $limit + (int) (!!$filterSql);
     // для проверки, есть ли след. страница.
     $addit = '';
     if ($filterSql) {
         if ($tops_only) {
             $addit = "(p.edit_date IS NOT NULL AND p.edit_date > NOW() - interval '2 month') AND ";
         } else {
             $addit = "(p.post_date > NOW() - interval '2 month') AND ";
         }
     }
     $addit .= (get_uid(false) ? '' : 'COALESCE(p.hide, false) = false AND ') . 'p.closed = false AND p.user_id <> 0 AND p.kind <> 9';
     if ($is_closed) {
         $addit .= ' AND ( p.end_date > NOW() OR p.end_date IS NULL )';
     }
     if ($kind == 6) {
         $addit .= ' AND p.pro_only = true';
     } else {
         if ($kind == 2) {
             $addit .= " AND (p.kind = 2 OR p.kind = 7)";
         } else {
             if ($kind != -1 && $kind != 5) {
                 $addit .= " AND p.kind = '{$kind}'";
             }
         }
     }
     if ($phidd && is_array($phidd)) {
         $hidden_projects = array();
         foreach ($phidd as $pkey => $pvalue) {
             $hidden_projects[] = $pkey;
         }
         $addit .= ' AND p.id NOT IN (' . implode(',', $hidden_projects) . ')';
     }
     if ($comments) {
         $comm = ' LEFT JOIN blogs_themes_old bt ON bt.id_gr = p.id AND bt.base = ' . ($kind == 2 ? 5 : 3);
         $sel = ', bt.thread_id, bt.messages_cnt - 1 as comm_count';
         if ($uid) {
             $comm .= " LEFT JOIN projects_watch pw ON pw.user_id = {$uid} AND pw.prj_id = p.id ";
             $sel .= ', pw.status AS prj_status';
         }
     }
     //выборка предложения по проекту пользователя
     if ($uid && !$is_emp) {
         $sel_offer = ", po.id as offer_id, po.refused, po.selected";
         $join_offer = " LEFT JOIN projects_offers po ON po.project_id = p.id AND po.user_id = '{$uid}' ";
     }
     // исключаем заблокированные проекты
     $sel_blocked = ", pb.reason as blocked_reason, pb.blocked_time, pb.project_id::boolean as is_blocked";
     $join_blocked = "LEFT JOIN projects_blocked pb ON p.id = pb.project_id ";
     if ($is_moder) {
         $sel_blocked .= ", admins.login as admin_login, admins.uname as admin_uname, admins.usurname as admin_usurname";
         $join_blocked .= "LEFT JOIN users as admins ON pb.admin = admins.uid ";
     } else {
         $join_c_blocked = $join_blocked;
         $wb = "(" . ($is_emp ? "p.user_id = {$uid} OR " : "") . " pb.project_id IS NULL) ";
         $where_blocked = "WHERE {$wb}";
         if ($filterSql) {
             $where_blocked = "";
         }
         $where_c_blocked = "AND {$wb}";
         if (!$is_blocked) {
             $join_is_blocked = $join_blocked;
             $where_is_blocked = "WHERE {$wb}";
             $where_is_c_blocked = "AND {$wb}";
         }
     }
     $offset = intvalPgSql((string) $offset);
//.........这里部分代码省略.........

作者:kapai6    项目:fl-ru-dam   
/**
  * Получает диалог в личных сообщениях между двумя пользователями для модераторов
  * Сюда не входят сообщения которые не когда не будут проверенны модераторами.
  *
  * @param int    $to_id         id пользователя-получателя
  * @param string $from_login    логин пользователя-отправителя
  * @param int    $num_msgs_from вывод, начиная с какого-то сообщения
  * @param int    $msg_offset    количество получаемых сообщений (($msg_offset-1) * $GLOBALS['msgspp'])
  *
  * @return mixed массив диалога в случае успеха или текст ошибки
  */
 public function GetMessagesForModers($to_id, $from_login, $offset = 1, $limit = null)
 {
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
     $limit = $limit ? $limit : $GLOBALS['msgspp'];
     $offset = (($offset < 1 ? 1 : $offset) - 1) * $limit;
     $user = new users();
     $user->login = $from_login;
     $from_id = $user->GetUid($error);
     $num_msgs_from = 0;
     if ($from_id) {
         $DB = new DB();
         $offset = intvalPgSql((string) $offset);
         $rows = $DB->rows('SELECT m.*, array_length(m.files, 1) AS fcount FROM messages_dialog(?i, ?i) m WHERE moderator_status IS NOT NULL LIMIT ?i OFFSET ?i', $to_id, $from_id, $limit, $offset);
         self::getMessagesAttaches($rows);
         return $rows;
     }
 }

作者:kapai6    项目:fl-ru-dam   
//.........这里部分代码省略.........
                     }
                 }
                 if (!$this->error['frl_db_id'] && $value != '') {
                     $frl = new freelancer();
                     $frl->GetUserByUID($value);
                     if ($frl->is_banned == 1) {
                         $this->error['frl_db_id'] = 'Данный пользователь заблокирован';
                         $this->error['frl_ban'] = 'Данный пользователь заблокирован';
                     }
                     $this->data['frl_id'] = $frl->uid;
                 }
                 break;
                 // специальность
             // специальность
             case 'profession0_db_id':
                 if (!$value) {
                     $this->error['profession0_db_id'] = 'Необходимо выбрать специальность';
                 }
                 break;
             case 'cost_sys':
                 $reqvs = $this->getUserReqvs();
                 if (!in_array($value, array(exrates::YM, exrates::WMR, exrates::BANK))) {
                     $this->error['cost_sys_err'] = 'Недопустимая валюта резервирования';
                     $value = exrates::BANK;
                 }
                 if (($value == exrates::YM || $value == exrates::WMR) && $reqvs['form_type'] == sbr::FT_JURI) {
                     $this->error['cost_sys_err'] = 'Резервирование через Яндекс.Деньги или WebMoney доступно только физическим лицам';
                 }
                 break;
             case 'project_id':
                 $value = $this->project['id'];
                 break;
             case 'id':
                 $value = intvalPgSql($value);
                 break;
             case 'scheme_type':
                 $value = intvalPgSql($value);
                 if ($value && (!self::$scheme_types[$value] || $value == self::SCHEME_OLD && (!$old || $old->scheme_type != self::SCHEME_OLD))) {
                     $this->error['scheme_type_err'] = 'Неверный тип договора';
                 }
                 break;
             case 'version':
                 $value = (int) $value > 32767 ? 32767 : (int) $value;
                 break;
             case 'frl_refuse_reason':
                 $value = substr($value, 0, self::SBR_REASONS_LENGTH);
                 break;
             default:
                 break;
         }
         $this->data[$field] = $value;
     }
     $this->data['professions'] = array();
     if ($_POST['profession0']) {
         $this->data['professions'][] = array('category_id' => __paramInit('int', null, 'profession0_column_id', 0), 'subcategory_id' => __paramInit('int', null, 'profession0_db_id', 0), 'prof_name' => __paramInit('string', null, 'profession0', 0));
     }
     if ($_POST['profession1']) {
         $this->data['professions'][] = array('category_id' => __paramInit('int', null, 'profession1_column_id', 0), 'subcategory_id' => __paramInit('int', null, 'profession1_db_id', 0), 'prof_name' => __paramInit('string', null, 'profession1', 0));
     }
     if ($_POST['profession2']) {
         $this->data['professions'][] = array('category_id' => __paramInit('int', null, 'profession2_column_id', 0), 'subcategory_id' => __paramInit('int', null, 'profession2_db_id', 0), 'prof_name' => __paramInit('string', null, 'profession2', 0));
     }
     if ($request['stages']) {
         foreach ($request['stages'] as $num => $stage) {
             if (isset($stage['attaches']) && is_array($stage['attaches'])) {
                 foreach ($stage['attaches'] as $anum => $att_id) {

作者:kapai6    项目:fl-ru-dam   
}
 if ($i > 0 && $question === '') {
     $error_flag = 1;
     $alert[5] = 'Введите текст вопроса';
 } else {
     if ($i > blogs::MAX_POLL_ANSWERS) {
         $error_flag = 1;
         $alert[5] = 'Вы можете указать максимум ' . blogs::MAX_POLL_ANSWERS . ' ответов';
     } else {
         if ($i < 2 && $question !== '') {
             $error_flag = 1;
             $alert[5] = 'Нужно указать минимум 2 варианта ответа в голосовании';
         }
     }
 }
 if (!($gr = intvalPgSql($gr)) && !($ord == 'my' || $PDA)) {
     include ABS_PATH . '/404.php';
     exit;
 }
 if (is_empty_html($msg)) {
     $msg = '';
 }
 if ($_POST['close_comments']) {
     $close_comments = 't';
 } else {
     $close_comments = 'f';
 }
 if ($_POST['is_private']) {
     $is_private = 't';
 } else {
     $is_private = 'f';

作者:Nikitia    项目:fl-ru-dam   
/**
  * Устанавливает/изменяет валюту выплаты за завершенный этап.
  * Вычисляет все налоги/комиссии, плюс в случае арбитража -- все необходимые коэффициэнты.
  *
  * @param integer $credit_sys   код валюты (см. класс exrates).
  * @param boolean $any_sys   разрешает любые валюты для выплаты (для админов).
  * @return boolean    успешно?
  */
 function setPayoutSys($credit_sys, $any_sys = false, $role = null)
 {
     setlocale(LC_ALL, 'en_US.UTF-8');
     $credit_sys = intvalPgSql($credit_sys);
     if (!$any_sys && !$this->checkPayoutSys($credit_sys)) {
         return false;
     }
     if (($cost = $this->getPayoutSum($role, $credit_sys, NULL, $credit_sys)) <= 0) {
         return false;
     }
     $is_arbitrage = 'false';
     if ($this->arbitrage['id']) {
         if (isset($this->arbitrage['resolved']) && !$this->arbitrage['resolved']) {
             return false;
         }
         $is_arbitrage = 'true';
     }
     $user_id = $this->sbr->uid;
     if ($role) {
         $user_id = $role == sbr::FRL ? $this->sbr->data['frl_id'] : $this->sbr->data['emp_id'];
     }
     $credit_sum = round($cost, 2);
     $sql = "\n          UPDATE sbr_stages_payouts\n             SET credit_sys = {$credit_sys}, credit_sum = {$credit_sum}, is_arbitrage = {$is_arbitrage}\n           WHERE stage_id = {$this->id}\n             AND user_id = {$user_id}\n             AND completed IS NULL\n        ";
     if ($res = pg_query(self::connect(false), $sql)) {
         if (!pg_affected_rows($res)) {
             $state = $this->sbr->data['scheme_type'] == sbr::SCHEME_LC ? NULL : '';
             $sql = "INSERT INTO sbr_stages_payouts(stage_id, user_id, credit_sys, credit_sum, is_arbitrage, state) VALUES ({$this->id}, {$user_id}, {$credit_sys}, {$credit_sum}, {$is_arbitrage}, '{$state}');";
             $res = pg_query(self::connect(false), $sql);
         }
     }
     return !!$res;
 }

作者:kapai6    项目:fl-ru-dam   
if ((int) $cat < 1) {
    $cat = 0;
}
// возможно лучше доработать функцию __paramInit
if ((int) $page < 1) {
    $page = extractInteger($_REQUEST['page'], 1);
}
$action = __paramInit('string', 'action', 'action');
$top_id = __paramInit('string', 'post', 'top_id');
$message_id = NULL;
list($t, $c) = split('[.]', $top_id);
if ($t) {
    $top_id = intvalPgSql($t);
}
if ($c) {
    $comment_id = intvalPgSql($c);
}
if ($_GET['post'] && $_GET['site'] == 'Topic' && !$_GET['newurl'] && $_SERVER['REQUEST_METHOD'] != 'POST') {
    $query_string = preg_replace('/post=' . preg_quote($_GET['post']) . '/', '', $_SERVER['QUERY_STRING']);
    $query_string = preg_replace('/site=Topic/', '', $query_string);
    //$query_string = preg_replace("/^&{1,}/", "", $query_string);
    $query_array = explode('&', $query_string);
    $query_string = '';
    $first_param = true;
    foreach ($query_array as $key => $value) {
        if ($value) {
            if ($first_param === true) {
                // перед первым параметром не ставим &
                $first_param = false;
            } else {
                $query_string .= '&';

作者:amag    项目:fl-ru-dam   
/**
  * Проверка пользовательского запроса перед созданием или редактированием документа.
  * Заполнение переменной ошибок и $this->post_doc (тот же запрос, без лишних слешей), а также загружает файл документа на сервер.
  * 
  * @param array $request   данные запроса (гет, пост).
  * @param array $files   массив $_FILES
  */
 function _docInitFromRequest($request, $files)
 {
     $this->post_doc = array();
     foreach ($request as $field => $value) {
         if (is_scalar($value)) {
             $value = stripslashes($value);
         }
         switch ($field) {
             case 'status':
             case 'access_role':
             case 'owner_role':
             case 'id':
             case 'type':
                 $value = intvalPgSql($value);
                 break;
         }
         $this->post_doc[$field] = $value;
     }
     if ($files != null) {
         $this->post_doc['file_id'] = null;
     }
     if (!$this->isAdmin() && !$this->isAdminFinance()) {
         if (!isset($this->post_doc['status'])) {
             $this->post_doc['status'] = self::DOCS_STATUS_SENT;
         }
         if (!isset($this->post_doc['access_role'])) {
             $this->post_doc['access_role'] = $this->isEmp() ? self::DOCS_ACCESS_EMP : self::DOCS_ACCESS_FRL;
         }
     }
     if (!$this->post_doc['name']) {
         $cnum = $this->getContractNum();
         $dn = sbr::$docs_types[$this->post_doc['type']][0];
         switch ($this->post_doc['type']) {
             case sbr::DOCS_TYPE_STATEMENT:
                 $this->post_doc['name'] = "{$dn} № {$cnum}";
                 break;
             case sbr::DOCS_TYPE_TZ_PDRD:
                 $this->post_doc['name'] = "{$dn} № {$cnum}";
                 break;
             case sbr::DOCS_TYPE_ACT:
             case sbr::DOCS_TYPE_FACTURA:
             case sbr::DOCS_TYPE_REP:
             case sbr::DOCS_TYPE_COPY_ACT:
             case sbr::DOCS_TYPE_COPY_FACTURA:
             case sbr::DOCS_TYPE_AGENT_REP:
             case sbr::DOCS_TYPE_PSKB_ACT:
                 $this->post_doc['name'] = "{$dn} по договору № {$cnum}";
                 break;
             case sbr::DOCS_TYPE_COPY_CONTRACT:
             case sbr::DOCS_TYPE_OFFER:
                 if ($this->post_doc['subtype'] == 1) {
                     // ВНИМАНИЕ!!! в названии документа обязательно должно присутствовать слово с корнем "договор" (договор, договора, договору ...)
                     $this->post_doc['name'] = "{$dn} № {$cnum} на заключение Договора";
                 } else {
                     if ($this->post_doc['subtype'] == 2) {
                         $this->post_doc['name'] = "{$dn} № {$cnum} на заключение Соглашения";
                     } else {
                         $this->post_doc['name'] = "{$dn} № {$cnum}";
                     }
                 }
                 break;
             case sbr::DOCS_TYPE_ARB_REP:
             case sbr::DOCS_TYPE_COPY_AGREEMENT:
             case sbr::DOCS_TYPE_FM_APPL:
             case sbr::DOCS_TYPE_WM_APPL:
             case sbr::DOCS_TYPE_YM_APPL:
                 $this->post_doc['name'] = "{$dn}";
                 break;
             default:
                 $this->error['docs']['name'] = 'Пожалуйста, заполните это поле';
                 break;
         }
     }
     if (!$this->error && $files['attach']['size']) {
         $this->getUploadDir();
         $file = new CFile($files['attach']);
         if ($err = $this->uploadFile($file, self::DOCS_FILE_MAX_SIZE)) {
             $this->error['docs']['attach'] = $err;
         } else {
             $this->post_doc['file_id'] = $file->id;
         }
     }
 }

作者:amag    项目:fl-ru-dam   
/**
  * Возвращает список тем в разделе
  *
  * -------------------------------------------------------------------------------------
  * Внимание! Замечание к подзапросу на основные вкладки (новые, популярные, актуальные).
  *
  * Подзапрос настроен на работу индексов типа "ix blogs_themes/viewgroup*", поэтому любое
  * добавление условий или (тем более с привязкой дополнительных таблиц!) испортит его.
  * Суть заключается в том, что мы все условия копируем в таблицы blogs_themes из таблиц blogs_msgs и других,
  * для того, чтобы использовать индексы и не делать лишних джойнов, т.е. все проверки делаются в рамках 
  * единственной
  * таблицы. Поэтому мы быстро выбираем все необходимые N тем и только потом связываем их с остальными таблицами.
  * Чтобы добавить условие, нужно по аналогии, например, с deleted, is_blocked и т.п.), добавить клон 
  * необходимого
  * поля в blogs_themes и скорректировать индекс(ы) (протестировав предварительно).
  * -------------------------------------------------------------------------------------
  *
  *
  * @param integer $gr_num				идентификатор раздела
  * @param string  $gr_name				возвращает название раздела
  * @param integer $num_treads			возвращает кол-во тем в данном разделе
  * @param integer $page					номер страницы из списка тем, которую надо выводить [получает или возвращает, в зависимости от $having_message]
  * @param string  $error				возвращает сообщение об ошибке
  * @param integer $fid					UID текущего юзера
  * @param integer $mod					имеет ли текущий юзер права на просмотр данного раздела [1 - да, 0 - нет]
  * @param integer $having_message		УСТАРЕЛО. id сообщения, страницу с которым необходимо отобразить (0 - показать страницу $page)
  * @param integer $read_only			возвращает параметр - является ли данный раздел разделом "только для чтения"
  * @param string  $ord					параметр сортировки ("my", "relevant", "best", "new", "favs")
  * @param string  $sort_order           позволяет передать дополнительные условия сортировки
  * @return array						[[информация о сообщении]]
  */
 function GetGroup($gr_num, &$gr_name, &$num_treads, $page, &$error, $fid = 0, $mod = 1, $having_message = 0, &$read_only, $ord = "new", $is_ban = true, $sort_order = '')
 {
     global $DB;
     $cachedelay = 300;
     if (hasPermissions("blogs")) {
         $cachedelay = 0;
     }
     $memBuff = new memBuff();
     $fid = (int) $fid;
     $gr_num = (int) $gr_num;
     $num_treads = 0;
     $year = date('Y');
     $can_prevyear_ontops = date('n') <= 2;
     $limit = $GLOBALS['blogspp'];
     $group = $gr_num != 0 ? "id_gr = {$gr_num} " : "";
     $offset = $limit * ($page - 1);
     $offset = intvalPgSql((string) $offset);
     $limit_str = "LIMIT {$limit} OFFSET {$offset}";
     $order = "post_time DESC";
     $ids = array();
     $idx = array();
     $get_ontops = $ord == 'ontop';
     if (!$get_ontops) {
         if ($gr_num != 0) {
             $gr_name = $this->GetGroupName($gr_num, 0, $mod);
             if (!$gr_name) {
                 $error = "У вас недостаточно прав для просмотра этого форума";
                 return 0;
             }
         } else {
             $gr_name = "Все вместе";
         }
     }
     // смотрим баны
     if ($fid && $fid == $_SESSION['uid']) {
         $role = $_SESSION['role'];
     } else {
         if ($fid) {
             $users = new users();
             $role = $users->GetField($fid, $error, 'role');
         } else {
             $role = 0;
         }
     }
     $is_moder = hasPermissions('blogs', $fid);
     if ($is_moder) {
         $sel_blocked = ", moderators.login as moder_login, moderators.uname AS moder_name, moderators.usurname as moder_uname";
         $join_blocked = " LEFT JOIN users AS moderators ON blogs_blocked.admin = moderators.uid ";
     } else {
         $where_blocked = '(t.is_blocked = false) ';
         $where_private = ' AND (' . ($fid ? "t.fromuser_id = {$fid} OR " : '') . 't.is_private = false)';
         $where_deleted = ' AND (t.deleted IS NULL )';
         $where_deleted_my = ' AND t.deleted IS NULL AND m.deleted IS NULL';
         // контролим баны
         if (!$is_ban) {
             $where_is_blocked = $where_blocked;
         }
     }
     $_group = $group ? " {$group} AND " : '';
     switch ($ord) {
         case "my_all":
         case "my_posts":
         case "my_comments":
         case 'favs_list':
         case 'favs_std':
             if ($ord != 'favs_list' && $ord != 'favs_std') {
                 $sReplyTo = $ord != 'my_all' ? $ord == 'my_posts' ? ' AND m.reply_to IS NULL' : ' AND m.reply_to IS NOT NULL' : '';
                 $join_banned = $where_deleted ? 'INNER JOIN users mtu 
             	   ON mtu.uid = t.fromuser_id AND mtu.is_banned = 0::bit(1)' : '';
//.........这里部分代码省略.........

作者:kapai6    项目:fl-ru-dam   
$stage = $sbr->initFromStage($stage_id);
     if ($action == 'arb_resolve' && $sbr->isAdmin()) {
         $resolve = __paramInit('bool', NULL, 'sendform');
         $cancel = __paramInit('bool', NULL, 'cancel');
         if ($resolve) {
             if (!($iagree = __paramInit('bool', NULL, 'iagree'))) {
                 $stage->error['arbitrage']['iagree'] = 'Необходимо подтверждение';
             } else {
                 if ($stage->arbResolve($_POST)) {
                     $frl_percent = $stage->request['frl_percent'] / 100;
                     $stage->getArbitrage(false, false);
                     // Раз вынесли решение берем арбитраж, для корректного расчета процентов
                     if ($frl_percent != 1 && $stage->sbr->scheme_type == sbr::SCHEME_LC) {
                         $pskb = new pskb($stage->sbr);
                         $lc = $pskb->getLC();
                         $credit_sys = intvalPgSql(pskb::$exrates_map[$lc['ps_emp']]);
                         $stage->setPayoutSys($credit_sys, true, sbr::EMP);
                     }
                     header_location_exit("/norisk2/?site=Stage&id={$stage->id}");
                 }
             }
         } elseif ($cancel) {
             if ($stage->arbCancel()) {
                 header_location_exit("/norisk2/?site=Stage&id={$stage->id}");
             }
         }
     }
     $arbitrsList = $stage->getArbitrs();
     break;
 case 'docs':
     $inner = $fpath . 'docs.php';

作者:kapai6    项目:fl-ru-dam   
$action = __paramInit('string', 'action', 'action');
     $folder = __paramInit('int', 'fld', 'fld', 0);
     if ($kind < 0 || $kind > 6) {
         $kind = 0;
     }
     $css_file = array('/css/block/b-free-share/b-free-share.css', '/css/block/b-note/b-note.css', '/css/block/b-button-multi/b-button-multi.css', '/css/block/b-prev/b-prev.css', 'projects.css', '/css/nav.css', '/css/projects3.css');
     $header = '../header.php';
     $footer = '../footer.html';
     $content = 'content_list.php';
     include '../template2.php';
     exit;
 case 'comment':
     if ($PDA) {
         $cid = intval($_GET['cid']);
         $user_id = get_uid(false);
         $prj_id = intvalPgSql((int) trim(str_replace('O', '0', $_GET['pid'])));
         $po_id = intval($_GET['id']);
         // Проект.
         $action = trim($_REQUEST['action']);
         $obj_project = new projects();
         $project = $obj_project->GetPrjCust($prj_id);
         $pod = new projects_offers_dialogue();
         if (is_emp()) {
             if ($project['user_id'] != get_uid(false)) {
                 $content = '404.php';
                 include '../template2.php';
                 exit;
             }
         } else {
             $po = new projects_offers();
             if (!$project || !$po->GetPrjOffer($prj_id, $user_id) || $cid && $pod->GetLastDialogueMessage($user_id, $po_id) != $cid) {

作者:Nikitia    项目:fl-ru-dam   
/**
  * Получение списка пользователей
  * 
  * @param  array $aParams массив входящих данных
  * @return array $aResult ответ
  */
 protected function x____users_get($aParams = array())
 {
     $this->_validDevice($aParams);
     $nUid = get_uid(false);
     $nId = intvalPgSql($aParams['id']);
     $aResult = array('user' => array());
     if (!empty($nId)) {
         require_once ABS_PATH . '/classes/users.php';
         $oUser = new users();
         $oUser->GetUserByUID($nId);
         if ($oUser->uid) {
             if (empty($oUser->is_banned)) {
                 $aData = array();
                 $aClassVars = array_keys(get_class_vars('users'));
                 foreach ($aClassVars as $sVar) {
                     $aData[$sVar] = $oUser->{$sVar};
                 }
                 if (!is_emp($aData['role'])) {
                     require_once ABS_PATH . '/classes/freelancer.php';
                     $aTmp = freelancer::getFreelancerByLogin(array($aData['login']));
                     $aData['spec'] = $aTmp[0]['spec'];
                 }
                 $aResult['user'] = $this->_getUserData($aData, false, true);
             } else {
                 $this->error(EXTERNAL_ERR_USER_BANNED);
             }
         } else {
             $this->error(EXTERNAL_ERR_USER_NOTFOUND);
         }
     } else {
         $this->error(EXTERNAL_ERR_EMPTY_USER_ID);
     }
     return $aResult;
 }

作者:Nikitia    项目:fl-ru-dam   
/**
  * Заполнение обязательных полей после регистрации через API мобильного приложения.
  * 
  * @param  array $aParams массив входящих данных
  * @return bool true - успех, false - провал
  */
 public function actionSaveInfoMobile($aParams = array())
 {
     $this->setFieldInfo('uname', __paramValue('string', iconv('utf-8', 'cp1251', $aParams['first_name'])));
     $this->setFieldInfo('usurname', __paramValue('string', iconv('utf-8', 'cp1251', $aParams['last_name'])));
     $this->setFieldInfo('birthday', __paramValue('string', $aParams['birthday']));
     $this->setFieldInfo('country', __paramValue('int', $aParams['country_id']));
     $this->setFieldInfo('city', __paramValue('int', $aParams['city_id']));
     $this->setFieldInfo('info_for_reg', array('birthday' => 0, 'sex' => 0, 'country' => 0, 'city' => 0));
     $gender = __paramValue('int', $aParams['gender']);
     $this->setFieldInfo('sex', $gender == 1 ? 't' : ($gender == 2 ? 'f' : NULL));
     $this->checkedFields();
     if (date('Y-m-d', strtotime($aParams['birthday'])) != $aParams['birthday']) {
         $this->error['birthday'] = 'Укажите некорректную дату дня рождения';
         $this->errno['birthday'] = 2;
     }
     if (empty($this->error)) {
         if (!is_emp()) {
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/freelancer.php';
             $user = new freelancer();
         } else {
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/employer.php';
             $user = new employer();
         }
         $user->info_for_reg = serialize($this->info_for_reg);
         $user->uname = $this->uname;
         $user->usurname = $this->usurname;
         $user->sex = $this->sex;
         $user->birthday = $this->birthday;
         $user->country = $this->country;
         $user->city = $this->city;
         if (!is_emp()) {
             $spec = intvalPgSql($aParams['prof_id']);
             if ($spec) {
                 require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/professions.php";
                 $or_spec = professions::GetProfessionOrigin($spec);
                 $spec_mod = professions::getLastModifiedSpec($_SESSION['uid']);
                 if (!is_pro() && $spec_mod['days'] > 0) {
                     $this->error['spec'] = 'Не прошло 30 дней с момента последней смены специализации';
                     $this->errno['spec'] = 2;
                 } else {
                     $user->spec = $spec;
                     $user->spec_orig = $or_spec;
                     professions::setLastModifiedSpec($_SESSION['uid'], $spec);
                 }
             } else {
                 $this->error['spec'] = 'Не указан параметр ID профессии';
                 $this->errno['spec'] = 1;
             }
         }
         if (empty($this->error)) {
             if ($sError = $user->Update($_SESSION['uid'], $res)) {
                 $this->error['save'] = $sError;
             } else {
                 if (!is_emp()) {
                     $_SESSION['specs'] = $user->GetAllSpecs($_SESSION['uid']);
                 }
             }
         }
         if (empty($this->error['save'])) {
             $_SESSION['check_user_access'] = true;
         }
     }
     return empty($this->error);
 }

作者:Nikitia    项目:fl-ru-dam   
/**
 * Корректная инициализация переданных параметров GET и POST переданных пользователем
 *
 * @param string  $type		Тип переданных данных (int, float, string, link, html, bool, money)
 * @param string  $get_name	Название данных в GET 
 * @param ustring $post_name	Название данных в POST 
 * @param mixed   $empty_val	Значение по умолчанию
 * @param integer $maxlen		Максимальная длинна данных
 * @param string $strip_tags		Для $type = 'html'. Если TRUE, то все теги и спецсимволы, сюда и будем пехать их
 * @param string $value  При обработке входящих данных в функции XAJAX необходима обработка чисто переменных
 *                            переводятся в сущности.
 *                            @see change_q_x()
 * @return mixed
 */
function __paramInit($type = 'int', $get_name = NULL, $post_name = NULL, $empty_val = NULL, $maxlen = NULL, $strip_tags = FALSE, $value = FALSE)
{
    //$value = FALSE;
    if ($get_name && isset($_GET[$get_name])) {
        if ($_GET[$get_name] !== '') {
            $value = $_GET[$get_name];
        }
    }
    if ($value === FALSE) {
        if ($post_name && isset($_POST[$post_name])) {
            if ($_POST[$post_name] !== '') {
                $value = $_POST[$post_name];
            }
        }
    }
    if ($value === FALSE) {
        return $empty_val;
    }
    if (intval($maxlen)) {
        $value = addslashes(substr(stripslashes($value), 0, intval($maxlen)));
    }
    switch ($type) {
        case 'striptrim':
            return stripslashes(trim($value));
        case 'page':
            $value = intvalPgSql($value);
            return $value <= 0 ? 1 : $value;
        case 'uinteger':
        case 'uint':
            return abs(intvalPgSql($value));
        case 'array_integer':
        case 'array_int':
            return array_map('intvalPgSql', $value);
        case 'integer':
        case 'int':
            return intvalPgSql($value);
        case 'String':
            //$value = stripslashes($value);
        //$value = stripslashes($value);
        case 'string':
            return change_q_x($value, TRUE);
        case 'string_no_slashes':
            return stripslashes(change_q_x($value, TRUE));
        case 'link':
            return change_q_x(strip_http($value), TRUE);
        case 'html':
            return $strip_tags ? change_q_x($value, FALSE, TRUE, "", false, false) : change_q_x($value, FALSE, TRUE, null, false, false);
        case 'htmltext':
            return change_q_x($value, TRUE, FALSE);
            // аналогичен 'htmltext', но оставляет теги ul, li, b, p, i
        // аналогичен 'htmltext', но оставляет теги ul, li, b, p, i
        case 'html_save_ul_li_b_p_i':
            return change_q_x($value, false, false, 'b|i|p|ul|li');
        case 'array':
            return $value;
        case 'bool':
            return !!$value;
        case 'float':
            setlocale(LC_ALL, 'en_US.UTF-8');
            return floatval($value);
        case 'money':
            setlocale(LC_ALL, 'en_US.UTF-8');
            return floatval(preg_replace('/\\s+/', '', str_replace(",", ".", $value)));
        case 'ckedit_nocut':
            $nocut = true;
        case 'ckeditor':
        case 'ckedit':
            //$value = stripslashes($value);
            $value = wysiwyg_video_replace($value, $wysiwyg_videos);
            if (hasPermissions('adm')) {
                $value = wysiwyg_image_replace($value, $wysiwyg_images);
            }
            $value = wysiwyg_code_replace($value, $wysiwyg_codes);
            $ph = md5(time()) . "_code";
            list($value, $url) = str_replace_mask('#((<a[^>]*>)(.*?)(<\\/a>))#mix', $value);
            foreach ($url as &$u) {
                $u = stripslashes($u);
                $u = cleanHref($u);
            }
            $value = preg_replace(array("~<cut\\s*?\\/>~mix", "~<\\/cut>~"), array("<cut>", ""), $value);
            // Заменяем каты
            if ($nocut) {
                // Удаляем каты
                $value = str_replace("<cut>", "", $value);
            }
            $value = str_replace(array("<br />", "<br/>", "<br>"), "___BR___", $value);
//.........这里部分代码省略.........

作者:Nikitia    项目:fl-ru-dam   
/**
 * Сохранение проектов и конкурсов
 * 
 * @param object $objResponse xajaxResponse
 * @param string $rec_id идентификатор записи
 * @param string $rec_type тип записи
 * @param array $aForm массив данных
 * @param string $sDrawFunc имя функции для выполнения после сохранения
 */
function _admEditProjectsSaveForm(&$objResponse, $rec_id = '', $rec_type = '', $aForm = array(), $sDrawFunc = '')
{
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/projects.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/professions.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/user_content.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/attachedfiles.php';
    $alert = array();
    $tmpPrj = new tmp_project($aForm['temp_key']);
    $prj = $tmpPrj->init(2);
    $kind = isset($aForm['kind']) ? intvalPgSql($aForm['kind']) : $prj['kind'];
    $sLink = change_q_x($aForm['link'], false, true, null, false, false);
    if (!empty($sLink)) {
        if (!preg_match('/http:\\/\\//', $sLink)) {
            $sLink = 'http://' . $sLink;
        }
    }
    $tmpPrj->setProjectField('kind', $kind);
    $tmpPrj->setProjectField('descr', antispam(change_q_x($aForm['descr'], FALSE, TRUE, "", false, false)));
    $tmpPrj->setProjectField('name', substr(antispam(change_q_x($aForm['name'], TRUE)), 0, 512));
    setlocale(LC_ALL, 'en_US.UTF-8');
    $tmpPrj->setProjectField('cost', isset($aForm['cost']) ? floatval($aForm['cost']) : 0);
    $tmpPrj->setProjectField('currency', isset($aForm['currency']) ? intvalPgSql($aForm['currency']) : 0);
    $tmpPrj->setProjectField('folder_id', isset($aForm['folder_id']) ? intvalPgSql($aForm['folder_id']) : 0);
    $tmpPrj->setProjectField('budget_type', isset($aForm['budget_type']) ? intvalPgSql($aForm['budget_type']) : 0);
    $tmpPrj->setProjectField('priceby', isset($aForm['priceby']) ? intvalPgSql($aForm['priceby']) : 0);
    $tmpPrj->setProjectField('agreement', isset($aForm['agreement']) ? intvalPgSql($aForm['agreement']) : 0);
    $tmpPrj->setProjectField('country', isset($aForm['country']) ? intvalPgSql($aForm['country']) : 0);
    $tmpPrj->setProjectField('city', isset($aForm['pf_city']) ? intvalPgSql($aForm['pf_city']) : 0);
    $tmpPrj->setProjectField('pro_only', isset($aForm['pro_only']) ? 't' : 'f');
    $tmpPrj->setProjectField('is_color', isset($aForm['is_color']) ? 't' : 'f');
    $tmpPrj->setProjectField('is_bold', isset($aForm['is_bold']) ? 't' : 'f');
    $tmpPrj->setProjectField('link', $sLink);
    if ($kind == 7) {
        $tmpPrj->setProjectField('end_date', change_q_x($aForm['end_date'], TRUE));
        $tmpPrj->setProjectField('win_date', change_q_x($aForm['win_date'], TRUE));
    }
    // разделы
    $c = $aForm['categories'];
    $sc = $aForm['subcategories'];
    if (empty($c) || sizeof($c) == 1 && $c[0] == 0) {
        $alert[3] = 'Не выбран раздел';
    } else {
        $cats = array();
        foreach ($c as $sKey => $value) {
            if ($value == 0) {
                continue;
            }
            $check[] = $value . "_" . $sc[$sKey];
        }
        $uniq = array_unique($check);
        foreach ($uniq as $val) {
            list($cat, $subcat) = explode('_', $val);
            $check_array[$cat][] = $subcat;
        }
        foreach ($check_array as $k => $val) {
            if (count($val) > 1 && array_search(0, $val) !== false) {
                $cats[] = array('category_id' => $k, 'subcategory_id' => 0);
                unset($check_array[$k]);
            } else {
                foreach ($val as $m => $v) {
                    $cats[] = array('category_id' => $k, 'subcategory_id' => $v);
                }
            }
        }
        $tmpPrj->setCategories($cats);
    }
    $prj = $tmpPrj->getProject();
    $descr_limit = 5000;
    if ($prj['cost'] < 0) {
        $alert[7] = 'Введите положительную сумму';
    }
    if ($prj['cost'] > 999999) {
        $alert[7] = 'Слишком большая сумма';
    }
    if ($prj['cost'] > 0 && ($prj['currency'] < 0 || $prj['currency'] > 3)) {
        $alert[7] = 'Валюта не определена';
    }
    if (is_empty_html($prj['name'])) {
        $alert[1] = 'Поле не заполнено';
    }
    if (is_empty_html($prj['descr'])) {
        $alert[2] = 'Поле не заполнено';
    }
    if (strlen_real($prj['descr']) > $descr_limit) {
        $alert[2] = "Исчерпан лимит символов ({$descr_limit})";
    }
    if ($prj['kind'] == 7) {
        if (!preg_match("/^([0-9]{1,2})\\-([0-9]{1,2})\\-([0-9]{4})\$/", $prj['end_date'], $o1) || !checkdate($o1[2], $o1[1], $o1[3])) {
            $alert[5] = 'Неправильная дата';
        }
        if (!preg_match("/^([0-9]{1,2})\\-([0-9]{1,2})\\-([0-9]{4})\$/", $prj['win_date'], $o2) || !checkdate($o2[2], $o2[1], $o2[3])) {
//.........这里部分代码省略.........

评论列表


问题


面经


文章

微信
公众号

扫码关注公众号