<?php

require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/stdf.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/project_exrates.php";
project_exrates::updateCBRates();
echo 'OK';
Esempio n. 2
0
 /**
  * Возвращает страницу каталога фрилансеров со всеми необходимыми причиндалами. ВЕДУТСЯ РАБОТЫ!
  *
  * @param integer prof_id     ид. профессии (раздела каталога). Если 0, то выводим фрилансеров из общего каталога.
  * @param integer uid         ид. юзера, просматривающего каталог.
  * @param integer count       количество всего фрилансеров в данном разделе каталога.
  * @param integer size        количество фрилансеров на данной странице каталога.
  * @param array   works       массив, индексированный ид. фрилансеров, содержащий массив из трех первых работ данного фрилансера в данном разделе.
  * @param integer limit       сколько фрилансеров на одной странице.
  * @param integer offset      OFFSET.
  * @param string  order       тип сортировки (см. использование).
  * @param int     direction   порядок сортировки. 0 -- по убывающей, не 0 -- по возрастающей.
  * @param int     favorite    флаг -- показывать ли только избранных.
  * @param array   filter      массив с параметрами фильтра или NULL -- фильтр не применен.
  *
  * @return array  массив с фрилансерами.
  */
 function old_getCatalog($prof_id, $uid, &$count, &$size, &$works, $limit, $offset, $order = "general", $direction = 0, $favorite = 0, $filter = NULL)
 {
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/projects.php";
     global $DB;
     $project_exRates = project_exrates::GetAll();
     $dir_sql = !$direction ? 'DESC' : 'ASC';
     $cost_fm = '';
     $fu_table = self::$fu_table;
     $fprms = self::createCatalogFilterSql($filter, $prof_id);
     if ($fprms == -1) {
         return null;
     }
     list($filter_where, $filter_join) = $fprms;
     if ($filter_where) {
         $filter_where = ' AND ' . $filter_where;
     }
     if (!$filter_where && intval($_SESSION['region_filter_country'])) {
         $filter_where = 'AND s.country IN (' . intval($_SESSION['region_filter_country']) . ')' . (intval($_SESSION['region_filter_city']) != 0 ? 'AND s.city IN (' . intval($_SESSION['region_filter_city']) . ') ' : '');
     }
     $size = 0;
     if ($prof_id) {
         $or_prof = professions::GetProfessionOrigin($prof_id);
         $ord_spec = ', s.its_his_main_spec DESC';
     }
     // Список специализаций для фильтрации в портфолио
     $specs_list = '';
     switch ($order) {
         case "opinions":
             $uc_side = 'INNER';
             $order = ", osum {$dir_sql}, s.rating {$dir_sql}";
             break;
         case "sbr":
             $uc_side = 'INNER';
             $order = ", ssum {$dir_sql}, s.rating {$dir_sql}";
             break;
         case "cost_hour":
             $order = "{$ord_spec}, cost_hour_is_0, cost_fm {$dir_sql}, s.rating {$dir_sql}";
             $orderCf = 'pc.cost_hour';
             $orderCt = 'pc.cost_type_hour';
             break;
         case "cost_month":
             $order = "{$ord_spec}, COALESCE(s.cost_month,0)=0, cost_fm {$dir_sql}, s.rating {$dir_sql}";
             $orderCf = 's.cost_month';
             $orderCt = 's.cost_type_month';
             break;
         case "cost_proj":
             $order = "{$ord_spec}, COALESCE(cost_from,0)=0, cost_fm {$dir_sql}, s.rating {$dir_sql}";
             $orderCf = 'pc.cost_from';
             $orderCt = 'pc.cost_type';
             break;
         case "cost_1000":
             $order = "{$ord_spec}, COALESCE(cost_1000,0)=0, cost_fm {$dir_sql}, s.rating {$dir_sql}";
             $orderCf = 'pc.cost_1000';
             $orderCt = 'pc.cost_type';
             break;
         case "general":
         default:
             $order = "{$ord_spec}, rating_get(s.rating, s.is_pro, s.is_verify, s.is_profi) {$dir_sql}";
             break;
     }
     if ($orderCf && $orderCt) {
         $cost_fm = ",\n            CASE WHEN COALESCE({$orderCt},0) = 0 THEN {$orderCf} * {$project_exRates[24]}\n                 WHEN {$orderCt} = 1 THEN {$orderCf} * {$project_exRates[34]}\n                 WHEN {$orderCt} = 2 THEN {$orderCf} * {$project_exRates[44]}\n                 WHEN {$orderCt} = 3 THEN {$orderCf} * {$project_exRates[14]}\n                 ELSE {$orderCf}\n             END as cost_fm ";
     }
     if (!$uc_side) {
         $uc_side = strpos($filter_where, 'uc.') !== false ? 'INNER' : 'OUTER';
     }
     $uc_cols[$uc_side] = "\n          , uc.ops_emp_plus + uc.ops_frl_plus as sg, uc.ops_emp_minus + uc.ops_frl_minus as sl, uc.ops_emp_null + uc.ops_frl_null as se,\n          zin(uc.paid_advices_cnt + uc.sbr_opi_plus + uc.tu_orders_plus + uc.projects_fb_plus)-zin(uc.sbr_opi_minus + uc.tu_orders_minus + uc.projects_fb_minus) as ssum, \n          zin(uc.ops_emp_plus)-zin(uc.ops_emp_minus) as osum,\n          (uc.paid_advices_cnt + uc.sbr_opi_plus + uc.tu_orders_plus + uc.projects_fb_plus) AS total_opi_plus,\n          (uc.sbr_opi_null) AS total_opi_null,\n          (uc.sbr_opi_minus + uc.tu_orders_minus + uc.projects_fb_minus) AS total_opi_minus,\n          uc.*\n        ";
     $uc_join[$uc_side] = "LEFT JOIN users_counters uc ON uc.user_id = s.uid";
     $fb_cols = "\n        ,   (fb.id > 0)::boolean as is_binded\n        ";
     if ($prof_id) {
         $fb_join = "LEFT JOIN freelancer_binds fb ON fb.user_id = s.uid AND fb.prof_id = '{$or_prof}' AND fb.status = TRUE AND fb.date_stop > NOW()";
         $pc_side = strpos($filter_where, 'pc.') !== false || strpos($cost_fm, 'pc.') !== false ? 'INNER' : 'OUTER';
         $pc_cols[$pc_side] = "\n              , (COALESCE(pc.cost_hour, 0) = 0) as cost_hour_is_0, pc.cost_hour, pc.cost_type_hour, pc.cost_from, pc.cost_type, pc.cost_1000\n              \n            ";
         $pc_join[$pc_side] = "LEFT JOIN portf_choise pc ON pc.prof_id = '{$or_prof}' AND pc.user_id = s.uid";
         $fu = "(\n              SELECT *, true as its_his_main_spec FROM {$fu_table} WHERE spec_orig = '{$or_prof}'\n              UNION ALL\n              SELECT {$fu_table}.*, false FROM {$fu_table} INNER JOIN spec_add_choise sp ON sp.user_id = {$fu_table}.uid AND sp.prof_id = '{$or_prof}' WHERE {$fu_table}.is_pro = true\n              UNION ALL\n              SELECT {$fu_table}.*, false FROM {$fu_table} INNER JOIN spec_paid_choise pc ON pc.user_id = {$fu_table}.uid AND pc.prof_id = '{$or_prof}' AND pc.paid_to > NOW()\n            )";
         $sql = "\n              SELECT s.*,\n                     city.city_name as str_city, country.country_name as str_country, sbr_meta.completed_cnt,\n                     rating_get(s.rating, s.is_pro, s.is_verify, s.is_profi) as t_rating\n                     {$uc_cols['OUTER']}\n                     {$pc_cols['OUTER']}\n                     {$fb_cols}\n                FROM (\n                  SELECT s.* {$cost_fm}, s.cost_hour as frl_cost_hour, s.cost_type_hour as frl_cost_type_hour\n                        {$uc_cols['INNER']}\n                        {$pc_cols['INNER']}\n                    FROM {$fu} as s\n                  {$uc_join['INNER']}\n                  {$pc_join['INNER']}\n                  {$filter_join}\n                   {$fb_join}\n                   WHERE s.is_banned = '0' {$filter_where} AND ( s.cat_show = 't' OR s.is_pro = 'f' ) \n                   ORDER BY (fb.id IS NULL)::boolean ASC, fb.date_start DESC, s.is_pro DESC {$order}, s.uid\n                   LIMIT {$limit} OFFSET {$offset}                 \n                ) as s\n              {$uc_join['OUTER']}\n              {$pc_join['OUTER']}\n              {$fb_join}\n              LEFT JOIN\n              \tcountry \n                  ON country.id = s.country\n              LEFT JOIN\n              \tcity \n                  ON city.id = s.city\n              LEFT JOIN\n              \tsbr_meta \n                  ON sbr_meta.user_id = s.uid\n              ORDER BY (fb.id IS NULL)::boolean ASC, fb.date_start DESC, s.is_pro DESC {$order}, s.uid\n            ";
         $countSql = "SELECT COUNT(s.uid) as count, SUM(s.is_pro::int) as payed FROM {$fu} as s {$filter_join} " . ($filter_where ? $uc_join['INNER'] . ' ' . $pc_join['INNER'] : '') . " WHERE s.is_banned = '0' {$filter_where}";
     } else {
         // Общий каталог.
         // В отличие от разделов тут жесткая связка с posrtf_choise -- это одно из условий нахождения в общем каталоге.
         //переменные для добавления проверки по дополнительным специальностям
         $join_add_spec = '';
         $prof_choise_condition = "pc.prof_id = s.spec_orig";
         $pattern = "#(s.spec_orig\\s+(IN\\s+\\([\\d,]+\\)))#";
         $order_add_spec = "";
         $order_add_spec_field = "";
         if (preg_match($pattern, $filter_where, $m)) {
             $filter_where = preg_replace($pattern, "(\n                \$1  \n                OR (sa.prof_id \$2 AND s.is_pro = 't' ) -- Только у ПРО учитываем ДОП специализацию, тк отменили платные специализации\n                OR (sp.prof_id \$2  )\n                    )", $filter_where);
             $join_add_spec = "LEFT JOIN \n                   spec_add_choise sa\n                     ON  sa.user_id = s.uid\n                     \n                  LEFT JOIN \n                    spec_paid_choise sp\n                     ON  sp.user_id = s.uid";
             $prof_choise_condition = "(\n                    pc.prof_id = s.spec_orig\n                      OR pc.prof_id = sa.prof_id\n                      OR pc.prof_id = sp.prof_id\n                      )";
             //$order_add_spec = "aso DESC, ";
             $order_add_spec_field = "CAST(s.spec_orig {$m[2]} AS integer) AS aso, ";
         }
         $distinct = array_map('trim', array_filter(explode(',', str_replace(array('DESC', 'ASC', 'descr', 'asc'), '', $order))));
         $distinct = $distinct ? implode(", ", $distinct) . "," : "";
         // Сортировка фрилансеров внутри специализаии верхнего уровня по подуровням
         $spec_case_order = '';
         if (isset($m[2]) && $m[2]) {
             $spec_case_order = ", CASE WHEN s.spec_orig {$m[2]} THEN 1 ELSE 2 END";
             $specs_list = "p.prof_id {$m[2]}";
         }
         $fb_on_prof = 0;
         if ($filter['prof']) {
             if (count($filter['prof'][0]) > 0) {
                 $group_ids = array_keys($filter['prof'][0]);
                 $fb_on_prof = $group_ids[0];
             }
         }
         $fb_join = "LEFT JOIN freelancer_binds fb ON fb.user_id = s.uid AND fb.prof_id = {$fb_on_prof} AND fb.is_spec = FALSE AND fb.status = TRUE AND fb.date_stop > NOW()";
         $sql = "\n                    SELECT s.*,\n                     city.city_name as str_city, country.country_name as str_country, sbr_meta.completed_cnt,\n                     p.name as profname, p.is_text,\n                     rating_get(s.rating, s.is_pro, s.is_verify, s.is_profi) as t_rating\n                     {$uc_cols['OUTER']}\n                     {$fb_cols}\n                FROM (\n                \tSELECT s.* FROM (\n                          SELECT  DISTINCT ON (s.is_pro, {$distinct} s.uid) s.*, s.cost_hour as frl_cost_hour, s.cost_type_hour as frl_cost_type_hour, {$order_add_spec_field}\n                                (COALESCE(pc.cost_hour, 0) = 0) as cost_hour_is_0, pc.cost_hour, pc.cost_from, pc.cost_type, pc.cost_1000, pc.cost_type_hour as pc_cost_type_hour\n                                {$cost_fm}\n                                {$uc_cols['INNER']}\n                            FROM {$fu_table} s\n                          {$join_add_spec}\n                          {$uc_join['INNER']}\n                          INNER JOIN\n                            portf_choise pc\n                              ON {$prof_choise_condition}\n                             AND pc.user_id = s.uid\n                          {$filter_join}\n                           WHERE s.is_banned = '0' {$filter_where}  AND ( s.cat_show = 't' OR s.is_pro = 'f' )\n                        ) as s\n                    ) as s \n              {$uc_join['OUTER']}\n              {$fb_join}\n              LEFT JOIN\n                professions p\n                  ON p.id = s.spec\n              LEFT JOIN\n              \tcountry \n                  ON country.id = s.country\n              LEFT JOIN\n              \tsbr_meta \n                  ON sbr_meta.user_id = s.uid\n              LEFT JOIN\n              \tcity \n                  ON city.id = s.city\n               ORDER BY (fb.id IS NULL)::boolean ASC, fb.date_start DESC, s.is_pro DESC {$spec_case_order} {$order}, {$order_add_spec} s.uid\n               LIMIT {$limit} OFFSET {$offset}\n            ";
         $countSql = self::_createMainCountSql($filter_where, $filter_join, $join_add_spec);
     }
     if (!$filter_where) {
         $memBuff = new memBuff();
         $DB->setTimeout(90);
         $frls = $memBuff->getSql($error, $sql, self::CATALOG_MEM_LIFE);
         $DB->setTimeout();
         if ($error || !$frls) {
             return NULL;
         }
         if (!$prof_id && !$offset && !$memBuff->getBWasMqUsed()) {
             professions::RecalcCatalogPositions();
         }
         $DB->setTimeout(90);
         $count_arr = $memBuff->getSql($error, $countSql, self::CATALOG_MEM_LIFE);
         $DB->setTimeout();
         $count = $count_arr[0]['count'];
         $size = sizeof($frls);
         if ($prof_id && !$memBuff->getSqlBWasMqUsed && !$filter_where) {
             professions::UpdateProfessionCount($or_prof, $count, $count_arr[0]['payed']);
         }
     } else {
         $DB->setTimeout(90);
         $frls = $DB->rows($sql);
         $DB->setTimeout();
         $error = $DB->error;
         if ($error || !$frls) {
             return NULL;
         }
         $DB->setTimeout(90);
         $count_arr = $DB->rows($countSql);
         //$memBuff->getSql($error, $countSql, 1800);
         $DB->setTimeout();
         $count = $count_arr[0]['count'];
         $size = sizeof($frls);
         //@todo: это никогда не срабатывает чтоли?
         if ($prof_id && !$filter_where) {
             professions::UpdateProfessionCount($or_prof, $count, $count_arr[0]['payed']);
         }
     }
     foreach ($frls as $row) {
         $frl_ids[] = $row['uid'];
     }
     $join_blocked = ' LEFT JOIN portfolio_blocked pb ON p.id = pb.src_id ';
     $where_blocked = ' AND pb.src_id IS NULL ';
     $sql = "SELECT p.id, p.user_id, p.name, p.descr, p.pict, p.prev_pict, p.show_preview, p.norder, p.prev_type, p.is_video\n               FROM portfolio p\n             INNER JOIN\n               portf_choise pc\n                 ON pc.user_id = p.user_id\n                AND pc.prof_id = p.prof_id \n             " . ($prof_id ? '' : 'INNER JOIN freelancer f ON f.uid = p.user_id') . "\n             {$join_blocked} \n              WHERE p.user_id IN (" . implode(',', $frl_ids) . ")\n        ";
     if ($specs_list) {
         $sql .= " AND {$specs_list}";
     } else {
         $sql .= " AND p.prof_id = " . ($prof_id ? "'{$or_prof}'" : 'f.spec_orig');
     }
     $sql .= " AND p.first3 = true  {$where_blocked} ORDER BY p.user_id, p.norder";
     if (!$filter_where) {
         if ($ret = $memBuff->getSql($error, $sql, 600, true)) {
             foreach ($ret as $row) {
                 $works[$row['user_id']][] = $row;
             }
         }
     } else {
         $ret = $DB->rows($sql);
         if ($ret) {
             foreach ($ret as $row) {
                 $works[$row['user_id']][] = $row;
             }
         }
     }
     return $frls;
 }
