<?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');

/**
 * @author     vinadelmar <vinadelmar@users.sourceforge.net>
 * @since      2006-02-20
 * @version    0.1.0d
 * @package    Core
 * @subpackage Forms
 */
class ContainerForm extends ObjectForm {

	var $containerId;
	var $contentId;
	var $containersListId;
	var $pageId;
	var $containerType;

	/**
	 * Constructor
	 *
	 * @param object $site
	 */
	function ContainerForm(&$site) {
		parent::ObjectForm($site);
		$this->containerId			= $this->site->getSubmittedVar('container_id', 0);
		$this->containersListId	= $this->site->getSubmittedVar('containers_list_id', 0);
		$this->pageId						= $this->site->getSubmittedVar('page_id', 0);
		$this->contentId				= $this->site->getSubmittedVar('content_id', 0);
		$this->containerType		= $this->site->getSubmittedVar('container_type', 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->getContainersManager();
		if(!$action) {
			$this->action = $mode;
		}
		else {
			$this->action = $action;
		}

		if ($this->containerId == 0) {
			if($this->containersListId > 0) {
				$containersListsManager = &$this->site->getContainersListsManager();
				$containersList = &$containersListsManager->getContainersList($this->containersListId, false);
				$aclId = $containersList->getContainersListAclId();
			}
			else if($this->pageId) {
        $pagesManager = &$this->site->getPagesManager();
        $page = &$pagesManager->getPage($this->pageId, false, false);
  			$aclId = $page->getPageAclId();
			}
			$container = &$this->objectManager->getNewContainer($aclId);
			$container->setContainerType($this->containerType);
			$this->objectManager->setContainer($container);
		}
		else {
			$container = &$this->objectManager->getContainer($this->containerId, false);
		}
		$this->object = &$container;
	}


	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_CONTAINER:
				break;
			case MODIF_CONTAINER:
				if($acl->userHasEditRight($user)) {
					$this->processFormModif();
				}
				break;
			case MOVE_CONTENT_TOP:
			case MOVE_CONTENT_BOTTOM:
			case MOVE_CONTENT_UP:
			case MOVE_CONTENT_DOWN:
				if($acl->userHasEditRight($user)) {
					$this->processFormMove();
				}
				break;
			case DELETE_CONTAINER:
				if($acl->userHasRemoveRight($user)) {
					$this->processFormDelete();
				}
				break;
		}
	}

	function processFormModif() {
		$this->object->setContainerValues($_POST);
		$this->objectManager->setContainer($this->object);

		if (!($containerId = $this->objectManager->storeContainer($this->containerId))) {
			return false;
		}

		if ($this->containersListId) {
			$containersListsManager = &$this->site->getContainersListsManager();
			$containersListsManager->addContainer($this->containersListId, $containerId);
			$containersListsManager->storeContainersList($this->containersListId);
		}

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

		return true;
	}

	function processFormMove() {
		if ($this->containerId && $this->contentId) {
			$dbManipulator = &$this->objectManager->getDBManipulator();

			$container_id = $this->containerId;

			if($this->object->getContainerCloneId() > 0) {
				$container_id = $this->object->getContainerCloneId();
			}

			// get the number of contents
			if(($result = $dbManipulator->getRecord(CONTAINER_CONTENTS_TABLE, $container_id, '', 'container_id'))) {
        $contents_count = $dbManipulator->getNumRows();
			}
			else {
        $contents_count = 0;
			}
			// get the position index of the content
			$result = $dbManipulator->getRecord(CONTAINER_CONTENTS_TABLE, $container_id, '`content_id`='.$this->contentId, 'container_id');

			if($row = $dbManipulator->fetchArray($result)){
				$index = $row['index'];
				if($this->action == MOVE_CONTENT_UP) {
		      if($index > 1) {
		        $this->processMoveUp($index);
		      }
				}
				elseif($this->action == MOVE_CONTENT_DOWN) {
          if($index < $contents_count) {
		        $this->processMoveDown($index);
          }
				}
				elseif($this->action == MOVE_CONTENT_TOP) {
		      while($index > 1) {
		        if(!$this->processMoveUp($index)) {
              break;
		        }
            --$index;
		      }
				}
				elseif($this->action == MOVE_CONTENT_BOTTOM) {
          while($index < $contents_count) {
		        if(!$this->processMoveDown($index)) {
              break;
		        }
            ++$index;
          }
				}
			}
		}
		$url = $this->site->getCurrentURL(false);
  	$this->site->redirectTo($url);
		exit();
	}

  function processMoveUp($index) {
    $result = true;
		$dbManipulator = &$this->objectManager->getDBManipulator();

		$container_id = $this->containerId;
		if($this->object->getContainerCloneId() > 0) {
			$container_id = $this->object->getContainerCloneId();
		}

		$result_array = $dbManipulator->sendQuery("SELECT max(`index`) as `index` FROM `".CONTAINER_CONTENTS_TABLE."`, `".TYPE_TABLES_PREFIX.$this->object->getContainerTypeName()."` WHERE `content_id` = `id` AND `deleted` = 0 AND `container_id` = ".$container_id." and `index` < $index");
		if(!($row = $dbManipulator->fetchArray($result_array))){
			$result = false;
		}
		else {
  		$previousIndex = $row['index'];
  		$result_array = $dbManipulator->getRecord(CONTAINER_CONTENTS_TABLE, $container_id, "`index`='$previousIndex'", 'container_id');
  		if($row = $dbManipulator->fetchArray($result_array)){
  			// there is a previous index
  			$previousContentId = $row['content_id'];
  			$fieldsArray = array();
  			$fieldsArray['index'] = $index;
  			$dbManipulator->setRecord(CONTAINER_CONTENTS_TABLE, $container_id, $fieldsArray, "`content_id`='$previousContentId'", 'container_id');
  			$fieldsArray['index'] = $previousIndex;
  			$dbManipulator->setRecord(CONTAINER_CONTENTS_TABLE, $container_id, $fieldsArray, "`content_id`='".$this->contentId."'", 'container_id');
  		}
    }
		return $result;
  }

  function processMoveDown($index) {
    $result = true;
    $dbManipulator = &$this->objectManager->getDBManipulator();

		$container_id = $this->containerId;
		if($this->object->getContainerCloneId() > 0) {
			$container_id = $this->object->getContainerCloneId();
		}

    $result_array = $dbManipulator->sendQuery("SELECT min(`index`) as `index` FROM `".CONTAINER_CONTENTS_TABLE."`, `".TYPE_TABLES_PREFIX.$this->object->getContainerTypeName()."` WHERE `content_id` = `id` AND `deleted` = 0 AND `container_id` = ".$container_id." and `index` > $index");
    if(!($row = $dbManipulator->fetchArray($result_array))){
    	$result = false;
    }
    $nextIndex = $row['index'];
    $result_array = $dbManipulator->getRecord(CONTAINER_CONTENTS_TABLE, $container_id, "`index`='$nextIndex'", 'container_id');
    if($row = $dbManipulator->fetchArray($result_array)){
    	// there is a next index
    	$nextContentId = $row['content_id'];
    	$fieldsArray = array();
    	$fieldsArray['index'] = $index;
    	$dbManipulator->setRecord(CONTAINER_CONTENTS_TABLE, $container_id, $fieldsArray, "`content_id`='$nextContentId'", 'container_id');
    	$fieldsArray['index'] = $nextIndex;
    	$dbManipulator->setRecord(CONTAINER_CONTENTS_TABLE, $container_id, $fieldsArray, "`content_id`='".$this->contentId."'", 'container_id');
    }
    return $result;
  }

	/**
	 * @return boolean
	 */
	function processFormDelete() {
		$containersManager = &$this->site->getContainersManager();
		return $containersManager->removeContainer($this->containerId);
	}

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