예제 #1
0
 /**
  * Saves file in storage
  *
  * @param string $sFile
  * @param string $sDestination
  *
  * @return bool|ModuleUploader_EntityItem
  */
 public function Store($sFile, $sDestination = null)
 {
     if (!$sDestination) {
         $oUser = E::ModuleUser()->GetUserCurrent();
         if (!$oUser) {
             return false;
         }
         $sDestination = E::ModuleUploader()->GetUserFileDir($oUser->getId());
     }
     if ($sDestination) {
         $sMimeType = ModuleImg::MimeType($sFile);
         $bIsImage = strpos($sMimeType, 'image/') === 0;
         $iUserId = E::UserId();
         $sExtension = F::File_GetExtension($sFile, true);
         if (substr($sDestination, -1) == '/') {
             $sDestinationDir = $sDestination;
         } else {
             $sDestinationDir = dirname($sDestination) . '/';
         }
         $sUuid = ModuleMresource::CreateUuid('file', $sFile, md5_file($sFile), $iUserId);
         $sDestination = $sDestinationDir . $sUuid . '.' . $sExtension;
         if ($sStoredFile = E::ModuleUploader()->Move($sFile, $sDestination, true)) {
             $oStoredItem = E::GetEntity('Uploader_Item', array('storage' => 'file', 'uuid' => $sUuid, 'original_filename' => basename($sFile), 'url' => $this->Dir2Url($sStoredFile), 'file' => $sStoredFile, 'user_id' => $iUserId, 'mime_type' => $sMimeType, 'is_image' => $bIsImage));
             return $oStoredItem;
         }
     }
     return false;
 }
예제 #2
0
 /**
  * Получение подписки по типу и емейлу
  *
  * @param string $sType    Тип
  * @param string $sMail    Емайл
  *
  * @return ModuleSubscribe_EntitySubscribe|null
  */
 public function GetSubscribeByTypeAndMail($sType, $sMail)
 {
     $sql = "SELECT * FROM ?_subscribe WHERE target_type = ? AND mail = ?";
     if ($aRow = $this->oDb->selectRow($sql, $sType, $sMail)) {
         return E::GetEntity('Subscribe', $aRow);
     }
     return null;
 }
예제 #3
0
 /**
  * Получает событие по типу и его ID
  *
  * @param string   $sEventType    Тип
  * @param int      $iTargetId     ID владельца события
  * @param int|null $iUserId       ID пользователя
  *
  * @return ModuleStream_EntityEvent
  */
 public function GetEventByTarget($sEventType, $iTargetId, $iUserId = null)
 {
     $sql = "SELECT * FROM\n\t\t\t\t\t?_stream_event\n\t\t\t\tWHERE target_id = ?d AND event_type = ? { AND user_id = ?d } ";
     $aRow = $this->oDb->selectRow($sql, $iTargetId, $sEventType, is_null($iUserId) ? DBSIMPLE_SKIP : $iUserId);
     if ($aRow) {
         return E::GetEntity('ModuleStream_EntityEvent', $aRow);
     }
     return null;
 }
예제 #4
0
 /**
  * @param string $sKeyName
  *
  * @return ModuleCaptcha_EntityCaptcha
  */
 public function GetCaptcha($sKeyName = null)
 {
     /** @var ModuleCaptcha_EntityCaptcha $oCaptcha */
     $oCaptcha = E::GetEntity('Captcha_Captcha');
     if (!$sKeyName) {
         $sKeyName = $this->sKeyName;
     }
     E::ModuleSession()->Set($sKeyName, $oCaptcha->getKeyString());
     return $oCaptcha;
 }
예제 #5
0
 /**
  * Returns array of skin entities
  *
  * @param   array   $aFilter    - array('type' => 'site'|'admin')
  * @return  ModuleSkin_EntitySkin[]
  */
 public function GetSkinsList($aFilter = array())
 {
     if (is_null($this->aSkins)) {
         $aSkinList = array();
         if (isset($aFilter['dir'])) {
             $sSkinsDir = $aFilter['dir'];
         } else {
             $sSkinsDir = Config::Get('path.skins.dir');
         }
         if (isset($aFilter['name'])) {
             $sPattern = $sSkinsDir . $aFilter['name'];
         } else {
             $sPattern = $sSkinsDir . '*';
         }
         $aList = glob($sPattern, GLOB_ONLYDIR);
         if ($aList) {
             if (!isset($aFilter['type'])) {
                 $aFilter['type'] = '';
             }
             $sActiveSkin = Config::Get('view.skin');
             foreach ($aList as $sSkinDir) {
                 $sSkin = basename($sSkinDir);
                 $aData = array('id' => $sSkin, 'dir' => $sSkinDir);
                 $oSkinEntity = E::GetEntity('Skin', $aData);
                 $oSkinEntity->SetIsActive($oSkinEntity->GetId() == $sActiveSkin);
                 $aSkinList[$oSkinEntity->GetId()] = $oSkinEntity;
             }
         }
         $this->aSkins = $aSkinList;
     }
     if (!$aFilter || empty($aFilter['type'])) {
         $aResult = $this->aSkins;
     } else {
         $aResult = array();
         foreach ($this->aSkins as $sSkinName => $oSkinEntity) {
             if ($aFilter['type'] == $oSkinEntity->GetType()) {
                 $aResult[$sSkinName] = $oSkinEntity;
             }
         }
     }
     return $aResult;
 }
 protected function SubmitAddField($oContentType)
 {
     // * Проверяем отправлена ли форма с данными
     if (!F::isPost('submit_field')) {
         return false;
     }
     // * Проверка корректности полей формы
     if (!$this->CheckFieldsField($oContentType)) {
         return false;
     }
     $oField = E::GetEntity('Topic_Field');
     $oField->setFieldType(F::GetRequest('field_type'));
     $oField->setContentId($oContentType->getContentId());
     $oField->setFieldName(F::GetRequest('field_name'));
     $oField->setFieldDescription(F::GetRequest('field_description'));
     $oField->setFieldRequired(F::GetRequest('field_required'));
     if (F::GetRequest('field_type') == 'select') {
         $oField->setOptionValue('select', F::GetRequest('field_values'));
     }
     $sFieldUniqueName = F::TranslitUrl(F::GetRequest('field_unique_name'));
     if (F::GetRequest('field_unique_name_translit')) {
         $sFieldUniqueName = F::TranslitUrl(F::GetRequest('field_name'));
     }
     $oField->setFieldUniqueName($sFieldUniqueName);
     try {
         if (E::ModuleTopic()->AddContentField($oField)) {
             E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('action.admin.contenttypes_success_fieldadd'), null, true);
             R::Location('admin/settings-contenttypes/edit/' . $oContentType->getContentId() . '/');
         }
     } catch (Exception $e) {
         // Если ошибка дублирования уникального ключа, то выводим соответствующее сообщение
         if (1062 == $e->getCode()) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('plugin.contentfieldsx.error_field_unique_name_duplicate', array('unique_name' => htmlspecialchars($sFieldUniqueName))), null, false);
         }
     }
     return false;
 }
