<?php
if (!defined('SIMPLE_CONTROLLER_VIEW_LIST')) define('SIMPLE_CONTROLLER_VIEW_LIST', '1');
if (!defined('SIMPLE_CONTROLLER_VIEW_FORM')) define('SIMPLE_CONTROLLER_VIEW_FORM', '2');
////@define('SIMPLE_CONTROLLER_VIEW_SINGLE', '2');
if (!defined('SIMPLE_CONTROLLER_VIEW_SINGLE')) define('SIMPLE_CONTROLLER_VIEW_SINGLE', '3');
if (!defined('SIMPLE_CONTROLLER_ACTION_ERROR')) define('SIMPLE_CONTROLLER_ACTION_ERROR', '10');
if (!defined('SIMPLE_CONTROLLER_ACTION_SUCCESS')) define('SIMPLE_CONTROLLER_ACTION_SUCCESS', '0');
if (!defined('SIMPLE_CONTROLLER_VIEW_NONE')) define('SIMPLE_CONTROLLER_VIEW_NONE', '99');
////@add
if (!defined('SIMPLE_CONTROLLER_VIEW_LIST_AND_FORM')) define('SIMPLE_CONTROLLER_VIEW_LIST_AND_FORM', '4');

if( !class_exists('XoopsSimpleController') )
{
 define('SIMPLE_CONTROLLER_REQUIRED_TABLEOBJECT_VER', 20060728);

class XoopsSimpleController {
	var $name;
	var $objectHandler;
	var $objectForm;
	var $objectList;
	var $listFilterCriteria = null;
	var $url;
	var $xoopsTpl;
	var $op = '';
//	var $defautlOp = '';
	var $defaultOp = 'list';
	var $allowedOp = array();
	var $object = null;
	var $errorMsg = '';
	var $_objectKey;
////@ add variable
	var $caption = '';
	var $classprefix;
	var $dirname;
	var $sort;
	var $order = 'asc';
	var $perpage = 30;
	var $start = 0;
	var $groupby = '';
	var $navclass = 'XoopsPageNav';
	var $classId = '';
	var $_listJoinCriteria = false;
	var $_filter = array();
	var $_having = '';
	var $_form_prefix = '';
	var $_const_prefix = '';

	function action() {
////@ add prepare process.
		$this->prepare();

		$object =& $this->objectHandler->create();
////@ chang for multiple key.
//		$objectKey = $object->getKeyFields();
//		$this->_objectKey = $objectKey[0];
		$this->_objectKey = $object->getKeyFields();

////@ enable limiting operation.(receive request only when operation is not limited)
//		$this->op = (!isset($_REQUEST['op'])) ? $this->defautlOp : $_REQUEST['op'];
//		if (in_array($this->op, $this->allowedOp) && method_exists($this, $this->op.'Action')) {
		if ($this->op == '') {
			if (isset($_REQUEST['op']) && in_array($_REQUEST['op'], $this->allowedOp)) {
				$this->op = $_REQUEST['op'];
			} else {
				$this->op = $this->defaultOp;
			}
		}
		if ($this->op != '' && method_exists($this, $this->op.'Action')) {
////@ end change
			$method = $this->op.'Action';
			return $this->$method();
		} else {
////@ to prevent endless loop.
//			$this->errorMsg = $this->__e('Invalid Operation');
//			return SIMPLE_CONTROLLER_ACTION_ERROR;
			die($this->op.'Action is not exist.<br />');
		}
	}

	function newAction() {
		$object =& $this->objectHandler->create();
////@ change for add prefix to form element's name.
//		$object->setFormVars($_POST,'');
		$object->setFormVars($_POST, $this->_form_prefix);
////@ end change
		return $this->_showForm($object, $this->__l('New'));
	}

	function editAction() {
////@ getting object process move to method '_getObject'.
//		if (isset($_GET[$this->_objectKey])) {
//			$object =& $this->objectHandler->get(intval($_GET[$this->_objectKey]));
		if ($object =& $this->_getObject($_GET)) {
////@ end change
			return $this->_showForm($object, $this->__l('Edit'));
		} else {
////@ setting error message move to method '_getObject'.
//			$this->errorMsg = $this->__e('Invalid Request');
			return SIMPLE_CONTROLLER_ACTION_ERROR;
		}
	}

	function _showForm(&$object, $caption) {
////@ add check form class is exist or not.
		if (!isset($this->objectForm)) die('Form object(ex:'.$this->classprefix.$this->classId.'Form) is not set.');

////@ check object and error-handling move to '_getObject' function.
//		if (is_object($object)) {

			$this->objectForm->setCaption($this->caption.' &raquo; '.$caption);

////@ use this method from '_insert' method.
//			$this->objectForm->showForm($object, $this->xoopsTpl);
			$this->objectForm->showForm($object, $this->xoopsTpl, $this->errorMsg);

			$this->object =& $object;
			return SIMPLE_CONTROLLER_VIEW_FORM;
////@ check object and error-handling move to '_getObject' function.
//		} else {
//			$this->errorMsg = $this->__e('No Record is found');
//			return SIMPLE_CONTROLLER_ACTION_ERROR;
//		}
////@ end change
	}

	function insertAction() {
		$object =& $this->objectHandler->create();
////@ add owner
		if (is_object($GLOBALS['xoopsUser'])) {
			$object->setOwner($GLOBALS['xoopsUser']->getVar('uid'));
		}

		return $this->_insert($object, $this->__l('New'));
	}

	function saveAction() {
////@ getting object process move to method '_getObject'.
//		$object =& $this->objectHandler->get(intval($_POST[$this->_objectKey]));
//		return $this->_insert($object, $this->__l('Edit'));
		if ($object =& $this->_getObject($_POST, true)) {
			return $this->_insert($object, $this->__l('Edit'));
		} else {
			return SIMPLE_CONTROLLER_ACTION_ERROR;
		}
////@ end change
	}

	function _insert(&$object, $caption) {
		if (class_exists('XoopsMultiTokenHandler') && !XoopsMultiTokenHandler::quickValidate($this->name.'_'.$this->op)) {
			$this->errorMsg = $this->__e('Token Error');
			return SIMPLE_CONTROLLER_ACTION_ERROR;
		}
////@ change checking object and error-handling move to '_getObject' function.
//		if (is_object($object)) {

			$this->object =& $object;
////@ change for form prefix
//			$object->setFormVars($_POST,'');
			$object->setFormVars($_POST, $this->_form_prefix);

////@ Set create/update time
			$object->setTime();

			if ($this->objectHandler->insert($object,false,true)) {
				return SIMPLE_CONTROLLER_ACTION_SUCCESS;
			} else {
////@ change for form prefix
//				$object->setFormVars($_POST,'');
				$object->setFormVars($_POST, $this->_form_prefix);

////@ use '_showForm' method
//				$this->objectForm->setCaption($this->caption.' &raquo; '.$caption);
//				$this->objectForm->showForm($object, $this->xoopsTpl, $this->objectHandler->getErrors());
//				return SIMPLE_CONTROLLER_VIEW_FORM;
				$this->errorMsg = $this->objectHandler->getErrors();
				return $this->_showForm($object, $caption);
////@ end change
			}
////@ change checking object and error-handling move to '_getObject' function.
//		} else {
//			$this->errorMsg = $this->__e('No Record is found');
//			return SIMPLE_CONTROLLER_ACTION_ERROR;
//		}
////@ end change
	}

	function deleteAction() {
////@ getting object process move to method '_getObject'.
//		if (isset($_GET[$this->_objectKey])) {
//			$key = intval(intval($_GET[$this->_objectKey]));
//			$object =& $this->objectHandler->get($key);
//			if (is_object($object)) {
		if ($object =& $this->_getObject($_GET)) {

////@ chang for multiple key.
//				ob_start();
//				xoops_confirm(array('op'=>'deleteok',$this->_objectKey=>$key), $this->url, $this->__l("Delete this Record")."? [ID=".$key."]");
			$hiddens = array('op'=>'deleteok');
			$strKey = $delim = '';
			foreach ($this->_objectKey as $k) {
				$value = $object->getVar($k);
				// use prefix
				$hiddens[$this->_form_prefix.$k] = $value;
				$id = (count($this->_objectKey) == 1) ? 'ID' : $k;
				$strKey .= $delim.$id.'='.$value;
				$delim = ', ';
			}
			ob_start();
			xoops_confirm($hiddens, $this->url, $this->__l("Delete this Record")."? [".$strKey."]");
////@ end change
				$this->xoopsTpl->assign('formhtml',ob_get_contents());
				ob_end_clean();
				$this->xoopsTpl->assign('title',$this->caption.' &raquo; '.$this->__l('Delete'));
////@ add for prevent notice
				$this->xoopsTpl->assign('errmsg','');

				return SIMPLE_CONTROLLER_VIEW_FORM;
////@ error-handling process move to '_getObject' function.
//			}
		}
//		$this->errorMsg = $this->__e('No Record is found');
		return SIMPLE_CONTROLLER_ACTION_ERROR;
	}

	function deleteokAction() {
	   if (class_exists('XoopsMultiTokenHandler') && !XoopsMultiTokenHandler::quickValidate(XOOPS_TOKEN_DEFAULT)) {
			$this->errorMsg = $this->__e('Token Error');
			return SIMPLE_CONTROLLER_ACTION_ERROR;
		}
////@ getting object process move to method '_getObject'.
//		if (isset($_POST[$this->_objectKey])) {
//			$key = intval(intval($_POST[$this->_objectKey]));
//			$object =& $this->objectHandler->get($key);
//		} else {
//			$object = false;
//		}
//		if (is_object($object)) {
		if ($object =& $this->_getObject($_POST, true)) {
////@ end change
			if ($this->objectHandler->delete($object)) {
				return SIMPLE_CONTROLLER_ACTION_SUCCESS;
			} else {
				$this->errorMsg = $this->__e('Record Delete Error');
				return SIMPLE_CONTROLLER_ACTION_ERROR;
			}
		}
////@ error-handling process move to '_getObject' function.
//		$this->errorMsg = $this->__e('No Record is found');
		return SIMPLE_CONTROLLER_ACTION_ERROR;
	}

	function listAction() {
////@ add check list class is exist or not.
		if (!isset($this->objectList)) die('List class(ex:'.$this->classprefix.$this->classId.'List) is not set');

////@ use module author designate default value.
//	  	$perpage = 30;
//	  	$start = isset($_GET['start']) ? intval($_GET['start']) : 0;
//	  	$order = (isset($_GET['order'])&& $_GET['order']=='desc') ? 'desc' : 'asc';
//	  	$sort = isset($_GET['sort']) ? htmlspecialchars($_GET['sort'],ENT_QUOTES) : $this->_objectKey;
//		if (!$this->objectList->inKey($sort)) $sort = $this->_objectKey;
		$perpage = isset($_GET['perpage']) ? intval($_GET['perpage']) : $this->perpage;
		$start = isset($_GET['start']) ? intval($_GET['start']) : $this->start;
		$order = (isset($_GET['order']) && ($_GET['order'] == 'desc' || $_GET['order'] == 'asc')) ? $_GET['order'] : $this->order;
		if (isset($_GET['sort']) && $this->objectList->inKey($_GET['sort'])) {
			$sort = $_GET['sort'];
		} elseif (isset($this->sort)) {
			$sort = $this->sort;
		} else {
		// for multiple key.
			$sort = $delim = '';
			foreach ($this->_objectKey as $k) {
				$sort .= $delim.$k;
				$delim = ',';
			}
		}

////@ get filter criteria from user request
//		if ($this->listFilterCriteria) {
//			$criteria =& $this->listFilterCriteria;
//		} else {
//			$criteria =& new Criteria(1,1);
//		}
		if (!$criteria =& $this->_getCriteria($_GET)) {
			return SIMPLE_CONTROLLER_ACTION_ERROR;
		}
		$this->objectList->setFilterCondition($this->_filter);
////@ end change
		$criteria->setStart($start);
		$criteria->setLimit($perpage);
		$criteria->setSort($sort);
		$criteria->setOrder($order);
////@ add groupby
		$criteria->setGroupby($this->groupby);

////@ change for grouping or join
//		$count = $this->objectHandler->getCount($criteria);
		$count = $this->objectHandler->getRowsNum($criteria, false, $this->_listJoinCriteria, $this->_having);

		require_once XOOPS_ROOT_PATH.'/class/pagenav.php';
////@ add filtering condition to link url
//		$extra = 'sort='.$sort.'&amp;order='.$order;
		$whereStr = '';
		foreach ($this->_filter as $k => $v) {
			$whereStr .= '&amp;'.$k.'='.$v;
		}
		$extra = 'sort='.htmlspecialchars($sort,ENT_QUOTES).'&amp;order='.$order.$whereStr;

////@ enable select navigator
//		$pageNav =& new XoopsPageNav($count,$perpage,$start,'start',$extra);
		$navclass = $this->navclass;
		$pageNav =& new $navclass($count, $perpage, $start, 'start', $extra);

////@ change add fieldlist and joincriteria
//		$objects =& $this->objectHandler->getObjects($criteria);
		$main_table = ($this->_listJoinCriteria) ? $this->objectHandler->getTableName().'.' : '';
		$sub_table = ($this->_listJoinCriteria) ? $this->_listJoinCriteria->getTableName().'.' : '';
		if ($this->groupby == '') {
			$keys = $this->_objectKey;
		} else {
			$keys = array();
		}
		$fieldlist = $this->objectList->getFieldlist($keys, $main_table, $sub_table);
		$objects =& $this->objectHandler->getObjects($criteria, false, $fieldlist, false, $this->_listJoinCriteria, $this->_having);
////@ end change
		$this->objectList->showList($objects, $this->xoopsTpl, $this->caption.' &raquo; '.$this->__l('List'),$sort, $order);
////@ show new button only when new option is allowed
//		$lang['new'] = $this->__l('New');
//    	$this->xoopsTpl->assign('lang', $lang);
//		$this->xoopsTpl->assign('newlink', $this->url.'?op=new');
		$lang = array();
		$newlink = false;
		if (in_array('new', $this->allowedOp)) {
			$lang['new'] = $this->__l('New');
			$newlink = $this->url.'?op=new';
		}
		$this->xoopsTpl->assign('newlink', $newlink);

////@ add deleteall and showall link
		$showalllink = false;
		if ($this->_filter) {
			$lang['showall'] = $this->__l('Show All');
			$showalllink = xoops_getenv('PHP_SELF').'?op=list';
		}
		$this->xoopsTpl->assign('showalllink', $showalllink);

		$delalllink = false;
		if (in_array('deleteall', $this->allowedOp) && $this->_having == '') {
			$lang['deleteall'] = $this->__l('Delete all');
			$delalllink = $this->url.'?op=deleteall'.$whereStr;
		}
		$this->xoopsTpl->assign('delalllink', $delalllink);

    	$this->xoopsTpl->assign('lang', $lang);
////@ end add
		$this->xoopsTpl->assign('pagenav', $pageNav->renderNav());
		return SIMPLE_CONTROLLER_VIEW_LIST;
//	    break;
	}

	function viewAction() {
////@ getting object process move to method '_getObject'.
//		if (isset($_GET[$this->_objectKey])) {
//			if ($object =& $this->objectHandler->get(intval($_GET[$this->_objectKey]))) {
		if ($object =& $this->_getObject($_GET, false, true)) {

////@ set object to class variable
			$this->object =& $object;

////@ assign all items to template
			$items = $object->getVarArray();
			if (isset($this->objectList)) {
				$items = array_merge($items, $this->objectList->getListItems($object));
			}
			$this->xoopsTpl->assign('items', $items);

				return SIMPLE_CONTROLLER_VIEW_SINGLE;
////@ error-handling process move to '_getObject' function.
//			}
		}
//		$this->errorMsg = $this->__e('No Record is found');
		return SIMPLE_CONTROLLER_ACTION_ERROR;
	}

	function __l($msg) {
		if (defined($this->_const_prefix.strtoupper($this->dirname).'_LANG_'.str_replace(' ','_',strtoupper($msg)))) {
			return constant($this->_const_prefix.strtoupper($this->dirname).'_LANG_'.str_replace(' ','_',strtoupper($msg)));
		} elseif (defined('_'.str_replace(' ','_',strtoupper($msg)))) {
			return constant('_'.str_replace(' ','_',strtoupper($msg)));
		} else {
			return $msg;
		}
	}

	function __e($msg) {
		if (defined($this->_const_prefix.strtoupper($this->dirname).'_ERROR_'.str_replace(' ','_',strtoupper($msg)))) {
			return constant($this->_const_prefix.strtoupper($this->dirname).'_ERROR_'.str_replace(' ','_',strtoupper($msg)));
		} else {
			return $msg;
		}
	}

	/**
	 * Confirmation of delete selected documents
	 */
	function deleteallAction() {
		if ($criteria =& $this->_getCriteria($_GET)) {
			if ($count = $this->objectHandler->getCount($criteria, $this->_listJoinCriteria)) {
				$this->_filter['op'] = 'deleteallok';
				ob_start();
				xoops_confirm($this->_filter, $this->url, $this->__l("Delete these Records")."? [$count records]");
				$this->xoopsTpl->assign('formhtml',ob_get_contents());
				ob_end_clean();
				$this->xoopsTpl->assign('title',$this->caption.' &raquo; '.$this->__l('Delete All'));
				$this->xoopsTpl->assign('errmsg','');
				return SIMPLE_CONTROLLER_VIEW_FORM;
			} else {
				$this->errorMsg = $this->__e('No Record is found');
			}
		}
		return SIMPLE_CONTROLLER_ACTION_ERROR;
	}

	/**
	 * Delete selected documents
	 */
	function deleteallokAction() {
		if (class_exists('XoopsMultiTokenHandler') && !XoopsMultiTokenHandler::quickValidate(XOOPS_TOKEN_DEFAULT)) {
			$this->errorMsg = $this->__e('Token Error');
			return SIMPLE_CONTROLLER_ACTION_ERROR;
		}

		if ($criteria =& $this->_getCriteria($_POST)) {
			if ($this->objectHandler->deleteAll($criteria)) {
				return SIMPLE_CONTROLLER_ACTION_SUCCESS;
			} else {
				$this->errorMsg = $this->__e('Record Delete Error');
			}
		}
		return SIMPLE_CONTROLLER_ACTION_ERROR;
	}

	/**
	 * Show list and form for posting new recored.
	 */
	function listwithformAction() {
		if ($this->listAction() == SIMPLE_CONTROLLER_ACTION_ERROR) {
			return SIMPLE_CONTROLLER_ACTION_ERROR;
		}
		$object =& $this->objectHandler->create();
		$this->_showForm($object, $this->__l('New'));
		return SIMPLE_CONTROLLER_VIEW_LIST_AND_FORM;
	}

	/**
	 * Get single XoopsTableObject by requested keys
	 *
	 * @param array $var_arr [ $_GET | $_POST ]
	 * @param bool[optional] $addPref
	 * @param bool[optional] $readOnly
	 * @return object reference to {@link XoopsTableObject}, bool false on fail
	 */
	function &_getObject($var_arr, $addPref = false, $readOnly = false) {
		$pref = ($addPref) ? $this->_form_prefix : '';
		$ret = false;
		$keys = array();
		foreach ($this->_objectKey as $k) {
			if (isset($var_arr[$pref.$k])) {
				$keys[$k] = $var_arr[$pref.$k];//@ set raw value
			} else {
				$this->errorMsg = $this->__e('Invalid Request');
				return $ret;
			}
		}
		$object =& $this->objectHandler->get($keys);
		if (is_object($object)) {
			if (!$readOnly && !$GLOBALS['xoopsUserIsAdmin']) {
				if (!is_object($GLOBALS['xoopsUser']) || $GLOBALS['xoopsUser']->getVar('uid') != $object->getOwner()) {
					$this->errorMsg = $this->__e('No permission');
					return $ret;
				}
			}
			return $object;
		}
		$this->errorMsg = $this->__e('No Record is found');
		return $ret;
	}

	/**
	 * Add record filtering condition
	 * @param string $column
	 * @param mixed $value
	 */
	function addFilter2List($column, $value) {
		$this->_filter[$column] = $value;
	}

	/**
	 * Add join criteria
	 * @param string $table_name
	 * @param string $main_field
	 * @param string $sub_field
	 * @param string $join_type
	 * @param string $table_alias
	 */
	function setJoin2List($table_name, $main_field, $sub_field, $join_type='LEFT', $table_alias="") {
		$this->_listJoinCriteria =& new XoopsJoinCriteria($GLOBALS['xoopsDB']->prefix($table_name), $main_field, $sub_field, $join_type, $table_alias);
	}

	/**
	 * Preparation for action
	 */
	function prepare() {
		if (!defined('XTOBJ_VERSION') || (XTOBJ_VERSION < SIMPLE_CONTROLLER_REQUIRED_TABLEOBJECT_VER)) {
			echo 'XoopsTableObject later than '. SIMPLE_CONTROLLER_REQUIRED_TABLEOBJECT_VER .' is required.<br />';
			echo 'Current efective file is<br />';
			$xtobj_ver = defined('XTOBJ_VERSION') ? XTOBJ_VERSION : 'Not defined.';
			$xtobj_path = defined('XTOBJ_FILE_PATH') ? XTOBJ_FILE_PATH : 'Not defined.';
			echo 'Ver: '. $xtobj_ver .'<br />';
			echo 'File path: '. $xtobj_path .'<br />';
			echo 'Update this file<br />';
			echo 'you can get latest version XoopsTableObject <a href="http://cvs.sourceforge.jp/cgi-bin/viewcvs.cgi/cell/util/">here</a><br />';
			exit();
		}
		if (!isset($this->name)) {
			die('Please set name of controller.<br />');
		}
		if (!isset($this->url)) {
			$this->url = xoops_getenv('PHP_SELF');
		}
		if (!isset($this->classprefix)) {
			$this->classprefix = $this->name;
		}
		if (!isset($this->xoopsTpl)) {
			$this->xoopsTpl =& $GLOBALS['xoopsTpl'];
		}
		if (!isset($this->dirname)) {
			$this->dirname = $GLOBALS['xoopsModule']->getVar('dirname');
		}
		if (!isset($this->objectHandler)) {
			$handlerName = $this->classprefix.'Handler';
			$this->objectHandler =& new $handlerName($GLOBALS['xoopsDB']);
		}
		if (!isset($this->objectList)) {
			$listName = $this->classprefix.$this->classId.'List';
			if (class_exists($listName)) {
				$this->objectList =& new $listName();
			}
		}
		if (!isset($this->objectForm)) {
			$formName = $this->classprefix.$this->classId.'Form';
			if (class_exists($formName)) {
				$this->objectForm =& new $formName();
				$this->objectForm->setName($this->name);
				$this->objectForm->setAction($this->url);
				$this->objectForm->setToken(1);
			}
		}
		if (isset($this->objectForm)) {
			$this->_form_prefix = $this->objectForm->getPrefix();
		}
		if (isset($this->defautlOp)) $this->defaultOp = $this->defautlOp;
	}

	/**
	 * Get criteria from filter
	 *
	 * @param array $arr [ $_GET | $_POST ]
	 * @return object {@link CriteriaCompo}
	 */
	function &_getCriteria($var_arr) {
		$ret = false;
		$criteria =& new CriteriaCompo();
		if (isset($this->listFilterCriteria)) {
			$criteria->add($this->listFilterCriteria);
		} else {
			$criteria->add(new Criteria(1,1));
		}

		//add filter criteria setting by module author
		foreach ($this->_filter as $key=>$Value) {
			$criteria->add(new Criteria($key, $Value));
		}

		// recieve filter request only when list class is exist.
		if (!isset($this->objectList)) {
			$this->_filter = array();
			return $criteria;
		}

		$p = ($this->op == 'deleteallok') ? $this->_form_prefix : '';
		$pref = ($this->op == 'deleteall') ? $this->_form_prefix : '';

		//if table is joined, table name is need.
		$main_table = ($this->_listJoinCriteria) ? $this->objectHandler->getTableName().'.' : '';
		$sub_table = ($this->_listJoinCriteria) ? $this->_listJoinCriteria->getTableName().'.' : '';

		//add filter criteria by request
		$filter = array();
		$myts =& MyTextSanitizer::getInstance();
		foreach ($this->objectList->getElements() as $k=>$element) {
			if (!isset($var_arr[$p.$k]) || isset($this->_filter[$k])) {
				continue;
			}
			if ((substr($var_arr[$p.$k], 0, 1) == '`') || (substr($var_arr[$p.$k], -1) == '`')) {
				$this->errorMsg = $this->__e('Invalid Request');
				return $ret;
			}
			$value = $myts->addSlashes($var_arr[$p.$k]);
			if (!isset($element['ext']['extraVar'])) {
				$criteria->add(new Criteria($main_table.$k, $value));
			} elseif (preg_match('/^(count|sum|avg|min|max)_(\w+)_$/i', $k, $matches)) {
				if ($action != 0) {
					$this->errorMsg = $this->__e('Invalid Request');
					return $ret;
				}
				$this->_having = $matches[1].'('.$matches[2].')'.' = '.$value;
			} elseif ( $k == '__SimpleCount__') {
				if ($action != 0) {
					$this->errorMsg = $this->__e('Invalid Request');
					return $ret;
				}
				$this->_having = 'count(*) = '.intval($var_arr[$p.$k]);

			} elseif ($element['ext']['extraVar'] == '__ExtraVar__') {
				$criteria->add(new Criteria($sub_table.$k, $value));
			} else {
				continue;
			}
			$filter[$pref.$k] = htmlspecialchars($var_arr[$p.$k], ENT_QUOTES);
		}
		foreach ($this->_objectKey as $k) {
			if (!isset($var_arr[$p.$k]) || isset($this->_filter[$k]) || isset($filter[$pref.$k])) {
				continue;
			}
			$criteria->add(new Criteria($main_table.$k, $myts->addSlashes($var_arr[$p.$k])));
			$filter[$pref.$k] = htmlspecialchars($var_arr[$p.$k], ENT_QUOTES);
		}
		$this->_filter = $filter;
		return $criteria;
	}
}//end of class XoopsSimpleController

class XoopsSimpleAdminController extends XoopsSimpleController{
//	var $dirname;
	var $formTemplate;
	var $listTemplate;

	function XoopsSimpleAdminController($name,$caption) {
		$this->name = $name;
		$this->caption = $caption;
////@ change for new XoopsSimpleController
//		$this->url = xoops_getenv('PHP_SELF');
//		$handlerName = $name.'Handler';
//		$listName = $name.'AdminList';
//		$formName = $name.'AdminForm';
//		$this->objectHandler =& new $handlerName($GLOBALS['xoopsDB']);
//		$this->objectForm =& new $formName($caption, $name, $this->url, 1);
//		$this->objectList =& new $listName();
		$this->xoopsTpl =& new XoopsAdminTpl();
		$this->dirname = $GLOBALS['xoopsModule']->getVar('dirname');
		$this->formTemplate = $this->dirname.'_admin_simpleform.html';
		$this->listTemplate = $this->dirname.'_admin_simplelist.html';
//		$this->defautlOp = 'list';
		$this->allowedOp = array('list','new','edit','insert','save','delete','deleteok');
	//add next 2 line
		$this->classId = 'Admin';
		$this->_const_prefix = '_AD_';
////@ end change
	}

	function execute() {
		$result = $this->action();
		switch ($result) {
			case SIMPLE_CONTROLLER_VIEW_FORM:
			case SIMPLE_CONTROLLER_VIEW_LIST:
			case SIMPLE_CONTROLLER_VIEW_LIST_AND_FORM:
				global $xoopsConfig, $xoopsModule;
				xoops_cp_header();
				$admin_dir = XOOPS_ROOT_PATH.'/modules/'.$this->dirname.'/admin';
				if (file_exists($admin_dir.'/mymenu.php')) {
					include( $admin_dir.'/mymenu.php' );
				}
				$this->xoopsTpl->assign('modulename', $GLOBALS['xoopsModule']->getVar('name'));
				if ($result == SIMPLE_CONTROLLER_VIEW_FORM) {
////@ 		// change start for using common templates
			// if this file is put on a common place.
//			    	$this->xoopsTpl->display($this->formTemplate);
					$template = $this->formTemplate;
					$templatetype = 'form';
			    } else {
//			    	$this->xoopsTpl->display($this->listTemplate);
			    	$template = $this->listTemplate;
					$templatetype = 'list';
			    }
			    if (!file_exists($this->xoopsTpl->template_dir.'/'.$template)) {
				    $this->xoopsTpl->template_dir = dirname(__FILE__).'/templates';
				    $template = 'admin_simple'.$templatetype.'.html';
			    }
			    $this->xoopsTpl->display($template);
////@ change end
				xoops_cp_footer();
				break;
			case SIMPLE_CONTROLLER_VIEW_NONE:
				break;
			case SIMPLE_CONTROLLER_ACTION_ERROR:
				redirect_header($this->url, 2, $this->errorMsg,2);
				break;
			case SIMPLE_CONTROLLER_ACTION_SUCCESS:
				redirect_header($this->url, 2, $this->__l('Action Success'));
				break;
			default:
				break;
		}
	}
/*
	function __l($msg) {
		if (defined('_AD_'.strtoupper($this->dirname).'_LANG_'.str_replace(' ','_',strtoupper($msg)))) {
			return constant('_AD_'.strtoupper($this->dirname).'_LANG_'.str_replace(' ','_',strtoupper($msg)));
		} else {
			return $msg;
		}
	}
	function __e($msg) {
		if (defined('_AD_'.strtoupper($this->dirname).'_ERROR_'.str_replace(' ','_',strtoupper($msg)))) {
			return constant('_AD_'.strtoupper($this->dirname).'_ERROR_'.str_replace(' ','_',strtoupper($msg)));
		} else {
			return $msg;
		}
	}
*/
}//end of class XoopsSimpleAdminController

/**
 * Simple controller that can use all type of action except deleteall
 */
class XoopsSimpleMainController extends XoopsSimpleController
{
	/**
	 * Cnstructor
	 * @param string $classprefix
	 * @param string $name
	 * @param string $caption
	 */
	function XoopsSimpleMainController($classprefix, $name, $caption = '') {
		$this->name = $name;
		$this->caption = $caption;
		$this->classprefix = $classprefix;
		$this->allowedOp = array('list','new','edit','insert','save','delete','deleteok','view');

		$this->classId = '';
		$this->_const_prefix = '_MD_';
	}

	function execute() {
		$result = $this->action();
		switch ($result) {
			case SIMPLE_CONTROLLER_VIEW_FORM:
			case SIMPLE_CONTROLLER_VIEW_LIST:
			case SIMPLE_CONTROLLER_VIEW_SINGLE:
			case SIMPLE_CONTROLLER_VIEW_LIST_AND_FORM:
				$this->xoopsTpl->assign('modulename', $GLOBALS['xoopsModule']->getVar('name'));
				$this->xoopsTpl->assign('type', $result);
			    break;
			case SIMPLE_CONTROLLER_VIEW_NONE:
				break;
			case SIMPLE_CONTROLLER_ACTION_ERROR:
				redirect_header($this->url, 2, $this->errorMsg);
				break;
			case SIMPLE_CONTROLLER_ACTION_SUCCESS:
				redirect_header($this->url, 2, $this->__l('Action Success'));
				break;
			default:
				die('Incomprehensible Error<br />');
				break;
		}
	}
}//end of class XoopsSimpleMainController

/**
 * Simple controller for block contents
 */
class XoopsSimpleBlockController extends XoopsSimpleController
{
	/**
	 * Cnstructor
	 * @param string $classprefix
	 * @param string $name
	 * @param string $caption
	 */
	function XoopsSimpleBlockController($name, $caption = '', $classprefix = null, $url = null) {
		$this->name = $name;
		$this->caption = $caption;
		$this->classprefix = $classprefix;
		$this->url = $url;

		$current_block = $GLOBALS['block_arr'][$GLOBALS['i']];
		$this->dirname = $current_block->getVar('dirname');
		$this->xoopsTpl =& new XoopsSimpleBlockItem();

		$this->classId = 'Block';
		$this->_const_prefix = '_MB_';
	}

	/**
	 * @return array array of block items
	 */
	function getBlockItems() {
		$result = $this->action();
		switch ($result) {
			case SIMPLE_CONTROLLER_VIEW_FORM:
			case SIMPLE_CONTROLLER_VIEW_LIST:
			case SIMPLE_CONTROLLER_VIEW_SINGLE:
			case SIMPLE_CONTROLLER_VIEW_LIST_AND_FORM:
				$block = $this->xoopsTpl->get_vars();
				$block['type'] = $result;
				return $block;
			    break;
			case SIMPLE_CONTROLLER_VIEW_NONE:
			    break;
			case SIMPLE_CONTROLLER_ACTION_ERROR:
				return array('errmsg' => $this->errorMsg, 'type' => SIMPLE_CONTROLLER_ACTION_ERROR);
				break;
			case SIMPLE_CONTROLLER_ACTION_SUCCESS:
				redirect_header($this->url, 2, $this->__l('Action Success'));
				break;
			default:
				die('Incomprehensible Error<br />');
				break;
		}
	}
}//end of class XoopsSimpleBlockController
}//end of if

