<?php
/**
* Component handler class
* @package Mambo
*/
class mosComponentHandler {
	var $_buffer = '';
	
	function &getInstance () {
		static $instance;
		if (!is_object($instance)) $instance = new mosComponentHandler();
		return $instance;
	}
	
	function &getParamsByName ($name) {
		$params = null;
		$row = new mosComponent();
		$query = "SELECT a.params, a.option"
		. "\n FROM #__components AS a"
		. "\n WHERE a.name = '$name'"
		;
		$database =& mamboDatabase::getInstance();
		$database->setQuery( $query );
		// load the row from the db table
		if ($database->loadObject($row)) {
			// get params definitions
			$mainframe =& mosMainFrame::getInstance();
			$params =& new mosParameters( $row->params);
		}
		return $params;
	}

	function mosMainBody() {
		// message passed via the url
		$mosmsg = mosGetParam($_REQUEST, 'mosmsg', '');
		if ($mosmsg) {
			if (!get_magic_quotes_gpc()) $mosmsg = addslashes( $mosmsg );
			echo "\n<div class=\"message\">$mosmsg</div>";
		}
		echo $this->_buffer;
//      Alternative if "popmessages" - apparently never implemented
//		echo "\n<script language=\"javascript\">alert('$mosmsg');</script>";
	}
	
	function startBuffer () {
		$this->_buffer = '';
		ob_start();
	}
	
	function endBuffer () {
		$this->_buffer = ob_get_contents();
		ob_end_clean();
	}
	
}
/**
* Component database table class
* @package Mambo
*/
class mosComponent extends mosDBTable {
	/** @var int Primary key */
	var $id=null;
	/** @var string */
	var $name=null;
	/** @var string */
	var $link=null;
	/** @var int */
	var $menuid=null;
	/** @var int */
	var $parent=null;
	/** @var string */
	var $admin_menu_link=null;
	/** @var string */
	var $admin_menu_alt=null;
	/** @var string */
	var $option=null;
	/** @var string */
	var $ordering=null;
	/** @var string */
	var $admin_menu_img=null;
	/** @var int */
	var $iscore=null;
	/** @var string */
	var $params=null;

	/**
	* @param database A database connector object
	*/
	function mosComponent() {
		$db = mamboDatabase::getInstance();
		$this->mosDBTable( '#__components', 'id', $db );
	}
}
/**
* Component common base class for both user and admin sides
* @package Mambo
*/
class mosComponentManager {
	var $plugin_name = '';
	var $magic_quotes_value = 0;
	var $plugin_version = '';
	var $option = '';
	
	function mosComponentManager ($component_name, $version) {
		$this->text_name = $component_name;
		$this->plugin_name = strtolower(str_replace(' ', '', $component_name));
		$this->plugin_version = $version;
		$this->option = mamboCore::get('option');
		$this->noMagicQuotes();
		$cname = 'com_'.$this->plugin_name;
		$mosConfig_absolute_path = mamboCore::get('mosConfig_absolute_path');
		if(file_exists($mosConfig_absolute_path."/components/$cname/language/".mamboCore::get('mosConfig_lang').'.php')) require_once($mosConfig_absolute_path."/components/$cname/language/".mamboCore::get('mosConfig_lang').'.php');
		else if (file_exists($mosConfig_absolute_path."/components/$cname/language/english.php")) require_once($mosConfig_absolute_path."/components/$cname/language/english.php");

	}

	function noMagicQuotes () {
		// Is magic quotes on?
		if (get_magic_quotes_gpc()) {
			// Yes? Strip the added slashes
			$_REQUEST =& $this->remove_magic_quotes($_REQUEST);
			$_GET =& $this->remove_magic_quotes($_GET);
			$_POST =& $this->remove_magic_quotes($_POST);
		}
		$this->magic_quotes_value = set_magic_quotes_runtime(0);
	}

	function &remove_magic_quotes ($array) {
		foreach ($array as $k => $v) {
			if (is_array($v)) $array[$k] = $this->remove_magic_quotes($v);
			else $array[$k] = stripslashes($v);
		}
		return $array;
	}

	function restore_magic_quotes () {
		set_magic_quotes_runtime($this->magic_quotes_value);
	}

	function checkCallable (&$object, $method) {
		if (is_callable(array(&$object, $method))) return true;
		$name = get_class($object);
		trigger_error (sprintf(T_('Component %s error: attempt to use non-existent class %s in %s'), $this->plugin_name, $method, $name));
		return false;
	}

}
/**
* Component base logic for user side
* @package Mambo
*/
class mosComponentUserManager extends mosComponentManager {

