/** * @param ModuleMresource_EntityMresource $oMresource * * @return bool */ public function AddTargetRel($oMresource) { $aParams = array(':id' => $oMresource->GetMresourceId(), ':target_type' => $oMresource->GetTargetType(), ':target_id' => $oMresource->GetTargetId(), ':date_add' => F::Now(), ':description' => $oMresource->GetDescription(), ':target_tmp' => $oMresource->GetTargetTmp(), ':incount' => $oMresource->GetIncount() ? $oMresource->GetIncount() : 1); $sql = "\n SELECT mresource_id\n FROM ?_mresource_target\n WHERE\n target_type = ?:target_type\n AND target_id = ?d:target_id\n AND mresource_id = ?d:id\n LIMIT 1\n "; if ($iId = $this->oDb->sqlSelectCell($sql, $aParams)) { $sql = "\n UPDATE ?_mresource_target\n SET incount=incount+?d:incount\n WHERE mresource_id = ?d:id\n "; if ($this->oDb->sqlQuery($sql, $aParams)) { return $iId; } } else { $sql = "\n INSERT INTO ?_mresource_target\n (\n mresource_id,\n target_type,\n target_id,\n date_add,\n description,\n target_tmp,\n incount\n )\n VALUES (\n ?d:id,\n ?:target_type,\n ?d:target_id,\n ?:date_add,\n ?:description,\n ?:target_tmp,\n ?d:incount\n )\n "; if ($iId = $this->oDb->sqlQuery($sql, $aParams)) { return $iId ? $iId : false; } } return false; }
/** * Добавление записи на стену * * @param ModuleWall_EntityWall $oWall Объект записи на стене * * @return bool|ModuleWall_EntityWall */ public function AddWall($oWall) { if (!$oWall->getDateAdd()) { $oWall->setDateAdd(F::Now()); } if (!$oWall->getIp()) { $oWall->setIp(F::GetUserIp()); } if ($iId = $this->oMapper->AddWall($oWall)) { $oWall->setId($iId); /** * Обновляем данные у родительской записи */ if ($oPidWall = $oWall->GetPidWall()) { $this->UpdatePidWall($oPidWall); } return $oWall; } return false; }
/** * Отписка от подписки */ protected function EventUnsubscribe() { /** * Получаем подписку по ключу */ $oSubscribe = E::ModuleSubscribe()->GetSubscribeByKey($this->getParam(0)); if ($oSubscribe && $oSubscribe->getStatus() == 1) { /** * Отписываем пользователя */ $oSubscribe->setStatus(0); $oSubscribe->setDateRemove(F::Now()); E::ModuleSubscribe()->UpdateSubscribe($oSubscribe); E::ModuleMessage()->AddNotice(E::ModuleLang()->Get('subscribe_change_ok'), null, true); } /** * Получаем URL для редиректа */ if (!($sUrl = E::ModuleSubscribe()->GetUrlTarget($oSubscribe->getTargetType(), $oSubscribe->getTargetId()))) { $sUrl = R::GetPath('index'); } R::Location($sUrl); }
/** * Обработка добавление комментария к письму * */ 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; }
/** * Предпросмотр топика * */ protected function EventPreviewTopic() { /** * Т.к. используется обработка отправки формы, то устанавливаем тип ответа 'jsonIframe' (тот же JSON только обернутый в textarea) * Это позволяет избежать ошибок в некоторых браузерах, например, Opera */ E::ModuleViewer()->SetResponseAjax(F::AjaxRequest(true) ? 'json' : 'jsonIframe', false); // * Пользователь авторизован? if (!$this->oUserCurrent) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error')); return; } // * Допустимый тип топика? if (!E::ModuleTopic()->IsAllowTopicType($sType = F::GetRequestStr('topic_type'))) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_create_type_error'), E::ModuleLang()->Get('error')); return; } // * Создаем объект топика для валидации данных $oTopic = E::GetEntity('ModuleTopic_EntityTopic'); $oTopic->_setValidateScenario($sType); // зависит от типа топика $oTopic->setTitle(strip_tags(F::GetRequestStr('topic_title'))); $oTopic->setTextSource(F::GetRequestStr('topic_text')); $aTags = F::GetRequestStr('topic_field_tags'); if (!$aTags) { // LS compatibility $aTags = F::GetRequestStr('topic_tags'); } $oTopic->setTags($aTags); $oTopic->setDateAdd(F::Now()); $oTopic->setUserId($this->oUserCurrent->getId()); $oTopic->setType($sType); $oTopic->setBlogId(F::GetRequestStr('blog_id')); $oTopic->setPublish(1); // * Валидируем необходимые поля топика $oTopic->_Validate(array('topic_title', 'topic_text', 'topic_tags', 'topic_type'), false); if ($oTopic->_hasValidateErrors()) { E::ModuleMessage()->AddErrorSingle($oTopic->_getValidateError()); return false; } // * Формируем текст топика list($sTextShort, $sTextNew, $sTextCut) = E::ModuleText()->Cut($oTopic->getTextSource()); $oTopic->setCutText($sTextCut); $oTopic->setText(E::ModuleText()->Parse($sTextNew)); $oTopic->setTextShort(E::ModuleText()->Parse($sTextShort)); // * Готовим дополнительные поля, кроме файлов if ($oType = $oTopic->getContentType()) { //получаем поля для данного типа if ($aFields = $oType->getFields()) { $aValues = array(); // вставляем поля, если они прописаны для топика foreach ($aFields as $oField) { if (isset($_REQUEST['fields'][$oField->getFieldId()])) { $sText = null; //текстовые поля if (in_array($oField->getFieldType(), array('input', 'textarea', 'select'))) { $sText = E::ModuleText()->Parse($_REQUEST['fields'][$oField->getFieldId()]); } //поле ссылки if ($oField->getFieldType() == 'link') { $sText = $_REQUEST['fields'][$oField->getFieldId()]; } //поле даты if ($oField->getFieldType() == 'date') { if (isset($_REQUEST['fields'][$oField->getFieldId()])) { if (F::CheckVal($_REQUEST['fields'][$oField->getFieldId()], 'text', 6, 10) && substr_count($_REQUEST['fields'][$oField->getFieldId()], '.') == 2) { list($d, $m, $y) = explode('.', $_REQUEST['fields'][$oField->getFieldId()]); if (@checkdate($m, $d, $y)) { $sText = $_REQUEST['fields'][$oField->getFieldId()]; } } } } if ($sText) { $oValue = E::GetEntity('Topic_ContentValues'); $oValue->setFieldId($oField->getFieldId()); $oValue->setFieldType($oField->getFieldType()); $oValue->setValue($sText); $oValue->setValueSource($_REQUEST['fields'][$oField->getFieldId()]); $aValues[$oField->getFieldId()] = $oValue; } } } $oTopic->setTopicValues($aValues); } } // * Рендерим шаблон для предпросмотра топика $oViewer = E::ModuleViewer()->GetLocalViewer(); $oViewer->Assign('oTopic', $oTopic); $oViewer->Assign('bPreview', true); // Alto-style template $sTemplate = 'topics/topic.show.tpl'; if (!E::ModuleViewer()->TemplateExists($sTemplate)) { // LS-style template $sTemplate = "topic_preview_{$oTopic->getType()}.tpl"; if (!E::ModuleViewer()->TemplateExists($sTemplate)) { $sTemplate = 'topic_preview_topic.tpl'; } } $sTextResult = $oViewer->Fetch($sTemplate); // * Передаем результат в ajax ответ E::ModuleViewer()->AssignAjax('sText', $sTextResult); return true; }
/** * Строит строку условий для SQL запроса топиков * * @param array $aFilter Фильтр * * @return string */ protected function buildFilter($aFilter) { $sWhere = ''; if (isset($aFilter['topic_date_more'])) { $sWhere .= " AND ((t.topic_date_show IS NOT NULL AND t.topic_date_show > " . $this->oDb->escape($aFilter['topic_date_more']) . ")"; $sWhere .= " OR (t.topic_date_show IS NULL AND t.topic_date_add > " . $this->oDb->escape($aFilter['topic_date_more']) . "))"; } if (isset($aFilter['topic_publish'])) { $sWhere .= " AND (t.topic_publish = " . ($aFilter['topic_publish'] ? 1 : 0) . ")"; $sWhere .= " AND (t.topic_date_show IS NULL OR t.topic_date_show <= '" . F::Now() . "')"; } if (isset($aFilter['topic_index_ignore'])) { $sWhere .= " AND ("; $sWhere .= "t.topic_index_ignore=" . ($aFilter['topic_index_ignore'] ? 1 : 0); if (!$aFilter['topic_index_ignore']) { $sWhere .= " OR t.topic_index_ignore IS NULL"; } $sWhere .= ") "; } if (isset($aFilter['topic_rating']) && is_array($aFilter['topic_rating'])) { $sPublishIndex = ''; if (isset($aFilter['topic_rating']['publish_index']) && $aFilter['topic_rating']['publish_index'] == 1) { $sPublishIndex = " OR topic_publish_index=1 "; } if ($aFilter['topic_rating']['type'] == 'top') { $sWhere .= " AND ( t.topic_rating >= " . (double) $aFilter['topic_rating']['value'] . " {$sPublishIndex} ) "; } else { $sWhere .= " AND ( t.topic_rating < " . (double) $aFilter['topic_rating']['value'] . " ) "; } } if (isset($aFilter['topic_new'])) { $sWhere .= " AND ("; $sWhere .= "(t.topic_date_show IS NOT NULL AND t.topic_date_show >= '" . $aFilter['topic_new'] . "' AND t.topic_date_show <='" . F::Now() . "')"; $sWhere .= " OR (t.topic_date_show IS NULL AND t.topic_date_add >= '" . $aFilter['topic_new'] . "')"; $sWhere .= ")"; } if (isset($aFilter['user_id'])) { $sWhere .= is_array($aFilter['user_id']) ? " AND t.user_id IN(" . implode(', ', $aFilter['user_id']) . ")" : " AND t.user_id = " . (int) $aFilter['user_id']; } if (isset($aFilter['blog_id'])) { if (!is_array($aFilter['blog_id'])) { $aFilter['blog_id'] = array($aFilter['blog_id']); } $sWhere .= " AND t.blog_id IN ('" . join("','", $aFilter['blog_id']) . "')"; } if (isset($aFilter['topic_id']) && is_array($aFilter['topic_id'])) { $sWhere .= " AND t.topic_id IN ('" . join("','", $aFilter['topic_id']) . "')"; } if (isset($aFilter['blog_type']) && is_array($aFilter['blog_type'])) { $aBlogTypes = array(); $aOrClauses = array(); $aFilter['blog_type'] = F::Array_FlipIntKeys($aFilter['blog_type'], 0); foreach ($aFilter['blog_type'] as $sType => $aBlogsId) { if ($aBlogsId) { // 'type'=>array('id1', 'id2') - blog type & blogs id if ($sType == '*') { $aOrClauses[] = "(t.blog_id IN ('" . join("','", $aBlogsId) . "'))"; } else { $aOrClauses[] = "b.blog_type='" . $sType . "' AND t.blog_id IN ('" . join("','", $aBlogsId) . "')"; } } else { // blog type only $aBlogTypes[] = "'" . $sType . "'"; } } if ($aBlogTypes) { $aOrClauses[] = '(b.blog_type IN (' . join(',', $aBlogTypes) . '))'; } if ($aOrClauses) { $sWhere .= ' AND (' . join(' OR ', $aOrClauses) . ')'; } } if (isset($aFilter['blog_type_exclude']) && is_array($aFilter['blog_type_exclude'])) { $sWhere .= " AND (b.blog_type NOT IN ('" . join("','", $aFilter['blog_type_exclude']) . "'))"; } if (isset($aFilter['topic_type'])) { if (!is_array($aFilter['topic_type'])) { $aFilter['topic_type'] = array($aFilter['topic_type']); } $sWhere .= " AND t.topic_type IN (" . join(",", array_map(array($this->oDb, 'escape'), $aFilter['topic_type'])) . ")"; } return $sWhere; }
/** * Получить ленту топиков по подписке * * @param array $aUserSubscribes Список подписок пользователя * @param int $iCount Число получаемых записей (если null, из конфига) * @param int $iFromId Получить записи, начиная с указанной * @param array $aFilter Дополнительные фильтры * * @return array */ public function ReadFeed($aUserSubscribes, $iCount, $iFromId, $aFilter) { $sql = "\n\t\t\t\tSELECT\n\t\t\t\t\tt.topic_id\n\t\t\t\tFROM\n\t\t\t\t\t?_topic as t,\n\t\t\t\t\t?_blog as b\n\t\t\t\tWHERE\n\t\t\t\t\tt.topic_publish = 1\n\t\t\t\t\tAND (t.topic_date_show IS NULL OR t.topic_date_show <= ?)\n\t\t\t\t\tAND t.blog_id=b.blog_id\n\t\t\t\t\t{ AND b.blog_type=? }\n\t\t\t\t\t{ AND b.blog_type IN (?a) }\n\t\t\t\t\t{ AND b.blog_type!=? }\n\t\t\t\t\t{ AND b.blog_type NOT IN (?a) }\n\t\t\t\t\t{ AND t.topic_id < ?d }\n\t\t\t\t\tAND ( 1=0 { OR t.blog_id IN (?a) } { OR t.user_id IN (?a) } )\n ORDER BY t.topic_id DESC\n { LIMIT 0, ?d }"; $aTopics = $aTopics = $this->oDb->selectCol($sql, F::Now(), isset($aFilter['include_types']) && !is_array($aFilter['include_types']) ? $aFilter['include_types'] : DBSIMPLE_SKIP, isset($aFilter['include_types']) && is_array($aFilter['include_types']) ? $aFilter['include_types'] : DBSIMPLE_SKIP, isset($aFilter['exclude_types']) && !is_array($aFilter['exclude_types']) ? $aFilter['exclude_types'] : DBSIMPLE_SKIP, isset($aFilter['exclude_types']) && is_array($aFilter['exclude_types']) ? $aFilter['exclude_types'] : DBSIMPLE_SKIP, $iFromId ? $iFromId : DBSIMPLE_SKIP, count($aUserSubscribes['blogs']) ? $aUserSubscribes['blogs'] : DBSIMPLE_SKIP, count($aUserSubscribes['users']) ? $aUserSubscribes['users'] : DBSIMPLE_SKIP, $iCount ? $iCount : DBSIMPLE_SKIP); return $aTopics; }
protected function _eventRecoverySend($sRecoveryCode) { /** @var ModuleUser_EntityReminder $oReminder */ if ($oReminder = E::ModuleUser()->GetReminderByCode($sRecoveryCode)) { /** @var ModuleUser_EntityUser $oUser */ if ($oReminder->IsValid() && ($oUser = E::ModuleUser()->GetUserById($oReminder->getUserId()))) { $sNewPassword = F::RandomStr(7); $oUser->setPassword($sNewPassword, true); if (E::ModuleUser()->Update($oUser)) { // Do logout of current user E::ModuleUser()->Logout(); // Close all sessions of this user E::ModuleUser()->CloseAllSessions($oUser); $oReminder->setDateUsed(F::Now()); $oReminder->setIsUsed(1); E::ModuleUser()->UpdateReminder($oReminder); E::ModuleNotify()->SendReminderPassword($oUser, $sNewPassword); $this->SetTemplateAction('reminder_confirm'); if (($sUrl = F::GetPost('return_url')) || ($sUrl = F::GetPost('return-path'))) { E::ModuleViewer()->Assign('return-path', $sUrl); } return true; } } } return false; }
/** * Выводит форму для редактирования профиля и обрабатывает её * */ 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')); }
/** * Универсальный метод отправки уведомлений на email * * @param ModuleUser_EntityUser|string $xUserTo Кому отправляем (пользователь или email) * @param string $sTemplate Шаблон для отправки * @param string $sSubject Тема письма * @param array $aAssign Ассоциативный массив для загрузки переменных в шаблон письма * @param string|null $sPluginName Плагин из которого происходит отправка * @param bool $bForceSend Отправлять сразу, даже при опции module.notify.delayed = true * * @return bool */ public function Send($xUserTo, $sTemplate, $sSubject, $aAssign = array(), $sPluginName = null, $bForceSend = false) { if ($xUserTo instanceof ModuleUser_EntityUser) { $sMail = $xUserTo->getMail(); $sName = $xUserTo->getLogin(); } else { $sMail = $xUserTo; $sName = ''; } /** * Передаём в шаблон переменные */ foreach ($aAssign as $sVarName => $sValue) { $this->oViewerLocal->Assign($sVarName, $sValue); } /** * Формируем шаблон */ $sTemplate = $this->sPrefix . $sTemplate; $sBody = $this->oViewerLocal->Fetch($this->GetTemplatePath($sTemplate, $sPluginName)); /** * Если в конфигураторе указан отложенный метод отправки, * то добавляем задание в массив. В противном случае, * сразу отсылаем на email */ if (Config::Get('module.notify.delayed') && !$bForceSend) { $oNotifyTask = E::GetEntity('Notify_Task', array('user_mail' => $sMail, 'user_login' => $sName, 'notify_text' => $sBody, 'notify_subject' => $sSubject, 'date_created' => F::Now(), 'notify_task_status' => self::NOTIFY_TASK_STATUS_NULL)); if (Config::Get('module.notify.insert_single')) { $this->aTask[] = $oNotifyTask; $bResult = true; } else { $bResult = $this->oMapper->AddTask($oNotifyTask); } } else { // * Отправляем e-mail E::ModuleMail()->SetAdress($sMail, $sName); E::ModuleMail()->SetSubject($sSubject); E::ModuleMail()->SetBody($sBody); E::ModuleMail()->SetHTML(); $bResult = E::ModuleMail()->Send(); } return $bResult; }
/** * Обработка редактирования топика * * @param ModuleTopic_EntityTopic $oTopic * * @return mixed */ protected function SubmitEdit($oTopic) { $oTopic->_setValidateScenario('topic'); // * Сохраняем старое значение идентификатора блога $iBlogIdOld = $oTopic->getBlogId(); // * Заполняем поля для валидации $iBlogId = F::GetRequestStr('blog_id'); // if blog_id is empty then save blog not changed if (is_numeric($iBlogId)) { $oTopic->setBlogId($iBlogId); } // issue 151 (https://github.com/altocms/altocms/issues/151) // Некорректная обработка названия блога // $oTopic->setTitle(strip_tags(F::GetRequestStr('topic_title'))); $oTopic->setTitle(E::ModuleTools()->RemoveAllTags(F::GetRequestStr('topic_title'))); $oTopic->setTextSource(F::GetRequestStr('topic_text')); if ($this->oContentType->isAllow('link')) { $oTopic->setSourceLink(F::GetRequestStr('topic_field_link')); } $oTopic->setTags(F::GetRequestStr('topic_field_tags')); $oTopic->setUserIp(F::GetUserIp()); if ($this->oUserCurrent && ($this->oUserCurrent->isAdministrator() || $this->oUserCurrent->isModerator())) { if (F::GetRequestStr('topic_url') && $oTopic->getTopicUrl() != F::GetRequestStr('topic_url')) { $sTopicUrl = E::ModuleTopic()->CorrectTopicUrl(F::TranslitUrl(F::GetRequestStr('topic_url'))); $oTopic->setTopicUrl($sTopicUrl); } } // * Проверка корректности полей формы if (!$this->checkTopicFields($oTopic)) { return false; } // * Определяем в какой блог делаем запись $nBlogId = $oTopic->getBlogId(); if ($nBlogId == 0) { $oBlog = E::ModuleBlog()->GetPersonalBlogByUserId($oTopic->getUserId()); } else { $oBlog = E::ModuleBlog()->GetBlogById($nBlogId); } // * Если блог не определен выдаем предупреждение if (!$oBlog) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_create_blog_error_unknown'), E::ModuleLang()->Get('error')); return false; } // * Проверяем права на постинг в блог if (!E::ModuleACL()->IsAllowBlog($oBlog, $this->oUserCurrent)) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_create_blog_error_noallow'), E::ModuleLang()->Get('error')); return false; } // * Проверяем разрешено ли постить топик по времени if (isPost('submit_topic_publish') && !$oTopic->getPublishDraft() && !E::ModuleACL()->CanPostTopicTime($this->oUserCurrent)) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('topic_time_limit'), E::ModuleLang()->Get('error')); return; } $oTopic->setBlogId($oBlog->getId()); // * Получаемый и устанавливаем разрезанный текст по тегу <cut> list($sTextShort, $sTextNew, $sTextCut) = E::ModuleText()->Cut($oTopic->getTextSource()); $oTopic->setCutText($sTextCut); $oTopic->setText(E::ModuleText()->Parser($sTextNew)); // Получаем ссылки, полученные при парсинге текста $oTopic->setTextLinks(E::ModuleText()->GetLinks()); $oTopic->setTextShort(E::ModuleText()->Parser($sTextShort)); // * Изменяем вопрос/ответы, только если еще никто не голосовал if ($this->oContentType->isAllow('poll') && F::GetRequestStr('topic_field_question') && F::GetRequest('topic_field_answers', array()) && $oTopic->getQuestionCountVote() == 0) { $oTopic->setQuestionTitle(strip_tags(F::GetRequestStr('topic_field_question'))); $oTopic->clearQuestionAnswer(); $aAnswers = F::GetRequest('topic_field_answers', array()); foreach ($aAnswers as $sAnswer) { $sAnswer = trim((string) $sAnswer); if ($sAnswer) { $oTopic->addQuestionAnswer($sAnswer); } } } $aPhotoSetData = E::ModuleMresource()->GetPhotosetData('photoset', $oTopic->getId()); $oTopic->setPhotosetCount($aPhotoSetData['count']); $oTopic->setPhotosetMainPhotoId($aPhotoSetData['cover']); // * Publish or save as a draft $bSendNotify = false; if (isset($_REQUEST['submit_topic_publish'])) { // If the topic has not been published then sets date of show (publication date) if (!$oTopic->getPublish() && !$oTopic->getDateShow()) { $oTopic->setDateShow(F::Now()); } $oTopic->setPublish(1); if ($oTopic->getPublishDraft() == 0) { $oTopic->setPublishDraft(1); $oTopic->setDateAdd(F::Now()); $bSendNotify = true; } } else { $oTopic->setPublish(0); } // * Принудительный вывод на главную if (E::ModuleACL()->IsAllowPublishIndex($this->oUserCurrent)) { if (F::GetRequest('topic_publish_index')) { $oTopic->setPublishIndex(1); } else { $oTopic->setPublishIndex(0); } } // * Запрет на комментарии к топику $oTopic->setForbidComment(F::GetRequest('topic_forbid_comment', 0)); // Если запрет на индексацию не устанавливался вручную, то задаем, как у блога $oBlogType = $oBlog->GetBlogType(); if ($oBlogType && !$oTopic->getIndexIgnoreLock()) { $oTopic->setTopicIndexIgnore($oBlogType->GetIndexIgnore()); } else { $oTopic->setTopicIndexIgnore(false); } $oTopic->setShowPhotoset(F::GetRequest('topic_show_photoset', 0)); E::ModuleHook()->Run('topic_edit_before', array('oTopic' => $oTopic, 'oBlog' => $oBlog)); // * Сохраняем топик if ($this->_updateTopic($oTopic)) { E::ModuleHook()->Run('topic_edit_after', array('oTopic' => $oTopic, 'oBlog' => $oBlog, 'bSendNotify' => &$bSendNotify)); // * Обновляем данные в комментариях, если топик был перенесен в новый блог if ($iBlogIdOld != $oTopic->getBlogId()) { E::ModuleComment()->UpdateTargetParentByTargetId($oTopic->getBlogId(), 'topic', $oTopic->getId()); E::ModuleComment()->UpdateTargetParentByTargetIdOnline($oTopic->getBlogId(), 'topic', $oTopic->getId()); } // * Обновляем количество топиков в блоге if ($iBlogIdOld != $oTopic->getBlogId()) { E::ModuleBlog()->RecalculateCountTopicByBlogId($iBlogIdOld); } E::ModuleBlog()->RecalculateCountTopicByBlogId($oTopic->getBlogId()); // * Добавляем событие в ленту E::ModuleStream()->Write($oTopic->getUserId(), 'add_topic', $oTopic->getId(), $oTopic->getPublish() && (!$oBlogType || !$oBlog->getBlogType()->IsPrivate())); // * Рассылаем о новом топике подписчикам блога if ($bSendNotify) { E::ModuleTopic()->SendNotifyTopicNew($oBlog, $oTopic, $oTopic->getUser()); } if (!$oTopic->getPublish() && !$this->oUserCurrent->isAdministrator() && !$this->oUserCurrent->isModerator() && $this->oUserCurrent->getId() != $oTopic->getUserId()) { R::Location($oBlog->getUrlFull()); } R::Location($oTopic->getUrl()); } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error')); F::SysWarning('System Error'); return R::Action('error'); } }
/** * Ban range of IPs * * @param string $sIp1 * @param string $sIp2 * @param string $sDate * @param bool $bUnlim * @param string $sComment * * @return bool */ public function SetBanIp($sIp1, $sIp2, $sDate, $bUnlim, $sComment) { $sql = "\n INSERT INTO ?_adminips\n (\n ip1,\n ip2,\n bandate,\n banline,\n banunlim,\n bancomment,\n banactive\n )\n VALUES (\n INET_ATON(?:ip1),\n INET_ATON(?:ip2),\n ?:bandate,\n ?:banline,\n ?:banunlim,\n ?:bancomment,\n ?:banactive\n )\n "; $nId = $this->oDb->sqlQuery($sql, array(':ip1' => $sIp1, ':ip2' => $sIp2, ':bandate' => F::Now(), ':banline' => $sDate, ':banunlim' => $bUnlim ? 1 : 0, ':bancomment' => $sComment, ':banactive' => 1)); return $nId ? $nId : false; }
/** * Добавляет коммент * * @param ModuleComment_EntityComment $oComment Объект комментария * * @return bool|ModuleComment_EntityComment */ public function AddComment(ModuleComment_EntityComment $oComment) { if (Config::Get('module.comment.use_nested')) { $nId = $this->oMapper->AddCommentTree($oComment); E::ModuleCache()->CleanByTags(array("comment_update")); } else { $nId = $this->oMapper->AddComment($oComment); } if ($nId) { if ($oComment->getTargetType() == 'topic') { E::ModuleTopic()->RecalcCountOfComments($oComment->getTargetId()); } // Освежим хранилище картинок E::ModuleMresource()->CheckTargetTextForImages($oComment->getTargetType() . '_comment', $nId, $oComment->getText()); // * Сохраняем дату последнего коммента для юзера E::User()->setDateCommentLast(F::Now()); E::ModuleUser()->Update(E::User()); // чистим зависимые кеши E::ModuleCache()->CleanByTags(array("comment_new", "comment_new_{$oComment->getTargetType()}", "comment_new_user_{$oComment->getUserId()}_{$oComment->getTargetType()}", "comment_new_{$oComment->getTargetType()}_{$oComment->getTargetId()}")); $oComment->setId($nId); return $oComment; } return false; }
/** * Обновляет коммент * * @param ModuleComment_EntityComment $oComment Объект комментария * * @return bool */ public function UpdateComment(ModuleComment_EntityComment $oComment) { $sql = "UPDATE ?_comment\n\t\t\tSET \n\t\t\t\tcomment_text= ?,\n\t\t\t\tcomment_rating= ?f,\n\t\t\t\tcomment_count_vote= ?d,\n\t\t\t\tcomment_count_favourite= ?d,\n\t\t\t\tcomment_delete = ?d ,\n\t\t\t\tcomment_publish = ?d ,\n\t\t\t\tcomment_date_edit = CASE comment_text_hash WHEN ? THEN comment_date_edit ELSE ? END,\n\t\t\t\tcomment_text_hash = ?\n\t\t\tWHERE\n\t\t\t\tcomment_id = ?d\n\t\t"; $bResult = $this->oDb->query($sql, $oComment->getText(), $oComment->getRating(), $oComment->getCountVote(), $oComment->getCountFavourite(), $oComment->getDelete(), $oComment->getPublish(), $oComment->getTextHash(), F::Now(), $oComment->getTextHash(), $oComment->getId()); return $bResult !== false; }
public function EventAjaxUserAdd() { E::ModuleViewer()->SetResponseAjax('json'); if ($this->IsPost()) { Config::Set('module.user.captcha_use_registration', false); $oUser = E::GetEntity('ModuleUser_EntityUser'); $oUser->_setValidateScenario('registration'); // * Заполняем поля (данные) $oUser->setLogin($this->GetPost('user_login')); $oUser->setMail($this->GetPost('user_mail')); $oUser->setPassword($this->GetPost('user_password')); $oUser->setPasswordConfirm($this->GetPost('user_password')); $oUser->setDateRegister(F::Now()); $oUser->setIpRegister(''); $oUser->setActivate(1); if ($oUser->_Validate()) { E::ModuleHook()->Run('registration_validate_after', array('oUser' => $oUser)); $oUser->setPassword($oUser->getPassword(), true); if (E::ModuleUser()->Add($oUser)) { E::ModuleHook()->Run('registration_after', array('oUser' => $oUser)); // Подписываем пользователя на дефолтные события в ленте активности E::ModuleStream()->SwitchUserEventDefaultTypes($oUser->getId()); if ($this->IsPost('user_setadmin')) { E::ModuleAdmin()->SetAdministrator($oUser->GetId()); } } E::ModuleMessage()->AddNoticeSingle(E::ModuleLang()->Get('registration_ok')); } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('error')); E::ModuleViewer()->AssignAjax('aErrors', $oUser->_getValidateErrors()); } } else { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error')); } }
/** * Обновляет блог * * @param ModuleBlog_EntityBlog $oBlog Блог * * @return ModuleBlog_EntityBlog|bool */ public function UpdateBlog(ModuleBlog_EntityBlog $oBlog) { $oBlog->setDateEdit(F::Now()); $bResult = $this->oMapper->UpdateBlog($oBlog); if ($bResult) { $aTags = array('blog_update', "blog_update_{$oBlog->getId()}", 'topic_update'); if ($oBlog->getOldType() && $oBlog->getOldType() != $oBlog->getType()) { // Списк авторов блога $aUsersId = $this->GetAuthorsIdByBlog($oBlog->GetId()); foreach ($aUsersId as $nUserId) { $aTags[] = 'topic_update_user_' . $nUserId; } } //чистим зависимые кеши E::ModuleCache()->CleanByTags($aTags); E::ModuleCache()->Delete("blog_{$oBlog->getId()}"); return true; } return false; }
/** * Closes all sessions of specifier user * * @param object|int $oUser * * @return bool */ public function CloseUserSessions($oUser) { if (is_object($oUser)) { $nUserId = $oUser->GetId(); } else { $nUserId = intval($oUser); } $sql = "\n UPDATE ?_session\n SET\n session_exit = ?\n WHERE user_id = ? AND (session_exit IS NULL OR session_exit = '')\n "; return $this->oDb->query($sql, F::Now(), $nUserId) !== false; }
/** * Получение новых комментариев * */ protected function AjaxResponseComment() { // * Устанавливаем формат Ajax ответа E::ModuleViewer()->SetResponseAjax('json'); // * Пользователь авторизован? if (!$this->oUserCurrent) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error')); return; } // * Топик существует? $iTopicId = intval(F::GetRequestStr('idTarget', null, 'post')); if (!$iTopicId || !($oTopic = E::ModuleTopic()->GetTopicById($iTopicId))) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error')); return; } // * Есть доступ к комментариям этого топика? Закрытый блог? if (!E::ModuleACL()->IsAllowShowBlog($oTopic->getBlog(), $this->oUserCurrent)) { E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'), E::ModuleLang()->Get('error')); return; } $idCommentLast = F::GetRequestStr('idCommentLast', null, 'post'); $selfIdComment = F::GetRequestStr('selfIdComment', null, 'post'); $aComments = array(); // * Если используется постраничность, возвращаем только добавленный комментарий if (F::GetRequest('bUsePaging', null, 'post') && $selfIdComment) { $oComment = E::ModuleComment()->GetCommentById($selfIdComment); if ($oComment && $oComment->getTargetId() == $oTopic->getId() && $oComment->getTargetType() == 'topic') { $aVars = array('oUserCurrent' => $this->oUserCurrent, 'bOneComment' => true, 'oComment' => $oComment); $sText = E::ModuleViewer()->Fetch(E::ModuleComment()->GetTemplateCommentByTarget($oTopic->getId(), 'topic')); $aCmt = array(); $aCmt[] = array('html' => $sText, 'obj' => $oComment); } else { $aCmt = array(); } $aReturn['comments'] = $aCmt; $aReturn['iMaxIdComment'] = $selfIdComment; } else { $aReturn = E::ModuleComment()->GetCommentsNewByTargetId($oTopic->getId(), 'topic', $idCommentLast); } $iMaxIdComment = $aReturn['iMaxIdComment']; /** @var ModuleTopic_EntityTopicRead $oTopicRead */ $oTopicRead = E::GetEntity('Topic_TopicRead'); $oTopicRead->setTopicId($oTopic->getId()); $oTopicRead->setUserId($this->oUserCurrent->getId()); $oTopicRead->setCommentCountLast($oTopic->getCountComment()); $oTopicRead->setCommentIdLast($iMaxIdComment); $oTopicRead->setDateRead(F::Now()); E::ModuleTopic()->SetTopicRead($oTopicRead); $aCmts = $aReturn['comments']; if ($aCmts && is_array($aCmts)) { foreach ($aCmts as $aCmt) { $aComments[] = array('html' => $aCmt['html'], 'idParent' => $aCmt['obj']->getPid(), 'id' => $aCmt['obj']->getId()); } } E::ModuleViewer()->AssignAjax('iMaxIdComment', $iMaxIdComment); E::ModuleViewer()->AssignAjax('aComments', $aComments); }
/** * Сохраняет заметку в БД, если ее нет то создает новую * * @param ModuleUser_EntityNote $oNote Объект заметки * * @return bool|ModuleUser_EntityNote */ public function SaveNote($oNote) { if (!$oNote->getDateAdd()) { $oNote->setDateAdd(F::Now()); } E::ModuleCache()->CleanByTags(array("user_note_change_by_user_{$oNote->getUserId()}")); if ($oNoteOld = $this->GetUserNote($oNote->getTargetUserId(), $oNote->getUserId())) { $oNoteOld->setText($oNote->getText()); $this->oMapper->UpdateUserNote($oNoteOld); return $oNoteOld; } else { if ($nId = $this->oMapper->AddUserNote($oNote)) { $oNote->setId($nId); return $oNote; } } return false; }
/** * Обработка 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()); } }
/** * Обновляет топик * * @param ModuleTopic_EntityTopic $oTopic Объект топика * * @return bool */ public function UpdateTopic($oTopic) { // * Получаем топик ДО изменения $oTopicOld = $this->GetTopicById($oTopic->getId()); $oTopic->setDateEdit(F::Now()); if ($this->oMapper->UpdateTopic($oTopic)) { // * Если топик изменил видимость (publish) или локацию (BlogId) или список тегов if ($oTopicOld && ($oTopic->getPublish() != $oTopicOld->getPublish() || $oTopic->getBlogId() != $oTopicOld->getBlogId() || $oTopic->getTags() != $oTopicOld->getTags())) { // * Обновляем теги $this->DeleteTopicTagsByTopicId($oTopic->getId()); if ($oTopic->getPublish() && $oTopic->getTags()) { $aTags = explode(',', $oTopic->getTags()); foreach ($aTags as $sTag) { /** @var ModuleTopic_EntityTopicTag $oTag */ $oTag = E::GetEntity('Topic_TopicTag'); $oTag->setTopicId($oTopic->getId()); $oTag->setUserId($oTopic->getUserId()); $oTag->setBlogId($oTopic->getBlogId()); $oTag->setText($sTag); $this->AddTopicTag($oTag); } } } if ($oTopicOld && $oTopic->getPublish() != $oTopicOld->getPublish()) { // * Обновляем избранное $this->SetFavouriteTopicPublish($oTopic->getId(), $oTopic->getPublish()); // * Удаляем комментарий топика из прямого эфира if ($oTopic->getPublish() == 0) { E::ModuleComment()->DeleteCommentOnlineByTargetId($oTopic->getId(), 'topic'); } // * Изменяем видимость комментов E::ModuleComment()->SetCommentsPublish($oTopic->getId(), 'topic', $oTopic->getPublish()); } if (R::GetAction() == 'content') { $this->processTopicFields($oTopic, 'update'); } $this->UpdateMresources($oTopic); // чистим зависимые кеши E::ModuleCache()->CleanByTags(array('topic_update', "topic_update_user_{$oTopic->getUserId()}")); E::ModuleCache()->Delete("topic_{$oTopic->getId()}"); return true; } return false; }
/** * Обработка подтверждения нового емайла при смене старого */ public function EventChangemailConfirmTo() { if (!($oChangemail = E::ModuleUser()->GetUserChangemailByCodeTo($this->GetParamEventMatch(1, 0)))) { return parent::EventNotFound(); } if (!$oChangemail->getConfirmFrom() || $oChangemail->getConfirmTo() || strtotime($oChangemail->getDateExpired()) < time()) { return parent::EventNotFound(); } $oChangemail->setConfirmTo(1); $oChangemail->setDateUsed(F::Now()); E::ModuleUser()->UpdateUserChangemail($oChangemail); $oUser = E::ModuleUser()->GetUserById($oChangemail->getUserId()); $oUser->setMail($oChangemail->getMailTo()); E::ModuleUser()->Update($oUser); /** * Меняем емайл в подписках */ if ($oChangemail->getMailFrom()) { E::ModuleSubscribe()->ChangeSubscribeMail($oChangemail->getMailFrom(), $oChangemail->getMailTo(), $oUser->getId()); } E::ModuleViewer()->Assign('sText', E::ModuleLang()->Get('settings_profile_mail_change_ok', array('mail' => htmlspecialchars($oChangemail->getMailTo())))); // Исправление ошибки смены email {@link https://github.com/altocms/altocms/issues/260} E::ModuleViewer()->Assign('oUserProfile', $oUser); $this->SetTemplateAction('changemail_confirm'); }