All pastes #203190 Raw Edit

Miscellany

public text v1 · immutable
#203190 ·published 2006-10-14 23:53 UTC
rendered paste body
<?php
/**
 * Blog Gadget
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or(at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * LICENSE: Use GPL license for gadgets, LGPL for Core
 *
 * @category   Gadget
 * @package    Blog
 * @author     Jonathan Hernandez  <ion@gluch.org.mx>
 * @author     Pablo Fischer <pablo@pablo.com.mx>
 * @copyright  2004-2005 Jaws Development Group
 * @license    http://www.gnu.org/copyleft/gpl.html
 */
class BlogHTML extends JawsGadgetHTML
{
    /**
     * Constructor
     *
     * @access       public
     */
    function BlogHTML()
    {
        $this->Init('Blog');
    }

    /**
     * Calls default action(view)
     *
     * @access       public
     * @return       template content
     */
    function DefaultAction()
    {
        return $this->View();
    }

    /**
     * Installs the gadget
     *
     * @access       public
     * @return       boolean True on successful installation, JawsError otherwise
     */
    function InstallGadget()
    {
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        return $model->InstallGadget();
    }


    /**
     * Displays default blog view
     *
     * @access       public
     * @return       template content
     */
    function View()
    {
        $base_url = $GLOBALS['app']->Registry->Get('/config/url').'/data/xml/';
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $GLOBALS['app']->Layout->AddHeadLink($base_url.'blog.atom', 'alternate', 'application/atom+xml', 'Atom - All', false);
        $GLOBALS['app']->Layout->AddHeadLink($base_url.'blog.rss', 'alternate', 'application/rss+xml', 'RSS 2.0 - All', false);

        /**
         * This will be supported in next Blog version - Bookmarks for each categorie
         *
         * $categories = $model->GetCategories();
         * if (!JawsError::IsError($categories)) {
         * //$GLOBALS['app']->Layout->AddHeadLink($base_url.'blog.atom', 'alternate', 'application/atom+xml', 'Atom - All', false);
         * foreach ($categories as $cat) {
         *                $name = $GLOBALS['app']->XSS->parse($cat['name']);
         * }
         *
         * foreach ($categories as $cat) {
         *   $name = $GLOBALS['app']->XSS->parse($cat['name']);
         * }
         *}
         */

        $entries = $model->GetEntries();
		
        $res = '';
        if (!JawsError::IsError($entries) && is_array($entries) && count($entries) > 0) {
            foreach ($entries as $e) {
                $res .= $this->ShowEntry($e, true, true, true);
            }
        }
		
        return $res;
    }
	
	
    /**
     * @access       public
     * @return       template content
     */
    function ViewDate()
    {
        $tpl =& new JawsTemplate('gadgets/Blog/templates/');
        $tpl->Load('ViewDate.html');
        $tpl->SetBlock('view_date');
        //Month, day and year
        $year  = isset($_GET['year'])  ? $_GET['year']  : date('Y');
        $month = isset($_GET['month']) ? $_GET['month'] : date('m');
        $day   = isset($_GET['day'])   ? $_GET['day']   : '';

        if ($day != '') {
            $title = $GLOBALS['app']->Date->MonthString($month).' '.$day.', '.$year;
        } else {
            $title = $GLOBALS['app']->Date->MonthString($month).' '.$year;
        }
        $tpl->SetVariable('title', $title);
        $tpl->ParseBlock('view_date');
        $header = $tpl->Get();
        $entries = '';
        //FIXME
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $entriesbydate = $model->GetEntriesByDate($year, $day, $month);
        if (!JawsError::IsError($entries)) {
            foreach ($entriesbydate as $e) {
                $entries .= $this->ShowEntry($e, true, true, true);
            }
        }

        return $header.$entries;
    }

