/**
  * Добавление записи на стену
  */
 public function EventWallAdd()
 {
     // * Устанавливаем формат Ajax ответа
     E::ModuleViewer()->SetResponseAjax('json');
     // * Пользователь авторизован?
     if (!E::IsUser()) {
         return parent::EventNotFound();
     }
     $xResult = E::Module('PluginMagicrules\\Rule')->CheckRuleAction('create_wall', E::User());
     if ($xResult === true) {
         return parent::EventWallAdd();
     } else {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('plugin.magicrules.check_rule_action_error'), E::ModuleLang()->Get('attention'));
         return Router::Action('error');
     }
 }
Esempio n. 2
0
 public function CodeHook()
 {
     // Если пользоватль авторизован и у него не заполнено поле о себе, то
     if (E::IsUser() && trim(E::User()->getProfileAbout()) == '') {
         // Получим меню пользователя
         /** @var ModuleMenu_EntityMenu $oMenu */
         $oMenu = E::ModuleMenu()->GetMenu('user');
         // Проверим, может в этой теме меню не объектное
         if ($oMenu && !$oMenu->GetItemById('plugin_menutest_my_menu')) {
             // Создадим элемент меню
             $oMenuItem = E::ModuleMenu()->CreateMenuItem('plugin_menutest_my_menu', array('text' => '{{plugin.menutest.empty_about}}', 'link' => E::User()->getProfileUrl() . 'settings/', 'display' => array('not_event' => array('settings')), 'options' => array('class' => 'btn right create')));
             // Добавим в меню
             $oMenu->AddItem('first', $oMenuItem);
             // Сохраним
             E::ModuleMenu()->SaveMenu($oMenu);
         }
     }
 }
 /**
  * @return string|void
  */
 protected function EventVoteUser()
 {
     // * Пользователь авторизован?
     if (!E::IsUser()) {
         E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('need_authorization'), E::ModuleLang()->Get('error'));
         return;
     }
     $xResult = E::Module('PluginMagicrules\\Rule')->CheckRuleAction('vote_user', E::User(), array('vote_value' => (int) $this->getPost('value')));
     if (true === $xResult) {
         return parent::EventVoteUser();
     } else {
         if (is_string($xResult)) {
             E::ModuleMessage()->AddErrorSingle($xResult, E::ModuleLang()->Get('attention'));
             return Router::Action('error');
         } else {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('plugin.magicrules.check_rule_action_error'), E::ModuleLang()->Get('attention'));
             return Router::Action('error');
         }
     }
 }
Esempio n. 4
0
 /**
  * Метод, который вызывается после создания меню
  */
 public function CodeHook()
 {
     // Получим результат выполнения метода-источника хука
     /** @var ModuleMenu_EntityMenu $oMenu */
     $oMenu = $this->GetSourceResult();
     // Убеждаемся, что было создано нужное нам меню - меню пользователя
     if ($oMenu && $oMenu->getId() == 'user') {
         // Если пользователь авторизован и у него не заполнено поле о себе, то
         if (E::IsUser() && trim(E::User()->getProfileAbout()) == '') {
             // Проверим, есть ли в меню нужный элемент
             if (!$oMenu->GetItemById('plugin.menutest.my_menu')) {
                 // Создадим элемент меню
                 $oMenuItem = E::ModuleMenu()->CreateMenuItem('plugin.menutest.my_menu', array('text' => '{{plugin.menutest.empty_about}}', 'link' => E::User()->getProfileUrl() . 'settings/', 'display' => array('not_event' => array('settings')), 'options' => array('class' => 'btn right create')));
                 // Добавим в меню
                 $oMenu->AddItem($oMenuItem, 'first');
                 // Сохраним
                 E::ModuleMenu()->SaveMenu($oMenu);
             }
         }
     }
 }
