コード例 #1
0
 /**
  * Получение размеров изображения после ресайза
  *
  * @param string $sParam
  *
  * @return array
  */
 protected function _getImageSize($sParam)
 {
     if ($aSize = F::GetRequest($sParam)) {
         if (isset($aSize['x']) && is_numeric($aSize['x']) && isset($aSize['y']) && is_numeric($aSize['y']) && isset($aSize['x2']) && is_numeric($aSize['x2']) && isset($aSize['y2']) && is_numeric($aSize['y2'])) {
             foreach ($aSize as $sKey => $sVal) {
                 $aSize[$sKey] = intval($sVal);
             }
             if ($aSize['x'] < $aSize['x2']) {
                 $aSize['x1'] = $aSize['x'];
             } else {
                 $aSize['x1'] = $aSize['x2'];
                 $aSize['x2'] = $aSize['x'];
             }
             $aSize['w'] = $aSize['x2'] - $aSize['x1'];
             unset($aSize['x']);
             if ($aSize['y'] < $aSize['y2']) {
                 $aSize['y1'] = $aSize['y'];
             } else {
                 $aSize['y1'] = $aSize['y2'];
                 $aSize['y2'] = $aSize['y'];
             }
             $aSize['h'] = $aSize['y2'] - $aSize['y1'];
             unset($aSize['y']);
             return $aSize;
         }
     }
     return array();
 }
コード例 #2
0
 /**
  * Ajax валидация формы регистрации
  */
 protected function EventAjaxValidateFields()
 {
     // * Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     // * Создаем объект пользователя и устанавливаем сценарий валидации
     /** @var ModuleUser_EntityUser $oUser */
     $oUser = E::GetEntity('ModuleUser_EntityUser');
     $oUser->_setValidateScenario('registration');
     //  Пробегаем по переданным полям/значениям и валидируем их каждое в отдельности
     $aFields = F::GetRequest('fields');
     if (is_array($aFields)) {
         foreach ($aFields as $aField) {
             if (isset($aField['field']) && isset($aField['value'])) {
                 E::ModuleHook()->Run('registration_validate_field', array('aField' => &$aField, 'oUser' => &$oUser));
                 $sField = $aField['field'];
                 $sValue = $aField['value'];
                 //  Список полей для валидации
                 switch ($sField) {
                     case 'login':
                         $oUser->setLogin($sValue);
                         break;
                     case 'mail':
                         $oUser->setMail($sValue);
                         break;
                     case 'captcha':
                         $oUser->setCaptcha($sValue);
                         break;
                     case 'password':
                         $oUser->setPassword($sValue);
                         if (isset($aField['params']['login'])) {
                             $oUser->setLogin($aField['params']['login']);
                         }
                         break;
                     case 'password_confirm':
                         $oUser->setPasswordConfirm($sValue);
                         $oUser->setPassword(isset($aField['params']['password']) ? $aField['params']['password'] : null);
                         break;
                     default:
                         continue;
                         break;
                 }
                 //  Валидируем поле
                 $oUser->_Validate(array($sField), false);
             }
         }
     }
     //  Возникли ошибки?
     if ($oUser->_hasValidateErrors()) {
         //  Получаем ошибки
         E::ModuleViewer()->AssignAjax('aErrors', $oUser->_getValidateErrors());
     }
 }
コード例 #3
0
ファイル: ActionSeopack.class.php プロジェクト: Azany/altocms
 /**
  * @return bool
  */
 protected function CheckSeopackFields()
 {
     E::ModuleSecurity()->ValidateSendForm();
     $bOk = true;
     if (F::isPost('title') && !F::CheckVal(F::GetRequest('title', null, 'post'), 'text', 0, 1000)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.seopack.title_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     if (F::isPost('description') && !F::CheckVal(F::GetRequest('description', null, 'post'), 'text', 0, 1000)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.seopack.description_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     if (F::isPost('keywords') && !F::CheckVal(F::GetRequest('keywords', null, 'post'), 'text', 0, 1000)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.seopack.keywords_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     if (!F::CheckVal(F::GetRequest('url', null, 'post'), 'text', 0, 255)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('plugin.seopack.url_error'), E::ModuleLang()->Get('error'));
         $bOk = false;
     }
     return $bOk;
 }
コード例 #4
0
ファイル: ActionAdmin.class.php プロジェクト: ZeoNish/altocms
 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;
 }
コード例 #5
0
ファイル: ActionTalk.class.php プロジェクト: ZeoNish/altocms
 /**
  * Обработка добавление комментария к письму
  *
  */
 protected function SubmitComment()
 {
     // * Проверям авторизован ли пользователь
     if (!E::ModuleUser()->IsAuthorization()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Проверяем разговор
     if (!($oTalk = E::ModuleTalk()->GetTalkById(F::GetRequestStr('cmt_target_id')))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return false;
     }
     if (!($oTalkUser = E::ModuleTalk()->GetTalkUser($oTalk->getId(), $this->oUserCurrent->getId()))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Проверяем разрешено ли отправлять инбокс по времени
     if (!E::ModuleACL()->CanPostTalkCommentTime($this->oUserCurrent)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('talk_time_limit'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Проверяем текст комментария
     $sText = E::ModuleText()->Parser(F::GetRequestStr('comment_text'));
     $iMin = intval(Config::Get('module.talk.min_length'));
     $iMax = intval(Config::Get('module.talk.max_length'));
     if (!F::CheckVal($sText, 'text', $iMin, $iMax)) {
         if ($iMax) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('talk_create_text_error_len', array('min' => $iMin, 'max' => $iMax)), E::ModuleLang()->Get('error'));
         } else {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('talk_create_text_error_min', array('min' => $iMin)), E::ModuleLang()->Get('error'));
         }
         return false;
     }
     // * Проверям на какой коммент отвечаем
     $sParentId = (int) F::GetRequest('reply');
     if (!F::CheckVal($sParentId, 'id')) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return false;
     }
     $oCommentParent = null;
     if ($sParentId != 0) {
         // * Проверяем существует ли комментарий на который отвечаем
         if (!($oCommentParent = E::ModuleComment()->GetCommentById($sParentId))) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
             return false;
         }
         // * Проверяем из одного топика ли новый коммент и тот на который отвечаем
         if ($oCommentParent->getTargetId() != $oTalk->getId()) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
             return false;
         }
     } else {
         // * Корневой комментарий
         $sParentId = null;
     }
     // * Проверка на дублирующий коммент
     if (E::ModuleComment()->GetCommentUnique($oTalk->getId(), 'talk', $this->oUserCurrent->getId(), $sParentId, md5($sText))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_comment_spam'), E::ModuleLang()->Get('error'));
         return false;
     }
     // * Создаём комментарий
     /** @var ModuleComment_EntityComment $oCommentNew */
     $oCommentNew = E::GetEntity('Comment');
     $oCommentNew->setTargetId($oTalk->getId());
     $oCommentNew->setTargetType('talk');
     $oCommentNew->setUserId($this->oUserCurrent->getId());
     $oCommentNew->setText($sText);
     $oCommentNew->setDate(F::Now());
     $oCommentNew->setUserIp(F::GetUserIp());
     $oCommentNew->setPid($sParentId);
     $oCommentNew->setTextHash(md5($sText));
     $oCommentNew->setPublish(1);
     // * Добавляем коммент
     E::ModuleHook()->Run('talk_comment_add_before', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTalk' => $oTalk));
     if (E::ModuleComment()->AddComment($oCommentNew)) {
         E::ModuleHook()->Run('talk_comment_add_after', array('oCommentNew' => $oCommentNew, 'oCommentParent' => $oCommentParent, 'oTalk' => $oTalk));
         E::ModuleViewer()->AssignAjax('sCommentId', $oCommentNew->getId());
         $oTalk->setDateLast(F::Now());
         $oTalk->setUserIdLast($oCommentNew->getUserId());
         $oTalk->setCommentIdLast($oCommentNew->getId());
         $oTalk->setCountComment($oTalk->getCountComment() + 1);
         E::ModuleTalk()->UpdateTalk($oTalk);
         // * Отсылаем уведомления всем адресатам
         $aUsersTalk = E::ModuleTalk()->GetUsersTalk($oTalk->getId(), ModuleTalk::TALK_USER_ACTIVE);
         foreach ($aUsersTalk as $oUserTalk) {
             if ($oUserTalk->getId() != $oCommentNew->getUserId()) {
                 E::ModuleNotify()->SendTalkCommentNew($oUserTalk, $this->oUserCurrent, $oTalk, $oCommentNew);
             }
         }
         // * Увеличиваем число новых комментов
         E::ModuleTalk()->IncreaseCountCommentNew($oTalk->getId(), $oCommentNew->getUserId());
         return true;
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
     }
     return false;
 }
