public function setSelectFilter($filter)
 {
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/professions.php";
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/project_exrates.php";
     $project_exRates = project_exrates::GetAll();
     $set_select[] = "*";
     // Мои специализации
     if ($filter['my_specs'] == 't' && $filter['user_specs']) {
         foreach ($filter['user_specs'] as $spec) {
             $select[] = "(prj_subcategory1 = {$spec} OR prj_subcategory2 = {$spec} OR prj_subcategory3 = {$spec})";
         }
         $set_select[] = "IF(" . implode(" OR ", $select) . ", 1, 0) as my_spec_filter";
         unset($select);
     }
     //Если не нужны завершенные конкурсы
     if ($filter['is_closed_contest']) {
         $set_select[] = "IF(NOT end_date OR end_date > NOW(), 1, 0) as closed_contest";
     }
     // Бюджет
     if ($filter['cost_from'] || $filter['cost_to']) {
         $cr = (int) $filter['currency'];
         $cex = array(2, 3, 4, 1);
         $cost_from = ($cost_from = (double) $filter['cost_from']) < 0 ? 0 : (double) $filter['cost_from'];
         $cost_to = ($cost_to = (double) $filter['cost_to']) < 0 ? 0 : (double) $filter['cost_to'];
         $cost_to = $cost_to < $cost_from && $cost_to != 0 ? $cost_from : $cost_to;
         if ($cost_to || $cost_from) {
             for ($i = 0; $i < 4; $i++) {
                 $exfr = round($cost_from * $project_exRates[$cex[$cr] . $cex[$i]], 4);
                 $exto = round($cost_to * $project_exRates[$cex[$cr] . $cex[$i]], 4);
                 $fSql .= ($i ? ' OR ' : '') . "(p.currency = {$i} AND p.cost >= {$exfr}" . ($cost_to ? " AND p.cost <= {$exto}" : '') . ')';
                 $select[] = "(currency = {$i} AND cost >= {$exfr}" . ($cost_to ? " AND cost <= {$exto}" : '') . ")";
             }
             if ($filter['wo_cost'] == 't') {
                 $select[] = '(cost = 0)';
             }
             $set_select[] = "IF(" . implode(" OR ", $select) . ", 1, 0) as cost_filter";
             unset($select);
         }
     } elseif ($filter['cost_from'] === '0' && $filter['cost_to'] === '0') {
         $set_select[] = "IF(cost = 0, 1, 0) as cost_filter";
     } else {
         $set_select[] = "IF(cost = 0 OR cost > 0, 1, 0) as cost_filter";
     }
     // Разделы/Подразделы
     if ($filter['categories'] && $filter['my_specs'] == 'f') {
         $categories = array();
         for ($ci = 0; $ci < 2; $ci++) {
             if (sizeof($filter['categories'][$ci])) {
                 foreach ($filter['categories'][$ci] as $ckey => $cvalue) {
                     $categories[$ci][] = (int) $ckey;
                 }
             }
         }
         $sProfCat = '';
         $sProfSubcat = '';
         // собираем подразделы выбранных разделов
         if (sizeof($categories[0])) {
             $sProfCat = professions::getProfIdForGroups($categories[0]);
         }
         // собираем выбранные подразделы
         if (sizeof($categories[1])) {
             $sProfSubcat = implode(',', $categories[1]);
         }
         // склеиваем и получаем все подразделы вместе с зеркалами
         $sProf = $sProfCat . ($sProfCat && $sProfSubcat ? ',' : '') . $sProfSubcat;
         $aProf = professions::GetMirroredProfs($sProf);
         foreach ($aProf as $prof) {
             $select[] = "(prj_subcategory1 = {$prof} OR prj_subcategory2 = {$prof} OR prj_subcategory3 = {$prof})";
         }
         if (sizeof($categories[0])) {
             foreach ($categories[0] as $cat) {
                 $select[] = "(prj_category1 = {$cat} OR prj_category2 = {$cat} OR prj_category3 = {$cat})";
             }
         }
         $set_select[] = "IF(" . implode(" OR ", $select) . ", 1, 0) as category_filter";
         unset($select);
     }
     $this->_engine->setSelect(implode(", ", $set_select));
     $this->_engine->setFilter("cost_filter", array(1));
     if ($filter['is_closed_contest']) {
         $this->_engine->setFilter("closed_contest", array(1));
     }
     if ($filter['only_sbr'] == 't') {
         $this->_engine->setFilter("prefer_sbr", array(1));
     }
     if ($filter['my_specs'] == 't' && $filter['user_specs']) {
         $this->_engine->setFilter("my_spec_filter", array(1));
     }
     if ($filter['categories'] && $filter['my_specs'] == 'f') {
         $this->_engine->setFilter("category_filter", array(1));
     }
     if ($filter['country']) {
         $this->_engine->setFilter("country", array($filter['country']));
     }
     if ($filter['city']) {
         $this->_engine->setFilter("city", array($filter['city']));
     }
 }