Esempio n. 5
0
 /**
  * Return filter for topic list by name and params
  *
  * @param string $sFilterName
  * @param array  $aParams
  *
  * @return array
  */
 public function GetNamedFilter($sFilterName, $aParams = array())
 {
     $aFilter = $this->GetTopicsFilter();
     switch ($sFilterName) {
         case 'good':
             // Filter for good topics
             $aFilter['topic_rating'] = array('value' => empty($aParams['rating']) ? 0 : intval($aParams['rating']), 'type' => 'top', 'publish_index' => 1);
             break;
         case 'bad':
             // Filter for good topics
             $aFilter['topic_rating'] = array('value' => empty($aParams['rating']) ? 0 : intval($aParams['rating']), 'type' => 'down', 'publish_index' => 1);
             break;
         case 'new':
             // Filter for new topics
             $sDate = date('Y-m-d H:00:00', time() - Config::Get('module.topic.new_time'));
             $aFilter['topic_new'] = $sDate;
             break;
         case 'new_all':
             // Filter for ALL new topics
             // Nothing others
             break;
         case 'discussed':
             //
             if (!empty($aParams['period'])) {
                 if (is_numeric($aParams['period'])) {
                     // количество последних секунд
                     $sPeriod = date('Y-m-d H:00:00', time() - intval($aParams['period']));
                 } else {
                     $sPeriod = $aParams['period'];
                 }
                 $aFilter['topic_date_more'] = $sPeriod;
             }
             if (!isset($aFilter['order'])) {
                 $aFilter['order'] = array();
             }
             $aFilter['order'][] = 't.topic_count_comment DESC';
             $aFilter['order'][] = 't.topic_date_show DESC';
             $aFilter['order'][] = 't.topic_id DESC';
             break;
         case 'top':
             if (!empty($aParams['period'])) {
                 if (is_numeric($aParams['period'])) {
                     // количество последних секунд
                     $sPeriod = date('Y-m-d H:00:00', time() - intval($aParams['period']));
                 } else {
                     $sPeriod = $aParams['period'];
                 }
                 $aFilter['topic_date_more'] = $sPeriod;
             }
             if (!isset($aFilter['order'])) {
                 $aFilter['order'] = array();
             }
             $aFilter['order'][] = 't.topic_rating DESC';
             $aFilter['order'][] = 't.topic_date_show DESC';
             $aFilter['order'][] = 't.topic_id DESC';
             break;
         default:
             // Nothing others
     }
     if (!empty($aParams['blog_id'])) {
         $aFilter['blog_id'] = intval($aParams['blog_id']);
     } else {
         $aFilter['blog_type'] = empty($aParams['personal']) ? E::ModuleBlog()->GetOpenBlogTypes() : 'personal';
         // If a user is authorized then adds blogs on which it is subscribed
         if (E::IsUser() && !empty($aParams['accessible']) && empty($aParams['personal'])) {
             $aOpenBlogs = E::ModuleBlog()->GetAccessibleBlogsByUser(E::User());
             if (count($aOpenBlogs)) {
                 $aFilter['blog_type']['*'] = $aOpenBlogs;
             }
         }
     }
     if (isset($aParams['personal']) && $aParams['personal'] === false && $aFilter['blog_type'] && is_array($aFilter['blog_type'])) {
         if (false !== ($iKey = array_search('personal', $aFilter['blog_type']))) {
             unset($aFilter['blog_type'][$iKey]);
         }
     }
     if (!empty($aParams['topic_type'])) {
         $aFilter['topic_type'] = $aParams['topic_type'];
     }
     if (!empty($aParams['user_id'])) {
         $aFilter['user_id'] = $aParams['user_id'];
     }
     if (isset($aParams['topic_published'])) {
         $aFilter['topic_publish'] = $aParams['topic_published'] ? 1 : 0;
     }
     return $aFilter;
 }
Esempio n. 6
0
/**
 * Выводит изображение и прикрепляет его ко временному объекту
 *
 * @param $aParams
 * @param Smarty $oSmarty
 * @return string
 */
function smarty_function_img($aParams, &$oSmarty = NULL)
{
    // Пропущен тип объекта
    if (!isset($aParams['attr']['target-type'])) {
        trigger_error("img: missing 'target-type' parameter", E_USER_WARNING);
        return '';
    }
    // Пропущен идентификатор объекта
    if (!isset($aParams['attr']['target-id'])) {
        trigger_error("img: missing 'target-id' parameter", E_USER_WARNING);
        return '';
    }
    // Получим тип объекта
    $sTargetType = $aParams['attr']['target-type'];
    unset($aParams['attr']['target-type']);
    // Получим ид объекта
    $iTargetId = intval($aParams['attr']['target-id']);
    unset($aParams['attr']['target-id']);
    // Получим ид объекта
    $sCrop = isset($aParams['attr']['crop']) ? $aParams['attr']['crop'] : FALSE;
    unset($aParams['attr']['crop']);
    // Получим изображение по временному ключу, или создадим этот ключ
    if (($sTargetTmp = E::ModuleSession()->GetCookie(ModuleUploader::COOKIE_TARGET_TMP)) && E::IsUser()) {
        // Продлим куку
        E::ModuleSession()->SetCookie(ModuleUploader::COOKIE_TARGET_TMP, $sTargetTmp, 'P1D', FALSE);
        // Получим предыдущее изображение и если оно было, установим в качестве текущего
        // Получим и удалим все ресурсы
        $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, $iTargetId, E::UserId());
        if ($aMresourceRel) {
            /** @var ModuleMresource_EntityMresource $oResource */
            $oMresource = array_shift($aMresourceRel);
            if ($oMresource) {
                if ($sCrop) {
                    $aParams['attr']['src'] = E::ModuleUploader()->ResizeTargetImage($oMresource->GetUrl(), $sCrop);
                } else {
                    $aParams['attr']['src'] = $oMresource->GetUrl();
                }
                $oSmarty->assign("bImageIsTemporary", TRUE);
            }
        }
    } else {
        // Куки нет, это значит, что пользователь первый раз создает этот тип
        // и старой картинки просто нет
        if ($iTargetId == '0') {
            E::ModuleSession()->SetCookie(ModuleUploader::COOKIE_TARGET_TMP, F::RandomStr(), 'P1D', FALSE);
        } else {
            E::ModuleSession()->DelCookie(ModuleUploader::COOKIE_TARGET_TMP);
            $sImage = E::ModuleUploader()->GetTargetImageUrl($sTargetType, $iTargetId, $sCrop);
            if ($sImage) {
                $aParams['attr']['src'] = $sImage;
                $oSmarty->assign("bImageIsTemporary", TRUE);
            }
        }
    }
    // Формируем строку атрибутов изображения
    $sAttr = '';
    if (isset($aParams['attr']) && is_array($aParams['attr'])) {
        foreach ($aParams['attr'] as $sAttrName => $sAttrValue) {
            $sAttr .= ' ' . $sAttrName . '="' . $sAttrValue . '"';
        }
    }
    // Сформируем тег изображения
    $sImageTag = '<img ' . $sAttr . '/>';
    return $sImageTag;
}
Esempio n. 7
0
 /**
  * Возвращает количество сообщений для пользователя
  *
  * @param bool $sTemplate
  * @return int|mixed|string
  */
 public function CountMessages($sTemplate = false)
 {
     if (!E::IsUser()) {
         return '';
     }
     $sKeyString = 'menu_count_messages_' . E::UserId() . '_' . (string) $sTemplate;
     if (FALSE === ($sData = E::ModuleCache()->GetTmp($sKeyString))) {
         $iValue = (int) $this->CountTrack() + (int) $this->NewTalk();
         if ($sTemplate && $iValue) {
             $sData = str_replace('{{count_messages}}', $iValue, $sTemplate);
         } else {
             $sData = $iValue ? $iValue : '';
         }
         E::ModuleCache()->SetTmp($sData, $sKeyString);
     }
     return $sData;
 }
