コード例 #1
0
 protected function checkBlogFields($oBlog = null)
 {
     $bOk = parent::checkBlogFields($oBlog);
     if (!F::isPost('submit_blog_add')) {
         //  Проверяем есть ли подзаголовок блога
         $iMin = C::Get('plugin.blogsubtitle.min_subtitle_len');
         $iMax = C::Get('plugin.blogsubtitle.max_subtitle_len');
         $sSubtitle = F::GetRequestStr('blog_subtitle');
         if (!$sSubtitle && $iMin) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.blogsubtitle.blog_create_subtitle_error', array('min' => $iMin, 'max' => $iMax)), E::ModuleLang()->Get('error'));
             $bOk = false;
         } elseif ($iMax) {
             if (!F::CheckVal($sSubtitle, 'text', $iMin, $iMax)) {
                 E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.blogsubtitle.blog_create_subtitle_error', array('min' => $iMin, 'max' => $iMax)), E::ModuleLang()->Get('error'));
                 $bOk = false;
             }
         }
     }
     return $bOk;
 }
コード例 #2
0
ファイル: ActionSeopack.class.php プロジェクト: Azany/altocms
 /**
  * @return bool
  */
 protected function CheckSeopackFields()
 {
     E::ModuleSecurity()->ValidateSendForm();
     $bOk = true;
     if (F::isPost('title') && !F::CheckVal(F::GetRequest('title', null, 'post'), 'text', 0, 1000)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.seopack.title_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     if (F::isPost('description') && !F::CheckVal(F::GetRequest('description', null, 'post'), 'text', 0, 1000)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.seopack.description_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     if (F::isPost('keywords') && !F::CheckVal(F::GetRequest('keywords', null, 'post'), 'text', 0, 1000)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.seopack.keywords_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     if (!F::CheckVal(F::GetRequest('url', null, 'post'), 'text', 0, 255)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.seopack.url_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     return $bOk;
 }
コード例 #3
0
ファイル: Topic.class.php プロジェクト: AlexSSN/altocms
 /**
  * Обработка дополнительных полей топика
  *
  * @param ModuleTopic_EntityTopic $oTopic
  * @param string $sType
  *
  * @return bool
  */
 public function processTopicFields($oTopic, $sType = 'add')
 {
     /** @var ModuleTopic_EntityContentValues $aValues */
     $aValues = array();
     if ($sType == 'update') {
         // * Получаем существующие значения
         if ($aData = $this->GetTopicValuesByArrayId(array($oTopic->getId()))) {
             $aValues = $aData[$oTopic->getId()];
         }
         // * Чистим существующие значения
         E::ModuleTopic()->DeleteTopicValuesByTopicId($oTopic->getId());
     }
     if ($oType = E::ModuleTopic()->GetContentTypeByUrl($oTopic->getType())) {
         //получаем поля для данного типа
         if ($aFields = $oType->getFields()) {
             foreach ($aFields as $oField) {
                 $sData = null;
                 if (isset($_REQUEST['fields'][$oField->getFieldId()]) || isset($_FILES['fields_' . $oField->getFieldId()]) || $oField->getFieldType() == 'single-image-uploader') {
                     //текстовые поля
                     if (in_array($oField->getFieldType(), array('input', 'textarea', 'select'))) {
                         $sData = E::ModuleText()->Parser($_REQUEST['fields'][$oField->getFieldId()]);
                     }
                     //поле ссылки
                     if ($oField->getFieldType() == 'link') {
                         $sData = $_REQUEST['fields'][$oField->getFieldId()];
                     }
                     //поле даты
                     if ($oField->getFieldType() == 'date') {
                         if (isset($_REQUEST['fields'][$oField->getFieldId()])) {
                             if (F::CheckVal($_REQUEST['fields'][$oField->getFieldId()], 'text', 6, 10) && substr_count($_REQUEST['fields'][$oField->getFieldId()], '.') == 2) {
                                 list($d, $m, $y) = explode('.', $_REQUEST['fields'][$oField->getFieldId()]);
                                 if (@checkdate($m, $d, $y)) {
                                     $sData = $_REQUEST['fields'][$oField->getFieldId()];
                                 }
                             }
                         }
                     }
                     //поле с файлом
                     if ($oField->getFieldType() == 'file') {
                         //если указано удаление файла
                         if (F::GetRequest('topic_delete_file_' . $oField->getFieldId())) {
                             if ($oTopic->getFieldFile($oField->getFieldId())) {
                                 @unlink(Config::Get('path.root.dir') . $oTopic->getFieldFile($oField->getFieldId())->getFileUrl());
                                 //$oTopic->setValueField($oField->getFieldId(),'');
                                 $sData = null;
                             }
                         } else {
                             //если удаление файла не указано, уже ранее залит файл^ и нового файла не загружалось
                             if ($sType == 'update' && isset($aValues[$oField->getFieldId()])) {
                                 $sData = $aValues[$oField->getFieldId()]->getValueSource();
                             }
                         }
                         if (isset($_FILES['fields_' . $oField->getFieldId()]) && is_uploaded_file($_FILES['fields_' . $oField->getFieldId()]['tmp_name'])) {
                             $iMaxFileSize = F::MemSize2Int(Config::Get('module.uploader.files.default.file_maxsize'));
                             $aFileExtensions = Config::Get('module.uploader.files.default.file_extensions');
                             if (!$iMaxFileSize || filesize($_FILES['fields_' . $oField->getFieldId()]['tmp_name']) <= $iMaxFileSize) {
                                 $aPathInfo = pathinfo($_FILES['fields_' . $oField->getFieldId()]['name']);
                                 if (!$aFileExtensions || in_array(strtolower($aPathInfo['extension']), $aFileExtensions)) {
                                     $sFileTmp = $_FILES['fields_' . $oField->getFieldId()]['tmp_name'];
                                     $sDirSave = Config::Get('path.uploads.root') . '/files/' . E::ModuleUser()->GetUserCurrent()->getId() . '/' . F::RandomStr(16);
                                     mkdir(Config::Get('path.root.dir') . $sDirSave, 0777, true);
                                     if (is_dir(Config::Get('path.root.dir') . $sDirSave)) {
                                         $sFile = $sDirSave . '/' . F::RandomStr(10) . '.' . strtolower($aPathInfo['extension']);
                                         $sFileFullPath = Config::Get('path.root.dir') . $sFile;
                                         if (copy($sFileTmp, $sFileFullPath)) {
                                             //удаляем старый файл
                                             if ($oTopic->getFieldFile($oField->getFieldId())) {
                                                 $sOldFile = Config::Get('path.root.dir') . $oTopic->getFieldFile($oField->getFieldId())->getFileUrl();
                                                 F::File_Delete($sOldFile);
                                             }
                                             $aFileObj = array();
                                             $aFileObj['file_hash'] = F::RandomStr(32);
                                             $aFileObj['file_name'] = E::ModuleText()->Parser($_FILES['fields_' . $oField->getFieldId()]['name']);
                                             $aFileObj['file_url'] = $sFile;
                                             $aFileObj['file_size'] = $_FILES['fields_' . $oField->getFieldId()]['size'];
                                             $aFileObj['file_extension'] = $aPathInfo['extension'];
                                             $aFileObj['file_downloads'] = 0;
                                             $sData = serialize($aFileObj);
                                             F::File_Delete($sFileTmp);
                                         }
                                     }
                                 } else {
                                     $sTypes = implode(', ', $aFileExtensions);
                                     E::ModuleMessage()->AddError(E::ModuleLang()->Get('topic_field_file_upload_err_type', array('types' => $sTypes)), null, true);
                                 }
                             } else {
                                 E::ModuleMessage()->AddError(E::ModuleLang()->Get('topic_field_file_upload_err_size', array('size' => $iMaxFileSize)), null, true);
                             }
                             F::File_Delete($_FILES['fields_' . $oField->getFieldId()]['tmp_name']);
                         }
                     }
                     // Поле с изображением
                     if ($oField->getFieldType() == 'single-image-uploader') {
                         $sTargetType = $oField->getFieldType() . '-' . $oField->getFieldId();
                         $iTargetId = $oTopic->getId();
                         // 1. Удалить значение target_tmp
                         // Нужно затереть временный ключ в ресурсах, что бы в дальнейшем картнка не
                         // воспринималась как временная.
                         if ($sTargetTmp = E::ModuleSession()->GetCookie(ModuleUploader::COOKIE_TARGET_TMP)) {
                             // 2. Удалить куку.
                             // Если прозошло сохранение вновь созданного топика, то нужно
                             // удалить куку временной картинки. Если же сохранялся уже существующий топик,
                             // то удаление куки ни на что влиять не будет.
                             E::ModuleSession()->DelCookie(ModuleUploader::COOKIE_TARGET_TMP);
                             // 3. Переместить фото
                             $sNewPath = E::ModuleUploader()->GetUserImageDir(E::UserId(), true, false);
                             $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, 0, E::UserId());
                             if ($aMresourceRel) {
                                 $oResource = array_shift($aMresourceRel);
                                 $sOldPath = $oResource->GetFile();
                                 $oStoredFile = E::ModuleUploader()->Store($sOldPath, $sNewPath);
                                 /** @var ModuleMresource_EntityMresource $oResource */
                                 $oResource = E::ModuleMresource()->GetMresourcesByUuid($oStoredFile->getUuid());
                                 if ($oResource) {
                                     $oResource->setUrl(E::ModuleMresource()->NormalizeUrl(E::ModuleUploader()->GetTargetUrl($sTargetType, $iTargetId)));
                                     $oResource->setType($sTargetType);
                                     $oResource->setUserId(E::UserId());
                                     // 4. В свойство поля записать адрес картинки
                                     $sData = $oResource->getMresourceId();
                                     $oResource = array($oResource);
                                     E::ModuleMresource()->UnlinkFile($sTargetType, 0, $oTopic->getUserId());
                                     E::ModuleMresource()->AddTargetRel($oResource, $sTargetType, $iTargetId);
                                 }
                             }
                         } else {
                             // Топик редактируется, просто обновим поле
                             $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, $iTargetId, E::UserId());
                             if ($aMresourceRel) {
                                 $oResource = array_shift($aMresourceRel);
                                 $sData = $oResource->getMresourceId();
                             } else {
                                 $sData = false;
                                 //                                    $this->DeleteField($oField);
                             }
                         }
                     }
                     E::ModuleHook()->Run('content_field_proccess', array('sData' => &$sData, 'oField' => $oField, 'oTopic' => $oTopic, 'aValues' => $aValues, 'sType' => &$sType));
                     //Добавляем поле к топику.
                     if ($sData) {
                         /** @var ModuleTopic_EntityContentValues $oValue */
                         $oValue = E::GetEntity('Topic_ContentValues');
                         $oValue->setTargetId($oTopic->getId());
                         $oValue->setTargetType('topic');
                         $oValue->setFieldId($oField->getFieldId());
                         $oValue->setFieldType($oField->getFieldType());
                         $oValue->setValue($sData);
                         $oValue->setValueSource(in_array($oField->getFieldType(), array('file', 'single-image-uploader')) ? $sData : $_REQUEST['fields'][$oField->getFieldId()]);
                         $this->AddTopicValue($oValue);
                     }
                 }
             }
         }
     }
     return true;
 }
コード例 #4
0
ファイル: ActionLogin.class.php プロジェクト: hard990/altocms
 protected function _eventRecovery($bAjax = false)
 {
     if ($this->IsPost()) {
         // Was POST request
         $sEmail = F::GetRequestStr('mail');
         // Пользователь с таким емайлом существует?
         if ($sEmail && F::CheckVal($sEmail, 'mail')) {
             if ($this->_eventRecoveryRequest($sEmail)) {
                 if (!$bAjax) {
                     E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('password_reminder_send_link'));
                 }
                 return;
             }
         }
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('password_reminder_bad_email'), E::ModuleLang()->Get('error'));
     } elseif ($sRecoveryCode = $this->GetParam(0)) {
         // Was recovery code in GET
         if (F::CheckVal($sRecoveryCode, 'md5')) {
             // Проверка кода подтверждения
             if ($this->_eventRecoverySend($sRecoveryCode)) {
                 return null;
             }
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('password_reminder_bad_code_txt'), E::ModuleLang()->Get('password_reminder_bad_code'));
             if (!$bAjax) {
                 return R::Action('error');
             }
             return;
         }
     }
 }
