Esempio n. 1
0
 public function EventDownloadFile()
 {
     $this->SetTemplate(false);
     $sTopicId = $this->GetParam(0);
     $sFieldId = $this->GetParam(1);
     E::ModuleSecurity()->ValidateSendForm();
     if (!($oTopic = E::ModuleTopic()->GetTopicById($sTopicId))) {
         return parent::EventNotFound();
     }
     if (!($this->oType = E::ModuleTopic()->GetContentType($oTopic->getType()))) {
         return parent::EventNotFound();
     }
     if (!($oField = E::ModuleTopic()->GetContentFieldById($sFieldId))) {
         return parent::EventNotFound();
     }
     if ($oField->getContentId() != $this->oType->getContentId()) {
         return parent::EventNotFound();
     }
     //получаем объект файла
     $oFile = $oTopic->getFieldFile($oField->getFieldId());
     //получаем объект поля топика, содержащий данные о файле
     $oValue = $oTopic->getField($oField->getFieldId());
     if ($oFile && $oValue) {
         if (preg_match("/^(http:\\/\\/)/i", $oFile->getFileUrl())) {
             $sFullPath = $oFile->getFileUrl();
             R::Location($sFullPath);
         } else {
             $sFullPath = Config::Get('path.root.dir') . $oFile->getFileUrl();
         }
         $sFilename = $oFile->getFileName();
         /*
          * Обновляем данные
          */
         $aFileObj = array();
         $aFileObj['file_name'] = $oFile->getFileName();
         $aFileObj['file_url'] = $oFile->getFileUrl();
         $aFileObj['file_size'] = $oFile->getFileSize();
         $aFileObj['file_extension'] = $oFile->getFileExtension();
         $aFileObj['file_downloads'] = $oFile->getFileDownloads() + 1;
         $sText = serialize($aFileObj);
         $oValue->setValue($sText);
         $oValue->setValueSource($sText);
         //сохраняем
         E::ModuleTopic()->UpdateContentFieldValue($oValue);
         /*
          * Отдаем файл
          */
         header('Content-type: ' . $oFile->getFileExtension());
         header('Content-Disposition: attachment; filename="' . $sFilename . '"');
         F::File_PrintChunked($sFullPath);
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('content_download_file_error'));
         return R::Action('error');
     }
 }
