Пример #1
0
	public function AddTopic(ModuleTopic_EntityTopic $oTopic) {
		$sql = "INSERT INTO ".Config::Get('db.table.topic')." 
			(blog_id,
			user_id,
			topic_type,
			topic_title,			
			topic_tags,
			topic_date_add,
			topic_user_ip,
			topic_publish,
			topic_publish_draft,
			topic_publish_index,
			topic_cut_text,
			topic_forbid_comment,			
			topic_text_hash			
			)
			VALUES(?d,  ?d,	?,	?,	?,  ?, ?, ?d, ?d, ?d, ?, ?, ?)
		";			
		if ($iId=$this->oDb->query($sql,$oTopic->getBlogId(),$oTopic->getUserId(),$oTopic->getType(),$oTopic->getTitle(),
			$oTopic->getTags(),$oTopic->getDateAdd(),$oTopic->getUserIp(),$oTopic->getPublish(),$oTopic->getPublishDraft(),$oTopic->getPublishIndex(),$oTopic->getCutText(),$oTopic->getForbidComment(),$oTopic->getTextHash())) 
		{
			$oTopic->setId($iId);
			$this->AddTopicContent($oTopic);
			return $iId;
		}		
		return false;
	}
Пример #2
0
 /**
  * Добавляет топик
  *
  * @param ModuleTopic_EntityTopic $oTopic Объект топика
  * @return int|bool
  */
 public function AddTopic(ModuleTopic_EntityTopic $oTopic)
 {
     $sql = "INSERT INTO " . Config::Get('db.table.topic') . "\n\t\t\t(blog_id,\n\t\t\tblog_id2,\n\t\t\tblog_id3,\n\t\t\tblog_id4,\n\t\t\tblog_id5,\n\t\t\tuser_id,\n\t\t\ttopic_type,\n\t\t\ttopic_title,\t\t\t\n\t\t\ttopic_slug,\n\t\t\ttopic_tags,\n\t\t\ttopic_date_add,\n\t\t\ttopic_date_publish,\n\t\t\ttopic_user_ip,\n\t\t\ttopic_publish,\n\t\t\ttopic_publish_draft,\n\t\t\ttopic_publish_index,\n\t\t\ttopic_skip_index,\n\t\t\ttopic_cut_text,\n\t\t\ttopic_forbid_comment,\t\t\t\n\t\t\ttopic_text_hash\t\t\t\n\t\t\t)\n\t\t\tVALUES(?d, ?d, ?d, ?d, ?d, ?d,\t?,\t?,\t?,\t?,  ?, ?, ?, ?d, ?d, ?d, ?d, ?, ?, ?)\n\t\t";
     if ($iId = $this->oDb->query($sql, $oTopic->getBlogId(), $oTopic->getBlogId2(), $oTopic->getBlogId3(), $oTopic->getBlogId4(), $oTopic->getBlogId5(), $oTopic->getUserId(), $oTopic->getType(), $oTopic->getTitle(), $oTopic->getSlug(), $oTopic->getTags(), $oTopic->getDateAdd(), $oTopic->getDatePublish(), $oTopic->getUserIp(), $oTopic->getPublish(), $oTopic->getPublishDraft(), $oTopic->getPublishIndex(), $oTopic->getSkipIndex(), $oTopic->getCutText(), $oTopic->getForbidComment(), $oTopic->getTextHash())) {
         $oTopic->setId($iId);
         $this->AddTopicContent($oTopic);
         return $iId;
     }
     return false;
 }
Пример #3
0
 /**
  * Расчет рейтинга и силы при гоосовании за топик
  *
  * @param ModuleUser_EntityUser $oUser	Объект пользователя, который голосует
  * @param ModuleTopic_EntityTopic $oTopic	Объект топика
  * @param int $iValue
  * @return int
  */
 public function VoteTopic(ModuleUser_EntityUser $oUser, ModuleTopic_EntityTopic $oTopic, $iValue)
 {
     $oTopic->setRating($oTopic->getRating() + $iValue);
     $skill = $oUser->getSkill();
     $oUserTopic = $this->User_GetUserById($oTopic->getUserId());
     $iSkillNew = $oUserTopic->getSkill() + $iValue;
     $oUserTopic->setSkill($iSkillNew);
     $this->User_Update($oUserTopic);
     return $iValue;
 }