コード例 #6
0
ファイル: ActionIndex.class.php プロジェクト: AntiqS/altocms
 /**
  * Вывод обсуждаемых топиков
  */
 protected function EventDiscussed()
 {
     $this->sTopicFilterPeriod = 1;
     // по дефолту 1 день
     if (in_array(F::GetRequestStr('period'), array(1, 7, 30, 'all'))) {
         $this->sTopicFilterPeriod = F::GetRequestStr('period');
     }
     /**
      * Меню
      */
     $this->sTopicFilter = $this->sMenuSubItemSelect = 'discussed';
     /**
      * Передан ли номер страницы
      */
     $iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
     if ($iPage == 1 && !F::GetRequest('period')) {
         E::ModuleViewer()->SetHtmlCanonical(R::GetPath('index') . 'discussed/');
     }
     /**
      * Получаем список топиков
      */
     $aResult = E::ModuleTopic()->GetTopicsDiscussed($iPage, Config::Get('module.topic.per_page'), $this->sTopicFilterPeriod == 'all' ? null : $this->sTopicFilterPeriod * 60 * 60 * 24);
     /**
      * Если нет топиков за 1 день, то показываем за неделю (7)
      */
     if (!$aResult['count'] && $iPage == 1 && !F::GetRequest('period')) {
         $this->sTopicFilterPeriod = 7;
         $aResult = E::ModuleTopic()->GetTopicsDiscussed($iPage, Config::Get('module.topic.per_page'), $this->sTopicFilterPeriod == 'all' ? null : $this->sTopicFilterPeriod * 60 * 60 * 24);
     }
     $aTopics = $aResult['collection'];
     /**
      * Вызов хуков
      */
     E::ModuleHook()->Run('topics_list_show', array('aTopics' => $aTopics));
     /**
      * Формируем постраничность
      */
     $aPaging = E::ModuleViewer()->MakePaging($aResult['count'], $iPage, Config::Get('module.topic.per_page'), Config::Get('pagination.pages.count'), R::GetPath('index') . 'discussed', array('period' => $this->sTopicFilterPeriod));
     E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('blog_menu_collective_discussed') . ($iPage > 1 ? ' (' . $iPage . ')' : ''));
     /**
      * Загружаем переменные в шаблон
      */
     E::ModuleViewer()->Assign('aTopics', $aTopics);
     E::ModuleViewer()->Assign('aPaging', $aPaging);
     E::ModuleViewer()->Assign('sPeriodSelectCurrent', $this->sTopicFilterPeriod);
     E::ModuleViewer()->Assign('sPeriodSelectRoot', R::GetPath('index') . 'discussed/');
     /**
      * Устанавливаем шаблон вывода
      */
     $this->SetTemplateAction('index');
 }
コード例 #7
0
ファイル: ActionAjax.class.php プロジェクト: anp135/altocms
 /**
  * Автоподставновка пользователей
  *
  */
 protected function EventAutocompleterUser()
 {
     // * Первые буквы логина переданы?
     if (!($sValue = F::GetRequest('value', null, 'post')) || !is_string($sValue)) {
         return;
     }
     $aItems = array();
     // * Формируем список пользователей
     /** @var ModuleUser_EntityUser[] $aUsers */
     $aUsers = E::ModuleUser()->GetUsersByLoginLike($sValue, 10);
     foreach ($aUsers as $oUser) {
         $aItems[] = (Config::Get('autocomplete.user.show_avatar') ? '<img src="' . $oUser->getAvatarUrl(Config::Get('autocomplete.user.avatar_size')) . '">' : '') . $oUser->getLogin();
     }
     // * Передаем результат в ajax ответ
     E::ModuleViewer()->AssignAjax('aItems', $aItems);
 }