示例#2
0
 /**
  * Формирует SQL-условия по заданному фильтру.
  *
  * @param array $filter    фильтр, см. функцию.
  * @param $prof_id   ид. специализации (если находимся в конкретном разделе каталога).
  * @return array   [where-условие, join-вставки].
  */
 function createCatalogFilterSql($filter, $prof_id = 0)
 {
     if (!$filter) {
         return NULL;
     }
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/projects.php";
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/teams.php";
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/professions.php";
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/project_exrates.php";
     global $project_exRates, $DB;
     $filter_join = array();
     $filter_where = array();
     if ($filter['prof'] && !$prof_id) {
         if (count($filter['prof'][0]) > 0) {
             $p1 = professions::getProfIdForGroups(array_keys($filter['prof'][0]), true);
         }
         if (count($filter['prof'][1]) > 0) {
             $p2 = professions::GetProfessionOrigin(implode(",", array_keys($filter['prof'][1])));
         }
         $in_sql = ($p2 ? $p2 : "") . ($p1 && $p2 ? ", " : "") . ($p1 ? $p1 : "");
         if ($in_sql) {
             $filter_where[] = "s.spec_orig IN ({$in_sql})";
             $has_prof_filter = true;
         }
     }
     if ($filter['orig_kwords']) {
         if (!$has_prof_filter && !$prof_id) {
             if ($kprofs = professions::getProfsByKeywords($filter['orig_kwords'])) {
                 $kprofs = professions::GetProfessionOrigin($kprofs);
                 $kf[] = "s.spec_orig IN ({$kprofs})";
             }
             $m = array();
             $e = explode(',', $filter['orig_kwords']);
             foreach ($e as $k => $v) {
                 if ($v = trim($v)) {
                     $m[] = strtolower($v);
                 }
             }
             if ($m) {
                 $kf[] = $DB->parse('s.uid IN (SELECT portf_word.uid FROM words JOIN portf_word ON portf_word.wid=words.id JOIN users ON users.uid=portf_word.uid where lower(name) IN (?l))', $m);
             }
         }
         if (!empty($filter['kword']) && is_array($filter['kword'])) {
             foreach ($filter['kword'] as $k => $v) {
                 $g[$v['group_id']] = $v['group_id'];
                 $w[$v['id']] = $v['id'];
             }
             $kf[] = 's.uid IN (SELECT DISTINCT pw.uid FROM words w JOIN portf_word pw ON pw.wid = w.id WHERE w.group_id IN (' . implode(',', $g) . '))';
         }
         if ($kf) {
             $filter_where[] = '(' . implode(' OR ', $kf) . ') ';
         } else {
             return -1;
         }
     }
     if ($filter['in_fav']) {
         $teams = new teams();
         if ($tt = $teams->teamsFavorites($uid, $error)) {
             foreach ($tt as $t) {
                 $favs[] = $t['uid'];
             }
             if ($favs) {
                 $filter_where[] = $DB->parse('s.uid IN (?l)', $favs);
             }
         }
     }
     $jstr_rating = 'INNER JOIN rating r ON r.user_id = s.uid';
     if ($filter['success_sbr'][0] == 1) {
         $filter_join['rating'] = $jstr_rating;
         for ($i = 1; $i < 4; $i++) {
             if ($filter['success_sbr'][$i] == 1) {
                 $s[] = $i;
             }
         }
         if ($s) {
             $filter_where[] = $DB->parse('r.rank IN (?l)', $s);
         }
         $filter_where[] = 'r.sbr_sum > 0';
     }
     if ($filter['is_preview']) {
         $filter_join['rating'] = $jstr_rating;
         $filter_where[] = 'r.o_wrk_factor_a > 0';
     }
     if ($filter['is_pro']) {
         $filter_where[] = 's.is_pro = true';
     }
     if ($filter['is_verify']) {
         $filter_where[] = 's.is_verify = true';
     }
     if ($filter['only_tu']) {
         $filter_where[] = ' s.uid IN (SELECT tservices.user_id FROM tservices WHERE tservices.active=true AND tservices.deleted=false) ';
     }
     if ($filter['sbr_is_positive']) {
         $filter_where[] = '(uc.paid_advices_cnt + uc.sbr_opi_plus + uc.tu_orders_plus + uc.projects_fb_plus) > 0';
     }
     if ($filter['sbr_not_negative']) {
         $filter_where[] = '(uc.sbr_opi_minus + uc.tu_orders_minus + uc.projects_fb_minus) = 0';
     }
     if ($filter['opi_is_positive']) {
         $filter_where[] = '(uc.ops_emp_plus + uc.ops_frl_plus) > 0';
     }
     if ($filter['opi_not_negative']) {
         $filter_where[] = '(uc.ops_emp_minus + uc.ops_frl_minus) = 0';
     }
     if ($filter['only_free']) {
         $filter_where[] = 's.status_type = 0';
     }
     if ($filter['in_office']) {
         $filter_where[] = 's.in_office = true';
     }
     if ($filter['wo_cost'] == 'f') {
         // hh
         $filter_where[] = 's.cost_month <> 0';
     }
     if ($filter['cost']) {
         foreach ($filter['cost'] as $k => $val) {
             if ($val['cost_from'] || $val['cost_to']) {
                 switch ($val['type_date']) {
                     default:
                     case 4:
                         if ($prof_id) {
                             $cf = 'pc.cost_hour';
                             $ct = 'pc.cost_type_hour';
                         } else {
                             $cf = 's.cost_hour';
                             $ct = 's.cost_type_hour';
                         }
                         break;
                     case 3:
                         $cf = 'pc.cost_from';
                         $ct = 'pc.cost_type';
                         break;
                     case 1:
                         $cf = 's.cost_month';
                         $ct = 's.cost_type_month';
                         break;
                     case 2:
                         $cf = 'pc.cost_1000';
                         $ct = 'pc.cost_type';
                         break;
                 }
                 $cr = (int) $val['cost_type'];
                 $cex = array(freelancer::USD => project_exrates::USD, freelancer::EUR => project_exrates::EUR, freelancer::RUR => project_exrates::RUR, freelancer::FM => project_exrates::FM);
                 if (($cost_from = (double) $val['cost_from']) < 0) {
                     $cost_from = 0;
                 }
                 if (($cost_to = (double) $val['cost_to']) < 0) {
                     $cost_to = 0;
                 }
                 if ($cost_to < $cost_from && $cost_to != 0) {
                     $cost_to = $cost_from;
                 }
                 if ($cost_to || $cost_from) {
                     $cost_sql = "";
                     for ($i = 0; $i < 4; $i++) {
                         $exfr = round($cost_from * $project_exRates[$cex[$cr] . $cex[$i]], 4);
                         $exto = round($cost_to * $project_exRates[$cex[$cr] . $cex[$i]], 4);
                         $cost_sql .= ($i ? ' OR ' : '') . "(COALESCE({$ct},0) = {$i} AND {$cf} >= {$exfr}" . ($cost_to ? " AND {$cf} <= {$exto}" : '') . ')';
                     }
                     if ($filter['wo_cost'] == 't') {
                         // hh
                         $cost_sql .= " OR {$cf} = 0";
                     }
                     $a_cost_sql[] = $cost_sql;
                 }
             }
         }
         if ($a_cost_sql) {
             $filter_where[] = '(' . implode(" OR ", $a_cost_sql) . ')';
         }
     }
     if ($filter['exp'][0] > 0 || $filter['exp'][1] > 0) {
         if ($filter['exp'][1] == 0 && $filter['exp'][0] > 0) {
             $filter_where[] = $DB->parse("s.exp >= ?", $filter['exp'][0]);
         } else {
             if ($filter['exp'][1] > 0 && $filter['exp'][0] == 0) {
                 $filter_where[] = $DB->parse("s.exp <= ?", $filter['exp'][1]);
             } else {
                 $filter_where[] = $DB->parse("s.exp >= ? AND s.exp <= ?", $filter['exp'][0], $filter['exp'][1]);
             }
         }
     }
     /* Не используется?
        if($filter['login']) {
            $filter_where[] = "(s.uname ILIKE '" . trim($filter['login']) . "' OR s.usurname ILIKE '" . trim($filter['login']) . "' OR s.login ILIKE '" . trim($filter['login']) . "')";
        }*/
     if ($filter['wo_age'] == 'f') {
         // hh
         $filter_where[] = "COALESCE(s.birthday, 'epoch') > '1910-01-01'";
     }
     if ($filter['age'][1] > 0 || $filter['age'][0] > 0) {
         $age_from = $filter['age'][0];
         $age_to = $filter['age'][1];
         $ccond = "AND s.birthday > '1910-01-01'";
         if ($filter['wo_age'] == 't') {
             // hh
             $ccond = "OR COALESCE(s.birthday, 'epoch') <= '1910-01-01'";
         }
         if ($age_to == 0 && $age_from > 0) {
             $filter_where[] = $DB->parse("extract('year' from age(s.birthday)) >= ?i {$ccond}", $age_from);
         } elseif ($age_to > 0 && $age_from == 0) {
             $filter_where[] = $DB->parse("extract('year' from age(s.birthday)) <= ?i {$ccond}", $age_to);
         } else {
             $filter_where[] = $DB->parse("(extract('year' from age(s.birthday)) BETWEEN ?i AND ?i) {$ccond}", $age_from, $age_to);
         }
     }
     $userIsAuth = $_SESSION["uid"];
     if ($cc = $filter['country']) {
         if (is_array($cc)) {
             $cc = implode(',', $cc);
         }
         $filter_where[] = "s.country IN ({$cc})";
         if (!$userIsAuth) {
             $filter_where[] = "position ('\"country\"' IN s.info_for_reg) = 0";
             /*смотрим в сериализованном массиве полей, которые не надо показывать неавторизованым, есть ли ключ country*/
         }
     }
     if ($cc = $filter['city']) {
         if (is_array($cc)) {
             $cc = implode(',', $cc);
         }
         $filter_where[] = "s.city IN ({$cc})";
         if (!$userIsAuth) {
             $filter_where[] = "position ('\"city\"' IN s.info_for_reg) = 0";
         }
     }
     if ($filter['sex']) {
         $fsex = $filter['sex'] == 2 ? 'TRUE' : 'FALSE';
         $filter_where[] = "s.sex = {$fsex}";
     }
     $filter_where = implode(' AND ', $filter_where);
     $filter_join = implode(' ', $filter_join);
     return array($filter_where, $filter_join);
 }
