<?php
/**
 * This is a controller for Page.
 *
 * This controller would be responsible for applying actions in classical admin area.
 * it could be any changes concerned mass applying
 * @author Pavel Savchuk
 */

class Backend_PageController extends RCMS_Core_BaseController {

/**
 * Special parser that creates seo for this site.
 *
 * @var RCMS_Object_Parser_SeoParser
 */
	protected $_seoParser = null;

	/**
	 * Preview path for page's image
	 *
	 * @var string
	 */
	protected $_savePathPreviewPage;

	public function init() {
		parent::init();
		$this->checkLogin();
		$this->_model = new Default_Model_PageModel();
		$this->_seoParser = new RCMS_Object_Parser_SeoParser();
		$this->_savePathPreviewPage = unserialize(Zend_Registry::get('config'))->website->website->path . 'public/tmp/';
	//echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";

	}

	/**
	 * @method Init form data for a page
	 * @return RCMS_Form_PageForm
	 */
	public function initDataForCreatePageForm() {
		$pageForm =  new RCMS_Form_PageForm();
		$categories = $this->_model->selectAllCategories();
		//$pageWeight = array('0','1','2','3','4','5');
		$categories[-1]="Select a category";
		$featuredAreas[-1]="Is this page featured?";
		//make a sort of each array by keys in order to have the first elements as default values
		ksort($categories);
		$pageForm->getElement('pageselectcategory')->setMultiOptions($categories);
		//$pageForm->getElement('weight')->setMultiOptions($pageWeight);
		$pageForm->getElement('selectmenu')->setMultiOptions($categories);
		$pageForm->getElement('selectmenu')->setMultiOptions($this->generateShowInMainMenuSelectData());
		return $pageForm;
	}


