Esempio n. 1
0
 /**
  * @param string $sType
  * @param bool   $bClear
  *
  * @throws Exception
  */
 public function loadConfig($sType = 'default', $bClear = true)
 {
     if ($bClear) {
         $this->tagsRules = array();
     }
     $aConfig = C::Get('jevix.' . $sType);
     if (is_array($aConfig)) {
         foreach ($aConfig as $sMethod => $aExec) {
             foreach ($aExec as $aParams) {
                 if (in_array(strtolower($sMethod), array_map('strtolower', array('cfgSetTagCallbackFull', 'cfgSetTagCallback')))) {
                     if (isset($aParams[1][0]) && $aParams[1][0] == '_this_') {
                         $aParams[1][0] = E::ModuleText();
                     }
                 }
                 call_user_func_array(array($this, $sMethod), $aParams);
             }
         }
         // * Хардкодим некоторые параметры
         unset($this->entities1['&']);
         // разрешаем в параметрах символ &
         if (C::Get('view.noindex') && isset($this->tagsRules['a'])) {
             $this->cfgSetTagParamDefault('a', 'rel', 'nofollow', true);
         }
     }
 }
Esempio n. 2
0
 /**
  * @param string $sType
  * @param bool   $bClear
  *
  * @throws Exception
  */
 public function loadConfig($sType = 'default', $bClear = true)
 {
     if ($bClear) {
         $this->tagsRules = array();
     }
     $aConfig = C::Get('qevix.' . $sType);
     if (is_array($aConfig)) {
         foreach ($aConfig as $sMethod => $aExec) {
             if ($sMethod == 'cfgSetAutoReplace') {
                 $this->aAutoReplace = $aExec;
                 continue;
             }
             foreach ($aExec as $aParams) {
                 call_user_func_array(array($this, $sMethod), $aParams);
             }
         }
         // * Хардкодим некоторые параметры
         unset($this->entities1['&']);
         // разрешаем в параметрах символ &
         if (C::Get('view.noindex') && isset($this->tagsRules['a'])) {
             $this->cfgSetTagParamDefault('a', 'rel', 'nofollow', true);
         }
     }
     if (C::Get('module.text.char.@')) {
         $this->cfgSetSpecialCharCallback('@', array(E::ModuleText(), 'CallbackTagAt'));
     }
     if ($aData = C::Get('module.text.autoreplace')) {
         $this->aAutoReplace = array(array_keys($aData), array_values($aData));
     }
 }