Esempio n. 8
0
 /**
  * Обработка напоминания пароля, подтверждение смены пароля
  *
  * @return string|null
  */
 protected function EventReminder()
 {
     if (E::IsUser()) {
         // Для авторизованного юзера восстанавливать нечего
         Router::Location('/');
     } else {
         // Устанавливаем title страницы
         E::ModuleViewer()->AddHtmlTitle(E::ModuleLang()->Get('password_reminder'));
         $this->_eventRecovery(false);
     }
 }
Esempio n. 9
0
     */
    $config['data']['user'] = array('list' => array('userbar' => array('text' => array('user_name' => array(), 'count_messages' => array($sTemplate = '<span class="badge badge-danger badge-mail-counter">+{{count_messages}}</span>'), '&nbsp;<span class="caret"></span>'), 'options' => array('class' => 'dropdown', 'link_class' => 'dropdown-toggle user-button', 'image_url' => array('user_avatar_url' => array('32x32crop')), 'image_title' => array('user_name'), 'image_class' => 'user', 'link_data' => array('toggle' => 'dropdown', 'role' => 'button', 'target' => '#'), 'data' => array('hidden-class' => 'btn'))), 'talk' => FALSE));
    /**
     *  Меню пользователя + experience
     */
    $config['data']['toolbar_user'] = array('init' => array('fill' => array('list' => array('*'))), 'description' => '{{menu_user_description}}', 'list' => array('userbar' => array('text' => array('user_name' => array(), 'count_messages' => array('<span class="badge badge-danger badge-mail-counter">+{{count_messages}}</span>')), 'link' => E::User()->getProfileUrl(), 'options' => array('image_url' => array('user_avatar_url' => array('32x32crop'))))));
    /**
     *  Подменю пользователя + experience
     */
    $config['data']['toolbar_userbar'] = array('init' => array('fill' => array('list' => array('*'))), 'description' => '{{menu_toolbar_userbar_description}}', 'class' => 'dropdown-menu dropdown-user-menu animated fadeIn', 'list' => array('user' => array('text' => '<span><i class="fa fa-user"></i></span><span>{{user_menu_profile}}</span>', 'link' => E::User()->getProfileUrl(), 'options' => array('class' => 'fixed-item')), 'favourites' => array('text' => '<span><i class="fa fa-star"></i></span><span>{{user_menu_profile_favourites}}</span>', 'link' => E::User()->getProfileUrl() . 'favourites/topics/', 'options' => array('class' => 'fixed-item')), 'talk' => array('text' => array('<span><i class="fa fa-envelope"></i></span><span>{{user_privat_messages}}</span>', '&nbsp;<span class="new-messages">', 'new_talk_string' => array(), '</span>'), 'link' => Router::GetPath('talk'), 'options' => array('link_id' => 'new_messages', 'class' => 'fixed-item')), 'settings' => array('text' => '<span><i class="fa fa-cog"></i></span><span>{{user_settings}}</span>', 'link' => '___path.root.url___/settings/', 'options' => array('class' => 'fixed-item')), 'toolbar_userbar_item' => '', 'logout' => array('text' => '<span><i class="fa fa-sign-out"></i></span><span>{{exit}}</span>', 'link' => Router::GetPath('login') . 'exit/?security_key=' . E::Security_GetSecurityKey(), 'options' => array('class' => 'fixed-item'))));
    /**
     *  Подменю пользователя + experience
     */
    $config['data']['userbar'] = array('class' => 'dropdown-menu dropdown-user-menu animated fadeIn', 'list' => array('pre' => array('text' => FALSE, 'link' => FALSE, 'options' => array('class' => 'user_activity_items'), 'submenu' => 'userinfo'), 'user' => array('text' => '<i class="fa fa-user"></i>&nbsp;{{user_menu_profile}}', 'link' => E::User()->getProfileUrl()), 'create' => array('text' => '<i class="fa fa-pencil"></i>&nbsp;{{block_create}}', 'link' => '#', 'options' => array('data' => array('toggle' => 'modal', 'target' => '#modal-write'))), 'talk' => array('text' => array('<i class="fa fa-envelope-o"></i>&nbsp;{{user_privat_messages}}', '&nbsp;<span class="new-messages">', 'new_talk_string' => array(), '</span>'), 'link' => Router::GetPath('talk'), 'options' => array('link_id' => 'new_messages')), 'wall' => array('text' => '<i class="fa fa-bars"></i>&nbsp;{{user_menu_profile_wall}}', 'link' => E::User()->getProfileUrl() . 'wall/'), 'publication' => array('text' => '<i class="fa fa-file-o"></i>&nbsp;{{user_menu_publication}}', 'link' => E::User()->getProfileUrl() . 'created/topics/'), 'favourites' => array('text' => '<i class="fa fa-star-o"></i>&nbsp;{{user_menu_profile_favourites}}', 'link' => E::User()->getProfileUrl() . 'favourites/topics/'), 'settings' => array('text' => '<i class="fa fa-cogs"></i>&nbsp;{{user_settings}}', 'link' => '___path.root.url___/settings/'), 'userbar_item' => '', 'logout' => array('text' => '<i class="fa fa-sign-out"></i>&nbsp;{{exit}}', 'link' => Router::GetPath('login') . 'exit/?security_key=' . E::Security_GetSecurityKey())));
}
if (E::IsUser()) {
    $config['data']['userinfo'] = array('init' => array('fill' => array('list' => array('*'))), 'description' => 'Индикаторы пользователя', 'list' => array('user_rating' => array('text' => array('user_rating' => array('<i class="fa fa-bar-chart-o"></i>', 'negative')), 'link' => E::User()->getProfileUrl(), 'options' => array('class' => 'menu-item-user-rating')), 'user_comments' => array('text' => array('count_track' => array('<i class="fa fa-bullhorn"></i>')), 'link' => Router::GetPath('feed') . 'track/', 'options' => array('class' => 'menu-item-user-comments')), 'user_mails' => array('text' => array('new_talk_string' => array('<i class="fa fa-envelope-o"></i>')), 'link' => Router::GetPath('talk'), 'options' => array('class' => 'menu-item-user-talks'))));
}
/**
 *  Меню топиков
 */
