<?php
/*
 * This file is part of the easy-CMS project.
 * easy-CMS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * easy-CMS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with easy-CMS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/**
 * @package    Core
 * @subpackage Forms
 */
 
include_once('classes/core/forms/ObjectForm.class.php');

/**
 * Menu Form
 *
 * @author cedseven
 */
class MenuForm extends ObjectForm {

	var $menuId;
	var $pageId;

	/**
	 * Constructor
	 *
	 * @param object $site
	 */
	function MenuForm(&$site) {
		parent::ObjectForm($site);
		$this->menuId			= $this->site->getSubmittedVar('menu_id', 0);
		$this->pageId			= $this->site->getSubmittedVar('page_id', 0);
		$mode							= $this->site->getSubmittedVar('mode');
		$action						= $this->site->getSubmittedVar('action');

//todo : check if all needed vars are found : otherwise it should generate errors

		if (!($lid = $site->getSubmittedVar('lid', 0))) {
			if (!($lid = $site->getPersistentVar('lid', 0))) {
				$lid = $this->site->getDefaultLangId();
			}
		}

		$this->objectManager = &$this->site->getMenusManager();
		if(!$action) {
			$this->action = $mode;
		}
		else {
			$this->action = $action;
		}

		if ($this->menuId == 0) {
			if($this->pageId > 0) {
        $pagesManager = &$this->site->getPagesManager();
        $page = &$pagesManager->getPage($this->pageId, false, false);
  			$aclId = $page->getPageAclId();
			}
			else {
        $aclId = $this->site->getRootAclId();
			}
			$menu = &$this->objectManager->getNewMenu($aclId);
			$this->objectManager->setMenu($menu);
		}
		else {
			$menu = &$this->objectManager->getMenu($this->menuId, false);
		}
		$this->object = &$menu;
  }
	
	function processForm() {
		// check user rights on current object
		$aclManager = &$this->site->getACLManager();
		$user       = &$this->site->getCurrentUser();
		$aclId      = $this->object->getAclId();
		$acl        = &$aclManager->getAcl($aclId);

		switch($this->action) {
			case ASK_MODIF_MENU:
				break;
			case MODIF_MENU:
				if($acl->userHasEditRight($user)) {
					$this->processFormModif();
				}
				break;
			case MOVE_PAGE_TOP:
			case MOVE_PAGE_BOTTOM:
			case MOVE_PAGE_UP:
			case MOVE_PAGE_DOWN:
				if($acl->userHasEditRight($user)) {
					$this->processFormMove();
				}
				break;
			case DELETE_MENU:
				if($acl->userHasRemoveRight($user)) {
					$this->processFormDelete();
				}
				break;
		}
	}

	function processFormModif() {
		$this->object->setMenuValues($_POST);
		$this->objectManager->setMenu($this->object);

		if (!($menuId = $this->objectManager->storeMenu($this->menuId))) {
			return false;
		}

		if ($this->pageId) {
			$pagesManager = &$this->site->getPagesManager();
			$pagesManager->setPageForCacheRenewalAndStore($this->pageId);
		}

		return true;
	}

	function processFormMove() {
		$menuNodeParentId = $this->site->getSubmittedVar('parent_id');
		$menuNodeId       = $this->site->getSubmittedVar('node_id');
		$menuId           = $this->menuId;

		if ($menuNodeParentId && $menuNodeId && $menuId) {
			$dbManipulator = &$this->objectManager->getDBManipulator();
			// get the number of nodes
			if(($result = $dbManipulator->getRecord(MENU_NODES_TABLE, $menuNodeParentId, '', 'parent_node_id'))) {
        $nodes_count = $dbManipulator->getNumRows();
			}
			else {
        $nodes_count = 0;
			}

			// get the position index of the content
			$result = $dbManipulator->getRecord(MENU_NODES_TABLE, $menuNodeId, "`menu_id`='$menuId'");
			if($row = $dbManipulator->fetchArray($result)) {
				$index = $row['index'];

				if($this->action == MOVE_PAGE_UP) {
					if($index > 1) {
            $this->processMoveUp($index);
					}
				}
				elseif($this->action == MOVE_PAGE_DOWN) {
          if($index < $nodes_count) {
            $this->processMoveDown($index);
          }
				}
        elseif($this->action == MOVE_PAGE_TOP) {
					while($index > 1) {
            if(!$this->processMoveUp($index)) {
              break;
            }
            --$index;
					}
        }
        elseif($this->action == MOVE_PAGE_BOTTOM) {
          while($index < $nodes_count) {
            if(!$this->processMoveDown($index)) {
              break;
            }
            ++$index;
          }
        }
			}
		}
		$url = $this->site->getCurrentURL(false);
    // force edit_mode
    $url = str_replace('mode=view','mode=edit', $url);
  	$this->site->redirectTo($url);
		exit();
	}