예제 #7
0
 /**
  * Возвращает объект смены емайла по коду подтверждения
  *
  * @param string $sCode Код подтверждения
  *
  * @return ModuleUser_EntityChangemail|null
  */
 public function GetUserChangemailByCodeTo($sCode)
 {
     $sql = "\n            SELECT *\n            FROM ?_user_changemail\n            WHERE code_to = ?\n            LIMIT 1\n            ";
     if ($aRow = $this->oDb->selectRow($sql, $sCode)) {
         return E::GetEntity('ModuleUser_EntityChangemail', $aRow);
     }
     return null;
 }
예제 #8
0
 /**
  * Запись события в ленту
  *
  * @param int    $iUserId       ID пользователя
  * @param string $sEventType    Тип события
  * @param int    $iTargetId     ID владельца
  * @param int    $iPublish      Статус
  *
  * @return bool
  */
 public function Write($iUserId, $sEventType, $iTargetId, $iPublish = 1)
 {
     $iPublish = (int) $iPublish;
     if (!$this->IsAllowEventType($sEventType)) {
         return false;
     }
     $aParams = $this->aEventTypes[$sEventType];
     if (isset($aParams['unique']) and $aParams['unique']) {
         // * Проверяем на уникальность
         /** @var ModuleStream_EntityEvent $oEvent */
         if ($oEvent = $this->GetEventByTarget($sEventType, $iTargetId)) {
             // * Событие уже было
             if ($oEvent->getPublish() != $iPublish) {
                 $oEvent->setPublish($iPublish);
                 $this->UpdateEvent($oEvent);
             }
             return true;
         }
     }
     if (isset($aParams['unique_user']) and $aParams['unique_user']) {
         // * Проверяем на уникальность для конкретного пользователя
         if ($oEvent = $this->GetEventByTarget($sEventType, $iTargetId, $iUserId)) {
             // * Событие уже было
             if ($oEvent->getPublish() != $iPublish) {
                 $oEvent->setPublish($iPublish);
                 $this->UpdateEvent($oEvent);
             }
             return true;
         }
     }
     if ($iPublish) {
         /**
          * Создаем новое событие
          */
         /** @var ModuleStream_EntityEvent $oEvent */
         $oEvent = E::GetEntity('Stream_Event');
         $oEvent->setEventType($sEventType);
         $oEvent->setUserId($iUserId);
         $oEvent->setTargetId($iTargetId);
         $oEvent->setDateAdded(date('Y-m-d H:i:s'));
         $oEvent->setPublish($iPublish);
         $this->AddEvent($oEvent);
     }
     return true;
 }
예제 #9
0
 public function EventAjaxUserAdd()
 {
     E::ModuleViewer()->SetResponseAjax('json');
     if ($this->IsPost()) {
         Config::Set('module.user.captcha_use_registration', false);
         $oUser = E::GetEntity('ModuleUser_EntityUser');
         $oUser->_setValidateScenario('registration');
         // * Заполняем поля (данные)
         $oUser->setLogin($this->GetPost('user_login'));
         $oUser->setMail($this->GetPost('user_mail'));
         $oUser->setPassword($this->GetPost('user_password'));
         $oUser->setPasswordConfirm($this->GetPost('user_password'));
         $oUser->setDateRegister(F::Now());
         $oUser->setIpRegister('');
         $oUser->setActivate(1);
         if ($oUser->_Validate()) {
             E::ModuleHook()->Run('registration_validate_after', array('oUser' => $oUser));
             $oUser->setPassword($oUser->getPassword(), true);
             if (E::ModuleUser()->Add($oUser)) {
                 E::ModuleHook()->Run('registration_after', array('oUser' => $oUser));
                 // Подписываем пользователя на дефолтные события в ленте активности
                 E::ModuleStream()->SwitchUserEventDefaultTypes($oUser->getId());
                 if ($this->IsPost('user_setadmin')) {
                     E::ModuleAdmin()->SetAdministrator($oUser->GetId());
                 }
             }
             E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('registration_ok'));
         } else {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('error'));
             E::ModuleViewer()->AssignAjax('aErrors', $oUser->_getValidateErrors());
         }
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
     }
 }
예제 #10
0
 /**
  * Creates RSS item for the topic
  *
  * @return ModuleRss_EntityRssItem
  */
 public function CreateRssItem()
 {
     $aRssItemData = array('title' => $this->getTitle(), 'description' => $this->getText(), 'link' => $this->getUrl(), 'author' => $this->getUser() ? $this->getUser()->getMail() : '', 'guid' => $this->getUrlShort(), 'comments' => $this->getUrl() . '#comments', 'pub_date' => $this->getDateShow() ? date('r', strtotime($this->getDateShow())) : '');
     $oRssItem = E::GetEntity('ModuleRss_EntityRssItem', $aRssItemData);
     return $oRssItem;
 }
예제 #11
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;
 }
예제 #12
0
 /**
  * Creates RSS channel for the blog (without items)
  *
  * @return ModuleRss_EntityRssChannel
  */
 public function CreateRssChannel()
 {
     $aRssChannelData = array('title' => C::Get('view.name') . '/' . $this->getTitle(), 'description' => $this->getDescription(), 'link' => $this->getLink(), 'language' => C::Get('lang.current'), 'managing_editor' => $this->getOwner() ? $this->getOwner()->getMail() : '', 'web_master' => C::Get('general.rss_editor_mail'), 'generator' => 'Alto CMS v.' . ALTO_VERSION);
     $oRssChannel = E::GetEntity('ModuleRss_EntityRssChannel', $aRssChannelData);
     return $oRssChannel;
 }