C::Set('menu.data.topics.discussed.text', array('{{blog_menu_all_discussed}}', '&nbsp;<i class="caret"></i>'));
$config['data']['topics'] = array('class' => 'menu-topics', 'list' => array('good' => array('active' => array('topic_kind' => array('good')), 'options' => array('class' => 'menu-topics-good')), 'new' => array('text' => array('{{blog_menu_all_new}}', 'new_topics_count' => array('red')), 'options' => array('class' => 'menu-topics-new', 'link_title' => '{{blog_menu_top_period_24h}}')), 'newall' => array('options' => array('class' => 'menu-topics-all', 'link_title' => '{{blog_menu_top_period_24h}}')), 'feed' => array('options' => array('class' => 'menu-topics-feed role-guest-hide')), 'discussed' => array('text' => array('{{blog_menu_all_discussed}}', '&nbsp;<i class="caret"></i>'), 'submenu' => 'discussed', 'options' => array('class' => 'dropdown menu-topics-discussed', 'link_data' => array('toggle' => 'dropdown')))));
if (C::Get('rating.enabled')) {
    $config['data']['topics']['list']['top'] = array('text' => array('{{blog_menu_all_top}}', '&nbsp;<i class="caret"></i>'), 'submenu' => 'top', 'options' => array('class' => 'dropdown menu-topics-top', 'link_data' => array('toggle' => 'dropdown')));
}
/**
 *  Подменю обсуждаемых
 */