コード例 #5
0
ファイル: User.class.php プロジェクト: AntiqS/altocms
 /**
  * @param      $aUserAuthData
  *
  * @return bool|ModuleUser_EntityUser|null
  */
 public function GetUserAuthorization($aUserAuthData)
 {
     $oUser = null;
     $iError = null;
     if (!empty($aUserAuthData['login'])) {
         $oUser = $this->GetUserByLogin($aUserAuthData['login']);
         if (!$oUser) {
             $iError = self::USER_AUTH_ERR_LOGIN;
         }
     }
     if (!$oUser && !empty($aUserAuthData['email'])) {
         if (F::CheckVal($aUserAuthData['email'], 'email')) {
             $oUser = $this->GetUserByMail($aUserAuthData['email']);
             if ($oUser) {
                 $iError = null;
             } else {
                 $iError = self::USER_AUTH_ERR_MAIL;
             }
         }
     }
     if (!$oUser && !empty($aUserAuthData['id'])) {
         if (F::CheckVal(!empty($aUserAuthData['id']), 'id')) {
             $oUser = $this->GetUserById($aUserAuthData['id']);
             if (!$oUser) {
                 $iError = self::USER_AUTH_ERR_ID;
             }
         }
     }
     if (!$oUser && !empty($aUserAuthData['session'])) {
         $oUser = $this->GetUserBySessionKey($aUserAuthData['session']);
         if (!$oUser) {
             $iError = self::USER_AUTH_ERR_SESSION;
         }
     }
     if ($oUser && !empty($aUserAuthData['password'])) {
         if (!$this->CheckPassword($oUser, $aUserAuthData['password'])) {
             $iError = self::USER_AUTH_ERR_PASSWORD;
         }
     }
     if ($oUser && !$iError) {
         $iError = self::USER_AUTH_RESULT_OK;
         if (!$oUser->getActivate()) {
             $iError = self::USER_AUTH_ERR_NOT_ACTIVATED;
         }
         // Не забанен ли юзер
         if ($oUser->IsBanned()) {
             if ($oUser->IsBannedByIp()) {
                 $iError = self::USER_AUTH_ERR_IP_BANNED;
             } elseif ($oUser->GetBanLine()) {
                 $iError = self::USER_AUTH_ERR_BANNED_DATE;
             } else {
                 $iError = self::USER_AUTH_ERR_BANNED_UNLIM;
             }
         }
     } elseif (!$iError) {
         $iError = self::USER_AUTH_ERROR;
     }
     $aUserAuthData['error'] = $iError;
     return $oUser;
 }