예제 #13
0
 /**
  * Подключение/отключение к блогу
  *
  */
 protected function AjaxBlogJoin()
 {
     //  Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     //  Пользователь авторизован?
     if (!$this->oUserCurrent) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return;
     }
     //  Блог существует?
     $nBlogId = intval(F::GetRequestStr('idBlog', null, 'post'));
     if (!$nBlogId || !($oBlog = E::ModuleBlog()->GetBlogById($nBlogId))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     $this->oCurrentBlog = $oBlog;
     // Type of the blog
     $oBlogType = $oBlog->getBlogType();
     // Current status of user in the blog
     /** @var ModuleBlog_EntityBlogUser $oBlogUser */
     $oBlogUser = E::ModuleBlog()->GetBlogUserByBlogIdAndUserId($oBlog->getId(), $this->oUserCurrent->getId());
     if (!$oBlogUser || $oBlogUser->getUserRole() < ModuleBlog::BLOG_USER_ROLE_GUEST && (!$oBlogType || $oBlogType->IsPrivate())) {
         // * Проверяем тип блога на возможность свободного вступления или вступления по запросу
         if ($oBlogType && !$oBlogType->GetMembership(ModuleBlog::BLOG_USER_JOIN_FREE) && !$oBlogType->GetMembership(ModuleBlog::BLOG_USER_JOIN_REQUEST)) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_join_error_invite'), E::ModuleLang()->Get('error'));
             return;
         }
         if ($oBlog->getOwnerId() != $this->oUserCurrent->getId()) {
             // Subscribe user to the blog
             if ($oBlogType->GetMembership(ModuleBlog::BLOG_USER_JOIN_FREE)) {
                 $bResult = false;
                 if ($oBlogUser) {
                     $oBlogUser->setUserRole(ModuleBlog::BLOG_USER_ROLE_USER);
                     $bResult = E::ModuleBlog()->UpdateRelationBlogUser($oBlogUser);
                 } elseif ($oBlogType->GetMembership(ModuleBlog::BLOG_USER_JOIN_FREE)) {
                     // User can free subscribe to blog
                     /** @var ModuleBlog_EntityBlogUser $oBlogUserNew */
                     $oBlogUserNew = E::GetEntity('Blog_BlogUser');
                     $oBlogUserNew->setBlogId($oBlog->getId());
                     $oBlogUserNew->setUserId($this->oUserCurrent->getId());
                     $oBlogUserNew->setUserRole(ModuleBlog::BLOG_USER_ROLE_USER);
                     $bResult = E::ModuleBlog()->AddRelationBlogUser($oBlogUserNew);
                 }
                 if ($bResult) {
                     E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('blog_join_ok'), E::ModuleLang()->Get('attention'));
                     E::ModuleViewer()->AssignAjax('bState', true);
                     //  Увеличиваем число читателей блога
                     $oBlog->setCountUser($oBlog->getCountUser() + 1);
                     E::ModuleBlog()->UpdateBlog($oBlog);
                     E::ModuleViewer()->AssignAjax('iCountUser', $oBlog->getCountUser());
                     //  Добавляем событие в ленту
                     E::ModuleStream()->Write($this->oUserCurrent->getId(), 'join_blog', $oBlog->getId());
                     //  Добавляем подписку на этот блог в ленту пользователя
                     E::ModuleUserfeed()->SubscribeUser($this->oUserCurrent->getId(), ModuleUserfeed::SUBSCRIBE_TYPE_BLOG, $oBlog->getId());
                 } else {
                     $sMsg = $oBlogType->IsPrivate() ? E::ModuleLang()->Get('blog_join_error_invite') : E::ModuleLang()->Get('system_error');
                     E::ModuleMessage()->AddErrorSingle($sMsg, E::ModuleLang()->Get('error'));
                     return;
                 }
             }
             // Подписываем по запросу
             if ($oBlogType->GetMembership(ModuleBlog::BLOG_USER_JOIN_REQUEST)) {
                 // Подписка уже была запрошена, но результатов пока нет
                 if ($oBlogUser && $oBlogUser->getUserRole() == ModuleBlog::BLOG_USER_ROLE_WISHES) {
                     E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('blog_join_request_already'), E::ModuleLang()->Get('attention'));
                     E::ModuleViewer()->AssignAjax('bState', true);
                     return;
                 }
                 if ($oBlogUser) {
                     if (!in_array($oBlogUser->getUserRole(), array(ModuleBlog::BLOG_USER_ROLE_REJECT, ModuleBlog::BLOG_USER_ROLE_WISHES))) {
                         $sMessage = E::ModuleLang()->Get('blog_user_status_is') . ' "' . E::ModuleBlog()->GetBlogUserRoleName($oBlogUser->getUserRole()) . '"';
                         E::ModuleMessage()->AddNoticeSingle($sMessage, E::ModuleLang()->Get('attention'));
                         E::ModuleViewer()->AssignAjax('bState', true);
                         return;
                     } else {
                         $oBlogUser->setUserRole(ModuleBlog::BLOG_USER_ROLE_WISHES);
                         $bResult = E::ModuleBlog()->UpdateRelationBlogUser($oBlogUser);
                     }
                 } else {
                     // Подписки ещё не было - оформим ее
                     /** @var ModuleBlog_EntityBlogUser $oBlogUserNew */
                     $oBlogUserNew = E::GetEntity('Blog_BlogUser');
                     $oBlogUserNew->setBlogId($oBlog->getId());
                     $oBlogUserNew->setUserId($this->oUserCurrent->getId());
                     $oBlogUserNew->setUserRole(ModuleBlog::BLOG_USER_ROLE_WISHES);
                     $bResult = E::ModuleBlog()->AddRelationBlogUser($oBlogUserNew);
                 }
                 if ($bResult) {
                     // Отправим сообщение модераторам и администраторам блога о том, что
                     // этот пользоватлеь захотел присоединиться к нашему блогу
                     $aBlogUsersResult = E::ModuleBlog()->GetBlogUsersByBlogId($oBlog->getId(), array(ModuleBlog::BLOG_USER_ROLE_MODERATOR, ModuleBlog::BLOG_USER_ROLE_ADMINISTRATOR), null);
                     if ($aBlogUsersResult) {
                         /** @var ModuleUser_EntityUser[] $aBlogModerators */
                         $aBlogModerators = array();
                         /** @var ModuleBlog_EntityBlogUser $oCurrentBlogUser */
                         foreach ($aBlogUsersResult['collection'] as $oCurrentBlogUser) {
                             $aBlogModerators[] = $oCurrentBlogUser->getUser();
                         }
                         // Добавим владельца блога к списку
                         $aBlogModerators = array_merge($aBlogModerators, array($oBlog->getOwner()));
                         $this->SendBlogRequest($oBlog, $aBlogModerators, $this->oUserCurrent);
                     }
                     E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('blog_join_request_send'), E::ModuleLang()->Get('attention'));
                     E::ModuleViewer()->AssignAjax('bState', true);
                     return;
                 }
             }
         } else {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_join_error_self'), E::ModuleLang()->Get('attention'));
             return;
         }
     }
     if ($oBlogUser && $oBlogUser->getUserRole() == ModuleBlog::BLOG_USER_ROLE_MEMBER) {
         // Unsubscribe user from the blog
         if (E::ModuleBlog()->DeleteRelationBlogUser($oBlogUser)) {
             E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('blog_leave_ok'), E::ModuleLang()->Get('attention'));
             E::ModuleViewer()->AssignAjax('bState', false);
             //  Уменьшаем число читателей блога
             $oBlog->setCountUser($oBlog->getCountUser() - 1);
             E::ModuleBlog()->UpdateBlog($oBlog);
             E::ModuleViewer()->AssignAjax('iCountUser', $oBlog->getCountUser());
             //  Удаляем подписку на этот блог в ленте пользователя
             E::ModuleUserfeed()->UnsubscribeUser($this->oUserCurrent->getId(), ModuleUserfeed::SUBSCRIBE_TYPE_BLOG, $oBlog->getId());
             return;
         } else {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
             return;
         }
     }
     if ($oBlogUser && $oBlogUser->getUserRole() == ModuleBlog::BLOG_USER_ROLE_NOTMEMBER) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_user_request_no_accept'), E::ModuleLang()->Get('error'));
         return;
     }
     if ($oBlogUser && $oBlogUser->getUserRole() == ModuleBlog::BLOG_USER_ROLE_BAN) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_leave_error_banned'), E::ModuleLang()->Get('error'));
         return;
     }
     if ($oBlogUser && $oBlogUser->getUserRole() == ModuleBlog::BLOG_USER_ROLE_BAN_FOR_COMMENT) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_leave_error_banned'), E::ModuleLang()->Get('error'));
         return;
     }
     if ($oBlogUser && $oBlogUser->getUserRole() == ModuleBlog::BLOG_USER_ROLE_WISHES) {
         E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('blog_join_request_leave'), E::ModuleLang()->Get('attention'));
         E::ModuleViewer()->AssignAjax('bState', true);
         return;
     }
 }
