<?php
class IndexController extends RCMS_Core_BaseController {

	public function init() {
		parent::init();
		$this->_model = new Default_Model_IndexModel();
		$this->checkUpdateContentTime();
		if(!$this->_session->pluginConfigData) {
			$this->_session->pluginConfigData = $this->getConfigDataForPlugin();
		}
	}

	/**
	 * Main action
	 *
	 */
	public function indexAction() {
		//things that are needed for both types of users (logged in and not logged)
		$searchResult = null;
		$allowModification = $this->_session->isLogged;
		$websiteUrl = $this->getWebSiteUrl();
		$seoParser = new RCMS_Object_Parser_SeoParser();
		$pageContent = '';
		//check for two default system pages
		$this->_checkIfNoCategoryAndIndexExist();
		$this->_checkForDraftCategory();

		//processing search results
		if($this->_session->searchResult != null) {
			$searchResult = $this->_session->searchResult;
		}

		//Here we are making a page! Most important part
		$requestedPage = urlencode($this->getRequest()->getParam('page'));
		$requestedPageAdditional = urlencode($this->getRequest()->getParam('additional'));
		if($requestedPageAdditional) {
			$requestedPage .= '/' . $requestedPageAdditional;
		}
		//if no requested page (ex: http://www.site_name.com/) then get default page from config
		if(empty($requestedPage)) {
			$requestedPage = unserialize(Zend_Registry::get('config'))->website->website->defaultPage;
		}
		elseif($requestedPage == 'no-category' || $requestedPage == 'no-category.html') {
			$this->_redirect($websiteUrl);
		}
		$pageData = $this->_grubPageData(RCMS_Tools_Tools::stripSlashesIfQuotesOn($requestedPage));
		//If page not found then send 404 NOT FOUND response
		if(!$pageData) {
			$pageData = $this->_show404Page($allowModification);
		}
		$pageData['websiteUrl'] = $this->view->websiteUrl;
		$pageData['currentTheme'] = $this->_model->selectCurrentTheme();
		//lounching parser
		$parser = new RCMS_Object_Parser_Parser($pageData['templateContent'], $pageData, $allowModification, $searchResult, $this->_session->langId);
		$pageContent = $parser->processContent();
		//handle forms messages and search results
		$this->_processFormsMessagesAndCleanSearch();
		//check wether users looged in or not and making some cool stuff
		if(!$this->_session->isLogged) {
			//disabling system layout for not logged users
			$this->_helper->layout->disableLayout();
			//do a little append to final page body
			$pageContent = $this->_appendBody($pageContent);
		}
		else {
			$this->_session->currentThemeName = $pageData['currentTheme'];
			$cantDelete = $this->_session->cantDelete;
			unset($this->_session->cantDelete);
			$this->_getServices();
			//setting view vars for logged user
			$this->view->loggedTitle = $pageData['header_title'];
			$this->view->cantDelete = $cantDelete;
			$this->view->servicesContent = $this->_session->servicesContent;
			$this->view->cntDraftPages = $this->_countDraftPages();
			//seo parser routine
			$seoParser->refreshHtAccess();
		}
		//commont variables
		$this->view->content  = $pageContent;
		$this->view->pageData = $pageData;

		//seo routine
		$seoParser->makeCanonicRules();
		$this->_checkForPRSFile();

	}

	/**
	 * Check if it is time to publish container
	 *
	 */
	public function checkUpdateContentTime() {
		if(isset($this->_session->updateContentDate)) {
			$updateDate =   $this->_session->updateContentDate;
			$currentDate = date("m-d-Y");
			if($currentDate >$updateDate ) {
				$this->_model->updatePublishedContent();
				$this->_session->updateContentDate = $currentDate;
			}
		}
		else {
			$this->_session->updateContentDate = date("m-d-Y");
			$this->_model->updatePublishedContent();
		}
	}