    /**
     * Displays a given blog entry according to given parameters
     *
     * @access       public
     * @param        int $entry entry id
     * @param        boolean $viewLink
     * @param        boolean $commentLink
     * @param        boolean $useMore(optional, false by default)
     * @param        boolean $showNavigation(optional, false by default)
     * @return       template content
     */
    function ShowEntry($entry, $viewLink = true, $commentLink = true,
                       $useMore = false, $showNavigation = false)
    {
        $tpl =& new JawsTemplate('gadgets/Blog/templates/');
        $tpl->Load('Entry.html');
        $tpl->SetBlock('entry');
        $tpl->SetVariablesArray($entry);
        $tpl->SetVariable('createtime',           $GLOBALS['app']->Date->Format($entry['createtime']));
        $tpl->SetVariable('createtime-monthname', $GLOBALS['app']->Date->Format($entry['createtime'], 'MN'));
        $tpl->SetVariable('createtime-month',     $GLOBALS['app']->Date->Format($entry['createtime'], 'm'));
        $tpl->SetVariable('createtime-day',       $GLOBALS['app']->Date->Format($entry['createtime'], 'd'));
        $tpl->SetVariable('createtime-year',      $GLOBALS['app']->Date->Format($entry['createtime'], 'Y'));
        $tpl->SetVariable('createtime-time',      $GLOBALS['app']->Date->Format($entry['createtime'], 'g:ia'));
        $text = $entry['text'];

        if (empty($entry['fast_url'])) {
            $perm_url = $this->GetURLFor('SingleView', array('id' => $entry['id']));
        } else {
            $perm_url = $this->GetURLFor('SingleView', array('id' => $entry['fast_url']));
        }

        if ($useMore){
            if (strpos($entry['text'], '[more]') !== false) {
                $post = explode('[more]', $entry['text']);
                $text = $post[0].'... [<a href="' . $perm_url.'#more">'._t('BLOG_READ_MORE').'</a>]';
            }
        } else {
            $text = str_replace('[more]', '<a id="more"></a>', $text);
            $base_url = $GLOBALS['app']->Registry->Get('/config/url').'/data/xml/';
            $GLOBALS['app']->Layout->AddHeadLink($base_url.'blog.atom', 'alternate', 'application/atom+xml', 'Atom - All', false);
            $GLOBALS['app']->Layout->AddHeadLink($base_url.'blog.rss', 'alternate', 'application/rss+xml', 'RSS 2.0 - All', false);
        }

        $tpl->SetVariable('text', $this->ParseText($GLOBALS['app']->XSS->parse($text, false), 'Blog', true, false));

        $tpl->SetVariable('permanent-link', $perm_url);

        $pos = 1;
        foreach ($entry['categories'] as $cat) {
            $tpl->SetBlock('entry/category');
            $tpl->SetVariable('id', $cat['id']);
            $tpl->SetVariable('name', $cat['name']);
            $tpl->SetVariable('url', $this->GetURLFor('ShowCategory', array('id' => $cat['id'])));
            if ($pos == count($entry['categories'])) {
                $tpl->SetVariable('separator', '');
            } else {
                $tpl->SetVariable('separator', ',');
            }
            $pos++;
            $tpl->ParseBlock('entry/category');
        }

        if (
            $viewLink === true &&
            $entry['allow_comments'] === true &&
            $GLOBALS['app']->Registry->Get('/gadgets/Blog/allow_comments') == 'true' &&
            $GLOBALS['app']->Registry->Get('/config/allow_comments') == 'true'
        ) {
            $tpl->SetBlock('entry/view-link');
            $tpl->SetVariablesArray($entry);

            $url = '<a href="' . $perm_url . '">';
            if ($entry['comments'] == '0') {
                $url .= _t('BLOG_COMMENT_ON_THIS') . '</a>';
                $tpl->SetVariable('view-link', $url);
            } else {
                $url .= _t('BLOG_HAS_N_COMMENTS', $entry['comments']) . '</a>';
                $tpl->SetVariable('view-link', $url);
            }
            $tpl->ParseBlock('entry/view-link');
        }
        $tpl->ParseBlock('entry');

        if ($showNavigation && $tpl->BlockExists('navigation')) {
            $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');

            $tpl->SetBlock('navigation');
            if ($prev = $model->GetNOPEntry($entry['id'], 'previous')) {
                $tpl->SetBlock('navigation/previous');
                $tpl->SetVariable('previous-url', $this->GetURLFor('SingleView',
                                                                   array('id' => empty($prev['fast_url']) ?
                                                                         $prev['id'] : $prev['fast_url'])));
                $tpl->SetVariable('previous-title', $prev['title']);
                $tpl->ParseBlock('navigation/previous');
            }

            if ($next = $model->GetNOPEntry($entry['id'], 'next')) {
                $tpl->SetBlock('navigation/next');
                $tpl->SetVariable('next-url', $this->GetURLFor('SingleView',
                                                               array('id' => empty($next['fast_url']) ?
                                                                     $next['id'] : $next['fast_url'])));
                $tpl->SetVariable('next-title', $next['title']);
                $tpl->ParseBlock('navigation/next');
            }
            $tpl->ParseBlock('navigation');
        }
	
        return $tpl->Get();
    }

    /**
     * Displays a given blog entry
     *
     * @access       public
     * @param        boolean $comment_mode(optional, false by default)
     * @return       template content
     */
    function SingleView($comment_mode = false)
    {
        $result = '';
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $entry = $model->GetEntry($_GET['id'], true);
        if (!JawsError::IsError($entry)) {
            if ($comment_mode == NO){
                $result .= $this->ShowEntry($entry, false, true, false, true);
                if (
                    $entry['allow_comments'] === true &&
                    $GLOBALS['app']->Registry->Get('/gadgets/Blog/allow_comments') == 'true' &&
                    $GLOBALS['app']->Registry->Get('/config/allow_comments') == 'true'
                ) {
                    $result .= $this->ShowTrackbacks($entry['id']);
                    $result .= $this->ShowComments($entry['id'], 0, 0, 1, 1);
                    $result .= $this->DisplayCommentForm($entry['id'], 0, 'Re: ' . $GLOBALS['app']->XSS->filter($entry['title']));
                    $result .= $this->ShowCommentsXMLLinks($entry['id']);
                }
            } else {
                $result .= $this->ShowEntry($entry, false, false);
            }
        }

        return $result;
    }

    /**
     * Displays xml links to a given post
     *
     * @access       public
     * @param        int $id post id
     * @return       template content
     */
    function ShowCommentsXMLLinks($id)
    {
        $tpl =& new JawsTemplate('gadgets/Blog/templates/');
        $tpl->Load('Comment.html');
        $tpl->SetBlock('xmllinks');
        $tpl->SetVariable('comments_feed', _t('BLOG_COMMENTS_XML'));
        $tpl->SetVariable('atom_url', '?gadget=Blog&amp;action=CommentsAtom&amp;id='.$id);
        $tpl->SetVariable('rss_url',  '?gadget=Blog&amp;action=CommentsRSS&amp;id='.$id);
        $tpl->ParseBlock('xmllinks');

        return $tpl->Get();
    }