	function mosComponentUserManager ($component_name, $control_name, $alternatives, $default, $title, $version) {
		mosComponentManager::mosComponentManager($component_name, $version);
		$mainframe =& mosMainFrame::getInstance();
		$mainframe->SetPageTitle($title);
		$func = mosGetParam ($_REQUEST, $control_name, $default);
		if (isset($alternatives[$func])) $method = $alternatives[$func];
		else $method = $func;
		$classname = $this->plugin_name.'_'.$method.'_Controller';
		if (class_exists($classname)) {
			$controller =& new $classname($this);
			if (is_callable(array(&$controller,$method))) $controller->$method($func);
			else trigger_error (sprintf(T_('Component %s error: attempt to use non-existent method %s in %s'), $this->plugin_name, $method, $controller));
		}
		else trigger_error(sprintf(T_('Component %s error: attempt to use non-existent class %s'), $this->plugin_name, $classname));
		$this->restore_magic_quotes();
	}

	function newHTMLClassCheck ($name, &$controller, $total_items, $clist) {
		if (class_exists($name)) return new $name ($controller, $this->limit, $clist);
		trigger_error(sprintf(T_('Component %s error: attempt to use non-existent class %s'), $this->plugin_name, $name));
		return false;
	}

}
/**
* Component base logic for admin side
* @package Mambo
*/
class mosComponentAdminManager extends mosComponentManager {
	var $act = '';
	var $task = '';
	var $limitstart = 0;
	var $limit = 0;
	var $cfid = 0;
	var $order = 0;
	var $currid = 0;

	function mosComponentAdminManager ($component_name, $version) {
		mosComponentManager::mosComponentManager($component_name, $version);
		$this->act = mosGetParam ($_REQUEST, 'act', $this->plugin_name);
		$this->task = mosGetParam($_REQUEST, 'task', 'list');
		$mainframe = mosMainFrame::getInstance();
		$default_limit  = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 20 );
		$this->limit = intval( mosGetParam( $_REQUEST, 'limit', $default_limit ) );
		$this->limitstart = mosGetParam($_REQUEST, 'limitstart', 0 );
		$this->cfid = mosGetParam($_REQUEST, 'cfid', array(0));
		if (is_array($this->cfid)) foreach ($this->cfid as $i=>$id) $this->cfid[$i] = intval($id);
		$this->order= mosGetParam($_REQUEST, 'order', array());
		if (is_array( $this->cfid )) $this->currid=intval($this->cfid[0]);
		else $this->currid=intval($this->cfid);
		$name = $this->getAction();
		if (class_exists($name)) {
			$controller =& new $name($this);
			$task = $this->task.'Task';
			if (is_callable(array(&$controller, 'getRequestData'))) $controller->getRequestData();
			if (is_callable(array(&$controller,$task))) $controller->$task();
			else trigger_error(sprintf(T_('MOS error in %s: method %s not found in class %s'), $this->plugin_name, $task, $name));
		}
		else trigger_error(sprintf(T_('MOS error in %s: class not found %s'), $this->plugin_name, $name));
		$this->restore_magic_quotes();
	}

	function check_selection ($text) {
		if (!is_array($this->cfid) OR count( $this->cfid ) < 1) {
			echo "<script> alert('".$text."'); window.history.go(-1);</script>\n";
			exit;
		}
	}

	function getAction () {
		$actname = strtoupper(substr($this->act,0,1)).strtolower(substr($this->act,1));
		return strtolower($this->plugin_name).'Admin'.$actname;
	}

	function newHTMLClassCheck ($name, &$controller, $total_items, $clist) {
		$controller->makePageNav($this, $total_items);
		if (class_exists($name)) return new $name ($controller, $this->limit, $clist);
		trigger_error(sprintf(T_('Component %s error: attempt to use non-existent class %s'), $this->plugin_name, $name));
		return false;
	}

}
/**
* Component base class for admin side component controller logic
* @package Mambo
*/
class mosComponentAdminControllers {
	var $admin = '';
	var $user = '';
	var $pageNav = '';
	var $rootPath = '';
	var $language = '';

	function mosComponentAdminControllers ($admin) {
		$this->admin = $admin;
		$this->user = mamboCore::get('currentUser');
		$this->rootPath = mamboCore::get('mosConfig_absolute_path');
		$this->language = mamboCore::get('mosConfig_lang');
	}

	function makePageNav (&$admin, $total) {
		require_once(mamboCore::get('mosConfig_absolute_path').'/administrator/includes/pageNavigation.php');
		$this->pageNav =& new mosPageNav( $total, $admin->limitstart, $admin->limit );
	}

}

