Esempio n. 1
0
 /**
  * Инициализация тизера.
  *
  * @global array $js_file
  *
  * @param array $options [kind, uid]
  */
 public function init($options = array())
 {
     global $js_file;
     $js_file[] = 'tservices/tservices_binds.js';
     if ($options) {
         $this->kind = (int) $options['kind'];
         $this->uid = (int) $options['uid'];
     }
     $time_to = time() + 7 * 86400;
     $use_bind_popup = false;
     $tu_bind_teaser = array('date' => date('j', $time_to) . ' ' . monthtostr(date('n', $time_to), true), 'href' => 'javascript:void(0);');
     $tservices_binds = new tservices_binds($this->kind);
     $tservices_class = new tservices($this->uid);
     $profs = array();
     if ($this->kind == tservices_binds::KIND_SPEC) {
         $profs[] = $this->prof_id;
     } elseif ($this->kind == tservices_binds::KIND_GROUP) {
         $tservices_categories = new tservices_categories();
         $categories = $tservices_categories->getCategoriesByParent($this->prof_id);
         foreach ($categories as $category) {
             $profs[] = $category['id'];
         }
     }
     if ($countBindedTu = $tservices_binds->countBindedTu($this->uid, (int) $this->prof_id)) {
         $binded_text = ending($countBindedTu, 'ваша услуга', 'ваши услуги', 'ваших услуг');
         $tu_bind_teaser['subtitle'] = $countBindedTu . ' ' . $binded_text . ' уже <br>закреплен' . ($countBindedTu > 1 ? 'ы' : 'а') . ' в этом разделе';
         if ($tservices_class->hasUnbindedTservices($this->kind, $this->uid, $profs)) {
             $use_bind_popup = true;
             $tu_bind_teaser['title'] = 'Закрепите еще одну услугу';
             $tu_bind_teaser['btn_text'] = 'Закрепить';
         } else {
             $tu_bind_teaser['title'] = 'Добавьте еще одну услугу<br>и закрепите ее здесь';
             $tu_bind_teaser['href'] = '/users/' . $_SESSION['login'] . '/tu/new/';
             $tu_bind_teaser['btn_text'] = 'Добавить';
         }
     } else {
         if ($tservices_class->hasUserTservice(true, $profs)) {
             $use_bind_popup = true;
             $tu_bind_teaser['title'] = 'Закрепите здесь услугу';
             $tu_bind_teaser['btn_text'] = 'Закрепить';
         } else {
             $tu_bind_teaser['title'] = 'Добавьте свою услугу<br>и закрепите ее здесь';
             $tu_bind_teaser['href'] = '/users/' . $_SESSION['login'] . '/tu/new/';
             $tu_bind_teaser['btn_text'] = 'Добавить';
         }
     }
     if ($use_bind_popup) {
         quickPaymentPopupTservicebind::getInstance()->init(array('uid' => $this->uid, 'kind' => $this->kind, 'prof_id' => $this->prof_id));
         $tu_bind_teaser['popup_id'] = quickPaymentPopupTservicebind::getInstance()->getPopupId(0);
         $tu_bind_teaser['popup'] = quickPaymentPopupTservicebind::getInstance()->render();
     }
     $this->data = $tu_bind_teaser;
     $this->data['price'] = $tservices_binds->getPrice(false, $this->uid, $this->prof_id);
     $this->data['main_div_class'] = $this->kind == tservices_binds::KIND_LANDING ? 'b-layout__tu-cols b-layout__tu-cols_height_330' : 'i-pic i-pic_port i-pic_width_225 i-pic_margbot_30';
 }