Пример #4
0
 /**
  * Добавляет топик
  *
  * @param ModuleTopic_EntityTopic $oTopic    Объект топика
  *
  * @return int|bool
  */
 public function AddTopic(ModuleTopic_EntityTopic $oTopic)
 {
     $sql = "INSERT INTO ?_topic (\n                blog_id,\n                user_id,\n                topic_type,\n                topic_title,\n                topic_tags,\n                topic_date_add,\n                topic_date_show,\n                topic_user_ip,\n                topic_publish,\n                topic_publish_draft,\n                topic_publish_index,\n                topic_cut_text,\n                topic_forbid_comment,\n                topic_text_hash,\n                topic_url,\n                topic_index_ignore\n\t\t\t)\n\t\t\tVALUES (\n                ?d:blog_id,\n                ?d:user_id,\n                ?:topic_type,\n                ?:topic_title,\n                ?:topic_tags,\n                ?:topic_date_add,\n                ?:topic_date_show,\n                ?:topic_user_ip,\n                ?d:topic_publish,\n                ?d:topic_publish_draft,\n                ?d:topic_publish_index,\n                ?:topic_cut_text,\n                ?d:topic_forbid_comment,\n                ?:topic_text_hash,\n                ?:topic_url,\n                ?d:topic_index_ignore\n\t\t\t)\n\t\t";
     $nId = $this->oDb->sqlQuery($sql, array(':blog_id' => $oTopic->getBlogId(), ':user_id' => $oTopic->getUserId(), ':topic_type' => $oTopic->getType(), ':topic_title' => $oTopic->getTitle(), ':topic_tags' => $oTopic->getTags(), ':topic_date_add' => $oTopic->getDateAdd(), ':topic_date_show' => $oTopic->getDateShow(), ':topic_user_ip' => $oTopic->getUserIp(), ':topic_publish' => $oTopic->getPublish() ? 1 : 0, ':topic_publish_draft' => $oTopic->getPublishDraft() ? 1 : 0, ':topic_publish_index' => $oTopic->getPublishIndex() ? 1 : 0, ':topic_cut_text' => $oTopic->getCutText(), ':topic_forbid_comment' => $oTopic->getForbidComment(), ':topic_text_hash' => $oTopic->getTextHash(), ':topic_url' => $oTopic->getTopicUrl(), ':topic_index_ignore' => $oTopic->getTopicIndexIgnore()));
     if ($nId) {
         $oTopic->setId($nId);
         $this->AddTopicContent($oTopic);
         return $nId;
     }
     return false;
 }
Пример #5
0
 /**
  * Расчет рейтинга и силы при гоосовании за топик
  *
  * @param ModuleUser_EntityUser $oUser Объект пользователя, который голосует
  * @param ModuleTopic_EntityTopic $oTopic Объект топика
  * @param int $iValue
  * @return int
  */
 public function VoteTopic(ModuleUser_EntityUser $oUser, ModuleTopic_EntityTopic $oTopic, $iValue)
 {
     /**
      * Устанавливаем рейтинг топика
      */
     $oTopic->setRating($oTopic->getRating() + $iValue);
     /**
      * Меняем рейтинг автора топика
      */
     $fDeltaUser = ($iValue < 0 ? -1 : 1) * Config::Get('module.rating.topic_multiplier');
     $oUserTopic = $this->User_GetUserById($oTopic->getUserId());
     $oUserTopic->setRating($oUserTopic->getRating() + $fDeltaUser);
     $this->User_Update($oUserTopic);
     return $iValue;
 }