/**
* Template Table Class
*
* Provides access to the mos_templates table
* @package Mambo
*/
class mosTemplate extends mosDBTable {
	/** @var int */
	var $id=null;
	/** @var string */
	var $cur_template=null;
	/** @var int */
	var $col_main=null;

	/**
	* @param database A database connector object
	*/
	function mosTemplate( &$database ) {
		$this->mosDBTable( '#__templates', 'id', $database );
	}
}

/**
* Class mosMambot
* @package Mambo
*/
class mosMambot extends mosDBTable {
	/** @var int */
	var $id=null;
	/** @var varchar */
	var $name=null;
	/** @var varchar */
	var $element=null;
	/** @var varchar */
	var $folder=null;
	/** @var tinyint unsigned */
	var $access=null;
	/** @var int */
	var $ordering=null;
	/** @var tinyint */
	var $published=null;
	/** @var tinyint */
	var $iscore=null;
	/** @var tinyint */
	var $client_id=null;
	/** @var int unsigned */
	var $checked_out=null;
	/** @var datetime */
	var $checked_out_time=null;
	/** @var text */
	var $params=null;

	function mosMambot( &$db ) {
		$this->mosDBTable( '#__mambots', 'id', $db );
	}
}

class mosModuleHandler {
	var $_db = null;
	var $_modules = null;
	var $_unpublished = null;
	var $_isAdmin = null;

	function mosModuleHandler () {
		$this->_db =& mamboDatabase::getInstance();
	}

	function &getInstance () {
		static $instance;
		if (!is_object($instance)) $instance = new mosModuleHandler();
		return $instance;
	}

	/**
	* Cache some modules information
	* @return array
	*/
	function initModules($isAdmin=false) {
		if (!isset($this->_modules) OR $isAdmin != $this->_isAdmin) {
			$this->_isAdmin = $isAdmin;
			if ($isAdmin) {
				$query = "SELECT id, title, module, position, content, showtitle, params, published"
				. "\n FROM #__modules AS m"
				. "\n WHERE m.published = '1'"
				. "\n AND (m.client_id = 1)"
				. "\n ORDER BY m.ordering";
			}
			else {
				$my = mamboCore::get('currentUser');
				$Itemid = mamboCore::get('Itemid');
				$query = "SELECT id, title, module, position, content, showtitle, params, published"
				."\nFROM #__modules AS m, #__modules_menu AS mm"
				. "\nWHERE m.access <= '$my->gid' AND m.client_id='0'"
				. "\nAND mm.moduleid=m.id"
				. "\nAND (mm.menuid = '$Itemid' OR mm.menuid = '0')"
				. "\nORDER BY ordering";
			}
			$this->_db->setQuery( $query );
			$modules = $this->_db->loadObjectList();
			foreach ($modules as $module) {
				if ($module->published == 1) $this->_modules[$module->position][] = $module;
				else $this->_unpublished[] = $module;
			}
		}
	}
	/**
	* @param string THe template position
	*/
	function mosCountModules( $position='left', $isAdmin=false ) {
		$this->initModules($isAdmin);
		return isset($this->_modules[$position]) ? count($this->_modules[$position]) : 0;
	}

	/**
	* @param string Name of module required
	*/
	function &getByName( $name, $isAdmin=false, $unpublished=false ) {
		$this->initModules($isAdmin);
		$modules = array();
		foreach ($this->_modules as $position) {
			foreach ($position as $module) if ($module->module == $name) $modules[] = $module;
		}
		if ($unpublished AND $this->_unpublished) foreach ($this->_unpublished as $module) if ($module->module == $name) $modules[] = $module;
		return $modules;
	}