$config['data']['discussed'] = array('class' => 'dropdown-menu  dropdown-content-menu animated fadeIn');
if (C::Get('rating.enabled')) {
Esempio n. 10
0
 /**
  * Получает топики пользователя с картинками
  *
  * @param int    $iUserId
  * @param string $sType
  * @param int    $iPage
  * @param int    $iPerPage
  *
  * @return array
  */
 public function GetTopicsPageByType($iUserId, $sType, $iPage, $iPerPage)
 {
     $iCount = 0;
     $aFilter = array('user_id' => $iUserId, 'mresource_type' => ModuleMresource::TYPE_IMAGE | ModuleMresource::TYPE_PHOTO | ModuleMresource::TYPE_PHOTO_PRIMARY, 'target_type' => array('photoset', 'topic'));
     if (E::IsUser() && E::User() !== $iUserId) {
         // Если текущий юзер не совпадает с запрашиваемым, то получаем список доступных блогов
         $aFilter['blogs_id'] = E::ModuleBlog()->GetAccessibleBlogsByUser(E::User());
         // И топики должны быть опубликованы
         $aFilter['topic_publish'] = 1;
     }
     if (!E::IsUser()) {
         // Если юзер не авторизован, то считаем все доступные для индексации топики
         $aFilter['topic_index_ignore'] = 0;
     }
     $aFilter['topic_type'] = $sType;
     $aTopicInfo = $this->oMapper->GetTopicInfo($aFilter, $iCount, $iPage, $iPerPage);
     if ($aTopicInfo) {
         $aFilter = array('topic_id' => array_keys($aTopicInfo), 'topic_type' => $sType);
         // Результат в формате array('collection'=>..., 'count'=>...)
         $aResult = E::ModuleTopic()->GetTopicsByFilter($aFilter, 1, count($aTopicInfo));
         if ($aResult) {
             /** @var ModuleTopic_EntityTopic $oTopic */
             foreach ($aResult['collection'] as $sTopicId => $oTopic) {
                 $oTopic->setImagesCount($aTopicInfo[$sTopicId]);
                 $aResult['collection'][$sTopicId] = $oTopic;
             }
             $aResult['count'] = $iCount;
             // total number of topics with images
         }
         return $aResult;
     }
     return array('collection' => array(), 'count' => 0);
 }
Esempio n. 11
0
 /**
  * Загрузка страницы картинок
  */
 protected function EventImageManagerLoadImages()
 {
     E::ModuleSecurity()->ValidateSendForm();
     // Менеджер изображений может запускаться в том числе и из админки
     // Если передано название скина админки, то используем его, если же
     // нет, то ту тему, которая установлена для сайта
     if (($sAdminTheme = F::GetRequest('admin')) && E::IsAdmin()) {
         C::Set('view.skin', $sAdminTheme);
     }
     // Получим идентификатор пользователя, изображения которого нужно загрузить
     $iUserId = (int) F::GetRequest('profile', FALSE);
     if ($iUserId && E::ModuleUser()->GetUserById($iUserId)) {
         C::Set('menu.data.profile_images.uid', $iUserId);
     } else {
         // Только пользователь может смотреть своё дерево изображений
         if (!E::IsUser()) {
             E::ModuleMessage()->AddErrorSingle(E::ModuleLang()->Get('system_error'));
             return;
         }
         $iUserId = E::UserId();
     }
     $sCategory = F::GetRequestStr('category', FALSE);
     $iPage = intval(F::GetRequestStr('page', '1'));
     $sTopicId = F::GetRequestStr('topic_id', FALSE);
     $sTargetType = F::GetRequestStr('target');
     if (!$sCategory) {
         return;
     }
     $aTplVariables = array('sTargetType' => $sTargetType, 'sTargetId' => $sTopicId);
     // Страница загрузки картинки с компьютера
     if ($sCategory == 'insert-from-pc') {
         $sImages = E::ModuleViewer()->Fetch('modals/insert_img/inject.pc.tpl', $aTplVariables);
         E::ModuleViewer()->AssignAjax('images', $sImages);
         return;
     }
     // Страница загрузки из интернета
     if ($sCategory == 'insert-from-link') {
         $sImages = E::ModuleViewer()->Fetch('modals/insert_img/inject.link.tpl', $aTplVariables);
         E::ModuleViewer()->AssignAjax('images', $sImages);
         return;
     }
     $sTemplateName = 'inject.images.tpl';
     $aResources = array('collection' => array());
     $iPagesCount = 0;
     if ($sCategory == 'user') {
         //ок
         // * Аватар и фото пользователя
         $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('target_type' => array('profile_avatar', 'profile_photo'), 'user_id' => $iUserId), $iPage, Config::Get('module.topic.images_per_page'));
         $sTemplateName = 'inject.images.user.tpl';
         $iPagesCount = 0;
     } elseif ($sCategory == '_topic') {
         // * Конкретный топик
         $oTopic = E::ModuleTopic()->GetTopicById($sTopicId);
         if ($oTopic && ($oTopic->isPublished() || $oTopic->getUserId() == E::UserId()) && E::ModuleACL()->IsAllowShowBlog($oTopic->getBlog(), E::User())) {
             $aResourcesId = E::ModuleMresource()->GetCurrentTopicResourcesId($iUserId, $sTopicId);
             if ($aResourcesId) {
                 $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'mresource_id' => $aResourcesId), $iPage, Config::Get('module.topic.images_per_page'));
                 $aResources['count'] = count($aResourcesId);
                 $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
                 $aTplVariables['oTopic'] = $oTopic;
             }
         }
         $sTemplateName = 'inject.images.tpl';
     } elseif ($sCategory == 'talk') {
         // * Письмо
         /** @var ModuleTalk_EntityTalk $oTopic */
         $oTopic = E::ModuleTalk()->GetTalkById($sTopicId);
         if ($oTopic && E::ModuleTalk()->GetTalkUser($sTopicId, $iUserId)) {
             $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'target_type' => 'talk', 'target_id' => $sTopicId), $iPage, Config::Get('module.topic.images_per_page'));
             $aResources['count'] = E::ModuleMresource()->GetMresourcesCountByTargetIdAndUserId('talk', $sTopicId, $iUserId);
             $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
             $aTplVariables['oTopic'] = $oTopic;
         }
         $sTemplateName = 'inject.images.tpl';
     } elseif ($sCategory == 'comments') {
         // * Комментарии
         $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'target_type' => array('talk_comment', 'topic_comment')), $iPage, Config::Get('module.topic.images_per_page'));
         $aResources['count'] = E::ModuleMresource()->GetMresourcesCountByTargetAndUserId(array('talk_comment', 'topic_comment'), $iUserId);
         $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
         $sTemplateName = 'inject.images.tpl';
     } elseif ($sCategory == 'current') {
         //ок
         // * Картинки текущего топика (текст, фотосет, одиночные картинки)
         $aResourcesId = E::ModuleMresource()->GetCurrentTopicResourcesId($iUserId, $sTopicId);
         if ($aResourcesId) {
             $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('user_id' => $iUserId, 'mresource_id' => $aResourcesId), $iPage, Config::Get('module.topic.images_per_page'));
             $aResources['count'] = count($aResourcesId);
             $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
         }
         $sTemplateName = 'inject.images.tpl';
     } elseif ($sCategory == 'blog_avatar') {
         // ок
         // * Аватары созданных блогов
         $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('target_type' => 'blog_avatar', 'user_id' => $iUserId), $iPage, Config::Get('module.topic.group_images_per_page'));
         $aResources['count'] = E::ModuleMresource()->GetMresourcesCountByTargetAndUserId('blog_avatar', $iUserId);
         // Получим блоги
         $aBlogsId = array();
         foreach ($aResources['collection'] as $oResource) {
             $aBlogsId[] = $oResource->getTargetId();
         }
         if ($aBlogsId) {
             $aBlogs = E::ModuleBlog()->GetBlogsAdditionalData($aBlogsId);
             $aTplVariables['aBlogs'] = $aBlogs;
         }
         $sTemplateName = 'inject.images.blog.tpl';
         $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.group_images_per_page'));
     } elseif ($sCategory == 'topics') {
         // ок
         // * Страница топиков
         $aTopicsData = E::ModuleMresource()->GetTopicsPage($iUserId, $iPage, Config::Get('module.topic.group_images_per_page'));
         $aTplVariables['aTopics'] = $aTopicsData['collection'];
         $sTemplateName = 'inject.images.topic.tpl';
         $iPagesCount = ceil($aTopicsData['count'] / Config::Get('module.topic.group_images_per_page'));
         $aResources = array('collection' => array());
     } elseif (in_array($sCategory, E::ModuleTopic()->GetTopicTypes())) {
         // ок
         // * Страница топиков
         $aTopicsData = E::ModuleMresource()->GetTopicsPageByType($iUserId, $sCategory, $iPage, Config::Get('module.topic.group_images_per_page'));
         $aTplVariables['aTopics'] = $aTopicsData['collection'];
         $sTemplateName = 'inject.images.topic.tpl';
         $iPagesCount = ceil($aTopicsData['count'] / Config::Get('module.topic.group_images_per_page'));
         $aResources = array('collection' => array());
     } elseif ($sCategory == 'talks') {
         // ок
         // * Страница писем
         $aTalksData = E::ModuleMresource()->GetTalksPage($iUserId, $iPage, Config::Get('module.topic.group_images_per_page'));
         $aTplVariables['aTalks'] = $aTalksData['collection'];
         $sTemplateName = 'inject.images.talk.tpl';
         $iPagesCount = ceil($aTalksData['count'] / Config::Get('module.topic.group_images_per_page'));
         $aResources = array('collection' => array());
     } else {
         // * Прочие изображения
         $aResources = E::ModuleMresource()->GetMresourcesByFilter(array('target_type' => $sCategory, 'user_id' => $iUserId), $iPage, Config::Get('module.topic.images_per_page'));
         $iPagesCount = ceil($aResources['count'] / Config::Get('module.topic.images_per_page'));
     }
     $aTplVariables['aResources'] = $aResources['collection'];
     $sPath = F::GetRequest('profile', FALSE) ? 'actions/profile/created_photos/' : 'modals/insert_img/';
     $sImages = E::ModuleViewer()->GetLocalViewer()->Fetch($sPath . $sTemplateName, $aTplVariables);
     E::ModuleViewer()->AssignAjax('images', $sImages);
     E::ModuleViewer()->AssignAjax('category', $sCategory);
     E::ModuleViewer()->AssignAjax('page', $iPage);
     E::ModuleViewer()->AssignAjax('pages', $iPagesCount);
 }