    /**
     * Recursively displays comments of a given post according to several parameters
     *
     * @access       public
     * @param        int $id post id
     * @param        int $parent parent comment id
     * @param        int $level deep level on thread
     * @param        int $thread 1 to show full thread
     * @param        int $reply_link 1 to show reply-to link
     * @return       template content
     */
    function ShowComments($id, $parent, $level, $thread, $reply_link)
    {
        $tpl =& new JawsTemplate('gadgets/Blog/templates/');
        $tpl->Load('Comment.html');
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $comments = $model->GetComments($id, $parent);
        if (!JawsError::IsError($comments)) {
            foreach ($comments as $c) {
                $tpl->SetBlock('comment');
                $tpl->SetVariable('id', $c['id']);
                $tpl->SetVariable('parent_id', $c['gadget_reference']);
                $tpl->SetVariable('name', $GLOBALS['app']->XSS->filter($c['name']));
                $email = $GLOBALS['app']->XSS->filter($c['email']);
                if ($GLOBALS['app']->Registry->Get('/gadgets/AntiSpam/protect_email') == 'yes' &&
                    !empty($email)) {
                    require_once JAWS_PATH . 'include/Apis/JawsAddressProtector.php';

                    $protector =& new JawsAddressProtector();
                    $emailProtected = $protector->Protect($email, $GLOBALS['app']->XSS->filter($c['name']));
                    $tpl->SetVariable('email', _t('GLOBAL_EMAIL'));
                    $tpl->SetVariable('emailurl', $emailProtected);
                } else {
                    $tpl->SetVariable('email', $email);
                    $tpl->SetVariable('emailurl', 'mailto:'.$email);
                }
                $tpl->SetVariable('url', $GLOBALS['app']->XSS->filter($c['url']));
                $tpl->SetVariable('ip_address', $c['ip']);
                $tpl->SetVariable('avatar_source', $c['avatar_source']);
                $tpl->SetVariable('title', $GLOBALS['app']->XSS->filter($c['title']));
                $tpl->SetVariable('replies', $c['replies']);
                $tpl->SetVariable('commentname', 'comment'.$c['id']);
                $commentsText = $this->ParseText($c['message']);
                $tpl->SetVariable('comments', $commentsText);
                $tpl->SetVariable('createtime',           $GLOBALS['app']->Date->Format($c['createtime']));
                $tpl->SetVariable('createtime-monthname', $GLOBALS['app']->Date->Format($c['createtime'], 'MN'));
                $tpl->SetVariable('createtime-month',     $GLOBALS['app']->Date->Format($c['createtime'], 'm'));
                $tpl->SetVariable('createtime-day',       $GLOBALS['app']->Date->Format($c['createtime'], 'd'));
                $tpl->SetVariable('createtime-year',      $GLOBALS['app']->Date->Format($c['createtime'], 'Y'));
                $tpl->SetVariable('createtime-time',      $GLOBALS['app']->Date->Format($c['createtime'], 'g:ia'));
                $tpl->SetVariable('level', $level);
                if ($reply_link === 1) {
                    $tpl->SetBlock('comment/reply-link');
                    $tpl->SetVariablesArray($c);
                    $tpl->SetVariable('reply-link', '<a href="index.php?gadget=Blog&amp;action=Reply'.
                                      '&amp;id='.$c['id'].'">'.
                                      _t('BLOG_REPLY').'</a>');

                    $tpl->ParseBlock('comment/reply-link');
                }

                if ($thread === 1) {
                    $tpl->SetBlock('comment/thread');
                    $tpl->SetVariable('thread', $this->ShowComments($id, $c['id'], $level + 1, $thread, $reply_link));
                    $tpl->ParseBlock('comment/thread');
                }
                $tpl->ParseBlock('comment');
            }
        }

        return $tpl->Get();
    }

    /**
     * Displays a given blog comment
     *
     * @access       public
     * @param        int $id comment id
     * @return       template content
     */
    function ShowSingleComment($id)
    {
        $tpl =& new JawsTemplate('gadgets/Blog/templates/');
        $tpl->Load('Comment.html');
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $comment = $model->GetComment($id);
        if (!JawsError::IsError($comment)) {
            $tpl->SetBlock('comment');
            $tpl->SetVariable('id', $comment['id']);
            $tpl->SetVariable('parent_id', $comment['gadget_reference']);
            $tpl->SetVariable('name',  $GLOBALS['app']->XSS->filter($comment['name']));
            $tpl->SetVariable('email', $GLOBALS['app']->XSS->filter($comment['email']));
            $tpl->SetVariable('url',   $GLOBALS['app']->XSS->filter($comment['url']));
            $tpl->SetVariable('title', $GLOBALS['app']->XSS->filter($comment['title']));
            $tpl->SetVariable('ip_address', $comment['ip']);
            $tpl->SetVariable('avatar_source', $comment['avatar_source']);
            $tpl->SetVariable('replies', $comment['replies']);
            $tpl->SetVariable('commentname', 'comment' . $comment['id']);
            $commentsText = $this->ParseText($comment['message']);
            $tpl->SetVariable('comments', $commentsText);
            $tpl->SetVariable('createtime',           $GLOBALS['app']->Date->Format($comment['createtime']));
            $tpl->SetVariable('createtime-monthname', $GLOBALS['app']->Date->Format($comment['createtime'], 'MN'));
            $tpl->SetVariable('createtime-month',     $GLOBALS['app']->Date->Format($comment['createtime'], 'm'));
            $tpl->SetVariable('createtime-day',       $GLOBALS['app']->Date->Format($comment['createtime'], 'd'));
            $tpl->SetVariable('createtime-year',      $GLOBALS['app']->Date->Format($comment['createtime'], 'Y'));
            $tpl->SetVariable('createtime-time',      $GLOBALS['app']->Date->Format($comment['createtime'], 'g:ia'));
            $tpl->SetVariable('level', 0);
            $tpl->ParseBlock('comment');
        }

        return $tpl->Get();
    }

