<?php

class catalyzActions extends sfActions {
    public function redirectToUrl($url)
    {
        header('Location: ' . $url);
        exit;
    }

    public function executeLogin($request)
    {
        if ($this->getRequest()->getMethod() == sfRequest::POST) {
            if ($node = $request->getParameter('node')) {
                $ContentTree = ContentTree::instance();
                $ContentTree->build();
                $contentNode = $ContentTree->initializeCurrentNodeById($node);
                $loginHandler = Catalyz::getLoginHandler();

                if ($loginHandler->Login($request->getParameter('username'), $request->getParameter('password'), $request->getParameter('remember_password'))) {
                    $target = $contentNode->getUrl();
                    if (empty($target)) {
                        $target = '/';
                    }
                    $this->redirectToUrl($target);
                } else {
                    $this->redirectToUrl($contentNode->getUrl() . '?do=login&error=1');
                }
            } else {
                throw new Exception('Node parameter must be defined');
            }
        } else {
            // $this->redirectToUrl('/');
            $this->ContentTree = ContentTree::instance();
            $this->ContentTree->build();

            $nodeObject = $this->getUser()->getAttribute('node'); // if we came from the index, we already have a node
			if($nodeObject){
				$this->node = $this->ContentTree->getContentTreeNodeById($nodeObject->getId());

			}
            if (!$this->node) {
                $this->ContentTree->initializeCurrentNodeByReferer($request);
                $this->node = $this->ContentTree->getCurrentNode();
                if (is_null($this->node)) {
                    $this->node = $this->ContentTree->getRoot();
                }
            }
        }
    }

    public function executeForgotPassword($request)
    {
        return Catalyz::getLoginHandler()->ForgotPassword($this, $request);

    }
    public function executeForgotLogin($request)
    {
		return Catalyz::getLoginHandler()->ForgotLogin($this, $request);

    }

    public function executeLogout($request)
    {
        $loginHandler = Catalyz::getLoginHandler();
        $loginHandler->Logout();

        $referer = $request->getReferer();
        if (empty($referer)) {
            $this->redirectToUrl('/');
        } else {
            $this->redirectToUrl(str_replace(sfConfig::get('app_admin_url'), sfConfig::get('app_static_url'), $referer));
        }
    }
    protected function getRequestUri()
    {
        $path = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : false;
        if (!$path && isset($_SERVER['REQUEST_URI'])) {
            $path = $_SERVER['REQUEST_URI'];
        }
        return $path;
    }
    protected function getCurrentPath()
    {
        $path = $this->getRequestUri();
        // if (!$path && isset($_REQUEST['path'])) {
        // $path = $_REQUEST['path'];
        // }
        // var_dump($path);exit;
        if (substr($path, 0, 1) != '/') {
            $path = '/' . $path;
        }
        $pos = strpos($path, '?');
        if ($pos !== false) {
            $path = substr($path, 0, $pos);
        }
        return $path;
    }

    protected function populateResquestWithParameters($request)
    {
        $path = $this->getRequestUri();
        $pos = strpos($path, '?');
        if ($pos !== false) {
            $path = substr($path, $pos + 1);
            $tokens = explode('&', $path);
            foreach($tokens as $token) {
                $items = explode('=', $token);
                $request->setParameter($items[0], isset($items[1])?urldecode($items[1]):null);
            }
        }
    }