Esempio n. 12
0
 /**
  * Проверяет доступность того или иного целевого объекта, переопределяется
  * плагинами. По умолчанию всё грузить запрещено.
  * Если всё нормально и пользователю разрешено сюда загружать картинки,
  * то метод возвращает целевой объект, иначе значение FALSE.
  *
  * @param string $sTarget
  * @param int    $iTargetId
  *
  * @return bool
  */
 public function CheckAccessAndGetTarget($sTarget, $iTargetId = null)
 {
     // Проверяем право пользователя на прикрепление картинок к топику
     if (mb_strpos($sTarget, 'single-image-uploader') === 0 || $sTarget == 'photoset') {
         // Проверям, авторизован ли пользователь
         if (!E::IsUser()) {
             return FALSE;
         }
         // Топик редактируется
         if ($oTopic = E::ModuleTopic()->GetTopicById($iTargetId)) {
             if (!E::ModuleACL()->IsAllowEditTopic($oTopic, E::User())) {
                 return FALSE;
             }
             return $oTopic;
         }
         return TRUE;
     }
     // Загружать аватарки можно только в свой профиль
     if ($sTarget == 'profile_avatar') {
         if ($iTargetId && E::IsUser() && $iTargetId == E::UserId()) {
             return E::User();
         }
         return FALSE;
     }
     // Загружать аватарки можно только в свой профиль
     if ($sTarget == 'profile_photo') {
         if ($iTargetId && E::IsUser() && $iTargetId == E::UserId()) {
             return E::User();
         }
         return FALSE;
     }
     if ($sTarget == 'blog_avatar') {
         /** @var ModuleBlog_EntityBlog $oBlog */
         $oBlog = E::ModuleBlog()->GetBlogById($iTargetId);
         if (!E::IsUser()) {
             return false;
         }
         if (!$oBlog) {
             // Блог еще не создан
             return E::ModuleACL()->CanCreateBlog(E::User()) || E::IsAdminOrModerator();
         }
         if ($oBlog && (E::ModuleACL()->CheckBlogEditBlog($oBlog, E::User()) || E::IsAdminOrModerator())) {
             return $oBlog;
         }
         return '';
     }
     if ($sTarget == 'topic') {
         if (!E::IsUser()) {
             return false;
         }
         /** @var ModuleTopic_EntityTopic $oTopic */
         $oTopic = E::ModuleTopic()->GetTopicById($iTargetId);
         if (!$oTopic) {
             // Топик еще не создан
             return TRUE;
         }
         if ($oTopic && (E::ModuleACL()->IsAllowEditTopic($oTopic, E::User()) || E::IsAdminOrModerator())) {
             return $oTopic;
         }
         return '';
     }
     if ($sTarget == 'topic_comment') {
         if (!E::IsUser()) {
             return false;
         }
         /** @var ModuleComment_EntityComment $oComment */
         $oComment = E::ModuleComment()->GetCommentById($iTargetId);
         if (!$oComment) {
             // Комментарий еще не создан
             return TRUE;
         }
         if ($oComment && (E::ModuleACL()->CanPostComment(E::User(), $oComment->getTarget()) && E::ModuleAcl()->CanPostCommentTime(E::User()) || E::IsAdminOrModerator())) {
             return $oComment;
         }
         return '';
     }
     if ($sTarget == 'talk_comment') {
         if (!E::IsUser()) {
             return false;
         }
         /** @var ModuleComment_EntityComment $oComment */
         $oComment = E::ModuleComment()->GetCommentById($iTargetId);
         if (!$oComment) {
             // Комментарий еще не создан
             return TRUE;
         }
         if ($oComment && (E::ModuleAcl()->CanPostTalkCommentTime(E::User()) || E::IsAdminOrModerator())) {
             return $oComment;
         }
         return '';
     }
     if ($sTarget == 'talk') {
         if (!E::IsUser()) {
             return false;
         }
         /** @var ModuleComment_EntityComment $oTalk */
         $oTalk = E::ModuleTalk()->GetTalkById($iTargetId);
         if (!$oTalk) {
             // Комментарий еще не создан
             return TRUE;
         }
         if ($oTalk && (E::ModuleAcl()->CanSendTalkTime(E::User()) || E::IsAdminOrModerator())) {
             return $oTalk;
         }
         return '';
     }
     return FALSE;
 }