    /**
     * Displays a given blog comments and a form for replying
     *
     * @access       public
     * @return       template content
     */
    function Reply()
    {
        $id = (int)$_GET['id'];
        $result = $this->ShowSingleComment($id);
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');

        $comment = $model->GetComment($id);
        if (JawsError::IsError($comment)) {
            $title  = '';
            $parent = 0;
        } else {
            $title  = $comment['title'];
            $parent = $comment['gadget_reference'];
        }

        $result .= $this->DisplayCommentForm($parent, $id,
                                             'Re: ' . $title);

        return $result;
    }

    /**
     * Displays a form to send a comment to the blog
     *
     * @access       public
     * @param        int $parent_id id of the replied item(immediately before on the thread)
     * @param        int $parent id of the replied entry(comment thread starter)
     * @param        string $title title of the comment
     * @param        string $comment body of the comment(optional, empty by default)
     * @return       template content
     */
    function DisplayCommentForm($parent_id, $parent, $title, $comment = '')
    {
        $tpl =& new JawsTemplate('gadgets/Blog/templates/');
        $tpl->Load('CommentForm.html');
        $tpl->SetBlock('commentform');

        $tpl->SetVariable('title', _t('BLOG_LEAVE_COMMENT'));

        // Get person info from cookie or post...
        if (isset($_POST['name'])) {
            $visitorName = $_POST['name'];
        } elseif (WebSession::GetCookie('visitor_name')) {
            $visitorName = WebSession::GetCookie('visitor_name');
        } else {
            $visitorName = '';
        }

        if (isset($_POST['email'])) {
            $visitorEmail = $_POST['email'];
        } elseif (WebSession::GetCookie('visitor_email')) {
            $visitorEmail = WebSession::GetCookie('visitor_email');
        } else {
            $visitorEmail = '';
        }

        if (isset($_POST['url'])) {
            $visitorUrl = $_POST['url'];
        } elseif (WebSession::GetCookie('visitor_url')) {
            $visitorUrl = WebSession::GetCookie('visitor_url');
        } else {
            $visitorUrl = '';
        }

        $form =& Piwi::CreateWidget('Form', 'index.php', 'post');
        $form->Add(Piwi::CreateWidget('HiddenEntry', 'parent_id', $parent_id));
        $form->Add(Piwi::CreateWidget('HiddenEntry', 'parent',    $parent));
        $form->Add(Piwi::CreateWidget('HiddenEntry', 'gadget',    'Blog'));
        $form->Add(Piwi::CreateWidget('HiddenEntry', 'action',    'SaveComment'));

        $captchasCanBeUsed = false;
        if (
            $GLOBALS['app']->Registry->Get('/gadgets/AntiSpam/allow_captchas') == 'yes' &&
            $GLOBALS['app']->Registry->Get('/gadgets/Blog/use_antispam') == 'true'
        ) {
            require_once JAWS_PATH . 'include/JawsCaptcha.php';
            $jawsCaptchas =& JawsCaptcha::factory('Image');
            if ($captchasCanBeUsed = $jawsCaptchas->CanBeUsed()) {
                $md5 = $jawsCaptchas->Random();
                $captchaCode =& Piwi::CreateWidget('Image', 'captchaCode', '');
                $captchaCode->SetTitle(_t('GLOBAL_CAPTCHA_CODE'));
                $captchaCode->SetSrc("index.php?gadget=Blog&amp;action=Captcha&amp;key=".$md5);
                $captcha =& Piwi::CreateWidget('Entry', 'captcha', '');
                $captcha->SetTitle(_t('GLOBAL_CAPTCHA'));

                $form->Add(Piwi::CreateWidget('HiddenEntry', 'captchaKey', $md5));
            }
        }

        include_once JAWS_PATH . 'include/JawsWidgets/JawsFieldSet.php';
        $fieldset =& new JawsFieldSet();

        $name =& Piwi::CreateWidget('Entry', 'name', $visitorName);
        $name->setStyle('width: 200px;');
        $name->SetTitle(_t('GLOBAL_NAME'));

        $email =& Piwi::CreateWidget('Entry', 'email', $visitorEmail);
        $email->setStyle('width: 200px;');
        $email->SetTitle(_t('GLOBAL_EMAIL'));

        $url =& Piwi::CreateWidget('Entry', 'url', $visitorUrl);
        $url->setStyle('width: 100%;');
        $url->SetTitle(_t('GLOBAL_URL'));

        $subject =& Piwi::CreateWidget('Entry', 'title', $title);
        $subject->setStyle('width: 100%;');
        $subject->SetTitle(_t('GLOBAL_TITLE'));

        $comment =& Piwi::CreateWidget('TextArea', 'comments', $comment);
        $comment->setStyle('width: 100%;');
        $comment->SetRows(7);
        $comment->SetTitle(_t('BLOG_COMMENT'));

        $previewButton =& Piwi::CreateWidget('Button', 'preview', _t('GLOBAL_PREVIEW'), STOCK_PRINT_PREVIEW);
        $previewButton->AddEvent(ON_CLICK, "this.form.action.value='Preview'; this.form.submit();");

        $submitButton =& Piwi::CreateWidget('Button', 'send', _t('GLOBAL_SAVE'), STOCK_SAVE);
        $submitButton->SetSubmit();

        $buttonbox =& Piwi::CreateWidget('HBox');
        $buttonbox->SetStyle('float: right;');
        $buttonbox->PackStart($previewButton);
        $buttonbox->PackStart($submitButton);

        $fieldset->Add($name);
        $fieldset->Add($email);
        $fieldset->Add($url);
        $fieldset->Add($subject);
        $fieldset->Add($comment);
        if ($GLOBALS['app']->Registry->Get('/Mailserver/use') == 'yes') {
            $emailme =& Piwi::CreateWidget('CheckButtons', 'mail_comment');
            $emailme->AddOption(_t('BLOG_MAIL_COMMENT_TO_ME'), 'mail_comment');
            $form->Add($emailme);
        }

        if (
            $GLOBALS['app']->Registry->Get('/gadgets/AntiSpam/allow_captchas') == 'yes' &&
            $GLOBALS['app']->Registry->Get('/gadgets/Blog/use_antispam') == 'true' &&
            $captchasCanBeUsed
        ) {
            $fieldset->Add($captchaCode);
            $fieldset->Add($captcha, '<small>'._t('GLOBAL_CAPTCHA_CODE_DESC').'</small>');
        }

        $form->add($fieldset);
        $form->Add($buttonbox);

        $tpl->SetVariable('form', $form->Get());
        $tpl->ParseBlock('commentform');

        return $tpl->Get();
    }