コード例 #6
0
 /**
  * Проверка полей блога
  *
  * @param ModuleBlog_EntityBlog|null $oBlog
  *
  * @return bool
  */
 protected function checkBlogFields($oBlog = null)
 {
     $bOk = true;
     // * Проверяем есть ли название блога
     if (!F::CheckVal(F::GetRequestStr('blog_title'), 'text', 2, 200)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('blog_create_title_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     } else {
         // * Проверяем есть ли уже блог с таким названием
         if ($oBlogExists = E::ModuleBlog()->GetBlogByTitle(F::GetRequestStr('blog_title'))) {
             if (!$oBlog || $oBlog->getId() != $oBlogExists->getId()) {
                 E::ModuleMessage()->AddError(E::ModuleLang()->Get('blog_create_title_error_unique'), E::ModuleLang()->Get('error'));
                 $bOk = false;
             }
         }
     }
     return $bOk;
 }
コード例 #7
0
ファイル: ActionSearch.class.php プロジェクト: Azany/altocms
 /**
  * Разбор запроса
  *
  * @param null $sType
  *
  * @return mixed
  */
 protected function _prepareRequest($sType = null)
 {
     $sRequest = trim(F::GetRequest('q'));
     // * Иногда ломается кодировка, напр., если ввели поиск в адресной строке браузера
     // * Пытаемся восстановить по основной кодировке браузера
     if (!mb_check_encoding($sRequest)) {
         list($sCharset) = explode(',', $_SERVER['HTTP_ACCEPT_CHARSET']);
         $sQueryString = mb_convert_encoding($_SERVER['QUERY_STRING'], 'UTF-8', $sCharset);
         $sRequest = mb_convert_encoding($sRequest, 'UTF-8', $sCharset);
     }
     if ($sRequest) {
         // Две звездочки подряд меняем на одну
         $sRequest = preg_replace('/(\\*{2,})/', '*', $sRequest);
         // Две пробела подряд меняем на один
         $sRequest = preg_replace('/(\\s{2,})/', ' ', $sRequest);
         // Последовательность звездочек и пробелов, начинающаяся со звездочки
         $sRequest = preg_replace('/\\*[\\*\\s]{2,}/', '* ', $sRequest);
         // Последовательность звездочек и пробелов, начинающаяся с пробела
         $sRequest = preg_replace('/\\s[\\*\\s]{2,}/', ' *', $sRequest);
     }
     $aReq['q'] = $sRequest;
     $aReq['regexp'] = preg_quote(trim(mb_strtolower($aReq['q'])));
     // * Проверка длины запроса
     if (!F::CheckVal($aReq['regexp'], 'text', Config::Get('module.search.min_length_req'), Config::Get('module.search.max_length_req'))) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('search_err_length', array('min' => Config::Get('module.search.min_length_req'), 'max' => Config::Get('module.search.max_length_req'))));
         $aReq['regexp'] = '';
     }
     // Save quoted substrings
     $aQuoted = array();
     if (preg_match_all('/"([^"]+)"/U', $aReq['regexp'], $aMatches)) {
         foreach ($aMatches[1] as $sStr) {
             $sSubstKey = 'begin-' . md5($sStr) . '-end';
             $aQuoted[0][] = $sSubstKey;
             $aQuoted[1][] = $sStr;
         }
         $aReq['regexp'] = str_replace($aQuoted[1], $aQuoted[0], $aReq['regexp']);
     }
     /*
      * Проверка длины каждого слова в запросе
      * Хотя бы одно слово должно быть больше минимальной длины
      * Слова меньше минимальной длины исключаем из поиска
      */
     if ($aReq['regexp']) {
         $aWords = explode(' ', $aReq['regexp']);
         $nErr = 0;
         $sStr = '';
         foreach ($aWords as $sWord) {
             if (!F::CheckVal($sWord, 'text', Config::Get('module.search.min_length_req'), Config::Get('module.search.max_length_req'))) {
                 $nErr += 1;
             } else {
                 if ($sStr) {
                     $sStr .= ' ';
                 }
                 $sStr .= $sWord;
             }
         }
         if ($nErr == sizeof($aWords)) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('search_err_length_word', array('min' => Config::Get('module.search.min_length_req'), 'max' => Config::Get('module.search.max_length_req'))));
             $aReq['regexp'] = '';
         } else {
             $aReq['regexp'] = $sStr;
         }
     }
     // * Если все нормально, формируем выражение для поиска
     if ($aReq['regexp']) {
         if ($this->bSearchStrict) {
             $aReq['regexp'] = str_replace('\\*', '*', $aReq['regexp']);
             /*
              * Проверка на "лишние" символы, оставляем только "слова"
              * На месте "небукв" оставляем пробелы
              */
             $aReq['regexp'] = preg_replace('/' . $this->sPatternXA . '/iusxSU', ' ', $aReq['regexp']);
             $aReq['regexp'] = trim(preg_replace('/(\\s{2,})/', ' ', $aReq['regexp']));
             // * Если после "чистки" что-то осталось, то продолжаем дальше
             if ($aReq['regexp']) {
                 $aReq['regexp'] = str_replace('* *', '|', $aReq['regexp']);
                 $aReq['regexp'] = str_replace('* ', '|[[:<:]]', $aReq['regexp']);
                 $aReq['regexp'] = str_replace(' *', '[[:>:]]|', $aReq['regexp']);
                 $aReq['regexp'] = str_replace(' ', '[[:>:]]|[[:<:]]', $aReq['regexp']);
                 if (mb_substr($aReq['regexp'], 0, 1) == '*') {
                     $aReq['regexp'] = mb_substr($aReq['regexp'], 1);
                 } else {
                     $aReq['regexp'] = '[[:<:]]' . $aReq['regexp'];
                 }
                 if (mb_substr($aReq['regexp'], -1) == '*') {
                     $aReq['regexp'] = mb_substr($aReq['regexp'], 0, mb_strlen($aReq['regexp']) - 1);
                 } else {
                     $aReq['regexp'] = $aReq['regexp'] . '[[:>:]]';
                 }
             }
         } else {
             $aReq['regexp'] = preg_replace('/' . $this->sPatternXA . '/uU', '', $aReq['regexp']);
             $aReq['regexp'] = trim(preg_replace('/(\\s{2,})/', ' ', $aReq['regexp']));
             $aReq['regexp'] = str_replace(' ', '|', $aReq['regexp']);
         }
     }
     // Restore quoted substrings
     if ($aReq['regexp'] && !empty($aQuoted[0])) {
         $aReq['regexp'] = str_replace($aQuoted[0], $aQuoted[1], $aReq['regexp']);
     }
     $aReq['params']['bSkipTags'] = false;
     if ($sType) {
         $aReq['sType'] = $sType;
     } else {
         $aReq['sType'] = 'topics';
     }
     // * Определяем текущую страницу вывода результата
     $aReq['iPage'] = intval(preg_replace('#^page(\\d+)$#', '\\1', $this->getParam(0)));
     if (!$aReq['iPage']) {
         $aReq['iPage'] = 1;
     }
     return $aReq;
 }