if( !class_exists('XoopsAdminTpl') )
{
require_once(XOOPS_ROOT_PATH.'/class/template.php');
class XoopsAdminTpl extends XoopsTpl
{
	function XoopsAdminTpl()
	{
		parent::XoopsTpl();
		$this->template_dir = XOOPS_ROOT_PATH . '/modules/' .$GLOBALS['xoopsModule']->getVar('dirname').'/admin/templates';
		$this->error_reporting = error_reporting();
	}

	function fetch($tplfile, $cache_id = null, $compile_id = null, $display = false)
	{
		if (!$compile_id) {
			$compile_id = 'admin_';
		}
		return parent::fetch($tplfile, $cache_id, $compile_id, $display);
	}
}//end of class XoopsAdminTpl
}//end of if

/**
 * Class that contain block items
 */
if( !class_exists('XoopsSimpleBlockItem') )
{
 class XoopsSimpleBlockItem
 {
 	/**
 	 * @var array array of block item
 	 */
 	var $_vars = array();

 	/**
 	 * Set block item value
 	 * @param mixed $var
 	 * @param mixed[optional] $value
 	 */
 	function assign($var, $value = null) {
		if (is_array($var)){
			foreach ($var as $key => $val) {
				if ($key != '') {
					$this->_vars[$key] = $val;
				}
			}
		} else {
			if ($var != '') {
				$this->_vars[$var] = $value;
			}
		}
 	}

 	/**
 	 * Return block item value
 	 * @param string[optional] $name
 	 * @return array array of block items
 	 */
 	function &get_vars($name=null)
 	{
		if(!isset($name)) {
			return $this->_vars;
		} elseif(isset($this->_vars[$name])) {
			return $this->_vars[$name];
		} else {
			$_tmp = null;
			return $_tmp;
		}
	}
 }//end of class XoopsSimpleBlockItem
}//end of if
?>