Ejemplo 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';
 }
 protected function _getTabTu($user, $page = 1)
 {
     require_once ABS_PATH . '/classes/tservices/tservices.php';
     require_once ABS_PATH . '/tu/models/TServiceItemIterator.php';
     $tab = null;
     $tservices = new tservices($user['uid']);
     $list = $tservices->setPage($this->limit, $page)->getShortList();
     if ($list) {
         $total = $tservices->getCount();
         $pages = ceil($total / $this->limit);
         $tab = array('elements' => new TServiceItemIterator($user, $list), 'pages' => $pages, 'page' => $page);
     }
     return $tab;
 }
Ejemplo n.º 3
0
function tservices_order_auth($email, $name, $surname, $options)
{
    $objResponse =& new xajaxResponse();
    $name = substr(strip_tags(trim(stripslashes($name))), 0, 21);
    //Для регистрации
    $surname = substr(strip_tags(trim(stripslashes($surname))), 0, 21);
    //Для регистрации
    $email = substr(strip_tags(trim(stripslashes($email))), 0, 64);
    //Для регистрации и авторизации
    $tu_id = intval(@$options['tu_id']);
    $tservices = new tservices();
    $tService = $tservices->getCard($tu_id);
    if (!$tService) {
        return $objResponse;
    }
    if (is_email($email)) {
        //Забираем только нужные нам ключи
        $options = array_intersect_key($options, array('extra' => '', 'is_express' => '', 'paytype' => ''));
        //Проверка входных параметров
        $is_valid_extra = !isset($options['extra']) || isset($options['extra']) && count(array_intersect(array_keys($tService['extra']), $options['extra'])) == count($options['extra']);
        $is_valid_express = !isset($options['is_express']) || isset($options['is_express']) && $options['is_express'] == '1' && $tService['is_express'] == 't';
        $is_valid_paytype = isset($options['paytype']) && in_array($options['paytype'], array('0', '1'));
        if (!($is_valid_extra && $is_valid_express && $is_valid_paytype)) {
            return $objResponse;
        }
        $tservices_auth_smail = new tservices_auth_smail();
        $user = new users();
        $user->GetUser($email, true, true);
        //Проверяем на всякий случай там точно мыло совпало а то может логин
        $is_email = $user->email == $email;
        //Создаем хеш для ссылки активации
        $code = TServiceOrderModel::model()->newOrderActivation(array('user_id' => $user->uid > 0 ? $user->uid : null, 'tu_id' => $tService['id'], 'uname' => !empty($name) ? $name : null, 'usurname' => !empty($surname) ? $surname : null, 'email' => $email, 'options' => $options));
        // Пользователь найден, ведь у него есть email. А как еще проверить?
        if ($user->uid > 0 && $is_email) {
            if (is_emp($user->role)) {
                $tservices_auth_smail->orderByOldUser($email, $tService, $code);
                $objResponse->call('TServices_Order_Auth.showSuccess', 'На указанную вами почту отправлено письмо со ссылкой-подтверждением. Пожалуйста, перейдите по ней для завершения процесса заказа услуги.');
            } else {
                $objResponse->call('TServices_Order_Auth.showError', 'email', 'Данный e-mail принадлежит фрилансеру');
            }
        } else {
            $tservices_auth_smail->orderByNewUser($email, $tService, $code);
            $objResponse->call('TServices_Order_Auth.showSuccess', 'На указанную вами почту отправлено письмо со ссылкой-подтверждением. Пожалуйста, перейдите по ней для завершения процесса заказа услуги.');
        }
    } else {
        $objResponse->call('TServices_Order_Auth.showError', 'email', 'Неверно указана почта');
    }
    return $objResponse;
}
 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;
 }