コード例 #8
0
ファイル: ActionStream.class.php プロジェクト: AntiqS/altocms
 /**
  * Активаци/деактивация типа события
  *
  */
 protected function EventSwitchEventType()
 {
     /**
      * Устанавливаем формат Ajax ответа
      */
     E::ModuleViewer()->SetResponseAjax('json');
     /**
      * Пользователь авторизован?
      */
     if (!$this->oUserCurrent) {
         parent::EventNotFound();
     }
     if (!F::GetRequest('type')) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
     }
     /**
      * Активируем/деактивируем тип
      */
     E::ModuleStream()->SwitchUserEventType($this->oUserCurrent->getId(), F::GetRequestStr('type'));
     E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('stream_subscribes_updated'), E::ModuleLang()->Get('attention'));
 }
コード例 #9
0
ファイル: Viewer.class.php プロジェクト: anp135/altocms
 /**
  * Ответ на ajax запрос
  *
  * @param string $sType - Варианты: json, jsonIframe, jsonp
  */
 public function DisplayAjax($sType = 'json')
 {
     $sOutput = '';
     // * Загружаем статус ответа и сообщение
     $bStateError = false;
     $sMsgTitle = '';
     $sMsg = '';
     $aMsgError = E::ModuleMessage()->GetError();
     $aMsgNotice = E::ModuleMessage()->GetNotice();
     if (count($aMsgError) > 0) {
         $bStateError = true;
         $sMsgTitle = $aMsgError[0]['title'];
         $sMsg = $aMsgError[0]['msg'];
     } elseif (count($aMsgNotice) > 0) {
         $sMsgTitle = $aMsgNotice[0]['title'];
         $sMsg = $aMsgNotice[0]['msg'];
     }
     $this->AssignAjax('sMsgTitle', $sMsgTitle);
     $this->AssignAjax('sMsg', $sMsg);
     $this->AssignAjax('bStateError', $bStateError);
     if ($sType == 'json') {
         $this->SetResponseHeader('Content-type', 'application/json; charset=utf-8');
         $sOutput = F::jsonEncode($this->aVarsAjax);
     } elseif ($sType == 'jsonIframe') {
         // Оборачивает json в тег <textarea>, это не дает браузеру выполнить HTML, который вернул iframe
         $this->SetResponseHeader('Content-type', 'application/json; charset=utf-8');
         // * Избавляемся от бага, когда в возвращаемом тексте есть &quot;
         $sOutput = '<textarea>' . htmlspecialchars(F::jsonEncode($this->aVarsAjax)) . '</textarea>';
     } elseif ($sType == 'jsonp') {
         $this->SetResponseHeader('Content-type', 'application/json; charset=utf-8');
         $sOutput = F::GetRequest('jsonpCallback', 'callback') . '(' . F::jsonEncode($this->aVarsAjax) . ');';
     }
     $this->Flush($sOutput);
     exit;
 }
コード例 #10
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'));
 }
コード例 #11
0
ファイル: ActionPeople.class.php プロジェクト: AntiqS/altocms
 /**
  * Показываем юзеров
  *
  */
 protected function EventIndex()
 {
     // Получаем статистику
     $this->GetStats();
     // По какому полю сортировать
     $sOrder = 'user_rating';
     if (F::GetRequest('order')) {
         $sOrder = F::GetRequestStr('order');
     }
     // В каком направлении сортировать
     $sOrderWay = 'desc';
     if (F::GetRequest('order_way')) {
         $sOrderWay = F::GetRequestStr('order_way');
     }
     $aFilter = array('activate' => 1);
     // Передан ли номер страницы
     $iPage = $this->GetParamEventMatch(0, 2) ? $this->GetParamEventMatch(0, 2) : 1;
     // Получаем список юзеров
     $aResult = E::ModuleUser()->GetUsersByFilter($aFilter, array($sOrder => $sOrderWay), $iPage, Config::Get('module.user.per_page'));
     $aUsers = $aResult['collection'];
     // Формируем постраничность
     $aPaging = E::ModuleViewer()->MakePaging($aResult['count'], $iPage, Config::Get('module.user.per_page'), Config::Get('pagination.pages.count'), R::GetPath('people') . 'index', array('order' => $sOrder, 'order_way' => $sOrderWay));
     // Получаем алфавитный указатель на список пользователей
     $aPrefixUser = E::ModuleUser()->GetGroupPrefixUser(1);
     // Загружаем переменные в шаблон
     E::ModuleViewer()->Assign('aPaging', $aPaging);
     E::ModuleViewer()->Assign('aUsersRating', $aUsers);
     E::ModuleViewer()->Assign('aPrefixUser', $aPrefixUser);
     E::ModuleViewer()->Assign("sUsersOrder", htmlspecialchars($sOrder));
     E::ModuleViewer()->Assign("sUsersOrderWay", htmlspecialchars($sOrderWay));
     E::ModuleViewer()->Assign("sUsersOrderWayNext", htmlspecialchars($sOrderWay == 'desc' ? 'asc' : 'desc'));
     // Устанавливаем шаблон вывода
     $this->SetTemplateAction('index');
 }