	public function draftlistAction() {
		$this->_helper->getHelper('layout')->disableLayout();

		$draftPagesViewData = array();
		$draftCategoryId = $this->_model->selectCategoryIdByName(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
		$draftPagesData = $this->_model->selectDraftPagesUrls($draftCategoryId);
		if(is_array($draftPagesData)) {
			foreach($draftPagesData as $draftPageData) {
				$draftPagesViewData[][$draftPageData['pageNavName']] = $draftPageData['pageUrl'];
			}
			$this->view->draftData = $draftPagesViewData;
		}
		else {
			$this->view->draftUrls = '';
		}
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	/**
	 * @method This method is an action which is responsible for adding new page
	 * @return void
	 */
	public function addpageAction() {


		$maxInsertedId = $this->_model->getLastPageId();
		$this->_cache->clean('all');
		////configurate settings variables from config file
		$websiteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;
		$websitePath  = unserialize(Zend_Registry::get('config'))->website->website->path;
		$previewPath  = unserialize(Zend_Registry::get('config'))->page->page->preview_path;
		$previewFolderName = unserialize(Zend_Registry::get('config'))->page->page->preview_folder;
		$pathTmp =  unserialize(Zend_Registry::get('config'))->website->website->path."public/tmp/";


		//check if preview folder is exists
		if(!is_dir($websitePath."public/".$previewFolderName)) {
			mkdir($websitePath."public/".$previewFolderName);
		}
		//check if temprorary folder is exists
		if(!is_dir($websitePath."public/tmp/")) {
			mkdir($websitePath."public/tmp");
		}
		//get current user object
		$userObj = unserialize($this->_session->currentUser);
		$this->_helper->getHelper('layout')->disableLayout();
		$pageForm = $this->initDataForCreatePageForm();


		//assing form to template
		$this->view->pageForm  =  $pageForm;
		//if request is POST and everything is valid

		if($this->getRequest()->isPost()) {
			if($this->view->pageForm->isValid($this->getRequest()->getParams())) {
			//get all values from form
				$pageData = array($this->view->pageForm->getValues());
				foreach ($pageData as &$data) {
				//here we are about getting neccessary values from form request
				//all of them will process dropdown lists, checkboxes and radiobuttons etc.
					$data['owner'] = $userObj->getId();
					$isCategory = $data['iscategory'];
					$categoryId = $data['pageselectcategory'];
					$imageName = $data['image_name'];
					$imagePath = $data['image_path'];
					$navigation_name = $data['nav_name'];
					$showInMenu = $data['selectmenu'];
					$h1image = $data['h1image'];
					$url = $this->proccessUrl($data['url']);

					if(empty($data['targetedKeyPhrase'])) {
						$targetedKeyPhrase = $data['url'];
					}else {
						$targetedKeyPhrase = trim($data['targetedKeyPhrase']);
					}
				}
				//check if this page is a category and if category with such a name is already exists
				if($isCategory && $this->_model->selectCategoryByName($navigation_name))
					$this->view->categoryExists = true;

				//check if the url of this page is already exits
				if($this->_model->selectUrl($url))
					$this->view->urlExists = true;


				//check if a page is with suca a navigation name is already in database
				if($this->_model->selectPageByNavigationName($navigation_name)) {
					if(!isset($this->_session->pageExists)) {
						$this->_session->pageExists = true;
						$this->view->pageExists = true;
					}else {
						unset($this->_session->pageExists);
						$this->view->pageExists = false;
					}
				}

				//if there are no errors
				if(!$this->view->categoryExists && !$this->view->pageExists && !$this->view->urlExists) {
					if($pageData) {
						$pageObj = new RCMS_Object_Page_Page();
						$pageObj->loadObjectFromArray($pageData);

						//if page marked is category than we insert new category
						//else we adjust page to existed category
						if($isCategory)
							$lastCategoryId = $this->_model->insertNewCategory($pageObj->getNavName());
						else
							$lastCategoryId =  $this->_model->insertNewCategory($pageObj->getNavName(), $categoryId);
						$pageObj->setCategoryId($lastCategoryId);
						$pageObj->setShowInMenu($showInMenu);

						//if template was not selected
						if ($pageObj->getTemplateId() == 0) {
						//put an error about it
							$this->view->errorElements = $this->processErrors(array('template' => array('isEmpty' => true)));
							$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
							$this->_helper->viewRenderer->setNoRender(true);
							echo $content;
							return;
						}
						//process image if it was uploaded.
						if(!empty ($imageName)) {
							$arr = explode(".", $imageName);
							$imageExtension = $arr[1];
							$oldImagePath = $websitePath."public/".$imagePath;
							$newImageFileName = RCMS_Tools_FilesystemTools::normalize(RCMS_Tools_FilesystemTools::trimInternalSpaces(str_replace(" ", "-", $h1image)),$maxInsertedId+1);
							$newImagePath = $websitePath.$previewPath.$newImageFileName.".".$imageExtension;
							@copy($oldImagePath,$newImagePath);
							@rename($oldImagePath,$this->_savePathPreviewPage.$newImageFileName.".".$imageExtension);
						//RCMS_Tools_FilesystemTools::recursive_remove_files_from_directory($pathTmp);
						}

						//save pageObject to the database.

						
						$pageId = $pageObj->save();

                         /*start process featured areas*/
						//featured areas stores in a hidden field as string of ids separated by ':'
						//for example '1:12:412:'
						$featuredIds = $pageForm->getElement('featured_ids')->getValue();
						$featuredIdsArray = explode(":", $featuredIds);
						foreach ($featuredIdsArray as $fa) {
							if(intval($fa))
								$this->_model->insertPageHasFa($pageId,$fa);
						}
                        /*end process featured areas*/
					
						//after uploading all images we need to put them in a corresponding table after doing neccessary checks
						if(isset($newImageFileName)) {
							$this->view->pageForm->image_name->setValue($newImageFileName.".".$imageExtension);
						}
						if(!empty ($imagePath)) {
							$this->_model->insertPagePreview($newImageFileName.".".$imageExtension, $pageId,$previewFolderName."/".$newImageFileName.".".$imageExtension);

						}
	
						//if page was saved successfuly
						
						if($pageId) {
						//for lucene search index.
						//$this->addLuceneIndex(new RCMS_Object_Page_Page($pageId));
							$this->_seoParser->createSiteMapFile();
							
							$this->view->redirect = $this->getWebSiteUrl().$pageObj->getUrl() . '.html';
							//exit;
						}
						
					}
				}
			} else {
				$this->view->errorElements = $this->processErrors($this->view->pageForm->getMessages());
			}
		}

		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;

	}

	/**
	 * @method  Edit page action
	 * @return Void
	 */
	public function editpageAction() {

		$this->_cache->clean('all');
		//set all settings variables
		$websiteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;
		$websitePath = unserialize(Zend_Registry::get('config'))->website->website->path;
		$previewPath  =  unserialize(Zend_Registry::get('config'))->page->page->preview_path;
		$previewFolderName = unserialize(Zend_Registry::get('config'))->page->page->preview_folder;
		$pathTmp =  unserialize(Zend_Registry::get('config'))->website->website->path."public/tmp/";
		$this->view->websiteUrl = $websiteUrl;

		//create temprorary directory if not exists
		if(!is_dir($pathTmp)) {
			mkdir($pathTmp);
		}
		//create directory for preview images if not exists
		if(!is_dir($websitePath."public/".$previewFolderName)) {
			mkdir($websitePath."public/".$previewFolderName);
		}
		$this->_helper->getHelper('layout')->disableLayout();

		//get pageId for updating
		$pageId = $this->getRequest()->getParam('pageId');
		if($pageId) {
		//create object of the page by id
			$pageObj  = new RCMS_Object_Page_Page($pageId);
			//create template for page by page id
			$templateObj  = new RCMS_Object_Template_Template($pageObj->getTemplateId());
			//put old url in session
			$this->_session->oldPageUrl = urldecode($pageObj->getUrl());
			//select image for a page.
			$pageImageObj = $this->_model->selectPageImage($pageId);

			if($pageObj->getCategoryId()>0) {
				$category = $this->_model->selectCategoryById($pageObj->getCategoryId());
				if($category)
					$categoryParent = $category->id_parent;
				else
					$categoryParent=-1;
			}

           /*getting array of Featured areas*/
			$featuredResult = $this->_model->selectFeaturedAreasByPageId($pageId);
			$featuredTimes = sizeof($featuredResult);
			//generate message for featured area
			if($featuredTimes>0) {
				$faLinkMessage = "Yes, ".sizeof($featuredResult)." Times.";
			}else {
				$faLinkMessage = "Not yet.";
			}
			//assign message on a template
			$this->view->faLinkMessage = $faLinkMessage;
			//featured area stores in a hidden field as consequences '2:3:41:'
			$featuredAreasStr="";
			if($featuredResult) {
				foreach ($featuredResult as $fa) {
					$featuredAreasArray[] = $fa['fa_id'];
				}
				$featuredAreasStr = implode(":", $featuredAreasArray);
				$featuredAreasStr = $featuredAreasStr.":";
			}
           /*end getting array of Featured areas*/
		}

		$oldCatagoryId = $pageObj->getCategoryId();
		$oldNavegationName = $pageObj->getNavName();
		$pageOrder = $pageObj->getOrder();
		$staticOrder = $pageObj->getStaticOrder();


		//init data for form variable

		$pageForm = $this->initPageEditForm($pageObj);

		$pageForm->getElement('featured_ids')->setValue($featuredAreasStr);
		//for page preview
		if($pageImageObj)
			$imageName = $pageImageObj->name;
		else
			$imageName='';
		//set image name for hidden field
		$pageForm->getElement('image_name')->setValue($imageName);
		$pageForm->getElement('h1image')->setValue($imageName);
		//assign form to template
		$this->view->pageForm = $pageForm;

		if($this->getRequest()->isPost()) {
		//is this category has pages and we trying to make it just regular page.
			$hasPages = false;
			if($this->view->pageForm->isValid($this->getRequest()->getParams())) {

				$pageData = array($this->view->pageForm->getValues());
				foreach ($pageData as &$data) {
				//we set id here because method save checks, whether id was set then we do update otherwise,we do insert
					$data['id'] = $pageObj->getId();
					$isCategory = $data['iscategory'];
					$categoryId = $data['pageselectcategory'];
					$imageName  = $data['image_name'];
					$imagePath  = $data['image_path'];
					$navigationName = trim($data['nav_name']);
					$showInMenu = $data['selectmenu'];
					$h1image = $data['h1image'];
					$url = $this->proccessUrl($data['url']);
					if(empty($data['targetedKeyPhrase'])) {
						$targetedKeyPhrase = $data['url'];
					}else {
						$targetedKeyPhrase = $data['targetedKeyPhrase'];
					}
				}

				if(!$isCategory) {
					if($this->_model->selectAllCategories($oldCatagoryId)) {
						$hasPages = true;
					}
				}

				//to do put the url check here
				$urlExists = false;
				if($this->_model->selectUrl($url) && $pageObj->getUrl()!=$url) {
					$this->view->urlExists = true;
					$urlExists = true;
				}

				$navigationNameExists = false;
				if($this->_model->selectPageByNavigationName($navigationName) && $pageObj->getNavName()!=$navigationName) {
					if(!isset($this->_session->navigationNameExists[$pageObj->getId()])) {
						$this->_session->navigationNameExists[$pageObj->getId()] = true;
						$this->view->navigationNameExists = true;
						$navigationNameExists = true;
					}else {
						unset($this->_session->navigationNameExists[$pageObj->getId()]);
						$this->view->navigationNameExists = false;
						$navigationNameExists = false;
					}
				}

				//check if there is a page with such a navigation name in the database?
				//and new navigation name was not changed
				if(!$hasPages && !$urlExists
					&& (trim(strtolower($navigationName)) == trim(strtolower($pageObj->getNavName())) || !$navigationNameExists)) {
					if($pageData) {
					//Zend_Debug::d($pageOrder,false);
						$pageObj->loadObjectFromArray($pageData);
						$pageObj->setOrder(!empty($pageOrder)? $pageOrder : "");
						$pageObj->setStaticOrder(!empty($staticOrder)? $staticOrder : "");

						//if page marked as no category
						if(!$isCategory) {   //if there was no category with such a name before
							if(!$this->_model->selectCategoryByName(trim($pageObj->getNavName()))) {
								$this->_model->updateCategory(trim($pageObj->getNavName()),$oldCatagoryId, $categoryId);
								$pageObj->setCategoryId($oldCatagoryId);
							}else {//if name not changed then error
								if(strtolower($pageObj->getNavName())!=strtolower(trim($oldNavegationName))) {

									$this->view->categoryExists = true;
								}else {   //update category name with saving hierarcy level

									$this->_model->updateCategory(trim($pageObj->getNavName()),$oldCatagoryId, $categoryId);
									$pageObj->setCategoryId($oldCatagoryId);
								}
							}
						}
						else //if page marked as category
						{//if there was no category with such name before

							if(!$this->_model->selectCategoryByName(trim($pageObj->getNavName()))) {
								$this->_model->updateCategory(trim($pageObj->getNavName()),$oldCatagoryId);
								$pageObj->setCategoryId($oldCatagoryId);
							}
							else {
								if(strtolower(trim($pageObj->getNavName()))!=strtolower(trim($oldNavegationName))) {
									$this->view->categoryExists = true;
								}
								else {
									$pageObj->setCategoryId($oldCatagoryId);
								}
							}

						}
						//if there was no such a category before
						if(!$this->view->categoryExists) {
						//set show in menu value to pageObj
							$pageObj->setShowInMenu($showInMenu);

							//*start to process image*//
							if(!empty ($imageName)) {
								$arr = explode(".", $imageName);
								$imageExtension = $arr[1];
								$oldImagePath = $websitePath."public/".$imagePath;

								$newImageFileName = RCMS_Tools_FilesystemTools::normalize(str_replace(" ", "-", $h1image),$pageObj->getId());
								$newImagePath = $websitePath.$previewPath.$newImageFileName.".".$imageExtension;

								$newH1Title = RCMS_Tools_FilesystemTools::normalize(str_replace(" ","-",trim($h1image)).".".$arr[1],$pageObj->getId());

								if(preg_match('/^[0-9]+$/',$arr[0])) {

									if(isset($pageImageObj) && !empty ($pageImageObj)) {
										@unlink($websitePath."public/".$previewFolderName."/".RCMS_Tools_FilesystemTools::normalize($pageImageObj->name),$pageObj->getId());
										clearstatcache();
									}

									if(!@copy($oldImagePath, $newImagePath)) {
										@unlink($websitePath."public/".$previewFolderName."/".RCMS_Tools_FilesystemTools::normalize($pageImageObj->name),$pageObj->getId());
										clearstatcache();
									}

									RCMS_Tools_FilesystemTools::recursive_remove_files_from_directory($pathTmp);
								}else {
									if($newH1Title!=$imageName) {
										@rename($websitePath.$previewPath.$imageName, $websitePath.$previewPath.RCMS_Tools_FilesystemTools::normalize($newH1Title,$pageObj->getId));
									}
								}
							}
                            /*end to process image*/

							$result = $pageObj->save();

                             /*start process featured areas*/
							$featuredIds = $pageForm->getElement('featured_ids')->getValue();
							$this->_model->deleteFeaturedAreasByPageId($pageId);
							if(!empty($featuredIds)) {
								$featuredIdsArray = explode(":", $featuredIds);
								//delete all from pages_has_fa
								foreach ($featuredIdsArray as $fa) {
									if(intval($fa))
										$this->_model->insertPageHasFa($pageId,$fa);
								}
							}
                            /*end process featured areas*/

							//assign new image name to a hidden field
							if(isset($newImageFileName)) {
								$this->view->pageForm->image_name->setValue($newImageFileName.".".$imageExtension);
							}
							//if page was saved succeessfuly
							if($result) {
							//synchronization for SEO
								$this->_seoParser->chainSyncOnUpdate($this->_session->oldPageUrl, $pageObj->getUrl(), $pageObj->getH1Tag(), $pageObj->getId());
								$this->_seoParser->createSiteMapFile();
								$this->view->redirect = $this->getWebSiteUrl().$pageObj->getUrl() . '.html';
							//$this->view->successEdit = true;
							}


							if(isset($newImageFileName) && $pageObj->getId()) {
							//if image for page already exists then update it
								$tryUpdate = $this->_model->updatePagePreview($newImageFileName.".".$imageExtension, $pageId,$previewFolderName."/".$newImageFileName.".".$imageExtension) ;
								if($tryUpdate==0) {//otherwivse insert new page preview.
									$this->_model->insertPagePreview($newImageFileName.".".$imageExtension, $pageId,$previewFolderName."/".$newImageFileName.".".$imageExtension);
								}
							}
						// }

						}
					}
				}
				else//else process errors
				{
					if($hasPages)
						$this->view->hasPages=$hasPages;
					if(!(trim(strtolower($navigationName)) == trim(strtolower($pageObj->getNavName()))) || !$this->_model->selectPageByNavigationName($navigationName))
						$this->view->pageExists = $navigationNameExists;
				}
			}
			else {
				$this->view->errorElements = $this->processErrors($this->view->pageForm->getMessages());
			}

		}

		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;

	}

	/**
	 *@method Init data for editing page form
	 *@param RCMS_Object_Page_Page $pageObj
	 *@return RCMS_Form_PageForm $pageForm
	 */
	private function initPageEditForm(RCMS_Object_Page_Page $pageObj) {
		if($pageObj instanceof RCMS_Object_Page_Page) {
			$pageForm = new RCMS_Form_PageForm();
			//   $pageWeight = array(0=>'0',1=>'1',2=>'2',3=>'3',4=>'4',5=>'5');
			// $pageForm->getElement('weight')->setMultiOptions($pageWeight);

			$pageForm->getElement('page_id')->setValue($pageObj->getId());
			$pageForm->getElement('h1')->setValue($pageObj->getH1Tag());
			$pageForm->getElement('header_title')->setValue($pageObj->getHeaderTitle());
			$pageForm->getElement('url')->setValue(urldecode(urldecode($pageObj->proccessUrl($pageObj->getUrl()))));
			$pageForm->getElement('nav_name')->setValue($pageObj->getNavName());
			$pageForm->getElement('meta_description')->setValue($pageObj->getMetaDescription());
			$pageForm->getElement('meta_keywords')->setValue($pageObj->getMetaKeywords());
			$pageForm->getElement('short_description')->setValue($pageObj->getShortDescription());
			$pageForm->getElement('is_404page')->setValue($pageObj->getIs404Page());
			$pageForm->getElement('targetedKeyPhrase')->setValue($pageObj->getTargetedKeyPhrase());
			//			$targetedKeyPhrase = empty(trim($data['targetedKeyPhrase']))? $data['url'] : trim($data['targetedKeyPhrase']) ;
			//$pageForm->getElement('weight')->setValue($pageObj->getWeight());

			$categoryData = $this->_model->selectCategoryById($pageObj->getCategoryId());
			if($categoryData) {
				if($categoryData->id_parent==0) {
					$pageForm->getElement('iscategory')->setValue(1);
				}
				else {
					$pageForm->getElement('iscategory')->setValue(0);
					$pageForm->getElement('pageselectcategory')->setValue($categoryData->id_parent);
				}
			}
			//set selected show in menu dropdown option
			$pageForm->getElement('selectmenu')->setValue($pageObj->getShowInMenu());
			//set template_id in a hidden field
			$pageForm->getElement('template_id')->setValue($pageObj->getTemplateId());
			//name the submit button.
			$pageForm->getElement('submit')->setLabel("{%UPDATE PAGE%}");

			//get new template for page using new template_id
			$templateObj  = new RCMS_Object_Template_Template($pageObj->getTemplateId());
			//setting correct name if it exists
			if($templateObj->getName()) {
				$templateName = ucfirst(strtolower(trim($templateObj->getName())));
			}else {
				$templateName = "Select a template.";
			}
			//set selected template name on a form.
			$pageForm->getElement('template_name')->setValue($templateName);

			$categories    = $this->_model->selectAllCategories();
			$featuredAreas = $this->_model->selectAllFeaturedAreas();
			$categories[-1] = "Select a category";
			$featuredAreas[-1] = "Is this page featured?";
			ksort($categories);
			ksort($featuredAreas);

			if(array_search($pageObj->getNavName(), $categories))
				unset($categories[array_search($pageObj->getNavName(), $categories)]);

			$pageForm->getElement('pageselectcategory')->setMultiOptions($categories);
			$pageForm->getElement('selectmenu')->setMultiOptions($this->generateShowInMainMenuSelectData());

			if($pageObj->getUrl() == 'index') {
				$this->_setReadOnly($pageForm, 'url');
			}
			elseif($pageObj->getUrl() == RCMS_Object_QuickConfig_QuickConfig::$draftCategoryUrl) {
				$this->_setReadOnly($pageForm, 'url');
				$this->_setReadOnly($pageForm, 'nav_name');
				$this->_setReadOnly($pageForm, 'h1');
				$this->_setReadOnly($pageForm, 'header_title');
				$this->_hideElement($pageForm, 'iscategory');
				$this->_hideElement($pageForm, 'selectmenu');
			}
			return $pageForm;
		}
		return null;

	}

	private function _setReadOnly($pageForm, $value) {
		$pageForm->getElement($value)->setAttrib('readonly','readonly');
		$pageForm->getElement($value)->setAttrib('style','background-color:#CCCCCC;');
	}

	private function _hideElement($pageForm, $value) {
		$pageForm->getElement($value)->setAttrib('style','display:none;');
	}


	/**
	 * @method This method generates data for select menu dropdown
	 * @return array
	 */
	public function generateShowInMainMenuSelectData() {
		return array(
		1=>"",
		2=>"",
		0=>""
		);
	}

	/**
	 * This method deletes page
	 *
	 * @return void
	 */
	public function deletepageAction() {
		$websiteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;

		$pageId = $this->getRequest()->getParam('pageId');
		if($pageId>0) {
			$pageObj = new RCMS_Object_Page_Page($pageId);
			if($pageObj->getUrl()!='index') {
				if(!$this->getCategoryChildren($pageObj->getCategoryId())) {
					if($pageObj->delete()) {

						$imagesArray = $this->_model->selectPageImagesByPageId($pageObj->getId());
						if($imagesArray) {

							foreach ($imagesArray as $imageObj) {
								$pathImage = (string) $this->_config->website->website->path .'public/previews/'.$imageObj->name;
								$flagDelete =  RCMS_Tools_FilesystemTools::deleteFile($pathImage);
							}
						}
						//delete all images concerned page from the database
						$pageObj->deleteAllImages();

						//delete content of container for a page
						$containersIdArray = $this->_model->selectContainerIdsForPageByPageId($pageObj->getId());
						foreach ($containersIdArray as $container) {
							$this->_model->deleteContentByIdContainer($container['id']);
							//delete conainer's dependencies
							$this->_model->deleteContainerDependencies($container['id']);
						}

						//delete deeplinks dependencies
						$this->_model->deleteDeeplinksDependencies($this->getWebSiteUrl() . $pageObj->getUrl() . '.html');
						//delete all containers
						$this->_model->deleteContainerByPageId($pageObj->getId());
						//delete all categories
						$this->_model->deleteCategoryById($pageObj->getCategoryId());
						//delete all featured areas
						$this->_model->deleteFeaturedAreasByPageId($pageObj->getId());
						//on index page for now
						$this->_redirectSuccessDelete($websiteUrl);
					}else {
						$this->view->message="Problems with deleting. Check if page exists";
					}
				}else {
					$this->_session->cantDelete = true;
					$this->_redirect($websiteUrl.$pageObj->getUrl().".html");
				}
			}else {
				$this->_redirect($websiteUrl);
			}

		}else {
			$this->_redirect($websiteUrl);
		}
	}

	/**
	 * @method This method is getting children pages of a category.
	 *
	 * @param integer $categoryId
	 * @return array or boolean
	 */
	public function getCategoryChildren($categoryId) {
		if($categoryId>0) {
			$category = $this->_model->selectCategoryById($categoryId);
			if($category->id_parent==0) {
				$result = $this->_model->selectAllCategories($categoryId);
				if($result) {
					return $result;
				}else {
					return false;
				}
			}
			else {
				return false;
			}
		}
		return false;
	}

	/**
	 * @method This method is executing redirect after page delete action.
	 *
	 * @param String $url
	 */
	private function _redirectSuccessDelete($url) {
		$this->_redirect($url);
	}

	/**
	 * @method This method is processing errors from Page Form
	 *
	 * @param Array $array
	 * @return String $htmlUl
	 */
	public function processErrors($array) {
		$messages = array();
		$htmlUl = "";
		foreach ($array as $key => $value) {
			switch ($key) {
				case 'h1':
					if(isset($value['isEmpty']))
						$messages[]="H1 Tag field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="H1 Tag field can only contain letters,digits and '-' .";
					break;

				case 'header_title':
					if(isset($value['isEmpty']))
						$messages[]="Header Title field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Header Title field can only contain letters,digits and '-' .";
					break;

				case 'url':
					if(isset($value['isEmpty']))
						$messages[]="Url Address field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Url Address field can only contain letters,digits and '-' .";
					break;

				case 'nav_name':
					if(isset($value['isEmpty']))
						$messages[]="Navigation Name field can't be empty.";
					if(isset($value['regexNotMatch']))
						$messages[]="Navigation Name field can only contain letters,digits and '-' .";
					break;

				case 'meta_description':
					if(isset($value['stringLengthTooShort']))
						$messages[]="Meta description field is too short.";
					if(isset($value['stringLengthTooLong']))
						$messages[]="Meta description field is too long.";
					break;

				case 'meta_keywords':
					if(isset($value['stringLengthTooShort']))
						$messages[]="Meta keywords field is too short.";
					if(isset($value['stringLengthTooLong']))
						$messages[]="Meta keywords field is too long.";
					break;

				case 'short_description':
					if(isset($value['stringLengthTooShort']))
						$messages[]="Page description field is too short.";
					if(isset($value['stringLengthTooLong']))
						$messages[]="Page description field is too long.";
					break;
				case 'template':
					$messages[] = "Please select template for your page";
					break;
			}
		}

		if(!empty($messages)) {
			$htmlUl = "";
			foreach ($messages as $message) {
				$htmlUl .= "<li><strong>".$message."</strong></li>";
			}
			return $htmlUl;
		}
		return null;
	}

	/**
	 * @method Checks if page is a category
	 * @param Integer $categoryId
	 * @return Boolean
	 */
	public function isCategory($categoryId) {
		if(intval($categoryId)>0) {
			$categoryObj = $this->_model->selectCategoryById($categoryId);
			if($categoryObj->id_parent==0) {
				return true;
			}
		}else {
			return false;
		}
		return false;

	}


	public function listallAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$catPages = $this->_model->getPagesCategories();
		foreach ($catPages as $key => $catPage) {
			$catPages[$key]['pages'] = $this->_model->getPagesForCategory($catPage['categoryId']);
		}
		$staticMenuPages = $this->_model->getStaicMenuPages();
		if(!empty ($staticMenuPages)) {
			$this->view->staticPages = $staticMenuPages;
		}
		$noMenuPages = $this->_model->getNoMenuPages();
		if(!empty($noMenuPages)) {
			$this->view->nomenuPages = $noMenuPages;
		}
		$this->view->pages = $catPages;

		$homePageId = $this->_model->getHomePageId();

		$this->view->homePageId = $homePageId;
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}


	/**
	 *@method  Recive order array and do the order routine
	 */
	public function orderAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		$ordersArray = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('orderList')));
        $staticOrderList = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('staticOrderList')));
        $noMenuList = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('nomenuList')));
		if(!empty ($ordersArray)) {
			foreach ($ordersArray as $arrayItem) {
				$category = new RCMS_Object_Page_Page($arrayItem->pageId);
				//$category->setUrl(urldecode($category->getUrl()));
				$category->setOrder($arrayItem->order);
				$catSaved = $category->save();
				$subPages = $arrayItem->pages;
				if(!empty ($subPages)) {
					foreach ($subPages as $subPage) {
						$categoryPage = new RCMS_Object_Page_Page($subPage->id);
						//$categoryPage->setUrl(urldecode($categoryPage->getUrl()));
						$categoryPage->setOrder($subPage->order);
						$categoryPage->setParentCategory($category->getCategoryId());
						$categoryPage->setShowInMenu(1);
						$catPageSaved = $categoryPage->save();
						}
				}
			}
		}
		
        if(!empty ($staticOrderList)) {
            foreach ($staticOrderList as $statOrderItem) {
                $statPage = new RCMS_Object_Page_Page($statOrderItem->id);
			//	$statPage->setUrl(urldecode($statPage->getUrl()));
                $statPage->setStaticOrder($statOrderItem->order);
                $statPage->setParentCategory(-1);
                $statPage->setShowInMenu(2);
                $statSaved = $statPage->save();
            }
        }
		if(!empty($noMenuList)) {
			foreach ($noMenuList as $noMenuItem) {
				$nomPage = new RCMS_Object_Page_Page($noMenuItem->id);
				//$nomPage->setUrl(urldecode($nomPage->getUrl()));
                $nomPage->setShowInMenu(0);
                $nomPage->setParentCategory(-1);
                $nomPage->save();
            }
        }
		
        if((isset($catSaved) && $catSaved) || (isset($statSaved) && $statSaved))  {
            echo 'success';
            exit;
        }
        echo "failed";
        exit;
    }

	/**
	 *@method Edit page h1 tag from listallpages
	 *
	 */
	public function edithtagAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$pageId = intval($this->getRequest()->getParam('pageId'));
		$newH1 = $this->getRequest()->getParam('newH1');
		$page = new RCMS_Object_Page_Page($pageId);
		$oldH1 = $page->getH1Tag();
		if($oldH1 != $newH1) {
			$page->setH1Tag($newH1);
			if($page->save()) {
				$this->_seoParser->chainSyncOnUpdate($page->getUrl(), $page->getUrl(), $page->getH1Tag(), $page->getId());
				$this->_seoParser->createSiteMapFile();
				echo $newH1;
				exit;
			}
			echo 'Error. Can not save page.';
			exit;
		}
		echo $oldH1;
		exit;
	}

	/**
	 *@method Edit edit keywords action
	 *
	 */
	public function editkeywordsAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$pageId = intval($this->getRequest()->getParam('pageId'));
		$newKeys = strip_tags($this->getRequest()->getParam('newKeys'));
		$page = new RCMS_Object_Page_Page($pageId);
		$page->setMetaKeywords($newKeys);
		if($page->save()) {
			echo $newKeys;
			exit;
		}
		echo 'Error. Can not save page.';
		exit;
	}

	/**
	 * @method Regenerates menu according to page (category / not category) (AJAX called in views/scripts/addpage.phtml)
	 *
	 */
	public function regeneratemenuAction() {
		$initMenu = 'all';
		$isCat = $this->getRequest()->getParam('iscat');
		if($isCat == 'true') {
			echo 'main';
		}
		elseif($isCat == 'false') {
			echo $initMenu;
		}
		exit;
	}

	/**
	 * @method checks not found
	 *
	 */
	public function checknotfoundAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$notFoundResult = $this->_model->selectNotFoundPage();
		echo (!empty($notFoundResult)) ? urlencode($notFoundResult . '.html') : 'fail';
	}

	/**
	 * @method updates not found
	 *
	 */
	public function updatenotfoundAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$pageUrl = $this->getRequest()->getParam('pageUrl');
		$page404State = $this->getRequest()->getParam('newVal');
		return $this->_model->updateNotFoundState($pageUrl, $page404State);
	}

	public function proccessUrl($url,$search=' ',$replace='-') {
		$url = str_replace(".html", '',trim($url));
		return str_replace($search, $replace,$url);
	}

	public function massdeletepagesAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost()) {
			$result1 = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('result1')));
			$result2 = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('result2')));
			$result3 = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('result3')));

			$common = array();
			foreach ($result1 as $value) {
				if($value!='0') {
					$common[] = str_replace("page-","",$value);
				}
			}

			foreach ($result2 as $value) {
				if($value!='0') {
					$common[]=str_replace("page-","",$value);
				}
			}

			foreach ($result3 as $value) {
				if($value!='0') {
					$common[]= str_replace("page-","",$value);
				}
			}
			
			foreach ($common as $value) {
				$pageObj = new RCMS_Object_Page_Page($value);
				if($pageObj->getUrl()!='index') {
					if(!$this->getCategoryChildren($pageObj->getCategoryId())) {
						if($pageObj->delete()) {
							$imagesArray = $this->_model->selectPageImagesByPageId($pageObj->getId());
							if($imagesArray) {

								foreach ($imagesArray as $imageObj) {
									$pathImage = (string) $this->_config->website->website->path .'public/previews/'.$imageObj->name;
									$flagDelete =  RCMS_Tools_FilesystemTools::deleteFile($pathImage);
								}
							}
							//delete all images concerned page from the database
							$pageObj->deleteAllImages();

							//delete content of container for a page
							$containersIdArray = $this->_model->selectContainerIdsForPageByPageId($pageObj->getId());
							foreach ($containersIdArray as $container) {
								$this->_model->deleteContentByIdContainer($container['id']);
								//delete conainer's dependencies
								$this->_model->deleteContainerDependencies($container['id']);
							}
							//delete deeplinks dependencies
							$this->_model->deleteDeeplinksDependencies($this->getWebSiteUrl() . $pageObj->getUrl() . '.html');
							//delete all containers
							$this->_model->deleteContainerByPageId($pageObj->getId());
							//delete all categories
							$this->_model->deleteCategoryById($pageObj->getCategoryId());
							//delete all featured areas
							$this->_model->deleteFeaturedAreasByPageId($pageObj->getId());
						//on index page for now
						//$this->_redirectSuccessDelete($websiteUrl);
						}
					}
				}
			}
