<?php
/**
 * Implementation of blog administration controller for trackbacks
 *
 * @package koubel homepage
 * @author Miroslav Kubelik (koubel@volny.cz)
 * @copyright Copyright (c) 2007-2009 Miroslav Kubelik
 * @license http://opensource.org/licenses/gpl-license.php GNU GPL
 */

/**
 * Serves administration actions for blog trackbacks
 *
 * @package koubel homepage
 * @author Miroslav Kubelik (koubel@volny.cz)
 * @copyright Copyright (c) 2007-2009 Miroslav Kubelik
 * @license http://opensource.org/licenses/gpl-license.php GNU GPL
 */
class Blog_Admin_TrackBackController extends Zend_Controller_Action
{
    /** count of items in a trackback list */
    const ITEMS_PER_PAGE = 10;

    /**
     * Views the table with the trackback list, the pagination is supported.
     */
    public function indexAction()
    {
        $trackBack = new TrackBackEntry();
        $this->view->trackbacks = $trackBack->getAll(
            $this->_helper->Paginator->getPageNumber(),
            self::ITEMS_PER_PAGE
        );

        $this->view->paginator = $trackBack->getPaginator();

        if ($this->_helper->flashMessenger->hasMessages()) {
            $this->view->messages=$this->_helper->flashMessenger->getMessages();
        }
    }

    /**
     * Views a dialog for an edit trackback page with a form.
     * It is used as target for the forward or redirect from the another actions,
     * hence it can set a form data from an old request, which will not serve 
     * in another actions.
     */
    public function editAction()
    {
        $trackBack = new TrackBackEntry();

        //in POST are old data, it occures when current submitted data are 
        //invalid, so we print old data in form, user can corrects these.
        if (isset($_POST["trackbackId"])) {
            $data = $this->getRequest()->getPost();
            $this->view->formData = $data;
            $this->view->formData["id"] = $data["trackbackId"];
            $trackBack->findById( $data["trackbackId"] );
        } else {
            //no old data, gets data from database
            $trackBack->findById( $this->_getParam("itemId") );
            $this->view->formData = $trackBack->getDaoRow(false)->toArray();

            //special format for a datetime
            $date = new Zend_Date($trackBack->getPosted(),Zend_Date::ISO_8601,"en_US");
            $this->view->formData["posted"] = $date->toString('dd-MM-yyyy HH:mm:ss');

        }//end isset($_POST["trackbackId"]

        $relatedArticle = $trackBack->getArticle();
        $this->view->article = $relatedArticle;
        $this->view->articleUrl = $this->_helper->url->url(
            array("entry" => $relatedArticle->getTitleUrl()),"blogArticle"
        );

        if ($this->_helper->flashMessenger->hasMessages()) {
            $this->view->messages=$this->_helper->flashMessenger->getMessages();
        }
    }

    /**
     * Updates the trackback entry in the database.
     * If something fails, forwards to the editAction. If the database update was OK, redirects
     * to the editAction with some flash message.
     */
    public function updateDbAction()
    {
        // Don't auto render
        $this->_helper->viewRenderer->setNoRender();
        $data=$this->getRequest()->getPost();

        $filters = array(
            'title' =>'StringTrim',
            'excerpt' => 'StringTrim',
            'url' => 'StringTrim',
            'blogName' => 'StringTrim',
            'ipAddr'  => 'StringTrim'
        );

        $validators = array(
            'title'   => 'NotEmpty',
            'excerpt'   => 'NotEmpty',
            'url'   => array('NotEmpty',new UrlValid()),
            'blogName'   => 'NotEmpty',
            'isSpam'   => 'NotEmpty',
            'ipAddr'   => array('NotEmpty','Ip'),
            'posted' => array('NotEmpty',new DateTimeValid())
        );

        $inputFilter = new Zend_Filter_Input($filters, $validators);
        $inputFilter->setData($data);

        if ($inputFilter->isValid()) {
            $title = $inputFilter->getUnescaped("title");
            $excerpt = $inputFilter->getUnescaped("excerpt");
            $url = $inputFilter->getUnescaped("url");
            if (!empty($url) && !preg_match("|^http(s)?://|i",$url)) $url="http://".$url;
            $postedDate = new Zend_Date($inputFilter->posted,'dd-MM-yyyy HH:mm:ss',"en_US");
            $blogName = $inputFilter->getUnescaped("blogName");
            $isSpam = $inputFilter->getUnescaped("isSpam");
            $ipAddr = $inputFilter->getUnescaped("ipAddr");

            $trackBack = new TrackBackEntry();
            
            try {
                $trackBack->setId($data["trackbackId"]);
                $trackBack->setTitle($title);
                $trackBack->setExcerpt($excerpt);
                $trackBack->setUrl($url);
                $trackBack->setBlogName($blogName);
                $trackBack->setIpAddr($ipAddr);
                $trackBack->setSpam($isSpam);
                $trackBack->setPosted($postedDate->toString('yyyy-MM-dd HH:mm:ss'));
                $trackBack->update();
            } catch (Zend_Db_Exception $e) {
                $message = "Cannot update record, database error: ".$e->getMessage();
                $this->view->messages = array($message);
                $this->_forward("edit");
                return;
            }

            $message="Record was updated";
            $this->_helper->flashMessenger->addMessage($message);
            $this->_helper->redirector->gotoUrlAndExit($this->_helper->url->url(
                array(
                    "controller" => "trackback",
                    "action" => "edit",
                    "itemId" => $trackBack->getId()
                ),
                "blogAdminItemAction"),
                array("prependBase"=>false));
            return;

        } else {
            //invalid data
            $messages[] = "Data are invalid:";
            $messages = array_merge($messages,Utils::getMessagesOneArray($inputFilter));
            $this->view->messages = $messages;
            $this->_forward("edit");
            return;
        }
    }