    public function executeIndex($request)
    {
	    $loginPending = false;
		$this->getUser()->setAttribute('node', null);
		$this->getUser()->setAttribute('page', null);
		$this->getUser()->setAttribute('culture', null);


        $available_languages = sfConfig::get('app_translations_available_languages');

        $path = $this->getCurrentPath();
        if ('/' == $path && count($available_languages) > 1) {
            $ContentTree = ContentTree::instance(sfConfig::get('app_translations_default_language'));
            $ContentTree->build();
            $node = $ContentTree->getRoot()->getNode();
            if ($node) {
                $cultures = $node->getAvailableCultures();
            } else {
                $cultures = array(sfConfig::get('app_translations_default_language'));
            }
            $culture = $request->getPreferredCulture($cultures);
            $this->redirectToUrl('/' . $culture);
        } else {
            $ContentTree = null;
            $culture = sfConfig::get('app_translations_default_language');
        }

        if ($path != '') {
            $path = explode('/', $path);
            array_shift($path);

            if (in_array($path[0], $available_languages)) {
                $culture = array_shift($path);
                $this->getUser()->setCulture($culture);
            }
            $path = '/' . implode('/', $path);
        }
        $this->getUser()->setFlash('error', '');

        if (in_array($culture, sfConfig::get('app_translations_disabled', array())) && !$this->getUser()->hasCredential('webmaster')) {
            $this->redirectToUrl(sfConfig::get('app_translations_disabled_uri', '/coming_soon.html'));
        }

        Catalyz::setPageCulture($culture);
        if (null == $ContentTree) {
            $ContentTree = ContentTree::instance($culture);
            $ContentTree->build();
        }
        $contentNode = $ContentTree->initializeCurrentNodeByPath($path);
        if (empty($contentNode)) {
            //$this->forward404('Unable to find page: ' . $path);
        	$this->forward('catalyz', 'error404');
        }
        // var_dump($contentNode);exit;
        $page = Catalyz::getPageByNodeIdAndClass($contentNode->getId(), $contentNode->getNodeClass());
        $this->forward404Unless($page);

        $node = $page->getNode();
        // var_dump($node);exit;
        $this->node = $node;
        $this->page = $page;
        $this->culture = $culture;
        $this->ContentTree = $ContentTree;
        if (!$contentNode->canViewContent()) {
            $this->getUser()->setFlash('error', $this->getContext()->getI18N()->__('Access to target page is restricted. Please login to access it.', null,'catalyz'));
            $this->getUser()->setAttribute('node', $node);
            $this->getUser()->setAttribute('page', $page);
            $this->getUser()->setAttribute('culture', $culture);
            $this->forward('catalyz', 'login');
        }

        $this->populateResquestWithParameters($request);

        $this->prepareResponse($contentNode, $this->getResponse());

        if ($page instanceof ICatalyzContextualNode) {
            if (!$page->initializeContext($request, ICatalyzContextualNode::VIEW)) {
                $this->forward404('Invalid context');
            }
        }

        return sfView::SUCCESS;
    }

    protected function prepareResponse($contentNode, $response)
    {
        switch ($contentNode->getBrowserTitleType()) {
            case Node::BROWSER_TITLE_CUSTOM:
                $response->setTitle($contentNode->getBrowserTitleContent());
                break;
            case Node::BROWSER_TITLE_IS_PAGE_TITLE:
                $response->setTitle($contentNode->getTitle());
                break;
            default:
                // throw new Exception('Unknown BrowserTitle: ' . $contentNode->getBrowserTitleType());
        } // switch
        $response->addMeta('keywords', $contentNode->getSeoKeywords());
        $response->addMeta('description', $contentNode->getSeoDescription());
    }