	/**
	 * Main action for news pages
	 *
	 * @todo refactor this method!
	 *
	 */
	public function newsAction() {
		$parseNewsList = false;
		$templateName = unserialize(Zend_Registry::get('config'))->news->news->templateName;
		$allowModification = true;
		// If this is a regular user - disable layout and tell parser do not add links to containers
		if(!$this->_session->isLogged) {
			$allowModification = false;
			$this->_helper->layout->disableLayout();
		}
		$requestedNewsPage = strtolower($this->getRequest()->getParam('news_url'));
		//if no requested page (ex: http://www.site_name.com/) then get default page from config
		if(empty($requestedNewsPage)) {
			$requestedNewsPage = unserialize(Zend_Registry::get('config'))->news->news->defaultNewsPage;
			$parseNewsList = true;
		}
		if(!$parseNewsList) {
			$newsData = $this->_grubNewsPageData($requestedNewsPage);
		}
		else {
			$newsData = null;
		}
		$newsData['websiteUrl'] = $this->view->websiteUrl;
		$this->view->loggedTitle = (isset($newsData['newsTitle'])? $newsData['newsTitle'] : "News Index");
		//set current theme name for parser
		$newsData['currentTheme'] = $this->_model->selectCurrentTheme();
		//set current theme name to session also.
		$this->_session->currentThemeName = $newsData['currentTheme'];
		//get news template content
		if(!empty($templateName)) {
			$templateObj = new RCMS_Object_Template_Template($this->_model->selectTemplateByName($templateName));
		}else {
			$templateObj =  new RCMS_Object_Template_Template($this->_model->selectTemplateByName('news'));
		}
		$newsData['requestedNewsPage'] = $requestedNewsPage;
		$newsData['templateId'] = $templateObj->getId();
		$parser = new RCMS_Object_Parser_Parser($templateObj->getContent(), $newsData, $allowModification);
		//setting view variables
		$this->view->content = $parser->processContent($parseNewsList,true);
		$this->view->newsData = $newsData;
		if(!$this->_session->isLogged) {
			$htmlHead = '<link href="' .$this->view->websiteUrl . 'system/js/thickbox/thickbox.css" media="screen" rel="stylesheet" type="text/css" />' . "\n" .
				'<script type="text/javascript" src="' .$this->view->websiteUrl . 'system/js/jquery/jquery.js"></script>' . "\n" .
				'<script type="text/javascript" src="' .$this->view->websiteUrl . 'system/js/thickbox/thickbox.js"></script>' . "\n";
			$this->view->content = preg_replace("~<head>(.*)<\/head>~s", "<head>" . $htmlHead . "$1</head>\n", $this->view->content);
		}
	}

	public function getConfigDataForPlugin()
	{
		$pluginConfigArray = array();

		$pluginConfigArray['smtp']['host'] = $this->_model->selectConfigValue('smtp_host');
		$pluginConfigArray['smtp']['login'] = $this->_model->selectConfigValue('smtp_login');
		$pluginConfigArray['smtp']['password'] = $this->_model->selectConfigValue('smtp_password');

		$pluginConfigArray['db']['adapter'] = unserialize(Zend_Registry::get('config'))->database->database->adapter;
		$pluginConfigArray['db']['host'] = unserialize(Zend_Registry::get('config'))->database->database->params->host;
		$pluginConfigArray['db']['username'] = unserialize(Zend_Registry::get('config'))->database->database->params->username;
		$pluginConfigArray['db']['password'] = unserialize(Zend_Registry::get('config'))->database->database->params->password;
		$pluginConfigArray['db']['name'] = unserialize(Zend_Registry::get('config'))->database->database->params->dbname;

		$pluginConfigArray['website']['url'] = unserialize(Zend_Registry::get('config'))->website->website->url;
		$pluginConfigArray['website']['path'] = unserialize(Zend_Registry::get('config'))->website->website->path;
		$pluginConfigArray['website']['defaultPage'] = unserialize(Zend_Registry::get('config'))->website->website->defaultPage;

		$pluginConfigArray['zend']['library '] = unserialize(Zend_Registry::get('config'))->production->includePaths->library;
		$pluginConfigArray['zend']['controllerDirectory'] = unserialize(Zend_Registry::get('config'))->production->resources->frontController->controllerDirectory;
		$pluginConfigArray['zend']['controllerDirectory'] = unserialize(Zend_Registry::get('config'))->production->resources->layout->layoutPath;


		return $pluginConfigArray;
	}