예제 #14
0
 /**
  * Предпросмотр топика
  *
  */
 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;
 }
예제 #15
0
 /**
  * Универсальный метод отправки уведомлений на email
  *
  * @param ModuleUser_EntityUser|string $xUserTo     Кому отправляем (пользователь или email)
  * @param string                       $sTemplate   Шаблон для отправки
  * @param string                       $sSubject    Тема письма
  * @param array                        $aAssign     Ассоциативный массив для загрузки переменных в шаблон письма
  * @param string|null                  $sPluginName Плагин из которого происходит отправка
  * @param bool                         $bForceSend  Отправлять сразу, даже при опции module.notify.delayed = true
  *
  * @return bool
  */
 public function Send($xUserTo, $sTemplate, $sSubject, $aAssign = array(), $sPluginName = null, $bForceSend = false)
 {
     if ($xUserTo instanceof ModuleUser_EntityUser) {
         $sMail = $xUserTo->getMail();
         $sName = $xUserTo->getLogin();
     } else {
         $sMail = $xUserTo;
         $sName = '';
     }
     /**
      * Передаём в шаблон переменные
      */
     foreach ($aAssign as $sVarName => $sValue) {
         $this->oViewerLocal->Assign($sVarName, $sValue);
     }
     /**
      * Формируем шаблон
      */
     $sTemplate = $this->sPrefix . $sTemplate;
     $sBody = $this->oViewerLocal->Fetch($this->GetTemplatePath($sTemplate, $sPluginName));
     /**
      * Если в конфигураторе указан отложенный метод отправки,
      * то добавляем задание в массив. В противном случае,
      * сразу отсылаем на email
      */
     if (Config::Get('module.notify.delayed') && !$bForceSend) {
         $oNotifyTask = E::GetEntity('Notify_Task', array('user_mail' => $sMail, 'user_login' => $sName, 'notify_text' => $sBody, 'notify_subject' => $sSubject, 'date_created' => F::Now(), 'notify_task_status' => self::NOTIFY_TASK_STATUS_NULL));
         if (Config::Get('module.notify.insert_single')) {
             $this->aTask[] = $oNotifyTask;
             $bResult = true;
         } else {
             $bResult = $this->oMapper->AddTask($oNotifyTask);
         }
     } else {
         // * Отправляем e-mail
         E::ModuleMail()->SetAdress($sMail, $sName);
         E::ModuleMail()->SetSubject($sSubject);
         E::ModuleMail()->SetBody($sBody);
         E::ModuleMail()->SetHTML();
         $bResult = E::ModuleMail()->Send();
     }
     return $bResult;
 }
예제 #16
0
 /**
  * Получает тип контента по id
  *
  * @param  int $nId
  *
  * @return ModuleTopic_EntityField|null
  */
 public function getContentFieldById($nId)
 {
     $sql = "SELECT\n\t\t\t\t\t\t*\n\t\t\t\t\tFROM\n\t\t\t\t\t\t?_content_field\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tfield_id = ?d\n\t\t\t\t\t";
     if ($aRow = $this->oDb->selectRow($sql, $nId)) {
         return E::GetEntity('Topic_Field', $aRow);
     }
     return null;
 }
예제 #17
0
 /**
  * Stores uploaded file
  *
  * @param string $sFile
  * @param string $sDestination
  * @param bool $bAddMresource
  *
  * @return bool|ModuleUploader_EntityItem
  */
 public function Store($sFile, $sDestination = null, $bAddMresource = TRUE)
 {
     if (!$sDestination) {
         $sDriverName = $this->sDefaultDriver;
     } else {
         $sDriverName = $this->DefineDriver($sDestination);
     }
     if ($sDriverName) {
         /**
          * TODO: Создать интерфейс или абстрактный класс, от которого будут унаследованы все «драйверы»
          * @var $oDriver ModuleUploader_EntityDriverFile
          */
         $oDriver = $this->GetDriver($sDriverName);
         $oStoredItem = $oDriver->Store($sFile, $sDestination);
         if ($oStoredItem) {
             if (!$oStoredItem->GetUuid()) {
                 $oStoredItem->SetUuid($sDriverName);
             }
             /** @var ModuleMresource_EntityMresource $oMresource */
             $oMresource = E::GetEntity('Mresource', $oStoredItem);
             if ($bAddMresource) {
                 E::ModuleMresource()->Add($oMresource);
             }
             return $oStoredItem;
         }
     }
     return false;
 }