コード例 #12
0
ファイル: function.php プロジェクト: AntiqS/altocms
function getRequest($sName, $default = null, $sType = null)
{
    return F::GetRequest($sName, $default, $sType);
}
コード例 #13
0
 /**
  * Изменение состояния подписки
  */
 protected function EventAjaxTrackToggle()
 {
     /**
      * Устанавливаем формат Ajax ответа
      */
     E::ModuleViewer()->SetResponseAjax('json');
     if (!$this->oUserCurrent) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return;
     }
     /**
      * Получаем тип объекта подписки
      */
     $sTargetType = F::GetRequestStr('target_type');
     if (!E::ModuleSubscribe()->IsAllowTargetType($sTargetType)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     $sTargetId = F::GetRequestStr('target_id') ? F::GetRequestStr('target_id') : null;
     $iValue = F::GetRequest('value') ? 1 : 0;
     $oTrack = null;
     /**
      * Проверка объекта подписки
      */
     if (!E::ModuleSubscribe()->CheckTarget($sTargetType, $sTargetId, $iValue)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     /**
      * Если подписка еще не существовала, то создаем её
      */
     if ($oTrack = E::ModuleSubscribe()->AddTrackSimple($sTargetType, $sTargetId, $this->oUserCurrent->getId())) {
         $oTrack->setStatus($iValue);
         E::ModuleSubscribe()->UpdateTrack($oTrack);
         E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('subscribe_change_ok'), E::ModuleLang()->Get('attention'));
         return;
     }
     E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
     return;
 }
コード例 #14
0
 /**
  * Редактирование поля контента
  *
  * @param ModuleTopic_EntityContentType $oContentType
  * @param ModuleTopic_EntityField $oField
  * @return bool
  */
 protected function SubmitEditField($oContentType, $oField)
 {
     // * Проверяем отправлена ли форма с данными
     if (!F::isPost('submit_field')) {
         return false;
     }
     // * Проверка корректности полей формы
     if (!$this->CheckFieldsField($oContentType)) {
         return false;
     }
     if (!E::ModuleTopic()->GetFieldValuesCount($oField->getFieldId())) {
         // Нет ещё ни одного значения этого поля, тогда можно сменить ещё и тип
         $oField->setFieldType(F::GetRequest('field_type'));
     }
     $oField->setFieldName(F::GetRequest('field_name'));
     $oField->setFieldDescription(F::GetRequest('field_description'));
     $oField->setFieldRequired(F::GetRequest('field_required'));
     if ($oField->getFieldType() == 'select') {
         $oField->setOptionValue('select', F::GetRequest('field_values'));
     }
     $sOldFieldUniqueName = $oField->getFieldUniqueName();
     if (F::GetRequest('field_unique_name_translit')) {
         $oField->setFieldUniqueName(F::TranslitUrl(F::GetRequest('field_name')));
     } else {
         $oField->setFieldUniqueName(F::TranslitUrl(F::GetRequest('field_unique_name')));
     }
     try {
         if (E::ModuleTopic()->UpdateContentField($oField)) {
             E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('action.admin.contenttypes_success_fieldedit'), null, true);
             R::Location('admin/settings-contenttypes/edit/' . $oContentType->getContentId() . '/');
         }
     } catch (Exception $e) {
         // Если ошибка дублирования уникального ключа, то выводим соответствующее сообщение
         if (1062 == $e->getCode()) {
             $sNewFieldUniqueName = $oField->getFieldUniqueName();
             $oField->setFieldUniqueName($sOldFieldUniqueName);
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('plugin.contentfieldsx.error_field_unique_name_duplicate', array('unique_name' => htmlspecialchars($sNewFieldUniqueName))), null, false);
         }
     }
     return false;
 }
コード例 #15
0
 /**
  * Отписка от блога или пользователя
  *
  */
 protected function EventUnsubscribe()
 {
     // * Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     if (!F::GetRequest('id')) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     $sType = F::GetRequestStr('type');
     $iType = null;
     // * Определяем от чего отписываемся
     switch ($sType) {
         case 'blogs':
         case 'blog':
             $iType = ModuleUserfeed::SUBSCRIBE_TYPE_BLOG;
             break;
         case 'users':
         case 'user':
             $iType = ModuleUserfeed::SUBSCRIBE_TYPE_USER;
             break;
         default:
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
             return;
     }
     // * Отписываем пользователя
     E::ModuleUserfeed()->UnsubscribeUser($this->oUserCurrent->getId(), $iType, F::GetRequestStr('id'));
     E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('userfeed_subscribes_updated'), E::ModuleLang()->Get('attention'));
 }
コード例 #16
0
 /**
  * Меняет сортировку элементов фотосета
  */
 public function EventSort()
 {
     // * Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     // Проверяем, целевой объект и права на его редактирование
     if (!($oTarget = E::ModuleUploader()->CheckAccessAndGetTarget($sTargetType = F::GetRequest('target', FALSE), $sTargetId = F::GetRequest('target_id', FALSE)))) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error'));
         return;
     }
     if (!($aOrder = F::GetRequest('order', FALSE))) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error'));
         return;
     }
     if (!is_array($aOrder)) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('not_access'), E::ModuleLang()->Get('error'));
         return;
     }
     E::ModuleMresource()->UpdateSort(array_flip($aOrder), $sTargetType, $sTargetId);
     E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('uploader_sort_changed'));
 }