コード例 #8
0
ファイル: ActionAdmin.class.php プロジェクト: ZeoNish/altocms
 public function EventAjaxUserList()
 {
     E::ModuleViewer()->SetResponseAjax('json');
     if ($this->IsPost()) {
         $sList = trim($this->GetPost('invite_listmail'));
         if ($aList = F::Array_Str2Array($sList, "\n", true)) {
             $iSentCount = 0;
             foreach ($aList as $iKey => $sMail) {
                 if (F::CheckVal($sMail, 'mail')) {
                     $oInvite = E::ModuleUser()->GenerateInvite($this->oUserCurrent);
                     if (E::ModuleNotify()->SendInvite($this->oUserCurrent, $sMail, $oInvite)) {
                         unset($aList[$iKey]);
                         $iSentCount++;
                     }
                 }
             }
             E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('action.admin.invaite_mail_done', array('num' => $iSentCount)), null, true);
             if ($aList) {
                 E::ModuleMessage()->AddError(E::ModuleLang()->Get('action.admin.invaite_mail_err', array('num' => count($aList))), null, true);
             }
         }
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
     }
 }
コード例 #9
0
ファイル: ActionTalk.class.php プロジェクト: ZeoNish/altocms
 /**
  * Обработка добавление комментария к письму
  *
  */
 protected function SubmitComment()
 {
     // * Проверям авторизован ли пользователь
     if (!E::ModuleUser()->IsAuthorization()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Проверяем разговор
     if (!($oTalk = E::ModuleTalk()->GetTalkById(F::GetRequestStr('cmt_target_id')))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return false;
     }
     if (!($oTalkUser = E::ModuleTalk()->GetTalkUser($oTalk->getId(), $this->oUserCurrent->getId()))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Проверяем разрешено ли отправлять инбокс по времени
     if (!E::ModuleACL()->CanPostTalkCommentTime($this->oUserCurrent)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('talk_time_limit'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Проверяем текст комментария
     $sText = E::ModuleText()->Parser(F::GetRequestStr('comment_text'));
     $iMin = intval(Config::Get('module.talk.min_length'));
     $iMax = intval(Config::Get('module.talk.max_length'));
     if (!F::CheckVal($sText, 'text', $iMin, $iMax)) {
         if ($iMax) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('talk_create_text_error_len', array('min' => $iMin, 'max' => $iMax)), E::ModuleLang()->Get('error'));
         } else {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('talk_create_text_error_min', array('min' => $iMin)), E::ModuleLang()->Get('error'));
         }
         return false;
     }
     // * Проверям на какой коммент отвечаем
     $sParentId = (int) F::GetRequest('reply');
     if (!F::CheckVal($sParentId, 'id')) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return false;
     }
     $oCommentParent = null;
     if ($sParentId != 0) {
         // * Проверяем существует ли комментарий на который отвечаем
         if (!($oCommentParent = E::ModuleComment()->GetCommentById($sParentId))) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
             return false;
         }
         // * Проверяем из одного топика ли новый коммент и тот на который отвечаем
         if ($oCommentParent->getTargetId() != $oTalk->getId()) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
             return false;
         }
     } else {
         // * Корневой комментарий
         $sParentId = null;
     }
     // * Проверка на дублирующий коммент
     if (E::ModuleComment()->GetCommentUnique($oTalk->getId(), 'talk', $this->oUserCurrent->getId(), $sParentId, md5($sText))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_spam'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Создаём комментарий
     /** @var ModuleComment_EntityComment $oCommentNew */
     $oCommentNew = E::GetEntity('Comment');
     $oCommentNew->setTargetId($oTalk->getId());
     $oCommentNew->setTargetType('talk');
     $oCommentNew->setUserId($this->oUserCurrent->getId());
     $oCommentNew->setText($sText);
     $oCommentNew->setDate(F::Now());
     $oCommentNew->setUserIp(F::GetUserIp());
     $oCommentNew->setPid($sParentId);
     $oCommentNew->setTextHash(md5($sText));
     $oCommentNew->setPublish(1);
     // * Добавляем коммент
     E::ModuleHook()->Run('talk_comment_add_before', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTalk' => $oTalk));
     if (E::ModuleComment()->AddComment($oCommentNew)) {
         E::ModuleHook()->Run('talk_comment_add_after', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTalk' => $oTalk));
         E::ModuleViewer()->AssignAjax('sCommentId', $oCommentNew->getId());
         $oTalk->setDateLast(F::Now());
         $oTalk->setUserIdLast($oCommentNew->getUserId());
         $oTalk->setCommentIdLast($oCommentNew->getId());
         $oTalk->setCountComment($oTalk->getCountComment() + 1);
         E::ModuleTalk()->UpdateTalk($oTalk);
         // * Отсылаем уведомления всем адресатам
         $aUsersTalk = E::ModuleTalk()->GetUsersTalk($oTalk->getId(), ModuleTalk::TALK_USER_ACTIVE);
         foreach ($aUsersTalk as $oUserTalk) {
             if ($oUserTalk->getId() != $oCommentNew->getUserId()) {
                 E::ModuleNotify()->SendTalkCommentNew($oUserTalk, $this->oUserCurrent, $oTalk, $oCommentNew);
             }
         }
         // * Увеличиваем число новых комментов
         E::ModuleTalk()->IncreaseCountCommentNew($oTalk->getId(), $oCommentNew->getUserId());
         return true;
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
     }
     return false;
 }
コード例 #10
0
ファイル: ActionSearch.class.php プロジェクト: AntiqS/altocms
 /**
  * Подготовка запроса на поиск
  *
  * @return array
  */
 protected function PrepareRequest()
 {
     $aReq['q'] = F::GetRequestStr('q');
     if (!F::CheckVal($aReq['q'], 'text', 2, 255)) {
         /*
          * Если запрос слишком короткий перенаправляем на начальную страницу поиска
          * Хотя тут лучше показывать юзеру в чем он виноват
          */
         Router::Location(Router::GetPath('search'));
     }
     $aReq['sType'] = strtolower(Router::GetActionEvent());
     // * Определяем текущую страницу вывода результата
     $aReq['iPage'] = intval(preg_replace('#^page([1-9]\\d{0,5})$#', '\\1', $this->getParam(0)));
     if (!$aReq['iPage']) {
         $aReq['iPage'] = 1;
     }
     // *  Передача данных в шаблонизатор
     E::ModuleViewer()->Assign('aReq', $aReq);
     return $aReq;
 }
コード例 #11
0
ファイル: ActionAjax.class.php プロジェクト: anp135/altocms
 /**
  * Предпросмотр топика
  *
  */
 protected function EventPreviewTopic()
 {
     /**
      * Т.к. используется обработка отправки формы, то устанавливаем тип ответа 'jsonIframe' (тот же JSON только обернутый в textarea)
      * Это позволяет избежать ошибок в некоторых браузерах, например, Opera
      */
     E::ModuleViewer()->SetResponseAjax(F::AjaxRequest(true) ? 'json' : 'jsonIframe', false);
     // * Пользователь авторизован?
     if (!$this->oUserCurrent) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Допустимый тип топика?
     if (!E::ModuleTopic()->IsAllowTopicType($sType = F::GetRequestStr('topic_type'))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_create_type_error'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Создаем объект топика для валидации данных
     $oTopic = E::GetEntity('ModuleTopic_EntityTopic');
     $oTopic->_setValidateScenario($sType);
     // зависит от типа топика
     $oTopic->setTitle(strip_tags(F::GetRequestStr('topic_title')));
     $oTopic->setTextSource(F::GetRequestStr('topic_text'));
     $aTags = F::GetRequestStr('topic_field_tags');
     if (!$aTags) {
         // LS compatibility
         $aTags = F::GetRequestStr('topic_tags');
     }
     $oTopic->setTags($aTags);
     $oTopic->setDateAdd(F::Now());
     $oTopic->setUserId($this->oUserCurrent->getId());
     $oTopic->setType($sType);
     $oTopic->setBlogId(F::GetRequestStr('blog_id'));
     $oTopic->setPublish(1);
     // * Валидируем необходимые поля топика
     $oTopic->_Validate(array('topic_title', 'topic_text', 'topic_tags', 'topic_type'), false);
     if ($oTopic->_hasValidateErrors()) {
         E::ModuleMessage()->AddErrorSingle($oTopic->_getValidateError());
         return false;
     }
     // * Формируем текст топика
     list($sTextShort, $sTextNew, $sTextCut) = E::ModuleText()->Cut($oTopic->getTextSource());
     $oTopic->setCutText($sTextCut);
     $oTopic->setText(E::ModuleText()->Parse($sTextNew));
     $oTopic->setTextShort(E::ModuleText()->Parse($sTextShort));
     // * Готовим дополнительные поля, кроме файлов
     if ($oType = $oTopic->getContentType()) {
         //получаем поля для данного типа
         if ($aFields = $oType->getFields()) {
             $aValues = array();
             // вставляем поля, если они прописаны для топика
             foreach ($aFields as $oField) {
                 if (isset($_REQUEST['fields'][$oField->getFieldId()])) {
                     $sText = null;
                     //текстовые поля
                     if (in_array($oField->getFieldType(), array('input', 'textarea', 'select'))) {
                         $sText = E::ModuleText()->Parse($_REQUEST['fields'][$oField->getFieldId()]);
                     }
                     //поле ссылки
                     if ($oField->getFieldType() == 'link') {
                         $sText = $_REQUEST['fields'][$oField->getFieldId()];
                     }
                     //поле даты
                     if ($oField->getFieldType() == 'date') {
                         if (isset($_REQUEST['fields'][$oField->getFieldId()])) {
                             if (F::CheckVal($_REQUEST['fields'][$oField->getFieldId()], 'text', 6, 10) && substr_count($_REQUEST['fields'][$oField->getFieldId()], '.') == 2) {
                                 list($d, $m, $y) = explode('.', $_REQUEST['fields'][$oField->getFieldId()]);
                                 if (@checkdate($m, $d, $y)) {
                                     $sText = $_REQUEST['fields'][$oField->getFieldId()];
                                 }
                             }
                         }
                     }
                     if ($sText) {
                         $oValue = E::GetEntity('Topic_ContentValues');
                         $oValue->setFieldId($oField->getFieldId());
                         $oValue->setFieldType($oField->getFieldType());
                         $oValue->setValue($sText);
                         $oValue->setValueSource($_REQUEST['fields'][$oField->getFieldId()]);
                         $aValues[$oField->getFieldId()] = $oValue;
                     }
                 }
             }
             $oTopic->setTopicValues($aValues);
         }
     }
     // * Рендерим шаблон для предпросмотра топика
     $oViewer = E::ModuleViewer()->GetLocalViewer();
     $oViewer->Assign('oTopic', $oTopic);
     $oViewer->Assign('bPreview', true);
     // Alto-style template
     $sTemplate = 'topics/topic.show.tpl';
     if (!E::ModuleViewer()->TemplateExists($sTemplate)) {
         // LS-style template
         $sTemplate = "topic_preview_{$oTopic->getType()}.tpl";
         if (!E::ModuleViewer()->TemplateExists($sTemplate)) {
             $sTemplate = 'topic_preview_topic.tpl';
         }
     }
     $sTextResult = $oViewer->Fetch($sTemplate);
     // * Передаем результат в ajax ответ
     E::ModuleViewer()->AssignAjax('sText', $sTextResult);
     return true;
 }
コード例 #12
0
 /**
  * Обрабатывает активацию аккаунта
  */
 protected function EventActivate()
 {
     $bError = false;
     // * Проверяет передан ли код активации
     $sActivateKey = $this->GetParam(0);
     if (!F::CheckVal($sActivateKey, 'md5')) {
         $bError = true;
     }
     // * Проверяет верный ли код активации
     if (!($oUser = E::ModuleUser()->GetUserByActivationKey($sActivateKey))) {
         $bError = true;
     }
     // * User is already activated
     if ($oUser && $oUser->isActivated()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('registration_activate_error_reactivate'), E::ModuleLang()->Get('error'));
         return R::Action('error');
     }
     // * Если что то не то
     if ($bError) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('registration_activate_error_code'), E::ModuleLang()->Get('error'));
         return R::Action('error');
     }
     // * Активируем
     if ($this->_activateUser($oUser)) {
         $this->DropInviteRegister();
         E::ModuleViewer()->Assign('bRefreshToHome', true);
         E::ModuleUser()->Authorization($oUser, false);
         return;
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
         return R::Action('error');
     }
 }