예제 #18
0
 /**
  * Обработка Ajax регистрации
  */
 protected function EventAjaxRegistration()
 {
     // * Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     E::ModuleSecurity()->ValidateSendForm();
     // * Создаем объект пользователя и устанавливаем сценарий валидации
     /** @var ModuleUser_EntityUser $oUser */
     $oUser = E::GetEntity('ModuleUser_EntityUser');
     $oUser->_setValidateScenario('registration');
     // * Заполняем поля (данные)
     $oUser->setLogin($this->GetPost('login'));
     $oUser->setMail($this->GetPost('mail'));
     $oUser->setPassword($this->GetPost('password'));
     $oUser->setPasswordConfirm($this->GetPost('password_confirm'));
     $oUser->setCaptcha($this->GetPost('captcha'));
     $oUser->setDateRegister(F::Now());
     $oUser->setIpRegister(F::GetUserIp());
     // * Если используется активация, то генерим код активации
     if (Config::Get('general.reg.activation')) {
         $oUser->setActivate(0);
         $oUser->setActivationKey(F::RandomStr());
     } else {
         $oUser->setActivate(1);
         $oUser->setActivationKey(null);
     }
     E::ModuleHook()->Run('registration_validate_before', array('oUser' => $oUser));
     // * Запускаем валидацию
     if ($oUser->_Validate()) {
         // Сбросим капчу // issue#342.
         E::ModuleSession()->Drop(E::ModuleCaptcha()->GetKeyName());
         E::ModuleHook()->Run('registration_validate_after', array('oUser' => $oUser));
         $oUser->setPassword($oUser->getPassword(), true);
         if ($this->_addUser($oUser)) {
             E::ModuleHook()->Run('registration_after', array('oUser' => $oUser));
             // * Подписываем пользователя на дефолтные события в ленте активности
             E::ModuleStream()->SwitchUserEventDefaultTypes($oUser->getId());
             // * Если юзер зарегистрировался по приглашению то обновляем инвайт
             if (Config::Get('general.reg.invite') && ($oInvite = E::ModuleUser()->GetInviteByCode($this->GetInviteRegister()))) {
                 $oInvite->setUserToId($oUser->getId());
                 $oInvite->setDateUsed(F::Now());
                 $oInvite->setUsed(1);
                 E::ModuleUser()->UpdateInvite($oInvite);
             }
             // * Если стоит регистрация с активацией то проводим её
             if (Config::Get('general.reg.activation')) {
                 // * Отправляем на мыло письмо о подтверждении регистрации
                 E::ModuleNotify()->SendRegistrationActivate($oUser, F::GetRequestStr('password'));
                 E::ModuleViewer()->AssignAjax('sUrlRedirect', R::GetPath('registration') . 'confirm/');
             } else {
                 E::ModuleNotify()->SendRegistration($oUser, F::GetRequestStr('password'));
                 $oUser = E::ModuleUser()->GetUserById($oUser->getId());
                 // * Сразу авторизуем
                 E::ModuleUser()->Authorization($oUser, false);
                 $this->DropInviteRegister();
                 // * Определяем URL для редиректа после авторизации
                 $sUrl = Config::Get('module.user.redirect_after_registration');
                 if (F::GetRequestStr('return-path')) {
                     $sUrl = F::GetRequestStr('return-path');
                 }
                 E::ModuleViewer()->AssignAjax('sUrlRedirect', $sUrl ? $sUrl : Config::Get('path.root.url'));
                 E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('registration_ok'));
             }
         } else {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
             return;
         }
     } else {
         // * Получаем ошибки
         E::ModuleViewer()->AssignAjax('aErrors', $oUser->_getValidateErrors());
     }
 }
예제 #19
0
 /**
  * @param string $sType
  *
  * @return ModuleViewerAsset_EntityPackage
  */
 protected function _getAssetPackage($sType)
 {
     $oResult = null;
     if (!isset($this->aAssets[$sType])) {
         if (in_array($sType, $this->aAssetTypes)) {
             $aParams = array('asset_type' => $sType);
             $this->aAssets[$sType] = E::GetEntity('ViewerAsset_Package' . ucfirst($sType), $aParams);
             $oResult = $this->aAssets[$sType];
         } else {
             if (!isset($this->aAssets['*'])) {
                 $this->aAssets['*'] = E::GetEntity('ViewerAsset_Package');
             }
             $oResult = $this->aAssets['*'];
         }
     } else {
         $oResult = $this->aAssets[$sType];
     }
     return $oResult;
 }
예제 #20
0
 /**
  * Создает элемент меню по конфигурационным параметрам
  * <pre>
  * 'index' => array(
  *      'text'      => '{{topic_title}}', // Текст из языкового файла
  *      'link'      => '___path.root.url___', // динамическая подстановка из конфига
  *      'active'    => 'blog.hello',
  *      'options' => array( // любые опции
  *                      'type' => 'special',
  *                      'icon_class' => 'fa fa-file-text-o',
  *                  ),
  *      'submenu' => array(
  *          // массив подменю
  *      ),
  *      'on'        => array('index', 'blog'), // где показывать
  *      'off'       => array('admin/*', 'settings/*', 'profile/*', 'talk/*', 'people/*'), // где НЕ показывать
  *      'display'   => true,  // true - выводить, false - не выводить
  *  ),
  * </pre>
  * @param $sItemId
  * @param $aItemConfig
  *
  * @return ModuleMenu_EntityItem
  */
 public function CreateMenuItem($sItemId, $aItemConfig)
 {
     if (is_string($aItemConfig)) {
         return $aItemConfig;
     }
     return E::GetEntity('Menu_Item', array_merge(array('item_id' => $sItemId, 'item_config' => $aItemConfig), isset($aItemConfig['title']) ? array('item_title' => $aItemConfig['title']) : array(), isset($aItemConfig['text']) ? array('item_text' => $aItemConfig['text']) : array(), isset($aItemConfig['link']) ? array('item_url' => $aItemConfig['link']) : array(), isset($aItemConfig['active']) ? array('item_active' => $aItemConfig['active']) : array(), isset($aItemConfig['description']) ? array('item_description' => $aItemConfig['description']) : array(), isset($aItemConfig['type']) ? array('item_active' => $aItemConfig['type']) : array(), isset($aItemConfig['submenu']) ? array('item_submenu' => $aItemConfig['submenu']) : array(), isset($aItemConfig['on']) ? array('item_on' => $aItemConfig['on']) : array(), isset($aItemConfig['off']) ? array('item_off' => $aItemConfig['off']) : array(), isset($aItemConfig['display']) ? array('item_display' => $aItemConfig['display']) : array(), isset($aItemConfig['show']) ? array('item_show' => $aItemConfig['show']) : array(), isset($aItemConfig['options']) ? array('item_options' => E::GetEntity('Menu_ItemOptions', $aItemConfig['options'])) : array()));
 }