Esempio n. 2
0
 /**
  * Инициализация тизера.
  *
  * @global array $js_file
  *
  * @param array $options [kind, uid]
  */
 public function init($options = array())
 {
     if ($options) {
         $this->kind = (int) $options['kind'];
         $this->uid = (int) $options['uid'];
     }
     $this->data = array();
     $tservices_binds = new tservices_binds($this->kind);
     $this->data['bind_up_price'] = $tservices_binds->getPrice(true, $this->uid);
     $this->data['date_stop'] = dateFormat('j', $this->date_stop) . ' ' . monthtostr(dateFormat('m', $this->date_stop), true);
     $this->data['allow_up'] = $this->allow_up;
     $this->data['tservice_id'] = $this->tservice_id;
 }
 public function init($params)
 {
     $kind = $params['kind'] ?: tservices_binds::KIND_LANDING;
     //По умолчанию ставим лендинг
     $prof_id = (int) $params['prof_id'];
     $this->setBuyPopupTemplate('buy_popup_tservicebindup.tpl.php');
     $tservices_binds = new tservices_binds($kind);
     $promoCodes = new PromoCodes();
     $buffer = new buffer();
     $options = array('popup_title_class_bg' => 'b-fon_bg_po', 'popup_title_class_icon' => 'b-icon__po', 'popup_title' => 'Поднятие закрепления на 1 место', 'popup_id' => $this->getPopupId(0), 'unic_name' => $this->UNIC_NAME, 'payments_title' => 'Сумма и способ оплаты', 'payments_exclude' => array(self::PAYMENT_TYPE_BANK), 'ac_sum' => round($_SESSION['ac_sum'], 2), 'payment_account' => self::PAYMENT_TYPE_ACCOUNT, 'kind' => $kind, 'profession' => $tservices_binds->getProfessionText(false, $prof_id), 'buffer' => $buffer->getSum(), 'ammount' => round($tservices_binds->getPrice(true, @$params['uid'], $prof_id), 2), 'disable_tservices' => false, 'prof_id' => $prof_id, 'promo_code' => $promoCodes->render(PromoCodes::SERVICE_TSERVICEBIND));
     //Обязательно передаем родителю
     parent::init($options);
     //Добавляем свойство к одному способу оплаты
     $this->options['payments'][self::PAYMENT_TYPE_CARD]['wait'] = 'Ждите ....';
     $this->options['payments'][self::PAYMENT_TYPE_PLATIPOTOM]['content_after'] = sprintf($this->options['payments'][self::PAYMENT_TYPE_PLATIPOTOM]['content_after'], 'закрепление');
     $this->inited = true;
 }
 public function init($params)
 {
     $kind = $params['kind'] ?: 1;
     //По умолчанию ставим лендинг
     $prof_id = (int) $params['prof_id'];
     $profs = array();
     if ($kind == tservices_binds::KIND_SPEC) {
         $profs[] = $prof_id;
     } elseif ($kind == tservices_binds::KIND_GROUP) {
         $tservices_categories = new tservices_categories();
         $categories = $tservices_categories->getCategoriesByParent($prof_id);
         foreach ($categories as $category) {
             $profs[] = $category['id'];
         }
     }
     $tservices = new tservices($params['uid']);
     $data = $tservices->getNotBindedList($kind, $profs);
     $tservices_text = $tservices_cur_text = '';
     $tservices_cur = 0;
     if ($data) {
         foreach ($data as $tservice) {
             if (!$tservices_cur) {
                 $tservices_cur = $tservice['id'];
             }
             if (!$tservices_cur_text) {
                 $tservices_cur_text = $tservice['title'];
             }
             $tservices_list[] = $tservice['id'] . ": '" . addslashes($tservice['title']) . "'";
         }
         $tservices_text = '{' . implode(', ', $tservices_list) . '}';
     } else {
         $tservices_text = '{}';
     }
     $this->setBuyPopupTemplate('buy_popup_tservicebind.tpl.php');
     $tservices_binds = new tservices_binds($kind);
     $promoCodes = new PromoCodes();
     $options = array('popup_title_class_bg' => 'b-fon_bg_po', 'popup_title_class_icon' => 'b-icon__po', 'popup_title' => $is_prolong ? 'Продление закрепления' : 'Закрепление услуги', 'popup_subtitle' => $is_prolong ? 'Срок продления закрепления' : 'Срок закрепления услуги', 'popup_id' => $this->getPopupId(0), 'unic_name' => $this->UNIC_NAME, 'payments_title' => 'Сумма и способ оплаты', 'payments_exclude' => array(self::PAYMENT_TYPE_BANK), 'ac_sum' => round($_SESSION['ac_sum'], 2), 'payment_account' => self::PAYMENT_TYPE_ACCOUNT, 'kind' => $kind, 'profession' => $tservices_binds->getProfessionText(false, $prof_id), 'tservices' => $tservices_text, 'tservices_cur' => $tservices_cur, 'tservices_cur_text' => $tservices_cur_text, 'ammount' => $tservices_binds->getPrice(false, $params['uid'], $prof_id), 'disable_tservices' => false, 'prof_id' => $prof_id, 'promo_code' => $promoCodes->render(PromoCodes::SERVICE_TSERVICEBIND));
     //Обязательно передаем родителю
     parent::init($options);
     //Добавляем свойство к одному способу оплаты
     $this->options['payments'][self::PAYMENT_TYPE_CARD]['wait'] = 'Ждите ....';
     $this->options['payments'][self::PAYMENT_TYPE_PLATIPOTOM]['content_after'] = sprintf($this->options['payments'][self::PAYMENT_TYPE_PLATIPOTOM]['content_after'], 'закрепление');
     $this->inited = true;
 }
 /**
  * Отображение страницы /tu/.
  */
 public function actionIndex()
 {
     $uid = get_uid();
     $page = __paramInit('int', 'page', 'page', 1);
     $limit = 21;
     $empty_criteria = $this->filter_widget->filter->isEmpty();
     $prof_id = $this->filter_widget->filter->category ? $this->filter_widget->filter->category : $this->filter_widget->filter->category_group;
     $tserviceModel = TServiceModel::model();
     $freelancerModel = FreelancerModel::model();
     $tservicesCatalogModel = new tservices_catalog();
     $tservicesCatalogModel->category_id = $prof_id;
     $kind = tservices_binds::KIND_ROOT;
     if ($this->filter_widget->filter->category) {
         $kind = tservices_binds::KIND_SPEC;
     } elseif ($this->filter_widget->filter->category_group) {
         $kind = tservices_binds::KIND_GROUP;
     }
     if ($page == 1 && $uid && !is_emp()) {
         $this->getClips()->add('bind_teaser', $this->widget('TServiceBindTeaser', array('kind' => $kind, 'uid' => $uid, 'prof_id' => $prof_id, 'is_inner' => !$empty_criteria), true));
         $this->getClips()->add('bind_teaser_short', $this->widget('TServiceBindTeaserShort', array(), true));
     }
     $free_places = true;
     //Сначала берем закрепленные
     $tservicesCatalogModel->setPage($limit, $page);
     $tservices_binded = $tservicesCatalogModel->getBindedList($kind);
     //Тут только для текущей страницы
     $tservices_binded_ids = $tservicesCatalogModel->getBindedIds($kind);
     //Тут для всех страниц
     $count_binded = count($tservices_binded_ids);
     $count_binded_cur_page = count($tservices_binded);
     if ($count_binded_cur_page) {
         // расширение сведений о типовых услугах
         $tserviceModel->extend($tservices_binded, 'id')->readVideos($tservices_binded, 'videos', 'videos');
         // во всех строках "распаковать" массив видео-клипов
         // расширение сведений о пользователях
         $freelancerModel->extend($tservices_binded, 'user_id', 'user');
         //Добавляем попапы продления и поднятия к услугам текущего юзера
         foreach ($tservices_binded as $key => $tservice) {
             $is_owner = $tservice['user_id'] == $uid;
             if ($is_owner) {
                 $this->getClips()->add('bind_links_' . $tservice['id'], $this->widget('TServiceBindLinks', array('kind' => $kind, 'uid' => $uid, 'is_inner' => !$empty_criteria, 'date_stop' => $tservice['date_stop'], 'allow_up' => $page > 1 || $key > 0, 'tservice_id' => $tservice['id']), true));
                 if (quickPaymentPopupTservicebind::getInstance()->inited == false) {
                     quickPaymentPopupTservicebind::getInstance()->init(array('uid' => $uid, 'kind' => $kind, 'prof_id' => $prof_id));
                 }
                 $popup_id = quickPaymentPopupTservicebind::getInstance()->getPopupId($tservice['id']);
                 $popups[] = quickPaymentPopupTservicebind::getInstance()->render(array('is_prolong' => true, 'date_stop' => $tservice['date_stop'], 'popup_id' => $popup_id, 'tservices_cur' => $tservice['id'], 'tservices_cur_text' => $tservice['title']));
                 if ($key > 0) {
                     if (quickPaymentPopupTservicebindup::getInstance()->inited == false) {
                         quickPaymentPopupTservicebindup::getInstance()->init(array('uid' => $uid, 'tservices_id' => $tservice['id'], 'tservices_title' => $tservice['title'], 'kind' => $kind, 'prof_id' => $prof_id));
                     }
                     $popup_id = quickPaymentPopupTservicebindup::getInstance()->getPopupId($tservice['id']);
                     $popups[] = quickPaymentPopupTservicebindup::getInstance()->render(array('popup_id' => $popup_id, 'tservices_cur' => $tservice['id'], 'tservices_cur_text' => $tservice['title']));
                 }
             }
         }
         $free_places = $count_binded_cur_page < $limit;
     }
     if ($free_places) {
         //Есть места для отображения незакрепленных услуг
         $tservicesCatalogModel->keywords = $this->filter_widget->filter->keywords;
         $tservicesCatalogModel->price_ranges = $this->filter_widget->filter->prices;
         $tservicesCatalogModel->price_max = $this->filter_widget->filter->price_max;
         $tservicesCatalogModel->country_id = $this->filter_widget->filter->country;
         $tservicesCatalogModel->city_id = $this->filter_widget->filter->city;
         $tservicesCatalogModel->order = $this->filter_widget->filter->order;
         $tservicesCatalogModel->setPage($limit, $page, $count_binded, $count_binded_cur_page);
         // поиск записей
         $list = $tservicesCatalogModel->cache(300)->getList($tservices_binded_ids);
         $tservices_search = $list['list'];
         $total = $list['total'];
         // расширение сведений о типовых услугах
         $tserviceModel->extend($tservices_search, 'id')->readVideos($tservices_search, 'videos', 'videos');
         // во всех строках "распаковать" массив видео-клипов
         // расширение сведений о пользователях
         $freelancerModel->extend($tservices_search, 'user_id', 'user');
     }
     $tservices = $tservices_binded;
     foreach ($tservices_search as $tservice) {
         if (count($tservices) < $limit && !in_array($tservice['id'], $tservices_binded_ids)) {
             $tservices[] = $tservice;
         }
     }
     $tservicesCatalogModel2 = new tservices_catalog();
     $tservicesCatalogModel2->category_id = $prof_id;
     $tservicesCatalogModel2->order = TServiceFilter::ORDER_PRICE_ASC;
     $tservicesCatalogModel2->setPage(1, 1);
     $list2 = $tservicesCatalogModel2->cache(300)->getList();
     $min_price = $list2['list'][0]['price'];
     SeoTags::getInstance()->initTserviceList($prof_id, $this->filter_widget->filter->category > 0, $total, $min_price);
     $view_name = !$empty_criteria ? 'list' : 'tile';
     $this->is_main = $empty_criteria;
     /*
             if ($empty_criteria)
             {
                 // над списком типовых услуг вывести рекламный блок раздела
                 require_once($_SERVER['DOCUMENT_ROOT'] . '/tu/widgets/TServiceCatalogPromo.php');
                 $this->getClips()->add('content-promo', $this->widget('TServiceCatalogPromo', array(), true));
             }
     */
     $tservices_binds = new tservices_binds($kind);
     $this->render($view_name, array('category_title' => $this->filter_widget->getCategoryAngGroupTitle(' / '), 'total' => $total, 'nothing_found' => empty($tservices), 'tservices' => $tservices, 'page' => $tservicesCatalogModel->page, 'limit' => $limit, 'paging_base_url' => $this->filter_widget->getUserFriendlyUrl(), 'is_adm' => $this->is_adm, 'orders' => $this->filter_widget->getAllowedOrders(true), 'cur_order' => $this->filter_widget->filter->order, 'uid' => $uid, 'popups' => $popups, 'bind_up_price' => $tservices_binds->getPrice(true, $uid, $prof_id)));
 }