Esempio n. 3
0
 /**
  * Обработка дополнительных полей топика
  *
  * @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;
 }
Esempio n. 4
0
 /**
  * Выводит форму для редактирования профиля и обрабатывает её
  *
  */
 protected function EventProfile()
 {
     // * Устанавливаем title страницы
     E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('settings_menu_profile'));
     E::ModuleViewer()->Assign('aUserFields', E::ModuleUser()->GetUserFields(''));
     E::ModuleViewer()->Assign('aUserFieldsContact', E::ModuleUser()->GetUserFields(array('contact', 'social')));
     // * Загружаем в шаблон JS текстовки
     E::ModuleLang()->AddLangJs(array('settings_profile_field_error_max'));
     // * Если нажали кнопку "Сохранить"
     if ($this->isPost('submit_profile_edit')) {
         E::ModuleSecurity()->ValidateSendForm();
         $bError = false;
         /**
          * Заполняем профиль из полей формы
          */
         // * Определяем гео-объект
         if (F::GetRequest('geo_city')) {
             $oGeoObject = E::ModuleGeo()->GetGeoObject('city', F::GetRequestStr('geo_city'));
         } elseif (F::GetRequest('geo_region')) {
             $oGeoObject = E::ModuleGeo()->GetGeoObject('region', F::GetRequestStr('geo_region'));
         } elseif (F::GetRequest('geo_country')) {
             $oGeoObject = E::ModuleGeo()->GetGeoObject('country', F::GetRequestStr('geo_country'));
         } else {
             $oGeoObject = null;
         }
         // * Проверяем имя
         if (F::CheckVal(F::GetRequestStr('profile_name'), 'text', 2, Config::Get('module.user.name_max'))) {
             $this->oUserCurrent->setProfileName(F::GetRequestStr('profile_name'));
         } else {
             $this->oUserCurrent->setProfileName(null);
         }
         // * Проверяем пол
         if (in_array(F::GetRequestStr('profile_sex'), array('man', 'woman', 'other'))) {
             $this->oUserCurrent->setProfileSex(F::GetRequestStr('profile_sex'));
         } else {
             $this->oUserCurrent->setProfileSex('other');
         }
         // * Проверяем дату рождения
         $nDay = intval(F::GetRequestStr('profile_birthday_day'));
         $nMonth = intval(F::GetRequestStr('profile_birthday_month'));
         $nYear = intval(F::GetRequestStr('profile_birthday_year'));
         if (checkdate($nMonth, $nDay, $nYear)) {
             $this->oUserCurrent->setProfileBirthday(date('Y-m-d H:i:s', mktime(0, 0, 0, $nMonth, $nDay, $nYear)));
         } else {
             $this->oUserCurrent->setProfileBirthday(null);
         }
         // * Проверяем информацию о себе
         if (F::CheckVal(F::GetRequestStr('profile_about'), 'text', 1, 3000)) {
             $this->oUserCurrent->setProfileAbout(E::ModuleText()->Parser(F::GetRequestStr('profile_about')));
         } else {
             $this->oUserCurrent->setProfileAbout(null);
         }
         // * Ставим дату последнего изменения профиля
         $this->oUserCurrent->setProfileDate(F::Now());
         // * Запускаем выполнение хуков
         E::ModuleHook()->Run('settings_profile_save_before', array('oUser' => $this->oUserCurrent, 'bError' => &$bError));
         // * Сохраняем изменения профиля
         if (!$bError) {
             if (E::ModuleUser()->Update($this->oUserCurrent)) {
                 // * Обновляем название личного блога
                 $oBlog = $this->oUserCurrent->getBlog();
                 if (F::GetRequestStr('blog_title') && $this->checkBlogFields($oBlog)) {
                     $oBlog->setTitle(strip_tags(F::GetRequestStr('blog_title')));
                     E::ModuleBlog()->UpdateBlog($oBlog);
                 }
                 // * Создаем связь с гео-объектом
                 if ($oGeoObject) {
                     E::ModuleGeo()->CreateTarget($oGeoObject, 'user', $this->oUserCurrent->getId());
                     if ($oCountry = $oGeoObject->getCountry()) {
                         $this->oUserCurrent->setProfileCountry($oCountry->getName());
                     } else {
                         $this->oUserCurrent->setProfileCountry(null);
                     }
                     if ($oRegion = $oGeoObject->getRegion()) {
                         $this->oUserCurrent->setProfileRegion($oRegion->getName());
                     } else {
                         $this->oUserCurrent->setProfileRegion(null);
                     }
                     if ($oCity = $oGeoObject->getCity()) {
                         $this->oUserCurrent->setProfileCity($oCity->getName());
                     } else {
                         $this->oUserCurrent->setProfileCity(null);
                     }
                 } else {
                     E::ModuleGeo()->DeleteTargetsByTarget('user', $this->oUserCurrent->getId());
                     $this->oUserCurrent->setProfileCountry(null);
                     $this->oUserCurrent->setProfileRegion(null);
                     $this->oUserCurrent->setProfileCity(null);
                 }
                 E::ModuleUser()->Update($this->oUserCurrent);
                 // * Обрабатываем дополнительные поля, type = ''
                 $aFields = E::ModuleUser()->GetUserFields('');
                 $aData = array();
                 foreach ($aFields as $iId => $aField) {
                     if (isset($_REQUEST['profile_user_field_' . $iId])) {
                         $aData[$iId] = F::GetRequestStr('profile_user_field_' . $iId);
                     }
                 }
                 E::ModuleUser()->SetUserFieldsValues($this->oUserCurrent->getId(), $aData);
                 // * Динамические поля контактов, type = array('contact','social')
                 $aType = array('contact', 'social');
                 $aFields = E::ModuleUser()->GetUserFields($aType);
                 // * Удаляем все поля с этим типом
                 E::ModuleUser()->DeleteUserFieldValues($this->oUserCurrent->getId(), $aType);
                 $aFieldsContactType = F::GetRequest('profile_user_field_type');
                 $aFieldsContactValue = F::GetRequest('profile_user_field_value');
                 if (is_array($aFieldsContactType)) {
                     foreach ($aFieldsContactType as $k => $v) {
                         $v = (string) $v;
                         if (isset($aFields[$v]) && isset($aFieldsContactValue[$k]) && is_string($aFieldsContactValue[$k])) {
                             E::ModuleUser()->SetUserFieldsValues($this->oUserCurrent->getId(), array($v => $aFieldsContactValue[$k]), Config::Get('module.user.userfield_max_identical'));
                         }
                     }
                 }
                 E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('settings_profile_submit_ok'));
                 E::ModuleHook()->Run('settings_profile_save_after', array('oUser' => $this->oUserCurrent));
             } else {
                 E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
             }
         }
     }
     // * Загружаем гео-объект привязки
     $oGeoTarget = E::ModuleGeo()->GetTargetByTarget('user', $this->oUserCurrent->getId());
     E::ModuleViewer()->Assign('oGeoTarget', $oGeoTarget);
     // * Загружаем в шаблон список стран, регионов, городов
     $aCountries = E::ModuleGeo()->GetCountries(array(), array('sort' => 'asc'), 1, 300);
     E::ModuleViewer()->Assign('aGeoCountries', $aCountries['collection']);
     if ($oGeoTarget) {
         if ($oGeoTarget->getCountryId()) {
             $aRegions = E::ModuleGeo()->GetRegions(array('country_id' => $oGeoTarget->getCountryId()), array('sort' => 'asc'), 1, 500);
             E::ModuleViewer()->Assign('aGeoRegions', $aRegions['collection']);
         }
         if ($oGeoTarget->getRegionId()) {
             $aCities = E::ModuleGeo()->GetCities(array('region_id' => $oGeoTarget->getRegionId()), array('sort' => 'asc'), 1, 500);
             E::ModuleViewer()->Assign('aGeoCities', $aCities['collection']);
         }
     }
     E::ModuleLang()->AddLangJs(array('settings_profile_avatar_resize_title', 'settings_profile_avatar_resize_text', 'settings_profile_photo_resize_title', 'settings_profile_photo_resize_text'));
 }