    protected function populateNodeFromRequest(Node $node, $request)
    {
        $culture = $request->getParameter('culture', sfConfig::get('app_translations_default_language'));
        $node->setTitle($this->getRequestParameter('title'), $culture);
        // -- Content Tab
        $node->setIsVisibleInMenu((boolean)$this->getRequestParameter('is_visible_in_menu'));
        $node->setMenuTitleType($this->getRequestParameter('menu_type'), $culture);
        $node->setMenuTitleContent($this->getRequestParameter('menu_custom'), $culture);
        // -- SEO Tab
        $node->setBrowserTitleType($this->getRequestParameter('seo_title_type'), $culture);
        $node->setBrowserTitleContent($this->getRequestParameter('seo_title_custom'), $culture);

        $node->setSeoDescriptionType($this->getRequestParameter('seo_description_type'), $culture);
        $node->setSeoDescriptionContent($this->getRequestParameter('seo_description_custom'), $culture);

        $node->setSeoKeywordsType($this->getRequestParameter('seo_keywords_type'), $culture);
        $node->setSeoKeywordsContent($this->getRequestParameter('seo_keywords_custom'), $culture);

        $node->setUrlType($this->getRequestParameter('seo_uri_type'), $culture);
        if ($node->getUrlType($culture) == Node::URL_TYPE_CUSTOM) {
            $node->setUrlIdentifier($this->getRequestParameter('seo_uri_custom'), $culture);
        }
        // -- Permissions Tab
        if (Catalyz::getLoginHandler()->hasAccessToPermsTab() && Catalyz::getLoginHandler() instanceof ILoginHandlerPermissionAdminProvider) {
            Catalyz::getLoginHandler()->updateNodePermisions($node, $this->getRequest());
        }
        // -- Layout Tab
        $node->setCurrentLayoutType($this->getRequestParameter('layout_current_type'));
        $node->setCurrentLayout($this->getRequestParameter('catalyz_current_layout'));
        // check errors
        if ('' == trim($node->getTitle($culture))) {
            $this->errors['title'] = 'Please specify a page title';
        }
        if ($node->getIsVisibleInMenu()) {
            switch ($node->getMenuTitleType()) {
                case Node::MENU_TITLE_CUSTOM:
                    if ('' == trim($node->getMenuTitleContent())) {
                        $this->errors['menu_custom'] = 'Please specify a menu title';
                    }
                    break;
                case Node::MENU_TITLE_USE_PAGE_TITLE:
                    // no error
                    break;
                default:
                    throw new Exception('Unknown MenuTitleType: ' . $node->getMenuTitleType());
            } // switch
        }
        switch ($node->getBrowserTitleType($culture)) {
            case Node::BROWSER_TITLE_CUSTOM:
                if ('' == trim($node->getBrowserTitleContent($culture))) {
                    $this->errors['seo_title_custom'] = 'Please specify a browser title';
                }
                break;
            case Node::BROWSER_TITLE_IS_PAGE_TITLE:
                // no error
                break;
            default:
                throw new Exception('Unknown BrowserTitleType: ' . $node->getBrowserTitleType());
        } // switch
        switch ($node->getSeoKeywordsType($culture)) {
            case Node::SEO_KEYWORDS_CUSTOM:
                if ('' == trim($node->getSeoKeywordsContent($culture)) && !$node->isRoot()) {
                    $this->errors['seo_keywords_custom'] = 'Please specify custom keywords';
                }
                break;
            case Node::SEO_KEYWORDS_INHERIT:
                // no error
                break;
            default:
                throw new Exception('Unknown SeoKeywordsType: ' . $node->getSeoKeywordsType());
        } // switch
        switch ($node->getSeoDescriptionType($culture)) {
            case Node::SEO_DESCRIPTION_CUSTOM:
                if ('' == trim($node->getSeoDescriptionContent($culture)) && !$node->isRoot()) {
                    $this->errors['seo_description_custom'] = 'Please specify custom description';
                }
                break;
            case Node::SEO_DESCRIPTION_INHERIT:
                // no error
                break;
            default:
                throw new Exception('Unknown SeoDescriptionType: ' . $node->getSeoDescriptionType());
        } // switch
        switch ($node->getUrlType($culture)) {
            case Node::URL_TYPE_CUSTOM:
                if ('' == trim($node->getUrlIdentifier($culture))) {
                    $this->errors['seo_uri_custom'] = 'Please specify a custom address';
                }
                break;
            case Node::URL_TYPE_GENERATED:
                // no error
                break;
            default:
                throw new Exception('Unknown UrlType: ' . $node->getUrlType($culture));
        } // switch
        $ContentTreeNode = ContentTree::instance()->getContentTreeNodeById($node->getId());
        if ($ContentTreeNode) {
            $ContentTreeNode->refreshProperties($node);
        }
//		var_dump($node);
//		var_dump($ContentTreeNode);
//    	exit;
    }