  function processMoveUp($index) {
    $result = true;
		$menuNodeParentId = $this->site->getSubmittedVar('parent_id');
		$menuNodeId       = $this->site->getSubmittedVar('node_id');
		$menuId           = $this->menuId;
    $dbManipulator = &$this->objectManager->getDBManipulator();
		$result_array = $dbManipulator->sendQuery("SELECT max(`index`) as `index` FROM `".MENU_NODES_TABLE."` WHERE `menu_id`='$menuId' AND `parent_node_id` = '$menuNodeParentId' and `index` < $index");
		if(!($row = $dbManipulator->fetchArray($result_array))){
			$result = false;
		}
		else {
  		$previousIndex = $row['index'];
  		$result_array = $dbManipulator->getRecord(MENU_NODES_TABLE, $menuNodeParentId, "`index`=$previousIndex", 'parent_node_id');
  		if($row = $dbManipulator->fetchArray($result_array)){
  			// there is a previous index
  			$prevNodeId = $row['id'];
  			$fieldsArray = array();
  			$fieldsArray['index'] = $index;
  			$dbManipulator->setRecord(MENU_NODES_TABLE, $menuNodeParentId, $fieldsArray, "`id`='$prevNodeId'", 'parent_node_id');
  			$fieldsArray['index'] = $previousIndex;
  			$dbManipulator->setRecord(MENU_NODES_TABLE, $menuNodeParentId, $fieldsArray, "`id`='$menuNodeId'", 'parent_node_id');
  		}
		}
    return $result;
  }
  
  function processMoveDown($index) {
    $result = true;
		$menuNodeParentId = $this->site->getSubmittedVar('parent_id');
		$menuNodeId       = $this->site->getSubmittedVar('node_id');
		$menuId           = $this->menuId;
    $dbManipulator = &$this->objectManager->getDBManipulator();
		$result_array = $dbManipulator->sendQuery("SELECT min(`index`) as `index` FROM `".MENU_NODES_TABLE."` WHERE `menu_id`='$menuId' AND `parent_node_id`='$menuNodeParentId' and `index` > $index");
		if(!($row = $dbManipulator->fetchArray($result_array))){
			$result = false;
		}
		else {
  		$nextIndex = $row['index'];
  		$result_array = $dbManipulator->getRecord(MENU_NODES_TABLE, $menuNodeParentId, "`index`='$nextIndex'", 'parent_node_id');
  		if($row = $dbManipulator->fetchArray($result_array)){
  			// there is a next index
  			$nextNodeId = $row['id'];
  			$fieldsArray = array();
  			$fieldsArray['index'] = $index;
  			$dbManipulator->setRecord(MENU_NODES_TABLE, $menuNodeParentId, $fieldsArray, "`id`='$nextNodeId'", 'parent_node_id');
  			$fieldsArray['index'] = $nextIndex;
  			$dbManipulator->setRecord(MENU_NODES_TABLE, $menuNodeParentId, $fieldsArray, "`id`='$menuNodeId'", 'parent_node_id');
  		}
    }
    return $result;
  }

	/**
	 * @return boolean
	 */
	function processFormDelete() {
		$site = &Site::getInstance();
		$menusManager = &$site->getMenusManager();
		return $menusManager->removeMenu($this->menuId);
	}

	function spreadAcl($aclId) {
		return $this->objectManager->updateMenuACL($this->menuId, $aclId);
	}
}
?>