Esempio n. 5
0
 protected function _eventUsersCmdMessageSeparate()
 {
     $bOk = true;
     $sTitle = F::GetRequest('talk_title');
     $sText = E::ModuleText()->Parser(F::GetRequest('talk_text'));
     $sDate = date(F::Now());
     $sIp = F::GetUserIp();
     if ($sUsers = $this->GetPost('users_list')) {
         $aUsers = explode(',', str_replace(' ', '', $sUsers));
     } else {
         $aUsers = array();
     }
     if ($aUsers) {
         // Если указано, то шлем самому себе со списком получателей
         if (F::GetRequest('send_copy_self')) {
             $oSelfTalk = E::GetEntity('Talk_Talk');
             $oSelfTalk->setUserId($this->oUserCurrent->getId());
             $oSelfTalk->setUserIdLast($this->oUserCurrent->getId());
             $oSelfTalk->setTitle($sTitle);
             $oSelfTalk->setText(E::ModuleText()->Parser('To: <i>' . $sUsers . '</i>' . "\n\n" . 'Msg: ' . $this->GetPost('talk_text')));
             $oSelfTalk->setDate($sDate);
             $oSelfTalk->setDateLast($sDate);
             $oSelfTalk->setUserIp($sIp);
             if ($oSelfTalk = E::ModuleTalk()->AddTalk($oSelfTalk)) {
                 $oTalkUser = E::GetEntity('Talk_TalkUser');
                 $oTalkUser->setTalkId($oSelfTalk->getId());
                 $oTalkUser->setUserId($this->oUserCurrent->getId());
                 $oTalkUser->setDateLast($sDate);
                 E::ModuleTalk()->AddTalkUser($oTalkUser);
                 // уведомление по e-mail
                 $oUserToMail = $this->oUserCurrent;
                 E::ModuleNotify()->SendTalkNew($oUserToMail, $this->oUserCurrent, $oSelfTalk);
             } else {
                 $bOk = false;
             }
         }
         if ($bOk) {
             // теперь рассылаем остальным - каждому отдельное сообщение
             foreach ($aUsers as $sUserLogin) {
                 if ($sUserLogin && $sUserLogin != $this->oUserCurrent->getLogin() && ($oUserRecipient = E::ModuleUser()->GetUserByLogin($sUserLogin))) {
                     $oTalk = E::GetEntity('Talk_Talk');
                     $oTalk->setUserId($this->oUserCurrent->getId());
                     $oTalk->setUserIdLast($this->oUserCurrent->getId());
                     $oTalk->setTitle($sTitle);
                     $oTalk->setText($sText);
                     $oTalk->setDate($sDate);
                     $oTalk->setDateLast($sDate);
                     $oTalk->setUserIp($sIp);
                     if ($oTalk = E::ModuleTalk()->AddTalk($oTalk)) {
                         $oTalkUser = E::GetEntity('Talk_TalkUser');
                         $oTalkUser->setTalkId($oTalk->getId());
                         $oTalkUser->setUserId($oUserRecipient->GetId());
                         $oTalkUser->setDateLast(null);
                         E::ModuleTalk()->AddTalkUser($oTalkUser);
                         // Отправка самому себе, чтобы можно было читать ответ
                         $oTalkUser = E::GetEntity('Talk_TalkUser');
                         $oTalkUser->setTalkId($oTalk->getId());
                         $oTalkUser->setUserId($this->oUserCurrent->getId());
                         $oTalkUser->setDateLast($sDate);
                         E::ModuleTalk()->AddTalkUser($oTalkUser);
                         // Отправляем уведомления
                         $oUserToMail = E::ModuleUser()->GetUserById($oUserRecipient->GetId());
                         E::ModuleNotify()->SendTalkNew($oUserToMail, $this->oUserCurrent, $oTalk);
                     } else {
                         $bOk = false;
                         break;
                     }
                 }
             }
         }
     }
     if ($bOk) {
         E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('action.admin.msg_sent_ok'), null, true);
     } else {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), null, true);
     }
 }