Esempio n. 13
0
/**
 * Выводит изображение и прикрепляет его ко временному объекту
 *
 * @param $aParams
 * @param Smarty $oSmarty
 * @return string
 */
function smarty_function_imgs($aParams, &$oSmarty = NULL)
{
    // Пропущен тип объекта
    if (!isset($aParams['target-type'])) {
        trigger_error("img: missing 'target-type' parameter", E_USER_WARNING);
        return '';
    }
    // Пропущен идентификатор объекта
    if (!isset($aParams['target-id'])) {
        trigger_error("img: missing 'target-id' parameter", E_USER_WARNING);
        return '';
    }
    // Получим тип объекта
    $sTargetType = $aParams['target-type'];
    unset($aParams['target-type']);
    // Получим ид объекта
    $iTargetId = intval($aParams['target-id']);
    unset($aParams['target-id']);
    // Получим параметры обрезки объекта
    $sCrop = isset($aParams['crop']) ? $aParams['crop'] : FALSE;
    unset($aParams['crop']);
    // Получим ид объекта
    $sTemplate = isset($aParams['template']) ? $aParams['template'] : FALSE;
    unset($aParams['template']);
    // Получим изображение по временному ключу, или создадим этот ключ
    $aParams['src'] = array();
    if (($sTargetTmp = E::ModuleSession()->GetCookie(ModuleUploader::COOKIE_TARGET_TMP)) && E::IsUser()) {
        // Продлим куку
        E::ModuleSession()->SetCookie(ModuleUploader::COOKIE_TARGET_TMP, $sTargetTmp, 'P1D', FALSE);
    } else {
        // Куки нет, это значит, что пользователь первый раз создает этот тип
        // и старой картинки просто нет
        if ($iTargetId == '0') {
            E::ModuleSession()->SetCookie(ModuleUploader::COOKIE_TARGET_TMP, F::RandomStr(), 'P1D', FALSE);
        } else {
            E::ModuleSession()->DelCookie(ModuleUploader::COOKIE_TARGET_TMP);
        }
    }
    // Получим предыдущее изображение и если оно было, установим в качестве текущего
    // Получим и удалим все ресурсы
    $aMresourceRel = E::ModuleMresource()->GetMresourcesRelByTargetAndUser($sTargetType, $iTargetId, E::UserId());
    if ($aMresourceRel && is_array($aMresourceRel)) {
        /** @var ModuleMresource_EntityMresource $oResource */
        foreach ($aMresourceRel as $oMresource) {
            if ($sCrop) {
                $aParams['src'][$oMresource->getMresourceId()] = array('url' => E::ModuleUploader()->ResizeTargetImage($oMresource->GetUrl(), $sCrop), 'cover' => $oMresource->IsCover());
            } else {
                $aParams['src'][$oMresource->getMresourceId()] = array('url' => $oMresource->GetUrl(), 'cover' => $oMresource->IsCover());
            }
            $oSmarty->assign("bHasImage", TRUE);
        }
    }
    // Создадим массив картинок
    $sItems = '';
    if ($aParams['src']) {
        foreach ($aParams['src'] as $sID => $aData) {
            $sItems .= str_replace(array('ID', 'uploader_item_SRC', 'MARK_AS_PREVIEW'), array($sID, $aData['url'], $aData['cover'] ? E::ModuleLang()->Get('topic_photoset_is_preview') : E::ModuleLang()->Get('topic_photoset_mark_as_preview')), $sTemplate);
        }
    }
    return $sItems;
}
Esempio n. 14
0
 /**
  * Условия показа виджета
  *
  * @return bool
  */
 public function isCondition()
 {
     $bResult = $this->getProp('_is_condition');
     if (is_null($bResult)) {
         $bResult = true;
         $sCondition = $this->GetCondition();
         if (is_string($sCondition) && $sCondition > '') {
             try {
                 extract($this->GetParams(), EXTR_SKIP);
                 $bResult = (bool) eval('return ' . $sCondition . ';');
             } catch (Exception $oException) {
                 $bResult = false;
             }
         }
         if ($bResult && ($sVisitors = $this->GetVisitors())) {
             if ($sVisitors == 'users') {
                 $bResult = E::IsUser();
             } elseif ($sVisitors == 'admins') {
                 $bResult = E::IsAdmin();
             }
         }
         $this->setProp('_is_condition', $bResult);
     }
     return $bResult;
 }