コード例 #13
0
ファイル: ActionBlog.class.php プロジェクト: anp135/altocms
 /**
  * Updates comment
  *
  */
 protected function AjaxUpdateComment()
 {
     // * Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     // * Пользователь авторизован?
     if (!$this->oUserCurrent) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return;
     }
     if (!E::ModuleSecurity()->ValidateSendForm(false) || $this->GetPost('comment_mode') != 'edit') {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Проверяем текст комментария
     $sNewText = E::ModuleText()->Parse($this->GetPost('comment_text'));
     $iMin = Config::Val('module.comment.min_length', 2);
     $iMax = Config::Val('module.comment.max_length', 0);
     if (!F::CheckVal($sNewText, 'text', $iMin, $iMax)) {
         if ($iMax) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_text_len', array('min' => $iMin, 'max' => $iMax)), E::ModuleLang()->Get('error'));
         } else {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_text_min', array('min' => $iMin)), E::ModuleLang()->Get('error'));
         }
         return;
     }
     // * Получаем комментарий
     $iCommentId = intval($this->GetPost('comment_id'));
     /** var ModuleComment_EntityComment $oComment */
     if (!$iCommentId || !($oComment = E::ModuleComment()->GetCommentById($iCommentId))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     if (!$oComment->isEditable()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('comment_cannot_edit'), E::ModuleLang()->Get('error'));
         return;
     }
     if (!$oComment->getEditTime() && !$oComment->isEditable(false)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('comment_edit_timeout'), E::ModuleLang()->Get('error'));
         return;
     }
     // Если все нормально, то обновляем текст
     $oComment->setText($sNewText);
     if (E::ModuleComment()->UpdateComment($oComment)) {
         $oComment = E::ModuleComment()->GetCommentById($iCommentId);
         E::ModuleViewer()->AssignAjax('nCommentId', $oComment->getId());
         E::ModuleViewer()->AssignAjax('sText', $oComment->getText());
         E::ModuleViewer()->AssignAjax('sDateEdit', $oComment->getCommentDateEdit());
         E::ModuleViewer()->AssignAjax('sDateEditText', E::ModuleLang()->Get('date_now'));
         E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('comment_updated'));
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
     }
 }