Esempio n. 6
0
 /**
  * Обработка добавление комментария к письму
  *
  */
 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;
 }
Esempio n. 7
0
 /**
  * Предпросмотр текста
  *
  */
 protected function EventPreviewText()
 {
     $sText = F::GetRequestStr('text', null, 'post');
     $bSave = F::GetRequest('save', null, 'post');
     // * Экранировать или нет HTML теги
     if ($bSave) {
         $sTextResult = htmlspecialchars($sText);
     } else {
         $sTextResult = E::ModuleText()->Parse($sText);
     }
     // * Передаем результат в ajax ответ
     E::ModuleViewer()->AssignAjax('sText', $sTextResult);
 }
Esempio n. 8
0
 /**
  * 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'));
     }
 }
Esempio n. 9
0
 /**
  * @return string
  */
 public function GetHomepage()
 {
     $sResult = $this->getProp('homepage');
     if (is_null($sResult)) {
         $sResult = E::ModuleText()->Parser((string) $this->_getXmlProperty('homepage'));
         $this->setProp('homepage', $sResult);
     }
     return $sResult;
 }
Esempio n. 10
0
 /**
  * Обработка редактирования топика
  *
  * @param ModuleTopic_EntityTopic $oTopic
  *
  * @return mixed
  */
 protected function SubmitEdit($oTopic)
 {
     $oTopic->_setValidateScenario('topic');
     // * Сохраняем старое значение идентификатора блога
     $iBlogIdOld = $oTopic->getBlogId();
     // * Заполняем поля для валидации
     $iBlogId = F::GetRequestStr('blog_id');
     // if blog_id is empty then save blog not changed
     if (is_numeric($iBlogId)) {
         $oTopic->setBlogId($iBlogId);
     }
     // issue 151 (https://github.com/altocms/altocms/issues/151)
     // Некорректная обработка названия блога
     // $oTopic->setTitle(strip_tags(F::GetRequestStr('topic_title')));
     $oTopic->setTitle(E::ModuleTools()->RemoveAllTags(F::GetRequestStr('topic_title')));
     $oTopic->setTextSource(F::GetRequestStr('topic_text'));
     if ($this->oContentType->isAllow('link')) {
         $oTopic->setSourceLink(F::GetRequestStr('topic_field_link'));
     }
     $oTopic->setTags(F::GetRequestStr('topic_field_tags'));
     $oTopic->setUserIp(F::GetUserIp());
     if ($this->oUserCurrent && ($this->oUserCurrent->isAdministrator() || $this->oUserCurrent->isModerator())) {
         if (F::GetRequestStr('topic_url') && $oTopic->getTopicUrl() != F::GetRequestStr('topic_url')) {
             $sTopicUrl = E::ModuleTopic()->CorrectTopicUrl(F::TranslitUrl(F::GetRequestStr('topic_url')));
             $oTopic->setTopicUrl($sTopicUrl);
         }
     }
     // * Проверка корректности полей формы
     if (!$this->checkTopicFields($oTopic)) {
         return false;
     }
     // * Определяем в какой блог делаем запись
     $nBlogId = $oTopic->getBlogId();
     if ($nBlogId == 0) {
         $oBlog = E::ModuleBlog()->GetPersonalBlogByUserId($oTopic->getUserId());
     } else {
         $oBlog = E::ModuleBlog()->GetBlogById($nBlogId);
     }
     // * Если блог не определен выдаем предупреждение
     if (!$oBlog) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_create_blog_error_unknown'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Проверяем права на постинг в блог
     if (!E::ModuleACL()->IsAllowBlog($oBlog, $this->oUserCurrent)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_create_blog_error_noallow'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Проверяем разрешено ли постить топик по времени
     if (isPost('submit_topic_publish') && !$oTopic->getPublishDraft() && !E::ModuleACL()->CanPostTopicTime($this->oUserCurrent)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_time_limit'), E::ModuleLang()->Get('error'));
         return;
     }
     $oTopic->setBlogId($oBlog->getId());
     // * Получаемый и устанавливаем разрезанный текст по тегу <cut>
     list($sTextShort, $sTextNew, $sTextCut) = E::ModuleText()->Cut($oTopic->getTextSource());
     $oTopic->setCutText($sTextCut);
     $oTopic->setText(E::ModuleText()->Parser($sTextNew));
     // Получаем ссылки, полученные при парсинге текста
     $oTopic->setTextLinks(E::ModuleText()->GetLinks());
     $oTopic->setTextShort(E::ModuleText()->Parser($sTextShort));
     // * Изменяем вопрос/ответы, только если еще никто не голосовал
     if ($this->oContentType->isAllow('poll') && F::GetRequestStr('topic_field_question') && F::GetRequest('topic_field_answers', array()) && $oTopic->getQuestionCountVote() == 0) {
         $oTopic->setQuestionTitle(strip_tags(F::GetRequestStr('topic_field_question')));
         $oTopic->clearQuestionAnswer();
         $aAnswers = F::GetRequest('topic_field_answers', array());
         foreach ($aAnswers as $sAnswer) {
             $sAnswer = trim((string) $sAnswer);
             if ($sAnswer) {
                 $oTopic->addQuestionAnswer($sAnswer);
             }
         }
     }
     $aPhotoSetData = E::ModuleMresource()->GetPhotosetData('photoset', $oTopic->getId());
     $oTopic->setPhotosetCount($aPhotoSetData['count']);
     $oTopic->setPhotosetMainPhotoId($aPhotoSetData['cover']);
     // * Publish or save as a draft
     $bSendNotify = false;
     if (isset($_REQUEST['submit_topic_publish'])) {
         // If the topic has not been published then sets date of show (publication date)
         if (!$oTopic->getPublish() && !$oTopic->getDateShow()) {
             $oTopic->setDateShow(F::Now());
         }
         $oTopic->setPublish(1);
         if ($oTopic->getPublishDraft() == 0) {
             $oTopic->setPublishDraft(1);
             $oTopic->setDateAdd(F::Now());
             $bSendNotify = true;
         }
     } else {
         $oTopic->setPublish(0);
     }
     // * Принудительный вывод на главную
     if (E::ModuleACL()->IsAllowPublishIndex($this->oUserCurrent)) {
         if (F::GetRequest('topic_publish_index')) {
             $oTopic->setPublishIndex(1);
         } else {
             $oTopic->setPublishIndex(0);
         }
     }
     // * Запрет на комментарии к топику
     $oTopic->setForbidComment(F::GetRequest('topic_forbid_comment', 0));
     // Если запрет на индексацию не устанавливался вручную, то задаем, как у блога
     $oBlogType = $oBlog->GetBlogType();
     if ($oBlogType && !$oTopic->getIndexIgnoreLock()) {
         $oTopic->setTopicIndexIgnore($oBlogType->GetIndexIgnore());
     } else {
         $oTopic->setTopicIndexIgnore(false);
     }
     $oTopic->setShowPhotoset(F::GetRequest('topic_show_photoset', 0));
     E::ModuleHook()->Run('topic_edit_before', array('oTopic' => $oTopic, 'oBlog' => $oBlog));
     // * Сохраняем топик
     if ($this->_updateTopic($oTopic)) {
         E::ModuleHook()->Run('topic_edit_after', array('oTopic' => $oTopic, 'oBlog' => $oBlog, 'bSendNotify' => &$bSendNotify));
         // * Обновляем данные в комментариях, если топик был перенесен в новый блог
         if ($iBlogIdOld != $oTopic->getBlogId()) {
             E::ModuleComment()->UpdateTargetParentByTargetId($oTopic->getBlogId(), 'topic', $oTopic->getId());
             E::ModuleComment()->UpdateTargetParentByTargetIdOnline($oTopic->getBlogId(), 'topic', $oTopic->getId());
         }
         // * Обновляем количество топиков в блоге
         if ($iBlogIdOld != $oTopic->getBlogId()) {
             E::ModuleBlog()->RecalculateCountTopicByBlogId($iBlogIdOld);
         }
         E::ModuleBlog()->RecalculateCountTopicByBlogId($oTopic->getBlogId());
         // * Добавляем событие в ленту
         E::ModuleStream()->Write($oTopic->getUserId(), 'add_topic', $oTopic->getId(), $oTopic->getPublish() && (!$oBlogType || !$oBlog->getBlogType()->IsPrivate()));
         // * Рассылаем о новом топике подписчикам блога
         if ($bSendNotify) {
             E::ModuleTopic()->SendNotifyTopicNew($oBlog, $oTopic, $oTopic->getUser());
         }
         if (!$oTopic->getPublish() && !$this->oUserCurrent->isAdministrator() && !$this->oUserCurrent->isModerator() && $this->oUserCurrent->getId() != $oTopic->getUserId()) {
             R::Location($oBlog->getUrlFull());
         }
         R::Location($oTopic->getUrl());
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
         F::SysWarning('System Error');
         return R::Action('error');
     }
 }
Esempio n. 11
0
 /**
  * Получает значение параметра из XML на основе языковой разметки
  *
  * @param SimpleXMLElement $oXml    XML узел
  * @param string           $sProperty    Свойство, которое нужно вернуть
  * @param string           $sLang    Название языка
  */
 protected function _xlang($oXml, $sProperty, $sLang, $bParseText = false)
 {
     $sProperty = trim($sProperty);
     if (!count($data = $oXml->xpath("{$sProperty}/lang[@name='{$sLang}']"))) {
         $data = $oXml->xpath("{$sProperty}/lang[@name='default']");
     }
     if ($bParseText) {
         $oXml->{$sProperty}->data = E::ModuleText()->Parser(trim((string) array_shift($data)));
     } else {
         $oXml->{$sProperty}->data = trim((string) array_shift($data));
     }
 }
Esempio n. 12
0
 /**
  * Поиск комментариев
  *
  */
 function EventComments()
 {
     /**
      * Ищем
      */
     $aReq = $this->PrepareRequest();
     $aRes = $this->PrepareResults($aReq, Config::Get('module.comment.per_page'));
     if (false === $aRes) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
         return Router::Action('error');
     }
     /**
      * Если поиск дал результаты
      */
     if ($this->bIsResults) {
         /**
          *  Получаем топик-объекты по списку идентификаторов
          */
         $aComments = E::ModuleComment()->GetCommentsAdditionalData(array_keys($this->aSphinxRes['matches']));
         /**
          * Конфигурируем парсер jevix
          */
         E::ModuleText()->LoadJevixConfig('search');
         /**
          * Делаем сниппеты
          */
         foreach ($aComments as $oComment) {
             $oComment->setText(E::ModuleText()->TextParser(E::ModuleSphinx()->GetSnippet(htmlspecialchars($oComment->getText()), 'comments', $aReq['q'], '<span class="searched-item">', '</span>')));
         }
         /**
          *  Отправляем данные в шаблон
          */
         E::ModuleViewer()->Assign('aRes', $aRes);
         E::ModuleViewer()->Assign('aComments', $aComments);
     }
 }
 protected function _updateBlog($oBlog)
 {
     $sSubtitle = E::ModuleText()->Parser(F::GetRequestStr('blog_subtitle'));
     $oBlog->setSubtitle($sSubtitle);
     return parent::_updateBlog($oBlog);
 }