Пример #6
0
 /**
  * Обработка дополнительных полей топика
  *
  * @param ModuleTopic_EntityTopic $oTopic
  * @param string $sType
  *
  * @return bool
  */
 public function processTopicFields($oTopic, $sType = 'add')
 {
     /** @var ModuleTopic_EntityContentValues $aValues */
     $aValues = array();
     if ($sType == 'update') {
         // * Получаем существующие значения
         if ($aData = $this->GetTopicValuesByArrayId(array($oTopic->getId()))) {
             $aValues = $aData[$oTopic->getId()];
         }
         // * Чистим существующие значения
         E::ModuleTopic()->DeleteTopicValuesByTopicId($oTopic->getId());
     }
     if ($oType = E::ModuleTopic()->GetContentTypeByUrl($oTopic->getType())) {
         //получаем поля для данного типа
         if ($aFields = $oType->getFields()) {
             foreach ($aFields as $oField) {
                 $sData = null;
                 if (isset($_REQUEST['fields'][$oField->getFieldId()]) || isset($_FILES['fields_' . $oField->getFieldId()]) || $oField->getFieldType() == 'single-image-uploader') {
                     //текстовые поля
                     if (in_array($oField->getFieldType(), array('input', 'textarea', 'select'))) {
                         $sData = E::ModuleText()->Parser($_REQUEST['fields'][$oField->getFieldId()]);
                     }
                     //поле ссылки
                     if ($oField->getFieldType() == 'link') {
                         $sData = $_REQUEST['fields'][$oField->getFieldId()];
                     }
                     //поле даты
                     if ($oField->getFieldType() == 'date') {
                         if (isset($_REQUEST['fields'][$oField->getFieldId()])) {
                             if (F::CheckVal($_REQUEST['fields'][$oField->getFieldId()], 'text', 6, 10) && substr_count($_REQUEST['fields'][$oField->getFieldId()], '.') == 2) {
                                 list($d, $m, $y) = explode('.', $_REQUEST['fields'][$oField->getFieldId()]);
                                 if (@checkdate($m, $d, $y)) {
                                     $sData = $_REQUEST['fields'][$oField->getFieldId()];
                                 }
                             }
                         }
                     }
                     //поле с файлом
                     if ($oField->getFieldType() == 'file') {
                         //если указано удаление файла
                         if (F::GetRequest('topic_delete_file_' . $oField->getFieldId())) {
                             if ($oTopic->getFieldFile($oField->getFieldId())) {
                                 @unlink(Config::Get('path.root.dir') . $oTopic->getFieldFile($oField->getFieldId())->getFileUrl());
                                 //$oTopic->setValueField($oField->getFieldId(),'');
                                 $sData = null;
                             }
                         } else {
                             //если удаление файла не указано, уже ранее залит файл^ и нового файла не загружалось
                             if ($sType == 'update' && isset($aValues[$oField->getFieldId()])) {
                                 $sData = $aValues[$oField->getFieldId()]->getValueSource();
                             }
                         }
                         if (isset($_FILES['fields_' . $oField->getFieldId()]) && is_uploaded_file($_FILES['fields_' . $oField->getFieldId()]['tmp_name'])) {
                             $iMaxFileSize = F::MemSize2Int(Config::Get('module.uploader.files.default.file_maxsize'));
                             $aFileExtensions = Config::Get('module.uploader.files.default.file_extensions');
                             if (!$iMaxFileSize || filesize($_FILES['fields_' . $oField->getFieldId()]['tmp_name']) <= $iMaxFileSize) {
                                 $aPathInfo = pathinfo($_FILES['fields_' . $oField->getFieldId()]['name']);
                                 if (!$aFileExtensions || in_array(strtolower($aPathInfo['extension']), $aFileExtensions)) {
                                     $sFileTmp = $_FILES['fields_' . $oField->getFieldId()]['tmp_name'];
                                     $sDirSave = Config::Get('path.uploads.root') . '/files/' . E::ModuleUser()->GetUserCurrent()->getId() . '/' . F::RandomStr(16);
                                     mkdir(Config::Get('path.root.dir') . $sDirSave, 0777, true);
                                     if (is_dir(Config::Get('path.root.dir') . $sDirSave)) {
                                         $sFile = $sDirSave . '/' . F::RandomStr(10) . '.' . strtolower($aPathInfo['extension']);
                                         $sFileFullPath = Config::Get('path.root.dir') . $sFile;
                                         if (copy($sFileTmp, $sFileFullPath)) {
                                             //удаляем старый файл
                                             if ($oTopic->getFieldFile($oField->getFieldId())) {
                                                 $sOldFile = Config::Get('path.root.dir') . $oTopic->getFieldFile($oField->getFieldId())->getFileUrl();
                                                 F::File_Delete($sOldFile);
                                             }
                                             $aFileObj = array();
                                             $aFileObj['file_hash'] = F::RandomStr(32);
                                             $aFileObj['file_name'] = E::ModuleText()->Parser($_FILES['fields_' . $oField->getFieldId()]['name']);
                                             $aFileObj['file_url'] = $sFile;
                                             $aFileObj['file_size'] = $_FILES['fields_' . $oField->getFieldId()]['size'];
                                             $aFileObj['file_extension'] = $aPathInfo['extension'];
                                             $aFileObj['file_downloads'] = 0;
                                             $sData = serialize($aFileObj);
                                             F::File_Delete($sFileTmp);
                                         }
                                     }
                                 } else {
                                     $sTypes = implode(', ', $aFileExtensions);
                                     E::ModuleMessage()->AddError(E::ModuleLang()->Get('topic_field_file_upload_err_type', array('types' => $sTypes)), null, true);
                                 }
                             } else {
                                 E::ModuleMessage()->AddError(E::ModuleLang()->Get('topic_field_file_upload_err_size', array('size' => $iMaxFileSize)), null, true);
                             }
                             F::File_Delete($_FILES['fields_' . $oField->getFieldId()]['tmp_name']);
                         }
                     }
                     // Поле с изображением
                     if ($oField->getFieldType() == 'single-image-uploader') {
                         $sTargetType = $oField->getFieldType() . '-' . $oField->getFieldId();
                         $iTargetId = $oTopic->getId();
                         // 1. Удалить значение target_tmp
                         // Нужно затереть временный ключ в ресурсах, что бы в дальнейшем картнка не
                         // воспринималась как временная.
                         if ($sTargetTmp = E::ModuleSession()->GetCookie(ModuleUploader::COOKIE_TARGET_TMP)) {
                             // 2. Удалить куку.
                             // Если прозошло сохранение вновь созданного топика, то нужно
                             // удалить куку временной картинки. Если же сохранялся уже существующий топик,
                             // то удаление куки ни на что влиять не будет.
                             E::ModuleSession()->DelCookie(ModuleUploader::COOKIE_TARGET_TMP);
                             // 3. Переместить фото
                             $sNewPath = E::ModuleUploader()->GetUserImageDir(E::UserId(), true, false);
                             $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, 0, E::UserId());
                             if ($aMresourceRel) {
                                 $oResource = array_shift($aMresourceRel);
                                 $sOldPath = $oResource->GetFile();
                                 $oStoredFile = E::ModuleUploader()->Store($sOldPath, $sNewPath);
                                 /** @var ModuleMresource_EntityMresource $oResource */
                                 $oResource = E::ModuleMresource()->GetMresourcesByUuid($oStoredFile->getUuid());
                                 if ($oResource) {
                                     $oResource->setUrl(E::ModuleMresource()->NormalizeUrl(E::ModuleUploader()->GetTargetUrl($sTargetType, $iTargetId)));
                                     $oResource->setType($sTargetType);
                                     $oResource->setUserId(E::UserId());
                                     // 4. В свойство поля записать адрес картинки
                                     $sData = $oResource->getMresourceId();
                                     $oResource = array($oResource);
                                     E::ModuleMresource()->UnlinkFile($sTargetType, 0, $oTopic->getUserId());
                                     E::ModuleMresource()->AddTargetRel($oResource, $sTargetType, $iTargetId);
                                 }
                             }
                         } else {
                             // Топик редактируется, просто обновим поле
                             $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, $iTargetId, E::UserId());
                             if ($aMresourceRel) {
                                 $oResource = array_shift($aMresourceRel);
                                 $sData = $oResource->getMresourceId();
                             } else {
                                 $sData = false;
                                 //                                    $this->DeleteField($oField);
                             }
                         }
                     }
                     E::ModuleHook()->Run('content_field_proccess', array('sData' => &$sData, 'oField' => $oField, 'oTopic' => $oTopic, 'aValues' => $aValues, 'sType' => &$sType));
                     //Добавляем поле к топику.
                     if ($sData) {
                         /** @var ModuleTopic_EntityContentValues $oValue */
                         $oValue = E::GetEntity('Topic_ContentValues');
                         $oValue->setTargetId($oTopic->getId());
                         $oValue->setTargetType('topic');
                         $oValue->setFieldId($oField->getFieldId());
                         $oValue->setFieldType($oField->getFieldType());
                         $oValue->setValue($sData);
                         $oValue->setValueSource(in_array($oField->getFieldType(), array('file', 'single-image-uploader')) ? $sData : $_REQUEST['fields'][$oField->getFieldId()]);
                         $this->AddTopicValue($oValue);
                     }
                 }
             }
         }
     }
     return true;
 }
