Exemplo n.º 1
0
 function ajax()
 {
     if (!$this->haveAccessTo('edit') || !bff::$isAjax) {
         $this->ajaxResponse(Errors::ACCESSDENIED);
     }
     switch (func::GET('act')) {
         case 'del':
             $nContactID = func::POST('rec', false, true);
             if ($nContactID <= 0) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             $this->db->execute('DELETE FROM ' . TABLE_CONTACTS . ' WHERE id = ' . $nContactID);
             $this->ajaxResponse(Errors::SUCCESSFULL);
             break;
         case 'send':
             $nType = func::POST('type', false, true);
             switch ($nType) {
                 case CONTACTS_TYPE_CONTACT:
                     //
                     break;
             }
             $this->ajaxResponse(Errors::IMPOSSIBLE);
             break;
     }
     $this->ajaxResponse(Errors::IMPOSSIBLE);
 }
Exemplo n.º 2
0
 /**
  * CRON задачи по рассылке писем
  */
 function cron()
 {
     if (empty($_GET['c']) || $_GET['c'] != 17) {
         return;
     }
     set_time_limit(0);
     switch (func::GET('action')) {
         //уведомления посетителя об успешной подписке
         case 'enotify-subscribe':
             $nLimit = 10;
             $aNotify = $this->db->select(' SELECT EN.id, EN.user_id, U.name, U.email, U.password
                         FROM ' . TABLE_ENOTIFY_SUBSCRIBE . ' as EN, ' . TABLE_USERS . ' as U
                         WHERE EN.user_id = U.user_id
                         ORDER BY EN.created
                         LIMIT ' . $nLimit . '
                         FOR UPDATE 
                        ');
             if (!empty($aNotify)) {
                 try {
                     $aNotifyID = array();
                     # инициализируем класс рассылки
                     $mailer = new CMail();
                     $mailer->From = config::get('mail_noreply', BFF_EMAIL_NOREPLY);
                     //"E-Mail адрес уведомлений" из настроек сайта
                     # подготавливаем заголовок письма
                     $mailer->FromName = 'ILove.zp.ua';
                     $mailer->Subject = 'Заявка на участие в акции "Согрей любовью родной город"';
                     $sTpl = nl2br($this->getMailTemplateContent('member_subscribe'));
                     foreach ($aNotify as $v) {
                         # подготавливаем тело письма
                         $mailer->AltBody = '';
                         $mailer->MsgHTML(strtr($sTpl, array('{name}' => $v['name'], '{email}' => $v['email'], '{password}' => $v['password'])));
                         # отправляем письмо
                         $mailer->AddAddress($v['email']);
                         if ($mailer->Send()) {
                             $aNotifyID[] = $v['id'];
                         }
                         $mailer->ClearAddresses();
                         usleep(150000);
                         // sleep for 0.15 second
                     }
                     $this->db->execute('DELETE FROM ' . TABLE_ENOTIFY_SUBSCRIBE . ' WHERE id IN(' . join(',', $aNotifyID) . ')');
                 } catch (phpmailerException $e) {
                     $this->errors->set($e->getMessage());
                 }
             }
             break;
     }
     if (!$this->errors->no()) {
         echo print_r($this->errors->get(), true), '\\n';
     }
     exit;
 }
Exemplo n.º 3
0
 function settings()
 {
     if (!$this->haveAccessTo('settings')) {
         return $this->showAccessDenied();
     }
     if (bff::$isAjax) {
         switch (func::GET('act')) {
             case 'update':
                 $nServiceID = $this->input->post('id', TYPE_UINT);
                 if (!$nServiceID) {
                     $this->ajaxResponse(Errors::UNKNOWNRECORD);
                 }
                 $sDescription = $this->input->post('description', TYPE_STR);
                 $aService = $this->db->one_array('SELECT * FROM ' . TABLE_SERVICES . ' WHERE id = ' . $nServiceID);
                 if (empty($aService)) {
                     $this->ajaxResponse(Errors::UNKNOWNRECORD);
                 }
                 $bUpdate = false;
                 switch ($aService['keyword']) {
                     case 'publicate':
                     case 'up':
                     case 'mark':
                     case 'premium':
                     case 'press':
                         $p = $this->input->postm(array('price' => TYPE_UNUM));
                         $bUpdate = true;
                         break;
                 }
                 if ($bUpdate) {
                     $this->db->execute('UPDATE ' . TABLE_SERVICES . ' 
                                 SET settings = ' . $this->db->str2sql(serialize($p)) . ',
                                     description = ' . $this->db->str2sql($sDescription) . ',
                                     modified = ' . $this->db->getNOW() . ',
                                     modified_uid = ' . $this->security->getUserID() . '
                                 WHERE id = ' . $nServiceID);
                     $this->ajaxResponse(Errors::SUCCESSFULL);
                 }
                 break;
         }
         $this->ajaxResponse(Errors::IMPOSSIBLE);
     }
     $aData = array('svc' => array());
     $aServices = $this->db->select('SELECT S.*, U.login as modified_login FROM ' . TABLE_SERVICES . ' S
                                 LEFT JOIN ' . TABLE_USERS . ' U ON S.modified_uid = U.user_id');
     foreach ($aServices as $v) {
         $v['settings'] = unserialize($v['settings']);
         $aData['svc'][$v['keyword']] = $v;
     }
     $this->adminCustomCenterArea();
     $this->includeJS('wysiwyg');
     return $this->tplFetchPHP($aData, 'admin.settings.php');
 }
Exemplo n.º 4
0
 function ajax()
 {
     if (!bff::$isAjax) {
         $this->ajaxResponse(Errors::ACCESSDENIED);
     }
     $nBillID = $this->input->post('bid', TYPE_UINT);
     switch (func::GET('act')) {
         case 'user-autocomplete':
             $sQ = $this->input->post('q', TYPE_STR);
             //получаем список подходящих по логину пользователей, исключая:
             // - неактивированных пользователей
             $aResult = $this->db->select('SELECT U.user_id as id, U.login FROM ' . TABLE_USERS . ' U 
                           WHERE U.activated = 1
                             AND U.login LIKE (' . $this->db->str2sql("{$sQ}%") . ')                                    
                           ORDER BY U.login
                           LIMIT 12');
             $aUsers = array();
             foreach ($aResult as $u) {
                 $aUsers[$u['id']] = $u['login'];
             }
             unset($aResult);
             $this->ajaxResponse($aUsers);
             break;
             /**
              * Изменение статуса счета:
              * @param integer $nStatus ID статуса, допустимые: завершен, отменен
              */
         /**
          * Изменение статуса счета:
          * @param integer $nStatus ID статуса, допустимые: завершен, отменен
          */
         case 'status':
             if (!$this->haveAccessTo('edit')) {
                 $this->ajaxResponse(Errors::ACCESSDENIED);
             }
             if (!$nBillID) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             $nStatus = $this->input->post('status', TYPE_UINT);
             if (!in_array($nStatus, array(self::statusCompleted, self::statusCanceled))) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             $aBill = $this->db->one_array('SELECT user_id, type, status, amount FROM ' . TABLE_BILLS . ' WHERE id=' . $nBillID . ' LIMIT 1');
             if (!$aBill) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             $res = $this->changeBillStatus($nBillID, $nStatus, $aBill['status']);
             if ($res) {
                 // обновляем баланс пользователя
                 // в случае закрытия счета типа: "пополнение счета"
                 if ($aBill['type'] == self::typeInPay && $nStatus == self::statusCompleted) {
                     $this->updateBalance($aBill['user_id'], $aBill['amount'], '+');
                 }
             }
             $this->ajaxResponse(array('status' => $nStatus));
             break;
             /**
              * Проверка состояния счета:
              * 1) webmoney - X18 интерфейс
              */
         /**
          * Проверка состояния счета:
          * 1) webmoney - X18 интерфейс
          */
         case 'check':
             if (!$this->haveAccessTo('edit')) {
                 $this->ajaxResponse(Errors::ACCESSDENIED);
             }
             if (!$nBillID) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             $aBill = $this->getBill($nBillID);
             if (!$aBill) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             switch ($aBill['psystem']) {
                 case self::psystemWMZ:
                 case self::psystemWME:
                 case self::psystemWMR:
                 case self::psystemWMU:
                     # Интерфейс запроса статуса платежа X18
                     $sResponse = '';
                     $wmid = config::get('ps_webmoney_id');
                     $lmi_payee_purse = $this->getWebmoneyPurse($aBill['psystem']);
                     // кошелек-получатель, на который совершался платеж
                     $md5 = strtoupper(md5($wmid . $lmi_payee_purse . $nBillID . $this->getWebmoneyPurseSecret($aBill['psystem'])));
                     # т.к. используется хеш, то 2 других метода авторизации - sign и secret_key - оставляем пустыми
                     $request = "<merchant.request>  \n                                      <wmid>{$wmid}</wmid>  \n                                      <lmi_payee_purse>{$lmi_payee_purse}</lmi_payee_purse>  \n                                      <lmi_payment_no>{$nBillID}</lmi_payment_no>  \n                                      <sign></sign><md5>{$md5}</md5><secret_key></secret_key> \n                                    </merchant.request>";
                     $ch = curl_init("https://merchant.webmoney.ru/conf/xml/XMLTransGet.asp");
                     curl_setopt($ch, CURLOPT_HEADER, 0);
                     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                     curl_setopt($ch, CURLOPT_POST, 1);
                     curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
                     //                        curl_setopt($ch, CURLOPT_CAINFO, "/path/to/verisign.cer");
                     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                     $result = curl_exec($ch);
                     curl_close($ch);
                     $xmlres = simplexml_load_string($result);
                     // смотрим результат выполнения запроса
                     $retval = strval($xmlres->retval);
                     if ($retval == -8) {
                         $sResponse = "Платеж №<b>{$nBillID}</b> не проводился";
                     } elseif ($retval != 0) {
                         // если результат не равен -8 и не равен 0, то возникла ошибка при обработке запроса
                         $sResponse = "Запрос составлен некорректно ({$retval})";
                     } else {
                         // если результат равен 0, то платеж с таким номером проведен
                         $wmtranid = strval($xmlres->operation->attributes()->wmtransid);
                         $date = strval($xmlres->operation->operdate);
                         $payer = strval($xmlres->operation->pursefrom);
                         $ip = strval($xmlres->operation->IPAddress);
                         $sResponse = "Платеж №<b>{$nBillID}</b> завершился успешно.<br /> \n                                   Он был произведен {$date} с кошелька {$payer}.<br /> \n                                   Плательщик использовал IP-адрес {$ip}.<br /> \n                                   WM-транзакции присвоен идентификатор {$wmtranid}.";
                     }
                     $this->ajaxResponse($sResponse);
                     break;
                 case self::psystemRobox:
                     if (!config::get('ps_robox_on', 0)) {
                         $this->ajaxResponse(Errors::IMPOSSIBLE);
                     }
                     $robox_login = config::get('ps_robox_login');
                     $robox_pass2 = config::get('ps_robox_pass2');
                     $request = 'https://merchant.roboxchange.com/WebService/Service.asmx/OpState?MerchantLogin='******'&InvoiceID=' . $nBillID . '&Signature=' . md5($robox_login . ':' . $nBillID . ':' . $robox_pass2);
                     $ch = curl_init($request);
                     curl_setopt($ch, CURLOPT_HEADER, 0);
                     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                     //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                     $result = curl_exec($ch);
                     curl_close($ch);
                     /**
                     
                         <?xml version="1.0" encoding="utf-8" ?> 
                         <OperationStateResponse xmlns="http://merchant.roboxchange.com/WebService/"> 
                             <Result> 
                                 <Code>integer</Code> 
                                 <Description>string</Description> 
                             </Result> 
                             <State> 
                                 <Code>integer</Code> 
                                 <RequestDate>datetime</RequestDate> 
                                 <StateDate>datetime</StateDate> 
                             </State> 
                             <Info> 
                                 <IncCurrLabel>string</IncCurrLabel> 
                                 <IncSum>decimal</IncSum> 
                                 <IncAccount>string</IncAccount> 
                                 <PaymentMethod> 
                                     <Code>string</Code> 
                                     <Description>string</Description> 
                                 </PaymentMethod> 
                                 <OutCurrLabel>string</OutCurrLabel> 
                                 <OutSum>decimal</OutSum> 
                             </Info> 
                         </OperationStateResponse>                        
                     */
                     $xml = simplexml_load_string($result);
                     // смотрим результат выполнения запрос
                     $sResponse = '';
                     if (empty($result)) {
                         $sResponse = 'Ошибка ответа сервера Robox';
                     } elseif (intval($xml->Result->Code) != 0) {
                         $sResponse = strval($xml->Result->Description);
                     } else {
                         $sResponse = '';
                         // состояние счета
                         $sState = '?';
                         switch (intval($xml->State->Code)) {
                             case 5:
                                 $sState = 'Операция только инициализирована, деньги от покупателя не получены';
                                 break;
                             case 10:
                                 $sState = 'Операция отменена, деньги от покупателя не были получены';
                                 break;
                             case 50:
                                 $sState = 'Деньги от покупателя получены, производится зачисление денег на счет магазина';
                                 break;
                             case 60:
                                 $sState = 'Деньги после получения были возвращены покупателю';
                                 break;
                             case 80:
                                 $sState = 'Исполнение операции приостановлено';
                                 break;
                             case 100:
                                 $sState = 'Операция выполнена, завершена успешно';
                                 break;
                         }
                         $sResponse = 'Состояние: ' . $sState . ' (' . date('d.m.Y H:i:s', strtotime(strval($xml->State->StateDate))) . ')<br/>';
                         //информация об операции
                         $sResponse .= ' Способ оплаты: <b>' . strval($xml->Info->PaymentMethod->Description) . '</b>, <br/> 
                                         Сумма уплаченная клиентом: <b>' . strval($xml->Info->IncSum) . ' ' . strval($xml->Info->IncCurrLabel) . '</b>, <br/>
                                         Аккаунт клиента в системе оплаты: <b>' . strval($xml->Info->IncAccount) . '</b>, <br/>
                                         Сумма отправленная ' . SITEHOST . ': <b>' . strval($xml->Info->OutSum) . ' ' . strval($xml->Info->OutCurrLabel) . '</b>';
                     }
                     $this->ajaxResponse($sResponse);
                     break;
             }
             break;
         case 'extra':
             if (!$nBillID) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             $aResponse = array('extra' => $this->db->one_data('SELECT details FROM ' . TABLE_BILLS . ' WHERE id=' . $nBillID . ' LIMIT 1'));
             $this->ajaxResponse($aResponse);
             break;
     }
     $this->ajaxResponse(Errors::IMPOSSIBLE);
 }
Exemplo n.º 5
0
 function listing()
 {
     if (!$this->haveAccessTo('read')) {
         return $this->showAccessDenied();
     }
     $nUserID = $this->security->getUserID();
     if (($nFolderID = func::GETPOST('f', false, true)) <= 0) {
         $nFolderID = INTERNALMAIL_FOLDER_ALL;
     }
     $aData = array('f' => $nFolderID);
     if (func::isPostMethod()) {
         switch (func::POST('act')) {
             case 'send':
                 $aData['recipient'] = func::POST('recipient', false, true);
                 if (!$aData['recipient']) {
                     $this->errors->set('no_recipient');
                 }
                 $aData['message'] = $this->cleanMessage(func::POST('message'));
                 if (!$aData['message']) {
                     $this->errors->set('no_message');
                 }
                 if ($this->errors->no()) {
                     $this->sendMessage($nUserID, $aData['recipient'], nl2br($aData['message']), $this->uploadAttachment(), $this->db->getNOW());
                     $this->adminRedirect(Errors::SUCCESSFULL, 'listing&f=' . $nFolderID);
                 }
                 break;
         }
     }
     $nLimit = 15;
     $aData['offset'] = func::GET('offset', false, true);
     if ($aData['offset'] <= 0) {
         $aData['offset'] = 0;
     }
     $sQuery = 'SELECT U.user_id, U.name, U.login, U.avatar, U.admin,
                       COUNT(IM.id) AS msgs_count, 
                       SUM( (IM.recipient=' . $nUserID . ' AND !(IM.status & ' . INTERNALMAIL_STATUS_NEW . ')) ) AS newmsgs, 
                       MAX(IM.id) AS lastmsg_id, 
                       MAX(IM.created) AS last 
                FROM ' . TABLE_INTERNALMAIL . ' IM, ' . TABLE_USERS . ' U 
                     LEFT JOIN ' . TABLE_INTERNALMAIL_FOLDERS_USERS . ' IMFU 
                         ON IMFU.user_id=' . $nUserID . ' AND IMFU.interlocutor_id=U.user_id ' . (!$nFolderID ? ' AND IMFU.folder_id=' . INTERNALMAIL_FOLDER_IGNORE . ' ' : '') . '
                WHERE ((IM.author=' . $nUserID . ' AND !(IM.status & ' . INTERNALMAIL_STATUS_DELAUTHOR . ')) OR 
                       (IM.recipient=' . $nUserID . ' AND !(IM.status & ' . INTERNALMAIL_STATUS_DELRECIPIENT . ')) )  AND 
                      U.user_id = IF(IM.author = ' . $nUserID . ', IM.recipient, IM.author) AND U.blocked = 0
     ' . (!$nFolderID ? ' AND IMFU.folder_id IS NULL ' : 'AND IMFU.folder_id=' . $nFolderID) . '
                GROUP BY 1  
                ORDER BY last DESC' . $this->db->prepareLimit($aData['offset'], $nLimit + 1);
     $aData['contacts'] = $this->db->select($sQuery);
     if (!empty($aData['contacts'])) {
         $aContacts = array();
         $aLastMessageID = array();
         foreach ($aData['contacts'] as $v) {
             $aContacts[$v['user_id']] = $v;
             $aContacts[$v['user_id']]['folders'] = array();
             $aLastMessageID[] = $v['lastmsg_id'];
         }
         $aUsersFolders = $this->db->select('SELECT folder_id as f, interlocutor_id as id FROM ' . TABLE_INTERNALMAIL_FOLDERS_USERS . '
             WHERE user_id = ' . $nUserID . ' AND interlocutor_id IN(' . implode(',', array_keys($aContacts)) . ') ');
         foreach ($aUsersFolders as $v) {
             $aContacts[$v['id']]['folders'][] = $v['f'];
         }
         $aLastMessageID = $this->db->select('SELECT id, author, recipient, status, created, readed, !(status & ' . INTERNALMAIL_STATUS_NEW . ') as newmsg 
                     FROM ' . TABLE_INTERNALMAIL . ' WHERE id IN (' . implode(',', $aLastMessageID) . ')');
         foreach ($aLastMessageID as $m) {
             $aContacts[$m['author'] == $nUserID ? $m['recipient'] : $m['author']]['lastmsg'] = $m;
         }
         $aData['contacts'] = $aContacts;
         unset($aContacts, $aLastMessageID, $aUsersFolders);
     }
     //generate pagenation: prev, next
     $this->generatePagenationPrevNext(null, $aData, 'contacts', $nLimit);
     $aData['folders'] = $this->getFolders();
     $this->adminCustomCenterArea();
     $this->includeJS('autocomplete');
     $this->includeCSS('im');
     $this->tplAssignByRef('aData', $aData);
     return $this->tplFetch('admin.listing.folders.tpl');
 }
Exemplo n.º 6
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.º 7
0
 function ajax()
 {
     if (!bff::$isAjax || !$this->security->haveAccessToAdminPanel()) {
         $this->ajaxResponse(Errors::ACCESSDENIED);
     }
     switch (func::GET('act')) {
         case 'city-list':
             $sPos = func::GETPOST('pos');
             $aExtra = array('expand' => true);
             $sEmptyTitle = func::GETPOST('empty_title');
             if (!empty($sEmptyTitle)) {
                 $aExtra['empty_title'] = $sEmptyTitle;
             }
             $this->ajaxResponse($this->geoCityOptions(0, $sPos, $aExtra));
             break;
         case 'city-regions':
             $nCityID = $this->input->id('city', 'p');
             if (!$nCityID) {
                 $this->ajaxResponse(Errors::UNKNOWNRECORD);
             }
             $bGetYData = func::GET('ydata') == 1;
             $sEmptyTitle = func::GETPOST('empty_title');
             $sEmptyTitle = !empty($sEmptyTitle) ? $sEmptyTitle : 'не указан';
             $aResponse = $this->geoRegionOptions($nCityID, 0, true, $sEmptyTitle, $bGetYData);
             if (!$bGetYData) {
                 unset($aResponse['regdata']);
             }
             $this->ajaxResponse($aResponse);
             break;
         case 'unsubscribe':
             if (($nRecordID = func::POSTGET('rec', false, true)) <= 0) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             $this->db->execute('DELETE FROM ' . TABLE_SUBSCRIBES . ' WHERE id = ' . $nRecordID);
             $this->ajaxResponse(Errors::SUCCESS);
             break;
     }
     $this->ajaxResponse(Errors::IMPOSSIBLE);
 }
Exemplo n.º 8
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.º 9
0
 function regions_ajax()
 {
     if (!$this->haveAccessTo('regions')) {
         return $this->showAccessDenied();
     }
     if (bff::$isAjax) {
         switch (func::GET('act')) {
             case 'region-add':
                 $this->input->postm(array('pid' => TYPE_UINT, 'numlevel' => TYPE_UINT, 'title' => TYPE_STR), $aData, array('title'));
                 if ($this->errors->no()) {
                     $nNum = (int) $this->db->one_data('SELECT MAX(num) FROM ' . TABLE_BBS_REGIONS . ' WHERE pid = ' . $aData['pid']);
                     $res = $this->db->execute('INSERT INTO ' . TABLE_BBS_REGIONS . ' (title, pid, numlevel, num)
                                         VALUES(' . $this->db->str2sql($aData['title']) . ', ' . $aData['pid'] . ', ' . $aData['numlevel'] . ', ' . ($nNum + 1) . ')');
                     if ($res) {
                         $this->ajaxResponse(Errors::SUCCESS);
                     }
                 }
                 break;
             case 'region-delete':
                 $nRecordID = Func::POSTGET('rec', false, true);
                 if (!$nRecordID) {
                     break;
                 }
                 $res = $this->db->execute('DELETE FROM ' . TABLE_BBS_REGIONS . ' WHERE (id = ' . $nRecordID . ' OR pid = ' . $nRecordID . ')');
                 if ($res) {
                     $this->ajaxResponse(Errors::SUCCESS);
                 }
                 break;
             case 'region-toggle':
                 $nRecordID = Func::POSTGET('rec', false, true);
                 if (!$nRecordID) {
                     break;
                 }
                 $res = $this->db->execute('UPDATE ' . TABLE_BBS_REGIONS . ' 
                                SET enabled = (1 - enabled) WHERE id=' . $nRecordID);
                 if ($res) {
                     $this->ajaxResponse(Errors::SUCCESS);
                 }
                 break;
             case 'region-toggle-main':
                 $nRecordID = Func::POSTGET('rec', false, true);
                 if (!$nRecordID) {
                     break;
                 }
                 $res = $this->db->execute('UPDATE ' . TABLE_BBS_REGIONS . ' SET main=(1-main) WHERE id=' . $nRecordID . ' AND pid>0 LIMIT 1');
                 if ($res) {
                     $this->ajaxResponse(Errors::SUCCESS);
                 }
                 break;
             case 'region-save':
                 $this->input->postm(array('rec' => TYPE_UINT, 'title' => TYPE_STR), $aData, array('title'));
                 if ($aData['rec'] && $this->errors->no()) {
                     $this->db->execute('UPDATE ' . TABLE_BBS_REGIONS . ' SET title = ' . $this->db->str2sql($aData['title']) . ' WHERE id = ' . $aData['rec']);
                     $this->ajaxResponse(array('title' => $aData['title'], 'id' => $aData['rec']));
                 }
                 break;
             case 'region-rotate':
                 $res = $this->db->rotateTablednd(TABLE_BBS_REGIONS, ' AND main = 1');
                 if ($res) {
                     $this->ajaxResponse(Errors::SUCCESS);
                 }
                 break;
             case 'country-rotate':
                 $res = $this->db->rotateTablednd(TABLE_BBS_REGIONS, ' AND pid = 0');
                 if ($res) {
                     $this->ajaxResponse(Errors::SUCCESS);
                 }
                 break;
                 //                case 'get-cities': // autocomplete
                 //                {
                 //                    $nCountryID = func::SESSION('cid');
                 //                    $arr['query'] = func::GET('query', true);
                 //
                 //                    $aData = $this->db->select('SELECT R.id, R.title
                 //                                           FROM ' . TABLE_REGION . ' R
                 //                                           LEFT JOIN ' . TABLE_REGION . ' R ON R.id = C.region_id
                 //                                           WHERE C.country_id = ' . $nCountryID . ' AND C.main = 0 AND C.title LIKE(' . $this->db->str2sql($arr['query'] . '%') . ')
                 //                                           ORDER BY title');
                 //
                 //                    if($aData)
                 //                    {
                 //                        foreach($aData as $key => $value)
                 //                        {
                 //                            $arr['suggestions'][] = $value['title'] . ($value['region'] ? ' (' . $value['region'] . ')' : '');
                 //                            $arr['data'][]        = $value['id'];
                 //                        }
                 //                    }
                 //                    else
                 //                    {
                 //                        $arr['suggestions'] = array();
                 //                        $arr['data'] = array();
                 //                    }
                 //
                 //                    echo json_encode($arr);
                 //                    exit;
                 //                }break;
         }
     }
     $this->ajaxResponse(Errors::IMPOSSIBLE);
 }
Exemplo n.º 10
0
 function mod_edit()
 {
     if (!$this->haveAccessTo('users-edit')) {
         return $this->showAccessDenied();
     }
     if (!($nRecordID = $this->input->id())) {
         $this->adminRedirect(Errors::IMPOSSIBLE, 'listing');
     }
     $sTUID = func::GET('tuid');
     if (!$this->checkTUID($sTUID, $nRecordID)) {
         return $this->showAccessDenied();
     }
     $aData = array('admin' => 0);
     #анализируем группы, в которые входит пользователь
     $bUserSuperadmin = 0;
     $aUserGroups = $this->getUserGroups($nRecordID);
     foreach ($aUserGroups as $v) {
         if ($v['group_id'] == self::GROUPID_SUPERADMIN) {
             $bUserSuperadmin = 1;
         }
         if ($v['adminpanel'] == 1) {
             $aData['admin'] = 1;
         }
     }
     if (bff::$isPost) {
         $this->input->postm(array('name' => TYPE_STR, 'email' => TYPE_STR, 'changepass' => TYPE_BOOL, 'password' => TYPE_STR, 'balance' => TYPE_NUM, 'skype' => TYPE_STR, 'email2' => TYPE_STR, 'phone' => TYPE_STR, 'group_id' => TYPE_ARRAY_INT, 'cat' => TYPE_ARRAY_UINT), $aData);
         if (!$aData['admin']) {
             //удаляем настройки предназначенные для админов
             unset($aData['im_noreply']);
         }
         if (empty($aData['email'])) {
             $this->errors->set('empty:email');
         } elseif (!func::IsEmailAddress($aData['email'])) {
             $this->errors->set('wrong:email');
         }
         if ($aData['changepass']) {
             if (empty($aData['password'])) {
                 $this->errors->set('empty:password');
             } else {
                 $aData['password'] = $this->security->getUserPasswordMD5($aData['password']);
             }
         } else {
             unset($aData['password']);
         }
         //            if($aData['city_id']<=0)
         //                $this->errors->set('wrong:city');
         $aGroupID = $aData['group_id'];
         $aData['email_hash'] = func::getEmailHash($aData['email']);
         if ($this->isEmailExists($aData['email_hash'], $nRecordID)) {
             $this->errors->set('email_exist');
         }
         if ($this->errors->no()) {
             #update user data
             unset($aData['changepass'], $aData['group_id']);
             $aData['member'] = in_array(self::GROUPID_MEMBER, $aGroupID) ? 1 : 0;
             $aData['cat'] = join(',', $aData['cat']);
             $this->userUpdate($nRecordID, $aData);
             $avatar = new CAvatar(TABLE_USERS, USERS_AVATAR_PATH, 'avatar', 'user_id');
             $avatar->update($nRecordID, true, true);
             #set user groups
             if ($bUserSuperadmin && !in_array(self::GROUPID_SUPERADMIN, $aGroupID)) {
                 $aGroupID = array_merge($aGroupID, array(self::GROUPID_SUPERADMIN));
             }
             $this->assignUser2Groups($nRecordID, $aGroupID);
             #обновляем, является ли юзер администратором
             $bIsAdmin = 0;
             if ($this->errors->no()) {
                 if ($bUserSuperadmin || in_array(self::GROUPID_MODERATOR, $aGroupID)) {
                     $bIsAdmin = 1;
                 } elseif (count($aGroupID) == 1 && current($aGroupID) == self::GROUPID_MEMBER) {
                     $bIsAdmin = 0;
                 } else {
                     $aUserGroups = $this->getUserGroups($nRecordID);
                     foreach ($aUserGroups as $v) {
                         if ($v['adminpanel'] == 1) {
                             $bIsAdmin = 1;
                             break;
                         }
                     }
                 }
                 if ($aData['admin'] != $bIsAdmin) {
                     $sQuery = ', im_noreply = 0';
                     $this->db->execute('UPDATE ' . TABLE_USERS . ' SET admin=' . $bIsAdmin . (!$bIsAdmin ? $sQuery : '') . ' WHERE user_id=' . $nRecordID);
                 }
             }
             #если пользователь редактирует собственные настройки
             if ($this->security->isCurrentUser($nRecordID)) {
                 $this->security->expire();
             }
             $this->adminRedirect(Errors::SUCCESSFULL, (!func::GET('members') ? 'admin_' : '') . 'listing');
         }
         $aActiveGroupsID = $aGroupID;
     } else {
         $aActiveGroupsID = array();
         for ($j = 0; $j < count($aUserGroups); $j++) {
             $aActiveGroupsID[] = $aUserGroups[$j]['group_id'];
         }
     }
     $aUserInfo = $this->db->one_array('SELECT U.*, C.title as city, R.region_id, R.title as region 
                                     FROM ' . TABLE_USERS . ' U
                                     LEFT JOIN ' . TABLE_CITY . ' C   ON U.city_id=C.city_id
                                     LEFT JOIN ' . TABLE_REGION . ' R ON C.region_id=R.region_id
                                    WHERE U.user_id=' . $nRecordID . ' LIMIT 1');
     $aData = func::array_2_htmlspecialchars(array_merge($aUserInfo, $aData), null, true);
     $aData['social_link'] = '';
     if ($aData['social']) {
         switch ($aData['social']) {
             case 'vk':
                 $aData['social_link'] = 'http://vkontakte.ru/id' . $aData['vk_id'];
         }
     }
     //assign groups
     $exists_options = $active_options = '';
     $aGroupsExlude = array(USERS_GROUPS_MEMBER);
     if (!$bUserSuperadmin) {
         $aGroupsExlude[] = USERS_GROUPS_SUPERADMIN;
     }
     $aGroups = $this->getGroups($aGroupsExlude);
     for ($i = 0; $i < count($aGroups); $i++) {
         if (in_array($aGroups[$i]['group_id'], $aActiveGroupsID)) {
             $active_options .= '<option value="' . $aGroups[$i]['group_id'] . '" style="color:' . $aGroups[$i]['color'] . ';">' . $aGroups[$i]['title'] . '</option>';
         } else {
             $exists_options .= '<option value="' . $aGroups[$i]['group_id'] . '" style="color:' . $aGroups[$i]['color'] . ';">' . $aGroups[$i]['title'] . '</option>';
         }
     }
     $this->tplAssignByRef('exists_options', $exists_options);
     $this->tplAssignByRef('active_options', $active_options);
     //$aData['city_options'] = bff::i()->Sites_geoCityOptions($aData['city_id'], 'edit');
     $aData['cat'] = explode(',', $aData['cat']);
     $this->tplAssign('aCategories', $this->getBBSCategories($aData['cat']));
     $aData['superadmin'] = $bUserSuperadmin;
     $aData['tuid'] = $sTUID;
     $aData['edit'] = true;
     $this->tplAssignByRef('aData', $aData);
     return $this->tplFetch('admin.mod.form.tpl');
 }
Exemplo n.º 11
0
 public function action()
 {
     $nOwnerID = $this->input->id('owner');
     $sReturnLink = $this->act_listing . '&owner=' . $nOwnerID;
     switch ($this->input->get('act')) {
         case 'add':
             $aData = array('data' => array());
             if (bff::$isPost) {
                 $aData['data'] = $this->input->post('dynprop', TYPE_ARRAY);
                 $res = $this->insert($aData['data'], $nOwnerID);
                 if ($res) {
                     $this->adminRedirect(Errors::SUCCESSFULL, $sReturnLink);
                 }
             }
             $aData['owner'] = $this->db->one_array('SELECT O.id, O.title, ' . ($this->inherit ? 'O.pid' : '0') . ' as parent 
                                            FROM ' . $this->ownerTable . ' O WHERE O.id = ' . $nOwnerID);
             if ($aData['owner']['parent'] != 0) {
                 $aData['owner']['parent'] = $this->db->one_array('SELECT O.id, O.title FROM ' . $this->ownerTable . ' O WHERE O.id = ' . $aData['owner']['parent']);
             }
             $this->includeJS(array('dynprops', 'tablednd'));
             $aData['edit'] = false;
             $aData['url_listing'] = $this->adminCreateLink($this->act_listing) . '&owner=';
             $aData['url_action_owner'] = $this->adminCreateLink($this->act_action) . '&owner=' . $nOwnerID . '&act=';
             return $this->tplFetchPHP($aData, 'manage.php');
             break;
         case 'child':
             $this->input->postm(array('parent_id' => TYPE_UINT, 'parent_value' => TYPE_UINT, 'child_act' => TYPE_STR, 'id' => TYPE_UINT), $aData);
             extract($aData);
             if (!empty($aData['child_act'])) {
                 switch ($aData['child_act']) {
                     case 'save':
                         $aDynpropParams = $this->input->post('dynprop', TYPE_ARRAY);
                         if ($aData['id']) {
                             $res = $this->update($aDynpropParams, $aData['id']);
                         } else {
                             $res = $this->insert($aDynpropParams, $nOwnerID, array('id' => $parent_id, 'value' => $parent_value));
                         }
                         if ($res) {
                             $this->ajaxResponse(Errors::SUCCESSFULL);
                         }
                         break;
                     case 'del':
                         $res = $this->del($aData['id'], $nOwnerID);
                         if ($res) {
                             $this->ajaxResponse(Errors::SUCCESSFULL);
                         }
                         break;
                 }
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             } else {
                 $aData['data'] = $this->db->one_array('SELECT * FROM ' . $this->tblDynprops . ' WHERE parent_id = ' . $parent_id . ' AND parent_value=' . $parent_value);
                 if (!empty($aData['data'])) {
                     $aData['id'] = $aData['data']['id'];
                     if ($this->isMulti($aData['data']['type'])) {
                         $aData['data']['multi'] = $this->db->select('SELECT * FROM ' . $this->tblMulti . ' WHERE dynprop_id = ' . $aData['data']['id'] . ' ORDER BY num');
                     }
                 }
                 $aData['edit'] = !empty($aData['id']);
             }
             //$aData['url_action_owner'] = $this->adminCreateLink($this->act_action).'&owner='.$nOwnerID.'&act=';
             $this->typesAllowed = $this->typesAllowedChild;
             $this->ajaxResponse(array('form' => $this->tplFetchPHP($aData, 'manage.child.php')));
             break;
         case 'inherit_list':
             if (!$nOwnerID || !$this->isInheritParticular()) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             $aData = $this->db->one_array('SELECT O.id as owner_id, O.title as owner_title, ' . ($this->inherit ? 'O.pid' : '0') . ' as parent 
                                             FROM ' . $this->ownerTable . ' O WHERE O.id = ' . $nOwnerID);
             if ($aData['parent'] == 0) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             $aOwnerParentID = $this->getOwnerParentsID($nOwnerID);
             if (empty($aOwnerParentID)) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             $aData['dynprops'] = $this->db->select('SELECT D.id, D.title, D.' . $this->ownerColumn . ', D.type, D.enabled, D.is_search, I.data_field, I2.' . $this->ownerColumn . ' as inherited
                                                FROM ' . $this->tblDynprops . ' D,
                                                     ' . $this->tblIn . ' I
                                                     LEFT JOIN ' . $this->tblIn . ' I2 ON I2.dynprop_id = I.dynprop_id AND I2.' . $this->ownerColumn . ' = ' . $nOwnerID . '
                                                WHERE ' . $this->db->prepareIN('I.' . $this->ownerColumn, $aOwnerParentID) . ' AND I.dynprop_id = D.id AND D.parent_id = 0
                                                GROUP BY D.id
                                                ORDER BY I.num');
             $aData['url_listing'] = $this->adminCreateLink($this->act_listing);
             $aData['url_action'] = $this->adminCreateLink($this->act_action);
             $this->ajaxResponse($this->tplFetchPHP($aData, 'inherit.php'));
             break;
         case 'inherit_do':
             $nDynpropID = $this->input->id('dynprop');
             if (!$this->isInheritParticular() || !$nDynpropID || !$nOwnerID) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             $res = $this->linkIN($nOwnerID, $nDynpropID, false, false);
             $this->ajaxResponse($res ? Errors::SUCCESSFULL : Errors::IMPOSSIBLE);
             break;
         case 'inherit_copy':
             $nDynpropID = $this->input->id('dynprop');
             if (!$this->isInheritParticular() || !$nDynpropID || !$nOwnerID) {
                 $this->ajaxResponse(Errors::IMPOSSIBLE);
             }
             $res = $this->copy($nDynpropID, $nOwnerID);
             $this->ajaxResponse($res ? Errors::SUCCESSFULL : Errors::IMPOSSIBLE);
             break;
         case 'edit':
             $nOwnerIDFrom = $this->input->id('owner_from');
             if ($nOwnerIDFrom) {
                 $sReturnLink = $this->act_listing . '&owner=' . $nOwnerIDFrom;
             }
             $nDynpropID = $this->input->id('dynprop');
             if (!$nDynpropID) {
                 $this->adminRedirect(Errors::IMPOSSIBLE, $sReturnLink);
             }
             $aData = array();
             if (bff::$isPost) {
                 $aData['data'] = $this->input->post('dynprop', TYPE_ARRAY);
                 $res = $this->update($aData['data'], $nDynpropID);
                 if ($res) {
                     $this->adminRedirect(Errors::SUCCESSFULL, $sReturnLink);
                 }
             } else {
                 $aData['data'] = $this->db->one_array('SELECT D.* FROM ' . $this->tblDynprops . ' D
                      WHERE D.id = ' . $nDynpropID . ' AND D.' . $this->ownerColumn . ' = ' . $nOwnerID);
                 $data =& $aData['data'];
                 if ($this->isMulti($data['type'])) {
                     $data['multi'] = $this->db->select('SELECT value, name FROM ' . $this->tblMulti . ' WHERE dynprop_id = ' . $nDynpropID . ' ORDER BY num');
                 }
                 if ($this->hasExtra($data['type']) || $data['parent'] || $data['txt']) {
                     $extra = unserialize($data['extra']);
                     if ($extra !== false) {
                         $data = array_merge($data, $extra);
                     }
                 }
             }
             if (empty($aData['data'])) {
                 $this->adminRedirect(Errors::IMPOSSIBLE, $sReturnLink);
             }
             $aData['owner'] = $this->db->one_array('SELECT O.id, O.title, ' . ($this->inherit ? 'O.pid' : '0') . ' as parent 
                                            FROM ' . $this->ownerTable . ' O WHERE O.id = ' . $nOwnerID);
             if ($aData['owner']['parent'] != 0) {
                 $aData['owner']['parent'] = $this->db->one_array('SELECT O.id, O.title FROM ' . $this->ownerTable . ' O WHERE O.id = ' . $aData['owner']['parent']);
             }
             $this->includeJS(array('dynprops', 'tablednd'));
             $aData['owner_from'] = $nOwnerIDFrom;
             $aData['edit'] = true;
             $aData['url_listing'] = $this->adminCreateLink($this->act_listing) . '&owner=';
             $aData['url_action_owner'] = $this->adminCreateLink($this->act_action) . '&owner=' . $nOwnerID . '&act=';
             return $this->tplFetchPHP($aData, 'manage.php');
             break;
         case 'rotate':
             if ($this->isInheritParticular()) {
                 $res = $this->db->rotateTablednd($this->tblIn, ' AND ' . $this->ownerColumn . ' = ' . $nOwnerID, 'dynprop_id', 'num', true, $this->ownerColumn);
             } else {
                 $res = $this->db->rotateTablednd($this->tblDynprops, ' AND ' . $this->ownerColumn . ' = ' . $nOwnerID, 'id', 'num', true, $this->ownerColumn);
             }
             $this->ajaxResponse($res ? Errors::SUCCESSFULL : Errors::IMPOSSIBLE);
             break;
         case 'del':
             $nDynpropID = $this->input->id('dynprop');
             if (!$nDynpropID) {
                 $this->adminRedirect(Errors::IMPOSSIBLE, $sReturnLink);
             }
             $bRemoveOnlyInheritence = func::GET('inherit') ? 1 : 0;
             $res = $this->del($nDynpropID, $nOwnerID, $bRemoveOnlyInheritence == 1);
             $this->adminRedirect($res ? Errors::SUCCESSFULL : Errors::IMPOSSIBLE, $sReturnLink);
             break;
     }
 }
Exemplo n.º 12
0
 function categories_move()
 {
     if (!$this->haveAccessTo('categories-edit')) {
         return $this->showAccessDenied();
     }
     $nQuestionID = func::GETPOST('rec', false, true);
     if (!$nQuestionID) {
         $this->ajaxResponse(Errors::IMPOSSIBLE);
     }
     if (bff::$isAjax) {
         switch (func::GET('act')) {
             case 'delete':
                 # удаляем вопрос
                 $this->db->execute('DELETE FROM ' . TABLE_FAQ . ' WHERE id = ' . $nQuestionID);
                 $this->ajaxResponse(Errors::SUCCESSFULL);
                 break;
         }
     }
     $this->ajaxResponse(Errors::IMPOSSIBLE);
 }
Exemplo n.º 13
0
 function mm_listing()
 {
     if (!FORDEV || !$this->security->isSuperAdmin()) {
         return $this->showAccessDenied();
     }
     if (bff::$isAjax) {
         switch (func::GET('act')) {
             case 'rotate':
                 $res = $this->db->rotateTablednd(TABLE_MODULE_METHODS, '', 'id', 'number');
                 $this->ajaxResponse($res ? Errors::SUCCESS : Errors::IMPOSSIBLE);
                 break;
             case 'delete':
                 if (!($nRecordID = $this->input->id('rec', 'p'))) {
                     break;
                 }
                 $aResult = $this->db->one_array('SELECT *
                            FROM ' . TABLE_MODULE_METHODS . '
                            WHERE id = ' . $nRecordID);
                 if (empty($aResult)) {
                     $this->ajaxResponse(Errors::IMPOSSIBLE);
                 }
                 if ($aResult['module'] == $aResult['method']) {
                     //если модуль, получаем методы
                     $aMethodsID = $this->db->select_one_column('SELECT id FROM ' . TABLE_MODULE_METHODS . '
                                WHERE module=' . $this->db->str2sql($aResult['module']) . ' AND module!=method
                                ORDER BY number, id');
                     //удалить методы
                     $this->db->execute('DELETE FROM ' . TABLE_MODULE_METHODS . ' WHERE id IN (' . implode(',', $aMethodsID) . ')');
                     $this->db->execute('DELETE FROM ' . TABLE_USERS_GROUPS_PERMISSIONS . ' WHERE item_type = ' . $this->db->str2sql('module') . ' and item_id IN (' . implode(',', $aMethodsID) . ')');
                 }
                 //удалить модули и методы
                 $this->db->execute('DELETE FROM ' . TABLE_MODULE_METHODS . ' WHERE id = ' . $nRecordID);
                 $this->db->execute('DELETE FROM ' . TABLE_USERS_GROUPS_PERMISSIONS . ' WHERE unit_type=' . $this->db->str2sql('group') . ' AND item_type=' . $this->db->str2sql('module') . ' AND item_id=' . $nRecordID);
                 $this->ajaxResponse(Errors::SUCCESS);
                 break;
         }
         $this->ajaxResponse(Errors::IMPOSSIBLE);
     }
     $aData = $this->db->select(' SELECT M.*, 1 as numlevel
                 FROM ' . TABLE_MODULE_METHODS . ' M  
                 WHERE M.module=M.method
                 ORDER BY M.number, M.id');
     $aSubData = $this->db->select('SELECT M.*, 2 as numlevel
                 FROM ' . TABLE_MODULE_METHODS . ' M
                 WHERE M.module!=M.method
                 ORDER BY M.number, M.id');
     $aSubData = Func::array_transparent($aSubData, 'module');
     for ($i = 0; $i < count($aData); $i++) {
         $aData[$i]['subitems'] = array();
         if (isset($aSubData[$aData[$i]['module']])) {
             $aData[$i]['subitems'] = $aSubData[$aData[$i]['module']];
         }
     }
     $this->includeJS('tablednd');
     $this->tplAssign('aData', $aData);
     return $this->tplFetch('admin.mm.tpl');
 }