예제 #21
0
 /**
  * Получает список информации обо всех плагинах, загруженных в plugin-директорию
  *
  * @param   array   $aFilter
  * @param   bool    $bAsArray
  *
  * @return  array
  */
 public function GetList($aFilter = array(), $bAsArray = true)
 {
     if (is_null($this->aPluginsList)) {
         // Если списка плагинов нет, то создаем его
         $aAllPlugins = F::GetPluginsList(true, false);
         $aActivePlugins = $this->GetActivePlugins();
         if ($aAllPlugins) {
             $iCnt = 0;
             foreach ($aAllPlugins as $sPluginId => $aPluginInfo) {
                 if ($bActive = isset($aActivePlugins[$sPluginId])) {
                     $nNum = ++$iCnt;
                 } else {
                     $nNum = -1;
                 }
                 // Создаем сущность плагина по его манифесту
                 /** @var ModulePlugin_EntityPlugin $oPluginEntity */
                 $oPluginEntity = E::GetEntity('Plugin', $aPluginInfo);
                 if ($oPluginEntity->GetId()) {
                     // Если сущность плагина создана, то...
                     $oPluginEntity->SetNum($nNum);
                     $oPluginEntity->SetIsActive($bActive);
                     $this->aPluginsList[$sPluginId] = $oPluginEntity;
                 }
             }
         } else {
             $this->aPluginsList = array();
         }
     }
     // Формируем список на выдачу
     $aPlugins = array();
     if (isset($aFilter['active']) || $bAsArray) {
         foreach ($this->aPluginsList as $sPluginId => $oPluginEntity) {
             if (!isset($aFilter['active']) || $aFilter['active'] && $oPluginEntity->GetIsActive() || !$aFilter['active'] && !$oPluginEntity->GetIsActive()) {
                 if ($bAsArray) {
                     $aPlugins[$sPluginId] = $oPluginEntity->getAllProps();
                 } else {
                     $aPlugins[$sPluginId] = $oPluginEntity;
                 }
             }
         }
     } else {
         $aPlugins = $this->aPluginsList;
     }
     // Если нужно, то сортируем плагины
     if ($aPlugins && isset($aFilter['order'])) {
         if ($aFilter['order'] == 'name') {
             uasort($aPlugins, array($this, '_PluginCompareByName'));
         } elseif ($aFilter['order'] == 'priority') {
             uasort($aPlugins, array($this, '_PluginCompareByPriority'));
         }
     }
     return $aPlugins;
 }
예제 #22
0
 /**
  * Создаёт персональный блог
  *
  * @param ModuleUser_EntityUser $oUser    Пользователь
  *
  * @return ModuleBlog_EntityBlog|bool
  */
 public function CreatePersonalBlog(ModuleUser_EntityUser $oUser)
 {
     $oBlogType = $this->GetBlogTypeByCode('personal');
     // Создаем персональный блог, только если это разрешено
     if ($oBlogType && $oBlogType->IsActive()) {
         $oBlog = E::GetEntity('Blog');
         $oBlog->setOwnerId($oUser->getId());
         $oBlog->setOwner($oUser);
         $oBlog->setTitle(E::ModuleLang()->Get('blogs_personal_title') . ' ' . $oUser->getLogin());
         $oBlog->setType('personal');
         $oBlog->setDescription(E::ModuleLang()->Get('blogs_personal_description'));
         $oBlog->setDateAdd(F::Now());
         $oBlog->setLimitRatingTopic(-1000);
         $oBlog->setUrl(null);
         $oBlog->setAvatar(null);
         return $this->AddBlog($oBlog);
     }
 }
예제 #23
0
 /**
  * Формирование процесса смены емайла в профиле пользователя
  *
  * @param ModuleUser_EntityUser $oUser       Объект пользователя
  * @param string                $sMailNew    Новый емайл
  *
  * @return bool|ModuleUser_EntityChangemail
  */
 public function MakeUserChangemail($oUser, $sMailNew)
 {
     /** @var ModuleUser_EntityChangemail $oChangemail */
     $oChangemail = E::GetEntity('ModuleUser_EntityChangemail');
     $oChangemail->setUserId($oUser->getId());
     $oChangemail->setDateAdd(date('Y-m-d H:i:s'));
     $oChangemail->setDateExpired(date('Y-m-d H:i:s', time() + 3 * 24 * 60 * 60));
     // 3 дня для смены емайла
     $oChangemail->setMailFrom($oUser->getMail() ? $oUser->getMail() : '');
     $oChangemail->setMailTo($sMailNew);
     $oChangemail->setCodeFrom(F::RandomStr(32));
     $oChangemail->setCodeTo(F::RandomStr(32));
     if ($this->AddUserChangemail($oChangemail)) {
         // * Если у пользователя раньше не было емайла, то сразу шлем подтверждение на новый емайл
         if (!$oChangemail->getMailFrom()) {
             $oChangemail->setConfirmFrom(1);
             E::ModuleUser()->UpdateUserChangemail($oChangemail);
             // * Отправляем уведомление на новый емайл
             E::ModuleNotify()->Send($oChangemail->getMailTo(), 'user_changemail_to.tpl', E::ModuleLang()->Get('notify_subject_user_changemail'), array('oUser' => $oUser, 'oChangemail' => $oChangemail), null, true);
         } else {
             // * Отправляем уведомление на старый емайл
             E::ModuleNotify()->Send($oUser, 'user_changemail_from.tpl', E::ModuleLang()->Get('notify_subject_user_changemail'), array('oUser' => $oUser, 'oChangemail' => $oChangemail), null, true);
         }
         return $oChangemail;
     }
     return false;
 }