	/**
	* @param string The position
	* @param int The style.  0=normal, 1=horiz, -1=no wrapper
	*/
	function mosLoadModules( $position='left', $style=0, $isAdmin=false ) {
		$Itemid = mamboCore::get('Itemid');
		$tp = mosGetParam( $_GET, 'tp', 0 );
		if ($tp) {
		    echo '<div style="height:50px;background-color:#eee;margin:2px;padding:10px;border:1px solid #f00;color:#700;">';
			echo $position;
			echo '</div>';
			return;
		}
		$style = intval($style);
		$cache =& mosCache::getCache('com_content');
		require_once( mamboCore::get('mosConfig_absolute_path').'/includes/frontend.html.php');
		$this->initModules($isAdmin);
		if (isset($this->_modules[$position] )) $modules = $this->_modules[$position];
		else {
			$modules = array();
			$style = 0;
		}
		if ($style == 1) {
			echo "<table cellspacing=\"1\" cellpadding=\"0\" border=\"0\" width=\"100%\">\n";
			echo "<tr>\n";
		}
		$prepend = ($style == 1) ? "<td valign=\"top\">\n" : '';
		$postpend = ($style == 1) ? "</td>\n" : '';
		$count = 1;
		foreach ($modules as $module) {
			$params =& new mosParameters($module->params);
			echo $prepend;
			if ((substr("$module->module",0,4))=="mod_") $modfunc = 'module2';
			else $modfunc = 'module';
			if ($params->get('cache') == 1 AND mamboCore::get('mosConfig_caching') == 1) {
				$cache->call("modules_html::$modfunc", $module, $params, $Itemid, $style );
			}
			else modules_html::$modfunc($module, $params, $Itemid, $style, $count);
			echo $postpend;
			$count++;
		}
		if ($style == 1) echo "</tr>\n</table>\n";
	}

	/**
	* Loads admin modules via module position
	* @param string The position
	* @param int 0 = no style, 1 = tabbed
	*/
	function mosLoadAdminModules( $position='left', $style=0 ) {
		global $my, $acl;
		$this->initModules(true);
		$cache =& mosCache::getCache( 'com_content' );
		if (isset($this->_modules[$position] )) $modules = $this->_modules[$position];
		else $modules = array();

		switch ($style) {
		    case 0:
		    default:
				foreach ($modules as $module) {
					$params =& new mosParameters( $module->params );
					if ( $module->module == '' ) mosLoadCustomModule( $module, $params );
					else mosLoadAdminModule( substr( $module->module, 4 ), $params );
				}
				break;
			case 1:
			    // Tabs
				$tabs = new mosTabs(1);
				$tabs->startPane( 'modules-' . $position );
				foreach ($modules as $module) {
					$params =& new mosParameters( $module->params );
					$editAllComponents 	= $acl->acl_check( 'administration', 'edit', 'users', $my->usertype, 'components', 'all' );
//				$authoriser = new mosAuthoriser($database);
//				$editAllComponents = $authoriser->checkPermission('mosUser', $my->id, 'edit', 'editAllComponents', 0);
				// special handling for components module
					if ( $module->module != 'mod_components' || ( $module->module == 'mod_components' && $editAllComponents ) ) {
						$tabs->startTab( T_($module->title), 'module' . $module->id );
						if ( $module->module == '' ) mosLoadCustomModule( $module, $params );
						else mosLoadAdminModule( substr( $module->module, 4 ), $params );
						$tabs->endTab();
					}
				}
				$tabs->endPane();
				break;
			case 2:
			    // Div'd
				foreach ($modules as $module) {
					$params =& new mosParameters( $module->params );
					echo '<div>';
					if ( $module->module == '' ) mosLoadCustomModule( $module, $params );
					else mosLoadAdminModule( substr( $module->module, 4 ), $params );
					echo '</div>';
				}
				break;
		}
	}


}

/**
* Module database table class
* @package Mambo
*/
class mosModule extends mosDBTable {
	/** @var int Primary key */
	var $id=null;
	/** @var string */
	var $title=null;
	/** @var string */
	var $showtitle=null;
	/** @var int */
	var $content=null;
	/** @var int */
	var $ordering=null;
	/** @var string */
	var $position=null;
	/** @var boolean */
	var $checked_out=null;
	/** @var time */
	var $checked_out_time=null;
	/** @var boolean */
	var $published=null;
	/** @var string */
	var $module=null;
	/** @var int */
	var $numnews=null;
	/** @var int */
	var $access=null;
	/** @var string */
	var $params=null;
	/** @var string */
	var $iscore=null;
	/** @var string */
	var $client_id=null;

	/**
	* @param database A database connector object
	*/
	function mosModule( &$db ) {
		$this->mosDBTable( '#__modules', 'id', $db );
	}
	// overloaded check function
	function check() {
		// check for valid name
		if (trim( $this->title ) == '') {
			$this->_error = T_('Your Module must contain a title.');
			return false;
		}

		// limitation has been removed
		// check for existing title
		//$this->_db->setQuery( "SELECT id FROM #__modules"
		//. "\nWHERE title='$this->title'"
		//);
		// check for module of same name
		//$xid = intval( $this->_db->loadResult() );
		//if ($xid && $xid != intval( $this->id )) {
		//	$this->_error = "There is a module already with that name, please try again.";
		//	return false;
		//}
		return true;
	}
}

?>