Esempio n. 3
0
        }
        if (!$error) {
            for ($i = 1; $i <= $ex_cnt; $i++) {
                @($pex[$i . '1'] = 1 / $pex['1' . $i]);
                $pex[$i . $i] = 1;
            }
            for ($i = 1; $i <= $ex_cnt; $i++) {
                for ($j = 1; $j <= $ex_cnt; $j++) {
                    $pex[$i . $j] = $pex[$i . $ri] / $pex[$j . $ri];
                }
            }
            if (!project_exrates::BatchUpdate($pex)) {
                $error = 'Пересчет не выполнен. Неизвестная ошибка.';
            }
        }
        if (!$error) {
            header("Location: /siteadmin/projects/?page=exrates&result=success");
            exit;
        }
        break;
}
$pex = project_exrates::GetAll(false);
$content = "../content.php";
$js_file = array('calendar.js');
$css_file = array('calendar.css', 'nav.css');
//$inner_page = trim($_GET['page']);
$inner_page = "index";
$inner_page = "inner_" . $inner_page . ".php";
$header = $rpath . "header.php";
$footer = $rpath . "footer.html";
include $rpath . "template.php";
Esempio n. 4
0
 /**
  * Получение списка предложений по конкретному проекту.
  *
  * @param integer $count    возвращает количество предложений
  * @param integer $prj_id   id проекта
  * @param string  $show_all признак отображения всех (true) или только открытых (false) предложений проекта
  * @param string  $sort     сортировка списка предложений
  * @param string  $type     выбор предложений одного типа ('o' - все, 'c' - выбранных в кандидаты, 'r' - отказанных, 'nor' - все кроме отказавшихся, 'i' - исполнитель)
  *
  * @return array список предложений
  */
 public function GetPrjOffers(&$count, $prj_id, $limit, $offset = 0, $user_id = 0, $show_all = false, $sort = 'date', $type = 'a')
 {
     global $DB;
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/teams.php';
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/notes.php';
     $user_id = intval($user_id);
     $limit = $limit == 'ALL' ? $limit : intval($limit);
     $offset = intval($offset);
     $limit_str = " LIMIT {$limit} OFFSET {$offset}";
     $bPermissions = hasPermissions('projects');
     // исключаем заблокированные предложения
     $sel_blocked = ', pb.reason as blocked_reason, pb.blocked_time, COALESCE(pb.src_id::boolean, false) as is_blocked';
     $join_blocked = 'LEFT JOIN projects_offers_blocked pb ON po.id = pb.src_id ';
     if ($bPermissions) {
         $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 ';
         $where_blocked = '';
         $and_blocked = '';
     } else {
         $where_blocked = " (po.user_id = {$user_id} OR pb.src_id IS NULL) ";
         $and_blocked = ' AND ' . $where_blocked;
     }
     //@todo: Рекомендуется вынести completed_cnt в users_counters таблицу и с ней соединяться
     //тем более, что в ней уже есть кол-во по новой БС reserves_completed_cnt
     //нужно добавить поле по старой БС и пересчитать туда
     if ($type == 'i') {
         $sql = "SELECT\n          po.*,\n          fl.uid, fl.login, fl.uname, fl.usurname, fl.photo, fl.photosm, fl.spec, fl.is_pro, fl.is_team, fl.is_pro_test, fl.is_profi, uc.ops_frl_plus as ops_plus, uc.ops_frl_null as ops_null, uc.ops_frl_minus as ops_minus, fl.role, fl.warn, fl.is_banned, fl.ban_where, rating_get(fl.rating, fl.is_pro, fl.is_verify, fl.is_profi) as rating, fl.is_verify, fl.reg_date, fl.modified_time, fl.photo_modified_time,\n          p.name AS spec_name,\n          cr.country_name,\n          ct.city_name, \n          COALESCE(sbr_meta.completed_cnt, 0) + COALESCE(uc.reserves_completed_cnt, 0) AS completed_cnt, -- старые БС + новые БС\n          uc.ops_emp_plus + uc.ops_frl_plus as ops_all_plus, uc.ops_emp_null + uc.ops_frl_null as ops_all_null, uc.ops_emp_minus + uc.ops_frl_minus as ops_all_minus,\n          uc.ops_emp_plus, uc.ops_emp_null, uc.ops_emp_minus,\n          uc.sbr_opi_plus, uc.sbr_opi_null, uc.sbr_opi_minus,\n          uc.paid_advices_cnt + uc.sbr_opi_plus + uc.ops_emp_plus + uc.tu_orders_plus + uc.projects_fb_plus as opinions_plus,\n          uc.sbr_opi_minus + uc.ops_emp_minus + uc.tu_orders_minus + uc.projects_fb_minus as opinions_minus\n          {$sel_blocked} \n          FROM (SELECT por.*, exec_id, pr.user_id as p_user_id FROM projects AS pr\n          LEFT JOIN projects_offers as por ON por.project_id=pr.id AND (pr.exec_id =por.user_id)\n          WHERE  pr.id = '{$prj_id}' AND (por.user_id > 0)" . ($show_all ? '' : " AND (por.only_4_cust='f')") . ') AS po
       INNER JOIN freelancer as fl ON (po.exec_id=fl.uid' . ($bPermissions ? '' : ' AND fl.is_banned::integer = 0') . ")\n          {$join_blocked} \n          LEFT JOIN professions p ON p.id=fl.spec\n          LEFT JOIN users_counters uc ON uc.user_id = fl.uid\n          LEFT JOIN sbr_meta ON sbr_meta.user_id = fl.uid -- старые БС\n          LEFT JOIN country cr ON cr.id=fl.country\n          LEFT JOIN city ct ON ct.id=fl.city\n          " . ($user_id == 0 ? "WHERE {$where_blocked}" : 'WHERE (fl.uid<>' . $user_id . ") {$and_blocked}");
         $ret = $DB->rows($sql);
         $error = $DB->error;
         if ($error) {
             $error = parse_db_error($error);
         } else {
             if ($ret) {
                 foreach ($ret as &$value) {
                     // Выбираем вложения.
                     if ($value['id']) {
                         $sql = 'SELECT a.id, a.prev_pict as prev, a.pict ' . 'FROM projects_offers_attach AS a ' . 'WHERE a.offer_id= ?i ';
                         $value['attach'] = $DB->rows($sql, $value['id']);
                     }
                 }
             }
         }
     } else {
         switch ($sort) {
             default:
             case 'date':
                 $order = ' ORDER BY (fl.is_verify AND fl.is_pro) DESC, fl.is_pro DESC, fl.is_verify DESC, post_date DESC';
                 break;
             case 'rating':
                 $order = ' ORDER BY rating DESC, fl.is_pro DESC, post_date DESC';
                 break;
             case 'opinions':
                 $order = ' ORDER BY ssum DESC, fl.is_pro DESC, post_date DESC';
                 break;
             case 'time':
                 $order = ' ORDER BY (((time_from = 0) OR (time_from IS NULL)) AND ((time_to = 0) OR (time_to IS NULL))) ASC, time_from_days ASC, time_to_days ASC, is_pro DESC, post_date DESC';
                 break;
             case 'cost':
                 $order = ' ORDER BY (((cost_from = 0) OR (cost_from IS NULL)) AND ((cost_to = 0) OR (cost_to IS NULL))) ASC, usd_cost_from DESC, usd_cost_to DESC, is_pro DESC, post_date DESC';
                 break;
         }
         switch ($type) {
             default:
             case 'a':
                 $filter = '';
                 break;
             case 'o':
                 $filter = ' AND NOT po.selected AND NOT po.refused AND NOT po.frl_refused AND COALESCE(pr.exec_id,0)<>fl.uid';
                 break;
             case 'c':
                 $filter = ' AND po.selected';
                 break;
             case 'r':
                 $filter = ' AND po.refused';
                 break;
             case 'nor':
                 $filter = ' AND NOT po.frl_refused';
                 break;
             case 'fr':
                 $filter = ' AND po.frl_refused';
                 break;
         }
         require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/project_exrates.php';
         $project_exRates = project_exrates::GetAll();
         $sql = "SELECT\n          CASE po.cost_type\n            WHEN 0 THEN po.cost_from\n            WHEN 1 THEN po.cost_from*{$project_exRates[32]}\n            WHEN 2 THEN po.cost_from*{$project_exRates[42]}\n            WHEN 3 THEN po.cost_from*{$project_exRates[12]}\n          END as usd_cost_from,\n          CASE po.cost_type\n            WHEN 0 THEN po.cost_to\n            WHEN 1 THEN po.cost_to*{$project_exRates[32]}\n            WHEN 2 THEN po.cost_to*{$project_exRates[42]}\n            WHEN 3 THEN po.cost_to*{$project_exRates[12]}\n          END as usd_cost_to,\n\n          CASE po.time_type\n            WHEN 0 THEN po.time_from\n            WHEN 1 THEN po.time_from * 30\n            WHEN 2 THEN po.time_from * 356\n            ELSE po.time_from\n          END as time_from_days,\n          CASE po.time_type\n            WHEN 0 THEN po.time_to\n            WHEN 1 THEN po.time_to * 30\n            WHEN 2 THEN po.time_to * 356\n            ELSE po.time_to\n          END as time_to_days,\n          po.*, pr.user_id AS p_user_id,\n          fl.uid, fl.login, fl.uname, fl.usurname, fl.photo, fl.photosm, fl.spec, fl.is_profi, fl.is_pro, fl.is_team, fl.is_pro_test, \n          uc.ops_frl_plus as ops_plus, \n          uc.ops_frl_null as ops_null, \n          uc.ops_frl_minus as ops_minus, \n          fl.role, fl.warn, fl.is_banned, fl.ban_where, \n          rating_get(fl.rating, fl.is_pro, fl.is_verify, fl.is_profi) as rating, \n          zin(uc.ops_emp_plus) + zin(uc.sbr_opi_plus) - zin(uc.ops_emp_minus) - zin(uc.sbr_opi_minus) as ssum, \n          fl.is_verify, fl.reg_date, fl.modified_time, fl.photo_modified_time,\n          p.name AS spec_name,\n          cr.country_name,\n          COALESCE(sbr_meta.completed_cnt, 0) + COALESCE(uc.reserves_completed_cnt, 0) AS completed_cnt, -- старые БС + новые БС\n          ct.city_name,\n          uc.ops_emp_plus + uc.ops_frl_plus as ops_all_plus, uc.ops_emp_null + uc.ops_frl_null as ops_all_null, uc.ops_emp_minus + uc.ops_frl_minus as ops_all_minus,\n          uc.ops_emp_plus, uc.ops_emp_null, uc.ops_emp_minus,\n          uc.sbr_opi_plus, uc.sbr_opi_null, uc.sbr_opi_minus,\n          uc.paid_advices_cnt + uc.sbr_opi_plus + uc.ops_emp_plus + uc.tu_orders_plus + uc.projects_fb_plus as opinions_plus,\n          uc.sbr_opi_minus + uc.ops_emp_minus + uc.tu_orders_minus + uc.projects_fb_minus as opinions_minus\n          {$sel_blocked} \n          FROM projects_offers AS po\n          LEFT JOIN projects pr ON pr.id=po.project_id\n          INNER JOIN freelancer as fl ON po.user_id=fl.uid\n          {$join_blocked} \n          LEFT JOIN users_counters uc ON uc.user_id = fl.uid\n          LEFT JOIN professions p ON p.id=fl.spec\n          LEFT JOIN country cr ON cr.id=fl.country\n          LEFT JOIN city ct ON ct.id=fl.city\n          LEFT JOIN sbr_meta ON sbr_meta.user_id = fl.uid -- старые БС\n          WHERE (po.project_id = ?i ) AND (po.user_id > 0) {$and_blocked}" . ($bPermissions ? '' : ' AND fl.is_banned::integer = 0') . ($show_all ? '' : " AND (po.only_4_cust='f')") . ($user_id == 0 ? '' : ' AND (fl.uid<>' . $user_id . ')') . $filter . $order . $limit_str;
         $ret = $DB->rows($sql, $prj_id);
         $error = $DB->error;
         if ($error) {
             $error = parse_db_error($error);
         } else {
             //$ret = pg_fetch_all($res);
             $sql = "SELECT COUNT(*) as num\n            FROM projects_offers AS po\n            LEFT JOIN projects as pr ON po.project_id=pr.id\n            INNER JOIN freelancer as fl ON po.user_id=fl.uid\n            {$join_blocked} \n            LEFT JOIN professions p ON p.id=fl.spec\n            LEFT JOIN country cr ON cr.id=fl.country\n            LEFT JOIN city ct ON ct.id=fl.city\n            WHERE (po.project_id = ?i ) AND (po.user_id > 0) {$and_blocked}" . ($bPermissions ? '' : ' AND fl.is_banned::integer = 0') . ($show_all ? '' : " AND (po.only_4_cust='f')") . ($user_id == 0 ? '' : ' AND (fl.uid<>' . $user_id . ')') . $filter;
             $count = $DB->val($sql, $prj_id);
             if ($count && $ret) {
                 foreach ($ret as &$value) {
                     // Выбираем вложения.
                     if ($value['id']) {
                         $sql = 'SELECT a.id, a.prev_pict as prev, a.pict ' . 'FROM projects_offers_attach AS a ' . 'WHERE a.offer_id= ?i';
                         $value['attach'] = $DB->rows($sql, $value['id']);
                     }
                 }
             }
         }
     }
     // временное решение для plproxy. очень не красиво, но пока не перенесется большая часть таблиц,
     // придется видимо оставить так
     if (!empty($ret)) {
         $teams = new teams();
         $notes = new notes();
         $t = $teams->teamsFavorites($ret[0]['p_user_id'], $error);
         $n = $notes->GetNotes($ret[0]['p_user_id'], 0, $error);
         for ($i = 0; $i < count($ret); ++$i) {
             // избранные
             $ret[$i]['in_team'] = 0;
             for ($j = 0; $j < count($t); ++$j) {
                 if ($t[$j]['uid'] == $ret[$i]['uid']) {
                     $ret[$i]['in_team'] = $ret[$i]['uid'];
                     break;
                 }
             }
             // заметки
             $ret[$i]['n_text'] = '';
             for ($j = 0; $j < count($n); ++$j) {
                 if ($n[$j]['to_id'] == $ret[$i]['uid']) {
                     $ret[$i]['n_text'] = $n[$j]['n_text'];
                     break;
                 }
             }
         }
     }
     return $ret;
 }
Esempio n. 5
0
 function initFromDraft($draft_id, $uid)
 {
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/drafts.php";
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/project_exrates.php";
     $drafts = new drafts();
     $this->_project = $drafts->getDraft($draft_id, $uid, 1);
     if (!$this->_project['id']) {
         return false;
     }
     if ($this->_project['logo_id'] > 0) {
         $this->_project['link'] = $this->_project['logo_link'];
         $LogoFile = new CFile($this->_project['logo_id']);
         $this->initLogo($LogoFile);
     }
     $cat = explode(",", $this->_project['categories']);
     foreach ($cat as $category) {
         list($cat_id, $subcat_id) = explode("|", $category);
         $categories[] = array('category_id' => $cat_id, 'subcategory_id' => $subcat_id);
     }
     $this->setCategories($categories);
     $pExrates = project_exrates::getAll();
     if ($this->_project['currency'] === 0) {
         // USD
         $costRub = $this->_project['cost'] * $pExrates['24'];
         // бюджет в рублях
     } elseif ($this->_project['currency'] === 1) {
         // EURO
         $costRub = $this->_project['cost'] * $pExrates['34'];
     } else {
         // рубли
         $costRub = $this->_project['cost'];
     }
     $this->setCostRub($costRub);
     $this->_project['draft_id'] = $this->_project['id'];
     unset($this->_project['id']);
     $this->_project['user_id'] = $this->_project['uid'];
     $this->_project['is_pro'] = is_pro(true, $uid) ? 't' : 'f';
     if ($this->_project['top_days'] > 0) {
         $this->setAddedTopDays($this->_project['top_days']);
     }
     if ($this->isKonkurs()) {
         $this->_project['end_date'] = date('d-m-Y', strtotime($this->_project['end_date']));
         $this->_project['win_date'] = date('d-m-Y', strtotime($this->_project['win_date']));
     }
     $attach = drafts::getAttachedFiles($draft_id, 4, $this->_project['uid']);
     if (!empty($attach)) {
         foreach ($attach as $file_id) {
             $ret[$file_id] = array('status' => 1, 'id' => $file_id);
         }
         $this->addAttachedFiles($ret, true);
     }
     return true;
 }
Esempio n. 6
0
<?php

require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/rating.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/xajax/projects_ci.common.php";
$xajax->printJavascript('/xajax/');
require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/project_exrates.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/HTML/projects_lenta.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/opinions.php";
// Подгружаем данные по мнения создалю проекта
$op_data = opinions::getCounts($project['user_id'], array('frl', 'norisk', 'all', 'total'));
$project_exRates = project_exrates::GetAll();
$exch = array(1 => 'FM', 'USD', 'Euro', 'Руб');
$translate_exRates = array(0 => 2, 1 => 3, 2 => 4, 3 => 1);
$foto_alt = $project['name'];
$answer_button_href = get_uid(FALSE) ? is_emp($_SESSION['role']) ? "/frl_only.php" : ($project['pro_only'] == 't' && !$is_pro && $project['user_id'] != $_SESSION['uid'] && !hasPermissions('projects') ? "/payed/" : "#new_offer") : "/registration/?from_prj=" . $project['id'];
$category = professions::GetGroup($project['category'], $eeee);
if ($category['name'] && $project['subcategory']) {
    $category['name'] .= '&nbsp;/&nbsp;' . professions::GetProfName($project['subcategory']);
}
$can_edit = !!is_numeric(InGet('edit')) && $user_offer['refused'] != 't';
$is_user_offer_exist = (!$user_offer_exist || $can_edit) && $project['closed'] != 't' && $uid > 0;
if ($project['pro_only'] == 't' && !$is_pro && $project['user_id'] != $_SESSION['uid'] && !hasPermissions('projects')) {
    $offers = array();
    $is_user_offer_exist = false;
}
if ($project['verify_only'] == 't') {
    $verify_check = $is_verify;
    if (!$is_verify) {
        //$answer_button_href = '/promo/verification/';
        if (!get_uid(false)) {
            $_SESSION['ref_uri2'] = $project['id'];
 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));
     }
 }
Esempio n. 8
0
 /**
  * Статистика по проектам за последний месяц и активным пользователям
  * @return   array   элемент u - данные по активным пользователям, p - данные по проектам.
  *                   Каждый содрежит массив с элементами:count - количество, phrase - обозначение единицы в нужном числе
  */
 function ShowStats()
 {
     require_once ABS_PATH . '/classes/project_exrates.php';
     $sql = "SELECT count(uid) as cnt FROM users WHERE active = true";
     $memBuff = new memBuff();
     $tmp = $memBuff->getSql($error, $sql, 600);
     $users = $tmp[0]['cnt'];
     $sql = "SELECT count(id) as cnt FROM projects WHERE post_date >= '" . date("Y-m-d", time() - 3600 * 24 * 31) . "'";
     $tmp = $memBuff->getSql($error, $sql, 600);
     $projects = $tmp[0]['cnt'];
     $projects = $tmp[0]['cnt'];
     $project_exRates = project_exrates::GetAll();
     $costProjectWithoutCost = 21000;
     $sql = "SELECT \n                    count(t.id) as cnt, SUM(t.cost_rub) as sum \n                    FROM (SELECT \n                            CASE WHEN currency = 0 THEN ( CASE WHEN cost = 0 THEN {$costProjectWithoutCost} ELSE cost * {$project_exRates[24]} END )\n                            WHEN currency  = 1 THEN ( CASE WHEN cost=0 THEN {$costProjectWithoutCost} ELSE cost * {$project_exRates[34]} END )\n                            WHEN currency = 3 THEN ( CASE WHEN cost=0 THEN {$costProjectWithoutCost} ELSE cost * {$project_exRates[14]} END )\n                            ELSE ( CASE WHEN cost=0 THEN {$costProjectWithoutCost} ELSE cost END ) END as cost_rub, id\n                          FROM projects WHERE post_date >= NOW() - interval '1 month'\n                    ) as t";
     $tmp = $memBuff->getSql($error, $sql, 600);
     if ($tmp[0]['cnt'] > 0) {
         $projects_budget = round($tmp[0]['sum'] / $tmp[0]['cnt'], 0);
     } else {
         $projects_budget = 0;
     }
     $users_str = ending($users, 'пользователь', 'пользователя', 'пользователей');
     $projects_str = ending($projects, 'проект', 'проекта', 'проектов');
     if ($projects >= 10000) {
         $projects = number_format($projects, 0, '', ' ');
     }
     if ($users >= 10000) {
         $users = number_format($users, 0, '', ' ');
     }
     if ($projects_budget >= 10000) {
         $projects_budget = number_format($projects_budget, 0, '', ' ');
     }
     //$str = "<span>".$projects."</span> ".$projects_str." в месяц, <span>".$users."</span> ".$users_str."";
     return array('u' => array('count' => $users, 'phrase' => $users_str), 'p' => array('count' => $projects, 'phrase' => $projects_str . ' в месяц'), 's' => array('count' => $projects_budget, 'phrase' => 'средний бюджет проектов'));
 }
Esempio n. 9
0
 }
 if (is_empty_html($project['descr'])) {
     $error['descr'] = 'Поле не заполнено';
 }
 if (is_empty_html($project['name'])) {
     $error['name'] = 'Поле не заполнено';
 }
 $descr_limit = !$PDA ? 5000 : 2500;
 if (strlen_real($project['descr']) > $descr_limit) {
     $error['descr'] = "Исчерпан лимит символов ({$descr_limit})";
 }
 if ($project['kind'] == 7) {
     $tmpPrj->setProjectField('end_date', str_replace('.', '-', __paramInit('string', NULL, 'end_date')), 0, 64);
     $tmpPrj->setProjectField('win_date', str_replace('.', '-', __paramInit('string', NULL, 'win_date')), 0, 64);
     $project = $tmpPrj->getProject();
     $pExrates = project_exrates::getAll();
     if ($project['currency'] == 0) {
         // USD
         $costRub = $project['cost'] * $pExrates['24'];
         // бюджет в рублях
     } elseif ($project['currency'] == 1) {
         // EURO
         $costRub = $project['cost'] * $pExrates['34'];
     } else {
         // рубли
         $costRub = $project['cost'];
     }
     $tmpPrj->setCostRub($costRub);
     // минимальный бюджет конкурса зависит от того введена ли новая система подсчета стоимости публикации
     $contestMinBudget = new_projects::isNewContestBudget($project['post_date']) ? new_projects::NEW_CONTEST_MIN_BUDGET : new_projects::CONTEST_MIN_BUDGET;
     if (!$project['cost'] || $costRub < $contestMinBudget) {
function quickprjedit_save_budget($prj_id, $frm, $type, $page_type)
{
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/projects.php';
    $objResponse = new xajaxResponse();
    $budget = null;
    if (hasPermissions('projects')) {
        if ($frm['agreement'] == 1 || $frm['cost'] == 0) {
            $budget = projects::updateBudget($prj_id, 0, 0, 0, true);
            $str_budget_cost = 'По договоренности';
            $agreement = true;
            $str_budget_lnk = "popupShowChangeBudget({$prj_id}, '', 0, 1, true, {$prj_id}, " . ($type == 1 ? 1 : 2) . ', ' . ($page_type ? $page_type : 0) . '); return false;';
            $budget_block = '<table cellspacing="0" cellpadding="0">
                                <tr>
                                    <td>
                                        <div class="form">
                                        <b class="b1"></b>
                                        <b class="b2"></b>
                                            <div class="form-in">
                                            <a href="#" id="prj_budget_lnk_' . $prj_id . '" onClick="popupShowChangeBudget(' . $prj_id . ', \'\', 0, 1, true, ' . $prj_id . ', ' . ($type == 1 ? 1 : 2) . ', ' . ($page_type ? $page_type : 0) . '); return false;">Бюджет по договоренности</a>
                                            </div>
                                        <b class="b2"></b>
                                        <b class="b1"></b>
                                        </div>
                                    </td>
                                </tr>
                             </table>';
            $budget_block_class = 'prj_cost prj-dogovor';
        } else {
            if ($frm['cost'] > 0) {
                $budget = projects::updateBudget($prj_id, $frm['cost'], $frm['currency'], $frm['costby'], false);
                $str_budget_cost = CurToChar($budget['cost'], $budget['currency']);
                $agreement = false;
                $str_budget_lnk = "popupShowChangeBudget({$prj_id}, '{$budget['cost']}', '{$budget['currency']}', '{$budget['costby']}', false, {$prj_id}, " . ($type == 1 ? 1 : 2) . ', ' . ($page_type ? $page_type : 0) . '); return false;';
                $budget_block_class = 'prj_cost';
                $budget_block = '<div class="budget-block">';
                switch ($budget['budget_type']) {
                    default:
                        $budget_price_str = '';
                        $budget_price_class = 'fl-form-grey';
                        break;
                }
                if ($budget['cost'] == '' || $budget['cost'] == 0) {
                    $budget_price_str = '';
                    $budget_price_class = 'fl-form-grey';
                }
                if ($budget_price_str != '') {
                    $budget_block .= '
                         <div class="fl-form fl-form-tr budget-type">
                             ' . $budget_price_str . '
                             <span class="cc cc-lt"></span>
                             <span class="cc cc-rt"></span>
                             <span class="cc cc-lb"></span>
                             <span class="cc cc-rb"></span>
                             <span class="budget-type-lug"></span>
                         </div>';
                }
                $budget_block .= '<div class="fl-form ' . $budget_price_class . ' color-budget">';
                switch ($budget['costby']) {
                    case '1':
                        $priceby_str = '/час';
                        break;
                    case '2':
                        $priceby_str = '/день';
                        break;
                    case '3':
                        $priceby_str = '/месяц';
                        break;
                    case '4':
                        $priceby_str = '/проект';
                        break;
                    default:
                        $priceby_str = '';
                        break;
                }
                if ($budget['cost'] == '' || $budget['cost'] == 0) {
                    $priceby_str = '';
                }
                $budget_block .= '<strong>
                                <a href="#" id="prj_budget_lnk_' . $prj_id . '">Бюджет: ' . CurToChar($budget['cost'], $budget['currency']) . $priceby_str . '</a>
                             </strong>';
                if ($budget['cost'] > 0) {
                    $project_exRates = project_exrates::GetAll();
                    $exch = array(1 => 'FM', 'USD', 'Euro', 'Руб');
                    $translate_exRates = array(0 => 2, 1 => 3, 2 => 4, 3 => 1);
                    $price_other_cur = '';
                    if ($budget['currency'] != 0) {
                        $price_other_cur .= CurToChar(preg_replace('/.00$/', '', sprintf('%.2f', round($budget['cost'] * $project_exRates[trim($translate_exRates[$budget['currency']]) . '2'], 2))), 0) . 'AA';
                    }
                    if ($budget['currency'] != 1) {
                        $price_other_cur .= CurToChar(preg_replace('/.00$/', '', sprintf('%.2f', round($budget['cost'] * $project_exRates[trim($translate_exRates[$budget['currency']]) . '3'], 2))), 1) . 'AA';
                    }
                    if ($budget['currency'] != 2) {
                        $price_other_cur .= CurToChar(preg_replace('/.00$/', '', sprintf('%.2f', round($budget['cost'] * $project_exRates[trim($translate_exRates[$budget['currency']]) . '4'], 2))), 2) . 'AA';
                    }
                    if ($budget['currency'] != 3) {
                        $price_other_cur .= CurToChar(preg_replace('/.00$/', '', sprintf('%.2f', round($budget['cost'] * $project_exRates[trim($translate_exRates[$budget['currency']]) . '1'], 2))), 3) . 'AA';
                    }
                    $price_other_cur = preg_replace('/AA$/', '', $price_other_cur);
                    $price_other_cur = preg_replace('/AA/', '&nbsp;—&nbsp;', $price_other_cur);
                    $budget_block .= '<em>' . $price_other_cur . '</em>';
                }
                $budget_block .= '
                             <span class="cc cc-lt"></span>
                             <span class="cc cc-rt"></span>
                             <span class="cc cc-lb"></span>
                             <span class="cc cc-rb"></span>
                         </div>
                     </div>';
            }
        }
        switch ($budget['costby']) {
            case '1':
                $costby_str = '/час';
                break;
            case '2':
                $costby_str = '/день';
                break;
            case '3':
                $costby_str = '/месяц';
                break;
            case '4':
                $costby_str = '/проект';
                break;
            default:
                $costby_str = '';
                break;
        }
        $str_budget_cost = $str_budget_cost . $costby_str;
    }
    if ($budget) {
        switch ($type) {
            case 1:
                // Лента
                $objResponse->assign("prj_budget_lnk_{$prj_id}", 'innerHTML', $str_budget_cost);
                if ($agreement) {
                    $objResponse->script('$("prj_budget_lnk_' . $prj_id . '").getParent().removeClass("b-post__price_bold").removeClass("b-post__price_fontsize_15").addClass("bujet-dogovor");');
                } else {
                    if ($page_type != 2) {
                        $objResponse->script('$("prj_budget_lnk_' . $prj_id . '").getParent().addClass("b-post__price_bold").removeClass("b-post__price_fontsize_13").addClass("b-post__price_fontsize_15");');
                    } else {
                        $objResponse->script('$("prj_budget_lnk_' . $prj_id . '").getParent().removeClass("b-post__price_bold").removeClass("b-post__price_fontsize_13").removeClass("bujet-dogovor");');
                    }
                }
                $objResponse->script("\$('prj_budget_lnk_{$prj_id}').addEvent('click', function() { {$str_budget_lnk} });");
                break;
            case 2:
                // Проект
                $objResponse->assign('budget_block', 'innerHTML', $budget_block);
                $objResponse->script("\$('budget_block').set('class', '{$budget_block_class}');");
                $objResponse->script("\$('prj_budget_lnk_{$prj_id}').addEvent('click', function() { {$str_budget_lnk} });");
                break;
        }
    }
    return $objResponse;
}
Esempio n. 11
0
 /**
  * Расчет средних цен размещенных работ фрилансеров. Вызывается в /hourly.php
  *
  */
 function calcAvgPrices()
 {
     global $DB;
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/project_exrates.php";
     $project_exrates = new project_exrates();
     $prj_exrates = $project_exrates->GetAll();
     $sql = "SELECT id, name FROM professions p LEFT JOIN mirrored_professions m ON p.id = m.mirror_prof WHERE m.main_prof IS NULL AND p.id>0";
     $professions = $DB->rows($sql);
     foreach ($professions as $profession) {
         //  Проекты
         $sql = "SELECT COUNT(\n                            CASE\n                                WHEN cost_type=0 THEN cost*" . $prj_exrates[21] . "\n                                WHEN cost_type=1 THEN cost*" . $prj_exrates[31] . "\n                                WHEN cost_type=2 THEN cost*" . $prj_exrates[41] . "\n                                WHEN cost_type=3 THEN cost\n                                ELSE cost*" . $prj_exrates[21] . "\n                            END\n                           ) as cnt \n                    FROM portfolio WHERE prof_id=?i AND (time_value IS NULL OR time_value=0) AND (time_type=0 OR time_type IS NULL) AND cost>0";
         $cnt = $DB->val($sql, $profession['id']);
         $is_manual_cost_prj = 'f';
         if ($cnt) {
             $count_portfolio = $DB->val("SELECT count(id) FROM portfolio WHERE prof_id=?i AND (time_value IS NULL OR time_value=0) AND (time_type=0 OR time_type IS NULL) AND cost>0", $profession['id']);
             if ($count_portfolio > 10) {
                 $sql = "SELECT (\n                                    CASE\n                                        WHEN cost_type=0 THEN cost*" . $prj_exrates[21] . "\n                                        WHEN cost_type=1 THEN cost*" . $prj_exrates[31] . "\n                                        WHEN cost_type=2 THEN cost*" . $prj_exrates[41] . "\n                                        WHEN cost_type=3 THEN cost\n                                        ELSE cost*" . $prj_exrates[21] . "\n                                    END\n                                   ) as acost\n                            FROM portfolio WHERE prof_id=?i AND (time_value IS NULL OR time_value=0) AND (time_type=0 OR time_type IS NULL) AND cost>0 ORDER BY acost ASC OFFSET ?i LIMIT 1";
                 if ($cnt % 2 == 0) {
                     $n = $cnt / 2;
                     $fin_avg_prj1 = $DB->val($sql, $profession['id'], $n - 1);
                     $fin_avg_prj2 = $DB->val($sql, $profession['id'], $n);
                     $fin_avg_prj = ceil(($fin_avg_prj1 + $fin_avg_prj1) / 2);
                 } else {
                     $n = ($cnt - 1) / 2;
                     $fin_avg_prj = ceil($DB->val($sql, $profession['id'], $n));
                 }
                 $fin_min_prj = $fin_avg_prj - ceil($fin_avg_prj / 4);
                 $fin_max_prj = $fin_avg_prj + ceil($fin_avg_prj / 4);
             } else {
                 $is_manual_cost_prj = 't';
             }
         } else {
             $is_manual_cost_prj = 't';
         }
         // Время
         $sql = "SELECT COUNT(\n                            CASE\n                                WHEN p.cost_type=0 THEN p.cost*" . $prj_exrates[21] . "\n                                WHEN p.cost_type=1 THEN p.cost*" . $prj_exrates[31] . "\n                                WHEN p.cost_type=2 THEN p.cost*" . $prj_exrates[41] . "\n                                WHEN p.cost_type=3 THEN p.cost\n                                ELSE p.cost*" . $prj_exrates[21] . "\n                            END\n                           ) as cnt \n                    FROM (\n                            SELECT (cost/time_value) as cost, cost_type FROM portfolio WHERE prof_id={$profession['id']} AND cost>0 AND time_value>0 AND time_type=0\n                            UNION ALL\n                            SELECT (cost/(8*time_value)) as cost, cost_type FROM portfolio WHERE prof_id={$profession['id']} AND cost>0 AND time_value>0 AND time_type=1\n                            UNION ALL\n                            SELECT (cost/(22*8*time_value)) as cost, cost_type FROM portfolio WHERE prof_id={$profession['id']} AND cost>0 AND time_value>0 AND time_type=2\n                            UNION ALL\n                            SELECT (cost*(time_value/60)) as cost, cost_type FROM portfolio WHERE prof_id={$profession['id']} AND cost>0 AND time_value>0 AND time_type=3\n                         ) as p\n                    ";
         $cnt = $DB->val($sql);
         $is_manual_cost_hour = 'f';
         if ($cnt) {
             $sql = "SELECT COUNT(p.id)\n                        FROM (\n                                SELECT id FROM portfolio WHERE prof_id={$profession['id']} AND cost>0 AND time_value>0 AND time_type=0\n                                UNION ALL\n                                SELECT id FROM portfolio WHERE prof_id={$profession['id']} AND cost>0 AND time_value>0 AND time_type=1\n                                UNION ALL\n                                SELECT id FROM portfolio WHERE prof_id={$profession['id']} AND cost>0 AND time_value>0 AND time_type=2\n                                UNION ALL\n                                SELECT id FROM portfolio WHERE prof_id={$profession['id']} AND cost>0 AND time_value>0 AND time_type=3\n                             ) as p\n                        ";
             $count_portfolio = $DB->val($sql);
             if ($cnt > 10) {
                 $sql = "SELECT (\n                                    CASE\n                                        WHEN p.cost_type=0 THEN p.cost*" . $prj_exrates[21] . "\n                                        WHEN p.cost_type=1 THEN p.cost*" . $prj_exrates[31] . "\n                                        WHEN p.cost_type=2 THEN p.cost*" . $prj_exrates[41] . "\n                                        WHEN p.cost_type=3 THEN p.cost\n                                        ELSE p.cost*" . $prj_exrates[21] . "\n                                    END\n                                   ) as acost \n                            FROM (\n                                    SELECT (cost/time_value) as cost, cost_type FROM portfolio WHERE prof_id={$profession['id']} AND cost>0 AND time_value>0 AND time_type=0\n                                    UNION ALL\n                                    SELECT (cost/(8*time_value)) as cost, cost_type FROM portfolio WHERE prof_id={$profession['id']} AND cost>0 AND time_value>0 AND time_type=1\n                                    UNION ALL\n                                    SELECT (cost/(22*8*time_value)) as cost, cost_type FROM portfolio WHERE prof_id={$profession['id']} AND cost>0 AND time_value>0 AND time_type=2\n                                    UNION ALL\n                                    SELECT (cost*(time_value/60)) as cost, cost_type FROM portfolio WHERE prof_id={$profession['id']} AND cost>0 AND time_value>0 AND time_type=3\n                                 ) as p\n                            ORDER BY acost ASC OFFSET ?i LIMIT 1;\n                        ";
                 if ($cnt % 2 == 0) {
                     $n = $cnt / 2;
                     $fin_avg_hour1 = $DB->val($sql, $n - 1);
                     $fin_avg_hour2 = $DB->val($sql, $n);
                     $fin_avg_hour = ceil(($fin_avg_hour1 + $fin_avg_hour1) / 2);
                 } else {
                     $n = ($cnt - 1) / 2;
                     $fin_avg_hour = ceil($DB->val($sql, $n));
                 }
                 $fin_min_hour = $fin_avg_hour - ceil($fin_avg_hour / 4);
                 $fin_max_hour = $fin_avg_hour + ceil($fin_avg_hour / 4);
             } else {
                 $is_manual_cost_hour = 't';
             }
         } else {
             $is_manual_cost_hour = 't';
         }
         $mirrors = $DB->col("SELECT mirror_prof FROM mirrored_professions WHERE main_prof = ?i", $profession['id']);
         if ($is_manual_cost_hour == 't') {
             $sql = "UPDATE professions SET is_manual_cost_hour='t' WHERE id IN (?l)";
             $DB->query($sql, array($profession['id']));
             if ($mirrors) {
                 $DB->query($sql, $mirrors);
             }
         } else {
             $sql = "UPDATE professions SET is_manual_cost_hour='f', min_cost_hour=?i, max_cost_hour=?, avg_cost_hour=?i WHERE id IN (?l)";
             $DB->query($sql, $fin_min_hour, $fin_max_hour, $fin_avg_hour, array($profession['id']));
             if ($mirrors) {
                 $DB->query($sql, $fin_min_hour, $fin_max_hour, $fin_avg_hour, $mirrors);
             }
         }
         if ($is_manual_cost_prj == 't') {
             $sql = "UPDATE professions SET is_manual_cost_prj='t' WHERE id IN (?l)";
             $DB->query($sql, array($profession['id']));
             if ($mirrors) {
                 $DB->query($sql, $mirrors);
             }
         } else {
             $sql = "UPDATE professions SET is_manual_cost_prj='f', min_cost_prj=?i, max_cost_prj=?, avg_cost_prj=?i WHERE id IN (?l)";
             $DB->query($sql, $fin_min_prj, $fin_max_prj, $fin_avg_prj, array($profession['id']));
             if ($mirrors) {
                 $DB->query($sql, $fin_min_prj, $fin_max_prj, $fin_avg_prj, $mirrors);
             }
         }
     }
 }
Esempio n. 12
0
 /**
  * Метод может использоваться в двух случаях:
  * 1. Для подсчета количества пользователей и стомости рассылки исходя из заданного фильтра.
  * 2. Расчитать (без дополнительно расчета каталога и городов) количество пользователей и стоимость + сохранить список пользователей в mass_sending_users
  * @param  integer  $uid      uid пользователя совершаемого рассылку
  * @param  array    $params   массив с данными фильтра фрилансеров
  * @param  commit   integer   если не 0, то сохранит всех найденых пользователей для рассылки $commit иначе просто расчет
  * @return          array     результат расчета в виде 
  *                            array('count', 'cost', 'pro'=>array('count', 'cost'), locations=>array(array('city', 'country', 'count', 'cost')), professions=>array(array('group', 'profession', 'count', 'cost')))
  *
  */
 public function Calculate($uid, array $params, $commit = 0)
 {
     global $DB;
     $result = array('count' => 0, 'cost' => 0, 'pro' => array('count' => 0, 'cost' => 0), 'professions' => array(), 'locations' => array());
     $cost = $this->GetTariff($this->tariff_id);
     $memBuff = new memBuff();
     $memBuffGroup = 'massending_calc';
     $ow = $cw = "";
     $op = $cp = array();
     $tmp = array();
     $profs = $profsgr = array();
     $jn = $wh = $whc = $whl = "";
     $wh .= " AND u.subscr & B'0000000000001000' = B'0000000000001000'";
     //----------------------------------------------------------------------
     // у меня в избранных
     if (!empty($params['favorites'])) {
         $dbProxy = new DB('plproxy');
         $targets = $dbProxy->col("SELECT target_id FROM teams(?)", $uid);
         if ($targets) {
             $wh .= $dbProxy->parse(" AND u.uid IN (?l)", $targets);
         }
     }
     //----------------------------------------------------------------------
     // только свободные
     if (!empty($params['free'])) {
         $wh .= " AND u.status_type = 0";
     }
     //----------------------------------------------------------------------
     // с верифицированым аккаунтом
     if (!empty($params['opi_is_verify'])) {
         $wh .= ' AND (u.is_verify = true)';
     }
     //----------------------------------------------------------------------
     // с примерами работ
     //if ($params['portfolio']) $wh .= " AND EXISTS(SELECT 1 FROM portfolio WHERE user_id = u.uid)";
     if (!empty($params['portfolio'])) {
         $jn = " INNER JOIN rating r ON r.user_id = u.uid AND r.o_wrk_factor_a > 0";
     }
     //----------------------------------------------------------------------
     // с успешными сбр и фрилансреами 1/2/3 разрядов
     if (!empty($params['sbr'])) {
         if (!$jn) {
             $jn = " INNER JOIN rating r ON u.uid = r.user_id";
         }
         if (!empty($params['discharge3'])) {
             $discharge = 3;
         } else {
             if (!empty($params['discharge2'])) {
                 $discharge = 2;
             } else {
                 if (!empty($params['discharge1'])) {
                     $discharge = 1;
                 } else {
                     $discharge = 0;
                 }
             }
         }
         if ($discharge) {
             $jn .= " AND r.rank >= {$discharge}";
         } else {
             $jn .= " AND r.sbr_count > 0 ";
         }
     }
     //----------------------------------------------------------------------
     $uc_where = '';
     // с положительными рекомендациями
     //if (!empty($params['sbr_is_positive'])) $uc_where .= " AND uc.sbr_opi_plus > 0";
     // без негативных рекомендация
     //if (!empty($params['sbr_not_negative'])) $uc_where .= " AND uc.sbr_opi_minus = 0";
     // с положительными отзывами
     if (!empty($params['opi_is_positive'])) {
         $uc_where .= ' AND ((uc.ops_emp_plus + uc.ops_frl_plus + uc.sbr_opi_plus) > 0)';
     }
     // без негативных отзывами
     if (!empty($params['opi_not_negative'])) {
         $uc_where .= ' AND ((uc.ops_emp_minus + uc.ops_frl_minus + uc.sbr_opi_minus) = 0 OR uc.user_id IS NULL)';
     }
     if ($uc_where) {
         $wh .= $uc_where;
         $jn .= "LEFT JOIN users_counters uc ON uc.user_id = u.uid";
     }
     //----------------------------------------------------------------------
     // ищет работу в офисе
     if ($params['inoffice']) {
         $wh .= " AND u.in_office = 't'";
     }
     //----------------------------------------------------------------------
     // стоимость
     if (!empty($params['cost_from']) && is_array($params['cost_from']) || !empty($params['cost_to']) && is_array($params['cost_to'])) {
         $exrates = project_exrates::GetAll();
         $cex = array(2, 3, 4, 1);
         $tmp = '';
         foreach ($params['cost_from'] as $i => $val) {
             if (!$params['cost_from'][$i] && !$params['cost_to'][$i]) {
                 continue;
             }
             $type = isset($params['cost_type'][$i]) && in_array($params['cost_type'][$i], array(0, 1, 2, 3)) ? $params['cost_type'][$i] : 0;
             if (isset($params['cost_period'][$i]) && $params['cost_period'][$i] == 'month') {
                 $ct = 'u.cost_type_month';
                 $cc = 'u.cost_month';
             } else {
                 $ct = 'u.cost_type_hour';
                 $cc = 'u.cost_hour';
             }
             $cost_from = floatval(str_replace(array(' ', ','), array('', '.'), $params['cost_from'][$i])) * $exrates[$cex[$type] . '1'];
             $cost_to = floatval(str_replace(array(' ', ','), array('', '.'), $params['cost_to'][$i])) * $exrates[$cex[$type] . '1'];
             $s = "(CASE WHEN {$ct} = 0 THEN {$exrates[$cex[0] . '1']} WHEN {$ct} = 1 THEN {$exrates[$cex[1] . '1']} WHEN {$ct} = 2 THEN {$exrates[$cex[2] . '1']} WHEN {$ct} = 3 THEN {$exrates[$cex[3] . '1']} END)";
             if ($cost_to > $cost_from || !$cost_to || !$cost_from) {
                 $s = ($cost_from ? " AND ({$cc} * {$s}) >= {$cost_from} " : "") . ($cost_to ? " AND ({$cc} * {$s}) <= {$cost_to}" : "");
             } else {
                 $s = ($cost_from ? " AND ({$cc} * {$s}) <= {$cost_from} " : "") . ($cost_to ? " AND ({$cc} * {$s}) >= {$cost_to}" : "");
             }
             $tmp .= ' OR (' . substr($s, 5) . ')';
         }
         if ($tmp) {
             $wh .= ' AND (' . substr($tmp, 4) . ')';
         }
     }
     //----------------------------------------------------------------------
     // опыт в годах
     if (intval($params['expire_from']) || intval($params['expire_to'])) {
         $f = intval($params['expire_from']);
         $t = intval($params['expire_to']);
         if ($f && $t && $f > $t) {
             list($f, $t) = array($t, $f);
         }
         //if ($f) $wh .= " AND ((regexp_replace(u.exp, '^([0-9]+)?.*', E'\\\\1')) <> '' AND (regexp_replace(u.exp, '^([0-9]+)?.*', E'\\\\1'))::int >= $f)";
         //if ($t) $wh .= " AND ((regexp_replace(u.exp, '^([0-9]+)?.*', E'\\\\1')) <> '' AND (regexp_replace(u.exp, '^([0-9]+)?.*', E'\\\\1'))::int <= $t)";
         if ($f) {
             $wh .= " AND u.exp >= {$f}";
         }
         if ($t) {
             $wh .= " AND u.exp <= {$t}";
         }
     }
     //----------------------------------------------------------------------
     // только pro
     if (!empty($params['is_pro'])) {
         $wh .= " AND u.is_pro = 't'";
     }
     //----------------------------------------------------------------------
     // меторасположение
     if (!empty($params['locations']) && is_array($params['locations'])) {
         $tmp = '';
         $tmpc = array();
         foreach ($params['locations'] as $location) {
             if (preg_match("/^([0-9]{1,10})\\:([0-9]{1,10})\$/", $location, $o)) {
                 if ($o[2]) {
                     if (empty($tmpc["{$o[1]}:{$o[2]}"])) {
                         $tmpc["{$o[1]}:{$o[2]}"] = 1;
                     } else {
                         continue;
                     }
                     $cw .= " OR (u.country = {$o[1]} AND u.city = {$o[2]})";
                     $tmp .= " OR (u.country = {$o[1]} AND u.city = {$o[2]})";
                 } else {
                     if (empty($tmpc["{$o[1]}:0"])) {
                         $tmpc["{$o[1]}:0"] = 1;
                     } else {
                         continue;
                     }
                     $ow .= " OR (u.country = {$o[1]})";
                     $tmp .= " OR (u.country = {$o[1]})";
                 }
             }
         }
         if ($tmp) {
             $whl = " AND (" . substr($tmp, 4) . ")";
         }
     }
     //----------------------------------------------------------------------
     // разделы в каталоге
     if (!empty($params['professions']) && is_array($params['professions'])) {
         $tmpc = array();
         foreach ($params['professions'] as $profession) {
             if (preg_match("/^([0-9]{1,10})\\:([0-9]{1,10})\$/", $profession, $o)) {
                 if ($o[2]) {
                     if (empty($tmpc["{$o[1]}:{$o[2]}"])) {
                         $tmpc["{$o[1]}:{$o[2]}"] = 1;
                     } else {
                         continue;
                     }
                     $cp[$o[2]] = array($o[1], $o[2]);
                 } else {
                     if (empty($tmpc["{$o[1]}:0"])) {
                         $tmpc["{$o[1]}:0"] = 1;
                     } else {
                         continue;
                     }
                     $op[] = $o[1];
                 }
             }
         }
     }
     // подготовка данных, если указаны разделы каталога
     if ($op || $cp) {
         // если группа и раздел
         if ($cp) {
             $tmp = array();
             foreach ($cp as $k => $v) {
                 if (in_array($v[0], $op)) {
                     unset($cp[$k]);
                 } else {
                     $tmp[] = $v[1];
                 }
             }
             if (!empty($cp)) {
                 $res = $DB->query('SELECT main_prof, mirror_prof FROM mirrored_professions WHERE mirror_prof IN (?l)', $tmp);
                 while ($row = pg_fetch_assoc($res)) {
                     $profs[] = $row['main_prof'];
                     $cp[$row['mirror_prof']][] = $row['main_prof'];
                 }
                 foreach ($cp as $v) {
                     if (empty($v[2])) {
                         $profs[] = $v[1];
                     }
                 }
             }
         }
         // если указаны только группы разделов
         if ($op) {
             $res = $DB->query('SELECT prof_group, id, main_prof FROM professions LEFT JOIN mirrored_professions ON mirror_prof = id WHERE prof_group IN (?l)', $op);
             $tmp = array();
             while ($row = pg_fetch_assoc($res)) {
                 $profsgr[] = $row['id'];
                 $tmp[$row['prof_group']] = 1;
                 if ($row['main_prof']) {
                     $profsgr[] = $row['main_prof'];
                 }
             }
             $op = array_keys($tmp);
         }
         $in_ids = implode(array_unique(array_merge($profs, $profsgr)), ',');
         //@todo: здесь лучше бы избавится от подзапроса, но походу никак
         //JOIN не быстрее да и другие результаты выдает
         $whc = " AND (u.spec_orig IN ({$in_ids})\n            OR (u.is_pro = TRUE AND EXISTS(\n                SELECT 1 FROM\n                    spec_add_choise\n                WHERE user_id = u.uid AND prof_id IN ({$in_ids})\n\t\t\t)))";
     } else {
         $whc = " AND u.spec_orig IS NOT NULL AND u.spec_orig > 0";
     }
     //----------------------------------------------------------------------
     // если указано меторасположение, то оно обробатывается своими запросами
     if (($cw || $ow) && !$commit && $this->isCalcMethond('locations')) {
         $locations = array();
         $haveTheir = array();
         // страны без городов
         if ($ow) {
             $sql = "SELECT country, is_pro, COUNT(*) AS cnt FROM freelancer u {$jn} WHERE is_banned = '0' {$whc}{$wh} AND (" . substr($ow, 4) . ") GROUP BY country, is_pro";
             if (!($rows = $memBuff->getSql($error, $sql, 600, false, $memBuffGroup))) {
                 $rows = array();
             }
             foreach ($rows as $row) {
                 $c = "{$row['country']}:0";
                 if (empty($locations[$c])) {
                     $locations[$c] = array('country' => $row['country'], 'city' => 0, 'cost' => 0, 'cost' => 0, 'pro' => array('cost' => 0, 'count' => 0));
                 }
                 $locations[$c]['count'] += $row['cnt'];
                 if ($row['is_pro'] == 't') {
                     $locations[$c]['cost'] += $row['cnt'] * $cost['pro'];
                     $locations[$c]['pro']['count'] += $row['cnt'];
                     $locations[$c]['pro']['cost'] += $row['cnt'] * $cost['pro'];
                 } else {
                     $locations[$c]['cost'] += $row['cnt'] * $cost['no_pro'];
                 }
                 $haveTheir[$row['country']] = TRUE;
             }
         }
         // страны с городами
         if ($cw) {
             $sql = "SELECT country, city, is_pro, COUNT(*) AS cnt FROM freelancer u {$jn} WHERE is_banned = '0' {$whc}{$wh} AND (" . substr($cw, 4) . ") GROUP BY country, city, is_pro";
             if (!($rows = $memBuff->getSql($error, $sql, 600, false, $memBuffGroup))) {
                 $rows = array();
             }
             foreach ($rows as $row) {
                 $c = "{$row['country']}:{$row['city']}";
                 if (empty($locations[$c])) {
                     $locations[$c] = array('country' => $row['country'], 'city' => $row['city'], 'cost' => 0, 'cost' => 0, 'pro' => array('cost' => 0, 'count' => 0));
                 }
                 if (!empty($haveTheir[$row['country']])) {
                     $locations[$c]['no'] = 1;
                 }
                 $locations[$c]['count'] += $row['cnt'];
                 if ($row['is_pro'] == 't') {
                     $locations[$c]['cost'] += $row['cnt'] * $cost['pro'];
                     $locations[$c]['pro']['count'] += $row['cnt'];
                     $locations[$c]['pro']['cost'] += $row['cnt'] * $cost['pro'];
                 } else {
                     $locations[$c]['cost'] += $row['cnt'] * $cost['no_pro'];
                 }
             }
         }
         foreach ($locations as $k => $v) {
             $v['cost'] = $v['cost'];
             if (empty($v['no'])) {
                 $result['count'] += $v['count'];
                 $result['cost'] += $v['cost'];
                 $result['pro']['count'] += $v['pro']['count'];
                 $result['pro']['cost'] += $v['pro']['cost'];
             }
             $result['locations'][] = $v;
         }
     }
     //----------------------------------------------------------------------
     // если указаны разделы каталога, то для них дополнительные запросы
     if (($op || $cp) && !$commit && $this->isCalcMethond('professions')) {
         $professions = array();
         if ($op) {
             $profsgr = array_unique($profsgr);
             if ($profsgr) {
                 $in_profsgr = implode($profsgr, ',');
                 $sql = "SELECT prof_group, is_pro, COUNT(uid) AS cnt\n                            FROM (\n                                SELECT s.prof_group, is_pro, uid\n                                FROM freelancer u\n                                INNER JOIN professions s ON s.id = u.spec_orig\n                                {$jn}\n                                WHERE \n                                    u.is_banned = '0' \n                                    AND u.spec_orig IN({$in_profsgr}) \n                                    {$wh}\n                                    {$whl}\n\n                                UNION\n\n                                SELECT s.prof_group, is_pro, uid\n                                FROM spec_add_choise sp\n                                INNER JOIN freelancer u ON sp.user_id = u.uid\n                                INNER JOIN professions s ON s.id = sp.prof_id\n                                {$jn}\n                                WHERE \n                                    u.is_banned = '0' \n                                    AND u.is_pro = TRUE \n                                    AND sp.prof_id IN({$in_profsgr}) \n                                    {$wh}\n                                    {$whl}\n                            ) s\n                            GROUP BY prof_group, is_pro";
                 if (!($rows = $memBuff->getSql($error, $sql, 600, false, $memBuffGroup))) {
                     $rows = array();
                 }
                 foreach ($rows as $row) {
                     if (empty($professions["{$row['prof_group']}:0"])) {
                         $professions["{$row['prof_group']}:0"] = array('id' => 0, 'group' => $row['prof_group'], 'count' => $row['cnt'], 'cost' => $row['cnt'] * ($row['is_pro'] == 't' ? $cost['pro'] : $cost['no_pro']));
                     } else {
                         $professions["{$row['prof_group']}:0"]['count'] += $row['cnt'];
                         $professions["{$row['prof_group']}:0"]['cost'] += $row['cnt'] * ($row['is_pro'] == 't' ? $cost['pro'] : $cost['no_pro']);
                     }
                 }
             }
         }
         if ($cp) {
             $in_profs = implode($profs, ',');
             $sql = "SELECT spec, is_pro, SUM(cnt) AS cnt\n\t\t\t\t\tFROM (\n\t\t\t\t\t\tSELECT spec_orig AS spec, is_pro, COUNT(uid) AS cnt\n\t\t\t\t\t\tFROM freelancer u\n\t\t\t\t\t\t{$jn}\n\t\t\t\t\t\tWHERE spec_orig IN ({$in_profs}) AND u.is_banned = '0' {$wh}{$whl}\n\t\t\t\t\t\tGROUP BY spec_orig, is_pro\n                        \n\t\t\t\t\t\tUNION ALL\n                        \n\t\t\t\t\t\tSELECT prof_id AS spec, is_pro, COUNT(uid) AS cnt\n\t\t\t\t\t\tFROM spec_add_choise sp\n\t\t\t\t\t\tINNER JOIN freelancer u ON sp.user_id = u.uid AND u.is_banned = '0' AND u.is_pro = TRUE\n\t\t\t\t\t\t{$jn}\n\t\t\t\t\t\tWHERE prof_id IN ({$in_profs}) {$wh}{$whl}\n\t\t\t\t\t\tGROUP BY prof_id, is_pro\n\t\t\t\t\t) s\n\t\t\t\t\tGROUP BY spec, is_pro\n\t\t\t\t";
             if (!($rows = $memBuff->getSql($error, $sql, 600, false, $memBuffGroup))) {
                 $rows = array();
             }
             foreach ($rows as $row) {
                 foreach ($cp as $k => $v) {
                     if ($row['spec'] == $v[1] || !empty($v[2]) && $row['spec'] == $v[2]) {
                         if (empty($professions["{$v[0]}:{$v[1]}"])) {
                             $professions["{$v[0]}:{$v[1]}"] = array('id' => $v[1], 'group' => $v[0], 'count' => $row['cnt'], 'cost' => $row['cnt'] * ($row['is_pro'] == 't' ? $cost['pro'] : $cost['no_pro']));
                         } else {
                             $professions["{$v[0]}:{$v[1]}"]['count'] += $row['cnt'];
                             $professions["{$v[0]}:{$v[1]}"]['cost'] += $row['cnt'] * ($row['is_pro'] == 't' ? $cost['pro'] : $cost['no_pro']);
                         }
                     }
                 }
             }
         }
         foreach ($professions as $k => $v) {
             $v['cost'] = $v['cost'];
             $result['professions'][] = $v;
         }
     }
     //----------------------------------------------------------------------
     // подсчет общего количества, если еще не было подсета при обратки месторасположения
     if (!($cw || $ow) || $commit || !$this->isCalcMethond('locations')) {
         $sql = "SELECT is_pro, COUNT(*) AS cnt FROM freelancer AS u {$jn} WHERE is_banned = '0' {$whc}{$whl}{$wh} GROUP BY is_pro";
         if (!($rows = $memBuff->getSql($error, $sql, 600, false, $memBuffGroup))) {
             $rows = array();
         }
         $result['count'] = 0;
         $result['cost'] = 0;
         $result['pro'] = array('count' => 0, 'cost' => 0);
         foreach ($rows as $row) {
             $result['count'] += $row['cnt'];
             if ($row['is_pro'] == 't') {
                 $result['pro']['count'] += $row['cnt'];
                 $result['pro']['cost'] += $row['cnt'] * $cost['pro'];
                 $result['cost'] += $row['cnt'] * $cost['pro'];
             } else {
                 $result['cost'] += $row['cnt'] * $cost['no_pro'];
             }
         }
     }
     //----------------------------------------------------------------------
     if ($commit) {
         $sql = "\n\t\t\t\tINSERT INTO mass_sending_users\n\t\t\t\tSELECT {$commit}, uid FROM freelancer u {$jn} WHERE is_banned = '0' {$whc}{$whl}{$wh} " . ($params['max_users'] > 0 && $params['max_cost'] > 0 ? 'ORDER BY u.rating DESC LIMIT ' . $params['max_users'] : '') . "\n\t\t\t";
         $DB->squery($sql);
     }
     return $result;
 }
Esempio n. 13
0
require_once $_SERVER['DOCUMENT_ROOT'] . "/xajax/public.common.php";
$xajax->printJavascript('/xajax/');
$categories = professions::GetAllGroupsLite();
$categories_specs = professions::GetAllProfessions(intval($project['category']) ? intval($project['category']) : $categories[0]['id']);
$aCnt = (int) count($tmpPrj->getAttach());
require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/country.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/city.php";
$countries = country::GetCountries();
if ($project['country']) {
    $cities = city::GetCities($project['country']);
}
$project['end_date'] = $_POST['end_date'] ? $_POST['end_date'] : ($project['end_date'] ? date('d-m-Y', strtotime($project['end_date'])) : '');
$project['win_date'] = $_POST['win_date'] ? $_POST['win_date'] : ($project['win_date'] ? date('d-m-Y', strtotime($project['win_date'])) : '');
require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/project_exrates.php";
$oprj_exrates = new project_exrates();
$prj_exrates = $oprj_exrates->GetAll();
$professions = professions::GetAllProfessions();
array_group($professions, 'groupid');
$professions[0] = array();
?>

<?php 
$templates = array(uploader::getTemplate('uploader', 'project/'), uploader::getTemplate('uploader.file', 'project/'), uploader::getTemplate('uploader.popup', ''));
uploader::init(array('attachedfiles' => uploader::sgetLoaderOptions($uploader->resource)), $templates);
?>
<script type="text/javascript">
var draft_saved = 0;
</script>

Esempio n. 14
0
    /**
     * Выделяем главную специализацию по его портфолио.
     *
     * @param integer $count        Вовзрашает Количество
     * @param integer $size         Вовзращает Размер выборки
     * @param integer $frl_pp       Количество портфолио на страницу
     * @param integer $offset       С какой позиции брать из БД
     * @param string  $order        Сортировка
     * @param integer $direction    Тип сортировки (DESC, ASC)
     * @param integer $favorite     Избранное (1, 0)
     * @param boolean $filter_apply Фильтр включен или нет
     * @param integer $filter       Фильтр
     *
     * @return array Данные по выборке
     */
    public function GetSpecPortfMain(&$count, &$size, $frl_pp = PRF_PP, $offset = 0, $order = 'rating', $direction = 0, $favorite = 0, $filter_apply = false, $filter = null)
    {
        global $DB;
        // START rates for convert
        require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/project_exrates.php';
        $project_exRates = project_exrates::GetAll();
        if ($filter['cost_type'] == 1) {
            //euro
            $rates = array(0 => $project_exRates[32], 1 => $project_exRates[33], 2 => $project_exRates[34], 3 => $project_exRates[31]);
        } elseif ($filter['cost_type'] == 2) {
            //rur
            $rates = array(0 => $project_exRates[42], 1 => $project_exRates[43], 2 => $project_exRates[44], 3 => $project_exRates[41]);
        } elseif ($filter['cost_type'] == 3) {
            //FM
            $rates = array(0 => $project_exRates[12], 1 => $project_exRates[13], 2 => $project_exRates[14], 3 => $project_exRates[11]);
        } else {
            //usd
            $rates = array(0 => $project_exRates[22], 1 => $project_exRates[23], 2 => $project_exRates[24], 3 => $project_exRates[21]);
        }
        $rates_sql = '	CASE WHEN p.cost_type=0
			THEN p.cost / ' . $rates[0] . '
			WHEN p.cost_type=1
			THEN p.cost / ' . $rates[1] . '
			WHEN p.cost_type=2
			THEN p.cost / ' . $rates[2] . '
			WHEN p.cost_type=3
			THEN p.cost / ' . $rates[3] . '
			END AS convert_cost';
        //print_r($filter);
        //print_r($rates);
        //echo $rates_sql;
        // END rates for convert
        $ret = array();
        $uid = get_uid(false);
        /**
         * Сортировка.
         */
        $order_orig = $order;
        switch ($order) {
            default:
            case 'rating':
                $order = 'rating DESC, uid, norder';
                break;
            case 'random':
                $order = 'random()';
                break;
            case 'costs':
                $order = '((cost = 0) OR (cost IS NULL)) ASC, convert_cost ' . $dir_sql;
                break;
            case 'opinions':
                $order = 'ssum DESC, uid, norder';
                $user_counters_join = 'LEFT JOIN users_counters uc ON uc.user_id = fu.uid';
                $ssum = ', zin(uc.ops_emp_plus) - zin(uc.ops_emp_minus) as ssum';
                break;
        }
        /**
         * Фильтр.
         */
        $cost_field = 'convert_cost';
        if ($filter_apply) {
            $filter_sql = '';
            if ($filter['cost_from'] > 0 || $filter['cost_to'] > 0) {
                if ($filter['cost_from'] > 0 && $filter['cost_to'] > 0) {
                    $filter_sql .= ($filter_sql != '' ? ' AND ' : '') . '(' . $cost_field . '>=' . $filter['cost_from'] . ' AND ' . $cost_field . '<=' . $filter['cost_to'] . ')';
                } else {
                    if ($filter['cost_from'] > 0) {
                        $filter_sql .= ($filter_sql != '' ? ' AND ' : '') . '(' . $cost_field . '>=' . $filter['cost_from'] . ')';
                    } elseif ($filter['cost_to'] > 0) {
                        $filter_sql .= ($filter_sql != '' ? ' AND ' : '') . '(' . $cost_field . '<=' . $filter['cost_to'] . ')';
                    }
                }
            }
            if ($filter_sql != '') {
                //                $filter_sql = ' WHERE' . $filter_sql;
                $filter_sql = $filter_sql;
            }
        } else {
            $filter_sql = '';
        }
        if (!$filter_sql && $order_orig == 'costs') {
            $filter_sql = $cost_field . ' > 0 ';
        }
        $size = 0;
        $dir_sql = $direction == 0 ? 'DESC' : 'ASC';
        $fav_sql = $favorite == 0 ? '' : ' INNER JOIN portfolio_fav AS pf ON p.id=pf.prf_id AND pf.user_id=' . $uid;
        $sql = "SELECT * FROM (SELECT p.id, p.name, p.descr, p.norder, p.pict, p.prev_pict, p.show_preview, p.cost, p.time_type, p.time_value, p.prev_type, p.cost_type, p.is_video,\n                               fu.uid, fu.login, fu.uname, fu.usurname, rating_get(fu.rating, fu.is_pro, fu.is_verify, fu.is_profi) as rating, {$rates_sql}\n                               {$ssum}\n           FROM fu\n         {$user_counters_join}  \n         INNER JOIN\n           portfolio p\n             ON p.user_id = fu.uid\n            AND p.prof_id = " . professions::BEST_PROF_ID . "\n            AND p.first3 = true\n         {$fav_sql}\n          WHERE fu.is_pro = true\n            AND fu.is_banned = '0') as t" . ($filter_sql ? " WHERE {$filter_sql}" : '') . " ORDER BY {$order}\n          LIMIT ?i OFFSET ?i";
        $ret = $DB->rows($sql, $frl_pp, $offset);
        if ($DB->error) {
            $error = $DB->error;
        } else {
            $size = count($res);
            $sql = "SELECT COUNT(*) FROM (SELECT  id, {$rates_sql}\n               FROM fu\n             INNER JOIN\n               portfolio p\n                 ON p.user_id = fu.uid\n                AND p.prof_id = " . professions::BEST_PROF_ID . "\n                AND p.first3 = true\n             {$fav_sql}\n              WHERE fu.is_pro = true\n                AND fu.is_banned = '0') as t" . ($filter_sql ? " WHERE {$filter_sql}" : '');
            $count = $DB->val($sql);
        }
        return $ret;
    }
Esempio n. 15
0
/**
 * формирует превью проекта на главной странице.
 */
function GetPreview($data)
{
    $objResponse = new xajaxResponse();
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/projects.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/attachedfiles.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/CFile.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/HTML/projects_lenta.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/project_exrates.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/memBuff2.php';
    $kind = 1;
    $memBuff = new memBuff();
    $htmlLenta = $memBuff->get('projectsLentaHTML');
    if (!$htmlLenta) {
        $prj = new new_projects();
        $prjs = $prj->getProjects($num_prjs, -1, 1, false, null, true);
        foreach ($prjs as &$proj) {
            // стираем принадлежность проекта к пользователю, чтобы не появилось кнопок РЕДАКТИРОВАТЬ и пр.
            unset($proj['user_id']);
        }
        unset($proj);
        $htmlPrj = new HTMLProjects();
        $htmlPrj->template = '/projects/tpl.lenta.new.php';
        $prj_content = $htmlPrj->ShowProjects($num_prjs, $prjs, 1, 1, null, true);
        $prfs = new professions();
        $profs = $prfs->GetAllProfessions('', 0, 1);
        // подложка с лентой проектов
        ob_start();
        include $_SERVER['DOCUMENT_ROOT'] . '/templates/main.php';
        $htmlLenta = ob_get_clean();
        // кэшируем ленту проектов
        $memBuff->set('projectsLentaHTML', $htmlLenta, 1800);
    }
    // подготавливаем данные для шаблона в ленту проектов
    $row = array();
    $row['kind'] = __paramValue('int', $data['kind']);
    $row['cost'] = __paramValue('int', $data['cost']);
    $row['currency'] = __paramValue('int', $data['currency_db_id']);
    $row['priceby'] = __paramValue('int', $data['priceby_db_id']);
    $row['name'] = stripslashes(__paramValue('html', $data['name'], null, true));
    $contacts = array('phone' => array('name' => 'Телефон', 'value' => ''), 'site' => array('name' => 'Сайт', 'value' => ''), 'icq' => array('name' => 'ICQ', 'value' => ''), 'skype' => array('name' => 'Skype', 'value' => ''), 'email' => array('name' => 'E-mail', 'value' => ''));
    if (isset($data['contacts'])) {
        foreach ($data['contacts'] as $name => $value) {
            if (!isset($contacts[$name])) {
                continue;
            }
            switch ($name) {
                case 'site':
                    if (!url_validate(ltrim(ltrim($value, 'http://'), 'https://')) && trim($value) != '') {
                        $error["contact_{$name}"] = 'Поле заполнено некорректно';
                    }
                    if (strpos($value, 'htt') === false && trim($value) != '') {
                        $value = 'http://' . $value;
                    }
                    break;
                case 'email':
                    if (!is_email($value) && trim($value) != '') {
                        $error["contact_{$name}"] = 'Поле заполнено некорректно';
                    }
                    break;
            }
            $contacts[$name]['value'] = __paramValue('htmltext', stripslashes($value));
        }
        $row['contacts'] = serialize($contacts);
    }
    $descrFull = stripslashes(__paramValue('html', $data['descr'], null, true));
    $descr = preg_replace('/^ /', "", $descrFull);
    $descr = preg_replace("/(\n) /", "\$1", $descr);
    $descr = reformat(strip_tags(htmlspecialchars(LenghtFormatEx(htmlspecialchars_decode($descr, ENT_QUOTES), 180), ENT_QUOTES), '<br />'), 50, 1, 0, 1);
    $descr = preg_replace("//", '&nbsp;', $descr);
    $row['descr'] = $descr;
    $row['t_is_payed'] = $data['logo_ok'] || $data['top_ok'];
    $row['t_is_ontop'] = __paramValue('bool', $data['top_ok']);
    $row['t_pro_only'] = $data['pro_only'] ? 't' : 'f';
    $row['t_verify_only'] = $data['verify_only'] ? 't' : 'f';
    $row['t_urgent'] = $data['urgent'] ? 't' : 'f';
    $row['t_hide'] = $data['hide'] ? 't' : 'f';
    $row['create_date'] = date('Y-m-d H:i', strtotime(date('Y-m-d H:i:s')) - 120);
    // делаем дату публикации 2 минуты назад
    $row['end_date'] = __paramValue('string', $data['end_date']);
    $row['win_date'] = __paramValue('string', $data['win_date']);
    $row['country'] = __paramValue('int', $data['project_location_columns'][0]);
    $row['city'] = __paramValue('int', $data['project_location_columns'][1]);
    list($row['country_name'], $row['city_name']) = explode(': ', __paramValue('string', $data['location']));
    $logoOK = __paramValue('bool', $data['logo_ok']);
    $topOK = __paramValue('bool', $data['top_ok']);
    $row['link'] = __paramValue('string', $data['link']);
    if ($logoOK) {
        $logoAttach = new attachedfiles($data['logo_attachedfiles_session']);
        $logoFiles = $logoAttach->getFiles(array(1));
        if (count($logoFiles)) {
            $logoFile = array_pop($logoFiles);
            // загружено может быть несколько файлов, берем последний
            $logoCFile = new CFile($logoFile['id']);
        } elseif (__paramValue('int', $data['logo_file_id'])) {
            $logoCFile = new CFile(__paramValue('int', $data['logo_file_id']));
        }
        $row['logo_name'] = $logoCFile->name;
        $row['logo_path'] = $logoCFile->path;
    }
    $is_ajax = true;
    // подготовка данных для подробной страницы проекта
    $project = $row;
    $categories = array();
    for ($i = 0; $i < 3; ++$i) {
        $categoryID = __paramValue('int', $data['project_profession' . $i . '_columns'][0]);
        $subcategoryID = __paramValue('int', $data['project_profession' . $i . '_spec_columns'][0]);
        if ($categoryID || $subcategoryID) {
            $categories[] = array('category_id' => $categoryID, 'subcategory_id' => $subcategoryID);
        }
    }
    $project['spec_txt'] = projects::_getSpecsStr($categories, ' / ', ', ', true);
    $project['ico_payed'] = $logoOK;
    $project['is_upped'] = $topOK;
    $project['descr'] = $descrFull;
    $project['logo_id'] = $logoCFile->id;
    $project['prefer_sbr'] = __paramValue('bool', $data['prefer_sbr']) ? 't' : 'f';
    $project['urgent'] = __paramValue('bool', $data['urgent']) ? 't' : 'f';
    $project['hide'] = __paramValue('bool', $data['hide']) ? 't' : 'f';
    if (trim($project['contacts']) != '') {
        $contacts_employer = unserialize($project['contacts']);
        $empty_contacts_employer = 0;
        foreach ($contacts_employer as $name => $contact) {
            if (trim($contact['value']) == '') {
                $empty_contacts_employer++;
            }
        }
        $is_contacts_employer_empty = count($contacts_employer) == $empty_contacts_employer;
    }
    $isPreview = true;
    $project_exRates = project_exrates::GetAll();
    $translate_exRates = array(0 => 2, 1 => 3, 2 => 4, 3 => 1);
    ob_start();
    include $_SERVER['DOCUMENT_ROOT'] . '/public/new/tpl.preview.php';
    ?>
    <?php 
    $htmlProject = ob_get_clean();
    $objResponse->assign('project_preview_lenta', 'innerHTML', $htmlLenta);
    $objResponse->assign('project_preview_content', 'innerHTML', $htmlProject);
    $objResponse->script('Public.showPreview()');
    return $objResponse;
}
Esempio n. 16
0
 public function getSQLFilterEmployer($filter)
 {
     global $DB;
     // Аккаунт
     if (isset($filter['filter_emp'])) {
         $main_sql[] = "e.active = true AND substring(e.subscr from 8 for 1)::integer = 1 AND e.is_banned = B'0'";
         if ($filter['etype_account'][0] == 1) {
             $sql[] = "e.is_pro = true";
         }
         if ($filter['etype_account'][1] == 1) {
             $sql[] = "e.is_pro = false";
         }
         if (sizeof($sql) == 1) {
             $main_sql[] = self::setMainWhereSQL($sql);
         }
         $sql = array();
         // Профиль
         if ($filter['etype_profile'][0] == 1) {
             $sql[] = "r.o_inf_factor > 0";
         }
         if ($filter['etype_profile'][1] == 1) {
             $sql[] = "r.o_inf_factor = 0";
         }
         if (sizeof($sql) == 1) {
             $inner_sql['rating'] = "LEFT JOIN rating r ON r.user_id = f.uid";
             $main_sql[] = self::setMainWhereSQL($sql);
         }
         $sql = array();
         // Зарегистрирован
         if ($filter['efrom_regdate']) {
             $date = date('Y-m-d', strtotime($filter['efrom_regdate']));
             $sql[] = "e.reg_date >= DATE '{$date}'";
         }
         if ($filter['eto_regdate']) {
             $date = date('Y-m-d', strtotime($filter['eto_regdate']));
             $sql[] = "e.reg_date <= DATE '{$date}'";
         }
         if ($sql) {
             $main_sql[] = self::setMainWhereSQL($sql, "AND");
         }
         //" ( ".implode(" AND ", $freg)." )\r\n";
         // Последний визит
         if ($filter['efrom_lastvisit']) {
             $date = date('Y-m-d', strtotime($filter['efrom_lastvisit']));
             $sql[] = "e.last_time >= DATE '{$date}'";
         }
         if ($filter['eto_lastvisit']) {
             $date = date('Y-m-d', strtotime($filter['eto_lastvisit']));
             $sql[] = "e.last_time <= DATE '{$date}'";
         }
         if ($sql) {
             $main_sql[] = self::setMainWhereSQL($sql, "AND");
         }
         //Пол
         if ($filter['etype_sex'][0] == 1) {
             $sql[] = "e.sex = true";
         }
         if ($filter['etype_sex'][1] == 1) {
             $sql[] = "e.sex = false";
         }
         if (sizeof($sql) == 1) {
             $main_sql[] = self::setMainWhereSQL($sql);
         }
         $sql = array();
         if ($main_sql) {
             $main_where = self::setMainWhereSQL($main_sql, "AND \r\n");
         }
         //Финансы
         if ($filter['efinance']) {
             $finance = $filter['efinance'];
             // Денег на счету
             if ($finance['money']) {
                 $inner_sql['account'] = "INNER JOIN account a ON a.uid = f.uid";
                 $union_sql[] = $DB->parse("a.sum <= ?", $finance['money']);
             }
             // Последнее списание
             if ($finance['spend'][0]) {
                 $date = date('Y-m-d', strtotime($finance['spend'][0]));
                 $sql[] = "ao.op_date >= DATE '{$date}'";
             }
             if ($finance['spend'][1]) {
                 $date = date('Y-m-d', strtotime($finance['spend'][1]));
                 $sql[] = "ao.op_date <= DATE '{$date}'";
             }
             if ($sql) {
                 $sql[] = "ao.ammount <= 0";
                 $union_sql[] = self::setMainWhereSQL($sql, "AND");
             }
             // Последнее пополнение
             if ($finance['deposit'][0]) {
                 $date = date('Y-m-d', strtotime($finance['deposit'][0]));
                 $sql[] = "ao.op_date >= DATE '{$date}'";
             }
             if ($finance['deposit'][1]) {
                 $date = date('Y-m-d', strtotime($finance['deposit'][1]));
                 $sql[] = "ao.op_date <= DATE '{$date}'";
             }
             if ($sql) {
                 $sql[] = "ao.ammount > 0";
                 $union_sql[] = self::setMainWhereSQL($sql, "AND");
             }
             if ($union_sql) {
                 $union_sql[] = self::setMainWhereSQL($union_sql);
             }
             //"( " . implode(" OR ", $ffsql). " )";
             //Способ пополнения счета
             if ($finance['method_deposit'][0] == 1) {
                 $sql[] = "ao.payment_sys = 3";
             }
             if ($finance['method_deposit'][1] == 1) {
                 $sql[] = "ao.payment_sys IN (1,2,10)";
             }
             if ($finance['method_deposit'][2] == 1) {
                 $sql[] = "ao.payment_sys = 7";
             }
             if ($finance['method_deposit'][3] == 1) {
                 $sql[] = "ao.payment_sys IN (4,5,6,11)";
             }
             if (sizeof($sql) != 4 && $sql) {
                 $union_sql[] = self::setMainWhereSQL($sql);
             }
             $sql = array();
             if ($union_sql) {
                 $where = self::setMainWhereSQL($union_sql, "AND");
             }
             if ($where && $main_where) {
                 $where .= " AND ( {$main_where} )";
             } else {
                 if ($main_where) {
                     $where = " ( {$main_where} )";
                 }
             }
             $union[] = "SELECT DISTINCT a.uid FROM \n                                account a\n                            INNER JOIN employer e ON e.uid = a.uid \n                            LEFT JOIN rating r ON r.user_id = e.uid\n                            INNER JOIN account_operations ao ON ao.billing_id = a.id\n                            " . ($where ? " WHERE {$where}" : '') . "\n                            GROUP BY a.uid";
             unset($where);
         }
         // Покупки
         if ($filter['ebuying']) {
             $buying = $filter['ebuying'];
             // Количество покупок
             if ($buying['buying'][0] == 1) {
                 $sql[] = "ao.id IS NULL";
             }
             if ($buying['buying'][1] == 1) {
                 $sql[] = "ao.id IS NOT NULL";
             }
             if (sizeof($sql) == 1) {
                 $inner_sql['account'] = "INNER JOIN account a ON a.uid = f.uid";
                 $inner_sql['acc_operations'] = "LEFT JOIN account_operations ao ON ao.billing_id = a .id";
                 $sql[] = self::setMainWhereSQL($sql);
             } else {
                 $sql = array();
             }
             // Последнее пополнение
             if ($buying['period'][0]) {
                 $date = date('Y-m-d', strtotime($buying['period'][0]));
                 $sql[] = "ao.op_date >= DATE '{$date}'";
             }
             if ($buying['period'][1]) {
                 $date = date('Y-m-d', strtotime($buying['period'][1]));
                 $sql[] = "ao.op_date <= DATE '{$date}'";
             }
             if ($sql) {
                 $sub_where = self::setMainWhereSQL($sql, "AND");
             }
             //Покупки
             if ($buying['buy']) {
                 foreach ($buying['buy'] as $key => $val) {
                     if ($val['type_buy'] > 0) {
                         $sql[] = $DB->parse("op_code = ?", $val['type_buy']);
                     }
                     if ($val['count_buy'][0] > 0) {
                         $sql[] = $DB->parse("cnt >= ?", $val['count_buy'][0]);
                     }
                     if ($val['count_buy'][1] > 0) {
                         $sql[] = $DB->parse("cnt <= ?", $val['count_buy'][1]);
                     }
                     if ($val['sum'][0] > 0) {
                         $sql[] = $DB->parse("ammount >= ?", $val['sum'][0]);
                     }
                     if ($val['sum'][1] > 0) {
                         $sql[] = $DB->parse("ammount <= ?", $val['sum'][1]);
                     }
                     if ($sql) {
                         $union_sql[] = self::setMainWhereSQL($sql, "AND");
                     }
                 }
                 if ($union_sql) {
                     $where = self::setMainWhereSQL($union_sql);
                 }
             }
             if ($sub_where && $main_where) {
                 $sub_where .= " AND ( {$main_where} )";
             } else {
                 if ($main_where) {
                     $sub_where = " ( {$main_where} )";
                 }
             }
             $union[] = "SELECT DISTINCT uid FROM (\n                                SELECT \n                                    COUNT(*) as cnt, \n                                    ABS(SUM(ammount)) as ammount, a.uid, op_code \n                                FROM \n                                    account a\n                                INNER JOIN employer e ON e.uid = a.uid\n                                LEFT JOIN rating r ON r.user_id = e.uid\n                                INNER JOIN account_operations ao ON ao.billing_id = a.id\n                                " . ($sub_where ? "WHERE " . $sub_where : "") . " \n                                GROUP BY a.uid, op_code) as tbl\n                            " . ($where ? " WHERE {$where}" : '');
             unset($where, $sub_where);
         }
         // Проекты
         if ($filter['eproject']) {
             $eproject = $filter['eproject'];
             require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/project_exrates.php";
             $project_exRates = project_exrates::GetAll();
             // Последнее пополнение
             if ($eproject['period'][0]) {
                 $date = date('Y-m-d', strtotime($eproject['period'][0]));
                 $sql[] = "p.post_date >= DATE '{$date}'";
             }
             if ($eproject['period'][1]) {
                 $date = date('Y-m-d', strtotime($eproject['period'][1]));
                 $sql[] = "p.post_date <= DATE '{$date}'";
             }
             if ($sql) {
                 $subunion_sql[] = self::setMainWhereSQL($sql, "AND");
             }
             // Создал проектов
             if ($eproject['created'][0]) {
                 $sql[] = $DB->parse("all_cnt >= ?", $eproject['created'][0]);
             }
             if ($eproject['created'][1]) {
                 $sql[] = $DB->parse("all_cnt <= ?", $eproject['created'][1]);
             }
             if ($sql) {
                 $union_sql[] = self::setMainWhereSQL($sql, "AND");
             }
             // Фри-ланс
             if ($eproject['freelance'][0]) {
                 $sql[] = $DB->parse("frl_cnt >= ?", $eproject['freelance'][0]);
             }
             if ($eproject['freelance'][1]) {
                 $sql[] = $DB->parse("frl_cnt <= ?", $eproject['freelance'][1]);
             }
             if ($sql) {
                 $union_sql[] = self::setMainWhereSQL($sql, "AND");
             }
             // Только для ПРО
             if ($eproject['only_pro'][0]) {
                 $sql[] = $DB->parse("pro_cnt >= ?", $eproject['only_pro'][0]);
             }
             if ($eproject['only_pro'][1]) {
                 $sql[] = $DB->parse("pro_cnt <= ?", $eproject['only_pro'][1]);
             }
             // В оффис
             if ($eproject['in_office'][0]) {
                 $sql[] = $DB->parse("office_cnt >= ?", $eproject['in_office'][0]);
             }
             if ($eproject['in_office'][1]) {
                 $sql[] = $DB->parse("office_cnt <= ?", $eproject['in_office'][1]);
             }
             if ($sql) {
                 $union_sql[] = self::setMainWhereSQL($sql, "AND");
             }
             // Конкурсы
             if ($eproject['konkurs'][0]) {
                 $sql[] = $DB->parse("konk_cnt >= ?", $eproject['konkurs'][0]);
             }
             if ($eproject['konkurs'][1]) {
                 $sql[] = $DB->parse("konk_cnt <= ?", $eproject['konkurs'][1]);
             }
             if ($sql) {
                 $union_sql[] = self::setMainWhereSQL($sql, "AND");
             }
             // Бюджет каждого проекта
             $cr = 2;
             $cex = array(2, 3, 4, 1);
             if (($cost_from = (double) $eproject['budget'][0]) < 0) {
                 $cost_from = 0;
             }
             if (($cost_to = (double) $eproject['budget'][1]) < 0) {
                 $cost_to = 0;
             }
             if ($cost_to < $cost_from && $cost_to != 0) {
                 $cost_to = $cost_from;
             }
             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);
                     $sql[] = $DB->parse("(currency = ? AND cost >= ?", $i, $exfr) . ($cost_to ? $DB->parse(" AND cost <= ?", $exto) : '') . ')';
                 }
             }
             if ($sql) {
                 $subunion_sql[] = self::setMainWhereSQL($sql, "OR");
             }
             // Сум. бюджета всех проектов
             if ($eproject['sum_budget'][0]) {
                 $sql[] = $DB->parse("sum_budget >= ?", $eproject['sum_budget'][0]);
             }
             if ($eproject['sum_budget'][1]) {
                 $sql[] = $DB->parse("sum_budget <= ?", $eproject['sum_budget'][1]);
             }
             if ($sql) {
                 $union_sql[] = self::setMainWhereSQL($sql, "AND");
             }
             // Ответы на проекты
             if ($eproject['avg_answer'][0]) {
                 $sql[] = $DB->parse("answers >= ?", $eproject['avg_answer'][0]);
             }
             if ($eproject['avg_answer'][1]) {
                 $sql[] = $DB->parse("answers <= ?", $eproject['avg_answer'][1]);
             }
             if ($sql) {
                 $union_sql[] = self::setMainWhereSQL($sql, "AND");
             }
             // Ответы на проекты
             if ($eproject['executor'][0] == 1) {
                 $sql[] = "budget_type = 3";
             }
             if ($eproject['executor'][1] == 1) {
                 $sql[] = "budget_type = 2";
             }
             if ($eproject['executor'][2] == 1) {
                 $sql[] = "budget_type = 1";
             }
             if ($sql) {
                 $subunion_sql[] = self::setMainWhereSQL($sql);
             }
             $sub_where = self::setMainWhereSQL($subunion_sql, "AND");
             if ($sub_where && $main_where) {
                 $sub_where .= " AND ( {$main_where} )";
             } else {
                 if ($main_where) {
                     $sub_where = " ( {$main_where} )";
                 }
             }
             $where = self::setMainWhereSQL($union_sql, "AND");
             $union[] = "SELECT user_id as uid FROM (\n                                SELECT \n                                    SUM(1) as all_cnt,\n                                    SUM(CASE WHEN kind = 7 OR kind = 2 THEN 1 ELSE 0 END) as konk_cnt,\n                                    SUM(CASE WHEN kind = 1 THEN 1 ELSE 0 END) as frl_cnt,\n                                    SUM(CASE WHEN pro_only = true THEN 1 ELSE 0 END) as pro_cnt,\n                                    SUM(CASE WHEN kind = 4 THEN 1 ELSE 0 END) as office_cnt,\n                                    SUM(CASE WHEN po.id IS NOT NULL THEN 1 ELSE 0 END) as answers,\n                                    SUM(\n                                        CASE WHEN currency = 0 THEN cost * {$project_exRates[24]}\n                                        WHEN currency  = 1 THEN cost * {$project_exRates[34]}\n                                        WHEN currency = 3 THEN cost * {$project_exRates[14]}\n                                        ELSE cost END\n                                    ) as sum_budget,\n                                    p.user_id\n                                FROM projects p\n                                INNER JOIN employer e ON e.uid = p.user_id\n                                LEFT JOIN rating r ON r.user_id = e.uid\n                                LEFT JOIN projects_offers po ON po.project_id = p.id\n                                " . ($sub_where ? "WHERE " . $sub_where : "") . "   \n                                GROUP BY p.user_id\n                            ) t " . ($where ? "WHERE {$where}" : "");
             unset($where, $sub_where);
         }
         if ($filter['emassend']) {
             $emassend = $filter['emassend'];
             if ($emassend['spec'] > 0) {
                 $union_inner = "LEFT JOIN mass_sending_profs msp ON msp.mass_sending_id = ms.id";
                 $union_sql[] = $DB->parse("msp.prof_id = ?", $emassend['spec']);
             }
             if ($emassend['recipients'][0] > 0) {
                 $sql[] = $DB->parse("ms.all_count >= ?", $emassend['recipient'][0]);
             }
             if ($emassend['recipients'][1] > 0) {
                 $sql[] = $DB->parse("ms.all_count <= ?", $emassend['recipient'][1]);
             }
             if ($sql) {
                 $union_sql[] = self::setMainWhereSQL($sql, "AND");
             }
             $where = self::setMainWhereSQL($union_sql, "AND");
             if ($where && $main_where) {
                 $where .= " AND ( {$main_where} )";
             } else {
                 if ($main_where) {
                     $where = " ( {$main_where} )";
                 }
             }
             if ($where) {
                 $union[] = "SELECT \n                                    ms.user_id as uid\n                                FROM \n                                mass_sending ms\n                                INNER JOIN employer e ON e.uid = ms.user_id\n                                LEFT JOIN rating r ON r.user_id = e.uid\n                                " . ($union_inner ? $union_inner : "") . " \n                                " . ($where ? "WHERE {$where}" : "");
                 unset($where, $union_inner);
             }
         }
         if ($main_where) {
             $union[] = "SELECT \n                            DISTINCT ON (e.uid) e.uid \n                        FROM  employer e\n                        LEFT JOIN rating r ON r.user_id = e.uid\n                        " . ($main_where ? "WHERE {$main_where}" : "");
         }
         if ($union) {
             return implode("\r\nINTERSECT\r\n", $union);
         } else {
             return "SELECT uid FROM employer e WHERE e.active = true AND substring(e.subscr from 8 for 1)::integer = 1 AND e.is_banned = B'0'";
         }
     } else {
         $sql = "SELECT uid FROM employer e WHERE e.active = true AND substring(e.subscr from 8 for 1)::integer = 1 AND e.is_banned = B'0'";
         return $sql;
     }
 }
 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']));
     }
 }