コード例 #17
0
ファイル: ActionSearch.class.php プロジェクト: Azany/altocms
 /**
  * Разбор запроса
  *
  * @param null $sType
  *
  * @return mixed
  */
 protected function _prepareRequest($sType = null)
 {
     $sRequest = trim(F::GetRequest('q'));
     // * Иногда ломается кодировка, напр., если ввели поиск в адресной строке браузера
     // * Пытаемся восстановить по основной кодировке браузера
     if (!mb_check_encoding($sRequest)) {
         list($sCharset) = explode(',', $_SERVER['HTTP_ACCEPT_CHARSET']);
         $sQueryString = mb_convert_encoding($_SERVER['QUERY_STRING'], 'UTF-8', $sCharset);
         $sRequest = mb_convert_encoding($sRequest, 'UTF-8', $sCharset);
     }
     if ($sRequest) {
         // Две звездочки подряд меняем на одну
         $sRequest = preg_replace('/(\\*{2,})/', '*', $sRequest);
         // Две пробела подряд меняем на один
         $sRequest = preg_replace('/(\\s{2,})/', ' ', $sRequest);
         // Последовательность звездочек и пробелов, начинающаяся со звездочки
         $sRequest = preg_replace('/\\*[\\*\\s]{2,}/', '* ', $sRequest);
         // Последовательность звездочек и пробелов, начинающаяся с пробела
         $sRequest = preg_replace('/\\s[\\*\\s]{2,}/', ' *', $sRequest);
     }
     $aReq['q'] = $sRequest;
     $aReq['regexp'] = preg_quote(trim(mb_strtolower($aReq['q'])));
     // * Проверка длины запроса
     if (!F::CheckVal($aReq['regexp'], 'text', Config::Get('module.search.min_length_req'), Config::Get('module.search.max_length_req'))) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('search_err_length', array('min' => Config::Get('module.search.min_length_req'), 'max' => Config::Get('module.search.max_length_req'))));
         $aReq['regexp'] = '';
     }
     // Save quoted substrings
     $aQuoted = array();
     if (preg_match_all('/"([^"]+)"/U', $aReq['regexp'], $aMatches)) {
         foreach ($aMatches[1] as $sStr) {
             $sSubstKey = 'begin-' . md5($sStr) . '-end';
             $aQuoted[0][] = $sSubstKey;
             $aQuoted[1][] = $sStr;
         }
         $aReq['regexp'] = str_replace($aQuoted[1], $aQuoted[0], $aReq['regexp']);
     }
     /*
      * Проверка длины каждого слова в запросе
      * Хотя бы одно слово должно быть больше минимальной длины
      * Слова меньше минимальной длины исключаем из поиска
      */
     if ($aReq['regexp']) {
         $aWords = explode(' ', $aReq['regexp']);
         $nErr = 0;
         $sStr = '';
         foreach ($aWords as $sWord) {
             if (!F::CheckVal($sWord, 'text', Config::Get('module.search.min_length_req'), Config::Get('module.search.max_length_req'))) {
                 $nErr += 1;
             } else {
                 if ($sStr) {
                     $sStr .= ' ';
                 }
                 $sStr .= $sWord;
             }
         }
         if ($nErr == sizeof($aWords)) {
             E::ModuleMessage()->AddError(E::ModuleLang()->Get('search_err_length_word', array('min' => Config::Get('module.search.min_length_req'), 'max' => Config::Get('module.search.max_length_req'))));
             $aReq['regexp'] = '';
         } else {
             $aReq['regexp'] = $sStr;
         }
     }
     // * Если все нормально, формируем выражение для поиска
     if ($aReq['regexp']) {
         if ($this->bSearchStrict) {
             $aReq['regexp'] = str_replace('\\*', '*', $aReq['regexp']);
             /*
              * Проверка на "лишние" символы, оставляем только "слова"
              * На месте "небукв" оставляем пробелы
              */
             $aReq['regexp'] = preg_replace('/' . $this->sPatternXA . '/iusxSU', ' ', $aReq['regexp']);
             $aReq['regexp'] = trim(preg_replace('/(\\s{2,})/', ' ', $aReq['regexp']));
             // * Если после "чистки" что-то осталось, то продолжаем дальше
             if ($aReq['regexp']) {
                 $aReq['regexp'] = str_replace('* *', '|', $aReq['regexp']);
                 $aReq['regexp'] = str_replace('* ', '|[[:<:]]', $aReq['regexp']);
                 $aReq['regexp'] = str_replace(' *', '[[:>:]]|', $aReq['regexp']);
                 $aReq['regexp'] = str_replace(' ', '[[:>:]]|[[:<:]]', $aReq['regexp']);
                 if (mb_substr($aReq['regexp'], 0, 1) == '*') {
                     $aReq['regexp'] = mb_substr($aReq['regexp'], 1);
                 } else {
                     $aReq['regexp'] = '[[:<:]]' . $aReq['regexp'];
                 }
                 if (mb_substr($aReq['regexp'], -1) == '*') {
                     $aReq['regexp'] = mb_substr($aReq['regexp'], 0, mb_strlen($aReq['regexp']) - 1);
                 } else {
                     $aReq['regexp'] = $aReq['regexp'] . '[[:>:]]';
                 }
             }
         } else {
             $aReq['regexp'] = preg_replace('/' . $this->sPatternXA . '/uU', '', $aReq['regexp']);
             $aReq['regexp'] = trim(preg_replace('/(\\s{2,})/', ' ', $aReq['regexp']));
             $aReq['regexp'] = str_replace(' ', '|', $aReq['regexp']);
         }
     }
     // Restore quoted substrings
     if ($aReq['regexp'] && !empty($aQuoted[0])) {
         $aReq['regexp'] = str_replace($aQuoted[0], $aQuoted[1], $aReq['regexp']);
     }
     $aReq['params']['bSkipTags'] = false;
     if ($sType) {
         $aReq['sType'] = $sType;
     } else {
         $aReq['sType'] = 'topics';
     }
     // * Определяем текущую страницу вывода результата
     $aReq['iPage'] = intval(preg_replace('#^page(\\d+)$#', '\\1', $this->getParam(0)));
     if (!$aReq['iPage']) {
         $aReq['iPage'] = 1;
     }
     return $aReq;
 }
コード例 #18
0
 /**
  * AJAX подгрузка следующих фото
  *
  */
 protected function EventAjaxPhotoGetMore()
 {
     // * Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     // * Существует ли топик
     $iTopicId = F::GetRequestStr('topic_id');
     $iLastId = F::GetRequest('last_id');
     $sThumbSize = F::GetRequest('thumb_size');
     if (!$sThumbSize) {
         $sThumbSize = '50crop';
     }
     if (!$iTopicId || !($oTopic = E::ModuleTopic()->GetTopicById($iTopicId)) || !$iLastId) {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         F::SysWarning('System Error');
         return;
     }
     // * Получаем список фото
     $aPhotos = $oTopic->getPhotosetPhotos($iLastId, Config::Get('module.topic.photoset.per_page'));
     $aResult = array();
     if (count($aPhotos)) {
         // * Формируем данные для ajax ответа
         foreach ($aPhotos as $oPhoto) {
             $aResult[] = array('id' => $oPhoto->getMresourceId(), 'path_thumb' => $oPhoto->getLink($sThumbSize), 'path' => $oPhoto->getLink(), 'description' => $oPhoto->getDescription());
         }
         E::ModuleViewer()->AssignAjax('photos', $aResult);
     }
     E::ModuleViewer()->AssignAjax('bHaveNext', count($aPhotos) == Config::Get('module.topic.photoset.per_page'));
 }