Пример #7
0
 /**
  * Формирует и возвращает полный ЧПУ URL для топика
  *
  * @param ModuleTopic_EntityTopic $oTopic
  * @param bool $bAbsolute При false вернет относительный УРЛ
  * @return string
  */
 public function BuildUrlForTopic($oTopic, $bAbsolute = true)
 {
     $sUrlMask = Config::Get('module.topic.url');
     $iDateCreate = strtotime($oTopic->getDatePublish());
     $aReplace = array('%year%' => date("Y", $iDateCreate), '%month%' => date("m", $iDateCreate), '%day%' => date("d", $iDateCreate), '%hour%' => date("H", $iDateCreate), '%minute%' => date("i", $iDateCreate), '%second%' => date("s", $iDateCreate), '%login%' => '', '%blog%' => '', '%id%' => $oTopic->getId(), '%title%' => $oTopic->getSlug(), '%type%' => $oTopic->getType());
     /**
      * Получаем связанные данные только если в этом есть необходимость
      */
     if (strpos($sUrlMask, '%blog%') !== false) {
         if (!($oBlog = $oTopic->GetBlog())) {
             $oBlog = $this->Blog_GetBlogById($oTopic->getBlogId());
         }
         if ($oBlog) {
             if ($oBlog->getType() == 'personal') {
                 $sUrlMask = str_replace('%blog%', '%login%', $sUrlMask);
             } else {
                 $aReplace['%blog%'] = $oBlog->getUrl();
             }
         }
     }
     if (strpos($sUrlMask, '%login%') !== false) {
         if (!($oUser = $oTopic->GetUser())) {
             $oUser = $this->User_GetUserById($oTopic->getUserId());
         }
         if ($oUser) {
             $aReplace['%login%'] = $oUser->getLogin();
         }
     }
     $sUrl = strtr($sUrlMask, $aReplace);
     return $bAbsolute ? Router::GetPathRootWeb() . '/' . $sUrl : $sUrl;
 }
Пример #8
0
 /**
  * Удаляет топик.
  * Если тип таблиц в БД InnoDB, то удалятся всё связи по топику(комменты,голосования,избранное)
  *
  * @param ModuleTopic_EntityTopic|int $oTopicId Объект топика или ID
  * @return bool
  */
 public function DeleteTopic($oTopicId)
 {
     if ($oTopicId instanceof ModuleTopic_EntityTopic) {
         $sTopicId = $oTopicId->getId();
         $this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array("topic_update_user_{$oTopicId->getUserId()}"));
     } else {
         $sTopicId = $oTopicId;
     }
     /**
      * Чистим зависимые кеши
      */
     $this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('topic_update'));
     $this->Cache_Delete("topic_{$sTopicId}");
     /**
      * Список изображений
      */
     $aPhotos = $this->getPhotosByTopicId($sTopicId);
     /**
      * Если топик успешно удален, удаляем связанные данные
      */
     if ($bResult = $this->oMapperTopic->DeleteTopic($sTopicId)) {
         return $this->DeleteTopicAdditionalData($sTopicId, $aPhotos);
     }
     return false;
 }