예제 #24
0
 /**
  * Удаляет юзера из разговора
  *
  * @param array $aTalkId    Список ID сообщений
  * @param int   $nUserId    ID пользователя
  * @param int   $iActive    Статус связи
  *
  * @return bool
  */
 public function DeleteTalkUserByArray($aTalkId, $nUserId, $iActive = self::TALK_USER_DELETE_BY_SELF)
 {
     if (!is_array($aTalkId)) {
         $aTalkId = array($aTalkId);
     }
     // Удаляем для каждого отметку избранного
     foreach ($aTalkId as $nTalkId) {
         $this->DeleteFavouriteTalk(E::GetEntity('Favourite', array('target_id' => intval($nTalkId), 'target_type' => 'talk', 'user_id' => $nUserId)));
     }
     $xResult = $this->oMapper->DeleteTalkUserByArray($aTalkId, $nUserId, $iActive);
     // Нужно почистить зависимые кеши
     foreach ($aTalkId as $nTalkId) {
         E::ModuleCache()->Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array("update_talk_user_{$nTalkId}"));
     }
     E::ModuleCache()->Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array("update_talk_user"));
     // Удаляем пустые беседы, если в них нет пользователей
     foreach ($aTalkId as $nTalkId) {
         $nTalkId = (string) $nTalkId;
         if (!count($this->GetUsersTalk($nTalkId, array(self::TALK_USER_ACTIVE)))) {
             $this->DeleteTalk($nTalkId);
         }
     }
     return $xResult;
 }
예제 #25
0
 protected function _eventRecoveryRequest($sMail)
 {
     if ($oUser = E::ModuleUser()->GetUserByMail($sMail)) {
         // Формируем и отправляем ссылку на смену пароля
         /** @var ModuleUser_EntityReminder $oReminder */
         $oReminder = E::GetEntity('User_Reminder');
         $oReminder->setCode(F::RandomStr(32));
         $oReminder->setDateAdd(F::Now());
         $oReminder->setDateExpire(date('Y-m-d H:i:s', time() + Config::Val('module.user.pass_recovery_delay', 60 * 60 * 24 * 7)));
         $oReminder->setDateUsed(null);
         $oReminder->setIsUsed(0);
         $oReminder->setUserId($oUser->getId());
         if (E::ModuleUser()->AddReminder($oReminder)) {
             E::ModuleNotify()->SendReminderCode($oUser, $oReminder);
             E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('password_reminder_send_link'));
             return true;
         }
     }
     return false;
 }
예제 #26
0
 /**
  * Возвращает категории изображения для пользователя
  * @param int $iUserId
  * @return array
  */
 public function GetAllImageCategoriesByUserId($iUserId)
 {
     $aRows = $this->oMapper->GetAllImageCategoriesByUserId($iUserId);
     $aResult = array();
     if ($aRows) {
         foreach ($aRows as $aRow) {
             $aResult[] = E::GetEntity('Mresource_MresourceCategory', array('id' => $aRow['ttype'], 'count' => $aRow['count'], 'label' => E::ModuleLang()->Get('aim_target_type_' . $aRow['ttype'])));
         }
     }
     return $aResult;
 }
예제 #27
0
 /**
  * Создает и возвращает объект валидатора
  *
  * @param string     $sName      Имя валидатора или метода при использовании параметра $oObject
  * @param LsObject   $oObject    Объект в котором необходимо вызвать метод валидации
  * @param null|array $aFields    Список полей сущности для которых необходимо провести валидацию
  * @param array      $aParams    Параметры
  *
  * @return ModuleValidate_EntityValidator
  */
 public function CreateValidator($sName, $oObject, $aFields = null, $aParams = array())
 {
     if (is_string($aFields)) {
         $aFields = preg_split('/[\\s,]+/', $aFields, -1, PREG_SPLIT_NO_EMPTY);
     }
     // * Определяем список сценариев валидации
     if (isset($aParams['on'])) {
         if (is_array($aParams['on'])) {
             $aOn = $aParams['on'];
         } else {
             $aOn = preg_split('/[\\s,]+/', $aParams['on'], -1, PREG_SPLIT_NO_EMPTY);
         }
     } else {
         $aOn = array();
     }
     // * Если в качестве имени валидатора указан метод объекта, то создаем специальный валидатор
     $sMethod = 'validate' . F::StrCamelize($sName);
     if (method_exists($oObject, $sMethod)) {
         /** @var ModuleValidate_EntityValidator $oValidator */
         $oValidator = E::GetEntity('ModuleValidate_EntityValidatorInline');
         if (!is_null($aFields)) {
             $oValidator->fields = $aFields;
         }
         $oValidator->object = $oObject;
         $oValidator->method = $sMethod;
         $oValidator->params = $aParams;
         if (isset($aParams['skipOnError'])) {
             $oValidator->skipOnError = $aParams['skipOnError'];
         }
     } else {
         // * Иначе создаем валидатор по имени
         if (!is_null($aFields)) {
             $aParams['fields'] = $aFields;
         }
         $sValidateName = 'Validator' . F::StrCamelize($sName);
         /** @var ModuleValidate_EntityValidator $oValidator */
         $oValidator = E::GetEntity('ModuleValidate_Entity' . $sValidateName);
         foreach ($aParams as $sNameParam => $sValue) {
             $oValidator->{$sNameParam} = $sValue;
         }
     }
     $oValidator->on = empty($aOn) ? array() : array_combine($aOn, $aOn);
     return $oValidator;
 }
예제 #28
0
 /**
  *
  */
 protected function _displayEmptyRss()
 {
     $oRss = E::GetEntity('Rss');
     $this->_displayRss($oRss);
 }
예제 #29
0
 public function GetPluginEntity()
 {
     if (!$this->oPluginEntity) {
         $sPluginId = F::StrUnderscore($this->GetName());
         $this->oPluginEntity = E::GetEntity('Plugin', $sPluginId);
     }
     return $this->oPluginEntity;
 }