コード例 #19
0
ファイル: ActionLogin.class.php プロジェクト: hard990/altocms
 /**
  * Обрабатываем процесс разлогинивания
  *
  */
 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;
     }
 }
コード例 #20
0
ファイル: ActionBlog.class.php プロジェクト: anp135/altocms
 /**
  * Обработка ajax запроса на отправку
  * пользователям приглашения вступить в приватный блог
  */
 protected function AjaxAddBlogInvite()
 {
     // * Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     $sUsers = F::GetRequest('users', null, 'post');
     $iBlogId = intval(F::GetRequestStr('idBlog', null, 'post'));
     // * Если пользователь не авторизирован, возвращаем ошибку
     if (!E::ModuleUser()->IsAuthorization()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return;
     }
     $this->oUserCurrent = E::ModuleUser()->GetUserCurrent();
     // * Проверяем существование блога
     if (!$iBlogId || !($oBlog = E::ModuleBlog()->GetBlogById($iBlogId)) || !is_string($sUsers)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     $this->oCurrentBlog = $oBlog;
     // * Проверяем, имеет ли право текущий пользователь добавлять invite в blog
     $oBlogUser = E::ModuleBlog()->GetBlogUserByBlogIdAndUserId($oBlog->getId(), $this->oUserCurrent->getId());
     $bBlogAdministrator = $oBlogUser ? $oBlogUser->IsBlogAdministrator() : false;
     if ($oBlog->getOwnerId() != $this->oUserCurrent->getId() && !$this->oUserCurrent->isAdministrator() && !$this->oUserCurrent->isModerator() && !$bBlogAdministrator) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error'));
         return;
     }
     // * Получаем список пользователей блога (любого статуса)
     $aBlogUsersResult = E::ModuleBlog()->GetBlogUsersByBlogId($oBlog->getId(), true, null);
     /** @var ModuleBlog_EntityBlogUser[] $aBlogUsers */
     $aBlogUsers = $aBlogUsersResult['collection'];
     $aUsers = explode(',', $sUsers);
     $aResult = array();
     // * Обрабатываем добавление по каждому из переданных логинов
     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('blog_user_invite_add_self'));
             continue;
         }
         // * Если пользователь не найден или неактивен, возвращаем ошибку
         $oUser = E::ModuleUser()->GetUserByLogin($sUser);
         if (!$oUser || $oUser->getActivate() != 1) {
             $aResult[] = array('bStateError' => true, 'sMsgTitle' => E::ModuleLang()->Get('error'), 'sMsg' => E::ModuleLang()->Get('user_not_found', array('login' => htmlspecialchars($sUser))), 'sUserLogin' => htmlspecialchars($sUser));
             continue;
         }
         if (!isset($aBlogUsers[$oUser->getId()])) {
             // * Создаем нового блог-пользователя со статусом INVITED
             /** @var ModuleBlog_EntityBlogUser $oBlogUserNew */
             $oBlogUserNew = E::GetEntity('Blog_BlogUser');
             $oBlogUserNew->setBlogId($oBlog->getId());
             $oBlogUserNew->setUserId($oUser->getId());
             $oBlogUserNew->setUserRole(ModuleBlog::BLOG_USER_ROLE_INVITE);
             if (E::ModuleBlog()->AddRelationBlogUser($oBlogUserNew)) {
                 $aResult[] = array('bStateError' => false, 'sMsgTitle' => E::ModuleLang()->Get('attention'), 'sMsg' => E::ModuleLang()->Get('blog_user_invite_add_ok', array('login' => htmlspecialchars($sUser))), 'sUserLogin' => htmlspecialchars($sUser), 'sUserWebPath' => $oUser->getProfileUrl(), 'sUserAvatar48' => $oUser->getAvatarUrl(48));
                 $this->SendBlogInvite($oBlog, $oUser);
             } else {
                 $aResult[] = array('bStateError' => true, 'sMsgTitle' => E::ModuleLang()->Get('error'), 'sMsg' => E::ModuleLang()->Get('system_error'), 'sUserLogin' => htmlspecialchars($sUser));
             }
         } elseif ($aBlogUsers[$oUser->getId()]->getUserRole() == ModuleBlog::BLOG_USER_ROLE_NOTMEMBER || $aBlogUsers[$oUser->getId()]->getUserRole() == ModuleBlog::BLOG_USER_ROLE_WISHES) {
             // * Change status of user to INVITED
             /** @var ModuleBlog_EntityBlogUser $oBlogUser */
             $oBlogUser = $aBlogUsers[$oUser->getId()];
             $oBlogUser->setUserRole(ModuleBlog::BLOG_USER_ROLE_INVITE);
             if (E::ModuleBlog()->UpdateRelationBlogUser($oBlogUser)) {
                 $aResult[] = array('bStateError' => false, 'sMsgTitle' => E::ModuleLang()->Get('attention'), 'sMsg' => E::ModuleLang()->Get('blog_user_invite_add_ok', array('login' => htmlspecialchars($sUser))), 'sUserLogin' => htmlspecialchars($sUser), 'sUserWebPath' => $oUser->getProfileUrl(), 'sUserAvatar48' => $oUser->getAvatarUrl(48));
                 $this->SendBlogInvite($oBlog, $oUser);
             } else {
                 $aResult[] = array('bStateError' => true, 'sMsgTitle' => E::ModuleLang()->Get('error'), 'sMsg' => E::ModuleLang()->Get('system_error'), 'sUserLogin' => htmlspecialchars($sUser));
             }
         } else {
             // Попытка добавить приглашение уже существующему пользователю,
             // возвращаем ошибку (сначала определяя ее точный текст)
             switch (true) {
                 case $aBlogUsers[$oUser->getId()]->getUserRole() == ModuleBlog::BLOG_USER_ROLE_INVITE:
                     $sErrorMessage = E::ModuleLang()->Get('blog_user_already_invited', array('login' => htmlspecialchars($sUser)));
                     break;
                 case $aBlogUsers[$oUser->getId()]->getUserRole() > ModuleBlog::BLOG_USER_ROLE_GUEST:
                     $sErrorMessage = E::ModuleLang()->Get('blog_user_already_exists', array('login' => htmlspecialchars($sUser)));
                     break;
                 case $aBlogUsers[$oUser->getId()]->getUserRole() == ModuleBlog::BLOG_USER_ROLE_REJECT:
                     $sErrorMessage = E::ModuleLang()->Get('blog_user_already_reject', array('login' => htmlspecialchars($sUser)));
                     break;
                 default:
                     $sErrorMessage = E::ModuleLang()->Get('system_error');
             }
             $aResult[] = array('bStateError' => true, 'sMsgTitle' => E::ModuleLang()->Get('error'), 'sMsg' => $sErrorMessage, 'sUserLogin' => htmlspecialchars($sUser));
             continue;
         }
     }
     // * Передаем во вьевер массив с результатами обработки по каждому пользователю
     E::ModuleViewer()->AssignAjax('aUsers', $aResult);
 }