Esempio n. 2
0
 /**
  * @return bool
  */
 protected function CheckSeopackFields()
 {
     E::ModuleSecurity()->ValidateSendForm();
     $bOk = true;
     if (F::isPost('title') && !F::CheckVal(F::GetRequest('title', null, 'post'), 'text', 0, 1000)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.seopack.title_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     if (F::isPost('description') && !F::CheckVal(F::GetRequest('description', null, 'post'), 'text', 0, 1000)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.seopack.description_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     if (F::isPost('keywords') && !F::CheckVal(F::GetRequest('keywords', null, 'post'), 'text', 0, 1000)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.seopack.keywords_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     if (!F::CheckVal(F::GetRequest('url', null, 'post'), 'text', 0, 255)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.seopack.url_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     return $bOk;
 }
Esempio n. 3
0
 /**
  * Загружаем картинку
  */
 public function EventMultiUpload()
 {
     // Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json', FALSE);
     E::ModuleSecurity()->ValidateSendForm();
     // Проверяем, загружен ли файл
     if (!($aUploadedFile = $this->GetUploadedFile('uploader-upload-image'))) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('error_upload_image'), E::ModuleLang()->Get('error'));
         return false;
     }
     $sTarget = F::GetRequest('target', FALSE);
     $sTargetId = F::GetRequest('target_id', FALSE);
     $oTarget = E::ModuleUploader()->CheckAccessAndGetTarget($sTarget, $sTargetId);
     $bTmp = F::GetRequest('tmp', FALSE);
     $bTmp = $bTmp == 'true' ? true : false;
     // Проверяем, целевой объект и права на его редактирование
     if (!$oTarget) {
         // Здесь два варианта, либо редактировать нельзя, либо можно, но топика еще нет
         if ($oTarget === TRUE) {
             // Будем делать временную картинку
         } else {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error'));
             return false;
         }
     }
     // Ошибок пока нет
     $sError = '';
     // Сделаем временный файд
     $sTmpFile = E::ModuleUploader()->UploadLocal($aUploadedFile);
     // Вызовем хук перед началом загрузки картинки
     E::ModuleHook()->Run('uploader_upload_before', array('oTarget' => $oTarget, 'sTmpFile' => $sTmpFile, 'sTarget' => $sTarget));
     // Если все ок, и по миме проходит, то
     if ($sTmpFile && E::ModuleImg()->MimeType($sTmpFile)) {
         // Проверим, проходит ли по количеству
         if (!E::ModuleUploader()->GetAllowedCount($sTarget = F::GetRequest('target', FALSE), $sTargetId = F::GetRequest('target_id', FALSE))) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('uploader_photoset_error_count_photos', array('MAX' => Config::Get('module.topic.photoset.count_photos_max'))), E::ModuleLang()->Get('error'));
             return FALSE;
         }
         // Определим, существует ли объект или он будет создан позже
         if (!($sTmpKey = E::ModuleSession()->GetCookie(ModuleUploader::COOKIE_TARGET_TMP)) && $sTargetId == '0' && $bTmp) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('error_upload_image'), E::ModuleLang()->Get('error'));
             return FALSE;
         }
         // Пересохраним файл из кэша
         // Сохраняем фото во временный файл
         $oImg = E::ModuleImg()->Read($sTmpFile);
         $sExtension = strtolower(pathinfo($sTmpFile, PATHINFO_EXTENSION));
         if (!($sTmpFile = $oImg->Save(F::File_UploadUniqname($sExtension)))) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('error_upload_image'), E::ModuleLang()->Get('error'));
             return FALSE;
         }
         // Окончательная запись файла только через модуль Uploader
         if ($oStoredFile = E::ModuleUploader()->StoreImage($sTmpFile, $sTarget, $sTargetId, null, true)) {
             /** @var ModuleMresource_EntityMresource $oResource */
             //$oResource = $this->AddUploadedFileRelationInfo($oStoredFile, $sTarget, $sTargetId, TRUE);
             $oResource = E::ModuleMresource()->GetMresourcesByUuid($oStoredFile->getUuid());
             $sFile = $oStoredFile->GetUrl();
             if ($oResource) {
                 $oResource->setType(ModuleMresource::TYPE_PHOTO);
                 E::ModuleMresource()->UpdateType($oResource);
             }
             $sFilePreview = $sFile;
             if ($sSize = F::GetRequest('crop_size', FALSE)) {
                 $sFilePreview = E::ModuleUploader()->ResizeTargetImage($sFile, $sSize);
             }
             // Запускаем хук на действия после загрузки картинки
             E::ModuleHook()->Run('uploader_upload_image_after', array('sFile' => $sFile, 'sFilePreview' => $sFilePreview, 'sTargetId' => $sTargetId, 'sTarget' => $sTarget, 'oTarget' => $oTarget));
             E::ModuleViewer()->AssignAjax('file', $sFilePreview);
             E::ModuleViewer()->AssignAjax('id', $oResource->getMresourceId());
             // Чистим
             E::ModuleImg()->Delete($sTmpFile);
             return TRUE;
         }
     } else {
         // Ошибки загрузки картинки
         $sError = E::ModuleUploader()->GetErrorMsg();
         if (!$sError) {
             $sError = E::ModuleLang()->Get('error_upload_image');
         }
     }
     // Выведем ошибки пользователю
     E::ModuleMessage()->AddError($sError, E::ModuleLang()->Get('error'));
     // Удалим ранее загруженый файл
     F::File_Delete($sTmpFile);
 }