Пример #9
0
 /**
  * Расчет рейтинга и силы при гоосовании за топик
  *
  * @param ModuleUser_EntityUser   $oUser     Объект пользователя, который голосует
  * @param ModuleTopic_EntityTopic $oTopic    Объект топика
  * @param int                     $iValue
  *
  * @return int
  */
 public function VoteTopic($oUser, $oTopic, $iValue)
 {
     $iDeltaRating = 0;
     $skill = $oUser->getSkill();
     if (C::Get('plugin.rating.topic.vote') && (C::Get('plugin.rating.topic.dislike') || !C::Get('plugin.rating.topic.dislike') && $iValue > 0)) {
         /**
          * Устанавливаем рейтинг топика
          */
         $iDeltaRating = $iValue * C::Get('plugin.rating.rating.topic_k1');
         //1
         if ($skill >= C::Get('plugin.rating.rating.topic_border_1') and $skill < C::Get('plugin.rating.rating.topic_border_2')) {
             // 100-250
             $iDeltaRating = $iValue * C::Get('plugin.rating.rating.topic_k2');
             //2
         } elseif ($skill >= C::Get('plugin.rating.rating.topic_border_2') and $skill < C::Get('plugin.rating.rating.topic_border_3')) {
             //250-400
             $iDeltaRating = $iValue * C::Get('plugin.rating.rating.topic_k3');
             //3
         } elseif ($skill >= C::Get('plugin.rating.rating.topic_border_3')) {
             //400
             $iDeltaRating = $iValue * C::Get('plugin.rating.rating.topic_k4');
             //4
         }
         $oTopic->setRating($oTopic->getRating() + $iDeltaRating);
     }
     if (C::Get('plugin.rating.rating.vote') && (C::Get('plugin.rating.topic.dislike') || !C::Get('plugin.rating.topic.dislike') && $iValue > 0)) {
         /**
          * Начисляем силу и рейтинг автору топика, используя логарифмическое распределение
          */
         $iMinSize = C::Get('plugin.rating.topic.min_change');
         //0.1;
         $iMaxSize = C::Get('plugin.rating.topic.max_change');
         //8;
         $iSizeRange = $iMaxSize - $iMinSize;
         $iMinCount = log(0 + 1);
         $iMaxCount = log(C::Get('plugin.rating.topic.max_rating') + 1);
         $iCountRange = $iMaxCount - $iMinCount;
         if ($iCountRange == 0) {
             $iCountRange = 1;
         }
         if ($skill > C::Get('plugin.rating.topic.left_border') and $skill < C::Get('plugin.rating.topic.right_border')) {
             //200
             $skill_new = $skill / C::Get('plugin.rating.topic.mid_divider');
             //70;
         } elseif ($skill >= C::Get('plugin.rating.topic.right_border')) {
             //200
             $skill_new = $skill / C::Get('plugin.rating.topic.right_divider');
             //10;
         } else {
             $skill_new = $skill / C::Get('plugin.rating.topic.left_divider');
             //100;
         }
         $iDelta = $iMinSize + (log($skill_new + 1) - $iMinCount) * ($iSizeRange / $iCountRange);
         /**
          * Сохраняем силу и рейтинг
          */
         $oUserTopic = $this->User_GetUserById($oTopic->getUserId());
         $iSkillNew = $oUserTopic->getSkill() + $iValue * $iDelta;
         $iSkillNew = $iSkillNew < 0 ? 0 : $iSkillNew;
         $oUserTopic->setSkill($iSkillNew);
         $oUserTopic->setRating($oUserTopic->getRating() + $iValue * $iDelta / C::Get('plugin.rating.topic.auth_coef'));
         //2.73
         $this->User_Update($oUserTopic);
     }
     if ($skill > C::Get('plugin.rating.topic.left_border') and $skill < C::Get('plugin.rating.topic.right_border')) {
         //200
         $skill_new = $skill / C::Get('plugin.rating.topic.mid_divider');
         //70;
     } elseif ($skill >= C::Get('plugin.rating.topic.right_border')) {
         //200
         $skill_new = $skill / C::Get('plugin.rating.topic.right_divider');
         //10;
     } else {
         $skill_new = $skill / C::Get('plugin.rating.topic.left_divider');
         //100;
     }
     $iDelta = $iMinSize + (log($skill_new + 1) - $iMinCount) * ($iSizeRange / $iCountRange);
     /**
      * Сохраняем силу и рейтинг
      */
     $oUserTopic = $this->User_GetUserById($oTopic->getUserId());
     $iSkillNew = $oUserTopic->getSkill() + $iValue * $iDelta;
     $iSkillNew = $iSkillNew < 0 ? 0 : $iSkillNew;
     $oUserTopic->setSkill($iSkillNew);
     $oUserTopic->setRating($oUserTopic->getRating() + $iValue * $iDelta / C::Get('plugin.rating.topic.auth_coef'));
     //2.73
     $this->User_Update($oUserTopic);
     return $iDeltaRating;
 }
Пример #10
0
 /**
  * Расчет рейтинга и силы при гоосовании за топик
  *
  * @param ModuleUser_EntityUser $oUser Объект пользователя, который голосует
  * @param ModuleTopic_EntityTopic $oTopic Объект топика
  * @param int $iValue
  *
  * @return int
  */
 public function VoteTopic($oUser, $oTopic, $iValue)
 {
     if (!C::Get('plugin.simplerating.topic.vote')) {
         return 0;
     }
     if (!C::Get('plugin.simplerating.topic.dislike') && $iValue < 0) {
         return 0;
     }
     /**
      * Устанавливаем рейтинг топика
      */
     if (C::Get('plugin.simplerating.topic.add')) {
         $oTopic->setRating((double) $oTopic->getRating() + $iValue * (double) C::Get('plugin.simplerating.topic.add'));
     }
     /**
      * Устанавливаем рейтинг автора
      */
     if (C::Get('plugin.simplerating.topic.user_add')) {
         $oUserTopic = $this->User_GetUserById($oTopic->getUserId());
         $oUserTopic->setRating((double) $oUserTopic->getRating() + $iValue * (double) C::Get('plugin.simplerating.topic.user_add'));
         $this->User_Update($oUserTopic);
     }
     /**
      * Убавляем рейтинг голосующего, если нужно
      */
     if (C::Get('plugin.simplerating.topic.user_remove')) {
         $oUser->setRating((double) $oUser->getRating() + (double) C::Get('plugin.simplerating.topic.user_remove'));
         $this->User_Update($oUser);
     }
     return (double) C::Get('plugin.simplerating.topic.add');
 }