コード例 #21
0
ファイル: Topic.class.php プロジェクト: AlexSSN/altocms
 /**
  * Обработка дополнительных полей топика
  *
  * @param ModuleTopic_EntityTopic $oTopic
  * @param string $sType
  *
  * @return bool
  */
 public function processTopicFields($oTopic, $sType = 'add')
 {
     /** @var ModuleTopic_EntityContentValues $aValues */
     $aValues = array();
     if ($sType == 'update') {
         // * Получаем существующие значения
         if ($aData = $this->GetTopicValuesByArrayId(array($oTopic->getId()))) {
             $aValues = $aData[$oTopic->getId()];
         }
         // * Чистим существующие значения
         E::ModuleTopic()->DeleteTopicValuesByTopicId($oTopic->getId());
     }
     if ($oType = E::ModuleTopic()->GetContentTypeByUrl($oTopic->getType())) {
         //получаем поля для данного типа
         if ($aFields = $oType->getFields()) {
             foreach ($aFields as $oField) {
                 $sData = null;
                 if (isset($_REQUEST['fields'][$oField->getFieldId()]) || isset($_FILES['fields_' . $oField->getFieldId()]) || $oField->getFieldType() == 'single-image-uploader') {
                     //текстовые поля
                     if (in_array($oField->getFieldType(), array('input', 'textarea', 'select'))) {
                         $sData = E::ModuleText()->Parser($_REQUEST['fields'][$oField->getFieldId()]);
                     }
                     //поле ссылки
                     if ($oField->getFieldType() == 'link') {
                         $sData = $_REQUEST['fields'][$oField->getFieldId()];
                     }
                     //поле даты
                     if ($oField->getFieldType() == 'date') {
                         if (isset($_REQUEST['fields'][$oField->getFieldId()])) {
                             if (F::CheckVal($_REQUEST['fields'][$oField->getFieldId()], 'text', 6, 10) && substr_count($_REQUEST['fields'][$oField->getFieldId()], '.') == 2) {
                                 list($d, $m, $y) = explode('.', $_REQUEST['fields'][$oField->getFieldId()]);
                                 if (@checkdate($m, $d, $y)) {
                                     $sData = $_REQUEST['fields'][$oField->getFieldId()];
                                 }
                             }
                         }
                     }
                     //поле с файлом
                     if ($oField->getFieldType() == 'file') {
                         //если указано удаление файла
                         if (F::GetRequest('topic_delete_file_' . $oField->getFieldId())) {
                             if ($oTopic->getFieldFile($oField->getFieldId())) {
                                 @unlink(Config::Get('path.root.dir') . $oTopic->getFieldFile($oField->getFieldId())->getFileUrl());
                                 //$oTopic->setValueField($oField->getFieldId(),'');
                                 $sData = null;
                             }
                         } else {
                             //если удаление файла не указано, уже ранее залит файл^ и нового файла не загружалось
                             if ($sType == 'update' && isset($aValues[$oField->getFieldId()])) {
                                 $sData = $aValues[$oField->getFieldId()]->getValueSource();
                             }
                         }
                         if (isset($_FILES['fields_' . $oField->getFieldId()]) && is_uploaded_file($_FILES['fields_' . $oField->getFieldId()]['tmp_name'])) {
                             $iMaxFileSize = F::MemSize2Int(Config::Get('module.uploader.files.default.file_maxsize'));
                             $aFileExtensions = Config::Get('module.uploader.files.default.file_extensions');
                             if (!$iMaxFileSize || filesize($_FILES['fields_' . $oField->getFieldId()]['tmp_name']) <= $iMaxFileSize) {
                                 $aPathInfo = pathinfo($_FILES['fields_' . $oField->getFieldId()]['name']);
                                 if (!$aFileExtensions || in_array(strtolower($aPathInfo['extension']), $aFileExtensions)) {
                                     $sFileTmp = $_FILES['fields_' . $oField->getFieldId()]['tmp_name'];
                                     $sDirSave = Config::Get('path.uploads.root') . '/files/' . E::ModuleUser()->GetUserCurrent()->getId() . '/' . F::RandomStr(16);
                                     mkdir(Config::Get('path.root.dir') . $sDirSave, 0777, true);
                                     if (is_dir(Config::Get('path.root.dir') . $sDirSave)) {
                                         $sFile = $sDirSave . '/' . F::RandomStr(10) . '.' . strtolower($aPathInfo['extension']);
                                         $sFileFullPath = Config::Get('path.root.dir') . $sFile;
                                         if (copy($sFileTmp, $sFileFullPath)) {
                                             //удаляем старый файл
                                             if ($oTopic->getFieldFile($oField->getFieldId())) {
                                                 $sOldFile = Config::Get('path.root.dir') . $oTopic->getFieldFile($oField->getFieldId())->getFileUrl();
                                                 F::File_Delete($sOldFile);
                                             }
                                             $aFileObj = array();
                                             $aFileObj['file_hash'] = F::RandomStr(32);
                                             $aFileObj['file_name'] = E::ModuleText()->Parser($_FILES['fields_' . $oField->getFieldId()]['name']);
                                             $aFileObj['file_url'] = $sFile;
                                             $aFileObj['file_size'] = $_FILES['fields_' . $oField->getFieldId()]['size'];
                                             $aFileObj['file_extension'] = $aPathInfo['extension'];
                                             $aFileObj['file_downloads'] = 0;
                                             $sData = serialize($aFileObj);
                                             F::File_Delete($sFileTmp);
                                         }
                                     }
                                 } else {
                                     $sTypes = implode(', ', $aFileExtensions);
                                     E::ModuleMessage()->AddError(E::ModuleLang()->Get('topic_field_file_upload_err_type', array('types' => $sTypes)), null, true);
                                 }
                             } else {
                                 E::ModuleMessage()->AddError(E::ModuleLang()->Get('topic_field_file_upload_err_size', array('size' => $iMaxFileSize)), null, true);
                             }
                             F::File_Delete($_FILES['fields_' . $oField->getFieldId()]['tmp_name']);
                         }
                     }
                     // Поле с изображением
                     if ($oField->getFieldType() == 'single-image-uploader') {
                         $sTargetType = $oField->getFieldType() . '-' . $oField->getFieldId();
                         $iTargetId = $oTopic->getId();
                         // 1. Удалить значение target_tmp
                         // Нужно затереть временный ключ в ресурсах, что бы в дальнейшем картнка не
                         // воспринималась как временная.
                         if ($sTargetTmp = E::ModuleSession()->GetCookie(ModuleUploader::COOKIE_TARGET_TMP)) {
                             // 2. Удалить куку.
                             // Если прозошло сохранение вновь созданного топика, то нужно
                             // удалить куку временной картинки. Если же сохранялся уже существующий топик,
                             // то удаление куки ни на что влиять не будет.
                             E::ModuleSession()->DelCookie(ModuleUploader::COOKIE_TARGET_TMP);
                             // 3. Переместить фото
                             $sNewPath = E::ModuleUploader()->GetUserImageDir(E::UserId(), true, false);
                             $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, 0, E::UserId());
                             if ($aMresourceRel) {
                                 $oResource = array_shift($aMresourceRel);
                                 $sOldPath = $oResource->GetFile();
                                 $oStoredFile = E::ModuleUploader()->Store($sOldPath, $sNewPath);
                                 /** @var ModuleMresource_EntityMresource $oResource */
                                 $oResource = E::ModuleMresource()->GetMresourcesByUuid($oStoredFile->getUuid());
                                 if ($oResource) {
                                     $oResource->setUrl(E::ModuleMresource()->NormalizeUrl(E::ModuleUploader()->GetTargetUrl($sTargetType, $iTargetId)));
                                     $oResource->setType($sTargetType);
                                     $oResource->setUserId(E::UserId());
                                     // 4. В свойство поля записать адрес картинки
                                     $sData = $oResource->getMresourceId();
                                     $oResource = array($oResource);
                                     E::ModuleMresource()->UnlinkFile($sTargetType, 0, $oTopic->getUserId());
                                     E::ModuleMresource()->AddTargetRel($oResource, $sTargetType, $iTargetId);
                                 }
                             }
                         } else {
                             // Топик редактируется, просто обновим поле
                             $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, $iTargetId, E::UserId());
                             if ($aMresourceRel) {
                                 $oResource = array_shift($aMresourceRel);
                                 $sData = $oResource->getMresourceId();
                             } else {
                                 $sData = false;
                                 //                                    $this->DeleteField($oField);
                             }
                         }
                     }
                     E::ModuleHook()->Run('content_field_proccess', array('sData' => &$sData, 'oField' => $oField, 'oTopic' => $oTopic, 'aValues' => $aValues, 'sType' => &$sType));
                     //Добавляем поле к топику.
                     if ($sData) {
                         /** @var ModuleTopic_EntityContentValues $oValue */
                         $oValue = E::GetEntity('Topic_ContentValues');
                         $oValue->setTargetId($oTopic->getId());
                         $oValue->setTargetType('topic');
                         $oValue->setFieldId($oField->getFieldId());
                         $oValue->setFieldType($oField->getFieldType());
                         $oValue->setValue($sData);
                         $oValue->setValueSource(in_array($oField->getFieldType(), array('file', 'single-image-uploader')) ? $sData : $_REQUEST['fields'][$oField->getFieldId()]);
                         $this->AddTopicValue($oValue);
                     }
                 }
             }
         }
     }
     return true;
 }