Esempio n. 4
0
 protected function CheckFieldsField($oContentType = null)
 {
     E::ModuleSecurity()->ValidateSendForm();
     $bOk = true;
     if (!F::CheckVal(F::GetRequest('field_name', null, 'post'), 'text', 2, 100)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('action.admin.contenttypes_field_name_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     if (!F::CheckVal(F::GetRequest('field_description', null, 'post'), 'text', 2, 200)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('action.admin.contenttypes_field_description_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     if (R::GetActionEvent() == 'fieldadd') {
         if ($oContentType == 'photoset' && (F::GetRequest('field_type', null, 'post') == 'photoset' || $oContentType->isPhotosetEnable())) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
             $bOk = false;
         }
         if (!in_array(F::GetRequest('field_type', null, 'post'), E::ModuleTopic()->GetAvailableFieldTypes())) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('action.admin.contenttypes_field_type_error'), E::ModuleLang()->Get('error'));
             $bOk = false;
         }
     }
     // * Выполнение хуков
     E::ModuleHook()->Run('check_admin_content_fields', array('bOk' => &$bOk));
     return $bOk;
 }
Esempio n. 5
0
 /**
  * Проверка полей при создании письма
  *
  * @return bool
  */
 protected function checkTalkFields()
 {
     E::ModuleSecurity()->ValidateSendForm();
     $bOk = true;
     // * Проверяем есть ли заголовок
     if (!F::CheckVal(F::GetRequestStr('talk_title'), 'text', 2, 200)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('talk_create_title_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     // * Проверяем есть ли содержание топика
     $iMin = intval(Config::Get('module.talk.min_length'));
     $iMax = intval(Config::Get('module.talk.max_length'));
     if (!F::CheckVal(F::GetRequestStr('talk_text'), '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'));
         }
         $bOk = false;
     }
     // * Проверяем адресатов
     $sUsers = F::GetRequest('talk_users');
     $aUsers = explode(',', (string) $sUsers);
     $aUsersNew = array();
     $aUserInBlacklist = E::ModuleTalk()->GetBlacklistByTargetId($this->oUserCurrent->getId());
     $this->aUsersId = array();
     foreach ($aUsers as $sUser) {
         $sUser = trim($sUser);
         if ($sUser == '' || strtolower($sUser) == strtolower($this->oUserCurrent->getLogin())) {
             continue;
         }
         if (($oUser = E::ModuleUser()->GetUserByLogin($sUser)) && $oUser->getActivate() == 1) {
             // Проверяем, попал ли отправиль в блек лист
             if (!in_array($oUser->getId(), $aUserInBlacklist)) {
                 $this->aUsersId[] = $oUser->getId();
             } else {
                 E::ModuleMessage()->AddError(str_replace('login', $oUser->getLogin(), E::ModuleLang()->Get('talk_user_in_blacklist', array('login' => htmlspecialchars($oUser->getLogin())))), E::ModuleLang()->Get('error'));
                 $bOk = false;
                 continue;
             }
         } else {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('talk_create_users_error_not_found') . ' «' . htmlspecialchars($sUser) . '»', E::ModuleLang()->Get('error'));
             $bOk = false;
         }
         $aUsersNew[] = $sUser;
     }
     if (!count($aUsersNew)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('talk_create_users_error'), E::ModuleLang()->Get('error'));
         $_REQUEST['talk_users'] = '';
         $bOk = false;
     } else {
         if (count($aUsersNew) > Config::Get('module.talk.max_users') && !$this->oUserCurrent->isAdministrator()) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('talk_create_users_error_many'), E::ModuleLang()->Get('error'));
             $bOk = false;
         }
         $_REQUEST['talk_users'] = join(',', $aUsersNew);
     }
     // * Выполнение хуков
     E::ModuleHook()->Run('check_talk_fields', array('bOk' => &$bOk));
     return $bOk;
 }