Esempio n. 6
0
                quickPaymentPopupTservicebind::getInstance()->init(array('uid' => $uid, 'kind' => tservices_binds::KIND_LANDING));
            }
            $popup_id = quickPaymentPopupTservicebind::getInstance()->getPopupId($tservice['id']);
            $popups[] = quickPaymentPopupTservicebind::getInstance()->render(array('is_prolong' => true, 'date_stop' => $tservice['date_stop'], 'popup_id' => $popup_id, 'tservices_cur' => $tservice['id'], 'tservices_cur_text' => $tservice['title']));
            if ($key > 0) {
                $isExistsBindUp = true;
                require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/quick_payment/quickPaymentPopupTservicebindup.php';
                if (quickPaymentPopupTservicebindup::getInstance()->inited == false) {
                    quickPaymentPopupTservicebindup::getInstance()->init(array('uid' => $uid, 'tservices_id' => $tservice['id'], 'tservices_title' => $tservice['title'], 'kind' => tservices_binds::KIND_LANDING));
                }
                $popup_id = quickPaymentPopupTservicebindup::getInstance()->getPopupId($tservice['id']);
                $popups[] = quickPaymentPopupTservicebindup::getInstance()->render(array('popup_id' => $popup_id, 'tservices_cur' => $tservice['id'], 'tservices_cur_text' => $tservice['title']));
            }
        }
    }
    if ($isExistsBindUp) {
        $tservicesBinds = new tservices_binds(tservices_binds::KIND_LANDING);
        $bindUpPrice = $tservicesBinds->getPrice(true, $uid);
    }
}
$suffix = $uid <= 0 ? '_anon' : (is_emp() ? '_emp' : '_frl');
$content_landing_image = $_SERVER['DOCUMENT_ROOT'] . "/templates/landings/tpl.landing_image{$suffix}.php";
$content = $_SERVER['DOCUMENT_ROOT'] . "/templates/landings/tpl.landing_tservices.php";
// Список профессий
$prfs = new professions();
$profs = $prfs->GetAllProfessions("", 0, 1);
// Сортировка категорий профессий по названию
//usort($profs, function($a, $b) { return strcmp($a['groupname'], $b['groupname']);});
$page_title = 'Фриланс сайт удаленной работы №1. Фрилансеры, работа на дому, freelance : FL.ru';
// отрисовка страницы
include $_SERVER['DOCUMENT_ROOT'] . "/template3.php";
/**
 * Оплата через Плати потом.
 * 
 * @param type $type - тип оплаты
 * @param type $data - данные по параметрам покупаемой услуги
 *
 * @return \xajaxResponse
 */