コード例 #22
0
 /**
  * Подгрузка ответов на стене к сообщению
  */
 public function EventWallLoadReply()
 {
     // * Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     if (!$this->CheckUserProfile()) {
         return parent::EventNotFound();
     }
     // пока оставлю здесь, логику не понял
     //if (!($oWall = E::ModuleWall()->GetWallById($this->GetPost('iPid'))) || $oWall->getPid()) {
     if (!($oWall = E::ModuleWall()->GetWallById($this->GetPost('iPid')))) {
         return parent::EventNotFound();
     }
     // * Формируем фильтр для запроса к БД
     $aFilter = array('wall_user_id' => $this->oUserProfile->getId(), 'pid' => $oWall->getId());
     if (is_numeric(F::GetRequest('iIdLess'))) {
         $aFilter['id_less'] = F::GetRequest('iIdLess');
     } elseif (is_numeric(F::GetRequest('iIdMore'))) {
         $aFilter['id_more'] = F::GetRequest('iIdMore');
     } else {
         E::ModuleMessage()->AddError(E::ModuleLang()->Get('error'));
         return;
     }
     // * Получаем сообщения и формируем ответ. Необходимо вернуть все ответы, но ставим "разумное" ограничение
     $aWall = E::ModuleWall()->GetWall($aFilter, array('id' => 'asc'), 1, 300);
     E::ModuleViewer()->Assign('aLang', E::ModuleLang()->GetLangMsg());
     E::ModuleViewer()->Assign('aReplyWall', $aWall['collection']);
     E::ModuleViewer()->AssignAjax('sText', E::ModuleViewer()->Fetch('actions/profile/action.profile.wall_items_reply.tpl'));
     E::ModuleViewer()->AssignAjax('iCountWall', $aWall['count']);
     E::ModuleViewer()->AssignAjax('iCountWallReturn', count($aWall['collection']));
 }