Esempio n. 6
0
 /**
  * Returns information about the uploaded file with form validation
  * If a field name is omitted it returns the first of uploaded files
  *
  * @param   string|null $sName
  *
  * @return  array|bool
  */
 protected function GetUploadedFile($sName = null)
 {
     $aFiles = $this->_getRequestData('FILES');
     if (E::ModuleSecurity()->ValidateSendForm(false) && !empty($aFiles)) {
         $aFileData = false;
         if (is_null($sName)) {
             $aFileData = reset($aFiles);
         } elseif (!empty($aFiles) && is_array($aFiles)) {
             foreach ($aFiles as $sKey => $aData) {
                 if (strtolower($sKey) === strtolower($sName)) {
                     $aFileData = $aData;
                     break;
                 }
             }
         }
         if ($aFileData && isset($aFileData['tmp_name']) && is_uploaded_file($aFileData['tmp_name'])) {
             return $aFileData;
         }
     }
     return false;
 }
Esempio n. 7
0
 /**
  * Returns information about the uploaded file with form validation
  * If a field name is omitted it returns the first of uploaded files
  *
  * @param   string|null $sName
  *
  * @return  array|bool
  */
 protected function GetUploadedFile($sName = null)
 {
     $aFiles = $this->_getRequestData('FILES');
     if (E::ModuleSecurity()->ValidateSendForm(false) && !empty($aFiles)) {
         if (is_null($sName)) {
             $aFileData = reset($aFiles);
         } elseif (isset($aFiles[$sName])) {
             $aFileData = $aFiles[$sName];
         } else {
             $aFileData = false;
         }
         if ($aFileData && isset($aFileData['tmp_name']) && is_uploaded_file($aFileData['tmp_name'])) {
             return $aFileData;
         }
     }
     return false;
 }
Esempio n. 8
0
 /**
  * Обрабатываем процесс разлогинивания
  *
  */
 protected function EventExit()
 {
     E::ModuleSecurity()->ValidateSendForm();
     E::ModuleUser()->Logout();
     $iShowTime = Config::Val('module.user.logout.show_exit', 3);
     $sRedirect = Config::Get('module.user.logout.redirect');
     if (!$sRedirect) {
         if (isset($_SERVER['HTTP_REFERER']) && F::File_IsLocalUrl($_SERVER['HTTP_REFERER'])) {
             $sRedirect = $_SERVER['HTTP_REFERER'];
         }
     }
     /**
      * issue #104, {@see https://github.com/altocms/altocms/issues/104}
      * Установим в lgp (last_good_page) хэш имени страницы с постфиксом "logout". Такая
      * кука будет означать, что на этой странице пользователь вышел с сайта. Время 60 -
      * заранее достаточное время, что бы произошел редирект на страницу HTTP_REFERER. Если
      * же эта страница выпадет в 404 то в экшене ActionError уйдем на главную, поскольку
      * эта страница недоступна стала после выхода с сайта, а до этого была вполне ничего.
      */
     if ($iShowTime) {
         $sUrl = F::RealUrl($sRedirect);
         $sReferrer = Config::Get('path.root.web') . R::GetAction() . "/" . R::GetActionEvent() . '/?security_key=' . F::GetRequest('security_key', '');
         E::ModuleSession()->SetCookie('lgp', md5($sReferrer . 'logout'), 60);
         E::ModuleViewer()->SetHtmlHeadTag('meta', array('http-equiv' => 'Refresh', 'Content' => $iShowTime . '; url=' . $sUrl));
     } elseif ($sRedirect) {
         // Если установлена пользовтаельская страница выхода, то считаем,
         // что она без ошибки и смело не нее редиректим, в других случаях
         // возможна 404
         if (!Config::Get('module.user.logout.redirect')) {
             E::ModuleSession()->SetCookie('lgp', md5(F::RealUrl($sRedirect) . 'logout'), 60);
         }
         R::Location($sRedirect);
         exit;
     } else {
         // E::ModuleViewer()->Assign('bRefreshToHome', true);
         // Время показа страницы выхода не задано, поэтому просто редирект
         R::Location(Config::Get('path.root.web'));
         exit;
     }
 }