function quickPaymentTservicebindPlatipotom($type, $data)
{
    $is_error = true;
    $uid = get_uid(false);
    $objResponse =& new xajaxResponse();
    $kind = (int) @$data['kind'];
    $tservice_id = (int) @$data['tservice_text_db_id'];
    $prof_id = (int) @$data['prof_id'];
    $is_prolong = (bool) @$data['is_prolong'];
    $promo_code = (string) @$data['promo'];
    $tservices_binds = new tservices_binds($kind);
    $tservices = new tservices($uid);
    $allow = $tservices_binds->isAllowBind($uid, $tservice_id, $kind, $prof_id);
    $valid = $tservices->isExists($tservice_id) && ($is_prolong ? !$allow : $allow);
    if ($valid) {
        $is_error = false;
        $bill = new billing($uid);
        //Допустимо использование промокодов
        $bill->setPromoCodes('SERVICE_TSERVICEBIND', $promo_code);
        $op_code = $tservices_binds->getOpCode();
        $option = array('weeks' => (int) @$data['weeks'], 'prof_id' => $prof_id, 'tservice_id' => $tservice_id, 'is_prolong' => $is_prolong);
        //Формируем заказ
        $billReserveId = $bill->addServiceAndCheckout($op_code, $option);
        $payed_sum = $bill->getRealPayedSum();
        $platipotom = new platipotom();
        $html_form = $platipotom->render($payed_sum, $bill->account->id, $billReserveId);
        if ($html_form) {
            $idx = quickPaymentPopupTservicebind::getPopupId($is_prolong ? $tservice_id : 0);
            $objResponse->script("\n                var qp_form_wrapper = \$\$('#" . $idx . " .__quick_payment_form');\n                if(qp_form_wrapper){    \n                    qp_form_wrapper.set('html','{$html_form}');\n                    qp_form_wrapper.getElement('form')[0].submit();\n                }\n            ");
            //сохранаем в сессию куда перейти при успешной покупке
            $redirect = (string) @$data['redirect'];
            $_SESSION[quickPaymentPopup::QPP_REDIRECT] = $redirect;
        }
    }
    // Показываем предупреждение в случае ошибки
    if ($is_error) {
        $idx = quickPaymentPopupTservicebind::getPopupId($is_prolong ? $tservice_id : 0);
        $action = $is_prolong ? 'продлении закрепления' : 'закреплении';
        $objResponse->script("\n            var qp = window.quick_payment_factory.getQuickPaymentById('tservicebind', '" . $idx . "');\n            if(qp) qp.show_error('Возникла ошибка при {$action} услуги!');\n        ");
    }
    return $objResponse;
}
Esempio n. 8
0
    $data['location'] = 'г. ' . $city->getCityName($data['city']);
}
//------------------------------------------------------------------------------
//Виджет попап окошка при заказе услуги
//непоказываем фрилансерам
$tserviceOrderPopup = NULL;
$is_frl = !is_emp() && get_uid(false);
if (!$is_frl) {
    require_once $_SERVER['DOCUMENT_ROOT'] . '/tu/widgets/TServiceOrderPopup.php';
    $tserviceOrderPopup = new TServiceOrderPopup();
    $tserviceOrderPopup->init(array('title' => $data['title'], 'frl_fullname' => "{$user_obj->uname} {$user_obj->usurname} [{$user_obj->login}]", 'price' => $data['price'], 'days' => $data['days'], 'category_id' => $data['category_id']));
}
//------------------------------------------------------------------------------
if (!$is_owner) {
    //Популярные услуги из этой же категории или пользователя если данная услуга закреплена
    require_once $_SERVER['DOCUMENT_ROOT'] . '/tu/widgets/TServicesPopular.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/tservices/tservices_binds.php';
    $tservicesPopular = new TServicesPopular();
    $tservicesPopularOptions = array('title_css' => 'b-layout__title_padtop_40', 'item_css' => 'i-pic_port_col4_desktop');
    $isBinded = tservices_binds::isBinded($data['id']);
    if ($isBinded) {
        $tservicesPopularOptions['user_id'] = $uid;
        $tservicesPopularOptions['limit'] = 100;
        $tservicesPopularOptions['fullname'] = view_fullname($user_obj);
    }
    $tservicesPopular->setOptions($tservicesPopularOptions);
    $tservicesPopular->init($data['category_id'], $data['id']);
}
//------------------------------------------------------------------------------
$inner = 'tpl.card.php';
include '../template3.php';
Esempio n. 9
0
 /**
  * Оплата услуг.
  * 
  * @param array $order Данные по оплачивоемой услуге
  *
  * @return bool
  */
 public function paymentOrder($order)
 {
     $_op_code = self::getOpCodeByDiscount($order['op_code']);
     switch ($_op_code) {
         // Верификация банковской картой через ЯКассу
         case 191:
             $error = $this->account->Buy($account_operation_id, $this->transaction, $order['op_code'], $this->user['uid'], $order['descr'], $order['comment']);
             if (!$error) {
                 $success = true;
                 //Устанавливаем флаг верификации
                 require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/Verification.php';
                 $verify = new Verification();
                 $verify->cardYK($this->user['uid']);
                 //Обновляем сессию
                 //@todo: эта штука не работает!
                 $session = new session();
                 $session->UpdateVerification($this->user['login']);
                 //Обновляем имя и фамилию
                 $fio = mb_unserialize($order['option']);
                 if (isset($fio['uname']) && isset($fio['usurname'])) {
                     require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/users.php';
                     $u = new users();
                     $u->GetUserByUID($this->user['uid']);
                     $u->uname = $fio['uname'];
                     $u->usurname = $fio['usurname'];
                     $u->Update($this->user['uid'], $db_errors);
                 }
                 //Назначаем возврат
                 require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/billing/BillPayback.php';
                 BillPayback::getInstance()->requestPayback($order['id'], $this->paymentSysParams['invoiceId'], $order['ammount']);
             }
             break;
             //------------------------------------------------------------------
             // Верификация через FF
         //------------------------------------------------------------------
         // Верификация через FF
         case 117:
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/Verification.php';
             $error = $this->account->Buy($account_operation_id, $this->transaction, Verification::FF_OP_CODE, $this->user['uid'], $order['comment'], $order['descr'], 1, 0);
             $verify = new Verification();
             $verify->data = unserialize($order['option']);
             $this->_db->query('UPDATE verify_ff SET is_pro = ?, bill_id = ?  WHERE id = ?', false, $account_operation_id, $order['src_id']);
             if ($verify->verify($this->user['uid'])) {
                 $this->_db->query('UPDATE verify_ff SET result = TRUE WHERE id = ?', $order['src_id']);
                 $success = true;
             }
             break;
             //------------------------------------------------------------------
             // Конкурс
         //------------------------------------------------------------------
         // Конкурс
         case 9:
         case 106:
         case 121:
         case 122:
         case 123:
         case 124:
         case 125:
         case 126:
         case 127:
         case 128:
         case 129:
         case 130:
             // Платный конкурс
         // Платный конкурс
         case 86:
             // Платный проект (вакансия, устаревший опкод)
         // Платный проект (вакансия, устаревший опкод)
         case 53:
             //Покупка вакансии
         //Покупка вакансии
         case 113:
             //пользователь не PRO
         //пользователь не PRO
         case 192:
             //пользователь PRO
             //Платные услуги проектов
         //пользователь PRO
         //Платные услуги проектов
         case 138:
         case 139:
         case 140:
         case 141:
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/projects.php';
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/drafts.php';
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/uploader/uploader.php';
             // Публикуем платный проект
             if ($order['parent_table'] == 'draft_projects') {
                 $draft_id = $order['parent_id'];
                 $this->project_key = md5(uniqid($this->user['uid']));
                 $tmpPrj = new tmp_project($this->project_key);
                 $tmpPrj->initFromDraft($draft_id, $this->user['uid']);
                 $tproject = $tmpPrj->getProject();
                 $isMovedToVacancy = false;
                 // Нет конкурса значит его уже опубликовали и оплатили, оставляем деньги на личном счете
                 if ((int) $tproject['prj_id'] <= 0) {
                     // Не тратим деньги на такой конкурс
                     if ($tmpPrj->isKonkurs() && strtotime($tproject['end_date']) <= time()) {
                         $success = true;
                         break;
                     }
                     $error = $tmpPrj->saveProject($this->user['uid'], $proj, $this->ordersPromoCodes);
                     $success = !$error;
                     // Отработали все по конкурсу удаляем его чтобы не мешал (после отработки всех операций)
                     $this->setAfterQuery($this->_db->parse('DELETE FROM draft_projects WHERE id = ? AND uid = ?', $draft_id, $this->user['uid']), $order['parent_id']);
                     $sql = 'UPDATE draft_projects SET prj_id = ? WHERE id = ? AND uid = ?';
                     $this->_db->query($sql, $proj['id'], $draft_id, $this->user['uid']);
                 } else {
                     $success = true;
                 }
             } elseif ($order['parent_table'] == 'projects') {
                 $prj_id = $order['parent_id'];
                 $this->project_key = md5(uniqid($this->user['uid']));
                 $tmpPrj = new tmp_project($this->project_key);
                 $tmpPrj->setInitFromDB($prj_id);
                 $tproject = $tmpPrj->getProject();
                 $isMovedToVacancy = $tmpPrj->isStateMovedToVacancy();
                 // Если закрыт или заблокирован не тратим деньги
                 if ($tproject['closed'] == 't' || $tproject['is_blocked'] == 't') {
                     $success = true;
                     break;
                 }
                 switch ($order['option']) {
                     case 'top':
                         $tmpPrj->setAddedTopDays($order['op_count']);
                         break;
                     case 'logo':
                         $LogoFile = new CFile($order['src_id']);
                         $tmpPrj->initLogo($LogoFile, $order['descr']);
                         break;
                     case 'urgent':
                         $tmpPrj->setProjectField('urgent', 't');
                         break;
                     case 'hide':
                         $tmpPrj->setProjectField('hide', 't');
                         break;
                     case 'office':
                         $tmpPrj->setProjectField('old_state', $tproject['state']);
                         $tmpPrj->setProjectField('state', projects::STATE_PUBLIC);
                         //Если оплачивается не перемещенная вакансия
                         //то работаем как обычно и подымаем вверх
                         if ($tproject['state'] != projects::STATE_MOVED_TO_VACANCY) {
                             $tmpPrj->setProjectField('post_now', true);
                         }
                         break;
                 }
                 $error = $tmpPrj->saveProject($this->user['uid'], $proj, $this->ordersPromoCodes);
                 $success = !$error;
                 if ($success) {
                     if (isset($tmpPrj->account_operation_id) && $tmpPrj->account_operation_id > 0) {
                         $account_operation_id = $tmpPrj->account_operation_id;
                     }
                     switch ($order['option']) {
                         case 'office':
                             if ($tproject['state'] == projects::STATE_MOVED_TO_VACANCY) {
                                 require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/smail.php';
                                 $smail = new smail();
                                 $smail->sendMovedToVacancySuccessPayed($tproject);
                                 require_once $_SERVER['DOCUMENT_ROOT'] . '/guest/models/GuestInviteModel.php';
                                 $guestInviteModel = new GuestInviteModel();
                                 $guestInviteModel->updateDatePublicBySrc($prj_id, array(GuestConst::TYPE_PROJECT, GuestConst::TYPE_VACANCY));
                                 require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/autoresponse.php';
                                 $autoresponse = new autoresponse();
                                 $autoresponse->reduceByProject($prj_id);
                             }
                             break;
                     }
                 }
             }
             //Сохраняем, чтобы показать попап юзеру
             $memBuff = new memBuff();
             $memBuff->add('bill_ok_project_' . $this->user['uid'], $proj['id']);
             //Если это оплата вакансии или конкусра то предлагаем еще купить платные опции
             if (in_array($order['option'], array('office', 'contest')) && !$isMovedToVacancy) {
                 $memBuff->add('bill_ok_project_payed_' . $this->user['uid'], true);
             }
             break;
             //------------------------------------------------------------------
             // Платное место в карусели
         //------------------------------------------------------------------
         // Платное место в карусели
         case 65:
             // На главной странице
             $catalog = 0;
         case 73:
             // В каталоге
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/pay_place.php';
             $payPlace = new pay_place(isset($catalog) ? $catalog : 1);
             $buyMain = $this->account->Buy($account_operation_id, $this->transaction, $order['op_code'], $this->user['uid'], $order['comment'], $order['descr'], $order['op_count'], 0, $order['promo_code']);
             if ($buyMain === 0) {
                 $options = unserialize($order['option']);
                 if (isset($options['adHead'])) {
                     //поддержка старого режима
                     $success = $payPlace->addUser($this->user['uid'], $options['adHead'], $options['adText'], $options['adImg']);
                 } else {
                     $success = $payPlace->addUserRequest($this->user['uid'], $options);
                 }
             }
             break;
             //------------------------------------------------------------------
             // ПРО аккаунт фрилансеры
         //------------------------------------------------------------------
         // ПРО аккаунт фрилансеры
         case 47:
             // Тестовый ПРО на 1 неделю
             if (payed::IsUserWasPro($this->user['uid'])) {
                 return false;
                 break;
             }
         case 15:
             // Про на 1 месяц (emp)
         // Про на 1 месяц (emp)
         case 48:
             // Про на 1 месяц (frl)
         // Про на 1 месяц (frl)
         case 118:
             // Про на 3 месяца (emp)
         // Про на 3 месяца (emp)
         case 49:
             // Про на 3 месяца (frl)
         // Про на 3 месяца (frl)
         case 119:
             // Про на 6 месяцeв (emp)
         // Про на 6 месяцeв (emp)
         case 50:
             // Про на 6 месяцев (frl)
         // Про на 6 месяцев (frl)
         case 120:
             // Про на 1 год (emp)
         // Про на 1 год (emp)
         case 51:
             // Про на 1 год (frl)
         // Про на 1 год (frl)
         case 132:
             // Про на 1 день (frl)
         // Про на 1 день (frl)
         case 131:
             // Про на 1 неделю (frl)
         // Про на 1 неделю (frl)
         case 163:
             // Тестовый ПРО на месяц
         // Тестовый ПРО на месяц
         case 164:
             // PROFI на 1 месяц
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/payed.php';
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/freelancer.php';
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/employer.php';
             $payed = new payed();
             $user = is_emp($this->user['role']) ? new employer() : new freelancer();
             $success = $payed->SetOrderedTarif($this->user['uid'], $this->transaction, $order['op_count'], $order['comment'], $order['op_code'], $order['promo_code'], $error);
             if ($success) {
                 if (isset($payed->account_operation_id) && $payed->account_operation_id > 0) {
                     $account_operation_id = $payed->account_operation_id;
                 }
                 // Обновим сессию сразу!
                 if (get_uid(false) == $this->user['uid']) {
                     $_SESSION['pro_last'] = payed::ProLast($this->user['login']);
                     $_SESSION['pro_last'] = $_SESSION['pro_last']['is_freezed'] ? false : $_SESSION['pro_last']['cnt'];
                     if ($_SESSION['pro_last']['is_freezed']) {
                         $_SESSION['payed_to'] = $_SESSION['pro_last']['cnt'];
                     }
                 } else {
                     $membuff = new memBuff();
                     $membuff->set('is_changed_pro_' . $this->user['uid'], true);
                     //Этот подход не работает
                     //$session = new session();
                     //$session->UpdateProEndingDate($this->user['login']);
                 }
                 if ($order['auto'] == 't') {
                     $user->setPROAutoProlong('on', $this->user['uid']);
                 } else {
                     $user->setPROAutoProlong('off', $this->user['uid']);
                 }
                 //Опубликовать перемещенные вакансии при покупке ПРО
                 //@todo: Теперь вакансии для всех платные разница лишь в цене для ПРО дешевле
                 //поэтому отключаем публикацию после покупки ПРО
                 //https://beta.free-lance.ru/mantis/view.php?id=28579
                 /*
                                     if (is_emp($this->user['role'])) { 	 
                                         require_once($_SERVER['DOCUMENT_ROOT'] . "/classes/projects.php"); 	
                                         $project = new projects();	 
                                         $project->publishedMovedToVacancy($this->user); 	
                                     }*/
                 //Чистим кеш каталога PROFI пользователей
                 if ($order['op_code'] == 164) {
                     freelancer::clearCacheProfiCatalog();
                 }
             }
             break;
             //------------------------------------------------------------------
         //------------------------------------------------------------------
         case 45:
             // рассылка по каталогу
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/masssending.php';
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/messages.php';
             $masssending = masssending::Get($order['parent_id']);
             $masssending = $masssending[0];
             $error = $this->account->Buy($account_operation_id, $this->transaction, masssending::OPER_CODE, $this->user['uid'], $order['descr'], $order['comment'], $masssending['pre_sum'], 0, $order['promo_code']);
             if ($error) {
                 break;
             }
             masssending::UpdateAcOpID($order['parent_id'], $account_operation_id);
             $success = (bool) messages::Masssending($masssending['user_id'], $masssending['id'], $masssending['msgtext'], $masssending['posted_time']);
             break;
             //------------------------------------------------------------------
             /*
              * Погашение задолженности
              */
         //------------------------------------------------------------------
         /*
          * Погашение задолженности
          */
         case 135:
             $error = $this->account->Buy($account_operation_id, $this->transaction, $order['op_code'], $this->user['uid'], $order['descr'], $order['comment'], 1, 1, 0, 0, $order['ammount']);
             if (!$error) {
                 $success = true;
                 //Начисление погашенной комиссии и удаление блокировки ТУ
                 require_once $_SERVER['DOCUMENT_ROOT'] . '/tu/models/TServiceOrderModel.php';
                 TServiceOrderModel::model()->clearDebt($this->user['uid']);
             }
             break;
             //-------------------------------------------------------------------
             /*
              * Операции над бизнес логикой резерва средств 
              * при успешном зачислении денег
              */
         //-------------------------------------------------------------------
         /*
          * Операции над бизнес логикой резерва средств 
          * при успешном зачислении денег
          */
         case 136:
             $success = false;
             $data = @$this->list_service[$order['id']]['info'];
             if (!$data) {
                 break;
             }
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/reserves/ReservesModelFactory.php';
             $reserveInstance = ReservesModelFactory::getInstance($data['type']);
             //Уже была зарезервирована или нет нужный параметров то
             //ничего не покупаем деньги остаются на ЛС
             if (!$reserveInstance || !isset($this->paymentSysParams['invoiceId'])) {
                 break;
             }
             //Невозможно сменить статус сделки выходим
             $reserveInstance->setReserveData($data);
             if (!$reserveInstance->allowChangeStatus(ReservesModel::STATUS_RESERVE)) {
                 break;
             }
             $ret = $this->account->Buy($account_operation_id, $this->transaction, $order['op_code'], $this->user['uid'], $order['descr'], $order['comment'], $order['ammount']);
             if ($ret === 0) {
                 //Успешно купили услугу и теперь меняем статус резерва
                 $data['invoice_id'] = $this->paymentSysParams['invoiceId'];
                 $data['acc_op_id'] = $account_operation_id;
                 $reserveInstance->setReserveData($data);
                 $success = $reserveInstance->changeStatus(ReservesModel::STATUS_RESERVE);
             }
             break;
             //------------------------------------------------------------------
             /*
              * Завершение покупки автоответов.
              */
         //------------------------------------------------------------------
         /*
          * Завершение покупки автоответов.
          */
         case 137:
             $success = false;
             $ret = $this->account->Buy($account_operation_id, $this->transaction, $order['op_code'], $this->user['uid'], $order['descr'], $order['comment'], $order['ammount'], 1, $order['promo_code']);
             if ($ret === 0 && isset($order['parent_id']) && intval($order['parent_id'])) {
                 require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/autoresponse.php';
                 autoresponse::$db = $GLOBALS['DB'];
                 // Активация покупки услуги автоответа
                 if ($autoresponse = autoresponse::get($order['parent_id'])) {
                     $autoresponse->activate();
                     $success = true;
                 }
             }
             break;
             //------------------------------------------------------------------
             // Закрепление в каталоге фрилансеров
         //------------------------------------------------------------------
         // Закрепление в каталоге фрилансеров
         case 142:
             // В корневом разделе
         // В корневом разделе
         case 143:
             // В разделе
             $is_spec = false;
         case 144:
             // В подразделе
             if (!isset($is_spec)) {
                 $is_spec = true;
             }
             $success = false;
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/freelancer_binds.php';
             $freelancer_binds = new freelancer_binds();
             $freelancer_binds->prepare($this->user['uid'], $order['src_id'], $is_spec, $order['op_count']);
             $ret = $this->account->Buy($account_operation_id, $this->transaction, $order['op_code'], $this->user['uid'], $freelancer_binds->bind_info['descr'], $freelancer_binds->bind_info['comment'], $order['ammount'], 1, $order['promo_code']);
             if ($ret === 0) {
                 $success = $freelancer_binds->create();
             }
             break;
             //------------------------------------------------------------------
             // Продление закрепления в каталоге фрилансеров
         //------------------------------------------------------------------
         // Продление закрепления в каталоге фрилансеров
         case 148:
             // В корневом разделе
         // В корневом разделе
         case 149:
             // В разделе
             $is_spec = false;
         case 150:
             // В подразделе
             if (!isset($is_spec)) {
                 $is_spec = true;
             }
             $success = false;
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/freelancer_binds.php';
             $freelancer_binds = new freelancer_binds();
             $bind_id = $freelancer_binds->isUserBinded($this->user['uid'], $order['src_id'], $is_spec);
             $ret = true;
             if ($bind_id) {
                 $freelancer_binds->getProlongInfo($this->user['uid'], $order['src_id'], $is_spec, $order['op_count']);
                 $ret = $this->account->Buy($account_operation_id, $this->transaction, $order['op_code'], $this->user['uid'], $freelancer_binds->bind_info['descr'], $freelancer_binds->bind_info['comment'], $order['ammount']);
             }
             if ($ret === 0) {
                 $success = $freelancer_binds->prolong($bind_id, $order['op_count'], $order['src_id'], $is_spec);
             }
             break;
             //------------------------------------------------------------------
             // Поднятие закрепления в каталоге фрилансеров
         //------------------------------------------------------------------
         // Поднятие закрепления в каталоге фрилансеров
         case 151:
             // В корневом разделе
         // В корневом разделе
         case 152:
             // В разделе
             $is_spec = false;
         case 153:
             // В подразделе
         // В подразделе
         case 194:
             //Оплата из буфера
             if (!isset($is_spec)) {
                 $is_spec = $order['src_id'] > 0;
             }
             $success = false;
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/freelancer_binds.php';
             $freelancer_binds = new freelancer_binds();
             $bind_id = $freelancer_binds->isUserBinded($this->user['uid'], $order['src_id'], $is_spec);
             if ($bind_id) {
                 $freelancer_binds->getUpInfo($this->user['uid'], $order['src_id'], $is_spec);
                 $ret = $this->account->Buy($account_operation_id, $this->transaction, $order['op_code'], $this->user['uid'], $freelancer_binds->bind_info['descr'], '', $order['ammount']);
                 if ($ret === 0) {
                     $success = $freelancer_binds->up($bind_id, $order['src_id'], $is_spec);
                 }
             }
             break;
             //------------------------------------------------------------------
             // Закрепление/продление в каталоге услуг
         //------------------------------------------------------------------
         // Закрепление/продление в каталоге услуг
         case 155:
             // В лендинге
         // В лендинге
         case 156:
             // В корневом разделе
         // В корневом разделе
         case 157:
             // В разделе
         // В разделе
         case 158:
             // В подразделе
             $success = false;
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/tservices/tservices_binds.php';
             $tservices_binds = new tservices_binds(tservices_binds::KIND_LANDING);
             $tservices_binds->setKindByOpCode($_op_code);
             $option = unserialize($order['option']);
             $tservice_id = isset($option['tservice_id']) ? $option['tservice_id'] : $order['option'];
             $is_prolong = isset($option['is_prolong']) ? $option['is_prolong'] : false;
             $tservices_binds->prepare($this->user['uid'], $tservice_id, $order['src_id'], $order['op_count'], $is_prolong);
             if ($tservices_binds->bind_info) {
                 $ret = $this->account->Buy($account_operation_id, $this->transaction, $order['op_code'], $this->user['uid'], $tservices_binds->bind_info['descr'], $tservices_binds->bind_info['comment'], $order['ammount']);
                 if ($ret === 0) {
                     $success = $is_prolong ? $tservices_binds->update() : $tservices_binds->create();
                 }
             }
             break;
             //------------------------------------------------------------------
             // Поднятие закрепления в каталоге услуг
         //------------------------------------------------------------------
         // Поднятие закрепления в каталоге услуг
         case 159:
             // В лендинге
         // В лендинге
         case 160:
             // В корневом разделе
         // В корневом разделе
         case 161:
             // В разделе
         // В разделе
         case 162:
             // В подразделе
         // В подразделе
         case 193:
             //Оплата из буфера
             $success = false;
             require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/tservices/tservices_binds.php';
             $tservices_binds = new tservices_binds(tservices_binds::KIND_LANDING);
             $tservices_binds->setKindByOpCode($_op_code);
             $bind = $tservices_binds->getItemById($order['src_id']);
             $tservices_binds->makeUpInfo($bind);
             if ($tservices_binds->bind_info) {
                 $ret = $this->account->Buy($account_operation_id, $this->transaction, $order['op_code'], $this->user['uid'], $tservices_binds->bind_info['descr'], $tservices_binds->bind_info['comment'], $order['ammount']);
                 if ($ret === 0) {
                     $success = $tservices_binds->update();
                 }
             }
             break;
     }
     if ($success) {
         $update = array('status' => self::STATUS_COMPLETE);
         $this->update($order['id'], $update);
         $memBuff = new memBuff();
         $memBuff->delete('last_operation_' . $order['uid'] . '_' . $order['service']);
         //Если только что была оплата из яндекс.кассы
         if ($this->paymentSysParams['invoiceId']) {
             //Фиксируем ID транзакции
             $label = op_codes::getLabel($order['op_code']);
             if (isset($account_operation_id) && $account_operation_id > 0) {
                 $label = (empty($label) ? '' : "{$label},") . "trans_{$account_operation_id}";
             }
             // Посылаем данные о покупке в google analytics
             $this->_db->query("SELECT pgq.insert_event('statistic', 'service_payed', ?)", http_build_query(array('is_emp' => is_emp($this->user['role']), 'label' => $label, 'ammount' => floatval($order['ammount']), 'cid' => $this->getCid())));
         }
     }
     return $success;
 }