	/**
	 * Get all page's data
	 *
	 * @param String $requestedPage
	 * @return Array
	 */
	protected function _grubNewsPageData($requestedNewsPage) {
		if(!empty ($requestedNewsPage)) {
			$ext = $this->_getExtension($requestedNewsPage);
			if($ext === '.html') {
				$requestedNewsPage = str_replace('.html', '', $requestedNewsPage);
			}
			else {
				return '';
			}
		}
		$requestedNewsPage = $this->_proccessUrl($requestedNewsPage);
		return $requestedData = $this->_model->getRequestedNewsData($requestedNewsPage);
	}

	/**
	 * @method Proccess Url replacing spaces to '-'
	 *
	 * @param  String $search
	 * @param  String $replace
	 * @return String ''
	 */
	protected function _proccessUrl($url, $search=' ', $replace='-') {
		return str_replace($search, $replace,trim($url));
	}

	/**
	 * Check url on .html extension
	 *
	 * @param  string $url
	 * @return string
	 */
	private function _getExtension($url) {
		$pu = parse_url($url);
		return substr($pu['path'], (strlen($pu['path'])-5));
	}

	/**
	 * Checks if page and category exist '-'
	 *
	 * @return void;
	 */
	private function _checkIfNoCategoryAndIndexExist() {
		//get data for no category page and for no-category category
		$noCategoryPage = $this->_model->getPageByUrl('no-category');
		$noCategoryCategory = $this->_model->selectCategoryByName('no category');
		//if category page exists
		if(!$noCategoryPage) {
			$templateId = $this->_model->selectTemplateByName('default');
			if($templateId) {
				if($noCategoryCategory) {
					$_categoryId = $noCategoryCategory['id'];
				}
				else {
					$this->_model->insertNewCategory('no category');
				}
				$pageObj = new RCMS_Object_Page_Page();
				$pageObj->setTemplateId($templateId);
				$pageObj->setCategoryId("-1");
				$pageObj->setNavName('no category');
				$pageObj->setMetaDescription('');
				$pageObj->setMetaKeywords('');
				$pageObj->setHeaderTitle('no category');
				$pageObj->setH1Tag('no category');
				$pageObj->setUrl('no-category');
				$pageObj->setShortDescription('');
				$pageObj->setOwner(0);
				$pageObj->setIs404Page(0);
				$pageObj->setShowInMenu(1);
				$pageObj->setOrder(0);
				$pageObj->setStaticOrder(100);
				$pageObj->setWeight(0);
				$pageObj->setSeosambaRuleId(0);
				$pageObj->setSiloId(0);
				$pageObj->setLastUpdate(date("Y-m-d H:i:s", time()));
				$pageObj->save();
			}
		}
		else // check if category no category exists
		{
			if(!$noCategoryCategory) {
				$this->_model->insertNewCategory('no category');
				$pageObj = new RCMS_Object_Page_Page($noCategoryPage->id);
				$pageObj->setCategoryId(-1);
				$pageObj->save();
			}
		}
	}


	/**
	 * Checks if rss file exists
	 *
	 * @return void;
	 */
	private function _checkForPRSFile() {
		$config = unserialize(Zend_Registry::get('config'));
		$path = $config->website->website->path . 'public/tmp/';
		if(!file_exists($path . 'pfs.prs')) {
			try {
				RCMS_Tools_FilesystemTools::saveFile($path . 'pfs.prs', 'forprsculpting');
			}
			catch (Exception $e) {
				return;
			}
		}
	}