Esempio n. 9
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. 10
0
 /**
  * Проверка полей формы
  *
  * @param $oTopic
  *
  * @return bool
  */
 protected function checkTopicFields($oTopic)
 {
     E::ModuleSecurity()->ValidateSendForm();
     $bOk = true;
     /**
      * Валидируем топик
      */
     if (!$oTopic->_Validate()) {
         E::ModuleMessage()->AddError($oTopic->_getValidateError(), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     /**
      * Выполнение хуков
      */
     E::ModuleHook()->Run('check_topic_fields', array('bOk' => &$bOk));
     return $bOk;
 }
Esempio n. 11
0
 /**
  * Возврат к предыдущему URL
  * В отличие от GotoBack() анализирует переданные POST-параметры
  *
  * @param   bool $bSecurity  - защита от CSRF
  */
 public static function ReturnBack($bSecurity = null)
 {
     if (!$bSecurity || E::ModuleSecurity()->ValidateSendForm(false)) {
         if (($sUrl = F::GetPost('return_url')) || ($sUrl = F::GetPost('return-path'))) {
             static::Location($sUrl);
         }
     }
     static::GotoBack();
 }
Esempio n. 12
0
 /**
  * Returns hash-key of current session
  */
 public function GetKey()
 {
     return E::ModuleSecurity()->Salted($this->GetId(), 'sess');
 }
Esempio n. 13
0
 /**
  * Sets hash of user agent of saved session
  *
  * @param string|null $data
  */
 public function setUserAgentHash($data = null)
 {
     if (is_null($data)) {
         $data = E::ModuleSecurity()->GetUserAgentHash();
     }
     $this->setProp('session_agent_hash', $data);
 }
Esempio n. 14
0
 /**
  * Устанавливает пароль
  *
  * @param   string $sPassword
  * @param   bool   $bEncrypt   - false, если пароль уже захеширован
  */
 public function setPassword($sPassword, $bEncrypt = false)
 {
     if ($bEncrypt) {
         $this->_aData['user_password'] = E::ModuleSecurity()->Salted($sPassword, 'pass');
     } else {
         $this->setProp('user_password', $sPassword);
     }
 }
Esempio n. 15
0
 /**
  * Удаление блога
  *
  */
 protected function EventDeleteBlog()
 {
     E::ModuleSecurity()->ValidateSendForm();
     // * Проверяем передан ли в УРЛе номер блога
     $nBlogId = intval($this->GetParam(0));
     if (!$nBlogId || !($oBlog = E::ModuleBlog()->GetBlogById($nBlogId))) {
         return parent::EventNotFound();
     }
     $this->oCurrentBlog = $oBlog;
     // * Проверям авторизован ли пользователь
     if (!E::ModuleUser()->IsAuthorization()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error'));
         return R::Action('error');
     }
     // * проверяем есть ли право на удаление блога
     if (!($nAccess = E::ModuleACL()->IsAllowDeleteBlog($oBlog, $this->oUserCurrent))) {
         return parent::EventNotFound();
     }
     $aTopics = E::ModuleTopic()->GetTopicsByBlogId($nBlogId);
     switch ($nAccess) {
         case ModuleACL::CAN_DELETE_BLOG_EMPTY_ONLY:
             if (is_array($aTopics) && count($aTopics)) {
                 E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_admin_delete_not_empty'), E::ModuleLang()->Get('error'), true);
                 R::Location($oBlog->getUrlFull());
             }
             break;
         case ModuleACL::CAN_DELETE_BLOG_WITH_TOPICS:
             /*
              * Если указан идентификатор блога для перемещения,
              * то делаем попытку переместить топики.
              *
              * (-1) - выбран пункт меню "удалить топики".
              */
             $nNewBlogId = intval(F::GetRequestStr('topic_move_to'));
             if ($nNewBlogId > 0 && is_array($aTopics) && count($aTopics)) {
                 if (!($oBlogNew = E::ModuleBlog()->GetBlogById($nNewBlogId))) {
                     E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_admin_delete_move_error'), E::ModuleLang()->Get('error'), true);
                     R::Location($oBlog->getUrlFull());
                 }
                 // * Если выбранный блог является персональным, возвращаем ошибку
                 if ($oBlogNew->getType() == 'personal') {
                     E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('blog_admin_delete_move_personal'), E::ModuleLang()->Get('error'), true);
                     R::Location($oBlog->getUrlFull());
                 }
                 // * Перемещаем топики
                 E::ModuleTopic()->MoveTopics($nBlogId, $nNewBlogId);
             }
             break;
         default:
             return parent::EventNotFound();
     }
     // * Удаляяем блог и перенаправляем пользователя к списку блогов
     E::ModuleHook()->Run('blog_delete_before', array('sBlogId' => $nBlogId));
     if ($this->_deleteBlog($oBlog)) {
         E::ModuleHook()->Run('blog_delete_after', array('sBlogId' => $nBlogId));
         E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('blog_admin_delete_success'), E::ModuleLang()->Get('attention'), true);
         R::Location(R::GetPath('blogs'));
     } else {
         R::Location($oBlog->getUrlFull());
     }
 }