Пример #11
0
 /**
  * Проверяет можно или нет пользователю удалять данный топик
  *
  * @param ModuleTopic_EntityTopic $oTopic    Топик
  * @param ModuleUser_EntityUser   $oUser     Пользователь
  *
  * @return bool
  */
 public function IsAllowDeleteTopic($oTopic, $oUser)
 {
     if (!$oTopic || !$oUser) {
         return false;
     }
     // * Разрешаем если это админ сайта или автор топика
     if ($oTopic->getUserId() == $oUser->getId() || $oUser->isAdministrator() || $oUser->isModerator()) {
         return true;
     }
     // * Если владелец блога
     if ($oTopic->getBlog()->getOwnerId() == $oUser->getId()) {
         return true;
     }
     // Проверяем права
     return $this->CheckBlogDeleteContent($oTopic->getBlog(), $oUser);
 }
Пример #12
0
 /**
  * Show topic
  *
  * @return string|null
  */
 protected function EventShowTopic()
 {
     $this->sMenuHeadItemSelect = 'index';
     $sBlogUrl = '';
     $sTopicUrlMask = R::GetTopicUrlMask();
     if ($this->oCurrentTopic) {
         $this->oCurrentBlog = $this->oCurrentTopic->getBlog();
         if ($this->oCurrentBlog) {
             $sBlogUrl = $this->oCurrentBlog->getUrl();
         }
         $this->sMenuItemSelect = 'blog';
     } else {
         if ($this->GetParamEventMatch(0, 1)) {
             // из коллективного блога
             $sBlogUrl = $this->sCurrentEvent;
             $iTopicId = $this->GetParamEventMatch(0, 1);
             $this->sMenuItemSelect = 'blog';
         } else {
             // из персонального блога
             $iTopicId = $this->GetEventMatch(1);
             $this->sMenuItemSelect = 'log';
         }
         // * Проверяем есть ли такой топик
         if (!$iTopicId || !($this->oCurrentTopic = E::ModuleTopic()->GetTopicById($iTopicId))) {
             return parent::EventNotFound();
         }
     }
     if (!$this->oCurrentTopic->getBlog()) {
         // Этого быть не должно, но если вдруг, то надо отработать
         return parent::EventNotFound();
     }
     $this->sMenuSubItemSelect = '';
     // Trusted user is admin or owner of topic
     if ($this->oUserCurrent && ($this->oUserCurrent->isAdministrator() || $this->oUserCurrent->isModerator() || $this->oUserCurrent->getId() == $this->oCurrentTopic->getUserId())) {
         $bTrustedUser = true;
     } else {
         $bTrustedUser = false;
     }
     if (!$bTrustedUser) {
         // Topic with future date
         if ($this->oCurrentTopic->getDate() > date('Y-m-d H:i:s')) {
             return parent::EventNotFound();
         }
         // * Проверяем права на просмотр топика-черновика
         if (!$this->oCurrentTopic->getPublish()) {
             if (!Config::Get('module.topic.draft_link')) {
                 return parent::EventNotFound();
             } else {
                 // Если режим просмотра по прямой ссылке включен, то проверяем параметры
                 $bOk = false;
                 if ($sDraftCode = F::GetRequestStr('draft', null, 'get')) {
                     if (strpos($sDraftCode, ':')) {
                         list($nUser, $sHash) = explode(':', $sDraftCode);
                         if ($this->oCurrentTopic->GetUserId() == $nUser && $this->oCurrentTopic->getTextHash() == $sHash) {
                             $bOk = true;
                         }
                     }
                 }
                 if (!$bOk) {
                     return parent::EventNotFound();
                 }
             }
         }
     }
     // Если номер топика правильный, но URL блога неверный, то корректируем его и перенаправляем на нужный адрес
     if ($sBlogUrl !== '' && $this->oCurrentTopic->getBlog()->getUrl() !== $sBlogUrl) {
         R::Location($this->oCurrentTopic->getUrl());
     }
     // Если запросили топик с определенной маской, не указаным названием блога,
     // но ссылка на топик и ЧПУ url разные, и это не запрос RSS
     // то перенаправляем на страницу для вывода топика (во избежание дублирования контента по разным URL)
     if ($sTopicUrlMask && $sBlogUrl == '' && $this->oCurrentTopic->getUrl() != R::GetPathWebCurrent() . (substr($this->oCurrentTopic->getUrl(), -1) === '/' ? '/' : '') && substr(R::RealUrl(true), 0, 4) !== 'rss/') {
         R::Location($this->oCurrentTopic->getUrl());
     }
     // Checks rights to show content from the blog
     if (!$this->oCurrentTopic->getBlog()->CanReadBy($this->oUserCurrent)) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('acl_cannot_show_content'), E::ModuleLang()->Get('not_access'));
         return R::Action('error');
     }
     // Обрабатываем добавление коммента
     if (isset($_REQUEST['submit_comment'])) {
         $this->SubmitComment();
     }
     // Достаём комменты к топику
     if (!Config::Get('module.comment.nested_page_reverse') && Config::Get('module.comment.use_nested') && Config::Get('module.comment.nested_per_page')) {
         $iPageDef = ceil(E::ModuleComment()->GetCountCommentsRootByTargetId($this->oCurrentTopic->getId(), 'topic') / Config::Get('module.comment.nested_per_page'));
     } else {
         $iPageDef = 1;
     }
     $iPage = intval(F::GetRequest('cmtpage', 0));
     if ($iPage < 1) {
         $iPage = $iPageDef;
     }
     $aReturn = E::ModuleComment()->GetCommentsByTargetId($this->oCurrentTopic, 'topic', $iPage, Config::Get('module.comment.nested_per_page'));
     $iMaxIdComment = $aReturn['iMaxIdComment'];
     /** @var ModuleComment_EntityComment[] $aComments */
     $aComments = $aReturn['comments'];
     if ($aComments && $iMaxIdComment && isset($aComments[$iMaxIdComment])) {
         $sLastCommentDate = $aComments[$iMaxIdComment]->getDate();
     } else {
         $sLastCommentDate = null;
     }
     // Если используется постраничность для комментариев - формируем ее
     if (Config::Get('module.comment.use_nested') && Config::Get('module.comment.nested_per_page')) {
         $aPaging = E::ModuleViewer()->MakePaging($aReturn['count'], $iPage, Config::Get('module.comment.nested_per_page'), Config::Get('pagination.pages.count'), '');
         if (!Config::Get('module.comment.nested_page_reverse') && $aPaging) {
             // переворачиваем страницы в обратном порядке
             $aPaging['aPagesLeft'] = array_reverse($aPaging['aPagesLeft']);
             $aPaging['aPagesRight'] = array_reverse($aPaging['aPagesRight']);
         }
         E::ModuleViewer()->Assign('aPagingCmt', $aPaging);
     }
     //      issue 253 {@link https://github.com/altocms/altocms/issues/253}
     //      Запрещаем оставлять комментарии к топику-черновику
     //      if ($this->oUserCurrent) {
     if ($this->oUserCurrent && (int) $this->oCurrentTopic->getPublish()) {
         $bAllowToComment = E::ModuleBlog()->GetBlogsAllowTo('comment', $this->oUserCurrent, $this->oCurrentTopic->getBlog()->GetId(), true);
     } else {
         $bAllowToComment = false;
     }
     // Отмечаем прочтение топика
     if ($this->oUserCurrent) {
         $oTopicRead = E::ModuleTopic()->GetTopicRead($this->oCurrentTopic->getId(), $this->oUserCurrent->getid());
         if (!$oTopicRead) {
             /** @var ModuleTopic_EntityTopicRead $oTopicRead */
             $oTopicRead = E::GetEntity('Topic_TopicRead');
             $oTopicRead->setTopicId($this->oCurrentTopic->getId());
             $oTopicRead->setUserId($this->oUserCurrent->getId());
             $oTopicRead->setCommentCountLast($this->oCurrentTopic->getCountComment());
             $oTopicRead->setCommentIdLast($iMaxIdComment);
             $oTopicRead->setDateRead(F::Now());
             E::ModuleTopic()->AddTopicRead($oTopicRead);
         } else {
             if ($oTopicRead->getCommentCountLast() != $this->oCurrentTopic->getCountComment() || $oTopicRead->getCommentIdLast() != $iMaxIdComment || !is_null($sLastCommentDate) && $oTopicRead->getDateRead() <= $sLastCommentDate) {
                 $oTopicRead->setCommentCountLast($this->oCurrentTopic->getCountComment());
                 $oTopicRead->setCommentIdLast($iMaxIdComment);
                 $oTopicRead->setDateRead(F::Now());
                 E::ModuleTopic()->UpdateTopicRead($oTopicRead);
             }
         }
     }
     // Выставляем SEO данные
     $sTextSeo = strip_tags($this->oCurrentTopic->getText());
     E::ModuleViewer()->SetHtmlDescription(F::CutText($sTextSeo, Config::Get('view.html.description_max_words')));
     E::ModuleViewer()->SetHtmlKeywords($this->oCurrentTopic->getTags());
     E::ModuleViewer()->SetHtmlCanonical($this->oCurrentTopic->getUrl());
     // Вызов хуков
     E::ModuleHook()->Run('topic_show', array('oTopic' => $this->oCurrentTopic));
     // Загружаем переменные в шаблон
     E::ModuleViewer()->Assign('oTopic', $this->oCurrentTopic);
     E::ModuleViewer()->Assign('aComments', $aComments);
     E::ModuleViewer()->Assign('iMaxIdComment', $iMaxIdComment);
     E::ModuleViewer()->Assign('bAllowToComment', $bAllowToComment);
     // Устанавливаем title страницы
     E::ModuleViewer()->AddHtmlTitle($this->oCurrentTopic->getBlog()->getTitle());
     E::ModuleViewer()->AddHtmlTitle($this->oCurrentTopic->getTitle());
     E::ModuleViewer()->SetHtmlRssAlternate(R::GetPath('rss') . 'comments/' . $this->oCurrentTopic->getId() . '/', $this->oCurrentTopic->getTitle());
     // Устанавливаем шаблон вывода
     $this->SetTemplateAction('topic');
     // Additional tags for <head>
     $aHeadTags = $this->_getHeadTags($this->oCurrentTopic);
     if ($aHeadTags) {
         E::ModuleViewer()->SetHtmlHeadTags($aHeadTags);
     }
     return null;
 }