コード例 #14
0
ファイル: function.php プロジェクト: AntiqS/altocms
function func_check($sValue, $sParam, $iMin = 1, $iMax = 100)
{
    return F::CheckVal($sValue, $sParam, $iMin, $iMax);
}
コード例 #15
0
 /**
  * Изменение состояния подписки
  */
 protected function EventAjaxSubscribeToggle()
 {
     /**
      * Устанавливаем формат Ajax ответа
      */
     E::ModuleViewer()->SetResponseAjax('json');
     /**
      * Получаем емайл подписки и проверяем его на валидность
      */
     $sMail = F::GetRequestStr('mail');
     if ($this->oUserCurrent) {
         $sMail = $this->oUserCurrent->getMail();
     }
     if (!F::CheckVal($sMail, 'mail')) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('registration_mail_error'), E::ModuleLang()->Get('error'));
         return;
     }
     /**
      * Получаем тип объекта подписки
      */
     $sTargetType = F::GetRequestStr('target_type');
     if (!E::ModuleSubscribe()->IsAllowTargetType($sTargetType)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     $sTargetId = F::GetRequestStr('target_id') ? F::GetRequestStr('target_id') : null;
     $iValue = F::GetRequest('value') ? 1 : 0;
     $oSubscribe = null;
     /**
      * Есть ли доступ к подписке гостям?
      */
     if (!$this->oUserCurrent && !E::ModuleSubscribe()->IsAllowTargetForGuest($sTargetType)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return;
     }
     /**
      * Проверка объекта подписки
      */
     if (!E::ModuleSubscribe()->CheckTarget($sTargetType, $sTargetId, $iValue)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     /**
      * Если подписка еще не существовала, то создаем её
      */
     if ($oSubscribe = E::ModuleSubscribe()->AddSubscribeSimple($sTargetType, $sTargetId, $sMail, $this->oUserCurrent ? $this->oUserCurrent->getId() : null)) {
         $oSubscribe->setStatus($iValue);
         E::ModuleSubscribe()->UpdateSubscribe($oSubscribe);
         E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('subscribe_change_ok'), E::ModuleLang()->Get('attention'));
         return;
     }
     E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
     return;
 }
コード例 #16
0
ファイル: User.class.php プロジェクト: ZeoNish/altocms
 /**
  * @param $sUserMailOrLogin
  *
  * @return ModuleUser_EntityUser|null
  */
 public function GetUserByMailOrLogin($sUserMailOrLogin)
 {
     if (F::CheckVal($sUserMailOrLogin, 'mail') && ($oUser = $this->GetUserByMail($sUserMailOrLogin)) || ($oUser = $this->GetUserByLogin($sUserMailOrLogin))) {
         return $oUser;
     }
     return null;
 }