Esempio n. 16
0
 /**
  * @return string
  */
 public function GetCachePrefix()
 {
     $sUniqKey = C::Get(C::ALTO_UNIQUE_KEY);
     if (!$sUniqKey) {
         $sUniqKey = E::ModuleSecurity()->GenerateUniqKey();
     }
     return C::Get('sys.cache.prefix') . '_' . F::Crc32($sUniqKey, true);
 }
Esempio n. 17
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());
     }
 }
Esempio n. 18
0
 /**
  * Compares user's password and passed password
  *
  * @param ModuleUser_EntityUser $oUser
  * @param string $sCheckPassword
  *
  * @return bool
  */
 public function CheckPassword($oUser, $sCheckPassword)
 {
     $sUserPassword = $oUser->getPassword();
     if (E::ModuleSecurity()->CheckSalted($sUserPassword, $sCheckPassword, 'pass') || E::ModuleSecurity()->CheckSalted($sUserPassword, trim($sCheckPassword), 'pass')) {
         return true;
     }
     return false;
 }
Esempio n. 19
0
 /**
  * Загрузка страницы картинок
  */
 protected function EventImageManagerLoadImages()
 {
     E::ModuleSecurity()->ValidateSendForm();
     // Менеджер изображений может запускаться в том числе и из админки
     // Если передано название скина админки, то используем его, если же
     // нет, то ту тему, которая установлена для сайта
     if (($sAdminTheme = F::GetRequest('admin')) && E::IsAdmin()) {
         C::Set('view.skin', $sAdminTheme);
     }
     // Получим идентификатор пользователя, изображения которого нужно загрузить
     $iUserId = (int) F::GetRequest('profile', FALSE);
     if ($iUserId && E::ModuleUser()->GetUserById($iUserId)) {
         C::Set('menu.data.profile_images.uid', $iUserId);
     } else {
         // Только пользователь может смотреть своё дерево изображений
         if (!E::IsUser()) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
             return;
         }
         $iUserId = E::UserId();
     }
     $sCategory = F::GetRequestStr('category', FALSE);
     $iPage = intval(F::GetRequestStr('page', '1'));
     $sTopicId = F::GetRequestStr('topic_id', FALSE);
     $sTargetType = F::GetRequestStr('target');
     if (!$sCategory) {
         return;
     }
     $aTplVariables = array('sTargetType' => $sTargetType, 'sTargetId' => $sTopicId);
     // Страница загрузки картинки с компьютера
     if ($sCategory == 'insert-from-pc') {
         $sImages = E::ModuleViewer()->Fetch('modals/insert_img/inject.pc.tpl', $aTplVariables);
         E::ModuleViewer()->AssignAjax('images', $sImages);
         return;
     }
     // Страница загрузки из интернета
     if ($sCategory == 'insert-from-link') {
         $sImages = E::ModuleViewer()->Fetch('modals/insert_img/inject.link.tpl', $aTplVariables);
         E::ModuleViewer()->AssignAjax('images', $sImages);
         return;
     }
     $sTemplateName = 'inject.images.tpl';
     $aResources = array('collection' => array());
     $iPagesCount = 0;
     if ($sCategory == 'user') {
         //ок
         // * Аватар и фото пользователя
         $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('target_type' => array('profile_avatar', 'profile_photo'), 'user_id' => $iUserId), $iPage, Config::Get('module.topic.images_per_page'));
         $sTemplateName = 'inject.images.user.tpl';
         $iPagesCount = 0;
     } elseif ($sCategory == '_topic') {
         // * Конкретный топик
         $oTopic = E::ModuleTopic()->GetTopicById($sTopicId);
         if ($oTopic && ($oTopic->isPublished() || $oTopic->getUserId() == E::UserId()) && E::ModuleACL()->IsAllowShowBlog($oTopic->getBlog(), E::User())) {
             $aResourcesId = E::ModuleMresource()->GetCurrentTopicResourcesId($iUserId, $sTopicId);
             if ($aResourcesId) {
                 $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'mresource_id' => $aResourcesId), $iPage, Config::Get('module.topic.images_per_page'));
                 $aResources['count'] = count($aResourcesId);
                 $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
                 $aTplVariables['oTopic'] = $oTopic;
             }
         }
         $sTemplateName = 'inject.images.tpl';
     } elseif ($sCategory == 'talk') {
         // * Письмо
         /** @var ModuleTalk_EntityTalk $oTopic */
         $oTopic = E::ModuleTalk()->GetTalkById($sTopicId);
         if ($oTopic && E::ModuleTalk()->GetTalkUser($sTopicId, $iUserId)) {
             $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'target_type' => 'talk', 'target_id' => $sTopicId), $iPage, Config::Get('module.topic.images_per_page'));
             $aResources['count'] = E::ModuleMresource()->GetMresourcesCountByTargetIdAndUserId('talk', $sTopicId, $iUserId);
             $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
             $aTplVariables['oTopic'] = $oTopic;
         }
         $sTemplateName = 'inject.images.tpl';
     } elseif ($sCategory == 'comments') {
         // * Комментарии
         $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'target_type' => array('talk_comment', 'topic_comment')), $iPage, Config::Get('module.topic.images_per_page'));
         $aResources['count'] = E::ModuleMresource()->GetMresourcesCountByTargetAndUserId(array('talk_comment', 'topic_comment'), $iUserId);
         $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
         $sTemplateName = 'inject.images.tpl';
     } elseif ($sCategory == 'current') {
         //ок
         // * Картинки текущего топика (текст, фотосет, одиночные картинки)
         $aResourcesId = E::ModuleMresource()->GetCurrentTopicResourcesId($iUserId, $sTopicId);
         if ($aResourcesId) {
             $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'mresource_id' => $aResourcesId), $iPage, Config::Get('module.topic.images_per_page'));
             $aResources['count'] = count($aResourcesId);
             $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
         }
         $sTemplateName = 'inject.images.tpl';
     } elseif ($sCategory == 'blog_avatar') {
         // ок
         // * Аватары созданных блогов
         $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('target_type' => 'blog_avatar', 'user_id' => $iUserId), $iPage, Config::Get('module.topic.group_images_per_page'));
         $aResources['count'] = E::ModuleMresource()->GetMresourcesCountByTargetAndUserId('blog_avatar', $iUserId);
         // Получим блоги
         $aBlogsId = array();
         foreach ($aResources['collection'] as $oResource) {
             $aBlogsId[] = $oResource->getTargetId();
         }
         if ($aBlogsId) {
             $aBlogs = E::ModuleBlog()->GetBlogsAdditionalData($aBlogsId);
             $aTplVariables['aBlogs'] = $aBlogs;
         }
         $sTemplateName = 'inject.images.blog.tpl';
         $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.group_images_per_page'));
     } elseif ($sCategory == 'topics') {
         // ок
         // * Страница топиков
         $aTopicsData = E::ModuleMresource()->GetTopicsPage($iUserId, $iPage, Config::Get('module.topic.group_images_per_page'));
         $aTplVariables['aTopics'] = $aTopicsData['collection'];
         $sTemplateName = 'inject.images.topic.tpl';
         $iPagesCount = ceil($aTopicsData['count'] / Config::Get('module.topic.group_images_per_page'));
         $aResources = array('collection' => array());
     } elseif (in_array($sCategory, E::ModuleTopic()->GetTopicTypes())) {
         // ок
         // * Страница топиков
         $aTopicsData = E::ModuleMresource()->GetTopicsPageByType($iUserId, $sCategory, $iPage, Config::Get('module.topic.group_images_per_page'));
         $aTplVariables['aTopics'] = $aTopicsData['collection'];
         $sTemplateName = 'inject.images.topic.tpl';
         $iPagesCount = ceil($aTopicsData['count'] / Config::Get('module.topic.group_images_per_page'));
         $aResources = array('collection' => array());
     } elseif ($sCategory == 'talks') {
         // ок
         // * Страница писем
         $aTalksData = E::ModuleMresource()->GetTalksPage($iUserId, $iPage, Config::Get('module.topic.group_images_per_page'));
         $aTplVariables['aTalks'] = $aTalksData['collection'];
         $sTemplateName = 'inject.images.talk.tpl';
         $iPagesCount = ceil($aTalksData['count'] / Config::Get('module.topic.group_images_per_page'));
         $aResources = array('collection' => array());
     } else {
         // * Прочие изображения
         $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('target_type' => $sCategory, 'user_id' => $iUserId), $iPage, Config::Get('module.topic.images_per_page'));
         $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
     }
     $aTplVariables['aResources'] = $aResources['collection'];
     $sPath = F::GetRequest('profile', FALSE) ? 'actions/profile/created_photos/' : 'modals/insert_img/';
     $sImages = E::ModuleViewer()->GetLocalViewer()->Fetch($sPath . $sTemplateName, $aTplVariables);
     E::ModuleViewer()->AssignAjax('images', $sImages);
     E::ModuleViewer()->AssignAjax('category', $sCategory);
     E::ModuleViewer()->AssignAjax('page', $iPage);
     E::ModuleViewer()->AssignAjax('pages', $iPagesCount);
 }
