<?php
/**
 * Implementation for the main application controller plugin class.
 *
 * @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
 */

/**
 * Front controller plugin for cookies and other application things.
 *
 * @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 HomeWebApp_Plugin_Main extends Zend_Controller_Plugin_Abstract
{
    /**
     * Plugin hook before front controller begins evaluating the request.
     *
     * Sets language and locale if necessary parameters are presented in the url.
     * This is a hack, because directly modifies the $request->pathInfo, which
     * is the used for matching routes.
     *
     * If detected language is
     */
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        //set host part for the base application URL
        AppBaseUrl::setHost($request->getServer("SERVER_NAME"));

        /* @var $bootstrap Bootstrap */
        $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
        /* @var $appLog Zend_Log */
        $appLog = $bootstrap->getResource("log");

        //pathinfo = requestUri - baseUrl
        //e.g.:
        //whole URL = http://server_name/homepage/blog/myitem
        //requestUri = /homepage/blog/myitem, baseUrl= /homepage, pathInfo=/blog/myitem
        $pathInfo = $request->getPathInfo();

        //check if lang identfier is in the pathinfo
        if (preg_match('#^/([a-z]{2}/|[a-z]{2}$)#',$pathInfo,$matches)) {
            $appLog->info("lang matched in pathInfo");
            $urlLang = rtrim($matches[1],'/');
            $appLog->info("urlLang: $urlLang");
            //remove lang identifiers from the pathInfo and sets as new pathinfo
            $pathInfo = strlen($pathInfo)==3 ? "/" : substr($pathInfo,3);
            $request->setPathInfo($pathInfo);
        } else {
            //language isn't in the url, default lang "without url specification" is cs
            $urlLang = "cs";
            $appLog->info("no urlLang found, sets default: $urlLang");
        }

        $appLog->info("pathInfo after language cut:" . $request->getPathInfo());

        $locale = $bootstrap->getResource("locale");
        $translate = $bootstrap->getResource("translate");
        
        //set detected language if we have available translation for detected
        //locale
        if (in_array($urlLang, $translate->getList())) {
            $translate->setLocale($urlLang);
            $locale->setLocale($urlLang);
        } else {
            //cannot set requested locale, sets application default locale and
            //redirects into page with default locale
            $defaultLocale = current(array_keys(Zend_Locale::getDefault()));
            $translate->setLocale($defaultLocale);
            $locale->setLocale($defaultLocale);
            trigger_error("translation for requested language '$urlLang' "
                . "isn't presented, so the redicrection into pages for default locale "
                . $defaultLocale . " will be used." ,
                E_USER_WARNING
            );
            //redirect
            $queryString = http_build_query($request->getParams());
            $redirectUrl = AppBaseUrl::getBaseUrl() . "/" . $locale->getLanguage()
                . $pathInfo
                . ($queryString ? "?". $queryString : "");
             //redirect via response object
            $this->getResponse()->setRedirect($redirectUrl)->sendHeaders();
            exit;
        }
        
        //set language in viewrenderer views
        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
        $viewRenderer->view->currentLang = $locale->getLanguage();
        //set doctype placeholder, needed in some form elements view helpers
        $viewRenderer->view->doctype('XHTML1_STRICT');
    }

    /**
     * Plugin hook after Zend_Controller_Front exits a whole dispatch loop.
     *
     * Add cookies and sets some headers, encoding. One note for encoding, if our
     * default encoding is utf-8 everything is ok, if not, ajax responses must
     * be encoded in utf-8 every time.
     */
    public function dispatchLoopShutdown()
    {
        $request  = $this->getRequest();
        $response = $this->getResponse();

        $response->setHeader("Cache-Control","max-age=7200,must-revalidate",true);
    }
}