Пример #13
0
 /**
  * Расчет рейтинга и силы при гоосовании за топик
  *
  * @param ModuleUser_EntityUser $oUser Объект пользователя, который голосует
  * @param ModuleTopic_EntityTopic $oTopic Объект топика
  * @param int $iValue
  * @return int
  */
 public function VoteTopic(ModuleUser_EntityUser $oUser, ModuleTopic_EntityTopic $oTopic, $iValue)
 {
     $skill = $oUser->getSkill();
     /**
      * Устанавливаем рейтинг топика
      */
     $iDeltaRating = $iValue;
     if ($skill >= 100 and $skill < 250) {
         $iDeltaRating = $iValue * 2;
     } elseif ($skill >= 250 and $skill < 400) {
         $iDeltaRating = $iValue * 3;
     } elseif ($skill >= 400) {
         $iDeltaRating = $iValue * 4;
     }
     $oTopic->setRating($oTopic->getRating() + $iDeltaRating);
     /**
      * Начисляем силу и рейтинг автору топика, используя логарифмическое распределение
      */
     $iMinSize = 0.1;
     $iMaxSize = 8;
     $iSizeRange = $iMaxSize - $iMinSize;
     $iMinCount = log(0 + 1);
     $iMaxCount = log(500 + 1);
     $iCountRange = $iMaxCount - $iMinCount;
     if ($iCountRange == 0) {
         $iCountRange = 1;
     }
     if ($skill > 50 and $skill < 200) {
         $skill_new = $skill / 70;
     } elseif ($skill >= 200) {
         $skill_new = $skill / 10;
     } else {
         $skill_new = $skill / 100;
     }
     $iDelta = $iMinSize + (log($skill_new + 1) - $iMinCount) * ($iSizeRange / $iCountRange);
     /**
      * Сохраняем силу и рейтинг
      */
     $oUserTopic = $this->User_GetUserById($oTopic->getUserId());
     $iSkillNew = $oUserTopic->getSkill() + $iValue * $iDelta;
     $iSkillNew = $iSkillNew < 0 ? 0 : $iSkillNew;
     $oUserTopic->setSkill($iSkillNew);
     $oUserTopic->setRating($oUserTopic->getRating() + $iValue * $iDelta / 2.73);
     $this->User_Update($oUserTopic);
     return $iDeltaRating;
 }