    /**
     * Search for a trackback - view a search form
     */
    public function searchAction()
    {
    }

    /**
     * Action, which is aim for a search trackback entry dialog.
     * When input data are invalid, forwards to the {@link searchAction()}.
     */
    public function searchResultAction()
    {
        if ($this->_hasParam("title")) {
            $data = $this->getRequest()->getPost();
            $filters = array(
                'title'   => 'StringTrim',
                'excerpt' => 'StringTrim',
                'blogName' => 'StringTrim',
                'from' => 'StringTrim',
                'to' => 'StringTrim'
            );

            $validators = array(
                'title' =>  array(Zend_Filter_Input::ALLOW_EMPTY => "true"),
                'excerpt' =>  array(Zend_Filter_Input::ALLOW_EMPTY => "true"),
                'blogName' =>  array(Zend_Filter_Input::ALLOW_EMPTY => "true"),
                'from' =>  array(Zend_Filter_Input::ALLOW_EMPTY => "true"),
                'to' =>  array(Zend_Filter_Input::ALLOW_EMPTY => "true"),
                'isSpam'   => new Zend_Validate_InArray(array("undef",1,0))
            );

            $inputFilter = new Zend_Filter_Input($filters,$validators);

            $inputFilter->setData($data);

            if ($inputFilter->isValid()) {
                $params = array(
                    "title" => $inputFilter->getUnescaped('title'),
                    "excerpt" => $inputFilter->getUnescaped('excerpt'),
                    "blogName" => $inputFilter->getUnescaped('blogName'),
                    "from" => $inputFilter->from,
                    "to" => $inputFilter->to,
                    "isSpam" => $inputFilter->isSpam
                );
            } else {
                //invalid data
                $messages[] = "Data are invalid:";
                $messages = array_merge($messages,Utils::getMessagesOneArray($inputFilter));
                $this->view->messages = $messages;
                $this->_forward("search");
                return;
            }
        }

        //search object
        $search = Search::factorySearch("SearchBlogTrackBack");
        //set the pagination
        $search->setPageParams(
            $this->_helper->Paginator->getPageNumber(),
            self::ITEMS_PER_PAGE
        );

        //set search parameters if are in the request, otherwise these are loaded from
        //session in the factory
        if (isset($params)) {
            $search->setParams($params);
        }

        //search result
        $trackBack = new TrackBackEntry();
        //found items
        $this->view->foundItems = $trackBack->getFound($search);
        $this->view->paginator = $search->getPaginator();

        $this->_helper->viewRenderer->setRender('index');

        //save search params to session if we have more then one page
        if (count($this->view->paginator)>1) {
            $search->saveToSession();
        }
    }

    /**
     * Action, which is complete responsible for a removing trackback from the database.
     * It views dialog for the confirmation, than if we realy want delete item and
     * serves database removing also.
     */
    public function deleteAction()
    {
        $trackBack = new TrackBackEntry();
        $itemId = $this->_getParam("itemId");
        $trackBack->findById($itemId);

        //"really want" delete flag
        $delflag = false;

        //confirmation was send
        if (isset($_GET['wantdel']))
        {
            //No - redirect entry list
            if ($_GET['wantdel']=="No") {
                $this->_helper->redirector->gotoUrlAndExit($this->_helper->url->url(
                array(
                    "controller" => "trackback",
                    "action" => "index",
                ),
                "blogAdmin"),array("prependBase"=>false));
                return;
            }
            //Yes - delete
            $delflag = $_GET['wantdel']=="Yes" ? true : false;
        }

        //if really want delete, make it
        if ($delflag) {
            //delete from database
            try {
                $trackBack->delete();
            } catch (Zend_Db_Exception $e) {
                $message = "Cannot delete record, database error: ".$e->getMessage();
                $this->_helper->flashMessenger->addMessage($message);
                $this->_helper->redirector->gotoUrlAndExit($this->_helper->url->url(
                    array(
                        "controller" => "trackback",
                        "action" => "delete",
                        "itemId" => $trackBack->getId()
                    ),
                    "blogAdminItemAction"),
                    array("prependBase"=>false)
                );
                return;
            }

            //redirect after successful deleting
            $this->_helper->flashMessenger->addMessage("TrackBack with ID ".$trackBack->getId()
                . " was deleted");
            $this->_helper->redirector->gotoUrlAndExit($this->_helper->url->url(
                array(
                    "controller" => "trackback",
                    "action" => "index"
                ),
                "blogAdmin"),array("prependBase"=>false));
            return;
        }

        $this->view->subject = "trackBack with ID: ".$trackBack->getId();
        $this->view->nextInfo = "<br />Title : ".$trackBack->getTitle();
        $this->view->wasDeleted = $delflag;

        //delete url
        $this->view->deleteUrl = $this->_helper->url->url(
                array(
                    "controller" => "trackback",
                    "action" => "delete",
                    "itemId" => $trackBack->getId()
                ),
                "blogAdminItemAction");

        if ($this->_helper->flashMessenger->hasMessages()) {
            $this->view->messages = $this->_helper->flashMessenger->getMessages();
        }

        $this->_helper->viewRenderer->setRender("admin/deleteItem",null,true);
    }
}