Esempio n. 10
0
 /**
  * Уведомление фрилансеру за 1 день до окончания 
  * размещения закрепления ТУ
  */
 public function remind24hEndBinds()
 {
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/tservices/tservices_binds.php";
     require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/quick_payment/quickPaymentPopupTservicebind.php";
     $tservices_categories = new tservices_categories();
     //Базовый шаблон письма
     $layout = Template::render(TSERVICES_BINDS_TPL_BASE_LAYOUT, array('params' => '', 'content' => '%CONTENT%'));
     $this->message = nl2br($layout);
     $count = 0;
     $page = 0;
     while ($binds = tservices_binds::getExpiring(++$page, 200)) {
         $bind_ids = array();
         foreach ($binds as $el) {
             $kind_txt = '';
             $link = '/?' . quickPaymentPopupTservicebind::getPopupId($el['tservice_id']) . '=1';
             switch ($el['kind']) {
                 case tservices_binds::KIND_LANDING:
                     $kind_txt = 'на главной странице сайта';
                     break;
                 case tservices_binds::KIND_ROOT:
                     $kind_txt = 'в общем разделе каталога услуг';
                     $link = '/tu' . $link;
                     break;
                 case tservices_binds::KIND_GROUP:
                     $category = $tservices_categories->getCategoryById($el['prof_id']);
                     $kind_txt = sprintf("в разделе %s каталога услуг", @$category['title']);
                     $link = sprintf("/tu/%s%s", @$category['link'], $link);
                     break;
                 case tservices_binds::KIND_SPEC:
                     $category = $tservices_categories->getCategoryById($el['prof_id']);
                     $kind_txt = sprintf("в подразделе %s каталога услуг", @$category['title']);
                     $link = sprintf("/tu/%s%s", @$category['link'], $link);
                     break;
             }
             //Шаблон уведомления
             $content = Template::render(TSERVICES_BINDS_TPL_MAIL_PATH . "remind_prolong.tpl.php", array('smail' => $this, 'time' => dateFormat('H:i', $el['date_stop']), 'kind' => $kind_txt, 'title' => $el['title'], 'link' => $link));
             $this->recipient[] = array('email' => $this->_formatFullname($el, true), 'extra' => array('CONTENT' => nl2br($content)));
             $bind_ids[] = $el['id'];
         }
         $count += count($bind_ids);
         $massId = $this->send('text/html');
         if ($massId) {
             tservices_binds::markSent('prolong', $bind_ids);
         }
     }
     return $count;
 }