	/**
	 * Check system for draft category.
	 * 
	 */
	private function _checkForDraftCategory() {
		$draftCategoryPage = $this->_model->getPageByUrl(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryUrl);
		$draftCategory = $this->_model->selectCategoryByName(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
		if(!$draftCategoryPage) {
			$templateId = $this->_model->selectTemplateByName('category');
			if($templateId) {
				if($draftCategory) {
					$draftCategoryId = $draftCategory['id'];
				}
				else {
					$draftCategoryId = $this->_model->insertNewCategory(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
				}
				$page = new RCMS_Object_Page_Page();
				$page->setTemplateId($templateId);
				$page->setCategoryId($draftCategoryId);
				$page->setNavName(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
				$page->setMetaDescription('');
				$page->setMetaKeywords('');
				$page->setHeaderTitle(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
				$page->setH1Tag(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
				$page->setUrl(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryUrl);
				$page->setShortDescription('');
				$page->setOwner(1);
				$page->setIs404Page(0);
				$page->setShowInMenu(1);
				$page->setOrder(100);
				$page->setStaticOrder(100);
				$page->setWeight(0);
				$page->setSeosambaRuleId(0);
				$page->setSiloId(0);
				$page->setLastUpdate(date("Y-m-d H:i:s", time()));
				$page->save();
			}
		}
		else {
			if(!$draftCategory) {
				$catId = $this->_model->insertNewCategory(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
				$pageObj = new RCMS_Object_Page_Page($draftCategoryPage->id);
				$pageObj->setCategoryId($catId);
				$pageObj->save();
			}
		}
	}

	/**
	 * Append needed things to the final unlogged-user's html
	 *
	 * @param string $pageContent
	 * @return string
	 */
	private function _appendBody($pageContent) {
		$websiteUrl = $this->getWebSiteUrl();
		$htmlHead = '<link href="' . $websiteUrl . 'system/js/thickbox/thickbox.css" media="screen" rel="stylesheet" type="text/css" />' . "\n" .
					'<script type="text/javascript" src="' . $websiteUrl . 'system/js/jquery/jquery.js"></script>' . "\n" .
					'<script type="text/javascript" src="' . $websiteUrl . 'system/js/complex.js"></script>' . "\n";
		$pageContent = preg_replace("~<head>(.*)<\/head>~s", "<head>" . $htmlHead . "$1</head>\n", $pageContent);
		$pageContent = str_replace(array('</body>', '</html>'), '', $pageContent);
		$pageContent .= '
			<input type="hidden" id="hid-main-wsurl" value="'. $websiteUrl . '" />
			<script type="text/javascript">
				replaceNSP();
			</script>
			</body>
			</html>
		';
		return $pageContent;
	}



	/**
	 * Get needed content for services menu
	 *
	 */
	private function _getServices() {
		//trying to get services and paste it to the cpanel
		if(!isset($this->_session->servicesContent)) {
			$servicesContent = $this->_getCustomServices();
			if(!$servicesContent) {
				$servicesContent = @RCMS_Tools_Tools::stripSlashesIfQuotesOn(file_get_contents(RCMS_Object_QuickConfig_QuickConfig::SERVICES_URL));
				if(strpos($servicesContent, '<ul', 0) === false) {
					$servicesContent = '';
				}
			}
			$this->_session->servicesContent = (!(empty($servicesContent))) ? $servicesContent : '<ul><li>No services.</li></ul>'  ;
		}
	}

	/**
	 * Shows correct 404 page
	 *
	 * @param <type> $isLogged
	 * @return <type>
	 */
	private function _show404Page($isLogged) {
		$websiteUrl = $this->getWebSiteUrl();
		$this->getResponse()->setHeader('HTTP/1.1', '404 Not Found');
		$this->getResponse()->setHeader('Status', '404 File not found');
		$page404Url = $this->_model->getPage404Url();
		if(!$page404Url) {
			if(!$isLogged) {
				$this->_helper->getHelper('layout')->disableLayout();
				$this->getResponse()->setBody("
					<div style=\"text-align: center;\">
						<span style=\"color: #ff0000; font-weight: bold; font-size: 20px; \">Error 404. Page not found.</span><br/>
						<a href=\"". $websiteUrl ."\">Back to home page</a>
					</div>
				");
			}
			else {
				$this->_helper->getHelper('layout')->disableLayout();
				$this->getResponse()->setBody("
					<div style=\"text-align: center;\">
						<span style=\"color: #ff0000; font-weight: bold; font-size: 20px; \">Error 404. Page not found.</span>
						<span style=\"color: #cecece; font-size: 12px;\">
							<br/>You can costumize this page - just create a page and assign it as 404 error page
							<br/>Use the checkbox on the create/update page screen.
						</span><br/>
						<a href=\"". $websiteUrl ."\">Back to home page</a>
					</div>
				");
			}
			return;
		}
		return $this->_grubPageData($page404Url . '.html');
	}

	/**
	 * Count pages in drft
	 * @return integer
	 */
	private function _countDraftPages() {
		$draftCategory = $this->_model->selectCategoryByName(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
		return $this->_model->countDraftPages($draftCategory['id']);
	}


	/**
	 * Try to get agency's custom services
	 *
	 * @return mixed Returns services content if it exists or false
	 */
	private function _getCustomServices() {
		$result = $this->_model->selectServicesContent();
		return (!empty($result) ? $result[0]['servicesContent'] : false);
	}

	/**
	 * Get all page's data
	 *
	 * @param string $requestedPage
	 * @return array
	 */
	protected function _grubPageData($requestedPage) {
		if(!empty ($requestedPage)) {
			$ext = $this->_getExtension($requestedPage);
			if($ext === '.html') {
				$requestedPage = str_replace('.html', '', $requestedPage);
			}
			else {
				return '';
			}
		}
		if(!$this->_session->isLogged) {
			if(!$requestedData = $this->_cache->load(preg_replace('/[^_A-Za-z0-9]/', '', (str_replace('-', '_', $requestedPage))))) {
				$requestedData = $this->_model->getRequestedData($requestedPage);

				$this->_cache->save($requestedData, preg_replace('/[^_A-Za-z0-9]/', '', str_replace('-', '_', $requestedPage)));
			}
		}
		else {
			$requestedData = $this->_model->getRequestedData($requestedPage);
		}
		return $requestedData;
	}

	/**
	 * Doing routine with form messages and cleaning search results
	 *
	 */
	private function _processFormsMessagesAndCleanSearch() {
		//unset search result variable after processing content
		unset($this->_session->searchResult);
		//Start Handling Errors For Forms
		if($this->_session->formSmtpMessage) {
			$this->view->formSmtpMessage = $this->_session->formSmtpMessage;
			unset($this->_session->formSmtpMessage);
		}
		if($this->_session->formErrorMessage) {
			$this->view->formErrorMessage = $this->_session->formErrorMessage;
			unset($this->_session->formErrorMessage);
		}
		if($this->_session->formSuccessMessage) {
			$this->view->formSuccessMessage = $this->_session->formSuccessMessage;
			unset($this->_session->formSuccessMessage);
		}
		if($this->_session->formCaptchaNotValid) {
			$this->view->formCaptchaNotValid = $this->_session->formCaptchaNotValid;
			unset($this->_session->formCaptchaNotValid);
		}
		if($this->_session->formEmailNotValid) {
			$this->view->formEmailNotValid = $this->_session->formEmailNotValid;
			unset($this->_session->formEmailNotValid);
		}
	}
}