Esempio n. 15
0
 /**
  * Добавляет коммент
  *
  * @param  ModuleComment_EntityComment $oComment    Объект комментария
  *
  * @return bool|ModuleComment_EntityComment
  */
 public function AddComment(ModuleComment_EntityComment $oComment)
 {
     if (Config::Get('module.comment.use_nested')) {
         $iCommentId = $this->oMapper->AddCommentTree($oComment);
         E::ModuleCache()->CleanByTags(array("comment_update"));
     } else {
         $iCommentId = $this->oMapper->AddComment($oComment);
     }
     if ($iCommentId) {
         $oComment->setId($iCommentId);
         if ($oComment->getTargetType() == 'topic') {
             E::ModuleTopic()->RecalcCountOfComments($oComment->getTargetId());
         }
         // Освежим хранилище картинок
         E::ModuleMresource()->CheckTargetTextForImages($oComment->getTargetType() . '_comment', $iCommentId, $oComment->getText());
         if (E::IsUser()) {
             // * Сохраняем дату последнего коммента для юзера
             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()}"));
         } else {
             // чистим зависимые кеши
             E::ModuleCache()->CleanByTags(array("comment_new", "comment_new_{$oComment->getTargetType()}", "comment_new_{$oComment->getTargetType()}_{$oComment->getTargetId()}"));
         }
         return $oComment;
     }
     return false;
 }
Esempio n. 16
0
 /**
  * Shutdown and output result
  */
 public function EventShutdown()
 {
     parent::EventShutdown();
     if ($this->bRestApi) {
         if (E::IsUser()) {
             $this->aResponseData['auth_token'] = E::User()->getAuthToken();
         }
         E::ModuleViewer()->AssignAjax('error', $this->iResponseError);
         E::ModuleViewer()->AssignAjax('message', $this->sResponseMessage);
         E::ModuleViewer()->AssignAjax('data', $this->aResponseData);
         E::ModuleViewer()->SetResponseHeader('Content-type', 'application/json; charset=utf-8');
         $sOutput = E::ModuleViewer()->getAjaxVars();
         E::ModuleViewer()->Flush($sOutput);
     }
 }