示例#3
0
 public function recalcCounters()
 {
     $sql = "SELECT COUNT(*) \n            FROM freelancer AS f \n            WHERE f.is_active AND f.is_banned = '0' \n                AND (f.cat_show = 't' OR f.is_pro = 'f') \n                AND f.last_time > now() - '6 months'::interval\n        ";
     $professions = new professions();
     $prof_groups = $professions->getProfGroupIds();
     foreach ($prof_groups as $group_id) {
         $profs_str = $professions->getProfIdForGroups($group_id, true);
         if ($profs_str) {
             $this->updateCounter($group_id, 0, $this->db->val($sql . " AND f.spec_orig IN ({$profs_str})"));
         }
     }
     $profs = $professions->getOriginProfsIds();
     foreach ($profs as $prof_id) {
         $this->updateCounter(0, $prof_id, $this->db->val($sql . ' AND f.spec_orig = ?i', $prof_id));
     }
     $this->updateCounter(0, 0, $this->db->val($sql));
 }
示例#4
0
 /**
  * Формирует SQL-условие по заданному фильтру (который у фрилансеров на главной и в меню "Проекты").
  *
  * @global $project_exRates Курс обмены валюты
  * 
  * @param array   $filter параметры фильтра. Если фильтр выключен можно передать NULL или в $filter['is_active'] задать false.
  * @param integer $kind   тип закладки проектов (@see new_projects::getProjects()), если находимся на главной странице.
  * @return string   SQL-условие для использования в запросе.
  */
 function createFilterSql($filter, $kind = NULL)
 {
     global $DB, $project_exRates;
     if (!$filter || $filter['active'] != 't') {
         return '';
     }
     $fSql = '';
     //Ислючаем из выборки перечисленные проекты
     if (isset($filter['not_project_ids']) && is_array($filter['not_project_ids'])) {
         $fSql .= $DB->parse(" AND p.id NOT IN(?l) ", $filter['not_project_ids']);
     }
     if ($filter['only_sbr'] == 't') {
         $fSql .= ' AND  p.prefer_sbr = true ';
     }
     if ($filter['urgent_only'] == 't') {
         $fSql .= ' AND  p.urgent = true ';
     }
     if ($filter['urgent'] == 't') {
         $fSql .= ' AND  p.urgent = true ';
     }
     if ($filter['pro_only'] == 't') {
         $fSql .= ' AND  p.pro_only = true ';
     }
     if ($filter['verify_only'] == 't') {
         $fSql .= ' AND  p.verify_only = true ';
     }
     if ($filter['less_offers'] == 't') {
         $fSql .= ' AND p.offers_count < 2 ';
     }
     //Только проекты с выбранным исполнителем
     if (isset($filter['hide_exec']) && $filter['hide_exec'] == 't') {
         $fSql .= ' AND (p.exec_id <= 0 OR p.exec_id IS NULL) ';
     }
     if (hasPermissions('projects')) {
         if ($filter['block_only'] == 't') {
             $fSql .= ' AND EXISTS (SELECT 1 FROM projects_blocked WHERE project_id=p.id) ';
         }
     }
     if ($kind != 1 && $kind != 2 && $kind != 7) {
         if (intval($filter['country'])) {
             $fSql .= 'AND (p.country=' . intval($filter['country']) . ' ';
             if (intval($filter['city'])) {
                 $fSql .= 'AND p.city=' . intval($filter['city']);
             }
             $fSql .= ') AND kind = 4 ';
         }
     }
     if ($filter['wo_cost'] == 'f') {
         $fSql .= 'AND p.cost > 0 ';
     }
     if ($filter['my_specs'] == 't' && $filter['user_specs']) {
         $profsWithMirrors = professions::GetMirroredProfs(implode(',', $filter['user_specs']));
         $fSql .= 'AND EXISTS (SELECT 1 from project_to_spec WHERE project_id = p.id AND subcategory_id IN (' . implode(',', $profsWithMirrors) . '))';
     } elseif ($filter['categories']) {
         $categories = array();
         for ($ci = 0; $ci < 2; $ci++) {
             if (sizeof($filter['categories'][$ci])) {
                 foreach ($filter['categories'][$ci] as $ckey => $cvalue) {
                     $categories[$ci][] = (int) $ckey;
                 }
             }
         }
         $fSql .= 'AND EXISTS (SELECT 1 from project_to_spec WHERE project_id = p.id AND (';
         $sProfCat = '';
         $sProfSubcat = '';
         // собираем подразделы выбранных разделов
         if (sizeof($categories[0])) {
             $sProfCat = professions::getProfIdForGroups($categories[0]);
         }
         // собираем выбранные подразделы
         if (sizeof($categories[1])) {
             $sProfSubcat = implode(',', $categories[1]);
         }
         // склеиваем и получаем все подразделы вместе с зеркалами
         $sProf = $sProfCat . ($sProfCat && $sProfSubcat ? ',' : '') . $sProfSubcat;
         $aProf = professions::GetMirroredProfs($sProf);
         $fSql .= 'subcategory_id in (' . implode(',', $aProf) . ') ';
         if (sizeof($categories[0])) {
             $fSql .= 'OR category_id IN (' . implode(',', $categories[0]) . ')';
         }
         $fSql .= ')) ';
     }
     if ($filter['keywords'] = trim($filter['keywords'])) {
         if (defined('FTS_PROJECTS') && FTS_PROJECTS) {
             if ($filter_keywords = $DB->parse('?ts', $filter['keywords'])) {
                 // При добавлении полей необходимо создать новый индекс вместо "ixts projects/name_descr".
                 $fSql .= "\n                      AND ( to_tsvector('pg_catalog.russian', COALESCE(p.name, '') || ' ' || COALESCE(p.descr, ''))\n                            @@ to_tsquery('pg_catalog.russian', {$filter_keywords}) )\n                    ";
             }
         } else {
             foreach (explode(',', $filter['keywords']) as $val) {
                 $val = trim(preg_replace('/([%_])/', '\\\\\\\\$1', htmlspecialchars($val, ENT_QUOTES, 'cp1251')));
                 if ($val) {
                     $filter_keywords[] = $val;
                 }
             }
             $fSql .= 'AND ( ';
             $fSql .= "(p.name ILIKE '%" . implode("%' OR p.name ILIKE '%", $filter_keywords) . "%') OR ";
             $fSql .= "(p.descr ILIKE '%" . implode("%' OR p.descr ILIKE '%", $filter_keywords) . "%') ";
             $fSql .= ') ';
         }
     }
     if ($filter['cost_from'] || $filter['cost_to']) {
         $cr = (int) $filter['currency'];
         $cex = array(2, 3, 4, 1);
         if (($cost_from = (double) $filter['cost_from']) < 0) {
             $cost_from = 0;
         }
         if (($cost_to = (double) $filter['cost_to']) < 0) {
             $cost_to = 0;
         }
         if ($cost_to < $cost_from && $cost_to != 0) {
             $cost_to = $cost_from;
         }
         if ($cost_to || $cost_from) {
             $fSql .= 'AND (';
             //##0028132
             /*
             $priceby = (int)$filter['priceby'];
             if($kind == 7) {
                 $priceby = NULL;
             }
             if($priceby) {
                 $fSql .= 'p.priceby = ' . $priceby . ' AND (';
             }
             */
             for ($i = 0; $i < 4; $i++) {
                 $exfr = round($cost_from * $project_exRates[$cex[$cr] . $cex[$i]], 4);
                 $exto = round($cost_to * $project_exRates[$cex[$cr] . $cex[$i]], 4);
                 $fSql .= ($i ? ' OR ' : '') . "(p.currency = {$i} AND p.cost >= {$exfr}" . ($cost_to ? " AND p.cost <= {$exto}" : '') . ')';
             }
             //##0028132
             /*
             if($priceby) {
                 $fSql .= ')';
             }
             */
             if ($filter['wo_cost'] == 't') {
                 $fSql .= ' OR p.cost = 0';
             }
             $fSql .= ')';
         }
     }
     if ($kind == 2 || $kind == 7) {
         if ($filter['konkurs_end_days_from'] !== null) {
             $fSql .= $DB->parse(' AND p.end_date::date - NOW()::date >= ? ', $filter['konkurs_end_days_from']);
         }
         if ($filter['konkurs_end_days_to'] !== null) {
             $fSql .= $DB->parse(' AND p.end_date::date - NOW()::date <= ? ', $filter['konkurs_end_days_to']);
         }
     }
     return $fSql;
 }
