1. Приветствуем Вас на неофициальном форуме технической поддержки XenForo на русском языке. XenForo - коммерческий форумный движок от бывших создателей vBulletin, написанный на PHP.

Используем XenForo для комментирования элементов сторонних сайтов

Тема в разделе "Статьи по XenForo Framework", создана пользователем FractalizeR, 25.03.2011.

Загрузка
  1. FractalizeR

    FractalizeR XenForo Addicted

    Регистрация:
    27.09.10
    Сообщения:
    1 085
    Симпатии:
    832
    Версия XF:
    1.3.2
    Недавно передо мной встала задача использовать XenForo для того, чтобы пользователи могли комментировать контент сайта на форуме. В результате получился вот такой простой класс:


    PHP:
    <?php
    /**
     * GSM[база] Goods discussion manager class.
     *
     * This class allows to manage discussions for something on linked XenForo forum
     */

    /**
     * The id of the user who will become the author of the posts, created by manager
     * @var int
     */
    $xenForoAuthorID 1;

    /**
     * The nickname of the user who will become the author of the posts, created by manager
     * @var string
     */
    $xenForoCommentAuthorUserName 'Бот-обсуждальщик';


    /**
     * Full path to the root of xenForo installation
     * @var string
     */
    $xenForoDirectory 'E:/WebServers/home/xenforo.local/www';


    /**
     * URL of xenForo installation
     * @var string
     */
    $xenForoURL 'http://support.gsmbaza.ru/forum';

    require_once 
    __DIR__ '/DiscussionManagerException.php';

    /**
     * Class, managing discussions
     *
     * @throws DiscussionManagerException
     *
     */
    class FR_DiscussionManager {

        
    /**
         * Function initialises XenForo internal structures
         *
         * @return void
         */
        
    private function _prepareXenForo() {
            global 
    $xenForoDirectory;
            if (
    class_exists('XenForo_Autoloader')) {
                return;
            }

            require_once 
    $xenForoDirectory '/library/XenForo/Autoloader.php';
            
    XenForo_Autoloader::getInstance()->setupAutoloader($xenForoDirectory '/library');
            
    XenForo_Application::initialize($xenForoDirectory '/library'$xenForoDirectory);
        }


        
    /**
         * Function returns an array of latest comments of the specified thread. You can use the return value of the method
         * in the following way:
         *              foreach ($result as $item) {
         *                  echo $item["post_id"];
         *                  echo $item["user_id"];
         *                  echo $item["username"];
         *                  echo $item["post_date"];
         *                  echo $item["message"];
         *              }
         *
         * @param  $threadId int Id of the thread to read posts from
         * @param  $count int Maximum number of comments to return
         * @return array Array of discussion items sorted by date descending. Discussion item is an array with
         *               the following indices: `post_date`, `message`, `username`, `user_id`
         */
        
    public function getPostsFrom($threadId$count) {
            global 
    $xenForoDirectory;

            
    $this->_prepareXenForo();

            
    $sql "SELECT `post_id`, `post_date`, `message`, `username`, `user_id` FROM `xf_post`
                WHERE `thread_id` = 
    {$threadId} AND `message_state` = 'visible'
                ORDER BY `post_date` DESC LIMIT 
    {$count}";

            return (
    XenForo_Application::get('db')->fetchAll($sql));
        }

        
    /**
         * @param $forumID int An id of the forum to create comments thread in
         * @param  $subject string The subject of the thread
         * @param  $message string The text of the first message in the thread
         * @return int Newly created thread id
         * @throws DiscussionManagerException
         */
        
    public function createCommentsThread($forumID$subject$message) {
            global 
    $xenForoAuthorID$xenForoCommentAuthorUserName;

            
    $this->_prepareXenForo();

            
    $newThread XenForo_DataWriter::create('XenForo_DataWriter_Discussion_Thread');
            
    $newThread->set('user_id'$xenForoAuthorID);
            
    $newThread->set('username'$xenForoCommentAuthorUserName);
            
    $newThread->set('title'$subject);
            
    $newFirstPostInThread $newThread->getFirstMessageDw();
            
    $newFirstPostInThread->set('message'XenForo_Helper_String::autoLinkBbCode($message));
            
    $newThread->set('node_id'$forumID);
            
    $newThread->preSave();
            if (!
    $newThread->hasErrors() and $newThread->save()) {
                return 
    $newThread->get('thread_id');
            } else {
                throw new 
    DiscussionManagerException($newThread->getErrors());
            }
        }

        
    /**
         * Function returns an URL to the specified thread. It can be used for redirection purposes for example
         *
         * @param  $threadId The id of the thread to return a link to
         * @return string URL to the thread like "http://www....."
         */
        
    public function getLinkToThread($threadId) {
            global 
    $xenForoURL;

            return 
    $xenForoURL "/threads/{$threadId}/";
        }

        
    /**
         * Function returns an URL to the specified thread. It can be used for redirection purposes
         * or link building for example
         *
         * @param  $userId The id of the user to return a link to
         * @return string URL to the user profile like "http://www....."
         */
        
    public function getLinkToUser($userId) {
            global 
    $xenForoURL;

            return 
    $xenForoURL "/users/{$userId}/";
        }

        
    /**
         * Function returns an URL to the specified post. It can be used for redirection purposes
         * or link building for example
         *
         * @param  $postId The id of the post to return a link to
         * @return string URL to the post like "http://www....."
         */
        
    public function getLinkToPost($postId) {
            global 
    $xenForoURL;

            return 
    $xenForoURL "/posts/{$postId}/";
        }
    }

    PHP:
    <?php

    class DiscussionManagerException extends Exception {
        private 
    $_errors = array();

        
    /**
         * Constructs and exception
         *
         * @param array $errors A list of errors occurred during operation. A list is a simple array in format:
         *          'errorCode' => 'errorText'
         */
        
    public function __construct(array $errors) {
            
    $this->_errors $errors;
            
    parent::__construct("Discussion manager exception thrown!");
        }

        
    /**
         * Function returns a list of errors occurred during operation
         *
         * @return array  A list of errors occurred during operation. A list is a simple array in format:
         *          'errorCode' => 'errorText'
         */
        
    public function getErrors() {
            return 
    $this->_errors;
        }

    }

    Использовать его можно так:


    PHP:
    <?php
    require_once __DIR__ '/DiscussionManager.php';
    $discussionManager = new FR_DiscussionManager();
    $threadId $discussionManager->createCommentsThread(2"Creation test""Creation message deep test!");

    echo(
    $discussionManager->getLinkToThread($threadId));
    PHP:
    <?php
    require_once __DIR__ '/DiscussionManager.php';
    $discussionManager = new FR_DiscussionManager();
    var_dump($discussionManager->getPostsFrom(510));
    Код несколько сыроват, но, полагаю основная идея понятна.
     
    SAS1024, R.J., TAIFUN и 2 другим нравится это.
  2. Pepelac

    Pepelac Продам луц в бутылках

    Регистрация:
    28.09.10
    Сообщения:
    1 794
    Симпатии:
    1 361
    Эм... А почему глобальные переменные?
     
  3. FractalizeR

    FractalizeR XenForo Addicted

    Регистрация:
    27.09.10
    Сообщения:
    1 085
    Симпатии:
    832
    Версия XF:
    1.3.2
    Да просто так. Это я не для себя делал. Людям так было... понятнее. Можно в статические поля вынести эти данные, если удобно. Или в конфиг какой-нибудь. Впрочем, конфиг - это тоже глобальные переменные...
     
  4. Pepelac

    Pepelac Продам луц в бутылках

    Регистрация:
    28.09.10
    Сообщения:
    1 794
    Симпатии:
    1 361
    Ясненько :)
     
  5. SeM13

    SeM13 Создатель системы

    Регистрация:
    05.01.11
    Сообщения:
    747
    Симпатии:
    258
    Версия XF:
    1.1.3
    Это что то вроде модуля вконтакте?
    Или я не правильно понял?:(
     
  6. Сергей

    Сергей Активный пользователь

    Регистрация:
    04.03.11
    Сообщения:
    15
    Симпатии:
    0
    Версия XF:
    1.1.0 Final
    Hi.
    Спасибо.
    Вот только еще всякие проверки нужно производить, начиная с наличия пользователя $xenForoCommentAuthorUserName = 'Бот-обсуждальщик'; , есть ли у него "бананы" и т.д.
     
  7. Andyk

    Andyk Местный

    Регистрация:
    27.01.12
    Сообщения:
    64
    Симпатии:
    6
    Версия XF:
    1.1.2
    А можно пример как это работает?
     
  8. FractalizeR

    FractalizeR XenForo Addicted

    Регистрация:
    27.09.10
    Сообщения:
    1 085
    Симпатии:
    832
    Версия XF:
    1.3.2
    Так последние два куска коды и есть пример. Попробуйте.
     
  9. SeaSoul

    SeaSoul Местный

    Регистрация:
    24.11.11
    Сообщения:
    132
    Симпатии:
    10
    Версия XF:
    1.1.4
    в личку пришлешь свой сайт(или здесь можно), где уже стоит? готовое охота увидеть)
     
  10. FractalizeR

    FractalizeR XenForo Addicted

    Регистрация:
    27.09.10
    Сообщения:
    1 085
    Симпатии:
    832
    Версия XF:
    1.3.2
    У меня самого нигде не стоит. А кто ставил - я не помню.
     
  11. Andyk

    Andyk Местный

    Регистрация:
    27.01.12
    Сообщения:
    64
    Симпатии:
    6
    Версия XF:
    1.1.2
    У меня не хватает знаний. Куда эти куски кода, в какие файлы? Можно мануальчик?
     

Поделиться этой страницей