/*
			foreach ($common as $value) {
				$pageObj = new RCMS_Object_Page_Page($value);
				$pageObj->delete();
			}*/
			echo RCMS_Tools_Tools::stripSlashesIfQuotesOn(json_encode($common));
		}
	}

/**
 * Method adds document about new page to lucene-index file
 *
 * @param RCMS_Object_Page_Page $pageObj
 * @return void
 */
	/*public function addLuceneIndex(RCMS_Object_Page_Page $pageObj)
	{
			$index = Zend_Search_Lucene::open('tmp/lucene-index');
				foreach($results as $result) {
					$doc = new Zend_Search_Lucene_Document();
					$doc->addField(Zend_Search_Lucene_Field::keyword('page_id',
						$pageObj->getId()));

					$doc->addField(Zend_Search_Lucene_Field::Text('meta_keywords',
						$pageObj->getMetaKeywords()));

					$doc->addField(Zend_Search_Lucene_Field::Text('meta_description',
						$pageObj->getMetaDescription()));

					$doc->addField(Zend_Search_Lucene_Field::Text('short_description',
						$pageObj->getShortDescription()));

					$doc->addField(Zend_Search_Lucene_Field::Text('header_title',
						$pageObj->getHeaderTitle()));

					$index->addDocument($doc);
				}
				$index->commit();
				$index->optimize();
	}*/


}