    protected function displayEditForm($page, $node)
    {
        $this->page = $page;
        $this->node = $node;
        $this->availableLayouts = LayoutManager::instance()->getSupportedLayouts($page);
        if ($node->isRoot()) {
            $this->canUseInheritedLayout = false;
        } else {
            $parentPage = $node->getParent()->getPage();
            $layoutsSupportedByParent = LayoutManager::instance()->getSupportedLayouts($parentPage);
            $this->canUseInheritedLayout = count(array_intersect($this->availableLayouts, $layoutsSupportedByParent)) > 0;
        }

        return sfView::SUCCESS;
    }
    protected function handleEditCancel($node)
    {
        $target = ContentTree::instance()->getContentTreeNodeById($node->getId())->getURL();
        // if ($target == '#') {
        // $target = '/';
        // }
        $this->redirectToUrl($target);
    }
    protected function displayPreview($page, $node, $request)
    {
        $this->populateNodeFromRequest($node, $request);
        if ($page instanceof ICatalyzContentProvider) {
            $page->updateFromRequest($node, $request, true);
        }

        $this->node = $node;
        $this->page = $page;
        $this->prepareResponse($this->ContentTree->getContentTreeNodeById($node->getId()), $this->getResponse());
        return 'Preview';
    }
    protected function handleEditSubmit($page, $node, $request)
    {
        $this->populateNodeFromRequest($node, $request);

        if ($page instanceof ICatalyzContentProvider) {
            $page->updateFromRequest($node, $request, false);
            if (isset($page->errors) && is_array($page->errors)) {
                $this->errors = array_merge($this->errors, $page->errors);
            }
        }
        // var_dump($this->errors);exit;
        if (count($this->errors) > 0) {
            $this->displayEditForm($page, $node);
        } else {
            $page->save();
            $node->save();
            $ContentTree = ContentTree::instance($this->getUser()->getCulture());
            $ContentTree->clearAllCache();
            $ContentTree->build(true);

            if ($page instanceof ICatalyzRedirectToParentNodeOnceCreated) {
                $target = $node->getParent();
            } else {
                $target = $node;
            }

            $culture = $request->getParameter('culture');

            $this->dispatcher->notify(new sfEvent($node, 'catalyz.publish_node'));

            $this->redirectToUrl($ContentTree->getContentTreeNodeById($target->getId())->getURL($culture));
        }
    }

    public function executeNodeEdit($request)
    {
        Catalyz::setPageCulture(sfContext::getInstance()->getUser()->getCulture());

        sfContext::getinstance()->getUser()->setCulture(sfConfig::get('app_catalyz_language'));
        $this->errors = array();
        $nodeId = $this->getRequestParameter('node_id');
        if (null === $nodeId) {
            $nodeId = $this->getRequestParameter('current_node');
        }

        $this->culture = $request->getParameter('culture', $this->getUser()->getCulture());
        $this->ContentTree = ContentTree::instance($this->culture);
        $this->ContentTree->build();
        // var_dump($this->ContentTree);exit;
        if (null == $nodeId) {
            // new node?
            $parentId = $this->getRequestParameter('parent_id');
            $parentNode = NodePeer::retrieveByPK($parentId);
            $this->forward404Unless($parentNode, 'Unable to find parent node with ID: ' . $parentId);

            if ($this->getRequestParameter('Cancel')) {
                return $this->handleEditCancel($parentNode);
            }
            $validSubClasses = $parentNode->getPage()->getValidSubClasses();

            $nodeClass = $this->getRequestParameter('page_type');
            if (!in_array($nodeClass, $validSubClasses)) {
                /**
                 *
                 * @todo Handle this error when requested node class is not valid
                 */
                $this->redirect404(sprintf('%s is not a valid subclass', $nodeClass));
            } else {
                $className = 'Node' . $nodeClass;
                $page = new $className();

                $node = new Node();
                if ($page instanceof ICatalyzInsertOnTop) {
                    $node->insertAsFirstChildOf($parentNode);
                } else {
                    $node->insertAsLastChildOf($parentNode);
                }
                $node->setNodeClass($nodeClass);

                $this->availableLayouts = LayoutManager::instance()->getSupportedLayouts($page);

                $currentParent = $parentNode;
                $found = false;
                while (!$found && $currentParent != null) {
                    if (in_array($currentParent->getCurrentLayout(), $this->availableLayouts)) {
                        $node->setCurrentLayout($currentParent->getCurrentLayout());
                        $found = true;
                    } else {
                        $currentParent = $currentParent->getParent();
                    }
                }
                if (!$found) {
                    $node->setCurrentLayout($this->availableLayouts[0]);
                }
                if ($node->getCurrentLayout() == $parentNode->getCurrentLayout()) {
                    $node->setCurrentLayoutType(Node::LAYOUT_INHERIT);
                } else {
                    $node->setCurrentLayoutType(Node::LAYOUT_CUSTOM);
                }
                $node->setUrltype(Node::URL_TYPE_GENERATED, $this->culture);

                if ($page instanceof ICatalyzDefaultContentProvider) {
                    $node->setTitle($page->getDefaultContent(Node::FIELDS_PAGE_TITLE));
                } else {
                    $node->setTitle($this->getContext()->getI18N()->__('New Page', null, 'catalyz'));
                }
                $page->setNode($node);

                $this->parentNode = $parentNode;

                $ParentContentTreeNode = $this->ContentTree->getContentTreeNodeById($parentId);
                $ContentTreeNode = new ContentTreeNode($node, $ParentContentTreeNode, $this->culture);
                $ParentContentTreeNode->addChild($ContentTreeNode);
                $this->ContentTree->initializeCurrentNode($ContentTreeNode);
            }
        } else {
            // existing node
            $ContentTreeNode = $this->ContentTree->initializeCurrentNodeById($nodeId);
            $this->forward404Unless($nodeId, 'Unable to find node');
            $page = $ContentTreeNode->getPage();
            $this->forward404Unless($page, 'Unable to find page related to node ' . $nodeId);
            $node = $ContentTreeNode->getNode();
            if ($this->getRequestParameter('Cancel')) {
                return $this->handleEditCancel($node);
            }
            // $this->parentNode = $node->getParent();
        }
        // $this->parentLayout = $parentNode->getCurrentLayout();
        // $this->currentlyUsedLayout = $parentNode->getCurrentLayout();
        if ($page instanceof ICatalyzContextualNode) {
            if (!$page->initializeContext($request, ICatalyzContextualNode::EDIT)) {
                $this->forward404('Invalid context');
            }
        }
        if (!$request->isMethod('post')) {
            return $this->displayEditForm($page, $node);
        }
        // var_dump($this->getRequestParameter('Cancel'));exit;
        if ($this->getRequestParameter('Preview')) {
            return $this->displayPreview($page, $node, $request);
        }
        if ($this->getRequestParameter('Submit')) {
            return $this->handleEditSubmit($page, $node, $request);
        }
        if ($page instanceof ICatalyzEditActionManager) {
            $page->handleEditActionIfAny($page, $node, $request);
        }
        $this->forward404('No action');
    }