Esempio n. 18
0
 /**
  * Инициализирует форму новой СБР по заданному проекту (из таблицы projects).
  *
  * @param int     $project_id ид. проекта.
  * @param inetger $exec_id    ИД Исполнителя СБР
  */
 public function initFromProject($project_id, $exec_id = false)
 {
     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/professions.php';
     $this->checkProject($project_id);
     if (!$this->error['project_id']) {
         $this->data['project_id'] = $this->project['id'];
         $this->data['name'] = $this->project['name'];
         $this->data['frl_id'] = $exec_id ? $exec_id : $this->project['exec_id'];
         $stage = new sbr_stages($this);
         $this->stages = array($stage);
         $stage->data['name'] = $this->project['name'];
         $stage->data['descr'] = $this->project['descr'];
         $allSpecs = projects::getProjectCategories($this->project['id']);
         $this->data['professions'] = $allSpecs;
         foreach ($this->data['professions'] as &$spec) {
             $spec['prof_name'] = $spec['subcategory_id'] ? professions::GetProfNameWP($spec['subcategory_id'], ': ', '', false) : professions::GetGroupName($spec['category_id']);
         }
         unset($spec);
         $stage->data['category'] = $allSpecs[0]['category_id'];
         //$this->project['category'];
         $stage->data['sub_category'] = $allSpecs[0]['subcategory_id'];
         //$this->project['subcategory'];
         $cost = $this->project['cost'];
         $cex = array(project_exrates::USD, project_exrates::EUR, project_exrates::RUR, project_exrates::FM);
         // конвертер кода projects.currency в коды project_exrates.
         $ccex = $cex[$this->project['currency']];
         switch ($ccex) {
             case project_exrates::RUR:
                 $cost_sys = exrates::BANK;
                 break;
             case project_exrates::FM:
             case project_exrates::EUR:
             case project_exrates::USD:
                 $prj_exrates = project_exrates::GetAll(false);
                 $cost_sys = exrates::BANK;
                 $cost *= $prj_exrates[$ccex . project_exrates::RUR];
                 break;
         }
         $stage->data['cost'] = (int) $cost === 0 ? '' : $cost;
         $this->data['cost_sys'] = $cost_sys;
         if ($this->project['attach']) {
             $stage->data['attach'] = $this->project['attach'];
         }
         return true;
     }
     return false;
 }