Пример #14
0
 /**
  * Проверяет можно или нет пользователю удалять данный топик
  *
  * @param ModuleTopic_EntityTopic $oTopic	Топик
  * @param ModuleUser_EntityUser $oUser	Пользователь
  * @return bool
  */
 public function IsAllowDeleteTopic($oTopic, $oUser)
 {
     /**
      * Разрешаем если это админ сайта или автор топика
      */
     if ($oTopic->getUserId() == $oUser->getId() or $oUser->isAdministrator()) {
         return true;
     }
     /**
      * Если автор(смотритель) блога
      */
     if ($oTopic->getBlog()->getOwnerId() == $oUser->getId()) {
         return true;
     }
     /**
      * Если модер или админ блога
      */
     if ($this->User_GetUserCurrent() and $this->User_GetUserCurrent()->getId() == $oUser->getId()) {
         /**
          * Для авторизованного пользователя данный код будет работать быстрее
          */
         if ($oTopic->getBlog()->getUserIsAdministrator() or $oTopic->getBlog()->getUserIsModerator()) {
             return true;
         }
     } else {
         $oBlogUser = $this->Blog_GetBlogUserByBlogIdAndUserId($oTopic->getBlogId(), $oUser->getId());
         if ($oBlogUser and ($oBlogUser->getIsModerator() or $oBlogUser->getIsAdministrator())) {
             return true;
         }
     }
     return false;
 }
Пример #15
0
 /**
  * Проверяет можно или нет пользователю удалять данный топик
  *
  * @param ModuleTopic_EntityTopic $oTopic Топик
  * @param ModuleUser_EntityUser $oUser Пользователь
  * @return bool
  */
 public function IsAllowDeleteTopic($oTopic, $oUser)
 {
     $that = $this;
     // fix for PHP < 5.4
     return $this->Rbac_IsAllowUser($oUser, 'remove_topic', array('callback' => function ($oUser, $aParams) use($that, $oTopic) {
         if (!$oUser) {
             return false;
         }
         /**
          * Разрешаем если это админ сайта или автор топика
          */
         if ($oTopic->getUserId() == $oUser->getId() or $oUser->isAdministrator()) {
             return true;
         }
         /**
          * Если автор(смотритель) блога
          */
         if ($oTopic->getBlog()->getOwnerId() == $oUser->getId()) {
             return true;
         }
         /**
          * Если модер или админ блога
          */
         if ($that->User_GetUserCurrent() and $that->User_GetUserCurrent()->getId() == $oUser->getId()) {
             /**
              * Для авторизованного пользователя данный код будет работать быстрее
              */
             if ($oTopic->getBlog()->getUserIsAdministrator() or $oTopic->getBlog()->getUserIsModerator()) {
                 return true;
             }
         } else {
             $oBlogUser = $that->Blog_GetBlogUserByBlogIdAndUserId($oTopic->getBlogId(), $oUser->getId());
             if ($oBlogUser and ($oBlogUser->getIsModerator() or $oBlogUser->getIsAdministrator())) {
                 return true;
             }
         }
         return false;
     }));
 }