    public function executeNodeReorder($request)
    {
        $nodeId = $request->getParameter('node_id');
        $this->forward404Unless($nodeId);

        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();
        $ContentTreeNode = $this->ContentTree->initializeCurrentNodeById($nodeId);

        $page = Catalyz::getPageByNodeId($nodeId);
        $this->forward404Unless($page);
        // $this->page = $page;
        // sfContext::getInstance()->set('page', $page);
        // $this->setLayout($page->getNode()->getCurrentLayoutNameForAction());
        if (!$this->getRequest()->isMethod('post')) {
            $this->page = $page;
            // var_dump($page);
            // exit;
            // $this->availableLayouts = LayoutPeer::doSelect(new Criteria());
            return sfView::SUCCESS;
        } else {
            if ($request->getParameter('Cancel')) {
                $this->redirectToUrl($ContentTreeNode->getURL());
            } elseif ($request->getParameter('Save')) {
                $node = $page->getNode();
                // reorder children
                if (preg_match_all('/([0-9]+)/', $request->getParameter('order'), $ids)) {
                    $newChildOrder = $ids[1];

                    $nodeId = array_shift($newChildOrder);
                    $prevSiblingNode = NodePeer::retrieveByPk($nodeId, null, false);
                    $prevSiblingNode->moveToFirstChildOf($node);
                    $prevSiblingNode->save();
                    $prevSiblingNodeId = $prevSiblingNode->getId();

                    foreach($newChildOrder as $nodeId) {
                        $childNode = NodePeer::retrieveByPk($nodeId, null, false);
                        $prevSiblingNode = NodePeer::retrieveByPk($prevSiblingNodeId, null, false);
                        $childNode->moveToNextSiblingOf($prevSiblingNode);
                        $childNode->save();
                        $prevSiblingNodeId = $nodeId;
                    }
                }
                $this->ContentTree->clearAllCache();
                $this->ContentTree->build();
                $this->redirectToUrl($this->ContentTree->getContentTreeNodeById($node->getId())->getURL());
            } else {
                $this->forward404();
            }
        }

        return sfView::SUCCESS;
    }

    public function executeNodeReorganize($request)
    {
        $nodeId = $request->getParameter('node_id');
        $this->forward404Unless($nodeId);

        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();
        $ContentTreeNode = $this->ContentTree->initializeCurrentNodeById($nodeId);

        $page = Catalyz::getPageByNodeId($nodeId);
        $this->forward404Unless($page);
        $this->page = $page;

        return sfView::SUCCESS;
    }