예제 #30
0
 /**
  * Добавление нового участника разговора (ajax)
  *
  */
 public function AjaxAddTalkUser()
 {
     // * Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     $sUsers = F::GetRequestStr('users', null, 'post');
     $idTalk = F::GetRequestStr('idTalk', null, 'post');
     // * Если пользователь не авторизирован, возвращаем ошибку
     if (!E::ModuleUser()->IsAuthorization()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Если разговор не найден, или пользователь не является его автором (или админом), возвращаем ошибку
     if (!($oTalk = E::ModuleTalk()->GetTalkById($idTalk)) || $oTalk->getUserId() != $this->oUserCurrent->getId() && !$this->oUserCurrent->isAdministrator()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('talk_not_found'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Получаем список всех участников разговора
     $aTalkUsers = $oTalk->getTalkUsers();
     $aUsers = explode(',', $sUsers);
     // * Получаем список пользователей, которые не принимают письма
     $aUserInBlacklist = E::ModuleTalk()->GetBlacklistByTargetId($this->oUserCurrent->getId());
     // * Ограничения на максимальное число участников разговора
     if (count($aTalkUsers) >= Config::Get('module.talk.max_users') && !$this->oUserCurrent->isAdministrator()) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('talk_create_users_error_many'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Обрабатываем добавление по каждому переданному логину пользователя
     foreach ($aUsers as $sUser) {
         $sUser = trim($sUser);
         if ($sUser == '') {
             continue;
         }
         // * Попытка добавить себя
         if (strtolower($sUser) == strtolower($this->oUserCurrent->getLogin())) {
             $aResult[] = array('bStateError' => true, 'sMsgTitle' => E::ModuleLang()->Get('error'), 'sMsg' => E::ModuleLang()->Get('talk_speaker_add_self'));
             continue;
         }
         if (($oUser = E::ModuleUser()->GetUserByLogin($sUser)) && $oUser->getActivate() == 1) {
             if (!in_array($oUser->getId(), $aUserInBlacklist)) {
                 if (array_key_exists($oUser->getId(), $aTalkUsers)) {
                     switch ($aTalkUsers[$oUser->getId()]->getUserActive()) {
                         // * Если пользователь ранее был удален админом разговора, то добавляем его снова
                         case ModuleTalk::TALK_USER_DELETE_BY_AUTHOR:
                             if (E::ModuleTalk()->AddTalkUser(E::GetEntity('Talk_TalkUser', array('talk_id' => $idTalk, 'user_id' => $oUser->getId(), 'date_last' => null, 'talk_user_active' => ModuleTalk::TALK_USER_ACTIVE)))) {
                                 E::ModuleNotify()->SendTalkNew($oUser, $this->oUserCurrent, $oTalk);
                                 $aResult[] = array('bStateError' => false, 'sMsgTitle' => E::ModuleLang()->Get('attention'), 'sMsg' => E::ModuleLang()->Get('talk_speaker_add_ok', array('login', htmlspecialchars($sUser))), 'sUserId' => $oUser->getId(), 'sUserLogin' => $oUser->getLogin(), 'sUserLink' => $oUser->getUserWebPath(), 'sUserWebPath' => $oUser->getUserWebPath(), 'sUserAvatar48' => $oUser->getAvatarUrl(48));
                                 $bState = true;
                             } else {
                                 $aResult[] = array('bStateError' => true, 'sMsgTitle' => E::ModuleLang()->Get('error'), 'sMsg' => E::ModuleLang()->Get('system_error'));
                             }
                             break;
                             // * Если пользователь является активным участником разговора, возвращаем ошибку
                         // * Если пользователь является активным участником разговора, возвращаем ошибку
                         case ModuleTalk::TALK_USER_ACTIVE:
                             $aResult[] = array('bStateError' => true, 'sMsgTitle' => E::ModuleLang()->Get('error'), 'sMsg' => E::ModuleLang()->Get('talk_speaker_user_already_exist', array('login' => htmlspecialchars($sUser))));
                             break;
                             // * Если пользователь удалил себя из разговора самостоятельно, то блокируем повторное добавление
                         // * Если пользователь удалил себя из разговора самостоятельно, то блокируем повторное добавление
                         case ModuleTalk::TALK_USER_DELETE_BY_SELF:
                             $aResult[] = array('bStateError' => true, 'sMsgTitle' => E::ModuleLang()->Get('error'), 'sMsg' => E::ModuleLang()->Get('talk_speaker_delete_by_self', array('login' => htmlspecialchars($sUser))));
                             break;
                         default:
                             $aResult[] = array('bStateError' => true, 'sMsgTitle' => E::ModuleLang()->Get('error'), 'sMsg' => E::ModuleLang()->Get('system_error'));
                     }
                 } elseif (E::ModuleTalk()->AddTalkUser(E::GetEntity('Talk_TalkUser', array('talk_id' => $idTalk, 'user_id' => $oUser->getId(), 'date_last' => null, 'talk_user_active' => ModuleTalk::TALK_USER_ACTIVE)))) {
                     E::ModuleNotify()->SendTalkNew($oUser, $this->oUserCurrent, $oTalk);
                     $aResult[] = array('bStateError' => false, 'sMsgTitle' => E::ModuleLang()->Get('attention'), 'sMsg' => E::ModuleLang()->Get('talk_speaker_add_ok', array('login', htmlspecialchars($sUser))), 'sUserId' => $oUser->getId(), 'sUserLogin' => $oUser->getLogin(), 'sUserLink' => $oUser->getUserWebPath(), 'sUserWebPath' => $oUser->getUserWebPath(), 'sUserAvatar48' => $oUser->getAvatarUrl(48));
                     $bState = true;
                 } else {
                     $aResult[] = array('bStateError' => true, 'sMsgTitle' => E::ModuleLang()->Get('error'), 'sMsg' => E::ModuleLang()->Get('system_error'));
                 }
             } else {
                 // * Добавляем пользователь не принимает сообщения
                 $aResult[] = array('bStateError' => true, 'sMsgTitle' => E::ModuleLang()->Get('error'), 'sMsg' => E::ModuleLang()->Get('talk_user_in_blacklist', array('login' => htmlspecialchars($sUser))));
             }
         } else {
             // * Пользователь не найден в базе данных или не активен
             $aResult[] = array('bStateError' => true, 'sMsgTitle' => E::ModuleLang()->Get('error'), 'sMsg' => E::ModuleLang()->Get('user_not_found', array('login' => htmlspecialchars($sUser))));
         }
     }
     // * Передаем во вьевер массив результатов обработки по каждому пользователю
     E::ModuleViewer()->AssignAjax('aUsers', $aResult);
 }