示例#5
0
 public function createSqlFilter($filter, $cl = 'WHERE')
 {
     if ($filter['categories']) {
         $categories = array();
         for ($ci = 0; $ci < 2; ++$ci) {
             if (sizeof($filter['categories'][$ci])) {
                 foreach ($filter['categories'][$ci] as $ckey => $cvalue) {
                     $categories[$ci][] = (int) $ckey;
                 }
             }
         }
         $fSql .= "{$cl} (";
         $sProfCat = '';
         $sProfSubcat = '';
         // собираем подразделы выбранных разделов
         if (sizeof($categories[0])) {
             $sProfCat = professions::getProfIdForGroups($categories[0]);
         }
         // собираем выбранные подразделы
         if (sizeof($categories[1])) {
             $sProfSubcat = implode(',', $categories[1]);
         }
         // склеиваем и получаем все подразделы вместе с зеркалами
         $sProf = $sProfCat . ($sProfCat && $sProfSubcat ? ',' : '') . $sProfSubcat;
         $aProf = professions::GetMirroredProfs($sProf);
         $fSql .= ' subcategory_id in (' . implode(',', $aProf) . ') ';
         if (sizeof($categories[0])) {
             $fSql .= 'OR category_id IN (' . implode(',', $categories[0]) . ')';
         }
         $fSql .= ') ';
     }
     if ($filter['only_my_offs'] == 't') {
         $fSql .= ' AND fo.user_id = ' . get_uid(0);
     }
     return $fSql;
 }
 public function setSelectFilter($filter)
 {
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/professions.php';
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/project_exrates.php';
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/teams.php';
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/freelancer.php';
     $project_exRates = project_exrates::GetAll();
     $set_select[] = '*';
     // Разделы/Подразделы
     if ($filter['prof']) {
         if (count($filter['prof'][0]) > 0) {
             $p1 = professions::getProfIdForGroups(array_keys($filter['prof'][0]), true);
         }
         if (count($filter['prof'][1]) > 0) {
             $p2 = professions::GetProfessionOrigin(implode(',', array_keys($filter['prof'][1])));
         }
         $specs = explode(',', ($p2 ? $p2 : '') . ($p1 && $p2 ? ', ' : '') . ($p1 ? $p1 : ''));
         $this->_engine->setFilter('specs', $specs);
         $this->_sortby = 'is_pro DESC, spec_origin IN (' . implode(',', $specs) . ') rating DESC, @id';
     }
     //Стоимость
     if ($filter['cost']) {
         foreach ($filter['cost'] as $val) {
             if ($val['cost_from'] || $val['cost_to']) {
                 switch ($val['type_date']) {
                     default:
                     case 4:
                         if ($prof_id) {
                             $cf = 'pcost_hour';
                             $ct = 'pcost_type_hour';
                         } else {
                             $cf = 'cost_hour';
                             $ct = 'cost_type_hour';
                         }
                         break;
                     case 3:
                         $cf = 'cost_from';
                         $ct = 'cost_type';
                         break;
                     case 1:
                         $cf = 'cost_month';
                         $ct = 'cost_type_month';
                         break;
                     case 2:
                         $cf = 'cost_1000';
                         $ct = 'cost_type';
                         break;
                 }
                 $cr = (int) $val['cost_type'];
                 $cex = array(freelancer::USD => project_exrates::USD, freelancer::EUR => project_exrates::EUR, freelancer::RUR => project_exrates::RUR, freelancer::FM => project_exrates::FM);
                 if (($cost_from = (double) $val['cost_from']) < 0) {
                     $cost_from = 0;
                 }
                 if (($cost_to = (double) $val['cost_to']) < 0) {
                     $cost_to = 0;
                 }
                 if ($cost_to < $cost_from && $cost_to != 0) {
                     $cost_to = $cost_from;
                 }
                 if ($cost_to || $cost_from) {
                     $cost_sql = '';
                     for ($i = 0; $i < 4; ++$i) {
                         $exfr = round($cost_from * $project_exRates[$cex[$cr] . $cex[$i]], 4);
                         $exto = round($cost_to * $project_exRates[$cex[$cr] . $cex[$i]], 4);
                         $cost[] = "({$ct} = {$i} AND {$cf} >= {$exfr}" . ($cost_to ? " AND {$cf} <= {$exto}" : '') . ')';
                     }
                     $select[] = implode(' OR ', $cost);
                 }
             }
         }
         if ($select) {
             $set_select[] = 'IF( ( ' . implode(' OR ', $select) . ' ), 1, 0) as cost_filter';
             unset($select);
             $this->_engine->setFilter('cost_filter', array(1));
         }
     }
     // Опыт работы
     if ($filter['exp'][0] > 0 || $filter['exp'][1] > 0) {
         if ($filter['exp'][1] == 0 && $filter['exp'][0] > 0) {
             $select[] = "( exp >= {$filter['exp'][0]} )";
         } elseif ($filter['exp'][1] > 0 && $filter['exp'][0] == 0) {
             $select[] = "( exp <= {$filter['exp'][1]} )";
         } else {
             $select[] = "( exp >= {$filter['exp'][0]} AND exp <= {$filter['exp'][1]} )";
         }
         $set_select[] = 'IF( ( ' . implode(' OR ', $select) . ' ), 1, 0) as exp_filter';
         unset($select);
         $this->_engine->setFilter('exp_filter', array(1));
     }
     //Возраст
     if ($filter['age'][1] > 0 || $filter['age'][0] > 0) {
         $age_from = $filter['age'][0];
         $age_to = $filter['age'][1];
         if ($age_to == 0 && $age_from > 0) {
             $select[] = "( age >= {$age_from} )";
         } elseif ($age_to > 0 && $age_from == 0) {
             $select[] = "( age <= {$age_to} )";
         } else {
             $select[] = "( age >= {$age_from} AND age <= {$age_to} )";
         }
         $set_select[] = 'IF( ( ' . implode(' OR ', $select) . ' ), 1, 0) as age_filter';
         unset($select);
         $this->_engine->setFilter('age_filter', array(1));
     }
     // Местоположение
     if ($filter['country']) {
         $this->_engine->setFilter('country', array($filter['country']));
     }
     if ($filter['city']) {
         $this->_engine->setFilter('city', array($filter['city']));
     }
     // Ищет работу в офисе
     if ($filter['in_office']) {
         $this->_engine->setFilter('in_office', array(1));
     }
     // У меня в избранных
     if ($filter['in_fav']) {
         $teams = new teams();
         if ($tt = $teams->teamsFavorites($uid, $error)) {
             foreach ($tt as $t) {
                 $select[] = " ( uid = {$t['uid']} ) ";
             }
             $set_select[] = 'IF(( ' . implode(' OR ', $select) . ' ), 1, 0) as is_fav';
             unset($select);
             $this->_engine->setFilter('is_fav', array(1));
         }
     }
     //С PRO аккаунтом
     if ($filter['is_pro']) {
         $this->_engine->setFilter('is_pro', array(1));
     }
     //С положительными рекомендациями
     if ($filter['sbr_is_positive']) {
         $select[] = '( sbr_opi_plus > 0 )';
         $set_select[] = 'IF(( ' . implode(' OR ', $select) . ' ), 1, 0) as sbr_positive_filter';
         unset($select);
         $this->_engine->setFilter('sbr_positive_filter', array(1));
     }
     //Без отрицательных рекомендаций
     if ($filter['sbr_not_negative']) {
         $select[] = '( sbr_opi_minus = 0 )';
         $set_select[] = 'IF(( ' . implode(' OR ', $select) . ' ), 1, 0) as sbr_not_negative_filter';
         unset($select);
         $this->_engine->setFilter('sbr_not_negative_filter', array(1));
     }
     //С положительными мнениями
     /*if($filter['opi_is_positive']) {
           $select[] = '( ops_emp_plus > 0 )';
           
           $set_select[] = "IF(( ".implode(" OR ", $select)." ), 1, 0) as opi_positive_filter";
           unset($select);
           
           $this->_engine->setFilter("opi_positive_filter", array(1));
       }
       
       //Без отрицательных мнений
       if($filter['opi_not_negative']) {
           $select[] = '( ops_emp_minus = 0 )';
           
           $set_select[] = "IF(( ".implode(" OR ", $select)." ), 1, 0) as opi_not_negative_filter";
           unset($select);
           
           $this->_engine->setFilter("opi_not_negative_filter", array(1));
       }*/
     // Только с примерами работ
     if ($filter['is_preview']) {
         $select[] = '( o_wrk_factor_a > 0 )';
         $set_select[] = 'IF(( ' . implode(' OR ', $select) . ' ), 1, 0) as preview_filter';
         unset($select);
         $this->_engine->setFilter('preview_filter', array(1));
     }
     // Только свободные
     if ($filter['only_free']) {
         $select[] = '( status_type = 0)';
         $set_select[] = 'IF(( ' . implode(' OR ', $select) . ' ), 1, 0) as onlyfree_filter';
         unset($select);
         $this->_engine->setFilter('onlyfree_filter', array(1));
     }
     //С успешным СБР
     if ($filter['success_sbr'][0] == 1) {
         $select[] = '( sbr_sum > 0 )';
         for ($i = 1; $i < 4; ++$i) {
             if ($filter['success_sbr'][$i] == 1) {
                 $rank[] = "( rank = {$i} )";
             }
         }
         if ($rank) {
             $select[] = '( ' . implode(' OR ', $rank) . ' )';
         }
         $set_select[] = 'IF(( ' . implode(' AND ', $select) . ' ), 1, 0) as sbr_rank_filter';
         unset($select);
         $this->_engine->setFilter('sbr_rank_filter', array(1));
     }
     if ($set_select) {
         $this->_engine->setSelect(implode(', ', $set_select));
     }
 }