Exemplo n.º 1
0
 function write()
 {
     if (bff::$isAjax) {
         $nUserID = $this->security->getUserID();
         $p = $this->input->postm(array('email' => TYPE_STR, 'phone' => TYPE_NOHTML, 'message' => TYPE_NOHTML, 'captcha' => TYPE_STR));
         if (!$nUserID) {
             if (empty($p['email']) || !Func::IsEmailAddress($p['email'])) {
                 $this->errors->set('wrong_email');
             }
         }
         $p['phone'] = func::cleanComment($p['phone']);
         if (empty($p['phone'])) {
             $this->errors->set('no_phone');
         }
         $p['message'] = func::cleanComment($p['message']);
         if (empty($p['message'])) {
             $this->errors->set('no_message');
         }
         if (!$nUserID) {
             $oProtection = new CCaptchaProtection();
             if (!$oProtection->valid(isset($_SESSION['c2']) ? $_SESSION['c2'] : '', $p['captcha'])) {
                 $this->errors->set('wrong_captcha');
             }
         }
         if ($this->errors->no()) {
             unset($_SESSION['c2']);
             $this->db->execute('INSERT INTO ' . TABLE_CONTACTS . ' (user_id, email, phone, message, created) 
                            VALUES (' . $nUserID . ', ' . $this->db->str2sql($p['email']) . ', 
                                    ' . $this->db->str2sql($p['phone']) . ', ' . $this->db->str2sql(nl2br($p['message'])) . ', 
                                    ' . $this->db->getNOW() . ')');
             $nRecordID = $this->db->insert_id(TABLE_CONTACTS, 'id');
             if ($nRecordID) {
                 config::saveCount('contacts_new', 1);
                 bff::sendMailTemplate(array('user' => !$nUserID ? 'Аноним' : $this->security->getUserEmail(), 'email' => !$nUserID ? $p['email'] : $this->security->getUserEmail(), 'phone' => $p['phone'], 'message' => nl2br($p['message'])), 'admin_contacts', config::get('mail_admin', BFF_EMAIL_SUPPORT));
             }
         }
         $this->ajaxResponse(Errors::SUCCESS);
     }
     config::set('title', 'Связь с редактором - ' . config::get('title', ''));
     return $this->tplFetch('write.tpl');
 }
Exemplo n.º 2
0
 function ajax()
 {
     switch (func::GET('act')) {
         case 'item-u-update':
             $this->input->postm(array('id' => TYPE_UINT, 'uid' => TYPE_UINT, 'p' => TYPE_STR), $p);
             $nUserID = $this->security->getUserID();
             $nItemID = $p['id'];
             if (!$nItemID || empty($p['p']) || !$nUserID) {
                 $this->ajaxResponse(Errors::ACCESSDENIED);
             }
             $aItem = $this->db->one_array('SELECT id, cat1_id FROM ' . TABLE_BBS_ITEMS . ' 
                 WHERE id = ' . $nItemID . ' AND status = ' . BBS_STATUS_NEW . ' 
                     AND pass = '******'p']));
             if (!empty($aItem)) {
                 $this->db->execute('UPDATE ' . TABLE_BBS_ITEMS . ' SET user_id = ' . $nUserID . ' WHERE id = ' . $nItemID);
                 // закрепляем за пользователем
                 $this->db->execute('UPDATE ' . TABLE_USERS . ' SET items = items+1 WHERE user_id = ' . $nUserID);
                 // обновляем счетчик объявлений пользователя
             }
             $sUID = $this->security->getUID(false, 'post');
             $bPayPublication = !$this->checkFreePublicationsLimit($aItem['cat1_id'], $nUserID, $sUID);
             $this->ajaxResponse(array('res' => !empty($aItem), 'pp' => $bPayPublication));
             break;
         case 'item-edit-pass':
             $p = $this->input->postm(array('id' => TYPE_UINT, 'pass' => TYPE_STR));
             $aResponse = array();
             do {
                 if (!$p['id']) {
                     $this->errors->set(Errors::IMPOSSIBLE);
                     break;
                 }
                 if (empty($p['pass'])) {
                     $this->errors->set('editpass_empty');
                     break;
                 }
                 if ($this->isEditPassGranted($p['id'])) {
                     $aResponse['result'] = true;
                     break;
                 }
                 $aData = $this->db->one_array('SELECT id, user_id FROM ' . TABLE_BBS_ITEMS . ' 
                           WHERE id = ' . $p['id'] . ' AND pass = '******'pass']));
                 if (empty($aData)) {
                     $this->errors->set(Errors::ACCESSDENIED);
                     break;
                 } else {
                     if ($aData['user_id'] > 0) {
                         $userID = $this->security->getUserID();
                         if ($userID > 0) {
                             if ($aData['user_id'] != $userID) {
                                 $this->errors->set('editpass_not_owner');
                             } else {
                                 $aResponse['result'] = true;
                                 break;
                             }
                         } else {
                             $this->errors->set('editpass_auth');
                         }
                     } else {
                         $this->grantEditPass($p['id']);
                         $aResponse['result'] = true;
                     }
                 }
             } while (false);
             $aResponse['errno'] = $this->errors->no();
             $this->ajaxResponse($aResponse);
             break;
         case 'item-claim':
             $p = $this->input->postm(array('id' => TYPE_UINT, 'reasons' => TYPE_ARRAY_UINT, 'comment' => TYPE_STR, 'captcha' => TYPE_STR));
             $p['comment'] = func::cleanComment($p['comment']);
             $aResponse = array();
             do {
                 if (!$p['id']) {
                     $this->errors->set(Errors::IMPOSSIBLE);
                     break;
                 }
                 if (empty($p['reasons']) && $p['comment'] == '') {
                     $this->errors->set('enter_claim_reason');
                     break;
                 }
                 $nUserID = $this->security->getUserID();
                 if (!$nUserID) {
                     $oProtection = new CCaptchaProtection();
                     if (!$oProtection->valid(isset($_SESSION['c2']) ? $_SESSION['c2'] : '', $p['captcha'])) {
                         $aResponse['captcha_wrong'] = 1;
                         $this->errors->set('claim_wrong_captcha');
                         break;
                     }
                 }
                 unset($_SESSION['c2']);
                 $nReasons = array_sum($p['reasons']);
                 $res = $this->db->execute('INSERT INTO ' . TABLE_BBS_ITEMS_CLAIMS . ' (item_id, user_id, comment, reasons, ip, created)
                     VALUES(' . $p['id'] . ', ' . $nUserID . ', ' . $this->db->str2sql($p['comment']) . ', ' . $nReasons . ', :ip, ' . $this->db->getNOW() . ')
                 ', array(':ip' => func::getRemoteAddress()));
                 if ($res) {
                     config::saveCount('bbs_items_claims', 1);
                     bff::sendMailTemplate(array('user' => !$nUserID ? 'Аноним' : $this->security->getUserEmail(), 'claim' => $this->getItemClaimText($nReasons, nl2br($p['comment'])), 'item_url' => SITEURL . '/item/' . $p['id']), 'admin_bbs_claim', config::get('mail_admin', BFF_EMAIL_SUPPORT));
                 }
             } while (false);
             $aResponse['result'] = $this->errors->no();
             $this->ajaxResponse($aResponse);
             break;
         case 'img-upload':
             $aFailResponse = array('success' => false);
             $nUserID = $this->security->getUserID();
             $nItemID = $this->input->post('id', TYPE_UINT);
             if ($nItemID > 0) {
                 $aData = $this->db->one_array('SELECT user_id, uid, img, imgcnt, status, moderated FROM ' . TABLE_BBS_ITEMS . ' WHERE id = ' . $nItemID);
                 if (empty($aData)) {
                     $aFailResponse['error'] = 'Редактируемое объявление не найдено';
                     $this->ajaxResponse($aFailResponse);
                 }
                 if ($aData['status'] == BBS_STATUS_BLOCKED && $aData['moderated'] == 0) {
                     $aFailResponse['error'] = 'Объявление ожидает проверки модератора';
                     $this->ajaxResponse($aFailResponse);
                 }
                 // доступ к редактированию объявления возможен только по паролю
                 if ($aData['user_id'] == 0) {
                     if (!$this->isEditPassGranted($nItemID)) {
                         $aFailResponse['error'] = 'В доступе отказано';
                         $this->ajaxResponse($aFailResponse);
                     }
                 } else {
                     // автор объявления = загеристрированный пользователь
                     if (!$nUserID || $nUserID > 0 && $aData['user_id'] != $nUserID) {
                         $aFailResponse['error'] = 'Вы не является владельцем данного объявления.';
                         $this->ajaxResponse($aFailResponse);
                     }
                 }
             } else {
                 // грузить новые фотографии(без привязки к объявлению) можно пока без ограничений
                 // вернее с ограничением swfuploader'a, до перезагрузки :)
             }
             $uploadResult = Upload::swfuploadStart(true);
             if (!is_array($uploadResult)) {
                 $sErrorMessage = $uploadResult;
                 $this->ajaxResponse(array('success' => false, 'error' => $uploadResult), 1);
             }
             $sFilename = $this->initImages()->saveImageFileCustom($this->items_images_path, $nItemID, $uploadResult);
             if (!empty($sFilename) && $nItemID > 0) {
                 $aData['img'] .= (!empty($aData['img']) ? ',' : '') . $sFilename;
                 $this->db->execute('UPDATE ' . TABLE_BBS_ITEMS . ' SET imgcnt = imgcnt+1, img = ' . $this->db->str2sql($aData['img']) . '
                                     WHERE id = ' . $nItemID);
             }
             $this->ajaxResponse(array('success' => true, 'filename' => $sFilename, 'id' => $nItemID), 1);
             break;
         case 'img-delete':
             $nUserID = $this->security->getUserID();
             $nItemID = $this->input->id('id', 'p');
             if ($nItemID > 0) {
                 $aData = $this->db->one_array('SELECT user_id, uid, img, imgcnt, status, moderated FROM ' . TABLE_BBS_ITEMS . ' WHERE id = ' . $nItemID);
                 if (empty($aData)) {
                     $aFailResponse['error'] = 'Редактируемое объявление не найдено';
                     $this->ajaxResponse($aFailResponse);
                 }
                 if ($aData['status'] == BBS_STATUS_BLOCKED && $aData['moderated'] == 0) {
                     $aFailResponse['error'] = 'Объявление ожидает проверки модератора';
                     $this->ajaxResponse($aFailResponse);
                 }
                 // доступ к редактированию объявления возможен только по паролю
                 if ($aData['user_id'] == 0) {
                     if (!$this->isEditPassGranted($nItemID)) {
                         $aFailResponse['error'] = 'В доступе отказано';
                         $this->ajaxResponse($aFailResponse);
                     }
                 } else {
                     // автор объявления = загеристрированный пользователь
                     if (!$nUserID || $nUserID > 0 && $aData['user_id'] != $nUserID) {
                         $aFailResponse['error'] = 'Вы не является владельцем данного объявления.';
                         $this->ajaxResponse($aFailResponse);
                     }
                 }
             } else {
                 // удалять фотографии(без привязки к объявлению) можно без ограничений
             }
             if (!($sFilename = func::POST('filename'))) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             $this->initImages()->deleteImageFileCustom($this->items_images_path, $nItemID, $sFilename);
             $this->ajaxResponse(Errors::SUCCESS);
             break;
         case 'regions':
             $p = $this->input->postm(array('pid' => TYPE_UINT, 'form' => TYPE_STR, 'empty' => TYPE_STR));
             if (!$p['pid']) {
                 break;
             }
             $result = false;
             if ($p['form'] == 'options') {
                 $result = $this->regionsOptions(0, $p['pid'], true, !empty($p['empty']) ? $p['empty'] : 'Выбрать...');
             }
             $this->ajaxResponse($result);
             break;
         case 'sub-cats':
             $p = $this->input->postm(array('pid' => TYPE_UINT, 'dp' => TYPE_BOOL, 'dp_form' => TYPE_STR, 'format' => TYPE_STR, 'type' => TYPE_STR));
             if (!$p['pid']) {
                 break;
             }
             $returnTypes = 0;
             $returnSubTypes = 0;
             // Dirty. We get here category for our custom subtype
             if ($p['type'] == 'type') {
                 $type = $this->db->select('SELECT T.cat_id FROM ' . TABLE_BBS_CATEGORIES_TYPES . ' T WHERE T.id = ' . $p['pid'] . ' LIMIT 1');
                 $p['pid'] = $type[0]['cat_id'];
             }
             $aParentInfo = $this->db->one_array('SELECT id, numlevel, numleft, numright, prices, prices_sett, regions FROM ' . TABLE_BBS_CATEGORIES . ' WHERE id = ' . $p['pid']);
             $aDynprops = array();
             $aCats = $this->db->select('SELECT id, title, numlevel FROM ' . TABLE_BBS_CATEGORIES . ' WHERE pid = ' . $p['pid'] . ' AND enabled = 1 ORDER BY numleft');
             if ($p['type'] == 'type') {
                 $aCats = array();
             }
             if (empty($aCats)) {
                 $returnTypes = 1;
                 $tableName = TABLE_BBS_CATEGORIES_TYPES;
                 if ($p['type'] == 'type') {
                     $tableName = TABLE_BBS_CATEGORIES_SUBTYPES;
                     $returnTypes = 0;
                     $returnSubTypes = 1;
                 }
                 //если категории не найдены, пытаемся получить "типы"
                 $aCats = $this->db->select('SELECT T.id, T.title 
                                                 FROM ' . $tableName . ' T,
                                                      ' . TABLE_BBS_CATEGORIES . ' C 
                                                 WHERE ((C.numleft <= ' . $aParentInfo['numleft'] . ' AND C.numright > ' . $aParentInfo['numright'] . ') OR (C.id = ' . $p['pid'] . '))
                                                     AND C.id = T.cat_id AND T.enabled = 1 
                                                 GROUP BY T.id
                                                 ORDER BY C.numleft, T.num');
                 if ($p['dp']) {
                     $sDynpropsForm = '';
                     switch ($p['dp_form']) {
                         case 'add':
                             $sDynpropsForm = 'dynprops.form.add.php';
                             break;
                     }
                     $aDynprops = $this->initDynprops()->form($p['pid'], false, true, array(), 'dp', $sDynpropsForm, $this->module_dir_tpl);
                 }
             }
             if ($aParentInfo['prices']) {
                 $aParentInfo['prices_sett'] = unserialize($aParentInfo['prices_sett']);
                 if (is_array($aParentInfo['prices_sett'])) {
                     unset($aParentInfo['prices_sett']['ranges']);
                 }
             }
             $this->ajaxResponse(array('cats' => $aCats, 'is_types' => $returnTypes, 'is_subtypes' => $returnSubTypes, 'dp' => $aDynprops, 'regions' => $aParentInfo['regions'], 'prices' => $aParentInfo['prices'], 'prices_sett' => $aParentInfo['prices_sett']));
             break;
         case 'dp-child':
             $p = $this->input->postm(array('dp_id' => TYPE_UINT, 'dp_value' => TYPE_UINT));
             if (empty($p['dp_id']) && empty($p['dp_value'])) {
                 $this->ajaxResponse('');
             }
             $aChildDynpropForm = $this->initDynprops()->formChildAdd($p['dp_id'], $p['dp_value'], 'dynprops.form.child.php', $this->module_dir_tpl);
             $this->ajaxResponse($aChildDynpropForm);
             break;
         case 'dp-child-filter':
             $p = $this->input->postm(array('dp_id' => TYPE_UINT, 'dp_value' => TYPE_UINT));
             do {
                 if (!$p['dp_id'] || !$p['dp_value']) {
                     break;
                 }
                 $aPairs = array(array('parent_id' => $p['dp_id'], 'parent_value' => $p['dp_value']));
                 $dp = $this->initDynprops();
                 $aResult = array();
                 $aDynprops = $dp->getByParentIDValuePairs($aPairs, true);
                 if (!empty($aDynprops[$p['dp_id']])) {
                     $aDynprop = current($aDynprops[$p['dp_id']]);
                     $aResult = $dp->formChildEdit($aDynprop, 'search.dp.child.php', $this->module_dir_tpl);
                 } else {
                     $aResult['form'] = '';
                 }
                 $aResult['pid'] = $p['dp_id'];
                 $aResult['vid'] = $p['dp_value'];
                 $this->ajaxResponse(array('form' => $aResult, 'res' => true));
             } while (false);
             $this->ajaxResponse(array('form' => array(), 'res' => false));
             break;
         case 'item-publicate2':
             $bSave = $this->input->post('save', TYPE_BOOL);
             $nItemID = $this->input->post('item', TYPE_UINT);
             $nUserID = $this->security->getUserID();
             if (!$nItemID) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             if (!$nUserID) {
                 $this->ajaxResponse(Errors::ACCESSDENIED);
             }
             $aItem = $this->db->one_array('SELECT id, user_id, status, moderated, publicated, publicated_to,
                          cat_id, cat1_id, cat2_id, cat_type 
                     FROM ' . TABLE_BBS_ITEMS . ' WHERE id = ' . $nItemID . ' AND status != ' . BBS_STATUS_NEW . ' AND user_id = ' . $nUserID);
             if (empty($aItem)) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             if ($aItem['status'] == BBS_STATUS_BLOCKED) {
                 $this->errors->set('Невозможно продлить публикацию, поскольку объявление ' . ($aItem['moderated'] == 0 ? 'ожидает проверки' : 'отклонено'));
                 $this->ajaxResponse(null);
             }
             if ($aItem['status'] == BBS_STATUS_PUBLICATED) {
                 $this->errors->set('Невозможно продлить публикацию, поскольку объявление опубликовано');
                 $this->ajaxResponse(null);
             }
             if (!empty($bSave)) {
                 $nPeriod = $this->input->post('period', TYPE_UINT);
                 //проверяем корректность периода публикации
                 if (!($nPeriod >= 1 && $nPeriod <= 6)) {
                     $this->errors->set('wrong_publicated_period');
                     $this->ajaxResponse(null);
                 }
                 $publicateTo = $this->preparePublicatePeriodTo($nPeriod, $aItem['status'] == BBS_STATUS_PUBLICATED_OUT ? time() : strtotime($aItem['publicated_to']));
                 if ($aItem['status'] == BBS_STATUS_PUBLICATED_OUT) {
                     $toOld = strtotime($aItem['publicated_to']);
                     /* если разница между датой снятия с публикации и текущей датой
                      * более 3 дней, тогда поднимаем объявление вверх.
                      * в противном случае: оставлем дату старта публикации(pulicated) и дату порядка публикации(publicated_order) прежними
                      */
                     $bUpdatePublicatedOrder = time() - $toOld > 259200;
                     //60*60*24*3
                     $sqlNOW = $this->db->getNOW();
                     $res = $this->db->execute('UPDATE ' . TABLE_BBS_ITEMS . ' 
                         SET publicated_to = ' . $this->db->str2sql($publicateTo) . ',
                             ' . ($bUpdatePublicatedOrder ? ' publicated = ' . $sqlNOW . ', publicated_order = ' . $sqlNOW . ',' : '') . '
                             status_prev = status,
                             status = ' . BBS_STATUS_PUBLICATED . ',
                             moderated = 0
                         WHERE id = ' . $nItemID . '
                     ');
                     if (!empty($res)) {
                         # накручиваем счетчики кол-ва опубликованных объявлений:
                         # в категориях и типах:
                         $this->itemsCounterUpdate(array($aItem['cat1_id'], $aItem['cat2_id'], $aItem['cat_id']), !empty($aItem['cat_type']) ? array($aItem['cat_type']) : array(), true, true);
                     }
                 } else {
                     // продление опубликованных пока НЕ делаем
                     //                        $res = $this->db->execute('UPDATE '.TABLE_BBS_ITEMS.'
                     //                            SET publicated_to = '.$this->db->str2sql( $publicateTo ).'
                     //                            WHERE id = '.$nItemID.'
                     //                        ');
                 }
                 $this->ajaxResponse(array('res' => $this->errors->no()));
             }
             $aResponse['res'] = $this->errors->no();
             $aResponse['popup'] = $this->tplFetchPHP($aItem, 'items.publicate2.popup.php');
             $this->ajaxResponse($aResponse);
             break;
     }
     $this->ajaxResponse(Errors::IMPOSSIBLE);
 }
Exemplo n.º 3
0
 private function resultURL($nBillID, $fAmount = 0, $nPaymentSystem = 0, $nItemID = 0, $nSvcID = 0, $mSvcExtra = 0)
 {
     $sPaymentSystem = $this->getPaymentSystemTitle($nPaymentSystem);
     #Проверяем формат номера счета
     if (!is_numeric($nBillID)) {
         $this->log($sPaymentSystem . ': некорректный номер счета, (#' . $nBillID . ')');
         return $this->payError('wrong_bill_id', 2);
     }
     $aBill = $this->getBill($nBillID);
     if (empty($aBill)) {
         $this->log($sPaymentSystem . ': Оплачен несуществующий счёт #' . $nBillID);
         return $this->payError('pay_error', 2);
     }
     if ($aBill['status'] == self::statusCanceled || $aBill['status'] == self::statusCompleted) {
         $this->log($sPaymentSystem . ': Оплачен уже ранее оплаченный счёт или счёт с другим статусом, #' . $nBillID);
         return $this->payError('pay_error', 2);
     }
     # Проверка суммы
     if ($fAmount < $aBill['amount']) {
         $this->log("{$sPaymentSystem}: Сумма оплаты({$fAmount}) счета#{$nBillID} меньше выставленной ранее({$aBill['amount']})");
         return $this->payError('amount_error', 2);
     }
     if ($this->changeBillStatus($nBillID, self::statusCompleted, $aBill['status']) !== false) {
         //Помечаем дату оплаты
         $res = $this->payBill($nBillID, false);
         if ($res) {
             $nUserID = $aBill['user_id'];
             if ($nUserID > 0) {
                 // обновляем баланс пользователя (если такой есть)
                 $this->updateBalance($aBill['user_id'], $fAmount, '+');
                 // помечаем текущий баланс в информации о счете
                 $aUserData = $this->db->one_array('SELECT login as email, balance FROM ' . TABLE_USERS . ' WHERE user_id = ' . $nUserID);
                 $balance = (double) $aUserData['balance'];
                 $this->db->execute('UPDATE ' . TABLE_BILLS . ' SET user_balance = ' . $balance . ' WHERE id = ' . $nBillID);
             } else {
                 $balance = $fAmount;
             }
             // активируем услугу, если такая была заявлена
             if ($nItemID > 0 && $nSvcID > 0) {
                 /** @var Services module */
                 $oServices = bff::i()->GetModule('Services');
                 do {
                     $svc = $oServices->getServiceSettings($nSvcID);
                     if (empty($svc)) {
                         break;
                     }
                     $price = $svc['price'];
                     $sDescription = $oServices->buildServiceBillDescription($nSvcID, $nItemID);
                     if ($price > $balance) {
                         $this->log('Ошибка активации услуги в момент пополнения счета, недостаточно средств для активации (' . $balance . ' из ' . $price . ')');
                         break;
                     }
                     // создаем счет "активации услуги"
                     $nBillID = $this->createBill_OutService($nItemID, $nSvcID, $nUserID, 0, $price, Bills::statusProcessing, $sDescription);
                     if (!$nBillID) {
                         break;
                     }
                     // активируем услугу
                     $res = $oServices->activateItemSvc($nItemID, $nSvcID, $mSvcExtra);
                     if (!$res) {
                         break;
                     }
                     // ^ ошибки выставляются тут
                     // списываем с баланса пользователя
                     if ($nUserID > 0) {
                         $res = $this->updateBalance($nUserID, $price, '-');
                         if ($res) {
                             $balance -= $price;
                         }
                     } else {
                         $balance = 0;
                     }
                     //актуaлизируем информацию о счете
                     $this->updateBill($nBillID, $balance, false, self::statusCompleted);
                     if ($nSvcID == Services::typePress && $nUserID > 0) {
                         // уведомляем о скором размещении в прессе
                         bff::sendMailTemplate(array('item_url' => SITEURL . '/item/' . $nItemID, 'email' => $aUserData['email']), 'member_bbs_press_payed', $aUserData['email']);
                     }
                 } while (false);
             }
         }
         return true;
     }
     return false;
 }
Exemplo n.º 4
0
 function ajax()
 {
     $nUserID = $this->security->getUserID();
     if (!bff::$isAjax) {
         $this->errors->set(Errors::IMPOSSIBLE);
     }
     $aResponse = array();
     switch (func::GET('act')) {
         case 'init':
             $aData =& $aResponse;
             $this->input->postm(array('type' => TYPE_UINT), $aData);
             $aServices = $this->db->select('SELECT id, keyword, settings, description FROM ' . TABLE_SERVICES . ' ORDER BY id');
             $aServicesData = array();
             foreach ($aServices as $v) {
                 $sett = unserialize($v['settings']);
                 $sett['desc'] = $v['description'];
                 $aServicesData[$v['keyword']] = $sett;
             }
             $aData['popup'] = $this->tplFetchPHP($aServicesData, 'items.svc.popup.php');
             break;
         case 'activate':
             $this->input->postm(array('item' => TYPE_UINT, 'svc' => TYPE_UINT), $aResponse);
             $nItemID = $aResponse['item'];
             $nSvcID = $aResponse['svc'];
             if (!$nItemID || !$nSvcID) {
                 $this->errors->set(Errors::IMPOSSIBLE);
                 break;
             }
             if ($nUserID > 0) {
                 $aUserData = $this->db->one_array('SELECT blocked, blocked_reason, balance, login as email FROM ' . TABLE_USERS . ' WHERE user_id = ' . $nUserID);
                 if ($aUserData['blocked']) {
                     $this->errors->set('Ваш аккаунт заблокирован по причине:<br/>' . $aUserData['blocked_reason']);
                     break;
                 }
                 $balance =& $aUserData['balance'];
                 if ($balance <= 0) {
                     $balance = 0;
                 }
             } else {
                 $balance = 0;
             }
             /** @var Bills module */
             $oBills = bff::i()->GetModule('Bills');
             $svc = $this->getServiceSettings($nSvcID);
             if (empty($svc) || !$svc['price']) {
                 $this->errors->set(Errors::IMPOSSIBLE);
                 break;
             }
             $price = $svc['price'];
             $sDescription = $this->buildServiceBillDescription($nSvcID, $nItemID);
             // денег на счету не хватило(или неавторизованный пользователь), выставляем счет, формируем форму оплаты
             if (!$nUserID || $price > $balance) {
                 $fAmount = round($price - $balance);
                 $nPaymentSystem = Bills::psystemRobox;
                 $nBillID = $oBills->createBill_InPay($nUserID, $balance, $fAmount, $fAmount, 'rur', $nPaymentSystem, Bills::typeInPay, Bills::statusWaiting, 'Пополнение счета', $nItemID, $nSvcID);
                 $aResponse['pay'] = true;
                 $aResponse['form'] = $oBills->buildPayForm($fAmount, $nPaymentSystem, $nBillID, $nItemID, $nSvcID);
                 break;
             }
             // создаем счет
             $nBillID = $oBills->createBill_OutService($nItemID, $nSvcID, $nUserID, 0, $price, Bills::statusProcessing, $sDescription);
             if (!$nBillID) {
                 $this->errors->set(Errors::IMPOSSIBLE);
                 break;
             }
             // активируем услугу
             $res = $this->activateItemSvc($nItemID, $nSvcID, 0);
             if (!$res) {
                 break;
             }
             // ^ ошибки выставляются тут
             // списываем с баланса пользователя
             $res = $oBills->updateBalance($nUserID, $price, '-');
             if ($res) {
                 $balance -= $price;
                 $this->security->setBalance($balance);
             }
             $aResponse['balance'] = $balance;
             //актуaлизируем информацию о счете
             $oBills->updateBill($nBillID, $balance, false, Bills::statusCompleted);
             if ($nSvcID == self::typePress) {
                 // уведомляем о скором размещении в прессе
                 bff::sendMailTemplate(array('item_url' => SITEURL . '/item/' . $nItemID, 'email' => $aUserData['email']), 'member_bbs_press_payed', $aUserData['email']);
             }
             break;
         default:
             $this->errors->set(Errors::IMPOSSIBLE);
     }
     $aResponse['res'] = $this->errors->no();
     $this->ajaxResponse($aResponse);
 }
Exemplo n.º 5
0
 function items_listing()
 {
     if (!$this->haveAccessTo('items-listing')) {
         return $this->showAccessDenied();
     }
     if (bff::$isAjax) {
         switch (func::GET('act')) {
             case 'press':
                 if (!$this->haveAccessTo('items-press')) {
                     $this->ajaxResponse(Errors::ACCESSDENIED);
                 }
                 $nItemID = $this->input->get('rec', TYPE_UINT);
                 $aData = $this->db->one_array('SELECT I.id, I.press, U.login as email 
                                                FROM ' . TABLE_BBS_ITEMS . ' I
                                                     LEFT JOIN ' . TABLE_USERS . ' U ON I.user_id = U.user_id
                                                WHERE I.id = ' . $nItemID);
                 if (empty($aData) || $aData['press'] != BBS_PRESS_PAYED) {
                     $this->ajaxResponse(Errors::IMPOSSIBLE);
                 }
                 $res = $this->db->execute('UPDATE ' . TABLE_BBS_ITEMS . ' SET press = ' . BBS_PRESS_PUBLICATED . ' WHERE id = ' . $nItemID);
                 if ($res && !empty($aData['email'])) {
                     bff::sendMailTemplate(array('item_url' => SITEURL . '/item/' . $nItemID, 'email' => $aData['email']), 'member_bbs_press_publicated', $aData['email']);
                     $this->ajaxResponse(Errors::SUCCESSFULL);
                 }
                 break;
             case 'delete':
                 if (!$this->haveAccessTo('items-edit')) {
                     $this->ajaxResponse(Errors::ACCESSDENIED);
                 }
                 $nItemID = $this->input->id('rec', 'p');
                 if ($nItemID) {
                     $aItemData = $this->db->one_array('SELECT user_id FROM ' . TABLE_BBS_ITEMS . ' WHERE id = ' . $nItemID);
                     if (empty($aItemData)) {
                         break;
                     }
                     $res = $this->itemDelete($nItemID, $aItemData['user_id']);
                     $this->ajaxResponse($res ? Errors::SUCCESSFULL : Errors::IMPOSSIBLE);
                 }
                 break;
         }
         $this->ajaxResponse(Errors::IMPOSSIBLE);
     }
     $this->input->getm(array('search' => TYPE_STR, 'cat_id' => TYPE_UINT, 'svc' => TYPE_UINT, 'page' => TYPE_UINT, 'perpage' => TYPE_UINT, 'uid' => TYPE_UINT, 'mod' => TYPE_UINT, 'press' => TYPE_UINT), $aData);
     $sqlWhere = array();
     if (!empty($aData['search'])) {
         if (intval($aData['search']) > 0) {
             $sqlWhere[] = 'I.id = ' . intval($aData['search']);
         } else {
             $sqlWhere[] = 'I.descr LIKE ' . $this->db->str2sql('%' . $aData['search'] . '%');
         }
     }
     if (!$this->security->isSuperAdmin()) {
         $aCatsAllowed = $this->security->getAllowedBBSCategories();
         if (empty($aCatsAllowed)) {
             $sqlWhere[] = 'I.cat1_id = -1';
         } else {
             $sqlWhere[] = 'I.cat1_id IN (' . join(',', $aCatsAllowed) . ')';
         }
     }
     if ($aData['cat_id'] > 0 && (!isset($aCatsAllowed) || in_array($aData['cat_id'], $aCatsAllowed))) {
         $sqlWhere[] = '(I.cat_id = ' . $aData['cat_id'] . ' OR I.cat1_id = ' . $aData['cat_id'] . ' OR I.cat2_id = ' . $aData['cat_id'] . ')';
     }
     if ($aData['mod']) {
         $sqlWhere[] = 'I.moderated = 0 AND I.status!=' . BBS_STATUS_PUBLICATED_OUT;
     } elseif ($aData['press']) {
         $sqlWhere[] = 'I.press > 0';
     } else {
         $sqlWhere[] = 'I.status IN (' . BBS_STATUS_PUBLICATED . ',' . BBS_STATUS_PUBLICATED_OUT . ')';
     }
     if ($aData['svc'] > 0) {
         $sqlWhere[] = 'I.svc = ' . $aData['svc'];
     }
     if ($aData['uid'] > 0) {
         $aData['uinfo'] = $this->db->one_array('SELECT name, email FROM ' . TABLE_USERS . ' WHERE user_id = ' . $aData['uid']);
         if (!empty($aData['uinfo'])) {
             $sqlWhere[] = 'I.user_id = ' . $aData['uid'];
         }
     }
     $sqlWhere = !empty($sqlWhere) ? 'WHERE ' . join(' AND ', $sqlWhere) : '';
     $nCount = $this->db->one_data('SELECT COUNT(I.id) FROM ' . TABLE_BBS_ITEMS . ' I ' . $sqlWhere);
     $this->prepareOrder($orderBy, $orderDirection, 'I.created,desc', array('I.created'));
     $aPerpage = $this->preparePerpage($aData['perpage'], array(20, 40, 60));
     $aData['order'] = "{$orderBy},{$orderDirection}";
     $sFilter = http_build_query($aData);
     unset($aData['page']);
     $this->generatePagenation($nCount, $aData['perpage'], "index.php?s={$this->module_name}&ev=items_listing&{$sFilter}&{pageId}", $sqlLimit);
     $aData['f'] = $sFilter;
     $aData['items'] = $this->db->select('SELECT I.id, I.status, I.press, I.status_prev, I.user_id, I.descr, I.price, CL.id as claims
                 FROM ' . TABLE_BBS_ITEMS . ' I
                     LEFT JOIN ' . TABLE_BBS_ITEMS_CLAIMS . ' CL ON I.id = CL.item_id
                 ' . $sqlWhere . "\n                    GROUP BY I.id\n                    ORDER BY {$orderBy} {$orderDirection} {$sqlLimit}");
     $aData['cats'] = $this->getCategoriesOptions($aData['cat_id'], 'все категории', 0, isset($aCatsAllowed) ? $aCatsAllowed : false);
     $aData['svcs'] = bff::i()->GetModule('Services')->getItemsSvcFilterOptions($aData['svc'], 'все услуги');
     $aData['perpage'] = $aPerpage;
     $this->tplAssign('curr_sign', $this->items_currency['sign']);
     $this->tplAssignByRef('aData', $aData);
     return $this->tplFetch('admin.items.listing.tpl');
 }
Exemplo n.º 6
0
 function ajax()
 {
     if (bff::$isAjax) {
         switch (func::GETPOST('act')) {
             case 'subscribe':
                 /*
                  * При подписке:
                  * - email выступает в дальнейшем в качестве логина
                  * - пароль генерируется автоматически
                  */
                 $sName = $this->input->post('name', TYPE_NOHTML);
                 $sEmail = mb_strtolower($this->input->post('email', TYPE_NOHTML));
                 $response = '';
                 do {
                     if (empty($sEmail) || !func::IsEmailAddress($sEmail)) {
                         $response = 0;
                         break;
                         // некорректно указан email
                     }
                     $isSubscribed = $this->db->one_data('SELECT user_id FROM ' . TABLE_USERS . ' WHERE login='******'email' - для рассылки, 'login' - для авторизации
                     $nUserID = $this->userCreate(array('login' => $sEmail, 'email' => $sEmail, 'password' => $sPassword, 'name' => $sName, 'subscribed' => 1, 'ip_reg' => func::getRemoteAddress(true)), self::GROUPID_MEMBER);
                     if ($nUserID) {
                         $response = 1;
                         // успешно подписались
                         # высылаем письмо (ставим в очередь на рассылку)
                         CMail::SendQueue('subscribe', array('user_id' => $nUserID));
                     } else {
                         $response = 4;
                         // системная ошибка
                     }
                 } while (false);
                 $this->ajaxResponse(array('result' => $response));
                 break;
             case 'enter':
                 if ($this->security->isLogined()) {
                     $this->ajaxResponse(array('result' => 'login-ok'));
                 }
                 $aData = $this->input->postm(array('email' => TYPE_STR, 'pass' => TYPE_STR, 'reg' => TYPE_BOOL));
                 if (!func::IsEmailAddress($aData['email'])) {
                     $this->errors->set('wrong:email');
                     break;
                     //email не корректный
                 }
                 if ($this->security->checkBan(false, func::getRemoteAddress(), $aData['email'], true)) {
                     $this->errors->set(Errors::ACCESSDENIED);
                     break;
                     //не прошли бан-фильтр
                 }
                 if ($aData['reg']) {
                     //регистрация
                     if (empty($aData['pass']) || strlen($aData['pass']) < 3) {
                         $this->errors->set('password_short');
                         break;
                         //пароль слишком короткий
                     }
                     $aData['email_hash'] = func::getEmailHash($aData['email']);
                     if ($this->isEmailExists($aData['email_hash'])) {
                         $this->errors->set('email_exist');
                         break;
                         //email уже занят
                     }
                     $this->getActivationInfo($sCode, $sLink);
                     $nUserID = $this->userCreate(array('login' => $aData['email'], 'email' => $aData['email'], 'email_hash' => $aData['email_hash'], 'password' => $aData['pass'], 'ip_reg' => Func::getRemoteAddress(true), 'activatekey' => $sCode, 'activated' => 0), self::GROUPID_MEMBER);
                     if ($nUserID) {
                         //$this->userAUTH($aData['email'], $aData['pass'], null, true);
                         $res = bff::sendMailTemplate(array('password' => $aData['pass'], 'email' => $aData['email'], 'activate_link' => "<a href=\"{$sLink}\">{$sLink}</a>"), 'member_registration', $aData['email']);
                         $this->ajaxResponse(array('result' => 'reg-ok'));
                     } else {
                         $this->ajaxResponse(Errors::IMPOSSIBLE);
                     }
                 } else {
                     //авторизация
                     $nResult = $this->userAUTH($aData['email'], $aData['pass'], null, true);
                     if ($nResult == 1) {
                         //$this->security->setRememberMe('u', $aData['email'], $aData['pass']);
                         bff::i()->Bbs_getFavorites(true);
                         $bReload = false;
                         if (!empty($_SERVER['HTTP_REFERER'])) {
                             if (stripos($_SERVER['HTTP_REFERER'], '/item/') !== FALSE || stripos($_SERVER['HTTP_REFERER'], '/items/fav') !== FALSE) {
                                 $bReload = true;
                             }
                         }
                         $userMenu = $this->tplFetch('user.menu.tpl');
                         $this->ajaxResponse(array('result' => 'login-ok', 'usermenu' => $userMenu, 'reload' => $bReload));
                     } else {
                         $mResponse = null;
                         switch ($nResult) {
                             case 0:
                                 $this->errors->set('email_or_pass_incorrect');
                                 break;
                             case -3:
                                 $this->errors->set('activate_first');
                                 break;
                                 //активируйте ваш аккаунт
                             //активируйте ваш аккаунт
                             case -2:
                                 $this->errors->set(Errors::ACCESSDENIED);
                                 break;
                                 //удален
                         }
                         if (is_array($nResult)) {
                             if ($nResult['res'] == -1) {
                                 $this->errors->set('Аккаунт заблокирован.' . (!empty($nResult['reason']) ? ' <br/><b>Причина:</b>' . nl2br($nResult['reason']) : ''));
                             }
                         }
                     }
                 }
                 break;
         }
     }
     $this->ajaxResponse(null);
 }