    /**
     * Displays a preview of the given blog comment
     *
     * @access       public
     * @return       template content
     */
    function Preview()
    {
        $tpl =& new JawsTemplate('gadgets/Blog/templates/');
        $tpl->Load('Comment.html');
        // display comment preview

        $tpl->SetBlock('comment');
        $tpl->SetVariable('name',  $GLOBALS['app']->XSS->filter($_POST['name']));
        $tpl->SetVariable('email', $GLOBALS['app']->XSS->filter($_POST['email']));
        $tpl->SetVariable('url',   $GLOBALS['app']->XSS->filter($_POST['url']));
        if (!isset($_POST['ip_address'])) {
            $_POST['ip_address'] = $_SERVER['REMOTE_ADDR'];
        }
        $tpl->SetVariable('title', $GLOBALS['app']->XSS->filter($_POST['title']));
        $tpl->SetVariable('comments', $this->ParseText($_POST['comments']));
        if (!isset($_POST['createtime'])) {
            $d    = getdate();
            $year = $d['year'];
            $mon  = $d['mon'];
            $day  = $d['mday'];
            $_POST['createtime'] = $GLOBALS['app']->Date->Format($year . $mon . $day);
        }
        $tpl->SetVariable('createtime', $_POST['createtime']);
        $tpl->SetVariable('level', 0);

        $tpl->SetVariable('ip_address', $_POST['ip_address']);
        $tpl->SetVariable('avatar_source', 'images/unknown.png');
        $tpl->SetVariable('replies', '0');
        $tpl->SetVariable('commentname', 'comment_preview');

        $tpl->ParseBlock('comment');
        // display comment form
        $commentForm = $this->DisplayCommentForm($_POST['parent_id'], $_POST['parent'],
                                                 $_POST['title'], $_POST['comments']);
        return $tpl->Get().$commentForm;
    }
    /**
     * Saves the given blog comment
     *
     * @access       public
     * @return       template content
     */
    function SaveComment()
    {
        require_once JAWS_PATH . 'include/JawsTypes/JawsHeader.php';

        if (trim($_POST['name']) == '' || trim($_POST['title']) == '' || trim($_POST['comments']) == '') {
            return $this->Preview();
        }


        $id  = (int)$_POST['parent_id'];
        $url = $this->GetURLFor('SingleView', array('id' => $id));
        if (
            $GLOBALS['app']->Registry->Get('/gadgets/AntiSpam/allow_captchas') == 'yes' &&
            $GLOBALS['app']->Registry->Get('/gadgets/Blog/use_antispam') == 'true'
        ) {

            require_once JAWS_PATH . 'include/JawsCaptcha.php';
            $jawsCaptchas =& JawsCaptcha::factory('Image');

            if ($jawsCaptchas->CanBeUsed()) {
                if (isset($_POST['captcha']) && isset($_POST['captchaKey'])) {
                    if (!$jawsCaptchas->IsValid($_POST['captchaKey'], $_POST['captcha'])) {
                        JawsHeader::Location($url);
                    }
                } else {
                    JawsHeader::Location($url);
                }
            }
        }

        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $model->NewComment($_POST['name'], $_POST['title'], $_POST['url'],
                           $_POST['email'], $_POST['comments'], $_POST['parent'],
                           $_POST['parent_id']);

        JawsHeader::Location($url);
    }

    /**
     * Displays a list of blog entries ordered by date
     *
     * @access       public
     * @return       template content
     */
    function Archive()
    {
        $tpl =& new JawsTemplate('gadgets/Blog/templates/');
        $tpl->Load('Archive.html');
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $archiveEntries = $model->GetEntriesAsArchive();
        $auxMonth = '';
        $tpl->SetBlock('archive');
        $tpl->SetVariable('archive', _t('BLOG_ARCHIVE'));
        if (!JawsError::IsError($archiveEntries)) {
            foreach ($archiveEntries as $entry) {
                $currentMonth = $GLOBALS['app']->Date->Format($entry['createtime'], 'MN');
                if ($currentMonth != $auxMonth) {
                    if ($auxMonth != '') {
                        $tpl->ParseBlock('archive/month');
                    }
                    $tpl->SetBlock('archive/month');
                    $year = $GLOBALS['app']->Date->Format($entry['createtime'], 'Y');
                    $tpl->SetVariable('month', $currentMonth);
                    $tpl->SetVariable('year', $year);
                    $auxMonth = $currentMonth;
                }
                $tpl->SetBlock('archive/month/record');
                $tpl->SetVariable('id', $entry['id']);
                $tpl->SetVariable('date',           $GLOBALS['app']->Date->Format($entry['createtime']));
                $tpl->SetVariable('date-monthname', $currentMonth);
                $tpl->SetVariable('date-month',     $GLOBALS['app']->Date->Format($entry['createtime'], 'm'));
                $tpl->SetVariable('date-day',       $GLOBALS['app']->Date->Format($entry['createtime'], 'd'));
                $tpl->SetVariable('date-year',      $year);
                $tpl->SetVariable('date-time',      $GLOBALS['app']->Date->Format($entry['createtime'], 'g:ia'));
                $tpl->SetVariable('title', $GLOBALS['app']->XSS->filter($entry['title']));
                $tpl->SetVariable('comments', $entry['comments']);
                if (empty($entry['fast_url'])) {
                    $url = $GLOBALS['app']->Map->GetURLFor('Blog', 'SingleView', array('id' => $entry['id']));
                } else {
                    $url = $GLOBALS['app']->Map->GetURLFor('Blog', 'SingleView', array('id' => $entry['fast_url']));
                }
                $tpl->SetVariable('view-link', $url);
                $tpl->ParseBlock('archive/month/record');
            }
            $tpl->ParseBlock('archive/month');
        }
        $tpl->ParseBlock('archive');

        return $tpl->Get('archive');
    }