Esempio n. 20
0
 /**
  * Устанавливает тип отдачи при ajax запросе, если null то выполняется обычный вывод шаблона в браузер
  *
  * @param string $sResponseAjax    Тип ответа
  * @param bool $bResponseSpecificHeader    Установливать специфичные тиру заголовки через header()
  * @param bool $bValidate    Производить или нет валидацию формы через {@link Security::ValidateSendForm}
  */
 public function SetResponseAjax($sResponseAjax = 'json', $bResponseSpecificHeader = true, $bValidate = true)
 {
     // Для возможности кросс-доменных запросов
     if ($sResponseAjax != 'jsonp' && $bValidate) {
         E::ModuleSecurity()->ValidateSendForm();
     }
     $this->sResponseAjax = $sResponseAjax;
     $_REQUEST['ALTO_AJAX'] = $sResponseAjax;
     $this->bResponseSpecificHeader = $bResponseSpecificHeader;
 }
Esempio n. 21
0
 /**
  * Returns information about the uploaded file with form validation
  * If a field name is omitted it returns the first of uploaded files
  *
  * @param   string|null $sName
  *
  * @return  array|bool
  */
 protected function GetUploadedFile($sName = null)
 {
     $aFileData = false;
     if (E::ModuleSecurity()->ValidateSendForm(false) && isset($_FILES)) {
         if (is_null($sName) && is_array($_FILES) && sizeof($_FILES)) {
             $aFileData = reset($_FILES);
         } elseif (isset($_FILES[$sName])) {
             $aFileData = $_FILES[$sName];
         }
         if ($aFileData && isset($aFileData['tmp_name']) && is_uploaded_file($aFileData['tmp_name'])) {
             return $aFileData;
         }
     }
     return false;
 }