    public function executeNodeReorganizeUpdate($request)
    {
        $node = NodePeer::retrieveByPK(str_replace('node-', '', $request->getParameter('node_id')));
        $this->forward404Unless($node);

        $sibling = NodePeer::retrieveByPK(str_replace('node-', '', $request->getParameter('sibling_id')));
        $this->forward404Unless($sibling);

        $position = $request->getParameter('position');
        if ('after' == $position) {
            $node->moveToNextSiblingOf($sibling);
            $node->save();
        } elseif ('inside' == $position) {
            $node->moveToLastChildOf($sibling);
            $node->save();
        }

        $ContentTree = ContentTree::instance();
        $ContentTree->clearAllCache();
        $ContentTree->build();

        return sfView::NONE;
    }

    public function executeNodeDelete($request)
    {
        $nodeId = $request->getParameter('node_id');
        $this->forward404Unless($nodeId);

        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();
        $this->ContentTree->initializeCurrentNodeById($nodeId);

        $page = Catalyz::getPageByNodeId($nodeId);
        $this->forward404Unless($page);
        // sfContext::getInstance()->set('page', $page);
        // $this->setLayout($page->getNode()->getCurrentLayoutNameForAction());
        if (!$this->getRequest()->isMethod('post')) {
            $this->page = $page;
            $this->availableLayouts = LayoutManager::instance()->getAll();
            return sfView::SUCCESS;
        } else {
            if ($request->getParameter('Cancel')) {
                $this->redirectToUrl($this->ContentTree->getContentTreeNodeById($page->getNodeId())->getURL());
            } elseif ($request->getParameter('Confirm')) {
                $node = $page->getNode();

                $parent = $node->getParent();

                $node->delete();
                $this->ContentTree->build();
                $this->redirectToUrl($this->ContentTree->getContentTreeNodeById($parent->getId())->getURL());
            } else {
                $this->forward404();
            }
        }
        return sfView::SUCCESS;
    }

    function executeNodeAdd($request)
    {
        $parentNode = NodePeer::retrieveByPK($request->getParameter('parent_id'));
        $this->forward404Unless($parentNode);

        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();
        $this->ContentTree->initializeCurrentNodeById($parentNode->getId());

        Catalyz::setPageCulture(sfContext::getinstance()->getUser()->getCulture());
        sfContext::getinstance()->getUser()->setCulture(sfConfig::get('app_catalyz_language'));
        $this->parentNode = $parentNode;
        $validSubClasses = $parentNode->getPage()->getValidSubClasses();
        switch (count($validSubClasses)) {
            case 0:
                $this->forward404('No valid subclasses');
            case 1:
                $request->setParameter('page_type', array_shift($validSubClasses));
                $this->forward('catalyz', 'nodeEdit') ;
        }
        $options = array();
        foreach($validSubClasses as $name) {
            if (class_exists('Node' . $name)) {
                $options[$name] =
                array(
                    'caption' => eval('return Node' . $name . '::getNodeClassCaption();'),
                    'description' => eval('return Node' . $name . '::getNodeClassDescription();'),
                    );
            } else {
                trigger_error('Class Node' . $name . ' does not exists', E_USER_WARNING);
            }
        }
        $this->options = $options;
        $this->node = $parentNode;
    }

    function executeNodeManageLanguageVersions($request)
    {
        $nodeId = $request->getParameter('node_id');
        $this->forward404Unless($nodeId);

        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();
        $this->ContentTree->initializeCurrentNodeById($nodeId);

        $page = Catalyz::getPageByNodeId($nodeId);
        $this->page = $page;

        return sfView::SUCCESS;
    }

    function executeNodeAddLanguageVersion($request)
    {
        $nodeId = $request->getParameter('node_id');
        $newLanguage = $request->getParameter('language');
        // $criteria = new Criteria();
        // $criteria->add(NodePeer::ID, $nodeId);
        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();
        $ContentTreeNode = $this->ContentTree->initializeCurrentNodeById($nodeId);

        $this->forward404Unless($ContentTreeNode, 'Unable to find node');
        Catalyz::createTranslation($ContentTreeNode->getNode(), $newLanguage);
        // $this->ContentTree->clearAllCache();
        $this->getUser()->setFlash('notice', $this->getContext()->getI18N()->__('New language has been added.', null, 'catalyz'));
        if ($request->getParameter('edit')) {
            $this->redirect('@node-translation-edit?node_id=' . $ContentTreeNode->getId() . '&culture=' . $newLanguage);
        } else {
            $this->redirect('@node-translations?node_id=' . $ContentTreeNode->getId());
        }
    }