    /**
     * Displays or writes a RSS feed for the blog
     *
     * @access       public
     * @param        boolean $save true to save RSS, false to display
     * @return       xml with RSS feed on display mode, nothing otherwise
     */
    function RSS($save = false)
    {
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $rss = $model->MakeRSS(true);
        if (!JawsError::IsError($rss)) {
            if (!$save) {
                header('Content-type: application/xml');
                return($rss);
            }
        }
    }

    /**
     * Displays or writes an Atom feed for the blog
     *
     * @access       public
     * @param        boolean $save true to save Atom, false to display
     * @return       xml with Atom feed on display mode, nothing otherwise
     */
    function Atom($save = false)
    {
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $atom = $model->MakeAtom();
        if (!JawsError::IsError($atom)) {
            if (!$save) {
                header('Content-type: application/xml');
                return($atom);
            }
        }
    }

    /**
     * Displays a RSS feed for a given blog category
     *
     * @access       public
     * @return       xml with RSS feed
     */
    function ShowRSSCategory()
    {
        header('Content-type: text/xml');
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $xml = $model->MakeCategoryRSS($_GET['id']);
        if (JawsError::IsError($xml)) {
            return '';
        }
        return $xml;
    }

    /**
     * Displays an Atom feed for a given blog category
     *
     * @access       public
     * @return       xml with Atom feed
     */
    function ShowAtomCategory()
    {
        header('Content-type: text/xml');
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $xml = $model->MakeCategoryAtom($_GET['id']);
        if (JawsError::IsError($xml)) {
            return '';
        }

        return $xml;
    }

    /**
     * Displays an Atom feed for blog most recent comments
     *
     * @access       public
     * @return       xml with Atom feed
     */
    function RecentCommentsAtom()
    {
        header('Content-type: text/xml');
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $xml = $model->GetRecentCommentsAtom();
        if (JawsError::IsError($xml)) {
            return '';
        }

        return $xml;
    }

    /**
     * Displays a RSS feed for blog most recent comments
     *
     * @access       public
     * @return       xml with RSS feed
     */
    function RecentCommentsRSS()
    {
        header('Content-type: text/xml');
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $xml = $model->GetRecentCommentsRSS();
        if (JawsError::IsError($xml)) {
            return '';
        }

        return $xml;
    }

    /**
     * Displays an Atom feed for most recent comments on the given blog entry
     *
     * @access       public
     * @return       xml with Atom feed
     */
    function CommentsAtom()
    {
        header('Content-type: text/xml');
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $xml = $model->GetPostCommentsAtom($_GET['id']);
        if (JawsError::IsError($xml)) {
            return '';
        }

        return $xml;
    }

    /**
     * Displays a RSS feed for most recent comments on the given blog entry
     *
     * @access       public
     * @return       xml with RSS feed
     */
    function CommentsRSS()
    {
        header('Content-type: text/xml');
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $xml = $model->GetPostCommentsRSS($_GET['id']);
        if (JawsError::IsError($xml)) {
            return '';
        }

        return $xml;
    }

    /**
     * Displays a list of blog posts included on the given category
     *
     * @access       public
     * @return       template content
     */
    function ShowCategory()
    {
        $base_url = $GLOBALS['app']->Registry->Get('/config/url').'data/xml/';
        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        $id = (int)$_GET['id'];
        $cat = $model->GetCategory($id);
        $name = $GLOBALS['app']->XSS->parse($cat['name']);
        $GLOBALS['app']->Layout->AddHeadLink($base_url.'blog.atom', 'alternate', 'application/atom+xml', 'Atom - '.$name, false);
        $GLOBALS['app']->Layout->AddHeadLink($base_url.'blog.rss', 'alternate', 'application/rss+xml', 'RSS 2.0 - '.$name, false);

        $tpl =& new JawsTemplate('gadgets/Blog/templates/');
        $tpl->Load('ShowCategory.html');
        $title = false;
        $entries = $model->GetEntriesByCategory($id);

        $result = '';
        if (!JawsError::IsError($entries)) {
            foreach ($entries as $e) {
                if (!$title) {
                    $tpl->SetBlock('show_category');
                    $catInfo = $model->GetCategory($id);
                    $tpl->SetVariable('title', $GLOBALS['app']->XSS->filter($catInfo['name']));
                    $tpl->ParseBlock('show_category');
                    $title = true;
                    $result .= $tpl->Get();
                }
                $result .= $this->ShowEntry($e, true, true, true);
            }
        }
        return $result;
    }