Esempio n. 14
0
 /**
  * Обработка добавления в друзья
  *
  * @param ModuleUser_EntityUser $oUser
  * @param string                $sUserText
  * @param ModuleUser_EntityUser $oFriend
  *
  * @return bool
  */
 protected function SubmitAddFriend($oUser, $sUserText, $oFriend = null)
 {
     /**
      * Ограничения на добавления в друзья, т.к. приглашение отправляется в личку, то и ограничиваем по ней
      */
     if (!E::ModuleACL()->CanSendTalkTime($this->oUserCurrent)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('user_friend_add_time_limit'), E::ModuleLang()->Get('error'));
         return false;
     }
     /**
      * Обрабатываем текст заявки
      */
     $sUserText = E::ModuleText()->Parse($sUserText);
     /**
      * Создаем связь с другом
      */
     /** @var ModuleUser_EntityFriend $oFriendNew */
     $oFriendNew = E::GetEntity('User_Friend');
     $oFriendNew->setUserTo($oUser->getId());
     $oFriendNew->setUserFrom($this->oUserCurrent->getId());
     // Добавляем заявку в друзья
     $oFriendNew->setStatusFrom(ModuleUser::USER_FRIEND_OFFER);
     $oFriendNew->setStatusTo(ModuleUser::USER_FRIEND_NULL);
     $bStateError = $oFriend ? !E::ModuleUser()->UpdateFriend($oFriendNew) : !E::ModuleUser()->AddFriend($oFriendNew);
     if (!$bStateError) {
         E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('user_friend_offer_send'), E::ModuleLang()->Get('attention'));
         $sTitle = E::ModuleLang()->Get('user_friend_offer_title', array('login' => $this->oUserCurrent->getLogin(), 'friend' => $oUser->getLogin()));
         F::IncludeLib('XXTEA/encrypt.php');
         $sCode = $this->oUserCurrent->getId() . '_' . $oUser->getId();
         $sCode = rawurlencode(base64_encode(xxtea_encrypt($sCode, Config::Get('module.talk.encrypt'))));
         $aPath = array('accept' => R::GetPath('profile') . 'friendoffer/accept/?code=' . $sCode, 'reject' => R::GetPath('profile') . 'friendoffer/reject/?code=' . $sCode);
         $sText = E::ModuleLang()->Get('user_friend_offer_text', array('login' => $this->oUserCurrent->getLogin(), 'accept_path' => $aPath['accept'], 'reject_path' => $aPath['reject'], 'user_text' => $sUserText));
         $oTalk = E::ModuleTalk()->SendTalk($sTitle, $sText, $this->oUserCurrent, array($oUser), false, false);
         /**
          * Отправляем пользователю заявку
          */
         E::ModuleNotify()->SendUserFriendNew($oUser, $this->oUserCurrent, $sUserText, R::GetPath('talk') . 'read/' . $oTalk->getId() . '/');
         /**
          * Удаляем отправляющего юзера из переписки
          */
         E::ModuleTalk()->DeleteTalkUserByArray($oTalk->getId(), $this->oUserCurrent->getId());
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
     }
     /**
      * Подписываем запрашивающего дружбу на
      */
     E::ModuleStream()->SubscribeUser($this->oUserCurrent->getId(), $oUser->getId());
     $oViewerLocal = $this->GetViewerLocal();
     $oViewerLocal->Assign('oUserFriend', $oFriendNew);
     E::ModuleViewer()->AssignAjax('sToggleText', $oViewerLocal->Fetch('actions/profile/action.profile.friend_item.tpl'));
 }