    function executeNodeDeleteLanguageVersion($request)
    {
        $nodeId = $request->getParameter('node_id');
        $culture = $request->getParameter('culture');

        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();
        $this->ContentTree->initializeCurrentNodeById($nodeId);

        $this->forward404Unless($nodeId, 'Unable to find node');
        $page = Catalyz::getPageByNodeId($nodeId);
        if ($page instanceof ICatalyzTranslatable) {
            $page->removeTranslation($culture);
        }

        NodeI18nPeer::doDelete(array($nodeId, $culture));
        Catalyz::clearTranslationCache($nodeId);

        $this->getUser()->setFlash('notice', $this->getContext()->getI18N()->__('Language has been removed.', null, 'catalyz'));
        $this->redirect('@node-translations?node_id=' . $nodeId);
    }
    // public function executeNodeView($request){
    // $ContentTree = ContentTree::instance();
    // $ContentTree->build($request->getParameter('culture'));
    // $currentNode = $ContentTree->initializeCurrentNodeById($request->getParameter('node_id'));
    // $this->redirectToUrl($currentNode->getUrl());
    // }
    function executeNodeTranslationOverview($request)
    {
        $nodeId = $request->getParameter('node_id');
        $this->forward404Unless($nodeId);

        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();
        $ContentTreeNode = $this->ContentTree->initializeCurrentNodeById($nodeId);

        $page = Catalyz::getPageByNodeId($nodeId);
        $this->forward404Unless($page);
        $this->page = $page;
        return sfView::SUCCESS;
    }

    public function executeCacheStatus($request)
    {
        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();
        $ContentTreeNode = $this->ContentTree->initializeCurrentNodeByPath('');

        $page = Catalyz::getPageByNodeId($ContentTreeNode->getId());
        $this->forward404Unless($page);
        $this->page = $page;
        return sfView::SUCCESS;
    }

	public function executeCacheClear($request)
	{
		CatalyzCache::clear($request->getParameter('node_id'), $request->getParameter('culture'));
		return $this->redirect('@cache-status');
	}
	public function executeCacheRefresh($request)
	{
		CatalyzCache::refresh();
		return $this->redirect('@cache-status');
	}

    public function executeCacheCreate($request)
    {
        CatalyzCache::create($request->getParameter('node_id'), $request->getParameter('culture'));
        return $this->redirect('@cache-status');
    }

    public function executeNotFound($request)
    {
        $this->getResponse()->setHttpHeader('HTTP/1.1', '404 Not Found');

        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();

        $this->ContentTree->initializeCurrentNodeByPath(str_replace(sprintf('%s/%s', sfConfig::get('app_site_url'), $this->getUser()->getCulture()), '', $request->getReferer()));
        $this->node = $this->ContentTree->getCurrentNode();
        if (is_null($this->node)) {
            $this->ContentTree->initializeCurrentNodeByPath('');
            $this->node = $this->ContentTree->getCurrentNode();
        }

        $handle = fopen(sfConfig::get('sf_log_dir') . '/404.log', 'a+');
        if ($handle) {
            fwrite($handle, sprintf('%s[%s] Page <%s%s> not found. Coming from <%s>', "\n", date('Y-m-d H:i:s'), sfConfig::get('app_site_url'), !empty($_SERVER['REQUEST_URI'])?$_SERVER['REQUEST_URI']:'', $request->getReferer()));
            fclose($handle);
        }
    }

	public function executeError404($request){
		$this->dispatcher->notify(new sfEvent($this, 'catalyz.error404'));
		return sfView::SUCCESS;
	}

    public function executeCheckup($request)
    {
        $checkup = new CatalyzCheckup();
        $this->tests = $checkup->execute();
        return sfView::SUCCESS;
    }

	public function executeXmlSitemap($request){
		$this->setLayout(false);
		sfConfig::set('sf_web_debug', false);
		$this->getResponse()->setHttpHeader('Content-Type', 'text/xml', true);

		return sfView::SUCCESS;
	}

	public function executeAdmin($request)
    {
        $this->ContentTree = ContentTree::instance();
        $this->ContentTree->build();
        $ContentTreeNode = $this->ContentTree->initializeCurrentNodeByPath('');

        $page = Catalyz::getPageByNodeId($ContentTreeNode->getId());
        $this->forward404Unless($page);
        $this->page = $page;
        return sfView::SUCCESS;
    }
}