    /**
     * Saves a new trackback if all is ok and sends response
     * The function other people send to so our blog gadget
     * gets trackbacks
     *
     * @access       public
     * @return       trackback xml response
     */
    function Trackback()
    {
        // Based on Wordpress trackback implementation
        $tb_msg_error = '<?xml version="1.0" encoding="iso-8859-1"?><response><error>1</error><message>#MESSAGE#</message></response>';
        $tb_msg_ok = '<?xml version="1.0" encoding="iso-8859-1"?><response><error>0</error></response>';
        if (!isset($_POST['title']) || !isset($_POST['url']) ||
            !isset($_POST['blog_name']) || !($_POST['excerpt'])) {
            require_once JAWS_PATH . 'include/JawsTypes/JawsHeader.php';
            JawsHeader::Location('index.php');
        }
        
        $id = isset($_GET['id']) ? $_GET['id'] : '';
        if (empty($id)) {
            if (isset($_POST['id'])) {
                $id = $_POST['id'];
            } else {
                $id = '';
            }
        }
        $title    = $_POST['title'];
        $url      = $_POST['url'];
        $blogname = $_POST['blog_name'];
        $excerpt  = $_POST['excerpt'];

        if (trim($id) == '') {
            require_once JAWS_PATH . 'include/JawsTypes/JawsHeader.php';
            JawsHeader::Location('index.php');
        } elseif (empty($title) && empty($url) && empty($blogname)) {
            require_once JAWS_PATH . 'include/JawsTypes/JawsHeader.php';
            JawsHeader::Location('index.php?gadget=Blog&action=SingleView&id='.$id);
        } elseif ($GLOBALS['app']->Registry->Get('/gadgets/Blog/trackback') == 'true') {
            header('Content-Type: text/xml');
            $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
            $trackback = $model->NewTrackback($id, $url, $title, $excerpt, $blogname);
            if (JawsError::IsError($trackback)) {
                return str_replace('#MESSAGE#', $trackback->GetMessage(), $tb_msg_error);
            }
            return $tb_msg_ok;
        } else {
            header('Content-Type: text/xml');
            return str_replace('#MESSAGE#', _t('BLOG_TRACKBACK_DISABLED'), $tb_msg_error);
        }
    }

    /**
     * Shows existing trackbacks for a given entry
     *
     * @access       public
     * @param        int $id entry id
     * @return       template content
     */
    function ShowTrackbacks($id)
    {
        if ($GLOBALS['app']->Registry->Get('/gadgets/Blog/trackback') == 'true') {
            $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
            $trackbacks = $model->GetTrackbacks($id);
            $tpl =& new JawsTemplate('gadgets/Blog/templates/');
            $tpl->Load('Trackbacks.html');
            $tpl->SetBlock('trackbacks');
            $tburi = $this->GetURLFor('Trackback', array('id' => $id));
            $tpl->SetVariable('TrackbackURI', $tburi);
            if (!JawsError::IsError($trackbacks)) {
                foreach ($trackbacks as $tb) {
                    $tpl->SetBlock('trackbacks/item');
                    $tpl->SetVariablesArray($tb);
                    $tpl->SetVariable('createtime', $GLOBALS['app']->Date->Format($tb['createtime']));
                    $tpl->SetVariable('createtime-monthname', $GLOBALS['app']->Date->Format($tb['createtime'], 'MN'));
                    $tpl->SetVariable('createtime-month', $GLOBALS['app']->Date->Format($tb['createtime'], 'm'));
                    $tpl->SetVariable('createtime-day', $GLOBALS['app']->Date->Format($tb['createtime'], 'd'));
                    $tpl->SetVariable('createtime-year', $GLOBALS['app']->Date->Format($tb['createtime'], 'Y'));
                    $tpl->SetVariable('createtime-time', $GLOBALS['app']->Date->Format($tb['createtime'], 'g:ia'));
                    $tpl->ParseBlock('trackbacks/item');
                }
            }
            $tpl->ParseBlock('trackbacks');

            return $tpl->Get();
        }
    }