Esempio n. 19
0
}
$rating = new rating();
if (date('H') == 1) {
    //$rating = new rating();
    //$log->TRACE( $rating->calcDaily() );
    $log->TRACE($rating->calcMonthly());
}
$log->TRACE($rating->calcDaily());
// перенесено в /minutly.php
/*if(date('H') >= 0 && date('H') <= 5) { 
    // разморозка ПРО
    $log->TRACE( payed::freezeUpdateProUsers() );
}*/
if (date('H') == 0) {
    //Пересчет курсов на основании курсов валют ЦБ
    $log->TRACE(project_exrates::updateCBRates());
    // Уведомление о разбане на сайте
    $log->TRACE($mail->sendReminderUsersUnBan(1));
    // за 1 день до
    // Напоминание о необходимости активирвать аккаунт через два дня после регистрации
    $log->TRACE($mail->activateAccountNotice());
    //
}
// отправляем уведомления о новых топиках в сообществах.
$log->TRACE($mail->CommuneNewTopic());
// Рассылка по базе контактов в /siteadmin/contacts
$log->TRACE($mail->SendMailToContacts());
/*
 * Рассылка новый проектов фрилансерам
 * @depricated: перенесена в отдельный крон /hourly_newsletter_frl.php
 *
Esempio n. 20
0
 /**
  * Обработка информации шага проекты.
  */
 public function actionProjects()
 {
     $prj_id = $_SESSION['view_wizard_project'];
     if (!$prj_id) {
         require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/attachedfiles.php';
         require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/project_exrates.php';
         require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/professions.php';
         require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/projects.php';
         require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/country.php';
         require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/city.php';
         $prj_exrates = project_exrates::GetAll();
         $categories = professions::GetAllGroupsLite();
         $professions = professions::GetAllProfessions();
         array_group($professions, 'groupid');
         $professions[0] = array();
         $addedPrc = is_pro() ? 0 : new_projects::PRICE_ADDED;
         $colorPrc = new_projects::PRICE_COLOR * ($addedPrc > 0 ? 1 : 0);
         $boldPrc = new_projects::PRICE_BOLD + $addedPrc;
         $logoPrc = new_projects::PRICE_LOGO + $addedPrc;
         $cTopPrice = new_projects::PRICE_CONTEST_TOP1DAY + $addedPrc;
         $pTopPrice = new_projects::PRICE_TOP1DAY + $addedPrc;
         $action = __paramInit('string', 'action', 'action', null);
         $attachedfiles_session = __paramInit('string', 'attachedfiles_session', 'attachedfiles_session', false);
         // проверяем есть ли уже созданый проект
         $projects = $this->getCreatedProjects();
         $existPrjID = count($projects) > 0 ? $projects[0][id] : null;
         // выводим ранее сохраненный проект
         if ($action != 'create_project' && $existPrjID) {
             $data = $projects[0];
             list($category, $subcategory) = explode('|', $data['categories']);
             $currency_name = $this->CURRENCY_TYPE[$data['currency']];
             $priceby_name = $this->PRICEBY_TYPE[$data['priceby']];
             $data['pro_only'] = $data['pro_only'] === 't';
             $price = $data['payed'];
             $option = array();
             $option['top'] = $data['top_count'] > 0;
             $option['top_count'] = $data['top_count'];
             $option['color'] = $data['is_color'] === 't';
             $option['bold'] = $data['is_bold'] === 't';
             $option['logo'] = $data['logo_id'] > 0;
         } elseif ($action == 'create_project') {
             // сохраняем новый проект или изменяем старый
             $in_office = __paramInit('int', null, 'in_office', 0);
             $type = __paramInit('string', null, 'kind');
             if ($type == 'contest') {
                 $data['kind'] = 7;
                 $data['end_date'] = date('d-m-Y', strtotime(__paramInit('string', null, 'end_date_eng_format', 0)));
                 $data['win_date'] = date('d-m-Y', strtotime(__paramInit('string', null, 'win_date_eng_format', 0)));
             } elseif ($in_office == 1) {
                 $location = __paramInit('integer', null, 'location_column_id');
                 if ($location == 1) {
                     $data['city'] = __paramInit('integer', null, 'location_db_id');
                     $data['country'] = country::getCountryByCityId($data['city']);
                 } else {
                     $data['country'] = __paramInit('integer', null, 'location_db_id');
                 }
                 $data['kind'] = 4;
             } else {
                 $data['kind'] = 1;
             }
             $data['name'] = __paramInit('string', null, 'name');
             $data['descr'] = __paramInit('string', null, 'descr');
             $category = __paramInit('int', null, 'r_category');
             $subcategory = __paramInit('int', null, 'r_subcategory');
             $agreement = __paramInit('int', null, 'agreement', 0);
             $data['pro_only'] = __paramInit('int', null, 'pro_only', 0) == 1 ? true : false;
             if ($agreement != 1) {
                 $data['cost'] = __paramInit('int', null, 'cost', 0);
                 $data['priceby'] = __paramInit('int', null, 'r_priceby', 0);
                 $data['currency'] = __paramInit('int', null, 'r_currency', 0);
                 $data['budget_type'] = __paramInit('int', null, 'budget_type', 0);
             }
             if (is_empty_html($data['descr'])) {
                 $error['descr'] = 'Поле не заполнено';
             }
             if (is_empty_html($data['name'])) {
                 $error['name'] = 'Поле не заполнено';
             }
             // проверяем длину необработанной строки, а иначе спецсимволы считаются как несколько символов
             if (strlen(stripslashes($_POST['name'])) > 60) {
                 $error['name'] = 'Превышен лимит - 60 символов';
             }
             if (!$category) {
                 $error['category'] = 'Не выбран раздел';
             } elseif ($subcategory) {
                 $data['categories'] = "{$category}|{$subcategory}";
             } else {
                 $data['categories'] = $category;
             }
             if ($data['cost'] < 0) {
                 $error['cost'] = 'Введите положительную сумму';
             }
             if ($data['cost'] > 999999) {
                 $error['cost'] = 'Слишком большая сумма';
             }
             if ($data['cost'] > 0 && ($data['currency'] < 0 || $data['currency'] > 3)) {
                 $error['currency'] = 'Валюта не определена';
             }
             if ($data['cost'] > 0 && ($data['priceby'] < 1 || $data['priceby'] > 4)) {
                 $error['priceby'] = 'Вид бюджета не определен';
             }
             $descr_limit = projects::LIMIT_DESCR;
             if (strlen_real($data['descr']) > $descr_limit) {
                 $error['descr'] = "Исчерпан лимит символов ({$descr_limit})";
             }
             if ($data['kind'] == 7) {
                 if (!preg_match("/^([0-9]{1,2})\\-([0-9]{1,2})\\-([0-9]{4})\$/", $data['end_date'], $o1) || !checkdate($o1[2], $o1[1], $o1[3])) {
                     $error['end_date'] = 'Неправильная дата';
                 }
                 if (!preg_match("/^([0-9]{1,2})\\-([0-9]{1,2})\\-([0-9]{4})\$/", $data['win_date'], $o2) || !checkdate($o2[2], $o2[1], $o2[3])) {
                     $error['win_date'] = 'Неправильная дата';
                 }
                 if (!$error['end_date'] && mktime(0, 0, 0, $o1[2], $o1[1], $o1[3]) <= mktime(0, 0, 0)) {
                     $error['end_date'] = 'Дата окончания конкурса не может находиться  в прошлом';
                 }
                 if (!$error['win_date'] && mktime(0, 0, 0, $o2[2], $o2[1], $o2[3]) <= mktime(0, 0, 0, $o1[2], $o1[1], $o1[3])) {
                     $error['win_date'] = 'Дата определения победителя должна быть больше даты окончания конкурса';
                 }
             }
             $option['top'] = __paramInit('int', null, 'option_top', 0);
             $option['top_count'] = __paramInit('int', null, 'option_top_count', 0);
             $option['color'] = __paramInit('int', null, 'option_color', 0);
             $option['bold'] = __paramInit('int', null, 'option_bold', 0);
             $option['logo'] = __paramInit('int', null, 'option_logo', 0);
             // логотип
             if ($option['logo'] == 1) {
                 $data['logo_link'] = str_replace('http://', '', __paramInit('string', null, 'logo_link', null));
                 $data['logo_id'] = __paramInit('int', null, 'logo_id', null);
                 // если выбрана опция "Логотип со ссылкой", то картинка должна быть обязательно
                 if (!$data['logo_id']) {
                     $error['logo_image'] = 'Отсутствует логотип';
                 }
                 if ($data['logo_link'] === 'Адрес сайта') {
                     $data['logo_link'] = '';
                 }
                 if ($data['logo_link'] !== '' && !is_url($data['logo_link'])) {
                     $error['logo_link'] = 'Не верно введен адрес';
                 }
             } else {
                 $data['logo_id'] = null;
             }
             $price = 0;
             // закрепление на верху
             if ($option['top'] == 1 && $option['top_count'] > 0) {
                 if ($option['top_count'] > 999) {
                     $option['top_count'] = 999;
                 }
                 $price = (int) $option['top_count'] * ($data['kind'] == 7 ? $cTopPrice : $pTopPrice);
                 $data['top_count'] = (int) $option['top_count'];
                 $pay_option[] = array('wiz_uid' => $this->getWizardUserID(), 'op_code' => new_projects::OPCODE_PAYED, 'option' => self::PROJECT_OPTION_TOP, 'type' => $data['kind'] == 7 ? self::BILL_TYPE_CONTEST : self::BILL_TYPE_PROJECT, 'ammount' => $price);
             } else {
                 $data['top_count'] = 0;
             }
             // выделение цветом
             if ($option['color'] == 1) {
                 $price += (int) $colorPrc;
                 $data['is_color'] = true;
                 $pay_option[] = array('wiz_uid' => $this->getWizardUserID(), 'op_code' => new_projects::OPCODE_PAYED, 'option' => self::PROJECT_OPTION_COLOR, 'type' => $data['kind'] == 7 ? self::BILL_TYPE_CONTEST : self::BILL_TYPE_PROJECT, 'ammount' => $colorPrc);
             } else {
                 $data['is_color'] = false;
             }
             // выделение жирным
             if ($option['bold'] == 1) {
                 $price += (int) $boldPrc;
                 $data['is_bold'] = true;
                 $pay_option[] = array('wiz_uid' => $this->getWizardUserID(), 'op_code' => new_projects::OPCODE_PAYED, 'option' => self::PROJECT_OPTION_BOLD, 'type' => $data['kind'] == 7 ? self::BILL_TYPE_CONTEST : self::BILL_TYPE_PROJECT, 'ammount' => $boldPrc);
             } else {
                 $data['is_bold'] = false;
             }
             if ($option['logo'] == 1) {
                 $price += (int) $logoPrc;
                 $pay_option[] = array('wiz_uid' => $this->getWizardUserID(), 'op_code' => new_projects::OPCODE_PAYED, 'option' => self::PROJECT_OPTION_LOGO, 'type' => $data['kind'] == 7 ? self::BILL_TYPE_CONTEST : self::BILL_TYPE_PROJECT, 'ammount' => $logoPrc);
             }
             if ($price > 0) {
                 $data['payed'] = (int) $price;
             }
             if (!$error) {
                 $data['wiz_uid'] = $this->getWizardUserID();
                 // если проект уже есть
                 if ($existPrjID) {
                     // то просто обновляем его
                     $prj_id = $this->updateProject($data, $existPrjID);
                     // и очищаем все платные опции для этого проекта
                     wizard_billing::clearPayedOptions($prj_id);
                 } else {
                     $prj_id = $this->createProject($data);
                 }
                 if ($prj_id && $_POST['attachedfiles_session']) {
                     $attachedfiles = new attachedfiles($_POST['attachedfiles_session']);
                     $files = $attachedfiles->getFiles(array(1, 2, 3, 4));
                     $this->parent->addAttachedFiles($files, $prj_id);
                     $attachedfiles->clear();
                 }
                 if ($prj_id && $data['kind'] == 7) {
                     $insert = array('wiz_uid' => $data['wiz_uid'], 'op_code' => new_projects::OPCODE_KON_NOPRO, 'type' => self::BILL_TYPE_CONTEST, 'ammount' => new_projects::getKonkursPrice(), 'parent' => $prj_id);
                     wizard_billing::addPaidOption($insert);
                 }
                 if ($price > 0 && $prj_id) {
                     foreach ($pay_option as $k => $opt) {
                         $opt['parent'] = $prj_id;
                         wizard_billing::addPaidOption($opt);
                     }
                 }
                 if ($prj_id) {
                     $_SESSION['view_wizard_project'] = $prj_id;
                     header('Location: /wizard/registration/');
                     exit;
                 } else {
                     $error['project'] = 'Ошибка записи проекта';
                 }
             }
             $currency_name = __paramInit('string', null, 'currency');
             $priceby_name = __paramInit('string', null, 'priceby');
         }
         // Генерируем данные для вывода ошибок и заполнения полей
         $loc[] = country::GetCountryName($data['country']);
         if ($data['city']) {
             $loc[] = city::GetCityName($data['city']);
         }
         $location_name = implode(': ', $loc);
         $cat[] = professions::GetGroupName($category);
         if ($subcategory) {
             $cat[] = professions::GetProfName($subcategory);
         }
         $category_name = implode(': ', $cat);
         if ($data['logo_id']) {
             $file = new CFile($data['logo_id']);
             $logo_path = WDCPREFIX . '/' . $file->path . $file->name;
         }
         include $_SERVER['DOCUMENT_ROOT'] . '/wizard/registration/steps/tpl.step.project.php';
     } else {
         $project = $this->getProjectById($prj_id);
         $attached = $this->getProjectAttach($prj_id);
         include $_SERVER['DOCUMENT_ROOT'] . '/wizard/registration/steps/tpl.step.project.view.php';
     }
 }