Ejemplo n.º 5
0
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/stdf.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/tservices/tservices_categories.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/tservices/tservices_tags.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/tservices/tservices.php';
$tservices_categories = new tservices_categories();
$result = $tservices_categories->getTitleAndSubtitle(10);
assert('$result == array("spec_title" => "Веб-программирование", "group_title" => "Разработка сайтов")');
$result = $tservices_categories->getCategoryParentId(10);
assert('$result == 7');
$tservices_tags = new tservices_tags();
$result = $tservices_tags->getsByTServiceId(39);
assert('$result == array( 0 => "альбом", 1 => "бронировать", 2 => "забронировать", 3 => "заказать", 4 => "заказывать", 5 => "зарезервировать" )');
$tservices = new tservices(2);
$result = $tservices->isExistFeedbacks(27);
assert('$result == 2');
$result = $tservices->getTotalCount();
assert('$result == array("plus" => 2, "minus" => 2)');
$result = $tservices->getNearBy('next', 38);
$result = $tservices->getNearBy('prev', 38);
$result = $tservices->getCountCompleteSbrServices();
assert('$result == 5');
$result = $tservices->deleteById(750);
assert('$result == TRUE');
$result = $tservices->isExists(749);
$result = $tservices->getFeedbacks(36);
$result = $tservices->getCard(36);
$result = $tservices->setPage(5)->getShortList();
$result = $tservices->initProps();
/**
 * Оплата через Плати потом.
 * 
 * @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;
}
Ejemplo n.º 7
0
        $on_page = $user->is_pro === 't' ? 20 : 21;
        $js_file[] = 'tservices/fineuploader.js';
        $js_file[] = 'tservices/tservices.js';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/tu/yii/tinyyii.php';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/tservices/functions.php';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/tservices/tservices_helper.php';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/tservices/tservices.php';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/tu/widgets/TServiceOrderDebtMessage.php';
        $page = __paramInit('int', 'page', 'page', 1);
        if ($page <= 0) {
            $page = 1;
        }
        $is_owner = $user->uid == $uid;
        $is_perm = hasPermissions('tservices');
        $is_not_public = $is_owner || $is_perm;
        $tservices = new tservices($user->uid);
        $data = $tservices->setPage($on_page, $page)->getShortList(!$is_not_public);
        $cnt = $tservices->getCount(!$is_not_public);
        //Виджет для рендера сообщения о блокировки
        $tserviceOrderDebtMessageWidget = new TServiceOrderDebtMessage();
        $tserviceOrderDebtMessageWidget->init($user->uid);
        $inner = 'tu_inner.php';
        $activ_tab = 2;
        //SEO
        $page_title = 'Типовые услуги на FL.ru';
        //$page_descr = '';
        //$page_keyw = '';
        break;
}
if (!$user->login) {
    include ABS_PATH . '/404.php';
Ejemplo n.º 8
0
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/tservices/tservices.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/tu/models/TServiceOrderModel.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/user_phone.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/seo/SeoTags.php';
const feedbacks_per_page = 5;
session_start();
$tuid = __paramInit('int', 'tuid', NULL, 0);
if (!$tuid) {
    //header("Location: /404.php");
    //exit;
    include ABS_PATH . '/404.php';
    exit;
}
//------------------------------------------------------------------------------
//Получаем ТУ
$tservices = new tservices();
$data = $tservices->getCard($tuid, false);
if (!$data) {
    include ABS_PATH . '/404.php';
    exit;
}
//------------------------------------------------------------------------------
//Проверяем уровень доступа
$is_owner = get_uid() == $data['user_id'];
$is_active = $data['active'] == 't';
$is_adm = hasPermissions('tservices');
$is_allow = $is_owner || $is_adm;
if (!($is_owner || $is_adm) && !$is_active) {
    include ABS_PATH . '/404.php';
    exit;
}
 /**
  * Провека параметров и подготовка настроек 
  * для обновлении или добавления
  * 
  * @param type $data
  * @return type
  */
 public function isValid($data)
 {
     require_once ABS_PATH . '/freelancers/widgets/FreelancersPreviewWidget.php';
     require_once ABS_PATH . '/classes/freelancer.php';
     $this->is_valid = false;
     $max_pos = FreelancersPreviewWidget::MAX_ITEMS;
     $this->group_id = isset($data['group']) ? intval($data['group']) : 0;
     $this->prof_id = isset($data['prof']) ? intval($data['prof']) : 0;
     $hash = isset($data['hash']) ? $data['hash'] : null;
     //Проверка группы/раздела именно тех на странице которых был открыт попап
     if ($hash !== paramsHash(array($this->group_id, $this->prof_id))) {
         return $this->is_valid;
     }
     $value = isset($data['value']) ? $data['value'] : '';
     $this->uid = isset($data['uid']) && $data['uid'] > 0 ? $data['uid'] : null;
     $this->pos = isset($data['pos']) && $data['pos'] > 0 && $data['pos'] <= $max_pos ? intval($data['pos']) : null;
     if (!$this->uid || !$this->pos || empty($value)) {
         return $this->is_valid;
     }
     $user = new freelancer();
     $user->GetUserByUID($this->uid);
     if ($user->uid <= 0) {
         return $this->is_valid;
     }
     $pattern = implode('|', FreelancersPreviewEditorPopup::$types);
     $matches = array();
     if (preg_match("/^({$pattern})_([0-9]+)\$/", $value, $matches)) {
         $this->type = self::$type_from_string[$matches[1]];
         $this->src_id = $matches[2];
         switch ($this->type) {
             case self::TYPE_PF:
                 require_once ABS_PATH . '/classes/portfolio.php';
                 $portfolio = new portfolio();
                 $this->is_valid = (bool) $portfolio->isExistActive($this->uid, $this->src_id);
                 break;
             case self::TYPE_TU:
                 require_once ABS_PATH . '/classes/tservices/tservices.php';
                 $tservices = new tservices($this->uid);
                 $this->is_valid = (bool) $tservices->isExistActive($this->src_id);
                 break;
         }
         if ($this->is_valid) {
             $res = $this->getRowByUidAndPos($this->uid, $this->pos, $this->group_id, $this->prof_id);
             $this->id = $res ? $res['id'] : 0;
             //Уже есть данная позиция
             //то готовим данные для обновления
             if ($this->id > 0) {
                 $this->data = array('src_id' => $this->src_id, 'type' => $this->type, 'is_default' => false);
                 $this->is_default = $res['is_default'] == 't';
                 //Первое добавление позиции
                 //то готовим новые данные для добавления
             } else {
                 $exist_data = isset($_SESSION[self::SESS_EXIST_PREVIEW_DATA]) ? $_SESSION[self::SESS_EXIST_PREVIEW_DATA] : null;
                 for ($idx = 1; $idx <= $max_pos; $idx++) {
                     if ($idx == $this->pos) {
                         $this->data[$idx] = array('src_id' => $this->src_id, 'type' => $this->type, 'user_id' => $this->uid, 'pos' => $idx, 'group_id' => $this->group_id, 'prof_id' => $this->prof_id, 'is_default' => false);
                     } elseif (isset($exist_data['ids'][$idx - 1])) {
                         $this->data[$idx] = array('src_id' => $exist_data['ids'][$idx - 1], 'type' => $exist_data['type'], 'user_id' => $this->uid, 'pos' => $idx, 'group_id' => $this->group_id, 'prof_id' => $this->prof_id, 'is_default' => false);
                     }
                 }
             }
             //Устанавливаем по возможности
             //текущии настройки для общего каталога / раздела
             /*
               - общий каталог поумолчанию из основного подраздела (специализации), но может и настраиваться по своему
               - раздел каталога поумолчанию из последнего отредактированного подраздела, но может настраиваться по своему
               - подраздел (специализация) настраивается по своему 
             */
             if ($this->prof_id > 0 && $this->group_id == 0 && count($this->data)) {
                 $is_exist_setting_for_catalog = false;
                 $is_exist_setting_for_group = false;
                 require_once ABS_PATH . '/classes/professions.php';
                 $group_id = professions::GetGroupIdByProf($this->prof_id);
                 $exist_data = $this->getExistData($group_id);
                 $current_settings = array();
                 if ($exist_data) {
                     foreach ($exist_data as $el) {
                         //Существующие текущие настройки раздела
                         if ($el['prof_id'] == $this->prof_id && $el['group_id'] == 0) {
                             unset($el['id']);
                             if ($el['pos'] == $this->pos) {
                                 $el['src_id'] = $this->src_id;
                                 $el['type'] = $this->type;
                             }
                             $current_settings[$el['pos']] = $el;
                             //Существующие настройки для общего каталога
                         } elseif ($el['prof_id'] == 0 && $el['group_id'] == 0 && $el['is_default'] == 'f') {
                             $is_exist_setting_for_catalog = true;
                             //Существующие настройки для группы
                         } elseif ($el['prof_id'] == 0 && $el['group_id'] == $group_id && $el['is_default'] == 'f') {
                             $is_exist_setting_for_group = true;
                         }
                     }
                 }
                 //Если настройки для каталога нет и эта основная
                 //специализация то ее добавляем в общий каталог
                 $data_extended = array();
                 $current_settings = $this->id > 0 ? $current_settings : $current_settings + $this->data;
                 if (!$is_exist_setting_for_catalog) {
                     $is_main_prof = (bool) $this->db()->val('SELECT 1 FROM freelancer 
                              WHERE uid = ?i AND spec = ?i LIMIT 1', $this->uid, $this->prof_id);
                     if ($is_main_prof) {
                         foreach ($current_settings as $el) {
                             $el['prof_id'] = 0;
                             $el['group_id'] = 0;
                             $el['is_default'] = true;
                             $data_extended[] = $el;
                         }
                     }
                 }
                 //Если нет настроек для группы раздела то добавляем текущии
                 //настройки как поумолчанию для группы
                 if (!$is_exist_setting_for_group) {
                     foreach ($current_settings as $el) {
                         $el['prof_id'] = 0;
                         $el['group_id'] = $group_id;
                         $el['is_default'] = true;
                         $data_extended[] = $el;
                     }
                 }
                 if ($data_extended) {
                     $this->data_extra_update = $data_extended;
                 }
             }
         }
     }
     return $this->is_valid;
 }
Ejemplo n.º 10
0
if (!$is_adm && is_emp()) {
    header("Location: /404.php");
    exit;
}
//------------------------------------------------------------------------------
$action = __paramInit('string', 'action');
$name = trim($_GET['user']);
$user_obj = new users();
$user_obj->GetUser($name);
$is_owner = $user_obj->uid == $uid;
if (!$user_obj->uid || !($is_owner || $is_adm)) {
    header("Location: /404.php");
    exit;
}
//------------------------------------------------------------------------------
$tservice = new tservices($user_obj->uid);
$errors = array();
$is_exist_feedbacks = 0;
switch ($action) {
    case 'edit':
        $tuid = __paramInit('int', 'tuid', NULL, 0);
        if ($tuid <= 0 || !$tservice->getByID($tuid)) {
            header("Location: /404.php");
            exit;
        }
        if ($is_adm) {
            $tservice->is_angry = FALSE;
        }
        $action = __paramInit('string', NULL, 'action', '');
        if ($action == 'save' && $tuid == __paramInit('int', NULL, 'id', 0)) {
            $is_exist_feedbacks = $tservice->isExistFeedbacks($tuid);
Ejemplo n.º 11
0
/**
 * Удаление сущности
 * 
 * @param  string $sId составной уникальный ID сущности
 * @param  int $sUid UID сздателя сущности
 * @param  string $sReason причина удаления
 * @param  string $sDrawFunc имя функции для выполнения после сохранения
 * @param  string $sParams JSON кодированные дополнительные параметры
 * @return xajaxResponse 
 */
function setDeleted($sId = '', $sUid = 0, $sReason = '', $sDrawFunc = '', $sParams = '')
{
    session_start();
    $objResponse = new xajaxResponse();
    list($rec_content_id, $rec_id, $rec_type) = explode('_', $sId);
    $aParams = _jsonArray($sParams);
    if ($sDrawFunc == 'stream0' || $sDrawFunc == 'stream1' || $sDrawFunc == 'stream2') {
        // удаление в потоках
        resolveContent($aParams['content_id'], $aParams['stream_id'], $sId, 2, $sUid, $aParams['content_cnt'], $aParams['status'], $aParams['is_sent'], $sReason, $objResponse);
    } else {
        require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/user_content.php';
        require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/permissions.php';
        $aPermissions = permissions::getUserPermissions($_SESSION['uid']);
        $user_content = new user_content($_SESSION['uid'], $aPermissions);
        $bSend = false;
        if ($user_content->hasContentPermissions($rec_content_id)) {
            if (strpos($sReason, '%USERNAME%') !== false && $sUid) {
                $user = new users();
                $user->GetUserByUID($sUid);
                $sReason = str_replace('%USERNAME%', $user->uname . ' ' . $user->usurname, $sReason);
            }
            switch ($rec_content_id) {
                case user_content::MODER_MSSAGES:
                    switch ($sDrawFunc) {
                        // дейсвие из переписки между юзерами
                        case 'updateLetter':
                            updateLetter($rec_id, $sUid, 2, $sReason, $objResponse);
                            break;
                        case 'delLetter':
                            // в потоке - важно чтобы поток не был потерян либо перехвачен
                        // в потоке - важно чтобы поток не был потерян либо перехвачен
                        default:
                            delLetter($aParams['stream_id'], $sUid, $rec_id . '_' . $rec_type, $sReason, $objResponse);
                            break;
                    }
                    break;
                case user_content::MODER_BLOGS:
                    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/blogs.php';
                    if ($rec_type == 1) {
                        // post
                        blogs::MarkDeleteBlog($_SESSION['uid'], $rec_id, $group, $base, $thread_id, $page, $msg, 0, $sReason);
                    } else {
                        // comment
                        blogs::MarkDeleteMsg($_SESSION['uid'], $rec_id, getRemoteIP(), $err, 0, $sReason);
                    }
                    $bSend = true;
                    break;
                case user_content::MODER_TSERVICES:
                    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/tservices/tservices.php';
                    $tserviceObj = new tservices();
                    if ($tserviceObj->Blocked($rec_id, $_SESSION['uid'], $sReason)) {
                        $objResponse->script("\$('ov-notice22-r').toggleClass('b-shadow_hide');");
                        $objResponse->script("\$\$('#__tservices_blocked,#__tservices_unblocked').toggleClass('b-button_hide');");
                    }
                    break;
                case user_content::MODER_SBR_REQV:
                    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/sbr_meta.php';
                    require_once $_SERVER['DOCUMENT_ROOT'] . '/classes/Finance/FinanceSmail.php';
                    if (sbr_meta::reqvBlocked($rec_id, $_SESSION['uid'], $sReason, 0, $_SESSION['login'])) {
                        $finSmail = new FinanceSmail();
                        $finSmail->financeBlocked($rec_id, $sReason);
                        $objResponse->script("\$('ov-notice22-r').toggleClass('b-shadow_hide');");
                        $objResponse->script("\$\$('#__finance_blocked,#__finance_unblocked').toggleClass('b-button_hide');");
                    }
                    break;
                default:
                    break;
            }
            if ($bSend) {
                $user_content->sendNotification($_SESSION['uid'], $sUid, $rec_content_id, $rec_id, $rec_type, 2, $sReason);
                $objResponse->script('window.location.reload(true)');
            }
        }
        return $objResponse;
    }
    $objResponse->script("delete banned.buffer['delreason_{$sId}'];");
    $objResponse->script("parent.\$\$(\"div[id^='ov-notice']\").setStyle('display', 'none');");
    $objResponse->script("parent.\$('ov-notice22-r').toggleClass('b-shadow_hide');");
    return $objResponse;
}