    /**
     * Generate captcha image
     *
     * @access  public
     * @return  binary  An image
     */
    function Captcha()
    {
        if (
            $GLOBALS['app']->Registry->Get('/gadgets/AntiSpam/allow_captchas') == 'yes' &&
            $GLOBALS['app']->Registry->Get('/gadgets/Blog/use_antispam') == 'true'
        ) {
            require_once JAWS_PATH . 'include/JawsCaptcha.php';
            $md5 = isset($_GET['key']) ? $_GET['key'] : '';
            $jawsCaptchas =& JawsCaptcha::factory('Image');
            $image = $jawsCaptchas->Build($md5);

            return $image;
        }

        return '';
    }
	 /**
     * Displays an editor to write a new blog entry or preview it before saving
     *
     * @access       public
     * @param        string $action "preview" or empty(optional, empty by default)
     * @return       template content
     */
    function NewEntry($action = '')
    {
      //  $GLOBALS['session']->CheckPermission('Blog', 'AddEntries');

        $GLOBALS['app']->Layout->AddScriptLink('index.php?gadget=Blog&amp;action=Ajax&amp;client');
        $GLOBALS['app']->Layout->AddScriptLink('index.php?gadget=Blog&amp;action=AjaxCommonFiles');
        $GLOBALS['app']->Layout->AddScriptLink('gadgets/Blog/resources/Blog.js');

        $tpl =& new JawsTemplate('gadgets/Blog/templates/');
        $tpl->Load('EditEntry.html');
        $tpl->SetBlock('edit_entry');

        // Header
        $tpl->SetVariable('menubar', $this->MenuBar('NewEntry'));
        $tpl->SetVariable('icon', JawsUtils::CheckImage('gadgets/Blog/images/Blog.png'));
        $tpl->SetVariable('name', '<a href="index.php">'._t('CONTROLPANEL_NAME').
                          "</a> &rarr; ".$this->_Name);

        // Title
        $tpl->SetVariable('title', _t('GLOBAL_TITLE'));
        $tpl->SetVariable('action', 'NewEntry');
        $tpl->SetVariable('id', 0);
        $titleEntry =& Piwi::CreateWidget('Entry', 'title', '');
        $titleEntry->SetStyle('width: 95%');
        $titleEntry->setId('title');
        $tpl->SetVariable('title_field', $titleEntry->Get());

        $model =& $GLOBALS['app']->LoadGadget('Blog', 'Model');
        // Category
        $catChecks =& Piwi::CreateWidget('CheckButtons', 'categories', 'vertical');
        $categories = $model->GetCategories();
        if (!JawsError::IsError($categories)) {
            foreach ($categories as $a) {
                $catChecks->AddOption($GLOBALS['app']->XSS->filter($a['name']), $a['id']);
            }
        }
        $catDefault = split(',', $GLOBALS["app"]->Registry->Get("/gadgets/Blog/default_category"));
        $catChecks->SetDefault($catDefault);
        $catChecks->OrderBySelected();

        $tpl->SetVariable('category', _t('GLOBAL_CATEGORY'));
        $tpl->SetVariable('category_field', $catChecks->Get());

        // Body
        $tpl->SetVariable('text', _t('BLOG_ENTRY_BODY'));
        $editor =& $GLOBALS['app']->LoadEditor('Blog', 'text', '');
        $editor->setId('text');
        $editor->TextArea->SetStyle('width: 100%;');
        $editor->SetWidth('96%');
        $tpl->SetVariable('editor', $editor->Get());

        // Allow Comments
        $comments =& Piwi::CreateWidget('CheckButtons', 'allow_comments');
        if ($GLOBALS['app']->Registry->Get('/gadgets/Blog/allow_comments') == 'true') {
            $selected = true;
        } else {
            $selected = false;
        }
        $comments->AddOption(_t('BLOG_ALLOW_COMMENTS'), 'comments', $selected);
        $tpl->SetVariable('allow_comments_field', $comments->Get());

        // Status
        $tpl->SetVariable('status', _t('BLOG_STATUS'));

        $statCombo =& Piwi::CreateWidget('Combo', 'published');
        $statCombo->setId('published');
        $statCombo->AddOption(_t('BLOG_DRAFT'), '0');
        $statCombo->AddOption(_t('BLOG_PUBLISHED'), '1');
        $statCombo->SetDefault('1');

        $tpl->SetVariable('status_field', $statCombo->Get());

        // Save
        $saveButton =& Piwi::CreateWidget('Button', 'save', _t('GLOBAL_SAVE'), STOCK_SAVE);
        $saveButton->AddEvent(ON_CLICK, "javascript: if(this.form.elements['title'].value == '') { alert('".
                              _t('BLOG_MISSING_TITLE') . "'); this.form.elements['title'].focus(); } ".
                              "else { this.form.submit(); }");
        $tpl->SetVariable('save_button', $saveButton->Get());

        // Preview
        // TODO: We need a different stock icon for this.
        $previewButton =& Piwi::CreateWidget('Button', 'preview', _t('GLOBAL_PREVIEW'), STOCK_PRINT_PREVIEW);
        $previewButton->AddEvent(ON_CLICK, "javascript: parseText(this.form);");

        $tpl->SetVariable('preview_button', $previewButton->Get());

        // Advanced stuff..
        $tpl->SetBlock('edit_entry/advanced');
        $advancedDefault = false;
        $tpl->SetVariable('advanced_style', 'display: none;');

        $editAdvancedchk =& Piwi::CreateWidget('CheckButtons', 'edit_advanced');
        $editAdvancedchk->SetID('advanced_toggle');
        $editAdvancedchk->AddOption(_t('BLOG_ADVANCED_MODE'), 'advanced', $advancedDefault);
        $editAdvancedchk->AddEvent(ON_CHANGE, 'toggleAdvanced();');
        $tpl->SetVariable('advanced_field', $editAdvancedchk->Get());

        $tpl->SetVariable('timestamp_label', _t('BLOG_EDIT_TIMESTAMP'));
        $tsChk =& Piwi::CreateWidget('CheckButtons', 'edit_timestamp');
        $tsChk->AddOption(_t('GLOBAL_UPDATE'), 'yes', false);
        $tpl->SetVariable('timestamp_check', $tsChk->Get());
        // Maybe we need to get date from MDB2
        $tsTxt =& Piwi::CreateWidget('Entry', 'timestamp', date('Y-m-d H:i:s'));
        $tpl->SetVariable('timestamp', $tsTxt->Get());

        $tpl->SetVariable('fasturl', _t('BLOG_FASTURL'));
        $tpl->SetVariable('fasturl_comment', _t('BLOG_FASTURL_COMMENT'));

        $fastUrlEntry =& Piwi::CreateWidget('Entry', 'fasturl', '');
        $fastUrlEntry->SetStyle('width: 100%');
        $tpl->SetVariable('fasturl_field', $fastUrlEntry->Get());

        if ($GLOBALS['app']->Registry->Get('/gadgets/Blog/trackback') == 'true') {
            $tpl->SetBlock('edit_entry/advanced/trackback');
            $tpl->SetVariable('trackback_to', _t('BLOG_TRACKBACK'));
            $tb =& Piwi::CreateWidget('TextArea', 'trackback_to', '');
            $tb->SetRows(4);
            $tb->SetColumns(30);
            // TODO: Remove this nasty hack, and replace it with some padding in the template.
            $tb->SetStyle('width: 99%;');
            $tpl->SetVariable('trackbackTextArea', $tb->Get());
            $tpl->ParseBlock('edit_entry/advanced/trackback');
        }
        $tpl->ParseBlock('edit_entry/advanced');
        $tpl->ParseBlock('edit_entry');
        return $tpl->Get();
    }

}
?>