public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		
		$table 		= SLS_String::substrAfterFirstDelimiter(SLS_String::trimSlashesFromString($this->_http->getParam("__table")),"_");
		$db			= SLS_String::substrBeforeFirstDelimiter(SLS_String::trimSlashesFromString($this->_http->getParam("__table")),"_");
		$columns 	= $this->_http->getParams();
		$class		= ucfirst($db)."_".SLS_String::tableToClass($table);
		$desc		= SLS_String::trimSlashesFromString($this->_http->getParam("description"));
		
		$this->_generic->useModel($table,$db,"user");
		$object = new $class();
		if (!empty($desc))
			$object->setTableComment($desc,$table,$db);
		
		// Descriptions
		foreach($columns as $key => $value)
		{
			if (SLS_String::startsWith($key,"col_"))
			{
				$column = SLS_String::substrAfterFirstDelimiter($key,"_");
				$object->setColumnComment($column,SLS_String::trimSlashesFromString($value),$table);
			}
		}
		
		$controllers = $this->_generic->getTranslatedController("SLS_Bo","EditModel");
		$this->_generic->redirect($controllers["controller"]."/".$controllers["scontroller"]."/name/".$db."_".$table);
		
		$this->saveXML($xml);
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$xmlBo = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/bo.xml"));
		
		$param = $this->_http->getParam("name");
		$model = SLS_String::substrAfterFirstDelimiter($param,"_");
		$alias = SLS_String::substrBeforeFirstDelimiter($param,"_");
		
		if ($this->_http->getParam("type") == "")	
			$actionsTypes = array("list","add","modify","delete","clone");
		else
			$actionsTypes = array($this->_http->getParam("type"));
		foreach($actionsTypes as $actionType)
			$this->deleteActionBo($model,$actionType,$alias);
		
		# Node into bo.xml
		$boPath = "//sls_configs/entry[@type='table' and @name='".strtolower($alias."_".$model)."']";
		$boExists = $xmlBo->getTag($boPath."/@type");
		if (empty($boExists))		
			$boPath = "//sls_configs/entry/entry[@type='table' and @name='".strtolower($alias."_".$model)."']";
		$boExists = $xmlBo->getTag($boPath);
		if (!empty($boExists))
		{
			$xmlBo->deleteTags($boPath, count($xmlBo->getTags($boPath)));
			$xmlBo->saveXML($this->_generic->getPathConfig("configSls")."/bo.xml",$xmlBo->getXML());
			$xmlBo->refresh();	
		}
		# /Node into bo.xml
			
		$controllers = $this->_generic->getTranslatedController("SLS_Bo","Bo");
		$this->_generic->redirect($controllers["controller"]."/".$controllers["scontroller"]);
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$actions = array("list","add","modify","delete","clone","email");
				
		// Get the table & class name
		$table = SLS_String::substrAfterFirstDelimiter($this->_http->getParam("name"),"_");
		$db	   = SLS_String::substrBeforeFirstDelimiter($this->_http->getParam("name"),"_");
		$class = ucfirst($db)."_".SLS_String::tableToClass($table);
		$file  = ucfirst($db).".".SLS_String::tableToClass($table);
		
		$sql = SLS_Sql::getInstance();
		
		// If current db is not this one
		if ($sql->getCurrentDb() != $db)
			$sql->changeDb($db);
		
		// If the table exists, delete the bo & model
		if ($sql->tableExists($table))
		{
			foreach($actions as $action)
				if($this->boActionExist($table,$db,$action))
					$this->deleteActionBo($table,$action,$db);
			
			@unlink($this->_generic->getPathConfig("models").$file.".model.php");
			@unlink($this->_generic->getPathConfig("modelsSql").$file.".sql.php");			
		}
		$controllers = $this->_generic->getTranslatedController("SLS_Bo","Models");
		$this->_generic->redirect($controllers['controller']."/".$controllers['scontroller']);
	}
	/**
	 * Constructor
	 *
	 * @access public
	 * @since 1.0
	 */
	public function __construct()
	{
		// Merge all params
		$this->_params = array_merge_recursive($_POST,$_GET,$this->fixFilesArray($_FILES));
		// Strip extension if exists		
		if (SLS_String::endsWith($this->_params['smode'], SLS_Generic::getInstance()->getSiteConfig('defaultExtension')))		
            $this->_params['smode'] = SLS_String::substrBeforeLastDelimiter($this->_params['smode'], '.'.SLS_Generic::getInstance()->getSiteConfig('defaultExtension'));
        // Command line
      	if (PHP_SAPI === 'cli')
      	{
      		global $argv;
      		if (is_array($argv))
      		{	
      			$args = array_slice($argv, 1);
      			$controllerPosition = 0;
      			for($i=0 ; $i<count($args) ; $i++)
      			{
      				$argKey = SLS_String::substrBeforeFirstDelimiter($args[$i],"=");
      				if (!empty($argKey) && strtolower($argKey) == "mode")
      				{
      					$this->_params['mode'] = SLS_String::substrAfterFirstDelimiter($args[$i],"=");
      					$controllerPosition = $i;
      				}
      				if (!empty($argKey) && strtolower($argKey) == "smode")
      				{
      					$args[$i] = SLS_String::substrAfterFirstDelimiter($args[$i],"=");
      				}
      			}
      			unset($args[$controllerPosition]);
      			$this->_params['smode'] = str_replace("=","/",implode("/",$args));
      		}
      	}
        // Get smode
		$explode = explode("/", $this->_params['smode']);
		$this->_params['smode'] = array_shift($explode);		
		// Transform url in classic queryString '?param1=value1&param2=value2...'
		$queryString = "";
		$params = array_chunk($explode, 2);		
		for($i=0 ; $i<$count=count($params) ; $i++)		
			if (count($params[$i]) == 2)
				$queryString .= (($i == 0) ? '' : '&').$params[$i][0].'='.(($params[$i][1] != "|sls_empty|") ? $params[$i][1] : "");		
		// Get all params/values
		parse_str($queryString,$params);		
		if (!empty($params))
		{
			foreach($params as $key => $value)
				$this->_params[$key] = $value;
		}
	}
	public function action()
	{
		$user = $this->hasAuthorative();
				
		// Objects		
		$xmlFk = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml"));
		$xmlBearer = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/bearers.xml"));
						
		// Get the table & class name
		$table = SLS_String::substrAfterFirstDelimiter($this->_http->getParam("name"),"_");
		$db	   = SLS_String::substrBeforeFirstDelimiter($this->_http->getParam("name"),"_");
		$class = ucfirst($db)."_".SLS_String::tableToClass($table);
		
		$result = array_shift($xmlBearer->getTagsAttributes("//sls_configs/entry[@tableBearer='".$class."']",array("table1")));
		if (!empty($result))
			$xmlBearer->saveXML($this->_generic->getPathConfig("configSls")."/bearers.xml",$xmlBearer->deleteTags("//sls_configs/entry[@tableBearer='".$class."']"));
		
		$this->_generic->forward("SLS_Bo","EditModel",array(array("key"=>"name","value"=>$this->_http->getParam("name"))));
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		
		$redirect		= true;		
		$param	 		= $this->_http->getParam("name");		
		$model			= SLS_String::substrAfterFirstDelimiter($param,"_");
		$alias			= SLS_String::substrBeforeFirstDelimiter($param,"_");				
		$checkbox		= $this->_http->getParam("redirect");
		
		if (empty($checkbox))
			$redirect = false;
		
		$controllersXML = $this->_generic->getControllersXML();
		$controller 	= array_shift($controllersXML->getTags("//controllers/controller[@isBo='true']/@name"));
		
		$this->createActionBoAdd($controller,$model,$alias,$redirect);
		
		$controllers = $this->_generic->getTranslatedController("SLS_Bo","EditBo");
		$this->_generic->redirect($controllers["controller"]."/".$controllers["scontroller"]."/name/".$param.".sls");
	}
示例#7
0
	public function action()
	{
		$user = $this->hasAuthorative();
		
		$controllersXML = $this->_generic->getControllersXML();
		$controller = array_shift($controllersXML->getTags("//controllers/controller[@isBo='true']/@name"));
		
		if (!empty($controller))
		{
			$param = $this->_http->getParam("name");
			$model = SLS_String::substrAfterFirstDelimiter($param,"_");
			$alias = SLS_String::substrBeforeFirstDelimiter($param,"_");			
			$type = ucfirst($this->_http->getParam("type"));
			
			$actionTypes = array("List","Add","Modify","Delete","Clone","Email");
			
			if (in_array($type,$actionTypes))			
				$this->{createActionBo.$type}($controller,$model,$alias);			
		}
		
		$controllers = $this->_generic->getTranslatedController("SLS_Bo","Bo");
		$this->_generic->redirect($controllers["controller"]."/".$controllers["scontroller"]);
	}
	public function getEnvironments()
	{
		$environments = array();
		$filesToCheck = array("site","db","project","mail");
		if ($handle = opendir($this->_generic->getPathConfig("configSecure")))
		{
			while (false !== ($entry = readdir($handle)))
			{
				foreach($filesToCheck as $file)
				{
			        if (SLS_String::startsWith($entry,$file."_") && SLS_String::endsWith($entry,".xml"))
			        {
			        	$environment = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($entry,$file."_"),".xml");
			        	if (!in_array($environment,$environments))
			        		$environments[] = $environment;
			        }
				}
			}
		}
		return $environments;
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$langs = $this->_generic->getObjectLang()->getSiteLangs();
		$errors = array();
		$siteXML = $this->_generic->getSiteXML();		
		$aliasesSelected = array();
		$componentsSelected = array();
		
		$plugin = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configPlugins")."/plugins.xml"));
		$pluginMobile = $plugin->getTag("//plugins/plugin[@code='mobile']");
		$pluginMobile = (!empty($pluginMobile)) ? true : false;
		
		$controllersXML = $this->_generic->getControllersXML();
		$metasXML = $this->_generic->getCoreXML('metas');
		$controller = $this->_http->getParam('Controller');
		$action = $this->_http->getParam('Action');
				
		$actionExist = $controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']");
		$actionId = array_shift($controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']/@id"));
		$protocol = $this->_generic->getActionProtocol($actionId);
		if (count($actionExist) == 1)
		{
			$aliasesChecked = array_shift($controllersXML->getTagsAttributes("//controllers/controller/scontrollers/scontroller[@id='".$actionId."']",array("domains")));
			if (!empty($aliasesChecked))
			{				
				$alias = explode(",",$aliasesChecked["attributes"][0]["value"]);
				foreach($alias as $cur_alias)
					array_push($aliasesSelected,$cur_alias);
			}
			$componentsChecked = array_shift($controllersXML->getTagsAttributes("//controllers/controller/scontrollers/scontroller[@id='".$actionId."']",array("components")));
			if (!empty($componentsChecked))
			{				
				$component = explode(",",$componentsChecked["attributes"][0]["value"]);
				foreach($component as $cur_component)
					array_push($componentsSelected,$cur_component);
			}
			
			$reload = $this->_http->getParam("reload");
			if ($reload == 'true')
			{
				$oldAction  		= SLS_String::trimSlashesFromString($this->_http->getParam("genericName"));
				$newAction 			= SLS_String::stringToUrl(ucwords(SLS_String::trimSlashesFromString($this->_http->getParam("actionName"))), "", false);
				$needDynamic 		= SLS_String::trimSlashesFromString($this->_http->getParam("dynamic"));
				$needOffline 		= SLS_String::trimSlashesFromString($this->_http->getParam("offline"));
				$needDefault 		= SLS_String::trimSlashesFromString($this->_http->getParam("default"));
				$searchEngine 		= SLS_String::trimSlashesFromString($this->_http->getParam("indexes"));
				$postProtocol		= SLS_String::trimSlashesFromString($this->_http->getParam("protocol"));
				$tpl 				= SLS_String::trimSlashesFromString($this->_http->getParam('template'));
				$aliases			= SLS_String::trimSlashesFromString($this->_http->getParam('domains'));
				$components			= SLS_String::trimSlashesFromString($this->_http->getParam('components'));
				$cache_visibility 	= SLS_String::trimSlashesFromString($this->_http->getParam('cache_visibility'));
				$cache_scope 		= SLS_String::trimSlashesFromString($this->_http->getParam('cache_scope'));
				$cache_expiration 	= SLS_String::trimSlashesFromString($this->_http->getParam('cache_expiration'));
				$cache_responsive 	= SLS_String::trimSlashesFromString($this->_http->getParam('cache_responsive'));
				$toCache			 = (in_array($cache_visibility,array("public","private"))) ? true : false;
				
				if ($controller == "Home" && $action == "Index")
				{
					$needDefault = "true";
					$newAction = $oldAction;
				}
				
				// If responsive wanted
				if ($cache_responsive == "true" && !$pluginMobile)
				{
					// Force Mobile plugin download
					file_get_contents($this->_generic->getFullPath("SLS_Bo",
																  "SearchPlugin",
																  array("Action" => "Download",
																  		"Server" => "4",
																  		"Plugin" => "20",
																  		"token"	 => sha1(substr($this->_generic->getSiteConfig("privateKey"), 0, 3).substr($this->_generic->getSiteConfig("privateKey"), strlen($this->_generic->getSiteConfig("privateKey"))-3))),
																  true));
				}
				
				$postActionsLang	= array();
				$postTitlesLang		= array();
				$postDescriptionsLang = array();
				$postKeywordsLang	= array();
				
				// Save Form informations
				$xml->startTag("form");
					$xml->addFullTag("actionName", $newAction, true);
					foreach ($langs as $lang)
					{
						$postLang = trim(SLS_String::stringToUrl(SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-action")), "", false));
						$postOldLang = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-oldAction"));
						if ($postLang != $oldAction)
						{
							$translationExist = $controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller[@name != '".$oldAction."']/scontrollerLangs[scontrollerLang = '".$postLang."']");
						
							if (empty($postLang)) 
								array_push($errors, "You need to fill the ".$lang." url translations");
							elseif(count($translationExist) != 0)
								array_push($errors, "You URL translation in ".$lang." is already in use on another action in the same controller");
							else
								$postActionsLang[$lang] =  $postLang;
						}
						
						// Get Titles	
						$postTitlesLang[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-title"));
						$postDescriptionsLang[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-description"));
						$postKeywordsLang[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-keywords"));
						$xml->addFullTag($lang."-action", $postLang, true);
						$xml->addFullTag($lang."-title", $postTitlesLang[$lang], true);
						$xml->addFullTag($lang."-description", $postDescriptionsLang[$lang], true);
						$xml->addFullTag($lang."-keywords", $postKeywordsLang[$lang], true);
					}
				$xml->endTag("form");
				
				if (empty($postProtocol) || ($postProtocol != 'http' && $postProtocol != 'https'))
						array_push($errors, "Protocol must be http or https");
					else 
						$protocol = $postProtocol;
								
				if (!empty($aliases) && is_array($aliases))
				{
					$aliasesSelected = array();
					foreach($aliases as $alias)
						array_push($aliasesSelected,$alias);
				}
				else
				{
					$aliasesSelected = array();
					$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']", array('domains' => ''));
				}
				
				if ($toCache && (!is_numeric($cache_expiration) || $cache_expiration < 0))
					array_push($errors, "Your expiration cache must be a positive time or 0");
				if ($toCache && (!in_array($cache_scope,array("full","partial"))))
					array_push($errors, "Your must describe your cache scope");
				
				if ($toCache && is_numeric($cache_expiration) && $cache_expiration >= 0 && in_array($cache_scope,array("full","partial")))
					$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']", array('cache' => $cache_visibility.'|'.$cache_scope.'|'.(($cache_responsive == 'true') ? 'responsive' : 'no_responsive').'|'.$cache_expiration));
				if (!$toCache)
					$controllersXML->deleteTagAttribute("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']","cache");
				
				if (!empty($components) && is_array($components))
				{
					$componentsSelected = array();
					foreach($components as $component)
						array_push($componentsSelected,$component);
				}
				else
				{
					$componentsSelected = array();
					$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']", array('components' => ''));
				}
				
				if ((($controller != 'Home' && $controller != 'Default') || (($controller == 'Home' && $action != 'Index') || ($controller == 'Default' && ($action != 'UrlError' && $action != 'BadRequestError' && $action != 'AuthorizationError' && $action != 'ForbiddenError' && $action != 'InternalServerError' && $action != 'TemporaryRedirectError' && $action != 'MaintenanceError')))) && ($oldAction != $newAction)) 
				{
					$newNameExist = $controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$newAction."']");
					if (count($newNameExist) != 0)
						array_push($errors, "The generic action name is already in use in this controller");						
				}
				else 
					$newAction = $oldAction;
				
				if (empty($newAction))
					array_push($errors, "Action name can't be empty.");
					
				if (!empty($aliases))									
					$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']", array('domains' => implode(",",$aliasesSelected)));					
					
				if (!empty($components))									
					$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']", array('components' => implode(",",$componentsSelected)));
								
				$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']", array('disable' => (empty($needOffline)) ? '0' : '1'));					
									
				if ($tpl == -1)
					$controllersXML->deleteTagAttribute("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']", "tpl");
				else
					$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']", array('tpl' => $tpl));
				file_put_contents($this->_generic->getPathConfig('configSecure')."controllers.xml", $controllersXML->getXML());

				$dynamic = (($controller != 'Home' && $controller != 'Default') || (($controller == 'Home' && $action != 'Index') || ($controller == 'Default' && ($action != 'UrlError' && $action != 'BadRequestError' && $action != 'AuthorizationError' && $action != 'ForbiddenError' && $action != 'InternalServerError' && $action != 'TemporaryRedirectError' && $action != 'MaintenanceError')))) ? ($needDynamic == 'on') ? "1" : "0" : array_shift($controllersXML->getTags("//controllers/controller[@name='".$controller."' and side='user']/scontrollers/scontroller[@name='".$oldAction."']/@needParam"));
				// If no errors
				if (empty($errors))
				{
					// If default, reset other in current controller
					if (!empty($needDefault))
					{
						$actions = $controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller/@id");
						foreach($actions as $curActionId)
							$controllersXML->setTagAttributes("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller[@id='".$curActionId."']", array('default' => '0'));
					}
					
					$controllersXML->setTagAttributes("//controllers/controller/scontrollers/scontroller[@id='".$actionId."']", array("name"=>$newAction,"needParam"=>$dynamic,'protocol'=>$protocol,"default"=>(empty($needDefault) ? '0' : '1')));
					
					foreach ($langs as $lang)
					{
						if (array_key_exists($lang, $postActionsLang))
							$controllersXML->setTag("//controllers/controller/scontrollers/scontroller[@id='".$actionId."']/scontrollerLangs/scontrollerLang[@lang='".$lang."']", $postActionsLang[$lang], true);
						else 
							$controllersXML->setTag("//controllers/controller/scontrollers/scontroller[@id='".$actionId."']/scontrollerLangs/scontrollerLang[@lang='".$lang."']", SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-oldAction")), true);
					}
					
					// If generic name is not the same, we modify all files
					if ($oldAction != $newAction)
					{
						// Controller
						$contentController = file_get_contents($this->_generic->getPathConfig('actionsControllers').$controller."/".$oldAction.".controller.php");
						$contentController = str_replace(array(0=>" ".$controller.$oldAction." ", 1=>" ".$oldAction." "), array(0=>" ".$controller.$newAction." ", 1=>" ".$newAction." "), $contentController);
						file_put_contents($this->_generic->getPathConfig('actionsControllers').$controller."/".$newAction.".controller.php", $contentController);
						unlink($this->_generic->getPathConfig('actionsControllers').$controller."/".$oldAction.".controller.php");
						
						//Langs
						foreach ($langs as $lang)
						{
							$contentLang = file_get_contents($this->_generic->getPathConfig('actionLangs').$controller."/".$oldAction.".".$lang.".lang.php");
							$contentLang = str_replace(array(0=>" ".$controller.$oldAction." ", 1=>" ".$oldAction." "), array(0=>" ".$controller.$newAction." ", 1=>" ".$newAction." "), $contentLang);
							file_put_contents($this->_generic->getPathConfig('actionLangs').$controller."/".$newAction.".".$lang.".lang.php", $contentLang);
							unlink($this->_generic->getPathConfig('actionLangs').$controller."/".$oldAction.".".$lang.".lang.php");
						}
						
						// Views
						// Body
						$contentBody = file_get_contents($this->_generic->getPathConfig('viewsBody').$controller."/".$oldAction.".xsl");
						$contentBody = str_replace(array(0=>"name=\"".$oldAction."\">", 1=>$oldAction.".xsl"), array(0=>"name=\"".$newAction."\">", 1=>$newAction.".xsl"), $contentBody);
						file_put_contents($this->_generic->getPathConfig('viewsBody').$controller."/".$newAction.".xsl", $contentBody);
						unlink($this->_generic->getPathConfig('viewsBody').$controller."/".$oldAction.".xsl");
						
						// Headers
						$contentHeader = file_get_contents($this->_generic->getPathConfig('viewsHeaders').$controller."/".$oldAction.".xsl");
						$contentHeader = str_replace(array(0=>"name=\"Header".$oldAction."\">"), array(0=>"name=\"Header".$newAction."\">"), $contentHeader);
						file_put_contents($this->_generic->getPathConfig('viewsHeaders').$controller."/".$newAction.".xsl", $contentHeader);
						unlink($this->_generic->getPathConfig('viewsHeaders').$controller."/".$oldAction.".xsl");
					}
					
					// We now update the XML
					
					foreach ($langs as $lang)
					{
						// Metas
						$metasXML->setTag("//sls_configs/action[@id='".$actionId."']/title[@lang='".$lang."']", $postTitlesLang[$lang], true);
						$metasXML->setTag("//sls_configs/action[@id='".$actionId."']/description[@lang='".$lang."']", $postDescriptionsLang[$lang], true);
						$metasXML->setTag("//sls_configs/action[@id='".$actionId."']/keywords[@lang='".$lang."']", $postKeywordsLang[$lang], true);
					}
					if (!SLS_String::contains($searchEngine,", "))
						$searchEngine = str_replace(",",", ",$searchEngine);
					if ($searchEngine != "index, follow" && $searchEngine != "noindex, follow" && $searchEngine != "noindex, nofollow" && $searchEngine != "index, nofollow")
						$searchEngine = "index, follow";
					$metasXML->setTag("//sls_configs/action[@id='".$actionId."']/robots", $searchEngine, true);
							
					file_put_contents($this->_generic->getPathConfig("configSecure")."controllers.xml", $controllersXML->getXML());
					file_put_contents($this->_generic->getPathConfig("configSls")."metas.xml", $metasXML->getXML());					
				}
				
				if (count($errors) != 0)
				{
					$xml->startTag("errors");
					foreach ($errors as $error)
						$xml->addFullTag("error", $error, true);
					$xml->endTag("errors");
				}
				
				$xml->startTag("cache");					
					$xml->addFullTag("cache_visibility", $cache_visibility,true);
					$xml->addFullTag("cache_scope", $cache_scope,true);
					$xml->addFullTag("cache_expiration", $cache_expiration,true);
					$xml->addFullTag("cache_responsive", $cache_responsive,true);
				$xml->endTag("cache");
			}
			else
			{
				$actionCache = $this->_cache->getAction($actionId);				
				$xml->startTag("cache");					
					$xml->addFullTag("cache_visibility", (is_array($actionCache)) ? $actionCache[0] : "",true);
					$xml->addFullTag("cache_scope", (is_array($actionCache)) ? $actionCache[1] : "",true);
					$xml->addFullTag("cache_expiration", (is_array($actionCache)) ? $actionCache[3] : "",true);
					$xml->addFullTag("cache_responsive", (is_array($actionCache)) ? (($actionCache[2]=="responsive") ? "true" : "") : "",true);
				$xml->endTag("cache");
			}
			$tpl = $controllersXML->getTag("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']/@tpl");
			if (empty($tpl))
				$tpl = $controllersXML->getTag("//controllers/controller[@name='".$controller."' and @side='user']/@tpl");
			
			$controllersXML = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSecure")."controllers.xml"));
			
			$xml->startTag("action");
				$xml->addFullTag("name", $action, true);
				$xml->addFullTag("dynamic", (array_shift($controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']/@needParam")) == '1') ? 'true' : 'false', true);
				$xml->addFullTag("offline", (array_shift($controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']/@disable")) == '1') ? 'true' : 'false', true);
				$xml->addFullTag("default", (array_shift($controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']/@default")) == '1') ? 'true' : 'false', true);
				$xml->addFullTag("indexes", array_shift($metasXML->getTags("//sls_configs/action[@id='".$actionId."']/robots")), true);
				$xml->addFullTag("canBeModified", (($controller != 'Home' && $controller != 'Default') || (($controller == 'Home' && $action != 'Index') || ($controller == 'Default' && ($action != 'UrlError' && $action != 'BadRequestError' && $action != 'AuthorizationError' && $action != 'ForbiddenError' && $action != 'InternalServerError' && $action != 'TemporaryRedirectError' && $action != 'MaintenanceError')))) ? 'true' : 'false', true);
				$xml->startTag("translations");
				foreach ($langs as $lang)
				{
					$xml->startTag("translation");
					$xml->addFullTag("lang", $lang, true);
					$xml->addFullTag("name", array_shift($controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']/scontrollerLangs/scontrollerLang[@lang='".$lang."']")) ,true);
					$xml->addFullTag("title", array_shift($metasXML->getTags("//sls_configs/action[@id='".$actionId."']/title[@lang='".$lang."']")),true);
					$xml->addFullTag("description", array_shift($metasXML->getTags("//sls_configs/action[@id='".$actionId."']/description[@lang='".$lang."']")),true);
					$xml->addFullTag("keywords", array_shift($metasXML->getTags("//sls_configs/action[@id='".$actionId."']/keywords[@lang='".$lang."']")),true);
					$xml->endTag("translation");
				}
				$xml->endTag("translations");
			$xml->endTag("action");
			$xml->startTag('controller');
				$xml->addFullTag("name", $controller, true);
				$xml->startTag('translations');
				foreach ($langs as $lang)
				{
					$xml->startTag('translation');
						$xml->addFullTag("lang", $lang, true);	
						$xml->addFullTag("name", $controllersXML->getTag("//controllers/controller[@name='".$controller."' and @side='user']/controllerLangs/controllerLang[@lang='".$lang."']"), true);	
					$xml->endTag('translation');
				}
				$xml->endTag('translations');
			$xml->endTag('controller');
			
			// Build all tpls
			$tpls = $this->getAppTpls();
			$xml->startTag("tpls");
			foreach($tpls as $template)
				$xml->addFullTag("tpl",$template,true);
			$xml->endTag("tpls");
			
			$xml->addFullTag('request', 'modifyAction', true);			
			
			$aliases = $siteXML->getTagsAttributes("//configs/domainName/domain",array("alias"));
			$xml->startTag("aliases");
			for($i=0 ; $i<$count=count($aliases) ; $i++)
			{				
				$xml->startTag("alias");
					$xml->addFullTag("name",$aliases[$i]["attributes"][0]["value"],true);
					$xml->addFullTag("selected",(in_array($aliases[$i]["attributes"][0]["value"],$aliasesSelected)) ? "true" : "false",true);
				$xml->endTag("alias");
			}
			$xml->endTag("aliases");
			
			$components = $this->_generic->recursiveReadDir($this->_generic->getPathConfig("componentsControllers"), array(), array(0=>"php"));
			$xml->startTag("components");				
			foreach ($components as $component)
			{
				$xml->startTag("component");
					$xml->addFullTag("name", SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($component, "/"), ".controller.php"),true);
					$xml->addFullTag("selected",(in_array(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($component, "/"), ".controller.php"),$componentsSelected)) ? "true" : "false",true);
				$xml->endTag("component");
			}
			$xml->endTag("components");
		}
		else 
		{
			$this->_generic->dispatch('SLS_Bo', 'Controllers');
		}
		$xml->addFullTag('protocol', $protocol, true);
		$xml->addFullTag('template', $tpl, true);
		$this->saveXML($xml);
	}
	public function action()
	{
		$user 	= $this->hasAuthorative();
		$xml 	= $this->getXML();
		$xml	= $this->makeMenu($xml);
		$siteXML = $this->_generic->getSiteXML();
		
		$googleSettings = array();
		
		if ($this->_http->getParam("reload") == "true")
		{
			$googleSettings = $this->_http->getParam("ga");
			
			$siteXML->setTag("//configs/google/setting[@name='ua']",trim($googleSettings["ua"]));
			$siteXML->setTag("//configs/google/setting[@name='apiKey']",trim($googleSettings["apiKey"]));
			$siteXML->setTag("//configs/google/setting[@name='clientId']",trim($googleSettings["clientId"]));
			$siteXML->setTag("//configs/google/setting[@name='accountId']",trim($googleSettings["accountId"]));
			$siteXML->saveXML($this->_generic->getPathConfig("configSecure")."site.xml");
			$siteXML->refresh();
			
			if (!empty($googleSettings["ua"]))
			{
				$googleSettings["ua"] = (SLS_String::startsWith(trim(strtolower($googleSettings["ua"])),"ua-")) ? $googleSettings["ua"] : "UA-".$googleSettings["ua"];
				$templates = scandir($this->_generic->getPathConfig("viewsTemplates"));
				foreach($templates as $template)
				{
					if (!SLS_String::startsWith($template,"."))
					{
						$templateContent = file_get_contents($this->_generic->getPathConfig("viewsTemplates").$template);
						
						if (SLS_String::contains($templateContent,"<!-- GA loading -->") && SLS_String::contains($templateContent,"_gaq.push(['_setAccount'"))
						{
							$oldUa = trim(str_replace("'","",SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($templateContent,"_gaq.push(['_setAccount',"),"]")));
							if ($oldUa != $googleSettings["ua"])
							{
								$templateContent = str_replace("_gaq.push(['_setAccount', '".$oldUa."']);","_gaq.push(['_setAccount', '".$googleSettings["ua"]."']);",$templateContent);
								file_put_contents($this->_generic->getPathConfig("viewsTemplates").$template,$templateContent);
							}
						}
						else
						{
							$newContent = "";
							$templateLines = explode("\n",$templateContent);
							
							for($i=0 ; $i<$count=count($templateLines) ; $i++)
							{
								$line = $templateLines[$i];
								
								if (SLS_String::contains($line,"</body>"))
								{
									$newContent .= t(4)."<!-- GA loading -->"."\n".
													t(4)."<xsl:if test=\"//Statics/Sls/Configs/site/isProd = '1'\">"."\n".
														t(5)."<script type=\"text/javascript\">"."\n".
															t(6)."var _gaq = _gaq || [];"."\n".
															t(6)."_gaq.push(['_setAccount', '".$googleSettings["ua"]."']);"."\n".
															t(6)."_gaq.push(['_trackPageview']);"."\n".
															t(6)."(function() {"."\n".
																t(7)."var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;"."\n".
																t(7)."ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';"."\n".
																t(7)."var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);"."\n".
															t(6)."})();"."\n".
														t(5)."</script>"."\n".
													t(4)."</xsl:if>"."\n".
													t(4)."<!-- /GA loading -->"."\n\n";
								}
								
								$newContent .= $line."\n";
							}
							
							file_put_contents($this->_generic->getPathConfig("viewsTemplates").$template,$newContent);
						}
					}
				}
			}
			
			$xml->addFullTag("success","Your settings have been saved.",true);
		}
		else
		{
			$googleSettings["ua"] = $siteXML->getTag("//configs/google/setting[@name='ua']");
			$googleSettings["apiKey"] = $siteXML->getTag("//configs/google/setting[@name='apiKey']");
			$googleSettings["clientId"] = $siteXML->getTag("//configs/google/setting[@name='clientId']");
			$googleSettings["accountId"] = $siteXML->getTag("//configs/google/setting[@name='accountId']");
		}
		
		$xml->startTag("google");
		foreach($googleSettings as $key => $value)
			$xml->addFullTag($key,$value,true);
		$xml->endTag("google");
		
		$this->saveXML($xml);		
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$langs = $this->_generic->getObjectLang()->getSiteLangs();
		$listing = true;
		$errors = array();
		
		// Get user controllers listing
		$controllersXML = $this->_generic->getControllersXML();
		$controllers = $controllersXML->getTags("//controllers/controller[@side='user']/@id");		
		$xml->startTag("controllers");
		foreach($controllers as $controller)
		{
			$controller_id = $controller;
			$controller_tpl = $controllersXML->getTag("//controllers/controller[@id='".$controller_id."']/@tpl");
			$controller = $controllersXML->getTag("//controllers/controller[@id='".$controller_id."']/@name");
			$xml->startTag("controller");
			$xml->addFullTag("name",$controller,"true");
			$xml->addFullTag("id",$controller_id,"true");
			$xml->addFullTag("tpl",(!empty($controller_tpl)) ? $controller_tpl : $controller_tpl = "default","true");
			$xml->addFullTag("canBeDeleted",($controller == 'Home' || $controller == 'Default') ? 'false' : 'true', true);
			$scontrollers = $controllersXML->getTags("//controllers/controller[@name='".$controller."']/scontrollers/scontroller/@id");			
			$xml->startTag("scontrollers");
			foreach($scontrollers as $scontroller)
			{
				$scontroller_id = $scontroller;
				$scontroller_tpl = $controllersXML->getTag("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@id='".$scontroller_id."']/@tpl");
				$scontroller_cache = $controllersXML->getTag("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@id='".$scontroller_id."']/@cache");
				if (!SLS_String::contains($scontroller_cache,"|"))
					$scontroller_cache = "false";
				 
				$scontroller = $controllersXML->getTag("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@id='".$scontroller_id."']/@name");				
				$xml->startTag("scontroller");
					$xml->addFullTag("name",$scontroller,true);
					$xml->addFullTag("id",$scontroller_id,true);
					$xml->addFullTag("cache",$scontroller_cache,true);
					$xml->addFullTag("tpl",(!empty($scontroller_tpl)) ? $scontroller_tpl : $controller_tpl,true);
					if (($controller == 'Home' && ($scontroller == 'Index')) || ($controller == 'Default' && ($scontroller == 'UrlError' || $scontroller == 'BadRequestError' || $scontroller == 'TemporaryRedirectError' || $scontroller == 'MaintenanceError' || $scontroller == 'AuthorizationError' || $scontroller == 'ForbiddenError' || $scontroller == 'InternalServerError')))
						$xml->addFullTag("canBeDeleted",'false',true);
					else 
						$xml->addFullTag("canBeDeleted",'true',true);
				$xml->endTag("scontroller");
			}
			$xml->endTag("scontrollers");	
			$xml->endTag("controller");
		}
		$xml->endTag("controllers");
		$xml->startTag("statics");
		$statics = $this->_generic->recursiveReadDir($this->_generic->getPathConfig("staticsControllers"), array(), array(0=>"php"));
		foreach ($statics as $static)
		{			
			$static = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($static, "/"), ".controller.php");
			$cache = $this->_cache->getObject(strtolower($static),"statics","visibility")."|".$this->_cache->getObject(strtolower($static),"statics","scope")."|".$this->_cache->getObject(strtolower($static),"statics","responsive")."|".$this->_cache->getObject(strtolower($static),"statics","expire");
			if ($cache == "|||")
				$cache = "false";
			$xml->startTag("static");
				$xml->addFullTag("id", strtolower($static),true);
				$xml->addFullTag("name", $static,true);
				$xml->addFullTag("cache",$cache,true);
			$xml->endTag("static");
		}
		$xml->endTag("statics");
		$xml->startTag("components");
		$components = $this->_generic->recursiveReadDir($this->_generic->getPathConfig("componentsControllers"), array(), array(0=>"php"));
		foreach ($components as $component)
		{
			$component = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($component, "/"), ".controller.php");
			$cache = $this->_cache->getObject(strtolower($component),"components","visibility")."|".$this->_cache->getObject(strtolower($component),"components","scope")."|".$this->_cache->getObject(strtolower($static),"statics","responsive")."|".$this->_cache->getObject(strtolower($component),"components","expire");
			if ($cache == "|||")
				$cache = "false";
			$xml->startTag("component");
				$xml->addFullTag("id", strtolower($component),true);
				$xml->addFullTag("name", $component,true);
				$xml->addFullTag("cache",$cache,true);
			$xml->endTag("component");
		}
		$xml->endTag("components");
		$xml->addFullTag('request', 'listing', true);
		$this->registerLink('ADDACTION', 'SLS_Bo', 'AddAction', false);
		$this->registerLink('ADDSTATICCONTROLLER', 'SLS_Bo', 'AddStaticController', false);
		$this->registerLink('EDITSTATICCONTROLLER', 'SLS_Bo', 'EditStaticController', false);
		$this->registerLink('DELSTATICCONTROLLER', 'SLS_Bo', 'DeleteStaticController', false);
		$this->registerLink('ADDCOMPONENTCONTROLLER', 'SLS_Bo', 'AddComponentController', false);
		$this->registerLink('EDITCOMPONENTCONTROLLER', 'SLS_Bo', 'EditComponentController', false);
		$this->registerLink('DELCOMPONENTCONTROLLER', 'SLS_Bo', 'DeleteComponentController', false);
		$this->registerLink('EDITACTION', 'SLS_Bo', 'EditAction', false);
		$this->registerLink('DELACTION', 'SLS_Bo', 'DeleteAction', false);
		$this->registerLink('ADDCONTROLLER', 'SLS_Bo', 'AddController', false);
		$this->registerLink('EDITCONTROLLER', 'SLS_Bo', 'EditController', false);
		$this->registerLink('FLUSHCACHE', 'SLS_Bo', 'FlushCache', false);
		$this->registerLink('DELCONTROLLER', 'SLS_Bo', 'DeleteController', false);
		$this->saveXML($xml);		
	}
	/**
	 * Action Home
	 *
	 */
	public function action() 
	{
		$this->secureURL();
		$this->_generic->registerLink('International', 'SLS_Init', 'International');
		$errors = array();
		$giveDataStep1 = false;
		$xml = $this->getXML();
		$step = 0;
		$langs = array();
		$handle = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."international.xml"));
		$xpathLangs = $handle->getTags("//sls_configs/sls_country/sls_country_langs/sls_country_lang[@iso != '']");
		foreach ($xpathLangs as $lang)
			if (!in_array(trim($lang), $langs))
				array_push($langs, trim($lang));
		array_multisort($langs, SORT_STRING, SORT_ASC);
		$xml->startTag("langs");
		foreach ($langs as $lang)
			$xml->addFullTag("lang", $lang, true);
		$xml->endTag("langs");
				
		// If reload
		if ($this->_http->getParam('reload_international_step1') == "true")
		{
			// If one lang at least
			$listLangs = SLS_String::trimSlashesFromString($this->_http->getParam("international_langs"));			
			if (empty($listLangs))
				array_push($errors,"You must choose at least one language");
			else
			{
				$xmlIsos = "";
				
				foreach($listLangs as $listLang)
				{
					$iso = array_shift($handle->getTags("//sls_configs/sls_country/sls_country_langs/sls_country_lang[node()='".$listLang."']/@iso"));
					$xmlIsos .= '<name isSecure="false" js="false" active="true"><![CDATA['.$iso.']]></name>';
					if (is_file($this->_generic->getPathConfig("installDeployement")."Langs/Generics/generic.".$iso.".lang.php"))
						copy($this->_generic->getPathConfig("installDeployement")."Langs/Generics/generic.".$iso.".lang.php", $this->_generic->getPathConfig("coreGenericLangs")."generic.".$iso.".lang.php");
				}
				
			}
			if (empty($errors))
			{
				$step = 1;
				$coreXml = $this->_generic->getSiteXML();
				$coreXml->setTag('langs',$xmlIsos,false);
				file_put_contents($this->_generic->getPathConfig("configSecure")."site.xml", $coreXml->getXML());
				$giveDataStep1 = true;
			}
			else
			{
				$step = 0;
				$xml->startTag("errors");
				foreach ($errors as $error)
					$xml->addFullTag("error", $error, true);
				$xml->endTag("errors");
			}
		}
		// Set controllers.xml
		else if ($this->_http->getParam('reload_international_step2') == "true")
		{
			$langs = $this->_generic->getSiteXML()->getTags("//configs/langs/name");
			$listLangs = explode("-", SLS_String::trimSlashesFromString($this->_http->getParam("international_languages")));
			$params = $this->_http->getParams('post');
			
			$userValues = array();
			foreach ($langs as $lang)
				$userValues[$lang] = array();
			
			foreach ($params as $key=>$param)
				if (array_key_exists(SLS_String::substrBeforeFirstDelimiter($key, '_'), $userValues))
					$userValues[SLS_String::substrBeforeFirstDelimiter($key, '_')][SLS_String::substrAfterFirstDelimiter($key, '_')] = SLS_String::trimSlashesFromString($param);
			
			// Check errors
			$errors = array();
			$xml->startTag("InternationalMemory");
			$xml->addFullTag("default", SLS_String::trimSlashesFromString($this->_http->getParam("default_lang")), true);
			foreach ($userValues as $key=>$values) 
			{
				$mods[$key] = array();
				$smods[$key]['home'] = array();
				$smods[$key]['error'] = array();
				
				foreach ($values as $name=>$value)
				{
					$xml->startTag("row");
					$xml->addFullTag("name", $key."_".$name, true);
					$xml->addFullTag("value", SLS_String::trimSlashesFromString($value), true);
					$xml->endTag("row");
					if (substr($name, 0, 11) == "TRANSLATION")
					{
						if (empty($value))
							array_push($errors, "You must fill the translation for ".ucwords(strtolower(str_replace("_", " ", substr($name, 11))))." in ".strtoupper($key));
					}					
				}
				
				if (empty($values['home_mod']))
					array_push($errors, "You must fill a value for the URL of Main Controller in ".strtoupper($key));				
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['home_mod']),"")!=strtolower($values['home_mod']))
					array_push($errors, "You must fill a value for the URL of Main Controller without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($mods[$key], $values['home_mod']);				
				if (empty($values['home_desc']))
					array_push($errors, "You must fill a page title for your home page in ".strtoupper($key));
				if (empty($values['home_index']))
					array_push($errors, "You must fill an action value for your home page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['home_index']),"")!=strtolower($values['home_index']))
					array_push($errors, "You must fill an action value for your home page without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['home'], $values['home_index']);
				if (empty($values['error_mod']))
					array_push($errors, "You must fill a value for the URL of Error Controller in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_mod']),"")!=strtolower($values['error_mod']))
					array_push($errors, "You must fill a value for the URL of Error Controller without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($mods[$key], $values['error_mod']);
				if (empty($values['error_400_desc']))
					array_push($errors, "You must fill a page title for your 400 page in ".strtoupper($key));
				if (empty($values['error_401_desc']))
					array_push($errors, "You must fill a page title for your 401 page in ".strtoupper($key));
				if (empty($values['error_403_desc']))
					array_push($errors, "You must fill a page title for your 403 page in ".strtoupper($key));
				if (empty($values['error_404_desc']))
					array_push($errors, "You must fill a page title for your 404 page in ".strtoupper($key));
				if (empty($values['error_500_desc']))
					array_push($errors, "You must fill a page title for your 500 page in ".strtoupper($key));
				if (empty($values['error_307_desc']))
					array_push($errors, "You must fill a page title for your 307 page in ".strtoupper($key));
				if (empty($values['error_302_desc']))
					array_push($errors, "You must fill a page title for your 302 page in ".strtoupper($key));
					
				if (empty($values['error_400_url']))
					array_push($errors, "You must fill a value for the URL of your 400 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_400_url']),"")!=strtolower($values['error_400_url']))
					array_push($errors, "You must fill an action value for the URL of you 400 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_400_url']);
				if (empty($values['error_401_url']))
					array_push($errors, "You must fill a value for the URL of your 401 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_401_url']),"")!=strtolower($values['error_401_url']))
					array_push($errors, "You must fill an action value for the URL of you 401 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_401_url']);
				if (empty($values['error_403_url']))
					array_push($errors, "You must fill a value for the URL of your 403 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_403_url']),"")!=strtolower($values['error_403_url']))
					array_push($errors, "You must fill an action value for the URL of you 403 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_403_url']);
				if (empty($values['error_404_url']))
					array_push($errors, "You must fill a value for the URL of your 404 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_404_url']),"")!=strtolower($values['error_404_url']))
					array_push($errors, "You must fill an action value for the URL of you 404 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_404_url']);
				if (empty($values['error_500_url']))
					array_push($errors, "You must fill a value for the URL of your 500 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_500_url']),"")!=strtolower($values['error_500_url']))
					array_push($errors, "You must fill an action value for the URL of you 500 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_500_url']);
				if (empty($values['error_307_url']))
					array_push($errors, "You must fill a value for the URL of your 307 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_307_url']),"")!=strtolower($values['error_307_url']))
					array_push($errors, "You must fill an action value for the URL of you 307 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_307_url']);
				if (empty($values['error_302_url']))
					array_push($errors, "You must fill a value for the URL of your 302 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_302_url']),"")!=strtolower($values['error_302_url']))
					array_push($errors, "You must fill an action value for the URL of you 302 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_302_url']);
				
				$unikUrl = array();
				foreach ($smods[$key]['error'] as $smod)
					if (!in_array($smod, $unikUrl))
						array_push($unikUrl, $smod);
				
				if (count($unikUrl) != count($smods[$key]['error']))
					array_push($errors, "You cannot set the same Action name for two differents actions in the same language : ".strtoupper($key));
					
			}
			
			$xml->endTag("InternationalMemory");
			if (empty($errors))
			{
				$caIds = array();
				// Set defaut lang
				$siteXML = $this->_generic->getSiteXML();
				$siteXML->setTag("defaultLang", SLS_String::trimSlashesFromString($this->_http->getParam("default_lang")));
				$siteXML->setTagAttributes("//configs/domainName/domain[@default='1']",array("lang" => SLS_String::trimSlashesFromString($this->_http->getParam("default_lang"))));
				file_put_contents($this->_generic->getPathConfig("configSecure")."site.xml", $siteXML->getXML());
				$langs = $this->_generic->getSiteXML()->getTags("//configs/langs/name");
				
				$xmlControllers = $this->_generic->getControllersXML();
				
				// Generate the Home Controller ID and the Default Controller ID
				$homeID = $this->_generic->generateControllerId();
				array_push($caIds, $homeID);
				
				$defaultID = $this->_generic->generateControllerId();
				while (in_array($defaultID, $caIds))
					$defaultID = $this->_generic->generateControllerId();
				array_push($caIds, $defaultID);
				
				// Generate Actions IDs
				// Home/Index
				$indexID = $this->_generic->generateActionId();
				array_push($caIds, $indexID);
				
				// Default/UrlError
				$urlErrorID = $this->_generic->generateActionId();
				while (in_array($urlErrorID, $caIds))
					$urlErrorID = $this->_generic->generateActionId();
				array_push($caIds, $urlErrorID);
				
				// Default/BadRequestError
				$badRequestID = $this->_generic->generateActionId();
				while (in_array($badRequestID, $caIds))
					$badRequestID = $this->_generic->generateActionId();
				array_push($caIds, $badRequestID);
				
				// Default/AuthorizationError
				$authorizationID = $this->_generic->generateActionId();
				while (in_array($authorizationID, $caIds))
					$authorizationID = $this->_generic->generateActionId();
				array_push($caIds, $authorizationID);
				
				// Default/ForbiddenError
				$forbiddenID = $this->_generic->generateActionId();
				while (in_array($forbiddenID, $caIds))
					$forbiddenID = $this->_generic->generateActionId();
				array_push($caIds, $forbiddenID);
				
				// Default/InternalServerError	
				$serverID = $this->_generic->generateActionId();
				while (in_array($serverID, $caIds))
					$serverID = $this->_generic->generateActionId();
				array_push($caIds, $serverID);
				
				// Default/TemporaryRedirectError	
				$redirectID = $this->_generic->generateActionId();
				while (in_array($redirectID, $caIds))
					$redirectID = $this->_generic->generateActionId();
				array_push($caIds, $redirectID);
				
				// Default/MaintenanceError	
				$maintenanceID = $this->_generic->generateActionId();
				while (in_array($maintenanceID, $caIds))
					$maintenanceID = $this->_generic->generateActionId();
				array_push($caIds, $maintenanceID);
								
				$controllerUser['home']['mod'] = "<controller name=\"Home\" side=\"user\" id=\"".$homeID."\"><controllerLangs>";
				$controllerUser['home']['smod'] = "<scontrollers><scontroller name=\"Index\" needParam=\"0\" id=\"".$indexID."\" default=\"1\"><scontrollerLangs>";
				$controllerUser['default']['mod'] = "<controller name=\"Default\" side=\"user\" id=\"".$defaultID."\"><controllerLangs>";
				$controllerUser['default']['smod']['404'] = "<scontrollers><scontroller name=\"UrlError\" needParam=\"0\" id=\"".$urlErrorID."\"><scontrollerLangs>";
				$controllerUser['default']['smod']['400'] = "<scontroller name=\"BadRequestError\" needParam=\"0\" id=\"".$badRequestID."\"><scontrollerLangs>";
				$controllerUser['default']['smod']['401'] = "<scontroller name=\"AuthorizationError\" needParam=\"0\" id=\"".$authorizationID."\"><scontrollerLangs>";
				$controllerUser['default']['smod']['403'] = "<scontroller name=\"ForbiddenError\" needParam=\"0\" id=\"".$forbiddenID."\"><scontrollerLangs>";
				$controllerUser['default']['smod']['500'] = "<scontroller name=\"InternalServerError\" needParam=\"0\" id=\"".$serverID."\"><scontrollerLangs>";
				$controllerUser['default']['smod']['307'] = "<scontroller name=\"TemporaryRedirectError\" needParam=\"0\" id=\"".$redirectID."\"><scontrollerLangs>";
				$controllerUser['default']['smod']['302'] = "<scontroller name=\"MaintenanceError\" needParam=\"0\" id=\"".$maintenanceID."\"><scontrollerLangs>";
				
				$paramsPost = $this->_http->getParams('post');
				
				$handleLangs = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."international.xml"));
				$projectName = array_shift($this->_generic->getSiteXML()->getTags("projectName"));
				
				/* Create Lang files and Lang Directory
				mkdir($this->_generic->getPathConfig("actionLangs")."Home");
				mkdir($this->_generic->getPathConfig("actionLangs")."Default");	
				*/
				$metasXML = $this->_generic->getCoreXML('metas');
				// Add Empty Actions in metas
				foreach ($caIds as $aId)
				{
					$str = "<action id=\"".$aId."\"></action>";
					$metasXML->appendXMLNode("//sls_configs", $str);
				}
				
				// Foreach langs
				foreach ($langs as $lang) 
				{
					// Home controller
					$controllerUser['home']['mod'] 		.= "<controllerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_home_mod"))."]]></controllerLang>";
					$controllerUser['home']['smod'] 	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_home_index"))."]]></scontrollerLang>";
					
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_home_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_home_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_home_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$indexID."']", $strTitle);
					
					// Default controller
					$controllerUser['default']['mod'] 			.= "<controllerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_mod"))."]]></controllerLang>";
					$controllerUser['default']['smod']['404']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_404_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_404_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_404_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_404_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$urlErrorID."']", $strTitle);
					
					$controllerUser['default']['smod']['400']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_400_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_400_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_400_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_400_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$badRequestID."']", $strTitle);
					
					$controllerUser['default']['smod']['401']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_401_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_401_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_401_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_401_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$authorizationID."']", $strTitle);
					
					$controllerUser['default']['smod']['403']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_403_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_403_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_403_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_403_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$forbiddenID."']", $strTitle);
					
					$controllerUser['default']['smod']['500']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_500_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_500_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_500_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_500_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$serverID."']", $strTitle);
					
					$controllerUser['default']['smod']['307']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_307_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_307_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_307_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_307_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$redirectID."']", $strTitle);
					
					$controllerUser['default']['smod']['302']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_302_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_302_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_302_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_302_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$maintenanceID."']", $strTitle);
					
					// Generic langs					
					$genericFile = "<?php\n/**\n * Generic Sls Vars\n */\n";
					$length = strlen($lang."_TRANSLATION");
					foreach ($paramsPost as $key=>$value)
					{
						$value = SLS_String::trimSlashesFromString($value);
						
						if (substr($key, 0, $length) == $lang."_TRANSLATION")
						{
							$genericFile .= '$GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'JS\'][\'SLS_'.substr($key, $length+1).'\'] = "'.$value.'";';
							$genericFile .= "\n";
						}	
						
					}
					$genericFile .= "?>";
					file_put_contents($this->_generic->getPathConfig("coreGenericLangs")."generic.".$lang.".lang.php", $genericFile);
					
					// Generic lang site
					$language = array_shift($handleLangs->getTags("//sls_configs/sls_country/sls_country_langs/sls_country_lang[@iso = '".$lang."']"));
					$contentSiteLang = "<?php\n/**\n * ".$projectName." Translations\n * Language : ".ucwords($language)." (".strtoupper($lang).")\n */\n\n?>";
					file_put_contents($this->_generic->getPathConfig('genericLangs')."site.".$lang.".lang.php", $contentSiteLang);
				}
				
				// Controllers
				$controllerUser['home']['mod'] 				.= "</controllerLangs>";
				$controllerUser['home']['smod']				.= "</scontrollerLangs></scontroller></scontrollers></controller>";
				
				$controllerUser['default']['mod']			.= "</controllerLangs>";
				$controllerUser['default']['smod']['404']	.= "</scontrollerLangs></scontroller>";
				$controllerUser['default']['smod']['400']	.= "</scontrollerLangs></scontroller>";
				$controllerUser['default']['smod']['401']	.= "</scontrollerLangs></scontroller>";
				$controllerUser['default']['smod']['403']	.= "</scontrollerLangs></scontroller>";
				$controllerUser['default']['smod']['307']	.= "</scontrollerLangs></scontroller>";
				$controllerUser['default']['smod']['302']	.= "</scontrollerLangs></scontroller>";
				$controllerUser['default']['smod']['500']	.= "</scontrollerLangs></scontroller></scontrollers></controller>";
				
				// Formation du Flux Final a append
				$flux = $controllerUser['home']['mod'].$controllerUser['home']['smod'].$controllerUser['default']['mod'].$controllerUser['default']['smod']['404'].$controllerUser['default']['smod']['400'].$controllerUser['default']['smod']['401'].$controllerUser['default']['smod']['403'].$controllerUser['default']['smod']['307'].$controllerUser['default']['smod']['302'].$controllerUser['default']['smod']['500'];
				$xmlControllers->appendXMLNode('//controllers', $flux);
				file_put_contents($this->_generic->getPathConfig("configSecure")."controllers.xml", $xmlControllers->getXML());
				
				// Add meta Tags
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$indexID."']", "<robots><![CDATA[index, follow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$urlErrorID."']", "<robots><![CDATA[noindex, follow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$authorizationID."']", "<robots><![CDATA[noindex, nofollow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$serverID."']", "<robots><![CDATA[noindex, nofollow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$forbiddenID."']", "<robots><![CDATA[noindex, nofollow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$badRequestID."']", "<robots><![CDATA[noindex, nofollow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$redirectID."']", "<robots><![CDATA[noindex, nofollow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$maintenanceID."']", "<robots><![CDATA[noindex, nofollow]]></robots>");
				file_put_contents($this->_generic->getPathConfig("configSls")."metas.xml", $metasXML->getXML());
				// Déplacement des Fichiers de déploiement
				
				// Controllers
				if (!is_dir($this->_generic->getPathConfig("actionsControllers")."Home"))
					mkdir($this->_generic->getPathConfig("actionsControllers")."Home");
				if (!is_dir($this->_generic->getPathConfig("actionsControllers")."Default"))
					mkdir($this->_generic->getPathConfig("actionsControllers")."Default");
					
				// Langs
				if (!is_dir($this->_generic->getPathConfig("actionLangs")."Home"))
					mkdir($this->_generic->getPathConfig("actionLangs")."Home");
				if (!is_dir($this->_generic->getPathConfig("actionLangs")."Default"))
					mkdir($this->_generic->getPathConfig("actionLangs")."Default");
				
					
				// Generic Site Protected functions
				copy($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/__site.protected.php", $this->_generic->getPathConfig("actionsControllers")."__site.protected.php");
				
				$homeFiles = scandir($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/Home");
				$defaultFiles = scandir($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/Default");

				// Copy Home Files
				foreach ($homeFiles as $file)
				{
					if (substr($file, (strlen($file)-3)) == "php")
					{ 
						copy($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/Home/".$file, $this->_generic->getPathConfig("actionsControllers")."Home/".$file);
						if (SLS_String::startsWith($file, "__"))
						{
							foreach ($langs as $lang)
							{
								$strLang = '<?php'."\n".
													'/**'."\n".
													'* '.strtoupper($lang).' File for all the Controller Home'."\n".
													'* You can create all your sentences variables here. To create it, follow the exemple :'."\n".
													'* '.t(1).'Access it with JS and XSL variable : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'JS\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
													'* '.t(1).'Access it with XSL variable only   : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'XSL\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
													'*'."\n".
													'* '.t(1).'You can customise the value \'KEY_OF_YOUR_VARIABLE\' and "value of your sentence in '.strtoupper($lang).'" '."\n".
													'* @author SillySmart'."\n".
													'* @copyright SillySmart'."\n".
													'* @package Langs.Actions.'.$controller."\n".
													'* @since 1.0'."\n".
													'*'."\n".
													'*/'."\n".
													'?>';
								file_put_contents($this->_generic->getPathConfig("actionLangs")."Home/__Home.".strtolower($lang).".lang.php", $strLang);
							}
						}
						else 
						{
							
							$actionName = trim(SLS_String::substrBeforeFirstDelimiter($file, ".controller"));
							foreach ($langs as $lang)
							{
								$strLang = '<?php'."\n".
													'/**'."\n".
													'* '.strtoupper($lang).' File for the action '.$actionName.' into Home Controller'."\n".
													'* You can create all your sentences variables here. To create it, follow the exemple :'."\n".
													'* '.t(1).'Access it with JS and XSL variable : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'JS\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
													'* '.t(1).'Access it with XSL variable only   : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'XSL\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
													'*'."\n".
													'* '.t(1).'You can customise the value \'KEY_OF_YOUR_VARIABLE\' and "value of your sentence in '.strtoupper($lang).'" '."\n".
													'* @author SillySmart'."\n".
													'* @copyright SillySmart'."\n".
													'* @package Langs.Actions.Home'."\n".
													'* @since 1.0'."\n".
													'*'."\n".
													'*/'."\n".
													'?>';
								file_put_contents($this->_generic->getPathConfig("actionLangs")."Home/".$actionName.".".strtolower($lang).".lang.php", $strLang);
							}
						}
					}
				}
				
				// Copy Default Files
				foreach ($defaultFiles as $file)
				{
					if (substr($file, (strlen($file)-3)) == "php")
					{ 
						copy($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/Default/".$file, $this->_generic->getPathConfig("actionsControllers")."Default/".$file);
						if (SLS_String::startsWith($file, "__"))
						{
							foreach ($langs as $lang)
							{
								$strLang = '<?php'."\n".
													'/**'."\n".
													'* '.strtoupper($lang).' File for all the Controller Default'."\n".
													'* You can create all your sentences variables here. To create it, follow the exemple :'."\n".
													'* '.t(1).'Access it with JS and XSL variable : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'JS\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
													'* '.t(1).'Access it with XSL variable only   : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'XSL\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
													'*'."\n".
													'* '.t(1).'You can customise the value \'KEY_OF_YOUR_VARIABLE\' and "value of your sentence in '.strtoupper($lang).'" '."\n".
													'* @author SillySmart'."\n".
													'* @copyright SillySmart'."\n".
													'* @package Langs.Actions.Default'."\n".
													'* @since 1.0'."\n".
													'*'."\n".
													'*/'."\n".
													'?>';
								file_put_contents($this->_generic->getPathConfig("actionLangs")."Default/__Default.".strtolower($lang).".lang.php", $strLang);
							}
						}
						else 
						{
							
							$actionName = trim(SLS_String::substrBeforeFirstDelimiter($file, ".controller"));
							foreach ($langs as $lang)
							{
								$strLang = '<?php'."\n".
													'/**'."\n".
													'* '.strtoupper($lang).' File for the action '.$actionName.' into Default Controller'."\n".
													'* You can create all your sentences variables here. To create it, follow the exemple :'."\n".
													'* '.t(1).'Access it with JS and XSL variable : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'JS\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
													'* '.t(1).'Access it with XSL variable only   : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'XSL\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
													'*'."\n".
													'* '.t(1).'You can customise the value \'KEY_OF_YOUR_VARIABLE\' and "value of your sentence in '.strtoupper($lang).'" '."\n".
													'* @author SillySmart'."\n".
													'* @copyright SillySmart'."\n".
													'* @package Langs.Actions.Home'."\n".
													'* @since 1.0'."\n".
													'*'."\n".
													'*/'."\n".
													'?>';
								file_put_contents($this->_generic->getPathConfig("actionLangs")."Default/".$actionName.".".strtolower($lang).".lang.php", $strLang);
							}
						}
					}
				}
					
				// Views
				if (!is_dir($this->_generic->getPathConfig("viewsBody")."Home"))
					mkdir($this->_generic->getPathConfig("viewsBody")."Home");
				if (!is_dir($this->_generic->getPathConfig("viewsBody")."Default"))
					mkdir($this->_generic->getPathConfig("viewsBody")."Default");
				if (!is_dir($this->_generic->getPathConfig("viewsHeaders")."Home"))
					mkdir($this->_generic->getPathConfig("viewsHeaders")."Home");
				if (!is_dir($this->_generic->getPathConfig("viewsHeaders")."Default"))
					mkdir($this->_generic->getPathConfig("viewsHeaders")."Default");
				
				$homeBodyFiles = scandir($this->_generic->getPathConfig("installDeployement")."Views/Body/Home");
				$defaultBodyFiles = scandir($this->_generic->getPathConfig("installDeployement")."Views/Body/Default");
				$homeHeadersFiles = scandir($this->_generic->getPathConfig("installDeployement")."Views/Headers/Home");
				$defaultHeadersFiles = scandir($this->_generic->getPathConfig("installDeployement")."Views/Headers/Default");

				// Copy Home Body Views
				foreach ($homeBodyFiles as $file)
					(substr($file, (strlen($file)-3)) == "xsl") ? copy($this->_generic->getPathConfig("installDeployement")."Views/Body/Home/".$file, $this->_generic->getPathConfig("viewsBody")."Home/".$file) : "";
				
				// Copy Default Body Views
				foreach ($defaultBodyFiles as $file)
					(substr($file, (strlen($file)-3)) == "xsl") ? copy($this->_generic->getPathConfig("installDeployement")."Views/Body/Default/".$file, $this->_generic->getPathConfig("viewsBody")."Default/".$file) : "";	
					
				// Copy Home Headers Views
				foreach ($homeHeadersFiles as $file)
					(substr($file, (strlen($file)-3)) == "xsl") ? copy($this->_generic->getPathConfig("installDeployement")."Views/Headers/Home/".$file, $this->_generic->getPathConfig("viewsHeaders")."Home/".$file) : "";
				
				// Copy Default Headers Views
				foreach ($defaultHeadersFiles as $file)
					(substr($file, (strlen($file)-3)) == "xsl") ? copy($this->_generic->getPathConfig("installDeployement")."Views/Headers/Default/".$file, $this->_generic->getPathConfig("viewsHeaders")."Default/".$file) : "";	
				
				
								
				$this->setInstallationStep(array(0=>"SLS_Init",1=>"Initialization"), array(0=>"DataBase",1=>"DataBase"));
				return $this->_generic->dispatch("SLS_Init", "DataBase");				
			}
			else 
			{
				$xml->startTag('errors');			
				foreach ($errors as $error)
					$xml->addFullTag('error', $error, true);
				$xml->endTag('errors');
				$giveDataStep1 = true;
				$step = 1;
			}
			
		}
		// Sinon, default
		else
		{
			$step = 0;
		}
		if ($giveDataStep1 == true)
		{
			$xml->startTag("choose_langs");
			$valueToHidden = "";
			$isos = array();
			foreach($listLangs as $listLang)
			{
				$iso = array_shift($handle->getTags("//sls_configs/sls_country/sls_country_langs/sls_country_lang[node()='".$listLang."']/@iso"));
				array_push($isos, $iso);
				$xml->startTag("choose_lang");					
				$xml->addFullTag("iso",$iso,true);
				$xml->addFullTag("label",$listLang,true);
				$xml->endTag("choose_lang");
				$valueToHidden .= "-".$listLang;
			}
			$xml->endTag("choose_langs");
			$xml->addFullTag("hidden_langs", substr($valueToHidden, 1), true);
			// Récupération des mots à traduire
			$xml->startTag("translate");
			foreach ($isos as $iso)
			{
				$xml->startTag($iso);
					if (is_file($this->_generic->getPathConfig("coreGenericLangs")."generic.".$iso.".lang.php"))
						$handle = fopen($this->_generic->getPathConfig("coreGenericLangs")."generic.".$iso.".lang.php", 'r');
					else 
						$handle = fopen($this->_generic->getPathConfig("coreGenericLangs")."generic.en.lang.php", 'r');
					$array = array();
					while (!feof($handle)) 
					{
						$line = fgets($handle, 4096);
						if (substr($line, 0, 1) == "$")
						{
							$tmpArray = array();
							$tmpArray['name'] =  str_replace("SLS_", "", SLS_String::substrAfterLastDelimiter(SLS_String::substrBeforeLastDelimiter($line, "']"), "['"));
							$tmpArray['value'] = SLS_String::substrBeforeLastDelimiter(SLS_String::substrAfterFirstDelimiter(trim(SLS_String::substrAfterLastDelimiter($line, " = ")), '"'), '"');
							array_push($array, $tmpArray);
						}
					}
					
					foreach ($array as $row)
					{
						$xml->startTag("sentence");
							$xml->addFullTag('name', strtolower(str_replace("_", " ", $row['name'])), true);
							$xml->addFullTag('code', $row['name'], true);
							$xml->addFullTag('value', $row['value'], true);
						$xml->endTag("sentence");
					}
				$xml->endTag($iso);
			}
			$xml->endTag("translate");
		}
		$xml->addFullTag("step", $step, true);
		$this->saveXML($xml);
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$langs = $this->_generic->getObjectLang()->getSiteLangs();
		$listing = true;
		$errors = array();
		$protocol = $this->_generic->getProtocol();
		$siteXML = $this->_generic->getSiteXML();
		$aliasesSelected = array();
		$componentsSelected = array();
		
		$plugin = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configPlugins")."/plugins.xml"));
		$pluginMobile = $plugin->getTag("//plugins/plugin[@code='mobile']");
		$pluginMobile = (!empty($pluginMobile)) ? true : false;
				
		$controllersXML = $this->_generic->getControllersXML();
		
		$controller = SLS_String::trimSlashesFromString($this->_http->getParam("Controller"));
		$controllers = $controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']");
		if (count($controllers) == 1)
		{
			$controllerID = array_shift($controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']/@id"));
			$protocol = $this->_generic->getControllerProtocol($controllerID);
			$listing = false;
			$xml->addFullTag('request', 'AddAction', true);
			
			if ($this->_http->getParam('reload') == 'true')
			{
				// Get the form informations
				$newAction 				= SLS_String::stringToUrl(ucwords(SLS_String::trimSlashesFromString($this->_http->getParam("actionName"))), "", false);
				$needDynamic 			= SLS_String::trimSlashesFromString($this->_http->getParam("dynamic"));
				$needOffline 			= SLS_String::trimSlashesFromString($this->_http->getParam("offline"));
				$needDefault 			= SLS_String::trimSlashesFromString($this->_http->getParam("default"));
				$searchEngine			= SLS_String::trimSlashesFromString($this->_http->getParam("indexes"));
				$postProtocol			= SLS_String::trimSlashesFromString($this->_http->getParam("protocol"));
				$tpl 					= SLS_String::trimSlashesFromString($this->_http->getParam('template'));
				$aliases				= SLS_String::trimSlashesFromString($this->_http->getParam('domains'));
				$components				= SLS_String::trimSlashesFromString($this->_http->getParam('components'));
				$cache_visibility 		= SLS_String::trimSlashesFromString($this->_http->getParam('cache_visibility'));
				$cache_scope 			= SLS_String::trimSlashesFromString($this->_http->getParam('cache_scope'));
				$cache_expiration 		= SLS_String::trimSlashesFromString($this->_http->getParam('cache_expiration'));
				$cache_responsive 		= SLS_String::trimSlashesFromString($this->_http->getParam('cache_responsive'));
				if (empty($postProtocol))
					$postProtocol = "http";
				$postActionsLang		= array();
				$postTitlesLang			= array();
				$postDescriptionsLang	= array();
				$postKeywordsLang		= array();	
				$toCache			 	= (in_array($cache_visibility,array("public","private"))) ? true : false;
				
				// If responsive wanted
				if ($cache_responsive == "true" && !$pluginMobile)
				{
					// Force Mobile plugin download
					file_get_contents($this->_generic->getFullPath("SLS_Bo",
																  "SearchPlugin",
																  array("Action" => "Download",
																  		"Server" => "4",
																  		"Plugin" => "20",
																  		"token"	 => sha1(substr($this->_generic->getSiteConfig("privateKey"), 0, 3).substr($this->_generic->getSiteConfig("privateKey"), strlen($this->_generic->getSiteConfig("privateKey"))-3))),
																  true));
				}
				
				if (empty($newAction))
					array_push($errors, "Action name can't be empty");
								
				$actionExist 		= $controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller[@name='".$newAction."']");
				if (count($actionExist) == 0)
				{
					if (empty($postProtocol) || ($postProtocol != 'http' && $postProtocol != 'https'))
						array_push($errors, "Protocol must be http or https");
					else 
						$protocol = $postProtocol;
										
					if (!empty($aliases) && is_array($aliases))
						foreach($aliases as $alias)
							array_push($aliasesSelected,$alias);
							
					if (!empty($components) && is_array($components))
						foreach($components as $component)
							array_push($componentsSelected,$component);
						
					$siteLangs = $this->_generic->getObjectLang()->getSiteLangs();
					
					foreach ($siteLangs as $lang)
					{
						// Check Url
						$postLang = trim(SLS_String::stringToUrl(SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-action")), "", false));
						$translationExist = $controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller/scontrollerLangs[scontrollerLang = '".$postLang."']");
						if (empty($postLang))
							array_push($errors, "You need to fill the ".$lang." url translations");
						elseif(count($translationExist) != 0)
							array_push($errors, "You URL translation in ".$lang." is already in use on another action in the same controller");
						else
							$postActionsLang[$lang] =  $postLang;
						
						// Get Titles	
						$postTitlesLang[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-title"));
						// Get Description
						$postDescriptionsLang[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-description"));
						// Get Keywords
						$postKeywordsLang[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-keywords"));
					}
					
					if ($toCache && (!is_numeric($cache_expiration) || $cache_expiration < 0))
						array_push($errors, "Your expiration cache must be a positive time or 0");
					if ($toCache && (!in_array($cache_scope,array("full","partial"))))
						array_push($errors, "Your must describe your cache scope");
					
					if (count($errors) == 0)
					{
						// If an error existing and the controller directory wasn't created
						if (!is_dir($this->_generic->getPathConfig("actionsControllers").$controller))
							mkdir($this->_generic->getPathConfig("actionsControllers").$controller);
						if (!is_file($this->_generic->getPathConfig("actionsControllers").$controller."/__".$controller.".protected.php"))
						{
							$strControllerProtected = '<?php'."\n".
							   '/**'."\n".
							   '* Class generic for the controller '.$newControllerName.''."\n".
							   '* Write here all your generic functions you need in your '.$newControllerName.' Actions'."\n".
							   '* @author SillySmart'."\n".
							   '* @copyright SillySmart'."\n".
							   '* @package Mvc.Controllers.'.$newControllerName.''."\n".
							   '* @see Mvc.Controllers.SiteProtected'."\n".
							   '* @see Sls.Controllers.Core.SLS_GenericController'."\n".
							   '* @since 1.0'."\n".
							   '*/'."\n".
							   'class '.$newControllerName.'ControllerProtected extends SiteProtected'."\n".
							   '{'."\n".
							   t(1).'public function init()'."\n".
							   t(1).'{'."\n".
							   		t(2).'parent::init();'."\n".
							   t(1).'}'."\n".
							   '}'."\n".
							   '?>';
						
							file_put_contents($this->_generic->getPathConfig("actionsControllers").$controller."/__".$controller.".protected.php", $strControllerProtected);
						}
						
						// Create Controller File
						$strControllerAction = '<?php'."\n".
												'/**'."\n".
												'* Class '.$newAction.' into '.$controller.' Controller'."\n".
												'* @author SillySmart'."\n".
												'* @copyright SillySmart'."\n".
												'* @package Mvc.Controllers.'.$controller."\n".
												'* @see Mvc.Controllers.'.$controller.'.ControllerProtected'."\n".
												'* @see Mvc.Controllers.SiteProtected'."\n".
												'* @see Sls.Controllers.Core.SLS_GenericController'."\n".
												'* @since 1.0'."\n".
												'*'."\n".
												'*/'."\n".
												'class '.$controller.$newAction.' extends '.$controller.'ControllerProtected'."\n".
												'{'."\n".
												t(1).'public function init()'."\n".
											   	t(1).'{'."\n".
											   		t(2).'parent::init();'."\n".
											   	t(1).'}'."\n\n".
												t(1).'public function action()'."\n".
												t(1).'{'."\n".
													t(2)."\n".
												t(1).'}'."\n".
												"}\n".
												'?>';
						file_put_contents($this->_generic->getPathConfig("actionsControllers").$controller."/".$newAction.".controller.php", $strControllerAction);
						
						// Create Lang Files
						if (!is_dir($this->_generic->getPathConfig("langs")."Actions/".$controller))
							mkdir($this->_generic->getPathConfig("langs")."Actions/".$controller);
						$langsFiles = array();
						
						foreach ($siteLangs as $lang)
						{
							$strLang = '<?php'."\n".
												'/**'."\n".
												'* '.strtoupper($lang).' File for the action '.$newAction.' into '.$controller.' Controller'."\n".
												'* You can create all your sentences variables here. To create it, follow the exemple :'."\n".
												'* '."\t".'Access it with JS and XSL variable : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'JS\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
												'* '."\t".'Access it with XSL variable only   : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'XSL\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
												'*'."\n".
												'* '."\t".'You can customise the value \'KEY_OF_YOUR_VARIABLE\' and "value of your sentence in '.strtoupper($lang).'" '."\n".
												'* @author SillySmart'."\n".
												'* @copyright SillySmart'."\n".
												'* @package Langs.Actions.'.$controller."\n".
												'* @since 1.0'."\n".
												'*'."\n".
												'*/'."\n".
												'?>';
							file_put_contents($this->_generic->getPathConfig("langs")."Actions/".$controller."/".$newAction.".".strtolower($lang).".lang.php", $strLang);
						}
						
						// Create Views File
						if (!is_dir($this->_generic->getPathConfig("viewsBody").$controller))
							mkdir($this->_generic->getPathConfig("viewsBody").$controller);
						if (!is_dir($this->_generic->getPathConfig("viewsHeaders").$controller))
							mkdir($this->_generic->getPathConfig("viewsHeaders").$controller);
						
						$strBody = '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" xmlns="http://www.w3.org/1999/xhtml">'."\n".
									t(1).'<xsl:template name="'.$newAction.'">'."\n".
										t(2).'<h1>Customize the body of this page in <i>'.$this->_generic->getPathConfig('viewsBody').$controller.'/'.$newAction.'.xsl</i></h1>'."\n".
										t(2).'<h2>And your headers in <i>'.$this->_generic->getPathConfig('viewsHeaders').$controller.'/'.$newAction.'.xsl</i></h2>'."\n".
									t(1).'</xsl:template>'."\n".
									'</xsl:stylesheet>';
						$strHeader = 	'<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" xmlns="http://www.w3.org/1999/xhtml">'."\n".
										t(1).'<xsl:template name="Header'.$newAction.'">'."\n".
										t(1).'</xsl:template>'."\n".
										'</xsl:stylesheet>';
						file_put_contents($this->_generic->getPathConfig("viewsBody").$controller.'/'.$newAction.'.xsl', $strBody);
						file_put_contents($this->_generic->getPathConfig("viewsHeaders").$controller.'/'.$newAction.'.xsl', $strHeader);
						// End of files creation
						
						// XML Modifications
						$metasXML = $this->_generic->getCoreXML('metas');
						// Get the titles
						
						// If default, reset other in current controller
						if (!empty($needDefault))
						{
							$actions = $controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller/@id");
							foreach($actions as $curActionId)
								$controllersXML->setTagAttributes("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller[@id='".$curActionId."']", array('default' => '0'));
						}
												
						$actionId = $this->_generic->generateActionId();
						$xmlAction = "<scontroller name=\"".$newAction."\" needParam=\"";
						$xmlAction .= ($this->_http->getParam("dynamic") == "on") ? "1" : "0";
						$xmlAction .= "\" id=\"".$actionId."\" protocol=\"".$protocol."\"";
						if ($tpl != -1)
							$xmlAction .= " tpl=\"".$tpl."\"";
						if (!empty($aliases))
							$xmlAction .= " domains=\"".implode(",",$aliases)."\"";
						if (!empty($components))
							$xmlAction .= " components=\"".implode(",",$components)."\"";
						if (!empty($needOffline))
							$xmlAction .= " disable=\"1\"";
						if (!empty($needDefault))
							$xmlAction .= " default=\"1\"";
						if ($toCache)
							$xmlAction .= " cache=\"".$cache_visibility."|".$cache_scope."|".(($cache_responsive == "true") ? "responsive" : "no_responsive")."|".$cache_expiration."\"";
						$xmlAction .= "><scontrollerLangs>";
						$strMetas = "<action id=\"".$actionId."\" />";
						$metasXML->appendXMLNode("//sls_configs", $strMetas);
						foreach ($siteLangs as $lang)
						{
							$xmlAction .= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".$postActionsLang[$lang]."]]></scontrollerLang>";
							// Metas
							$metas = "<title lang=\"".$lang."\"><![CDATA[".$postTitlesLang[$lang]."]]></title>";
							$metas .= "<description lang=\"".$lang."\"><![CDATA[".$postDescriptionsLang[$lang]."]]></description>";
							$metas .= "<keywords lang=\"".$lang."\"><![CDATA[".$postKeywordsLang[$lang]."]]></keywords>";
							$metasXML->appendXMLNode("//sls_configs/action[@id=\"".$actionId."\"]", $metas);							
						}
						$xmlAction .= "</scontrollerLangs></scontroller>";
						if (!SLS_String::contains($searchEngine,", "))
							$searchEngine = str_replace(",",", ",$searchEngine);
						if ($searchEngine != "index, follow" && $searchEngine != "noindex, follow" && $searchEngine != "noindex, nofollow" && $searchEngine != "index, nofollow")
							$searchEngine = "index, follow";
						$metasXML->appendXMLNode("//sls_configs/action[@id='".$actionId."']", "<robots><![CDATA[".$searchEngine."]]></robots>");
						$controllersXML->appendXMLNode("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers", $xmlAction);
						file_put_contents($this->_generic->getPathConfig("configSecure")."controllers.xml", $controllersXML->getXML());
						file_put_contents($this->_generic->getPathConfig("configSls")."metas.xml", $metasXML->getXML());
						$controllers = $this->_generic->getTranslatedController("SLS_Bo", "Controllers");
						$this->_generic->redirect($controllers['controller']."/".$controllers['scontroller'].".sls");
					}				
				}
				else 
					array_push($errors, "This generic name is already in use for this controller");
								
				if (!empty($errors))
				{
					$xml->startTag("errors");
						foreach ($errors as $error)
							$xml->addFullTag("error", $error, true);
					$xml->endTag("errors");
					$xml->startTag('form');
					$xml->addFullTag("controllerName", $postControllerName);					
					foreach ($postActionsLang as $key=>$value)
						$xml->addFullTag($key."-action", $value, true);					
					$xml->endTag('form');
					$xml->addFullTag("default",(empty($needDefault)) ? "false" : "true",true);
					$xml->addFullTag("dynamic",(empty($needDynamic)) ? "false" : "true",true);
					$xml->addFullTag("offline",(empty($needOffline)) ? "false" : "true",true);
					$xml->startTag("cache");			
						$xml->addFullTag("cache_visibility", $cache_visibility,true);
						$xml->addFullTag("cache_scope", $cache_scope,true);
						$xml->addFullTag("cache_responsive", $cache_responsive,true);
						$xml->addFullTag("cache_expiration", $cache_expiration,true);
					$xml->endTag("cache");
				}
			}
			else
			{
				$defaultExists = $controllersXML->getTag("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@default='1']/@name");
				$xml->addFullTag("default",(empty($defaultExists)) ? "true" : "false",true);
				$xml->startTag("cache");					
					$xml->addFullTag("cache_visibility", "",true);
					$xml->addFullTag("cache_scope", "",true);
					$xml->addFullTag("cache_responsive","",true);
					$xml->addFullTag("cache_expiration", 0,true);
				$xml->endTag("cache");
			}
			
			// Build all tpls
			$tpls = $this->getAppTpls();
			$xml->startTag("tpls");
			foreach($tpls as $template)
				$xml->addFullTag("tpl",$template,true);
			$xml->endTag("tpls");
			
			$xml->startTag('controller');
			$xml->addFullTag("name", $controller, true);
				$xml->startTag('translations');
				foreach ($langs as $lang)
				{
					$xml->startTag('translation');
						$xml->addFullTag("lang", $lang, true);
						$xml->addFullTag("name", $controllersXML->getTag("//controllers/controller[@name='".$controller."' and @side='user']/controllerLangs/controllerLang[@lang='".$lang."']"), true);
					$xml->endTag('translation');
				}
				$xml->endTag('translations');
			$xml->endTag('controller');
			$xml->addFullTag('request', 'addAction', true);
		}
		else {
			$this->_generic->dispatch('SLS_Bo', 'Controllers');
		}
		
		if (empty($tpl))
			$tpl = $controllersXML->getTag("//controllers/controller[@name='".$controller."' and @side='user']/@tpl");
		
		$xml->addFullTag('protocol', $protocol, true);
		$xml->addFullTag('template', $tpl, true);
		
		$aliases = $siteXML->getTagsAttributes("//configs/domainName/domain",array("alias"));
		$xml->startTag("aliases");
		for($i=0 ; $i<$count=count($aliases) ; $i++)
		{
			$xml->startTag("alias");
				$xml->addFullTag("name",$aliases[$i]["attributes"][0]["value"],true);
				$xml->addFullTag("selected",(in_array($aliases[$i]["attributes"][0]["value"],$aliasesSelected)) ? "true" : "false",true);
			$xml->endTag("alias");
		}
		$xml->endTag("aliases");
		
		$components = $this->_generic->recursiveReadDir($this->_generic->getPathConfig("componentsControllers"), array(), array(0=>"php"));
		$xml->startTag("components");				
		foreach ($components as $component)
		{
			$xml->startTag("component");
				$xml->addFullTag("name", SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($component, "/"), ".controller.php"),true);
				$xml->addFullTag("selected",(in_array(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($component, "/"), ".controller.php"),$componentsSelected)) ? "true" : "false",true);
			$xml->endTag("component");
		}
		$xml->endTag("components");
		
		$this->saveXML($xml);
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$langs = $this->_lang->getSiteLangs();
		$listing = true;
		$errors = array();
		$controllersXML = $this->_generic->getControllersXML();
		$controller = $this->_http->getParam('Controller');
		$protocol = $this->_generic->getSiteConfig("protocol");
				
		// Check if bo controller
		$isBo = ($this->_http->getParam('isBo')=="true") ? true : false;
				
		if ($this->_http->getParam('reload') == 'true')
		{
			$postControllerName = SLS_String::trimSlashesFromString($this->_http->getParam('controllerName'));
			$newControllerName = SLS_String::stringToUrl(ucwords($postControllerName), "", false);
			$postProtocol = SLS_String::trimSlashesFromString($this->_http->getParam('protocol'));
			$tpl = SLS_String::trimSlashesFromString($this->_http->getParam('template'));
			$postControllerLangs = array();
			if (empty($newControllerName))
				array_push($errors, "The generic controller name is required to add a new Controller");
			if (empty($postProtocol) || ($postProtocol != 'http' && $postProtocol != 'https'))
				array_push($errors, "Protocol must be http or https");
			else 
				$protocol = $postProtocol;
			foreach ($langs as $lang)
			{
				$langController = SLS_String::stringToUrl(SLS_String::trimSlashesFromString($this->_http->getParam($lang."-controller")), "", false);
				if (empty($langController))
					array_push($errors, "The translation in ".$lang." is required to add a new Controller");
				else
					$postControllerLangs[$lang] = $langController;
			}
			
							
			if (empty($errors))
			{
				$test = $controllersXML->getTags("//controllers/controller[@name='".$newControllerName."']");
				if (count($test) != 0)
					array_push($errors, ($newControllerName == $postControllerName) ? "The controller Name '".$postControllerName."' already exist" : "The controller Name '".$postControllerName."' (".$newControllerName.") already exist");
			}
			if (empty($errors))
			{
				$translatedController = $controllersXML->getTags("//controllers/controller/controllerLangs/controllerLang",  'id');
				foreach ($postControllerLangs as $key=>$value)
				{
					if (in_array($value, $translatedController))
						array_push($errors, "The translated name '".$value."' for this controller is alredy used");
				}
				if (empty($errors))
				{
				
					$controllerID = $this->_generic->generateControllerId();
					$str = "<controller name=\"".$newControllerName."\" side=\"user\" protocol=\"".$protocol."\" id=\"".$controllerID."\"";
					
					if (!$isBo && $tpl != -1)
						$str .= " tpl=\"".$tpl."\"";
					if ($isBo)
						$str .= " isBo=\"true\" tpl=\"bo\"";
					
					$str .= "><controllerLangs>";

					foreach ($postControllerLangs as $key=>$value)
						$str .= "<controllerLang lang=\"".$key."\"><![CDATA[".$value."]]></controllerLang>";
					
					$str .= "</controllerLangs><scontrollers></scontrollers></controller>";
					$controllersXML->appendXMLNode("//controllers", $str);
					
					$strControllerProtected = '<?php'."\n".
						   '/**'."\n".
						   '* Class generic for the controller '.$newControllerName.''."\n".
						   '* Write here all your generic functions you need in your '.$newControllerName.' Actions'."\n".
						   '* @author SillySmart'."\n".
						   '* @copyright SillySmart'."\n".
						   '* @package Mvc.Controllers.'.$newControllerName.''."\n".
						   '* @see Mvc.Controllers.SiteProtected'."\n".
						   '* @see Sls.Controllers.Core.SLS_GenericController'."\n".
						   '* @since 1.0'."\n".
						   '*/'."\n".
						   'class '.$newControllerName.'ControllerProtected extends SiteProtected'."\n".
						   '{'."\n".
						   t(1).'public function init()'."\n".
						   t(1).'{'."\n".
						   		t(2).'parent::init();'."\n".
						   t(1).'}'."\n".
						   '}'."\n".
						   '?>';
					
					// Create the Controller Directory and Protected Function file					
					mkdir($this->_generic->getPathConfig("actionsControllers").$newControllerName);					
					file_put_contents($this->_generic->getPathConfig("actionsControllers").$newControllerName."/__".$newControllerName.".protected.php", $strControllerProtected);
					// Create Lang Directory
					mkdir($this->_generic->getPathConfig("actionLangs").$newControllerName);
					
					// Create Lang Files
					foreach ($langs as $lang)
					{
						$strLang = '<?php'."\n".
											'/**'."\n".
											'* '.strtoupper($lang).' File for all the Controller '.$newControllerName."\n".
											'* You can create all your sentences variables here. To create it, follow the exemple :'."\n".
											'* '.t(1).'Access it with JS and XSL variable : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'JS\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
											'* '.t(1).'Access it with XSL variable only   : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'XSL\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
											'*'."\n".
											'* '."\t".'You can customise the value \'KEY_OF_YOUR_VARIABLE\' and "value of your sentence in '.strtoupper($lang).'" '."\n".
											'* @author SillySmart'."\n".
											'* @copyright SillySmart'."\n".
											'* @package Langs.Actions.'.$newControllerName."\n".
											'* @since 1.0'."\n".
											'*'."\n".
											'*/'."\n".
											'?>';
						file_put_contents($this->_generic->getPathConfig("actionLangs").$newControllerName."/__".$newControllerName.".".strtolower($lang).".lang.php", $strLang);
					}	
						
					// Create Views Directory
					mkdir($this->_generic->getPathConfig("viewsHeaders").$newControllerName);
					mkdir($this->_generic->getPathConfig("viewsBody").$newControllerName);
					// Save the new XML
					file_put_contents($this->_generic->getPathConfig('configSecure')."controllers.xml", $controllersXML->getXML());
					// Insert Into Meta
					$metasXML = $this->_generic->getCoreXML('metas');
					$strMetas = "<action id=\"".$controllerID."\" />";
					$metasXML->appendXMLNode("//sls_configs", $strMetas);
					file_put_contents($this->_generic->getPathConfig('configSls')."metas.xml", $metasXML->getXML());
					
					# isBo
					if ($isBo)
					{
						# Public/Files/__Uploads/images/bo
						if (!file_exists($this->_generic->getPathConfig("files")."__Uploads") && !is_dir($this->_generic->getPathConfig("files")."__Uploads"))
							mkdir($this->_generic->getPathConfig("files")."__Uploads");
						if (!file_exists($this->_generic->getPathConfig("files")."__Uploads/images") && !is_dir($this->_generic->getPathConfig("files")."__Uploads/images"))
							mkdir($this->_generic->getPathConfig("files")."__Uploads/images");
						if (!file_exists($this->_generic->getPathConfig("files")."__Uploads/images/bo") && !is_dir($this->_generic->getPathConfig("files")."__Uploads/images/bo"))
							mkdir($this->_generic->getPathConfig("files")."__Uploads/images/bo");
						if (file_exists($this->_generic->getPathConfig("installDeployement")."Public/Files/__Uploads/images/bo") && is_dir($this->_generic->getPathConfig("installDeployement")."Public/Files/__Uploads/images/bo"))
						{
							$files = scandir($this->_generic->getPathConfig("installDeployement")."Public/Files/__Uploads/images/bo");
							foreach($files as $file)
							{
								if (!SLS_String::startsWith($file,"."))
								{
									@copy($this->_generic->getPathConfig("installDeployement")."Public/Files/__Uploads/images/bo/".$file, $this->_generic->getPathConfig("files")."__Uploads/images/bo/".$file);
								}
							}
						}
						# /Public/Files/__Uploads/images/bo
						
						# Controller langs
						foreach($langs as $lang)
						{
							if (file_exists($this->_generic->getPathConfig("installDeployement")."Langs/Actions/{{USER_BO}}/__{{USER_BO}}.".$lang.".lang.php"))
								$langContent = str_replace(array("{{USER_BO}}"),array($newControllerName),file_get_contents($this->_generic->getPathConfig("installDeployement")."Langs/Actions/{{USER_BO}}/__{{USER_BO}}.".$lang.".lang.php"));
							else
								$langContent = str_replace(array("{{USER_BO}}"),array($newControllerName),file_get_contents($this->_generic->getPathConfig("installDeployement")."Langs/Actions/{{USER_BO}}/__{{USER_BO}}.en.lang.php"));
							if (!empty($langContent))
								file_put_contents($this->_generic->getPathConfig("actionLangs").$newControllerName."/__".$newControllerName.".".$lang.".lang.php",$langContent);
						}
						# /Controller langs
						
						# XSL Templates
						$boTemplates = array("bo.xsl","bo_light.xsl","bo_blank.xsl");
						foreach($boTemplates as $boTemplate)
						{
							if (file_exists($this->_generic->getPathConfig("installDeployement")."Views/Templates/".$boTemplate) && !is_dir($this->_generic->getPathConfig("installDeployement")."Views/Templates/".$boTemplate))
							{
								@copy($this->_generic->getPathConfig("installDeployement")."Views/Templates/".$boTemplate, $this->_generic->getPathConfig("viewsTemplates").$boTemplate);
							}
						}
						# /XSL Templates
						
						# XSL Generics
						$boGenerics = array("Boactionsbar.xsl","Boheaders.xsl","Bomenu.xsl");
						foreach($boGenerics as $boGeneric)
						{
							if (file_exists($this->_generic->getPathConfig("installDeployement")."Views/Generics/".$boGeneric) && !is_dir($this->_generic->getPathConfig("installDeployement")."Views/Generics/".$boGeneric))
							{
								@copy($this->_generic->getPathConfig("installDeployement")."Views/Generics/".$boGeneric, $this->_generic->getPathConfig("viewsGenerics").$boGeneric);
							}
						}
						# /XSL Generics
						
						# Controllers Statics
						$boStatics = array("BoMenu.controller.php");
						foreach($boStatics as $boStatic)
						{
							if (file_exists($this->_generic->getPathConfig("installDeployement")."Controllers/Statics/".$boStatic) && !is_dir($this->_generic->getPathConfig("installDeployement")."Controllers/Statics/".$boStatic))
							{
								@copy($this->_generic->getPathConfig("installDeployement")."Controllers/Statics/".$boStatic, $this->_generic->getPathConfig("staticsControllers").$boStatic);
							}
						}
						# /Controllers Statics
						
						# __{{USER_BO}}.protected.php
						if (file_exists($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/{{USER_BO}}/__{{USER_BO}}.protected.php") && !is_dir($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/{{USER_BO}}/__{{USER_BO}}.protected.php"))
						{
							@copy($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/{{USER_BO}}/__{{USER_BO}}.protected.php", $this->_generic->getPathConfig("actionsControllers").$newControllerName."/__".$newControllerName.".protected.php");
							@file_put_contents($this->_generic->getPathConfig("actionsControllers").$newControllerName."/__".$newControllerName.".protected.php",str_replace(array("{{USER_BO}}"),array($newControllerName),file_get_contents($this->_generic->getPathConfig("actionsControllers").$newControllerName."/__".$newControllerName.".protected.php")));
						}
						# /__{{USER_BO}}.protected.php
						
						# Native actions
						$controllerPath = $this->_generic->getPathConfig("installDeployement")."Controllers/Actions/{{USER_BO}}";
						$boActions = scandir($controllerPath);
						$boLightActions = array("BoLogin","BoRenewPwd","BoForgottenPwd");
						$boBlankActions = array("BoMenu");
						$tokenSecret = sha1(substr($this->_generic->getSiteConfig("privateKey"), 0, 3).substr($this->_generic->getSiteConfig("privateKey"), strlen($this->_generic->getSiteConfig("privateKey"))-3));
						foreach($boActions as $boAction)
						{
							if ( SLS_String::startsWith($boAction,"Bo") 			&& // Real boAction
								 file_exists($controllerPath."/".$boAction) 		&& // File exist
								!is_dir($controllerPath."/".$boAction)				&& // Not a directory 
								!SLS_String::startsWith($boAction,"BoUser") 		&& // Exclude custom action "BoUser(*)" 
								!SLS_String::startsWith($boAction,"Boi18n") 		&& // Exclude custom action "Boi18n" 
								!SLS_String::startsWith($boAction,"BoFileUpload") 	&& // Exclude custom action "BoFileUpload"
								!SLS_String::startsWith($boAction,"BoProjectSettings") // Exclude custom action "BoProjectSettings"
							)
							{
								// Generate Action
								$action = SLS_String::substrBeforeFirstDelimiter($boAction,".");
								$params = array(0 => array("key" 	=> "reload",
										  				   "value" 	=> "true"),
										  		1 => array("key" 	=> "Controller",
										  				   "value" 	=> $newControllerName),
											 	2 => array("key" 	=> "actionName",
										  				   "value" 	=> $action),
										  		3 => array("key"	=> "token",
										  				   "value"	=> $tokenSecret),
										  		4 => array("key"	=> "template",
										  				   "value" 	=> (in_array($action,$boLightActions)) ? "bo_light" : ((in_array($action,$boBlankActions)) ? "bo_blank" : "bo")),
										  		5 => array("key"	=> "dynamic",
										  				   "value" 	=> "on"),
										  		6 => array("key"	=> "indexes",
										  				   "value"	=> "noindex,nofollow")
											    );
								if ($action == "BoLogin")
									$params[] = array("key" 	=> "default",
										  			  "value"  => "on");
								foreach($langs as $lang)
								{
									$tmpParam = array("key" 	=> $lang."-action",
													  "value" 	=> $action."_".$lang);
									$tmpTitle = array("key" 	=> $lang."-title",
													  "value" 	=> $action);
									array_push($params,$tmpParam);
									array_push($params,$tmpTitle);
								}
								file_get_contents($this->_generic->getFullPath("SLS_Bo",
																			  "AddAction",
																			  $params,
																			  true));
								
								// Erase Action
								$source = str_replace(array("{{USER_BO}}"),array($newControllerName),file_get_contents($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/{{USER_BO}}/".$action.".controller.php"));
								file_put_contents($this->_generic->getPathConfig("actionsControllers").$newControllerName."/".$action.".controller.php",$source);
								
								// Erase View Head
								if (file_exists($this->_generic->getPathConfig("installDeployement")."Views/Headers/{{USER_BO}}/".$action.".xsl"))
									file_put_contents($this->_generic->getPathConfig("viewsHeaders").$newControllerName."/".$action.".xsl",file_get_contents($this->_generic->getPathConfig("installDeployement")."Views/Headers/{{USER_BO}}/".$action.".xsl"));
								
								// Erase View Body
								if (file_exists($this->_generic->getPathConfig("installDeployement")."Views/Body/{{USER_BO}}/".$action.".xsl"))
									file_put_contents($this->_generic->getPathConfig("viewsBody").$newControllerName."/".$action.".xsl",file_get_contents($this->_generic->getPathConfig("installDeployement")."Views/Body/{{USER_BO}}/".$action.".xsl"));
							}
						}
						# /Native actions
					}
					# /isBo
						
					$controllersRedirect = $this->_generic->getTranslatedController('SLS_Bo', 'Controllers');
					$this->_generic->redirect($controllersRedirect['controller']."/".$controllersRedirect['scontroller']);
				}
			}
			
			if (!empty($errors))
			{
				$xml->startTag("errors");
					foreach ($errors as $error)
						$xml->addFullTag("error", $error, true);
				$xml->endTag("errors");
				$xml->startTag('form');
				$xml->addFullTag("controllerName", $postControllerName);
					foreach ($postControllerLangs as $key=>$value)
						$xml->addFullTag($key."-controller", $value, true);
						
				$xml->endTag('form');
			}
			
		}
		// Build all tpls
		$tpls = $this->getAppTpls();
		$xml->startTag("tpls");
		foreach($tpls as $template)
			$xml->addFullTag("tpl",$template,true);
		$xml->endTag("tpls");
		
		$xml->startTag('controller');
		$xml->addFullTag('isBo',($isBo) ? "true" : "false",true);
			$xml->startTag('translations');
			foreach ($langs as $lang)
			{
				$xml->startTag('translation');
					$xml->addFullTag("lang", $lang, true);	
				$xml->endTag('translation');
			}
			$xml->endTag('translations');
		$xml->endTag('controller');
		$listing = false;
		$xml->addFullTag('request', 'addController', true);
		$xml->addFullTag('protocol', $protocol, true);
		$xml->addFullTag('template', $tpl, true);
		$this->saveXML($xml);
	}
示例#15
0
	public function action() 
	{		
		// Objects
		$xml = $this->getXML();
		$user = $this->hasAuthorative();
		$xml = $this->makeMenu($xml);
		$this->_generic->registerLink('Generate', 'SLS_Bo', 'GenerateBo');
		$this->_generic->registerLink('Translation', 'SLS_Bo', 'GenerateBoAction', array("Actions" => "Boi18n"));
		$this->_generic->registerLink('FileUpload', 'SLS_Bo', 'GenerateBoAction', array("Actions" => "BoFileUpload"));
		$this->_generic->registerLink('ManageAdmin', 'SLS_Bo', 'GenerateBoAction', array("Actions" => "BoUserList|BoUserAdd|BoUserDelete|BoUserModify|BoUserStatus"));
		$this->_generic->registerLink('ProjectSettings', 'SLS_Bo', 'GenerateBoAction', array("Actions" => "BoProjectSettings"));
		$this->_generic->registerLink('Manage_Rights', 'SLS_Bo', 'ManageRights');
		$this->_generic->registerLink('Manage_BoMenu', 'SLS_Bo', 'BoMenu');
		$xml->addFullTag("delete",$this->_generic->getFullPath("SLS_Bo","DeleteBo",array(),false));
		$xml->addFullTag("edit",$this->_generic->getFullPath("SLS_Bo","EditBo",array(),false));
		$this->_xmlBo = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/bo.xml"));
		$bos = array();
		
		// Search for user back-office
		$controllersXML = $this->_generic->getControllersXML();
		$controller = array_shift($controllersXML->getTags("//controllers/controller[@isBo='true']/@name"));
		if (!empty($controller))
		{
			$models = $this->getAllModels();			
			for($i=0 ; $i<$count=count($models) ; $i++)
			{
				$model 	= SLS_String::substrAfterFirstDelimiter($models[$i],".");
				$db 	= SLS_String::substrBeforeFirstDelimiter($models[$i],".");
				if ($this->boActionExist($model,$db))
				{
					$this->_generic->useModel($model,$db,"user");
					$class = ucfirst($db)."_".SLS_String::tableToClass($model);
					$object = new $class();
					$bos[$class] = array("db" 			=> $db,
									 	 "className" 	=> $class,
									 	 "tableName" 	=> $object->getTable(),											 	
									 	 "nb_actions" 	=> count($this->getActionsBo($model,$db)));
				}
			}	
		}		
		
		asort($bos,SORT_REGULAR);
		
		$xml->startTag("bos");
		foreach($bos as $bo)
		{
			$categoryExists = $this->_xmlBo->getTag("//sls_configs/entry[@type='category' and entry[@type='table' and @name='".strtolower($bo["db"]."_".$bo["tableName"])."']]/@name");
			
			$xml->startTag("bo");
			$xml->addFullTag("db",strtolower($bo["db"]),true);
			$xml->addFullTag("class",$bo["className"],true);
			$xml->addFullTag("table",$bo["tableName"],true);
			$xml->addFullTag("category",(empty($categoryExists)) ? "X" : $categoryExists,true);
			$xml->addFullTag("nb_actions",$bo["nb_actions"],true);
			$xml->endTag("bo");
		}
		$xml->endTag("bos");		
		
		$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/rights.xml");
		$xmlRights = new SLS_XMLToolbox($pathsHandle);
		$result = $xmlRights->getTags("//sls_configs/entry");
		$xml->addFullTag("admins_exist",(!empty($result)) ? "true" : "false",true);
		
		$xml->startTag("actions");
		$action = array_shift($controllersXML->getTags("//controllers/controller[@isBo='true']/scontrollers/scontroller[@name='Boi18n']"));
		$action2 = array_shift($controllersXML->getTags("//controllers/controller[@isBo='true']/scontrollers/scontroller[@name='BoFileUpload']"));
		$action3 = array_shift($controllersXML->getTags("//controllers/controller[@isBo='true']/scontrollers/scontroller[@name='BoUserList']"));
		$action4 = array_shift($controllersXML->getTags("//controllers/controller[@isBo='true']/scontrollers/scontroller[@name='BoProjectSettings']"));
		$xml->startTag("action");
			$xml->addFullTag("name","Translation",true);
			$xml->addFullTag("icon","boi18n16.png",true);
			$xml->addFullTag("existed",(!empty($action)) ? "true" : "false",true);
		$xml->endTag("action");
		$xml->startTag("action");
			$xml->addFullTag("name","FileUpload",true);
			$xml->addFullTag("icon","boupload16.png",true);
			$xml->addFullTag("existed",(!empty($action2)) ? "true" : "false",true);
		$xml->endTag("action");
		$xml->startTag("action");
			$xml->addFullTag("name","ManageAdmin",true);
			$xml->addFullTag("icon","boadmin16.png",true);
			$xml->addFullTag("existed",(!empty($action3)) ? "true" : "false",true);
		$xml->endTag("action");
		$xml->startTag("action");
			$xml->addFullTag("name","ProjectSettings",true);
			$xml->addFullTag("icon","bosettings16.png",true);
			$xml->addFullTag("existed",(!empty($action4)) ? "true" : "false",true);
		$xml->endTag("action");
		$xml->endTag("actions");
		if (SLS_Sql::getInstance()->tableExists("sls_graph"))
		{
			$this->_generic->useModel("Sls_graph",$this->defaultDb,"sls");
			$className = ucfirst($this->defaultDb)."_Sls_graph";
			$slsGraph = new $className;
			$nbGraph = $slsGraph->countModels("sls_graph");
		}
		else
			$nbGraph = 0;
		$xml->addFullTag("nb_reporting",$nbGraph,true);
		$xml->addFullTag("url_reporting",$this->_generic->getFullPath("SLS_Bo","ReportingBo"),true);
		
		$this->saveXML($xml);
	}
	public function action()
	{
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$user = $this->hasAuthorative();
				
		// Objects
		$sql = SLS_Sql::getInstance();
		$xmlBo = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/bo.xml"));
		$xmlFk = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml"));
		$xmlType = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/types.xml"));
		
		// Get the table & class name
		$tableName 	= SLS_String::substrAfterFirstDelimiter($this->_http->getParam("name"),"_");
		$db	   		= SLS_String::substrBeforeFirstDelimiter($this->_http->getParam("name"),"_");
		$className 	= ucfirst($db)."_".SLS_String::tableToClass($tableName);
		$file 		= ucfirst($db).".".SLS_String::tableToClass($tableName);
		$fileName 	= ucfirst($db).".".SLS_String::tableToClass($tableName).".model.php";
		
		// If current db is not this one
		if ($sql->getCurrentDb() != $db)
			$sql->changeDb($db);
		
		// Remind old properties
		$this->_generic->useModel(SLS_String::tableToClass($tableName),ucfirst(strtolower($db)), "user");
		$object = new $className();
		$oldColumns = $object->getColumns();
		
		// Update Model
		$contentM = $this->getModelSource($tableName,$db);
		file_put_contents($this->_generic->getPathConfig("models").$fileName,$contentM);
		
		// Check Bo
		$controllerBo = $this->_generic->getBo();
		if (!empty($controllerBo))
		{
			$boPath = "//sls_configs/entry[@type='table' and @name='".strtolower($className)."']";
			$boExists = $xmlBo->getTag($boPath."/@type");
			if (empty($boExists))
			{
				$boPath = "//sls_configs/entry/entry[@type='table' and @name='".strtolower($className)."']";
				$boExists = $xmlBo->getTag($boPath);
			}
			if (!empty($boExists))
			{
				$columns = $sql->showColumns($tableName);
				$newColumns = array();
				for($i=0 ; $i<$count=count($columns) ; $i++)
					$newColumns[] = $columns[$i]->Field;
				
				$xmlNodes = '';
				foreach($newColumns as $column)
				{
					$columnExists = $xmlBo->getTag($boPath."/columns/column[@table='".strtolower($className)."' and @name='".$column."']/@name");
					if (empty($columnExists))
					{
						// Avoid pk
						$isPk = ($column == $object->getPrimaryKey() || $column == 'pk_lang') ? true : false;
						// Avoid fk
						$fkExist = $xmlFk->getTag("//sls_configs/entry[@tableFk='".strtolower($db."_".$tableName)."' and @columnFk='".$column."']/@tablePk");
						$isFk = (!empty($fkExist)) ? true : false;
						// Avoid quick edit on type file
						$fileExist = $xmlType->getTag("//sls_configs/entry[@table='".strtolower($db."_".$tableName)."' and @column='".$column."' and (@type='file_all' or @type='file_img')]/@column");
						$isFile = (!empty($fileExist)) ? true : false;
						
						$xmlNodes .= '            <column table="'.strtolower($db."_".$tableName).'" name="'.$column.'" multilanguage="'.(($object->isMultilanguage() && !$isPk) ? "true" : "false").'" displayFilter="true" displayList="'.(($isFk) ? "false" : "true").'" allowEdit="'.(($isPk || $isFk || $isFile) ? "false" : "true").'" allowHtml="false" />'."\n";
					}
				}
				if (!empty($xmlNodes))
				{
					$xmlBo->appendXMLNode($boPath."/columns",$xmlNodes);
				}
				$deprecatedColumns = array_diff($oldColumns,$newColumns);
				foreach($deprecatedColumns as $column)
				{
					$xmlBo->deleteTags($boPath."/columns/column[@table='".strtolower($className)."' and @name='".$column."']",1);
				}
				$xmlBo->saveXML($this->_generic->getPathConfig("configSls")."/bo.xml",$xmlBo->getXML());
				$xmlBo->refresh();
			}
		}
		
		$action_id = $this->_http->getParam("Redirect");
		if ($this->_generic->actionIdExists($action_id))
		{
			$infos = $this->_generic->translateActionId($action_id);			
			$this->_generic->redirect($infos['controller']."/".$infos['scontroller']);
		}
		else
		{
			$controllers = $this->_generic->getTranslatedController("SLS_Bo","EditModel");		
			$this->_generic->redirect($controllers['controller']."/".$controllers['scontroller']."/name/".$db."_".$tableName);
		}
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		
		// Objects
		$sql = SLS_Sql::getInstance();		
		$xml = $this->getXML();		
		$xml = $this->makeMenu($xml);
		
		// Actions
		$xml->addFullTag("delete",$this->_generic->getFullPath("SLS_Bo","DeleteModel",array(),false));
		$xml->addFullTag("delete_bearer",$this->_generic->getFullPath("SLS_Bo","DeleteBearerTable",array(),false));
		$xml->addFullTag("delete_type",$this->_generic->getFullPath("SLS_Bo","DeleteType",array(),false));
		$xml->addFullTag("edit_type",$this->_generic->getFullPath("SLS_Bo","EditType",array(),false));
		$xml->addFullTag("delete_fk",$this->_generic->getFullPath("SLS_Bo","DeleteForeignKey",array(),false));
		$xml->addFullTag("edit_fk",$this->_generic->getFullPath("SLS_Bo","EditForeignKey",array(),false));
		$xml->addFullTag("update",$this->_generic->getFullPath("SLS_Bo","UpdateModel",array(),false));		
		$xml->addFullTag("descriptions",$this->_generic->getFullPath("SLS_Bo","UpdateDescription",array(),false));
		
		// Get the table & class name
		$table = SLS_String::substrAfterFirstDelimiter($this->_http->getParam("name"),"_");
		$db	   = SLS_String::substrBeforeFirstDelimiter($this->_http->getParam("name"),"_");
		$class = ucfirst($db)."_".SLS_String::tableToClass($table);
		$file  = ucfirst($db).".".SLS_String::tableToClass($table);
		
		// If current db is not this one
		if ($sql->getCurrentDb() != $db)
			$sql->changeDb($db);
		
		// Get generic object
		$this->_generic->useModel(SLS_String::tableToClass($table),$db,"user");
		$object = new $class();
		
		// Get description's table
		$description = $object->getTableComment($table);	
		$columnsInfos = $sql->showColumns($table);
		
		// Get object's infos
		$columns = array();
		$columnsP = $object->getParams();
		$pk = $object->getPrimaryKey();
		$multilanguage = $object->isMultilanguage();
		$xml->startTag("model");
		$xml->addFullTag("table",$table,true);
		$xml->addFullTag("description",(SLS_String::contains($description,"InnoDB free")) ? SLS_String::substrBeforeFirstDelimiter($description,"; InnoDB free") : $description,true);
		$xml->addFullTag("db",$db,true);
		$xml->addFullTag("class",$class,true);
		$xml->addFullTag("pk",$pk,true);
		$xml->addFullTag("multilanguage",($multilanguage) ? "true" : "false",true);
		$xml->startTag("columns");
		$cursor = 0;
		foreach($columnsP as $column => $value)
		{
			$xml->startTag("column");
			$xml->addFullTag("name",$column,true);
			array_push($columns,$column);
			$fk = "";
			$sType = "";
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml");
			$xmlFk = new SLS_XMLToolbox($pathsHandle);			
			$res = $xmlFk->getTagsByAttributes("//sls_configs/entry",array("tableFk","columnFk"),array($db."_".$table,$column));
			if (!empty($res))
			{
				$tableTmp = substr($res,(strpos($res,'tablePk="')+9),(strpos($res,'"/>')-(strpos($res,'tablePk="')+9)));
				$fk = SLS_String::substrAfterFirstDelimiter($tableTmp,"_");				
			}
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/types.xml");
			$xmlType = new SLS_XMLToolbox($pathsHandle);						
			$res = $xmlType->getTagsByAttributes("//sls_configs/entry",array("table","column"),array($db."_".$table,$column));
			if (!empty($res))
			{
				$sType = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($res,'type="'),'"/>');
				// If specific type numeric and native type too
				if (SLS_String::startsWith($sType,"num_") && $this->containsRecursive($columnsInfos[$cursor]->Type,array("int","float","double","decimal","real")))
					$xml->addFullTag("allow_to_delete_type","false",true);
			}
			
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/filters.xml");
			$xmlFilter = new SLS_XMLToolbox($pathsHandle);			
			$results = $xmlFilter->getTagsAttributes("//sls_configs/entry[@table='".$db."_".$table."' and @column='".$column."']",array("filter","hash"));			
			$xml->startTag("filters");
			for($i=0 ; $i<$count=count($results) ; $i++)
			{
				$filter = $results[$i]["attributes"][0]["value"];
				$result = $results[$i]["attributes"][1]["value"];
				
				$xml->startTag("filter");
					$xml->addFullTag("name",$filter.((!empty($result)) ? ' ['.$result.']' : ''),true);
					$xml->addFullTag("url_delete",$this->_generic->getFullPath("SLS_Bo","DeleteFilter",array(array("key"=>"table","value"=>$this->_http->getParam("name")),array("key"=>"column","value"=>$column),array("key"=>"filter","value"=>$filter))),true);
				$xml->endTag("filter");
			}
			$xml->endTag("filters");
			$xml->addFullTag("fk",$fk,true);
			$xml->addFullTag("type",ucfirst($sType),true);
			$xml->addFullTag("comment",$object->getColumnComment($column),true);
			$xml->endTag("column");
			
			$cursor++;
		}
		$xml->endTag("columns");
		$xml->addFullTag("url_add_type",$this->_generic->getFullPath("SLS_Bo","AddType",array(0=>array("key"=>"name","value"=>$db."_".$table))),true);
		$xml->addFullTag("url_add_filter",$this->_generic->getFullPath("SLS_Bo","AddFilter",array(0=>array("key"=>"name","value"=>$db."_".$table))),true);
		$xml->addFullTag("url_add_fk",$this->_generic->getFullPath("SLS_Bo","AddForeignKey",array(0=>array("key"=>"name","value"=>$db."_".$table))),true);
		
		// Get the source of the current model
		$xml->addFullTag("current_source",str_replace("\t","    ",file_get_contents($this->_generic->getPathConfig("models").$file.".model.php")),true);
		
		// Get the source of the current table
		if (!$sql->tableExists($table))
			$xml->addFullTag("current_table",-1,true);
		else
		{
			$columns = $sql->showColumns($table);					
			$tableName = $table;
			$currentTable = array("table"=>$db.".".$tableName,"errors"=>array());			
			$className = ucfirst($db)."_".SLS_String::tableToClass($tableName);
			$fileName = ucfirst($db).".".SLS_String::tableToClass($table).".model.php";
			$primaryKey = "";
			$multiLanguage = 'false';
			
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/types.xml");
			$xmlType = new SLS_XMLToolbox($pathsHandle);
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml");
			$xmlFk = new SLS_XMLToolbox($pathsHandle);
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/filters.xml");
			$xmlFilter = new SLS_XMLToolbox($pathsHandle);
			
			// Get source
			$contentM = $this->getModelSource($tableName,$db);
			
			// Is data bearer
			$xmlBearer = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/bearers.xml"));
			$result = array_shift($xmlBearer->getTagsAttributes("//sls_configs/entry[@tableBearer='".$class."']",array("table1")));
			$xml->addFullTag("is_data_bearer",(!empty($result)) ? $result["attributes"][0]["value"] : "false",true);
			
			// Save the new source
			$xml->addFullTag("current_table",str_replace("\t","    ",$contentM),true);
			$xml->addFullTag("url_data_bearer",$this->_generic->getFullPath("SLS_Bo","AddBearerTable",array(array("key"=>"name","value"=>$this->_http->getParam("name")))),true);
		}		
		$xml->endTag("model");
		$this->saveXML($xml);
	}
	/**
	 * Read recursively path & sub-paths to include components files used by currect action controller
	 *
	 * @access private
	 * @param string $path the root path
	 * @param string $type the type ('core' || 'user')
	 * @since 1.0
	 */
	private function recursiveStaticLoading($path, $type)
	{
		$controllersXML = $this->_generic->getControllersXML();
		
		if ($this->_isCache)
		{			
			$staticsHandle = file_get_contents($this->_generic->getPathConfig("configSecure")."cache.xml");
			$xmlCache = new SLS_XMLToolbox($staticsHandle);	
			$files = $xmlCache->getTags("//components/".$type."/controller/file");
			$names = $xmlCache->getTags("//components/".$type."/controller/name");
			for($i=0;$i<count($files);$i++)
			{				
				$components = array_shift($controllersXML->getTagsAttributes("//controllers/controller/scontrollers/scontroller[@id='".$this->_generic->getActionId()."']",array("components")));				
				if (!empty($components))
				{
					$components = explode(",",$components["attributes"][0]["value"]);
					$components = array_map("trim",$components);
					$components = array_map("strtolower",$components);					
				}
				else
					$components = array();
				
				if (empty($components) || in_array(strtolower(trim(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($names[$i], "/"), "Controller"))),$components))
				{
					$this->_generic->_time_checkpoint = microtime(true);
					include_once($this->_generic->getRoot().$files[$i]);
					$name = $names[$i];
					$xml = "";
					
					// Component cache enabled ?
					$componentsName = strtolower(SLS_String::substrBeforeFirstDelimiter($name,"Controller"));					
					$componentsCacheVisibility = $this->_cache->getObject($componentsName,"components","visibility");
					$componentsCacheResponsive = $this->_cache->getObject($componentsName,"components","responsive");
					$componentsCacheExpiration = $this->_cache->getObject($componentsName,"components","expire");					
					$componentsCache = false;					
					
					if ($this->_generic->getSide() == "user" &&
						$this->_generic->getGenericControllerName() != "Default" &&
						!$this->_generic->isBo() && 
						in_array($componentsCacheVisibility,array("public","private")))
					{
						$componentsCache = true;
						
						// Partial xml cached
						if (false !== ($componentsCached = $this->_cache->getCachePartial($componentsCacheExpiration,"component",$componentsName,$componentsCacheVisibility,$componentsCacheResponsive)))
						{				
							$xml = $componentsCached;
							$this->_generic->logTime($this->_generic->monitor($this->_generic->_time_checkpoint),"Cache (Partial): Executing Component Controller", "Controller: ".SLS_String::substrBeforeLastDelimiter($name,"Controller"),"Controller Component");
						}
					}
					
					if (empty($xml))
					{					
						$classObj = new $name();
						$xml = $classObj->getXML();
						$this->_generic->logTime($this->_generic->monitor($this->_generic->_time_checkpoint),"Executing Component Controller", "Controller: ".SLS_String::substrBeforeLastDelimiter($name,"Controller"),"Controller Component");
						
						// Save partial xml component cache
						if ($componentsCache)						
							$this->_cache->saveCachePartial($xml,"component",$componentsName,$componentsCacheVisibility,$componentsCacheResponsive);						
					}
					
					$this->_xmlToolBox->appendXMLNode("//Components/".$type, $xml);					
				}				
			}
		}
		else 
		{
			$searchedExt = array('php');
			$arrayResult = array();
			$arrayResult = $this->_generic->recursiveReadDir($path, $arrayResult, $searchedExt);
			
			$this->_cacheXML->startTag($type);
			for($i=0;$i<$count = count($arrayResult);$i++)
			{
				$components = array_shift($controllersXML->getTagsAttributes("//controllers/controller/scontrollers/scontroller[@id='".$this->_generic->getActionId()."']",array("components")));
				if (!empty($components))
				{
					$components = explode(",",$components["attributes"][0]["value"]);
					$components = array_map("trim",$components);
					$components = array_map("strtolower",$components);					
				}
				else
					$components = array();
				
				$this->_cacheXML->startTag("controller");				
				include_once($arrayResult[$i]);
				$componentName = array_shift(explode(".", SLS_String::substrAfterLastDelimiter($arrayResult[$i], "/")))."Controller";
				
				if (class_exists($componentName))
				{
					$this->_cacheXML->addFullTag("file", $arrayResult[$i], true);
					$this->_cacheXML->addFullTag("name", $componentName, true);
					if (empty($components) || in_array(strtolower(trim(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($arrayResult[$i], "/"), ".controller.php"))),$components))
					{
						$this->_generic->_time_checkpoint = microtime(true);
						$classObj = new $componentName();						
						$this->_xmlToolBox->appendXMLNode("//Components/".$type, $classObj->getXML());
						$this->_generic->logTime($this->_generic->monitor($this->_generic->_time_checkpoint),"Executing Component Controller", "Controller: ".SLS_String::substrBeforeLastDelimiter($componentName,"Controller"),"Controller Component");
					}
				}
				$this->_cacheXML->endTag("controller");
			}
			$this->_cacheXML->endTag($type);				
		}
	}
	public function action()
	{
		$user 	= $this->hasAuthorative();
		$xml 	= $this->getXML();
		$xml	= $this->makeMenu($xml);
		$siteXML = $this->_generic->getSiteXML();
		
		$errors = array();
		$aliases = array();
		$domains = array();
		
		// Prod Deployment		
		$env = $this->_http->getParam("Env");
		if (empty($env))
			$env = "prod";
		$finalFile = ($this->_http->getParam("ProdDeployment") == "true") ? "site_".$env.".xml" : "site.xml";
		$isInBatch = ($this->_http->getParam("CompleteBatch") == "true") ? true : false;
		$xml->addFullTag("is_batch",($isInBatch) ? "true" : "false",true);
		$xml->addFullTag("is_prod",($this->_http->getParam("ProdDeployment") == "true") ? "true" : "false",true);
		$xml->addFullTag("env",$env,true);
		
		// Get default values
		if ($this->_http->getParam("ProdDeployment") == "true" && file_exists($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/site_".$env.".xml"))
		{			
			$xmlSite = new SLS_XMLToolbox(file_get_contents($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/site_".$env.".xml"));
			
			$defaultDomain 				= $xmlSite->getTag("//configs/domainName/domain");
			$defaultProject				= $xmlSite->getTag("//configs/projectName");
			$defaultVersion				= $xmlSite->getTag("//configs/versionName");
			$defaultExtension			= $xmlSite->getTag("//configs/defaultExtension");
			$defaultCharset				= $xmlSite->getTag("//configs/defaultCharset");
			$defaultDoctype				= $xmlSite->getTag("//configs/defaultDoctype");
			$timezone_area				= SLS_String::substrBeforeFirstDelimiter($xmlSite->getTag("//configs/defaultTimezone"),"/");
			$timezone_city				= SLS_String::substrAfterFirstDelimiter($xmlSite->getTag("//configs/defaultTimezone"),"/"); 
			$defaultLang 				= $xmlSite->getTag("//configs/defaultLang");
			$defaultdomainSessionShare 	= $xmlSite->getTag("//configs/domainSession");
		}
		else
		{
			$defaultDomain 				= $this->_generic->getSiteConfig("domainName");
			$defaultProject				= $this->_generic->getSiteConfig("projectName");
			$defaultVersion				= $this->_generic->getSiteConfig("versionName"); 
			$defaultExtension			= $this->_generic->getSiteConfig("defaultExtension");
			$defaultCharset				= $this->_generic->getSiteConfig("defaultCharset");
			$defaultDoctype				= $this->_generic->getSiteConfig("defaultDcotype");
			$timezone_area				= SLS_String::substrBeforeFirstDelimiter($this->_generic->getSiteConfig("defaultTimezone"),"/");
			$timezone_city				= SLS_String::substrAfterFirstDelimiter($this->_generic->getSiteConfig("defaultTimezone"),"/"); 
			$defaultLang 				= $this->_generic->getSiteConfig("defaultLang");
			$defaultdomainSessionShare 	= $this->_generic->getSiteConfig("domainSession");
		}
		
		$reload 			= $this->_http->getParam("reload");

		$charsetsXML = new SLS_XMLToolBox(file_get_contents($this->_generic->getPathConfig('configSls')."charset.xml"));
		$charsets = array_map('strtoupper', $charsetsXML->getTags('//sls_configs/charset/code'));
		$handle2 = file_get_contents($this->_generic->getPathConfig("configSls").'timezone.xml');
		$xml->addFullTag("timezones", SLS_String::substrBeforeLastDelimiter(SLS_String::substrAfterFirstDelimiter($handle2, "<sls_configs>"), "</sls_configs>"), false);
		
		$langs = $this->_generic->getSiteXML()->getTags('//configs/langs/name');
			
		if ($reload == "true")
		{			
			$domains = 	$siteXML->getTagsAttributes("//configs/domainName/domain",array("alias"));			
			for($i=0 ; $i<$count=count($domains) ; $i++)
				array_push($aliases,$domains[$i]["attributes"][0]["value"]);
			
			// Get New Parameters
			$exportConfig	= $this->_http->getParam('export');
			
			$domains = array();
			foreach($aliases as $alias)
			{
				$domain = SLS_String::trimSlashesFromString($this->_http->getParam("domain_".$alias, "post"));
				if (SLS_String::endsWith(trim($domain),"/"))
					$domain = SLS_String::substrBeforeLastDelimiter(trim($domain),"/");
				$domains[$alias]= $domain;
			}	
			
			$postProject		= SLS_String::trimSlashesFromString($this->_http->getParam("project", "post"));
			$postVersion		= SLS_String::trimSlashesFromString($this->_http->getParam("version", "post"));
			$postExtension 		= SLS_String::trimSlashesFromString($this->_http->getParam("extension", "post"));
			$postCharset		= SLS_String::trimSlashesFromString($this->_http->getParam("charset", "post"));
			$postDoctype		= SLS_String::trimSlashesFromString($this->_http->getParam("doctype", "post"));
			$timezone_area		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_timezone_area'));
			$timezone_city		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_timezone_area_'.$timezone_area));
			$postLang			= SLS_String::trimSlashesFromString($this->_http->getParam("lang", "post"));
			$domainSessionShare	= SLS_String::trimSlashesFromString($this->_http->getParam("domainSession", "post"));

			if ($this->_http->getParam("domainSessionActive") == "")
				$domainSessionShare = "";		

			foreach($domains as $alias => $domain)
				if (empty($domain))
					array_push($errors, "The Domain name is required for the domain alias ".$alias);
			if (empty($postProject))
				array_push($errors, "The project Name is required");
			if (empty($postVersion))
				array_push($errors, "The version Name is required");
			if (empty($postExtension))
				array_push($errors, "The extension is required");
			if (!in_array($postCharset, $charsets))
				array_push($errors, "The Charset selected is incorrect");
			if (empty($postDoctype))
				array_push($errors, "The doctype is required");
			if (empty($timezone_area) || empty($timezone_city))
				array_push($errors,"You must choose your default timezone");
			if (!in_array($postLang, $langs))
				array_push($errors, "The Default lang selected is incorrect");
			if ($this->_http->getParam("domainSessionActive") != "" && empty($domainSessionShare))
				array_push($errors,"You need to fill the domain pattern from which you want to share session");
			if (empty($errors))
			{
				foreach($domains as $alias => $domain)
					$siteXML->setTag("//configs/domainName/domain[@alias='".$alias."']", $domain, true);
				if ($defaultProject != $postProject)
					 $siteXML->setTag("//configs/projectName", $postProject, true);
				if ($defaultVersion != $postVersion)
					 $siteXML->setTag("//configs/versionName", $postVersion, true);
				if ($defaultExtension != $postExtension)
					 $siteXML->setTag("//configs/defaultExtension", $postExtension, true);
				if ($defaultCharset != $postCharset)
					 $siteXML->setTag("//configs/defaultCharset", $postCharset, true);
				if ($defaultDoctype != $postDoctype)
					 $siteXML->setTag("//configs/defaultDoctype", $postDoctype, true);
				if ($defaultTimezone != $timezone_area."/".$timezone_city)
					 $siteXML->setTag("//configs/defaultTimezone", $timezone_area."/".$timezone_city, true);
				if ($defaultLang != $postLang)
					 $siteXML->setTag("//configs/defaultLang", $postLang, true);
				if ($defaultdomainSessionShare != $domainSessionShare)
					$siteXML->setTag("//configs/domainSession", $domainSessionShare, true);
				if ($exportConfig == "on")
				{
					$date = gmdate('D, d M Y H:i:s');
					header("Content-Type: text/xml"); 
					header('Content-Disposition: attachment; filename='.$finalFile);
					header('Last-Modified: '.$date. ' GMT');
					header('Expires: ' .$date);
					// For This F**k'in Browser
					if(preg_match('/msie|(microsoft internet explorer)/i', $_SERVER['HTTP_USER_AGENT']))
					{
						header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
						header('Pragma: public');
					}
					else
						header('Pragma: no-cache');
					
					print($siteXML->getXML());
					exit; 
				}
				else
				{
					$siteXML->refresh();
					@file_put_contents($this->_generic->getPathConfig("configSecure").$finalFile, $siteXML->getXML());					
					if ($isInBatch)
						$this->_generic->forward("SLS_Bo","DataBaseSettings",array(array("key"=>"ProdDeployment","value"=>"true"),array("key"=>"CompleteBatch","value"=>"true"),array("key"=>"Env","value"=>$env)));
					else if ($this->_http->getParam("ProdDeployment") == "true")
						$this->_generic->forward("SLS_Bo","ProductionDeployment");
				}
			}
			else 
			{
				$xml->startTag('errors');
				foreach ($errors as $error)				
					$xml->addFullTag('error', $error);				
				$xml->endTag('errors');
			}
	
		}
		$this->_generic->eraseCache('Site');
		$xml->startTag("charsets");
		foreach ($charsets as $charset)
			$xml->addFullTag('charset', $charset, true);
		$xml->endTag("charsets");
		
		$xml->startTag("langs");
			foreach ($langs as $lang)
			$xml->addFullTag('lang', $lang, true);
		$xml->endTag("langs");
		
		$xmlSite = (file_exists($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/site_".$env.".xml")) ? new SLS_XMLToolbox(file_get_contents($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/site_".$env.".xml")) : null;
		$xml->startTag("current_values");
			if ($this->_http->getParam("ProdDeployment") == "true" && file_exists($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/site_".$env.".xml"))
				$domains = 	$xmlSite->getTagsAttributes("//configs/domainName/domain",array("alias","default","lang"));
			else
				$domains = 	$siteXML->getTagsAttributes("//configs/domainName/domain",array("alias","default","lang"));
			
			$xml->startTag("domains");
			for($i=0 ; $i<$count=count($domains) ; $i++)
			{
				$alias = $domains[$i]["attributes"][0]["value"];
				$default = ($domains[$i]["attributes"][1]["value"] == 1) ? true : false;
				$domain_lang = $domains[$i]["attributes"][2]["value"];
				$xml->startTag("domain");
					$xml->addFullTag("alias",$alias,true);
					$xml->addFullTag("default",($default) ? "true" : "false",true);
					$xml->addFullTag("domain",$domains[$i]["value"],true);
					$xml->addFullTag("lang",$domain_lang,true);
					$xml->addFullTag("delete_url",$this->_generic->getFullPath("SLS_Bo","DeleteDomain",array(array("key"=>"alias","value"=>$alias))),true);
				$xml->endTag("domain");
			}
			$xml->endTag("domains");
			$xml->addFullTag("project", ($this->_http->getParam("ProdDeployment") == "true" && file_exists($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/site_".$env.".xml")) ? $xmlSite->getTag("//configs/projectName") : $this->_generic->getSiteConfig("projectName"), true);
			$xml->addFullTag("version", ($this->_http->getParam("ProdDeployment") == "true" && file_exists($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/site_".$env.".xml")) ? $xmlSite->getTag("//configs/versionName") : $this->_generic->getSiteConfig("versionName"), true);
			$xml->addFullTag("extension", ($this->_http->getParam("ProdDeployment") == "true" && file_exists($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/site_".$env.".xml")) ? $xmlSite->getTag("//configs/defaultExtension") :$this->_generic->getSiteConfig("defaultExtension"), true);
			$xml->addFullTag("charset", ($this->_http->getParam("ProdDeployment") == "true" && file_exists($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/site_".$env.".xml")) ? $xmlSite->getTag("//configs/defaultCharset") :$this->_generic->getSiteConfig("defaultCharset"), true);
			$xml->addFullTag("doctype", ($this->_http->getParam("ProdDeployment") == "true" && file_exists($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/site_".$env.".xml")) ? $xmlSite->getTag("//configs/defaultDoctype") :$this->_generic->getSiteConfig("defaultDoctype"), true);
			$xml->addFullTag("lang", ($this->_http->getParam("ProdDeployment") == "true" && file_exists($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/site_".$env.".xml")) ? $xmlSite->getTag("//configs/defaultLang") :$this->_generic->getSiteConfig("defaultLang"), true);
			$xml->addFullTag("domain_session", ($this->_http->getParam("ProdDeployment") == "true" && file_exists($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/site_".$env.".xml")) ? $xmlSite->getTag("//configs/domainSession") : ((is_null($this->_generic->getSiteConfig("domainSession"))) ? "" : $this->_generic->getSiteConfig("domainSession")), true);
			$xml->startTag("timezone");
				$xml->addFullTag("area",$timezone_area,true);
				$xml->addFullTag("city",$timezone_city,true);
			$xml->endTag("timezone");
		$xml->endTag("current_values");
		
		$xml->addFullTag("add_domain_url",$this->_generic->getFullPath("SLS_Bo","AddDomain"),true);
		
		$environments = $this->getEnvironments();
		$xml->startTag("environments");
		foreach($environments as $environment)
			$xml->addFullTag("environment",$environment,true);
		$xml->endTag("environments");
		
		$this->saveXML($xml);		
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$sql = SLS_Sql::getInstance();		
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$errors = array();
		
		// Get the table name
		$table = SLS_String::substrAfterFirstDelimiter($this->_http->getParam("name"),"_");
		$db	   = SLS_String::substrBeforeFirstDelimiter($this->_http->getParam("name"),"_");
		$class = ucfirst($db)."_".SLS_String::tableToClass($table);
		$file  = ucfirst($db).".".SLS_String::tableToClass($table);
		
		// If current db is not this one
		if ($sql->getCurrentDb() != $db)
			$sql->changeDb($db);
		
		if ($sql->tableExists($table))
		{
			if ($this->_http->getParam("reload") == "true")
			{
				$columnWanted = $this->_http->getParam("column");
				$filterWanted = $this->_http->getParam("filter");
				
				$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml");
				$xmlFk = new SLS_XMLToolbox($pathsHandle);
				$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/types.xml");
				$xmlType = new SLS_XMLToolbox($pathsHandle);
				$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/filters.xml");
				$xmlFilter = new SLS_XMLToolbox($pathsHandle);
				
				$result = $xmlFilter->getTags("//sls_configs/entry[@table='".$db."_".$table."' and @column='".$columnWanted."' and @filter='".$filterWanted."']");
				
				// If an entry already exists in the XML, delete this record
				if (!empty($result))
				{
					$xmlTmp = $xmlFilter->deleteTags("//sls_configs/entry[@table='".$db."_".$table."' and @column='".$columnWanted."' and @filter='".$filterWanted."']");					
					$xmlFilter->saveXML($this->_generic->getPathConfig("configSls")."/filters.xml",$xmlTmp);
					$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/filters.xml");
					$xmlFilter = new SLS_XMLToolbox($pathsHandle);
				}
				
				if ($filterWanted == "hash")
				{
					$passwordHash = $this->_http->getParam("hash");
					
					// Save it into the XML
					$xmlNode = '<entry table="'.$db.'_'.$table.'" column="'.$columnWanted.'" hash="'.$passwordHash.'" filter="'.$filterWanted.'" />';				
					$xmlFilter->appendXMLNode("//sls_configs",$xmlNode);
					$xmlFilter->saveXML($this->_generic->getPathConfig("configSls")."/filters.xml",$xmlFilter->getXML());
				}				
				else
				{
					// Save it into the XML
					$xmlNode = '<entry table="'.$db.'_'.$table.'" column="'.$columnWanted.'" filter="'.$filterWanted.'" />';				
					$xmlFilter->appendXMLNode("//sls_configs",$xmlNode); 
					$xmlFilter->saveXML($this->_generic->getPathConfig("configSls")."/filters.xml",$xmlFilter->getXML());
				}
				
				// Update model
				$this->_generic->goDirectTo("SLS_Bo","UpdateModel",array(array("key"=>"name","value"=>$this->_http->getParam("name"))));		
			}
			
			// Get generic object
			$this->_generic->useModel($table,$db,"user");
			$object = new $class();
			
			// Get object's infos
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml");
			$xmlFk = new SLS_XMLToolbox($pathsHandle);
			$columnsP = $object->getParams();
			$pk = $object->getPrimaryKey();
			$multilanguage = $object->isMultilanguage();		
			$xml->startTag("model");
			$xml->addFullTag("table",$table,true);
			$xml->addFullTag("db",$db,true);
			$xml->addFullTag("class",$class,true);
			$xml->addFullTag("pk",$pk,true);
			$xml->addFullTag("multilanguage",($multilanguage) ? "true" : "false",true);
			$xml->startTag("columns");
			foreach($columnsP as $column => $value)
			{
				$res = $xmlFk->getTags("//sls_configs/entry[@tableFk='".$db."_".$table."' and @columnFk='".$column."']/@tablePk");				
				if ($object->getPrimaryKey() != $column && $column != "pk_lang" && empty($res))			
					$xml->addFullTag("column",$column,true);
			}
			$xml->endTag("columns");
			$xml->endTag("model");
		}
		else
		{
			$xml->addFullTag("error","Sorry this table doesn't exist anymore",true);
		}
		
		$this->saveXML($xml);
	}
示例#21
0
	/**
	 * Protect a sql column
	 * 
	 * @param string $col the column to protect
	 * @return string column protected
	 * @since 1.0.7
	 * @example
     * protectColumn("news_id")
     * // will produce "`news_id`"
     * protectColumn("news.news_id")
     * // will produce "`news`.`news_id`"
	 */
	public function protectColumn($col)
	{
		return ((SLS_String::contains($col,'.'))
				? self::ESC.SLS_String::substrBeforeFirstDelimiter($col,'.').self::ESC.'.'.self::ESC.SLS_String::substrAfterFirstDelimiter($col,'.').self::ESC
				: self::ESC.$col.self::ESC);
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		
		$param	 		= $this->_http->getParam("class");		
		$model			= SLS_String::substrAfterFirstDelimiter($param,"_");
		$alias			= SLS_String::substrBeforeFirstDelimiter($param,"_");		
		$filters 		= $this->_http->getParam("filters");
		$columns 		= $this->_http->getParam("columns");
		$column 		= $this->_http->getParam("column");
		$group	 		= $this->_http->getParam("group");
		$order 			= $this->_http->getParam("order");
		$start	 		= $this->_http->getParam("start");
		$length 		= $this->_http->getParam("length");
		$action_add 	= $this->_http->getParam("action_add");
		$action_modify 	= $this->_http->getParam("action_modify");
		$action_delete 	= $this->_http->getParam("action_delete");
		$action_clone 	= $this->_http->getParam("action_clone");
		$action_email 	= $this->_http->getParam("action_email");
		$join 			= $this->_http->getParam("join");
				
		if (!empty($order) && !empty($column))
		{
			$orderA = array("column" 	=> $column,
							"order"		=> $order);
		}
		else
			$orderA = array();
		if (is_numeric($start) && is_numeric($length) && $start >= 0 && $length > 0)
		{
			$limitA = array("start" 	=> $start,
							"length" 	=> $length);
		}
		else
			$limitA = array();
			
		if (is_array($join))
		{
			$newJoin = array();
			foreach($join as $cur_join)
			{
				$this->_generic->useModel(SLS_String::tableToClass($cur_join),$alias,"user");
				$class = ucfirst($alias)."_".SLS_String::tableToClass($cur_join);
				$object = new $class();
				$newJoin[] = array("table" => $cur_join, "column" => $object->getPrimaryKey(), "mode" => "left");
			}
			$join = $newJoin;
		}
			
		$join = (empty($join)) ? "" : (is_array($join) ? $join : "");
		
		$actions = array("add" 		=> ($action_add 	== "true") 	? true : false,
						 "modify" 	=> ($action_modify 	== "true") 	? true : false,
						 "delete" 	=> ($action_delete 	== "true") 	? true : false,
						 "clone" 	=> ($action_clone 	== "true") 	? true : false,
						 "email" 	=> ($action_email 	== "true") 	? true : false);
		
		$controllersXML = $this->_generic->getControllersXML();
		$controller 	= array_shift($controllersXML->getTags("//controllers/controller[@isBo='true']/@name"));
		
		$this->createActionBoList($controller,$model,$alias,$columns,$filters,$group,$orderA,$limitA,$join,$actions);
		
		$controllers = $this->_generic->getTranslatedController("SLS_Bo","EditBo");
		$this->_generic->redirect($controllers["controller"]."/".$controllers["scontroller"]."/name/".$param.".sls");
	}
	public function action()
	{
		$user 	= $this->hasAuthorative();
		$xml 	= $this->getXML();
		$xml 	= $this->makeMenu($xml);
		$dbXML 	= $this->_generic->getDbXML();
		
		// Check if db exists
		$alias = rawurldecode($this->_http->getParam("alias"));
		$result = $dbXML->getTagsAttribute("//dbs/db","alias");
		$dbs = array();
		for($i=0 ; $i<$count=count($result) ; $i++)
			array_push($dbs,$result[$i]["attribute"]);
			
		if (in_array($alias,$dbs))
		{
			// Check if it is not the default db
			$result = array_shift($this->_generic->getDbXML()->getTagsAttribute("//dbs/db[@isDefault='true']","alias"));
			if ($alias != $result["attribute"])
			{	
				$files = array();
				$bos = array();
				$xml->addFullTag("db_exists","true",true);
				
				$controllerXML = $this->_generic->getControllersXML();
				$genericBo = array_shift($controllerXML->getTags("//controllers/controller[@isBo='true']/@name"));
				
				// List files which will be deleted
				$models = $this->getAllModels();
				$xml->startTag("models");
				foreach($models as $model)
				{
					if (SLS_String::startsWith($model,$alias))
					{
						$xml->startTag("model");
						$xml->addFullTag("label",SLS_String::substrAfterFirstDelimiter($model,"."),true);
						$xml->addFullTag("file",ucfirst($model),true);
						array_push($files,$this->_generic->getPathConfig("models").ucfirst($model).".model.php");
						array_push($files,$this->_generic->getPathConfig("modelsSql").ucfirst($model).".sql.php");
						
						$actionsBo = $this->getActionsBo(SLS_String::substrAfterFirstDelimiter($model,"."),$alias);
						$xml->startTag("bos");
						foreach($actionsBo as $actionBo)
						{
							$tmp = array("model"=>SLS_String::substrAfterFirstDelimiter($model,"."),"action"=>strtolower(SLS_String::substrBeforeFirstDelimiter($actionBo,ucfirst($alias)."_")),"alias"=>$alias);							
							array_push($bos,$tmp);
							$xml->startTag("bo");
							$xml->addFullTag("label",SLS_String::substrBeforeFirstDelimiter($actionBo,ucfirst($alias)."_"),true);
							$xml->addFullTag("file",$actionBo.".controller.php",true);
							$xml->endTag("bo");
						}
						$xml->endTag("bos");
						$xml->endTag("model");
					}
				}
				$xml->endTag("models");
				
				if ($this->_http->getParam("reload") == "true")
				{
					$password = SLS_String::trimSlashesFromString($this->_http->getParam("password", 'post'));
					$login = SLS_String::trimSlashesFromString($this->_http->getParam("login", 'post'));
					
					$slsXml = $this->_generic->getCoreXML('sls');
					$passXML = array_shift($slsXml->getTags("//sls_configs/auth/users/user[@login='******' and @level='0']/@pass"));
					
					if (!empty($passXML) && $passXML == sha1($password))
					{						
						// Delete files bo
						foreach($bos as $bo)
							$this->deleteActionBo($bo["model"],$bo["action"],$bo["alias"]);
						// Delete files model
						foreach($files as $file)
							@unlink($file);
						// Delete config
						$dbXML->deleteTags("//dbs/db[@alias='".$alias."']");						
						$dbXML->saveXML($this->_generic->getPathConfig("configSecure")."db.xml");
						
						$controllers = $this->_generic->getTranslatedController("SLS_Bo","DataBaseSettings");
						$this->_generic->redirect($controllers["controller"]."/".$controllers["scontroller"].".sls");
					}
					else					
						$xml->addFullTag("incorrect_account","true",true);					
				}
				
				
				$xml->addFullTag("database",$alias,true);
			}
			else
			{
				$xml->startTag("errors");
				$xml->addFullTag("error","You can't delete the default database",true);
				$xml->endTag("errors");
			}
		}
		else
		{
			$xml->startTag("errors");
			$xml->addFullTag("error","This database can't be found",true);
			$xml->endTag("errors");
		}
		
		$this->saveXML($xml);
	}	
	public function action()
	{
		set_time_limit(0);
		
		$user = $this->hasAuthorative();
		$errors = array();
		$sql = SLS_Sql::getInstance();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);

		// Get all models
		$models = array();
		$handle = opendir($this->_generic->getPathConfig("models"));
		while (false !== ($file = readdir($handle)))
		{
			if (!is_dir($this->_generic->getPathConfig("models")."/".$file) && substr($file, 0, 1) != ".") 
			{
				$modelExploded = explode(".",$file);
				array_push($models,strtolower($modelExploded[0]).".".$modelExploded[1]);
			}
		}
		
		// If reload
		if ($this->_http->getParam("reload")=="true")
		{
			// Get the tables dude wants to generate
			$tablesG = ($this->_http->getParam("tables")=="") ? array() : $this->_http->getParam("tables");
			
			// Foreach tables, generate model
			foreach($tablesG as $tableG)
			{
				$db = Sls_String::substrBeforeFirstDelimiter($tableG,".");
				$table = Sls_String::substrAfterFirstDelimiter($tableG,".");
				
				// Change db if it's required
				if ($sql->getCurrentDb() != $db)
					$sql->changeDb($db);
				
				// If table exists
				if ($sql->tableExists($table))
				{					
					$columns = $sql->showColumns($table);
					$tableName = $table;
					$currentTable = array("table"=>$db.".".$tableName,"errors"=>array());
					$fieldsOk = true;
					$className = ucfirst($db)."_".SLS_String::tableToClass($tableName);
					$fileName  = ucfirst($db).".".SLS_String::tableToClass($table).".model.php";					
															
					for($i=0 ; $i<$count=count($columns) ; $i++)
					{						
						// Check forbidden chars
						if (SLS_String::removePhpChars($columns[$i]->Field) != $columns[$i]->Field)
						{
							$error = array("column"=>$columns[$i]->Field,"column_clean"=>SLS_String::removePhpChars($columns[$i]->Field));
							array_push($currentTable["errors"],$error);
							$fieldsOk = false;
						}
					}
					
					// If all ok with special chars for the current model
					if ($fieldsOk)
					{
						// Check real fks
						$create = array_shift($sql->select("SHOW CREATE TABLE `".$table."`"));						
						$queries = array_map("trim",explode("\n",$create->{Create." ".Table}));						
						foreach($queries as $query)
						{
							if (SLS_String::startsWith($query,"CONSTRAINT"))
							{
								$tableFk = strtolower($db."_".$tableName);
								$columnFk = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($query,"FOREIGN KEY (`"),"`)");
								$tablePk = $db."_".SLS_String::tableToClass(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($query,"REFERENCES `"),"`"));
								$onDelete = strtolower(SLS_String::stringToUrl(trim(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($query,"ON DELETE"),"ON UPDATE")),"_"));
								$labelPk = "";
								$columns = $sql->showColumns(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($query,"REFERENCES `"),"`"));
								for($i=0 ; $i<$count=count($columns) ; $i++)
								{
									if ($columns[$i]->Key != "PRI" && $columns[$i]->Field != "pk_lang" && SLS_String::contains($columns[$i]->Type,"char"))
									{
										$labelPk = $columns[$i]->Field;
										break;
									}
								}
								if (empty($labelPk))
									$labelPk = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($query,"REFERENCES `".SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($query,"REFERENCES `"),"`")."` (`"),"`)");
								$xmlNode = '<entry tableFk="'.$tableFk.'" columnFk="'.$columnFk.'" multilanguage="false" ondelete="'.$onDelete.'" labelPk="'.$labelPk.'" tablePk="'.$tablePk.'" />';
								
								$xmlFk = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml"));
								$result = $xmlFk->getTags("//sls_configs/entry[@tableFk='".$tableFk."' and @columnFk='".$columnFk."' and @tablePk='".$tablePk."']");
								if (!empty($result))
								{
									$xmlTmp = $xmlFk->deleteTags("//sls_configs/entry[@tableFk='".$tableFk."' and @columnFk='".$columnFk."' and @tablePk='".$tablePk."']");
									$xmlFk->saveXML($this->_generic->getPathConfig("configSls")."/fks.xml",$xmlTmp);
									$xmlFk = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml"));
								}
								
								$xmlFk->appendXMLNode("//sls_configs",$xmlNode);
								$xmlFk->saveXML($this->_generic->getPathConfig("configSls")."/fks.xml",$xmlFk->getXML());
							}
						}
						
						// Generate Model						
						$contentM = $this->getModelSource($tableName,$db);						
						$status = touch($this->_generic->getPathConfig("models")."/".$fileName);
						if ($status)					
							file_put_contents($this->_generic->getPathConfig("models").$fileName,$contentM);
						
						// Create SQL
						$fileNameS = ucfirst($db).".".SLS_String::tableToClass($table).".sql.php";
						$contentS = '<?php'."\n".
								   '/**'."\n".
								   '* Object '.$className.'Sql'."\n".
								   '* @author SillySmart'."\n".
								   '* @copyright SillySmart'."\n".
								   '* @package Mvc.Models.Objects'."\n".
								   '* @see Sls.Models.Core.SLS_FrontModel'."\n".
								   '* @since 1.0'."\n".
								   '*/'."\n".
								   'class '.$className.'Sql extends SLS_FrontModelSql'."\n".
								   '{'."\n".
								   ''."\n".
								   '}'."\n".
								   '?>';
						if ($status)
							$status2 = touch($this->_generic->getPathConfig("modelsSql")."/".$fileNameS);
						if ($status2)					
							file_put_contents($this->_generic->getPathConfig("modelsSql")."/".$fileNameS,$contentS);					 
					}
					else					
						array_push($errors,$currentTable);					
				}
			}
			// If no errors
			if (empty($errors))
			{
				$controllers = $this->_generic->getTranslatedController("SLS_Bo","Models");
				$this->_generic->redirect($controllers['controller']."/".$controllers['scontroller']);
			}
			else
			{	
				// Get all models
				$models = array();
				$handle = opendir($this->_generic->getPathConfig("models"));
				while (false !== ($file = readdir($handle))) 			
					if (!is_dir($this->_generic->getPathConfig("models")."/".$file) && substr($file, 0, 1) != ".") 
					{
						$modelExploded = explode(".",$file);
						array_push($models,strtolower($modelExploded[0]).".".$modelExploded[1]);
					}
					
				// Form errors
				$xml->startTag("errors");
				for($i=0 ; $i<$count=count($errors) ; $i++)
				{
					$xml->startTag("error");
					$xml->addFullTag("table",SLS_String::substrAfterFirstDelimiter($errors[$i]["table"],"."),true);
					$xml->addFullTag("db",SLS_String::substrBeforeFirstDelimiter($errors[$i]["table"],"."),true);
					$xml->startTag("columns");
					for($j=0 ; $j<$count2=count($errors[$i]["errors"]) ; $j++)
					{
						$xml->startTag("column");
						$xml->addFullTag("old",$errors[$i]["errors"][$j]["column"],true);
						$xml->addFullTag("new",$errors[$i]["errors"][$j]["column_clean"],true);
						$xml->endTag("column");
					}
					$xml->endTag("columns");
					$xml->endTag("error");
				}
				$xml->endTag("errors");				
			}
		}
		
		// Foreach db
		$dbs = $sql->getDbs();
		$allDbs = array();	
		
		foreach($dbs as $db)
		{
			$allDbs[$db] = array();
			
			// Change db
			$sql->changeDb($db);
			
			// Get all tables
			$tables = $sql->showTables();						
			for($i=0 ; $i<$count=count($tables) ; $i++)
			{
				$allDbs[$db][$tables[$i]->Name] = array("name" 	=> $tables[$i]->Name,
														"existed" => (in_array($db.".".SLS_String::tableToClass($tables[$i]->Name),$models)) ? 'true' : 'false');				
			}
		}
		
		asort($allDbs,SORT_REGULAR);
		uksort($allDbs,array($this, 'unshiftDefaultDb'));
		
		$xml->startTag("dbs");
		foreach($allDbs as $key => $db)
		{
			asort($db,SORT_REGULAR);
			
			$xml->startTag("db");
			$xml->addFullTag("name",$key,true);
			$xml->startTag("tables");
			foreach($db as $tableCur)
			{
				if (!SLS_String::startsWith(strtolower($tableCur["name"]),"sls_graph"))
				{
					$xml->startTag("table");				
					$xml->addFullTag("name",$tableCur["name"]);
					$xml->addFullTag("existed",$tableCur["existed"]);
					$xml->endTag("table");
				}
			}
			$xml->endTag("tables");
			$xml->endTag("db");
		}
		$xml->endTag("dbs");
			
		$this->saveXML($xml);
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);

		$sql = SLS_Sql::getInstance();

		$slsGraphId = $this->_http->getParam('id');
		
		$this->useModel('Sls_graph_query',$this->defaultDb,"sls");
		$this->useModel('Sls_graph',$this->defaultDb,"sls");
		$this->useModel('Sls_graph_query_column',$this->defaultDb,"sls");
		$this->useModel('Sls_graph_query_join',$this->defaultDb,"sls");
		$this->useModel('Sls_graph_query_group',$this->defaultDb,"sls");
		$this->useModel('Sls_graph_query_where',$this->defaultDb,"sls");

		$className = ucfirst($this->defaultDb)."_Sls_graph_query";
		$slsGraphQuery = new $className();
		$className = ucfirst($this->defaultDb)."_Sls_graph";
		$slsGraph = new $className();

		if($slsGraph->getModel($slsGraphId) === false || $slsGraphQuery->getModel($slsGraph->sls_graph_query_id) === false)
			$this->forward('SLS_Default', 'UrlError');

		$slsGraphQueryCurrent = $slsGraphQuery;

		$errors = array();
		$slsGraphTypes = array('pie', 'bar', 'pivot', 'list');
		$slsGraphAggregationTypes = array('sum', 'avg', 'count');
		$slsGraphAggregationTypesNeedField = array('sum', 'avg');
		$slsGraphQueryOperators = array('like','notlike','startwith','endwith','equal','notequal','in','notin','lt','lte','gt','gte','null','notnull');
		$this->queryOperatorsNeedField = array('like','notlike','startwith','endwith','equal','notequal','in','notin','lt','lte','gt','gte');

		$tableFieldsValues = array();
		$slsGraphQueryData = array(
			'sls_graph_query_where' => array(
				'sls_graph_query_where_type'      => 'group',
				'sls_graph_query_where_condition' => '',
				'sls_graph_query_where_column'    => '',
				'sls_graph_query_where_operator'  => '',
				'sls_graph_query_where_value'     => '',
				'sls_graph_query_where_children'  => array(),
				'sls_graph_query_where_root'      => 'true',
			)
		);
		$slsGraphData = array();
		$slsGraphQueryWheres = array();

		# reload
		if($this->_http->getParam('reload') == 'true')
		{
			$xmlFk = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml"));
			$slsGraphQueryData = $this->_http->getParam('sls_graph_query');
			$slsGraphData = $this->_http->getParam('sls_graph');

			if(!$slsGraph->setSlsGraphTitle($slsGraphData['sls_graph_title']))
				$errors['sls_graph_title'] = 'Titre invalide';

			$tmp = explode('.', $slsGraphQueryData['sls_graph_query_table']);

			if(count($tmp) == 2)
			{
				$slsGraphQueryDbAlias = $tmp[0];
				$slsGraphQueryTable = $tmp[1];
				$slsGraphQueryTableAlias = $this->getTableAlias($slsGraphQueryTable);
				$sql->changeDb($slsGraphQueryDbAlias);
			}
			else
			{
				$slsGraphQueryTableAlias = $slsGraphQueryDbAlias = $slsGraphQueryTable = '';
			}

			if(!$slsGraphQuery->setSlsGraphQueryDbAlias($slsGraphQueryDbAlias) || !$slsGraphQuery->setSlsGraphQueryTable($slsGraphQueryTable) || !$slsGraphQuery->setSlsGraphQueryTableAlias($slsGraphQueryTableAlias) || !$sql->tableExists($slsGraphQueryTable))
				$errors['sls_graph_query_table'] = 'Table invalide';
			else
			{

				$tableFields = $sql->showColumns($slsGraphQueryTable);
				$tableFieldsValues = array_map(array($this,'filterFields'), $tableFields);
			}

			if(!$slsGraph->setSlsGraphType($slsGraphData['sls_graph_type']))
			{
				$errors['sls_graph_type'] = 'Type invalide';
			}
			else if($slsGraphData['sls_graph_type'] == 'pie')
			{
				# query columns
				$tmp = explode('.', $slsGraphData['sls_graph_pie_group_by']);
				$column = $tmp[1];
				$columnConcat = $column;

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
				$slsGraphQueryColumn1 = new $className();
				$slsGraphQueryColumn1->setSlsGraphQueryColumnName($column);
				$slsGraphQueryColumn1->setSlsGraphQueryColumnAlias('legend_id');
				$slsGraphQueryColumn1->setSlsGraphQueryColumnTable($slsGraphQueryTable);
				$slsGraphQueryColumn1->setSlsGraphQueryColumnTableAlias($slsGraphQueryTableAlias);

				$columnFk = array_shift($xmlFk->getTagsAttributes("//sls_configs/entry[@tableFk='".strtolower($slsGraphQueryDbAlias.'_'.$slsGraphQueryTable)."' and @columnFk = '".$column."']",array("tablePk","labelPk")));

				if(!empty($columnFk))
				{
					$tablePk = $columnFk['attributes'][0]['value'];
					$labelPk = $columnFk['attributes'][1]['value'];

					$dbPk 	 = SLS_String::substrBeforeFirstDelimiter($tablePk, '_');
					$tablePk = SLS_String::substrAfterFirstDelimiter($tablePk, '_');

					$this->_generic->useModel($tablePk, $dbPk, "user");
					$classFk = ucfirst($dbPk)."_".SLS_String::tableToClass($tablePk);
					$objectFk = new $classFk();
					$columns = array();
					$columnsLabel = array();
					$clause = array();
					$render = array();

					$columnTable = $objectFk->getTable();

					# add join
					$i = 1;
					# target
					$className = ucfirst($this->defaultDb)."_Sls_graph_query_join";
					${slsGraphQueryJoin.$i} = new $className();
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableTarget($slsGraphQueryTable);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableAliasTarget($slsGraphQueryTableAlias);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinColumnTarget($column);
					# /target

					# source
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableSource($columnTable);
					$slsGraphQueryJoin = $this->getTableAlias($columnTable);
					/*$slsGraphQueryJoin = $columnTable.$aliasIndex;
					$aliasIndex++;*/
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableAliasSource($slsGraphQueryJoin);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinColumnSource($objectFk->getPrimaryKey());
					# /source

					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinMode('left');
					$i++;
					# /add join

					foreach($objectFk->getParams() as $key => $value)
					{
						array_push($columns,"`".$key."`");
						if (SLS_String::contains($labelPk,$key))
							$columnsLabel[$key] = strpos($labelPk,$key);
					}
					array_multisort($columnsLabel);

					foreach($columnsLabel as $columnLabel => $offset)
						array_push($clause,$columnLabel);

					$pattern = str_replace("'","''",$labelPk);

					foreach($clause as $columnC)
						$pattern = str_replace($columnC,"',"."CAST(".$slsGraphQueryJoin.".`".$columnC."` AS CHAR),'",$pattern);

					$columnConcat = "CONCAT('".$pattern."')";
				}

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
				$slsGraphQueryColumn2 = new $className();
				$slsGraphQueryColumn2->setSlsGraphQueryColumnName($columnConcat);
				$slsGraphQueryColumn2->setSlsGraphQueryColumnAlias('legend');
				$slsGraphQueryColumn2->setSlsGraphQueryColumnTable($slsGraphQueryTable);
				$slsGraphQueryColumn2->setSlsGraphQueryColumnTableAlias($slsGraphQueryTableAlias);

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
				$slsGraphQueryColumn3 = new $className();
				$slsGraphQueryColumn3->setSlsGraphQueryColumnAggregation('count');
				$slsGraphQueryColumn3->setSlsGraphQueryColumnAlias('count');
				$slsGraphQueryColumn3->setSlsGraphQueryColumnTable($slsGraphQueryTable);
				$slsGraphQueryColumn3->setSlsGraphQueryColumnTableAlias($slsGraphQueryTableAlias);
				# /query columns

				# query groups
				$className = ucfirst($this->defaultDb)."_Sls_graph_query_group";
				$slsGraphQueryGroup1 = new $className();
				if(!$slsGraphQueryGroup1->setSlsGraphQueryGroupColumn($column)/* || !in_array($slsGraphData['sls_graph_pie_group_by'], $tableFieldsValues)*/)
					$errors['sls_graph_pie_group_by'] = 'Champ groupé invalide';
				# /query groups

				$sql->changeDb($slsGraphQueryDbAlias);
				$joins = $this->getQueryJoin($slsGraphQueryTable, $slsGraphQueryTableAlias, array($slsGraphData['sls_graph_pie_group_by']));
			}
			else if($slsGraphData['sls_graph_type'] == 'bar')
			{
				$i = 1;
				$j = 1;

				# query columns
				$tmp = explode('.', $slsGraphData['sls_graph_bar_aggregation_field']);
				if(count($tmp) == 2)
					$columnAggregationField = $tmp[1];
				else
					$columnAggregationField = '';

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
				${slsGraphQueryColumn.$j} = new $className();
				if(empty($slsGraphData['sls_graph_bar_aggregation'])
					|| !${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnAggregation($slsGraphData['sls_graph_bar_aggregation'])
					|| !${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTable($slsGraphQueryTable)
					|| !${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTableAlias($slsGraphQueryTableAlias)
					|| !${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnAlias('value'))
					$errors['sls_graph_bar_aggregation'] = 'Aggrégation invalide';

				if(in_array($slsGraphData['sls_graph_bar_aggregation'], $slsGraphAggregationTypesNeedField) && (empty($columnAggregationField) ||  !${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnName($columnAggregationField)))
					$errors['sls_graph_bar_aggregation_field'] = 'Champ aggrégation invalide';
				$j++;

				# query column group
				$tmp = explode('.', $slsGraphData['sls_graph_bar_group_by']);
				$column = $tmp[1];
				$columnConcat = $column;

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
				${slsGraphQueryColumn.$j} = new $className();
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnName($column);
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnAlias('legend_group_id');
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTable($slsGraphQueryTable);
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTableAlias($slsGraphQueryTableAlias);
				$j++;

				$columnFk = array_shift($xmlFk->getTagsAttributes("//sls_configs/entry[@tableFk='".strtolower($slsGraphQueryDbAlias.'_'.$slsGraphQueryTable)."' and @columnFk = '".$column."']",array("tablePk","labelPk")));

				if(!empty($columnFk))
				{
					$tablePk = $columnFk['attributes'][0]['value'];
					$labelPk = $columnFk['attributes'][1]['value'];

					$dbPk 	 = SLS_String::substrBeforeFirstDelimiter($tablePk, '_');
					$tablePk = SLS_String::substrAfterFirstDelimiter($tablePk, '_');

					$this->_generic->useModel($tablePk, $dbPk, "user");
					$classFk = ucfirst($dbPk)."_".SLS_String::tableToClass($tablePk);
					$objectFk = new $classFk();
					$columns = array();
					$columnsLabel = array();
					$clause = array();
					$render = array();

					$columnTable = $objectFk->getTable();

					# add join
					# target
					$className = ucfirst($this->defaultDb)."_Sls_graph_query_join";
					${slsGraphQueryJoin.$i} = new $className();
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableTarget($slsGraphQueryTable);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableAliasTarget($slsGraphQueryTableAlias);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinColumnTarget($column);
					# /target

					# source
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableSource($columnTable);
					$slsGraphQueryJoin = $this->getTableAlias($columnTable);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableAliasSource($slsGraphQueryJoin);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinColumnSource($objectFk->getPrimaryKey());
					# /source

					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinMode('left');
					$i++;
					# /add join

					foreach($objectFk->getParams() as $key => $value)
					{
						array_push($columns,"`".$key."`");
						if (SLS_String::contains($labelPk,$key))
							$columnsLabel[$key] = strpos($labelPk,$key);
					}
					array_multisort($columnsLabel);

					foreach($columnsLabel as $columnLabel => $offset)
						array_push($clause,$columnLabel);

					$pattern = str_replace("'","''",$labelPk);
					foreach($clause as $columnC)
						$pattern = str_replace($columnC,"',"."CAST(".$slsGraphQueryJoin.".`".$columnC."` AS CHAR),'",$pattern);

					$columnConcat = "CONCAT('".$pattern."')";
				}

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
				${slsGraphQueryColumn.$j} = new $className();
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnName($columnConcat);
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnAlias('legend_group');
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTable($slsGraphQueryTable);
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTableAlias($slsGraphQueryTableAlias);
				$j++;
				# query column group

				# query column stacked
				if(!empty($slsGraphData['sls_graph_bar_stacked_field']))
				{
					$tmp = explode('.', $slsGraphData['sls_graph_bar_stacked_field']);
					$column = $tmp[1];
					$columnConcat = $column;

					$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
					${slsGraphQueryColumn.$j} = new $className();
					${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnName($column);
					${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnAlias('legend_stacked_id');
					${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTable($slsGraphQueryTable);
					${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTableAlias($slsGraphQueryTableAlias);
					$j++;

					$columnFk = array_shift($xmlFk->getTagsAttributes("//sls_configs/entry[@tableFk='".strtolower($slsGraphQueryDbAlias.'_'.$slsGraphQueryTable)."' and @columnFk = '".$column."']",array("tablePk","labelPk")));
					if(!empty($columnFk))
					{
						$tablePk = $columnFk['attributes'][0]['value'];
						$labelPk = $columnFk['attributes'][1]['value'];

						$dbPk 	 = SLS_String::substrBeforeFirstDelimiter($tablePk, '_');
						$tablePk = SLS_String::substrAfterFirstDelimiter($tablePk, '_');

						$this->_generic->useModel($tablePk, $dbPk, "user");
						$classFk = ucfirst($dbPk)."_".SLS_String::tableToClass($tablePk);
						$objectFk = new $classFk();
						$columns = array();
						$columnsLabel = array();
						$clause = array();
						$render = array();

						$columnTable = $objectFk->getTable();

						# add join
						# target
						$className = ucfirst($this->defaultDb)."_Sls_graph_query_join";
						${slsGraphQueryJoin.$i} = new $className();
						${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableTarget($slsGraphQueryTable);
						${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableAliasTarget($slsGraphQueryTableAlias);
						${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinColumnTarget($column);
						# /target

						# source
						${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableSource($columnTable);
						$slsGraphQueryJoin = $this->getTableAlias($columnTable);
						${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableAliasSource($slsGraphQueryJoin);
						${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinColumnSource($objectFk->getPrimaryKey());
						# /source

						${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinMode('left');
						$i++;
						# /add join

						foreach($objectFk->getParams() as $key => $value)
						{
							array_push($columns,"`".$key."`");
							if (SLS_String::contains($labelPk,$key))
								$columnsLabel[$key] = strpos($labelPk,$key);
						}
						array_multisort($columnsLabel);

						foreach($columnsLabel as $columnLabel => $offset)
							array_push($clause,$columnLabel);

						$pattern = str_replace("'","''",$labelPk);
						foreach($clause as $columnC)
							$pattern = str_replace($columnC,"',"."CAST(".$slsGraphQueryJoin.".`".$columnC."` AS CHAR),'",$pattern);

						$columnConcat = "CONCAT('".$pattern."')";
					}

					$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
					${slsGraphQueryColumn.$j} = new $className();
					${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnName($columnConcat);
					${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnAlias('legend_stacked');
					${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTable($slsGraphQueryTable);
					${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTableAlias($slsGraphQueryTableAlias);
				}
				# query column stacked
				# /query columns

				# query groups
				$tmp = explode('.', $slsGraphData['sls_graph_bar_group_by']);
				$columnGroupByField = $tmp[1];

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_group";
				$slsGraphQueryGroup1 = new $className();
				if(!$slsGraphQueryGroup1->setSlsGraphQueryGroupColumn($columnGroupByField))
					$errors['sls_graph_bar_group_by'] = 'Champ groupé invalide';

				if(!empty($slsGraphData['sls_graph_bar_stacked_field']))
				{
					$tmp = explode('.', $slsGraphData['sls_graph_bar_stacked_field']);
					$columnStackedField = $tmp[1];

					$className = ucfirst($this->defaultDb)."_Sls_graph_query_group";
					$slsGraphQueryGroup2 = new $className();
					if(!$slsGraphQueryGroup2->setSlsGraphQueryGroupColumn($columnStackedField))
						$errors['sls_graph_bar_stacked_field'] = 'Champ réservé invalide';
				}
				# /query groups

				$joins = $this->getQueryJoin($slsGraphQueryTable, $slsGraphQueryTableAlias, array($slsGraphData['sls_graph_bar_group_by']));
			}
			else if($slsGraphData['sls_graph_type'] == 'pivot')
			{
				$i = 1;
				$j = 1;
				# query columns
				$tmp = explode('.', $slsGraphData['sls_graph_pivot_aggregation_field']);
				if(count($tmp) == 2)
					$columnAggregationField = $tmp[1];
				else
					$columnAggregationField = '';

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
				${slsGraphQueryColumn.$j} = new $className();
				if(empty($slsGraphData['sls_graph_pivot_aggregation'])
					|| !${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnAggregation($slsGraphData['sls_graph_pivot_aggregation'])
					|| !${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTable($slsGraphQueryTable)
					|| !${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTableAlias($slsGraphQueryTableAlias)
					|| !${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnAlias('value'))
					$errors['sls_graph_pivot_aggregation'] = 'Aggrégation invalide';

				if(in_array($slsGraphData['sls_graph_pivot_aggregation'], $slsGraphAggregationTypesNeedField) && (empty($columnAggregationField) ||  !${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnName($columnAggregationField)))
					$errors['sls_graph_pivot_aggregation_field'] = 'Champ aggrégation invalide';
				$j++;

				# query column line
				$tmp = explode('.', $slsGraphData['sls_graph_pivot_line']);
				$column = $tmp[1];
				$columnConcat = $tmp[1];

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
				${slsGraphQueryColumn.$j} = new $className();
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnName($column);
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnAlias('legend_line_id');
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTable($slsGraphQueryTable);
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTableAlias($slsGraphQueryTableAlias);
				$j++;

				$columnFk = array_shift($xmlFk->getTagsAttributes("//sls_configs/entry[@tableFk='".strtolower($slsGraphQueryDbAlias.'_'.$slsGraphQueryTable)."' and @columnFk = '".$column."']",array("tablePk","labelPk")));
				if(!empty($columnFk))
				{
					$tablePk = $columnFk['attributes'][0]['value'];
					$labelPk = $columnFk['attributes'][1]['value'];

					$dbPk 	 = SLS_String::substrBeforeFirstDelimiter($tablePk, '_');
					$tablePk = SLS_String::substrAfterFirstDelimiter($tablePk, '_');

					$this->_generic->useModel($tablePk, $dbPk, "user");
					$classFk = ucfirst($dbPk)."_".SLS_String::tableToClass($tablePk);
					$objectFk = new $classFk();
					$columns = array();
					$columnsLabel = array();
					$clause = array();
					$render = array();

					$columnTable = $objectFk->getTable();

					# add join
					# target
					$className = ucfirst($this->defaultDb)."_Sls_graph_query_join";
					${slsGraphQueryJoin.$i} = new $className();
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableTarget($slsGraphQueryTable);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableAliasTarget($slsGraphQueryTableAlias);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinColumnTarget($column);
					# /target

					# source
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableSource($columnTable);
					$slsGraphQueryJoin = $this->getTableAlias($columnTable);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableAliasSource($slsGraphQueryJoin);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinColumnSource($objectFk->getPrimaryKey());
					# /source

					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinMode('left');
					$i++;
					# /add join

					foreach($objectFk->getParams() as $key => $value)
					{
						array_push($columns,"`".$key."`");
						if (SLS_String::contains($labelPk,$key))
							$columnsLabel[$key] = strpos($labelPk,$key);
					}
					array_multisort($columnsLabel);

					foreach($columnsLabel as $columnLabel => $offset)
						array_push($clause,$columnLabel);

					$pattern = str_replace("'","''",$labelPk);
					foreach($clause as $columnC)
						$pattern = str_replace($columnC,"',"."CAST(".$slsGraphQueryJoin.".`".$columnC."` AS CHAR),'",$pattern);

					$columnConcat = "CONCAT('".$pattern."')";
				}

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
				${slsGraphQueryColumn.$j} = new $className();
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnName($columnConcat);
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnAlias('legend_line');
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTable($slsGraphQueryTable);
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTableAlias($slsGraphQueryTableAlias);
				$j++;
				# query column line

				# query column column
				$tmp = explode('.', $slsGraphData['sls_graph_pivot_column']);
				$column = $tmp[1];
				$columnConcat = $column;

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
				${slsGraphQueryColumn.$j} = new $className();
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnName($column);
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnAlias('legend_column_id');
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTable($slsGraphQueryTable);
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTableAlias($slsGraphQueryTableAlias);
				$j++;

				$columnFk = array_shift($xmlFk->getTagsAttributes("//sls_configs/entry[@tableFk='".strtolower($slsGraphQueryDbAlias.'_'.$slsGraphQueryTable)."' and @columnFk = '".$column."']",array("tablePk","labelPk")));
				if(!empty($columnFk))
				{
					$tablePk = $columnFk['attributes'][0]['value'];
					$labelPk = $columnFk['attributes'][1]['value'];

					$dbPk 	 = SLS_String::substrBeforeFirstDelimiter($tablePk, '_');
					$tablePk = SLS_String::substrAfterFirstDelimiter($tablePk, '_');

					$this->_generic->useModel($tablePk, $dbPk, "user");
					$classFk = ucfirst($dbPk)."_".SLS_String::tableToClass($tablePk);
					$objectFk = new $classFk();
					$columns = array();
					$columnsLabel = array();
					$clause = array();
					$render = array();

					$columnTable = $objectFk->getTable();

					# add join
					# target
					$className = ucfirst($this->defaultDb)."_Sls_graph_query_join";
					${slsGraphQueryJoin.$i} = new $className();
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableTarget($slsGraphQueryTable);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableAliasTarget($slsGraphQueryTableAlias);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinColumnTarget($column);
					# /target

					# source
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableSource($columnTable);
					$slsGraphQueryJoin = $this->getTableAlias($columnTable);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinTableAliasSource($slsGraphQueryJoin);
					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinColumnSource($objectFk->getPrimaryKey());
					# /source

					${slsGraphQueryJoin.$i}->setSlsGraphQueryJoinMode('left');
					$i++;
					# /add join

					foreach($objectFk->getParams() as $key => $value)
					{
						array_push($columns,"`".$key."`");
						if (SLS_String::contains($labelPk,$key))
							$columnsLabel[$key] = strpos($labelPk,$key);
					}
					array_multisort($columnsLabel);

					foreach($columnsLabel as $columnLabel => $offset)
						array_push($clause,$columnLabel);

					$pattern = str_replace("'","''",$labelPk);
					foreach($clause as $columnC)
						$pattern = str_replace($columnC,"',"."CAST(".$slsGraphQueryJoin.".`".$columnC."` AS CHAR),'",$pattern);

					$columnConcat = "CONCAT('".$pattern."')";
				}

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
				${slsGraphQueryColumn.$j} = new $className();
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnName($columnConcat);
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnAlias('legend_column');
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTable($slsGraphQueryTable);
				${slsGraphQueryColumn.$j}->setSlsGraphQueryColumnTableAlias($slsGraphQueryTableAlias);
				# query column column

				# /query columns

				# query groups
				$tmp = explode('.', $slsGraphData['sls_graph_pivot_line']);
				$columnLine = $tmp[1];

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_group";
				$slsGraphQueryGroup1 = new $className();
				if(!$slsGraphQueryGroup1->setSlsGraphQueryGroupColumn($columnLine))
					$errors['sls_graph_pivot_line'] = 'Champ Ligne invalide';

				$tmp = explode('.', $slsGraphData['sls_graph_pivot_column']);
				$columnColumn = $tmp[1];

				$className = ucfirst($this->defaultDb)."_Sls_graph_query_group";
				$slsGraphQueryGroup2 = new $className();
				if(!$slsGraphQueryGroup2->setSlsGraphQueryGroupColumn($columnColumn))
					$errors['sls_graph_pivot_column'] = 'Champ colonne invalide';
				# /query groups

				$joins = $this->getQueryJoin($slsGraphQueryTable, $slsGraphQueryTableAlias, array($slsGraphData['sls_graph_pivot_column']));
			}
			else if($slsGraphData['sls_graph_type'] == 'list')
			{
				# columns
				$i = 1;
				$j = 1;
				$joins = array();

				foreach($slsGraphQueryData['sls_graph_query_column'] as $col)
				{
					$column = $col['sls_graph_query_column_value'];
					$path = explode('|', $column);
					$nbJoins = count($path);

					$data = explode('.', $path[$nbJoins-1]);
					$table = $data[0];
					$column = $data[1];
					$joinBefore = null;

					# joins
					for($k = 0; $k<$nbJoins ; $k++)
					{
						if($k == 0)
						{

							$columns = $sql->showColumns($slsGraphQueryTable);
							$columnSource = array_shift(array_filter($columns, array($this,'filterPK')));
							$columnSourcePK = $columnSource->Field;

							$join = array(
								'sls_graph_query_join_table_source' => $slsGraphQueryTable,
								'sls_graph_query_join_column_source' => $columnSourcePK
							);
						}
						else
						{
							$dataSource = explode('.', $path[$k]);
							$dataTarget = explode('.', $path[$k-1]);

							$tableSource = $dataSource[0];
							$tableTarget = $dataTarget[0];
							$columnSource = $dataSource[1];
							$columnTarget = $dataTarget[1];

							$columns = $sql->showColumns($tableSource);
							$columnSourcePK = array_shift(array_filter($columns, array($this,'filterPK')))->Field;

							$columns = $sql->showColumns($tableTarget);
							$this->columnTarget = $columnTarget;
							$columnTargetComment = array_shift(array_filter($columns, array($this,'filterFieldTarget')))->Comment;
							
							$join = array(
								'sls_graph_query_join_table_target' => $tableTarget,
								'sls_graph_query_join_column_target' =>$columnTarget,
								'sls_graph_query_join_table_comment_target' => empty($columnTargetComment) ? $columnTarget : $columnTargetComment,
								'sls_graph_query_join_table_source' => $tableSource,
								'sls_graph_query_join_column_source' => $columnSourcePK
							);
						}

						$joinSearch = $this->array_search_multi($join, $joins);
						if(empty($joinSearch))
						{
							$join['sls_graph_query_join_table_alias_source'] = ($k == 0) ? $slsGraphQueryTableAlias : $this->getTableAlias($join['sls_graph_query_join_table_source']); /*$join['sls_graph_query_join_table_source'].$aliasIndex++*/;

							if($k > 0)
							{
								$className = ucfirst($this->defaultDb)."_Sls_graph_query_join";
								${slsGraphQueryJoin.$j} = new $className();
								${slsGraphQueryJoin.$j}->setSlsGraphQueryJoinTableSource($join['sls_graph_query_join_table_source']);
								${slsGraphQueryJoin.$j}->setSlsGraphQueryJoinTableAliasSource($join['sls_graph_query_join_table_alias_source']);
								${slsGraphQueryJoin.$j}->setSlsGraphQueryJoinColumnSource($join['sls_graph_query_join_column_source']);
								${slsGraphQueryJoin.$j}->setSlsGraphQueryJoinTableTarget($join['sls_graph_query_join_table_target']);
								${slsGraphQueryJoin.$j}->setSlsGraphQueryJoinTableAliasTarget($joinBefore['sls_graph_query_join_table_alias_source']);
								${slsGraphQueryJoin.$j}->setSlsGraphQueryJoinColumnTarget($join['sls_graph_query_join_column_target']);
								${slsGraphQueryJoin.$j}->setSlsGraphQueryJoinMode('left');
								$j++;
							}

							array_push($joins, $join);
						}
						else
							$join = $joinSearch;

						$joinBefore = $join;
					}
					# /joins

					$columns = $sql->showColumns($table);
					$this->column = $column;
					$columnComment = array_shift(array_filter($columns, array($this,'filterColumnField')))->Comment;

					$tableComment = $join['sls_graph_query_join_table_comment_target'];

					if(empty($tableComment))
					{
						$tables = $sql->showTables();
						$this->table = $table;
						$tableComment = array_shift(array_filter($tables, array($this,'filterTable4')))->Comment;
					}

					$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
					${slsGraphQueryColumn.$i} = new $className();
					${slsGraphQueryColumn.$i}->setSlsGraphQueryColumnTable($join['sls_graph_query_join_table_source']);
					${slsGraphQueryColumn.$i}->setSlsGraphQueryColumnTableAlias($join['sls_graph_query_join_table_alias_source']);
					${slsGraphQueryColumn.$i}->setSlsGraphQueryColumnName($column);
					${slsGraphQueryColumn.$i}->setSlsGraphQueryColumnAlias($tableComment.' - '.$columnComment);
					$i++;
				}

				# /columns
			}

			# query where
			if(!empty($slsGraphQueryData['sls_graph_query_where']))
			{
				$i = 0; $j = 0;
				$this->iterateSetSlsGraphQueryWhere($slsGraphQueryData['sls_graph_query_where'], $i, $j, $slsGraphQueryWheres, $errors, $joins);
			}
			# /query where

			if (empty($errors))
			{
				$sql->changeDb($this->defaultDb);

				# query
				$this->deleteQuery($slsGraphQueryCurrent->sls_graph_query_id);
				$slsGraphQuery->create();
				# /query

				# graph
				$slsGraph->setSlsGraphQueryId($slsGraphQuery->sls_graph_query_id);
				$slsGraph->save();
				# /graph

				# query joins
				$i = 1;
				//$slsGraphQueryJoin1
				while(${slsGraphQueryJoin.$i})
				{
					${slsGraphQueryJoin.$i}->setSlsGraphQueryId($slsGraphQuery->sls_graph_query_id);
					${slsGraphQueryJoin.$i}->create();
					$i++;
				}
				# /query joins

				# query columns
				$i = 1;
				while(${slsGraphQueryColumn.$i})
				{
					${slsGraphQueryColumn.$i}->setSlsGraphQueryId($slsGraphQuery->sls_graph_query_id);
					${slsGraphQueryColumn.$i}->create();
					$i++;
				}
				# /query columns

				# query groups
				$i = 1;
				while(${slsGraphQueryGroup.$i})
				{
					${slsGraphQueryGroup.$i}->setSlsGraphQueryGroupTable($slsGraphQueryTable);
					${slsGraphQueryGroup.$i}->setSlsGraphQueryGroupTableAlias($slsGraphQueryTableAlias);
					${slsGraphQueryGroup.$i}->setSlsGraphQueryId($slsGraphQuery->sls_graph_query_id);
					${slsGraphQueryGroup.$i}->create();
					$i++;
				}
				# /query groups

				# query where
				if(!empty($slsGraphQueryData['sls_graph_query_where']))
				{
					$i = 0;
					$this->iterateCreateQueryWhere($slsGraphQueryData['sls_graph_query_where'], 0, $i, $slsGraphQueryWheres, $slsGraphQuery->sls_graph_query_id);
				}
				# /query where

				$this->forward('SLS_Bo', 'ReportingBo');
			}
			else
			{
				$xml->startTag("errors");
				foreach($errors as $key => $error)
				{
					if($key == 'sls_graph_query_where')
					{
						foreach($error as $slsGraphQueryWhereIndex => $slsGraphQueryWhereErrors)
						{
							foreach($slsGraphQueryWhereErrors as $slsGraphQueryWhereKey => $slsGraphQueryWhereError)
							{
								$xml->addFullTag("error", $slsGraphQueryWhereError, true, array("num" => $slsGraphQueryWhereIndex, "column" => $slsGraphQueryWhereKey));
							}
						}
					}
					else
						$xml->addFullTag("error", $error, true, array("column" => $key));
				}

				$xml->endTag("errors");
			}

			$slsGraphQueryData = $this->_http->getParam('sls_graph_query');
		}
		# /reload

		# load
		else
		{
			$this->useModel('Sls_graph_query',$this->defaultDb,"sls");
			$this->useModel('Sls_graph',$this->defaultDb,"sls");
			$this->useModel('Sls_graph_query_column',$this->defaultDb,"sls");
			$this->useModel('Sls_graph_query_join',$this->defaultDb,"sls");
			$this->useModel('Sls_graph_query_group',$this->defaultDb,"sls");
			$this->useModel('Sls_graph_query_where',$this->defaultDb,"sls");

			$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
			$slsGraphQueryColumn = new $className();
			$className = ucfirst($this->defaultDb)."_Sls_graph_query_join";
			$slsGraphQueryJoin = new $className();
			$className = ucfirst($this->defaultDb)."_Sls_graph_query_where";
			$slsGraphQueryWhere = new $className();
			$className = ucfirst($this->defaultDb)."_Sls_graph_query_group";
			$slsGraphQueryGroup = new $className();

			$slsGraphQueryId = $slsGraphQueryCurrent->sls_graph_query_id;
			$tables = array($slsGraphQueryCurrent->sls_graph_query_table => !empty($slsGraphQueryCurrent->sls_graph_query_alias) ? $slsGraphQuery->sls_graph_query_alias : $slsGraphQueryCurrent->sls_graph_query_table);
			$columns = $slsGraphQueryColumn->searchModels("sls_graph_query_column",array(),array(0=>array("column"=>"sls_graph_query_id","value"=>$slsGraphQueryId,"mode"=>"equal")),array(),array(array("column"=>"sls_graph_query_column_id","order"=>"asc")));
			$joins = $slsGraphQueryJoin->searchModels("sls_graph_query_join",array(),array(0=>array("column"=>"sls_graph_query_id","value"=>$slsGraphQueryId,"mode"=>"equal")),array(),array(array("column"=>"sls_graph_query_join_id","order"=>"asc")));
			$wheres = $slsGraphQueryWhere->searchModels("sls_graph_query_where",array(),array(0=>array("column"=>"sls_graph_query_id","value"=>$slsGraphQueryId,"mode"=>"equal")),array(),array(array("column"=>"sls_graph_query_where_id","order"=>"asc")));
			$groups = $slsGraphQueryGroup->searchModels("sls_graph_query_group",array(),array(0=>array("column"=>"sls_graph_query_id","value"=>$slsGraphQueryId,"mode"=>"equal")),array(),array(array("column"=>"sls_graph_query_group_id","order"=>"asc")));

			if($slsGraph->sls_graph_type == 'pie')
			{
				$slsGraphData['sls_graph_pie_group_by'] = !empty($groups) ? $slsGraphQueryCurrent->sls_graph_query_table_alias.'.'.$groups[0]->sls_graph_query_group_column : '';
			}
			else if($slsGraph->sls_graph_type == 'bar')
			{
				$slsGraphData['sls_graph_bar_aggregation'] = !empty($columns) ? $columns[0]->sls_graph_query_column_aggregation : '';
				$slsGraphData['sls_graph_bar_aggregation_field'] = !empty($columns) && !empty($columns[0]->sls_graph_query_column_name) ? $slsGraphQueryCurrent->sls_graph_query_table_alias.'.'.$columns[0]->sls_graph_query_column_name : '';
				$slsGraphData['sls_graph_bar_group_by'] = !empty($groups) && !empty($groups[0]->sls_graph_query_group_column) ? $slsGraphQueryCurrent->sls_graph_query_table_alias.'.'.$groups[0]->sls_graph_query_group_column : '';
				$slsGraphData['sls_graph_bar_stacked_field'] = !empty($groups) && !empty($groups[1]->sls_graph_query_group_column) ? $slsGraphQueryCurrent->sls_graph_query_table_alias.'.'.$groups[1]->sls_graph_query_group_column : '';
			}
			else if($slsGraph->sls_graph_type == 'pivot')
			{
				$slsGraphData['sls_graph_pivot_aggregation'] = !empty($columns) ? $columns[0]->sls_graph_query_column_aggregation : '';
				$slsGraphData['sls_graph_pivot_aggregation_field'] = !empty($columns) && !empty($columns[0]->sls_graph_query_column_name) ? $slsGraphQueryCurrent->sls_graph_query_table_alias.'.'.$columns[0]->sls_graph_query_column_name : '';
				$slsGraphData['sls_graph_pivot_line'] = !empty($groups) && !empty($groups[0]->sls_graph_query_group_column) ? $slsGraphQueryCurrent->sls_graph_query_table_alias.'.'.$groups[0]->sls_graph_query_group_column : '';
				$slsGraphData['sls_graph_pivot_column'] = !empty($groups) && !empty($groups[1]->sls_graph_query_group_column) ? $slsGraphQueryCurrent->sls_graph_query_table_alias.'.'.$groups[1]->sls_graph_query_group_column : '';
			}

			foreach($slsGraph->getParams() as $key => $value)
				$slsGraphData[$key] = $value;

			if ($slsGraphQueryCurrent->sls_graph_query_db_alias != $sql->getCurrentDb())
					$sql->changeDb($slsGraphQueryCurrent->sls_graph_query_db_alias);
			$tableFields = $sql->showColumns($slsGraphQueryCurrent->sls_graph_query_table);
			foreach($slsGraphQueryCurrent->getParams() as $key => $value)
			{
				if($key == 'sls_graph_query_table')
					$value = $slsGraphQueryCurrent->sls_graph_query_db_alias.'.'.$value;
				$slsGraphQueryData[$key] = $value;
			}

			$slsGraphQueryData['sls_graph_query_column'] = $this->iterateFormatQueryColumnToArray($columns, $joins);
			$slsGraphQueryData['sls_graph_query_where'] = $this->iterateFormatQueryWhereToArray($wheres, 0);
		}
		# /load

		# graph
		$xml->startTag('sls_graph');
		foreach($slsGraphData as $key => $value)
			$xml->addFullTag($key, $value, true);
		$xml->addFullTag('graph_table_fields_class', empty($tableFields) ? 'hide' : '', true);
		$xml->startTag('sls_graph_query');
		foreach($slsGraphQueryData as $key => $value)
		{
			if($key == 'sls_graph_query_where')
			{
				$i = 0; $j = 0;
				$this->iterateAddXmlQueryWhere($value, $i, $j, $xml);
			}
			else if($key == 'sls_graph_query_column')
			{
				$xml->startTag('sls_graph_query_columns');
				foreach($value as $column)
				{
					$xml->startTag('sls_graph_query_column');
					$xml->addFullTag('sls_graph_query_column_value', $column['sls_graph_query_column_value'], true);
					$xml->addFullTag('sls_graph_query_column_label', $column['sls_graph_query_column_label'], true);
					$xml->endTag('sls_graph_query_column');
				}
				$xml->endTag('sls_graph_query_columns');
			}
			else
				$xml->addFullTag($key, $value, true);
		}

		$xml->endTag('sls_graph_query');
		$xml->endTag('sls_graph');
		# /graph

		$labels = array(
			'SLS_GRAPH_TYPE_PIE' => "Pie Chart",
			'SLS_GRAPH_TYPE_BAR' => "Bar Chart",
			'SLS_GRAPH_TYPE_PIVOT' => "Pivot Table",
			'SLS_GRAPH_TYPE_LIST' => "List",
			'SLS_AGGREGATION_TYPE_SUM' => "SUM",
			'SLS_AGGREGATION_TYPE_AVG' => "AVG",
			'SLS_AGGREGATION_TYPE_COUNT' => "COUNT",
			'SLS_AGGREGATION_TYPE_SUM_LABEL' => "Sum",
			'SLS_AGGREGATION_TYPE_AVG_LABEL' => "Average",
			'SLS_AGGREGATION_TYPE_COUNT_LABEL' => "Total",
			'SLS_QUERY_OPERATOR_LIKE' => "LIKE",
			'SLS_QUERY_OPERATOR_NOTLIKE' => "NOT LIKE",
			'SLS_QUERY_OPERATOR_STARTWITH' => "START WITH",
			'SLS_QUERY_OPERATOR_ENDWITH' => "END WITH",
			'SLS_QUERY_OPERATOR_EQUAL' => "EQUAL",
			'SLS_QUERY_OPERATOR_NOTEQUAL' => "NOT EQUAL",
			'SLS_QUERY_OPERATOR_IN' => "IN",
			'SLS_QUERY_OPERATOR_NOTIN' => "NOT IN",
			'SLS_QUERY_OPERATOR_LT' => "LESS THAN",
			'SLS_QUERY_OPERATOR_LTE' => "LESS THAN EQUAL",
			'SLS_QUERY_OPERATOR_GT' => "GREATER THAN",
			'SLS_QUERY_OPERATOR_GTE' => "GREATER THAN EQUAL",
			'SLS_QUERY_OPERATOR_NULL' => "IS NULL",
			'SLS_QUERY_OPERATOR_NOTNULL' => "IS NOT NULL"
		);

		# graph types
		$xml->startTag('sls_graph_types');
		foreach($slsGraphTypes as $slsGraphType){
			$xml->startTag('sls_graph_type');
			$xml->addFullTag('sls_graph_type_value', $slsGraphType, true);
			$xml->addFullTag('sls_graph_type_label', $labels['SLS_GRAPH_TYPE_'.mb_strtoupper($slsGraphType, 'UTF-8')], true);
			$xml->endTag('sls_graph_type');
		}
		$xml->endTag('sls_graph_types');
		# /graph types

		# aggregation types
		$xml->startTag('sls_graph_aggregation_types');
		foreach($slsGraphAggregationTypes as $slsGraphAggregationType){
			$xml->startTag('sls_graph_aggregation_type');
			$xml->addFullTag('sls_graph_aggregation_type_value', $slsGraphAggregationType, true);
			$xml->addFullTag('sls_graph_aggregation_type_label', $labels['SLS_AGGREGATION_TYPE_'.mb_strtoupper($slsGraphAggregationType, 'UTF-8')], true);
			$xml->endTag('sls_graph_aggregation_type');
		}
		$xml->endTag('sls_graph_aggregation_types');
		# /aggregation types

		# query operators
		$xml->startTag('sls_graph_query_operators');
		foreach($slsGraphQueryOperators as $slsGraphQueryOperator){
			$xml->startTag('sls_graph_query_operator');
			$xml->addFullTag('sls_graph_query_operator_value', $slsGraphQueryOperator, true);
			$xml->addFullTag('sls_graph_query_operator_label', $labels['SLS_QUERY_OPERATOR_'.mb_strtoupper($slsGraphQueryOperator, 'UTF-8')], true);
			$xml->endTag('sls_graph_query_operator');
		}
		$xml->endTag('sls_graph_query_operators');
		# /query operators

		# tables
		$xml->startTag('tables');
		$dbs = $sql->getDbs();
		foreach($dbs as $db)
		{
			$sql->changeDb($db);
			$tables = $sql->showTables();
			usort($tables, array($this,'cmpTables'));

			foreach($tables as $table)
			{
				$xml->startTag('table');
					$xml->addFullTag('table_name', $db.'.'.$table->Name, true);
					$xml->addFullTag('table_label', $db.' - '.$table->Name, true);
				$xml->endTag('table');
			}
		}
		$xml->endTag('tables');
		# /tables

		$xml->addFullTag("url_reporting_getfields",$this->_generic->getFullPath("SLS_Bo","ReportingBoGetFields"),true);
		$xml->addFullTag("url_reporting_getfieldsfrommutipletables",$this->_generic->getFullPath("SLS_Bo","ReportingBoGetFieldsFromMultipleTables"),true);
		$xml->addFullTag("url_report",$this->_generic->getFullPath("SLS_Bo","ReportingBo"),true);
		$xml->addFullTag("url_delete",$this->_generic->getFullPath("SLS_Bo","ReportingBoDelete",array("id" => $slsGraphId)),true);
		$xml->addFullTag("url_status",$this->_generic->getFullPath("SLS_Bo","ReportingBoStatus",array("id" => $slsGraphId)),true);
		
		$this->saveXML($xml);
	}
	/**
	 * Action Home
	 *
	 */
	public function action() 
	{
		$this->secureURL();
		
		$this->_generic->registerLink('GlobalSettings', 'SLS_Init', 'GlobalSettings');
		$handle = file_get_contents($this->_generic->getPathConfig("configSls").'charset.xml');
		$handle2 = file_get_contents($this->_generic->getPathConfig("configSls").'timezone.xml');
		$xml = $this->getXML();
		$xml->addFullTag("charsets", SLS_String::substrBeforeLastDelimiter(SLS_String::substrAfterFirstDelimiter($handle, "<sls_configs>"), "</sls_configs>"), false);
		$xml->addFullTag("timezones", SLS_String::substrBeforeLastDelimiter(SLS_String::substrAfterFirstDelimiter($handle2, "<sls_configs>"), "</sls_configs>"), false);
				
		$errors = array();
		
		$domain 		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_domain'));
		$protocol 		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_protocol'));
		$project 		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_project'));
		$description 	= SLS_String::trimSlashesFromString($this->_http->getParam('settings_description'));
		$keywords 		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_keywords'));
		$author		 	= SLS_String::trimSlashesFromString($this->_http->getParam('settings_author'));
		$copyright	 	= SLS_String::trimSlashesFromString($this->_http->getParam('settings_copyright'));
		$extension 		= ($this->_http->getParam('settings_extension') == "") ? "sls" : SLS_String::trimSlashesFromString($this->_http->getParam('settings_extension'));
		$charset 		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_charset'));
		$doctype 		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_doctype'));
		$bo 			= SLS_String::trimSlashesFromString($this->_http->getParam('settings_bo'));
		$timezone_area	= SLS_String::trimSlashesFromString($this->_http->getParam('settings_timezone_area'));
		$timezone_city	= SLS_String::trimSlashesFromString($this->_http->getParam('settings_timezone_area_'.$timezone_area));
		
		$xmlTmp = new SLS_XMLToolbox($handle);		
		$allowedCharsets = $xmlTmp->getTags("//sls_configs/charset/code");
		
		if ($this->_http->getParam('globalSettings_reload') == "true")
		{	
			if (empty($domain))
				array_push($errors,"You must fill your main domain name");
			if ($protocol != 'http' && $protocol != 'https')
				array_push($errors,"You must choose a correct Protocol");
			if (empty($project))
				array_push($errors,"You must fill your project name");
			if (empty($description))
				array_push($errors,"You must fill your project description");
			if (empty($author))
				$author = $project;
			if (empty($copyright))
				$copyright = $domain;
			if (empty($extension))
				array_push($errors,"You must fill your default extension");
			if (empty($bo))
				array_push($errors,"You must fill your access to your SillySmart's Back-Office");
			if (!in_array($charset,$allowedCharsets))
				array_push($errors,"You must choose a valid charset");
			if (empty($doctype))
				array_push($errors,"You must choose your default doctype");
			if (empty($timezone_area) || empty($timezone_city))
				array_push($errors,"You must choose your default timezone");
							
			if (empty($errors))
			{
				$key = substr(md5($domain).sha1($project).uniqid(microtime()),mt_rand(5,10),mt_rand(20,32));
				$coreXml = $this->_generic->getSiteXML();
				$coreXml->setTag('//configs/domainName', "<domain alias='__default' default='1' js='true' isSecure='false' lang=''><![CDATA[".$domain."]]></domain>", false);
				$coreXml->setTag('//configs/protocol',$protocol);
				$coreXml->setTag('//configs/defaultExtension',$extension);
				$coreXml->setTag('//configs/projectName',$project);
				$coreXml->setTag('//configs/versionName',date("Ymd")."-dev");
				$coreXml->setTag('//configs/metaDescription',$description);
				$coreXml->setTag('//configs/metaKeywords',$keywords);
				$coreXml->setTag('//configs/metaAuthor',$author);
				$coreXml->setTag('//configs/metaCopyright',$copyright);
				$coreXml->setTag('//configs/privateKey',$key);
				$coreXml->setTag('//configs/defaultCharset',strtoupper($charset));
				$coreXml->setTag('//configs/defaultDoctype',$doctype);
				$coreXml->setTag('//configs/defaultTimezone',$timezone_area."/".$timezone_city);
				file_put_contents($this->_generic->getPathConfig("configSecure")."site.xml", $coreXml->getXML());
				$controllersXml = $this->_generic->getControllersXML();
				$controllersXml->setTag("//controllers/controller[@name='SLS_Bo']/controllerLangs/controllerLang",$bo);
				
				$uniqs = array();
				$metas = array();
				
				// Generate Controllers IDS
				$slsControllers = $controllersXml->getTags("//controllers/controller[@side='sls']/@name");	
				$slsLangs = $controllersXml->getTags("//controllers/controller[@side='sls'][1]/scontrollers/scontroller[1]/scontrollerLangs/scontrollerLang/@lang");
				foreach ($slsControllers as $slsController)
				{
					// Take a random id and set it
					$uniq = uniqid("c_");
					while(in_array($uniq, $uniqs))					
						$uniq = uniqid("c_");					
					array_push($uniqs, $uniq);
					$controllersXml->setTagAttributes("//controllers/controller[@name='".$slsController."' and @side='sls']", array("id"=>$uniq));
					
					// Generate Actions IDS
					$slsActions = $controllersXml->getTags("//controllers/controller[@side='sls' and @name='".$slsController."']/scontrollers/scontroller/@name");					
					foreach ($slsActions as $slsAction)
					{
						// Take a random id and set it
						$uniq = uniqid("a_");
						while(in_array($uniq, $uniqs))						
							$uniq = uniqid("a_");						
						array_push($uniqs, $uniq);
						$controllersXml->setTagAttributes("//controllers/controller[@name='".$slsController."' and @side='sls']/scontrollers/scontroller[@name='".$slsAction."']", array("id"=>$uniq));
						
						// Get title attribute, save it into array and delete this attribute
						$tmpArray = array();
						foreach ($slsLangs as $lang)
						{
							$tmpArray[$lang] = array_shift($controllersXml->getTags("//controllers/controller[@name='".$slsController."' and @side='sls']/scontrollers/scontroller[@name='".$slsAction."']/scontrollerLangs/scontrollerLang[@lang='".$lang."']/@title"));
							$controllersXml->deleteTagAttribute("//controllers/controller[@name='".$slsController."' and @side='sls']/scontrollers/scontroller[@name='".$slsAction."']/scontrollerLangs/scontrollerLang[@lang='".$lang."']","title");
						}
						$metas[$uniq] = $tmpArray;
					}	
				}
				
				// Update metas.xml
				$metaXml = '';
				foreach($metas as $key => $value)
				{
					$metaXml .= '<action id="'.$key.'">';
					foreach ($value as $lang => $title)
						$metaXml .=	'<title lang="'.$lang.'"><![CDATA['.$title.']]></title>';
					$metaXml .=	'<robots><![CDATA[noindex, nofollow]]></robots>';
					$metaXml .= '</action>';
				}
				$metaO = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."metas.xml"));
				$metaO->appendXML("//sls_configs",$metaXml);
				$metaO->saveXML($this->_generic->getPathConfig("configSls")."metas.xml");
				
				// Overwrite template __default
				$this->createXslTemplate("__default",$doctype);
				
				file_put_contents($this->_generic->getPathConfig("configSecure")."controllers.xml", $controllersXml->getXML());
				$this->setInstallationStep(array(0=>"SLS_Init",1=>"Initialization"), array(0=>"International",1=>"International"));
				return $this->_generic->dispatch("SLS_Init", "International");
			}
			else
			{
				$xml->startTag("errors");
				foreach ($errors as $error)
					$xml->addFullTag("error", $error, true);
				$xml->endTag("errors");
				
				$xml->addFullTag("domain",$domain,true);
				$xml->addFullTag("protocol",$protocol,true);
				$xml->addFullTag("project",$project,true);
				$xml->addFullTag("description",$description,true);
				$xml->addFullTag("keywords",$keywords,true);
				$xml->addFullTag("author",$author,true);
				$xml->addFullTag("copyright",$copyright,true);
				$xml->addFullTag("extension",$extension,true);
				$xml->addFullTag("charset",$charset,true);
				$xml->addFullTag("doctype",$doctype,true);
				$xml->addFullTag("bo",$bo,true);
				$xml->startTag("timezone");
					$xml->addFullTag("area",$timezone_area,true);
					$xml->addFullTag("city",$timezone_city,true);
				$xml->endTag("timezone");				
			}
		}
		else
		{
			$timezone = date_default_timezone_get();
			$xml->addFullTag("domain",$_SERVER['HTTP_HOST'].(($_SERVER['SCRIPT_NAME'] != "/index.php") ? SLS_String::substrBeforeFirstDelimiter($_SERVER['SCRIPT_NAME'],"/index.php") : ""),true);
			$xml->addFullTag("protocol",(SLS_String::startsWith($_SERVER['SERVER_PROTOCOL'],'HTTPS')) ? 'https' : 'http',true);
			$xml->addFullTag("author","SillySmart",true);
			$xml->addFullTag("extension","sls",true);
			$xml->startTag("timezone");
				$xml->addFullTag("area",(empty($timezone) || !SLS_String::contains($timezone,'/')) ? 'Europe' : SLS_String::substrBeforeFirstDelimiter($timezone,'/'),true);
				$xml->addFullTag("city",(empty($timezone) || !SLS_String::contains($timezone,'/')) ? 'Paris' : SLS_String::substrAfterFirstDelimiter($timezone,'/'),true);
			$xml->endTag("timezone");
			$xml->addFullTag("bo","Manage",true);
		}
		
		$this->saveXML($xml);
	}
	/**
	 * Format XML for a given recordsets collection
	 * 
	 * @access public
	 * @param SLS_XMLToolbox $xml current controller's XML
	 * @param array $recordsets array of PDO recordsets
	 * @param array $options transformations on some columns - delimited by ":". each function can be methods of SLS' classes or php standard function
	 * <code>
     * // Complete example
	 * $newss = $news->searchModels("news",array("user","article_category"));
	 * $xml = $news->pdoToXML($xml,$newss,array("news_excerpt" => array("php:strip_tags","SLS_String:trimStringToLength:100"),
	 *											"news_date" => array("SLS_Date:getDate:FULL_LITTERAL_TIME","php:ucwords"),
	 *											"news_photo" => "SLS_String:getUrlFileImg:_0",
	 *											"news_pdf" => "SLS_String:getUrlFile",
	 *											"news_title" => "php:trim")
	 *						, "all_news/news");
	 * </code>
	 * @param string $nodeName the root node of your model, by default it's your classname in lowercase
	 * @return SLS_XMLToolbox $xml current controller's XML updated
	 * @see SLS_FrontModel::getParams
	 * @see SLS_FrontModel::toXML
	 * @since 1.0.8	 
	 */
	public function pdoToXML($xml,$recordsets,$options=array(),$nodeNames="")
	{
		$nodeName 	= (SLS_String::contains($nodeNames,"/")) ? SLS_String::substrAfterLastDelimiter($nodeNames,"/") : "";
		$nodeNames 	= (SLS_String::contains($nodeNames,"/")) ? SLS_String::substrBeforeFirstDelimiter($nodeNames,"/") : strtolower($this->getTable())."s";
		
		$xml->startTag($nodeNames);
		for($i=0 ; $i<$count=count($recordsets) ; $i++)		
			$xml = $this->toXML($xml,$options,array(),$nodeName,SLS_String::objectToArray($recordsets[$i]));		
		$xml->endTag($nodeNames);
		
		return $xml;
	}
示例#28
0
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);

		# Params
		$tableName = $this->_http->getParam('name');
		$this->_db_alias = SLS_String::substrBeforeFirstDelimiter($tableName, "_");
		$this->_table = SLS_String::substrAfterFirstDelimiter($tableName, "_");
		# /Params

		# Objects
		$errors = array();
		$operators = array('like','notlike','startwith','endwith','equal','notequal','in','notin','lt','lte','gt','gte','null','notnull');
		$operatorsNeedValue = array('like','notlike','startwith','endwith','equal','notequal','in','notin','lt','lte','gt','gte');
		$orders = array( 'desc', 'asc');
		$limits = array( '20', '50', '100', '250', '500', '1000');

		$this->_db = new SLS_Sql();
		$this->_db->changeDb($this->_db_alias);
		if(!$this->_db->tableExists($this->_table))
			$this->forward('SLS_Default', 'UrlError');

		$className = ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table);
		$this->_generic->useModel(SLS_String::tableToClass($this->_table),ucfirst(strtolower($this->_db_alias)), "user");
		$this->_object = new $className();

		$this->_xmlFk = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml"));
		$this->_xmlType = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/types.xml"));
		$this->_xmlBearers = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/bearers.xml"));
		
		$this->_xmlBo = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/bo.xml"));
		$boPath = "//sls_configs/entry[@type='table' and @name='".strtolower($className)."']";
		$boExists = $this->_xmlBo->getTag($boPath."/@type");
		if (empty($boExists))
			$boPath = "//sls_configs/entry/entry[@type='table' and @name='".strtolower($className)."']";
		# /Objects
		
		$menuCategories = $this->_xmlBo->getTags("//sls_configs/entry[@type='category']/@name");
		$xml->startTag("categories");
		for($i=0 ; $i<$count=count($menuCategories) ; $i++)
			$xml->addFullTag("category",$menuCategories[$i],true);
		$xml->endTag("categories");
			
		$tableAttributes = array_shift($this->_xmlBo->getTagsAttributes($boPath, array('multilanguage')));

		# reload
		if($this->_http->getParam('reload') == 'true')
		{
			$boData = $this->_http->getParam('bo');
			$newCategory = $this->_http->getParam('category');
			$results = $this->_xmlBo->getTagsAttributes($boPath.'/joins/join', array('table', 'column'));

			$joinsNews = !empty($boData['joins']) ? $boData['joins'] : array();
			$joinsOld = array();
			foreach($results as $result)
				array_push($joinsOld, SLS_String::substrAfterFirstDelimiter($result['attributes'][0]['value'], '_'));

			$joinsToDelete = array_diff($joinsOld, $joinsNews);
			$joinsToAdd = array_diff($joinsNews, $joinsOld);

			$xmlNew = '';

			# columns

			# add columns of news join tables
			if(!empty($joinsToAdd))
			{
				foreach($joinsToAdd as $join)
				{
					$tableColumns = $this->_db->showColumns($join);
					if(!empty($tableColumns))
					{
						foreach($tableColumns as $tableColumn)
						{
							if(!in_array($tableColumn, array('pk_lang')))
							{
								array_push($boData['columns'], array(
									'table' => $join,
									'column_value' => $join.'.'.$tableColumn->Field,
									'column_label' => $join.' / '.$tableColumn->Field,
									'display_filter' => 'on',
									'display_list' => 'off',
									'allow_edit' => 'off',
									'allow_html' => 'off',
									'multilanguage' => 'off',
								));
							}
						}
					}
				}
			}

			$xmlNew .= '<columns>';
			if(!empty($boData['columns']))
			{
				foreach($boData['columns'] as $index => $column)
				{
					$table = $this->_db_alias.'_'.$column['table'];
					$name = SLS_String::substrAfterLastDelimiter($column['column_value'], '.');
					$multilanguage = $column['multilanguage'] == 'on' ? 'true' : 'false';
					$displayFilter = $column['display_filter'] == 'on' ? 'true' : 'false';
					$displayList = $column['display_list'] == 'on' ? 'true' : 'false';
					$allowEdit = $column['allow_edit'] == 'on' ? 'true' : 'false';
					$allowHtml = $column['allow_html'] == 'on' ? 'true' : 'false';

					if($table == $tableName || (is_array($joinsNews) && in_array($column['table'], $joinsNews)))
						$xmlNew .= '<column table="'.$table.'" name="'.$name.'" multilanguage="'.$multilanguage.'" displayFilter="'.$displayFilter.'" displayList="'.$displayList.'" allowEdit="'.$allowEdit.'" allowHtml="'.$allowHtml.'" />';
					else
						unset($boData['columns'][$index]);
				}
			}

			$xmlNew .= '</columns>';
			# /columns

			# joins
			$xmlNew .= '<joins>';
			if(!empty($boData['joins']))
			{
				foreach($boData['joins'] as $index => $join)
				{

					$tablePk = $this->_db_alias.'_'.ucfirst($join);
					$res = array_shift($this->_xmlFk->getTagsAttributes("//sls_configs/entry[@tableFk='".$tableName."' and @tablePk='".$tablePk."']",array("columnFk")));
					$table = $this->_db_alias.'_'.$join;
					$column = $res['attributes'][0]['value'];


					if($table == $tableName || (is_array($joinsNews) && in_array($join, $joinsNews)))
						$xmlNew .= '<join table="'.$table.'" column="'.$column.'" />';
					else
						unset($boData['joins'][$index]);
				}
			}
			$xmlNew .= '</joins>';
			# /joins

			# wheres
			$xmlNew .= '<wheres>';
			if(!empty($boData['wheres']))
			{
				foreach($boData['wheres'] as $index => $where)
				{
					$table = $this->_db_alias.'_'.SLS_String::substrBeforeFirstDelimiter($where['column'], '.');
					$column = SLS_String::substrAfterFirstDelimiter($where['column'], '.');
					$value = in_array($where['mode'], $operatorsNeedValue) ? $where['value'] : '';
					$mode = $where['mode'];

					if($table == $tableName || (is_array($joinsNews) && in_array(SLS_String::substrBeforeFirstDelimiter($where['column'], '.'), $joinsNews)))
						$xmlNew .= '<where table="'.$table.'" column="'.$column.'" value="'.$value.'" mode="'.$mode.'" />';
					else
						unset($boData['wheres'][$index]);
				}
			}
			$xmlNew .= '</wheres>';
			# /wheres

			# groups
			$xmlNew .= '<groups>';
			if(!empty($boData['groups']))
			{
				foreach($boData['groups'] as $index => $group)
				{
					$table = $this->_db_alias.'_'.SLS_String::substrBeforeFirstDelimiter($group, '.');
					$column = SLS_String::substrAfterFirstDelimiter($group, '.');

					if($table == $tableName || (is_array($joinsNews) && in_array(SLS_String::substrBeforeFirstDelimiter($group, '.'), $joinsNews)))
						$xmlNew .= '<group table="'.$table.'" column="'.$column.'" />';
					else
						unset($boData['groups'][$index]);
				}
			}
			$xmlNew .= '</groups>';
			# /groups

			# orders
			$xmlNew .= '<orders>';
			if(!empty($boData['orders']))
			{
				foreach($boData['orders'] as $index => $order)
				{
					$table = $this->_db_alias.'_'.SLS_String::substrBeforeFirstDelimiter($order['column'], '.');
					$column = SLS_String::substrAfterFirstDelimiter($order['column'], '.');
					$orderValue = $order['order'];

					if($table == $tableName || (is_array($joinsNews) && in_array(SLS_String::substrBeforeFirstDelimiter($order['column'], '.'), $joinsNews)))
						$xmlNew .= '<order table="'.$table.'" column="'.$column.'" order="'.$orderValue.'" />';
					else
						unset($boData['orders'][$index]);
				}
			}
			$xmlNew .= '</orders>';
			# /orders

			# limits
			$xmlNew .= '<limits>';
			if(!empty($boData['limits']))
			{
				foreach($boData['limits'] as $index => $limit)
				{
					$length = $limit['length'];
					$xmlNew .= '<limit start="0" length="'.$length.'" />';
				}
			}
			$xmlNew .= '</limits>';
			# limits


			# children
			$xmlNew .= '<children>';

			if(!empty($boData['children']))
			{
				foreach($boData['children'] as $index => $child)
				{
					$this->_generic->useModel($child, $this->_db_alias, 'user');
					try
					{
						$className = ucfirst($this->_db_alias.'_'.ucfirst($child));
						$classObject = new $className();

						$column = $classObject->getPrimaryKey();
						$table = strtolower($className);
						$xmlNew .= '<child table="'.$table.'" column="'.$column.'" />';
					}
					catch (Exception $e){}
				}
			}
			$xmlNew .= '</children>';
			# /children
			
			$newPath = (empty($newCategory)) ? '//sls_configs' : '//sls_configs/entry[@type="category" and @name="'.$newCategory.'"]';
			$this->_xmlBo->deleteTags($boPath);
			$this->_xmlBo->appendXMLNode($newPath, '<entry type="table" name="'.strtolower($this->_db_alias.'_'.$this->_table).'" multilanguage="'.($this->_object->isMultilanguage() ? 'true' : 'false').'">'.$xmlNew.'</entry>');
			$this->_xmlBo->saveXML($this->_generic->getPathConfig("configSls")."/bo.xml");
			$this->_xmlBo->refresh();
			
			// Crappy hack to force reload
			$this->_generic->forward("SLS_Bo","EditBo",array("name"=>$this->_http->getParam('name')));
		}
		# /reload
		else
		{
			$tempData = array(
				'columns' => $this->_xmlBo->getTagsAttributes($boPath."/columns/column",array("table","name","multilanguage","displayFilter", "displayList", "allowEdit", "allowHtml")),
				'joins' => $this->_xmlBo->getTagsAttributes($boPath."/joins/join",array("table")),
				'wheres' => $this->_xmlBo->getTagsAttributes($boPath."/wheres/where",array("table","column","value","mode")),
				'groups' => $this->_xmlBo->getTagsAttributes($boPath."/groups/group",array("table","column")),
				'orders' => $this->_xmlBo->getTagsAttributes($boPath."/orders/order",array("table","column","order")),
				'limits' => $this->_xmlBo->getTagsAttributes($boPath."/limits/limit",array("start","length")),
				'children' => $this->_xmlBo->getTagsAttributes($boPath."/children/child",array("table","column"))
			);

			# columns
			$boData['columns'] = array();
			$position = 1;
			$strings = array();
			foreach($tempData['columns'] as $column)
			{
				$table = SLS_String::substrAfterFirstDelimiter($column['attributes'][0]['value'], '_');
				
				// Avoid pk
				$class = ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($table);
				$this->_generic->useModel(SLS_String::tableToClass($table),$this->_db_alias,"user");
				$object = new $class();
				
				// String type ?
				if (!array_key_exists($table,$strings))
				{
					$columns = $this->_db->showColumns($table);
					for($i=0 ; $i<$count=count($columns) ; $i++)
					{
						$strings[$table][$columns[$i]->Field] = (SLS_String::contains($columns[$i]->Type,"text") || SLS_String::contains($columns[$i]->Type,"char")) ? true : false;
					}
				}
				
				// Avoid fk
				$isFk = $this->_xmlFk->getTags("//sls_configs/entry[@tableFk='".strtolower($this->_db_alias."_".$table)."' and @columnFk='".$column['attributes'][1]['value']."']/@tablePk");
				
				// Avoid quick edit on type file
				$specificTypeFileExists = $this->_xmlType->getTag("//sls_configs/entry[@table='".$column['attributes'][0]['value']."' and @column='".$column['attributes'][1]['value']."' and (@type='file_all' or @type='file_img')]/@column");
				
				array_push($boData['columns'], array(
					'table' => $table,
					'column_value' => $table.'.'.$column['attributes'][1]['value'],
					'column_label' => $table.' / '.$column['attributes'][1]['value'],
					'display_filter' => ($column['attributes'][3]['value'] == 'true') ? 'on' : 'off',
					'display_list' => ($column['attributes'][4]['value'] == 'true') ? 'on' : 'off',
					'allow_edit' => ($column['attributes'][5]['value'] == 'true') ? 'on' : 'off',
					'allow_html' => ($column['attributes'][6]['value'] == 'true') ? 'on' : 'off',
					'multilanguage' => ($column['attributes'][2]['value'] == 'true') ? 'on' : 'off',
					'type_file' => (!empty($specificTypeFileExists)) ? "true" : "false",
					'type_pk' => ($column['attributes'][1]['value'] == $object->getPrimaryKey() || $column['attributes'][1]['value'] == "pk_lang") ? "true" : "false",
					'type_fk' => ($isFk) ? "true" : "false",
					'type_string' => ($strings[$table][$column['attributes'][1]['value']]) ? "true" : "false"
				));
				$position++;
			}
			# /columns

			# joins
			$boData['joins'] = array();
			foreach($tempData['joins'] as $join)
				array_push($boData['joins'], SLS_String::substrAfterFirstDelimiter($join['attributes'][0]['value'], '_'));
			# /joins

			# wheres
			$boData['wheres'] = array();
			foreach($tempData['wheres'] as $where)
			{
				array_push($boData['wheres'], array(
					'column' => SLS_String::substrAfterFirstDelimiter($where['attributes'][0]['value'], '_').'.'.$where['attributes'][1]['value'],
					'mode' => $where['attributes'][3]['value'],
					'value' => $where['attributes'][2]['value']
				));
			}
			# /wheres

			# groups
			$boData['groups'] = array();
			foreach($tempData['groups'] as $group)
				array_push($boData['groups'], SLS_String::substrAfterFirstDelimiter($group['attributes'][0]['value'], '_').'.'.$group['attributes'][1]['value']);
			# /groups

			# orders
			$boData['orders'] = array();
			foreach($tempData['orders'] as $order)
			{
				array_push($boData['orders'], array(
					'column' =>  SLS_String::substrAfterFirstDelimiter($order['attributes'][0]['value'], '_').'.'.$order['attributes'][1]['value'],
					'order' => $order['attributes'][2]['value']
				));
			}
			# /orders

			# limits
			$boData['limits'] = array();
			foreach($tempData['limits'] as $limit)
			{
				array_push($boData['limits'], array(
					'length' =>  $limit['attributes'][1]['value']
				));
			}
			# /limits

			# children
			$boData['children'] = array();
			foreach($tempData['children'] as $child)
				array_push($boData['children'], SLS_String::substrAfterFirstDelimiter($child['attributes'][0]['value'], '_'));
			# /children
		}

		$xml->addFullTag("delete",$this->_generic->getFullPath("SLS_Bo","DeleteBo",array(),false));
		$menuCategoryExist = $this->_xmlBo->getTag("//sls_configs/entry[@type='category' and entry[@type='table' and @name='".strtolower($className)."']]/@name");
		$xml->startTag('bo');
			$xml->addFullTag('table', $this->_table, true);
			$xml->addFullTag('db_alias', $this->_db_alias, true);
			$xml->addFullTag('category', $menuCategoryExist, true);
			$xml->addFullTag('multilanguage', $tableAttributes['attributes'][0]['value'], true);
			$xml->addFullTag('class', $className, true);

			if(!empty($boData))
			{
				foreach($boData as $key => $values)
				{
					$xml->startTag($key);
					if(!empty($values) && is_array($values))
					{
						foreach($values as $value)
						{
							if(is_array($value))
							{
								$xml->startTag('line');
								foreach($value as $col => $val)
									$xml->addFullTag($col, $val, true);

								if($key == 'columns' && is_array($boData['groups']) && in_array($value['column_value'] , $boData['groups']))
									$xml->addFullTag('column_group', 'true', true);

								$xml->endTag('line');
							}
							else
								$xml->addFullTag('line', $value, true);
						}

					}
					$xml->endTag($key);
				}
			}
		$xml->endTag('bo');

		$children = $this->_xmlFk->getTagsAttributes("//sls_configs/entry[@tablePk='".(SLS_String::substrBeforeFirstDelimiter($tableName, '_').'_'.ucfirst(SLS_String::substrAfterFirstDelimiter($tableName, '_')))."']",array("tableFk", 'columnFk'));
		$xml->startTag('children');
		$childrenFound = array();
		if(!empty($children))
		{
			foreach($children as $child)
			{
				$bearerExists = $this->_xmlBearers->getTag("//sls_configs/entry[@tableBearer='".ucfirst(strtolower(SLS_String::substrBeforeFirstDelimiter($child['attributes'][0]['value'],"_")))."_".SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($child['attributes'][0]['value'],"_"))."']/@tableBearer");
				if (empty($bearerExists) && !in_array($child['attributes'][0]['value'],$childrenFound))
				{
					$xml->startTag('child');
						$tmp = SLS_String::substrAfterFirstDelimiter($child['attributes'][0]['value'], '_');
						$xml->addFullTag('child_selected', is_array($boData['children']) && in_array($tmp, $boData['children']) ? 'true' : 'false', true);
						$xml->addFullTag('child_value', $tmp, true);
					$xml->endTag('child');
					$childrenFound[] = $child['attributes'][0]['value'];
				}
			}
		}
		$xml->endTag('children');

		$joins = $this->_xmlFk->getTagsAttributes("//sls_configs/entry[@tableFk='".$tableName."']",array("tablePk", "columnFk"));
		$xml->startTag('joins');
		if(!empty($joins))
		{
			foreach($joins as $join)
			{
				$tableTmp = $join['attributes'][0]['value'];
				$tableLowerTmp = strtolower($join['attributes'][0]['value']);
				$tableNameLowerTmp = SLS_String::substrAfterFirstDelimiter($tableLowerTmp, '_');
				$columnTmp = $join['attributes'][1]['value'];

				$classNameTmp = ucfirst($tableTmp);
				$this->_generic->useModel($tableNameLowerTmp, $this->_db_alias, "user");
				$classObject = new $classNameTmp();

				if($classObject->getPrimaryKey() == $columnTmp)
				{
					$xml->addFullTag('join', $tableNameLowerTmp, true);
				}
			}
		}
		$xml->endTag('joins');

		$labels = array(
			'OPERATOR_LIKE' => "LIKE",
			'OPERATOR_NOTLIKE' => "NOT LIKE",
			'OPERATOR_STARTWITH' => "START WITH",
			'OPERATOR_ENDWITH' => "END WITH",
			'OPERATOR_EQUAL' => "EQUAL",
			'OPERATOR_NOTEQUAL' => "NOT EQUAL",
			'OPERATOR_IN' => "IN",
			'OPERATOR_NOTIN' => "NOT IN",
			'OPERATOR_LT' => "LESS THAN",
			'OPERATOR_LTE' => "LESS THAN EQUAL",
			'OPERATOR_GT' => "GREATER THAN",
			'OPERATOR_GTE' => "GREATER THAN EQUAL",
			'OPERATOR_NULL' => "IS NULL",
			'OPERATOR_NOTNULL' => "IS NOT NULL",
			'ORDER_ASC' => 'ASC',
			'ORDER_DESC' => 'DESC'
		);
		
		# operators
		$xml->startTag('operators');
		if(!empty($operators))
		{
			foreach($operators as $operator)
			{
				$xml->startTag('operator');
				$xml->addFullTag('operator_need_value', (is_array($operatorsNeedValue) && in_array($operator, $operatorsNeedValue)) ? 'true' : 'false', true);
				$xml->addFullTag('operator_value', $operator, true);
				$xml->addFullTag('operator_label', $labels['OPERATOR_'.mb_strtoupper($operator, 'UTF-8')], true);
				$xml->endTag('operator');
			}
		}
		$xml->endTag('operators');
		# /operators

		# orders
		$xml->startTag('orders');
		if(!empty($orders))
		{
			foreach($orders as $order)
			{
				$xml->startTag('order');
				$xml->addFullTag('order_value', $order, true);
				$xml->addFullTag('order_label', $labels['ORDER_'.mb_strtoupper($order, 'UTF-8')], true);
				$xml->endTag('order');
			}
		}
		$xml->endTag('orders');
		# /orders

		# limits
		$xml->startTag('limits');
		if(!empty($limits))
		{
			foreach($limits as $limit)
				$xml->addFullTag('limit', $limit, true);
		}
		$xml->endTag('limits');
		# /limits

		$xml->addFullTag("url_add_category",$this->_generic->getFullPath("SLS_Bo","AddBoCategory",array("name" => $this->_http->getParam("name"))),true);
		$xml->addFullTag("url_delete",$this->_generic->getFullPath("SLS_Bo","DeleteBo",array("name" => $this->_db_alias."_".$this->_table)),true);

		$this->saveXML($xml);
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$sql = SLS_Sql::getInstance();
		
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$errors = array();
		
		// Get the table name
		$table = SLS_String::substrAfterFirstDelimiter($this->_http->getParam("name"),"_");
		$db	   = SLS_String::substrBeforeFirstDelimiter($this->_http->getParam("name"),"_");
		$column= $this->_http->getParam("column");		
		$class = ucfirst($db)."_".SLS_String::tableToClass($table);
		$file  = ucfirst($db).".".SLS_String::tableToClass($table);
		
		// If current db is not this one
		if ($sql->getCurrentDb() != $db)
			$sql->changeDb($db);
		
		if ($sql->tableExists($table))
		{
			if ($this->_http->getParam("reload") == "true")
			{
				$replacements = array('&amp;','&gt;','&lt;','&#61;','"',"'");
				$masks = array('&','>','<','=','','','');
				
				$columnWanted 	= $this->_http->getParam("column");
				$tableWanted 	= $this->_http->getParam("table");
				$labelWanted 	= $this->_http->getParam($tableWanted.'_fkLabel');
				$labelSpecified = SLS_String::trimSlashesFromString($this->_http->getParam("fkLabel_specified"));				
				$multilang 		= $this->_http->getParam("multilanguage");
				$onDelete 		= $this->_http->getParam("ondelete");
								
				$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml");
				$xmlFk = new SLS_XMLToolbox($pathsHandle);
				$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/types.xml");
				$xmlType = new SLS_XMLToolbox($pathsHandle);
				$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/filters.xml");
				$xmlFilter = new SLS_XMLToolbox($pathsHandle);
				if (!empty($labelSpecified))
					$labelSpecified = str_replace(array('='),array('&#61;'),htmlentities(strtolower($labelSpecified),ENT_QUOTES,"UTF-8"));				
				$result = $xmlFk->getTags("//sls_configs/entry[@tableFk='".$db."_".$table."' and @columnFk='".$columnWanted."' and @tablePk='".$tableWanted."']");
				
				// If an entry already exists in the XML, delete this record
				if (!empty($result))
				{
					$xmlTmp = $xmlFk->deleteTags("//sls_configs/entry[@tableFk='".$db."_".$table."' and @columnFk='".$columnWanted."' and @tablePk='".$tableWanted."']");					
					$xmlFk->saveXML($this->_generic->getPathConfig("configSls")."/fks.xml",$xmlTmp);
					$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml");
					$xmlFk = new SLS_XMLToolbox($pathsHandle);
				}
				
				// Save it into the XML
				$xmlNode = '<entry tableFk="'.$db."_".$table.'" columnFk="'.$columnWanted.'" multilanguage="'.$multilang.'" ondelete="'.$onDelete.'" labelPk="'.(empty($labelSpecified) ? $labelWanted : $labelSpecified).'" tablePk="'.$tableWanted.'" />';					
				$xmlFk->appendXMLNode("//sls_configs",$xmlNode);
				$xmlFk->saveXML($this->_generic->getPathConfig("configSls")."/fks.xml",$xmlFk->getXML());
				
				// Update model
				$this->_generic->goDirectTo("SLS_Bo","UpdateModel",array(array("key"=>"name","value"=>$this->_http->getParam("name"))));
			}
			
			// Get generic object
			$this->_generic->useModel(SLS_String::tableToClass($table),$db,"user");
			$object = new $class();
			
			// Get object's infos
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml");
			$xmlFk = new SLS_XMLToolbox($pathsHandle);
			$columnsP = $object->getParams();
			$pk = $object->getPrimaryKey();
			$multilanguage = $object->isMultilanguage();		
			$xml->startTag("model");
			$xml->addFullTag("table",$table,true);
			$xml->addFullTag("db",$db,true);
			$xml->addFullTag("class",$class,true);
			$xml->addFullTag("pk",$pk,true);
			$xml->addFullTag("multilanguage",($multilanguage) ? "true" : "false",true);
			$xml->startTag("columns");
			foreach($columnsP as $key => $value)
			{							
				if ($object->getPrimaryKey() != $key && $key != "pk_lang")			
					$xml->addFullTag("column",$key,true);
			}
			$xml->endTag("columns");
						
			$attributes = array_shift($xmlFk->getTagsAttributes("//sls_configs/entry[@tableFk='".strtolower($db."_".$table)."' and @ columnFk='".$column."']",array("multilanguage","labelPk","tablePk","ondelete")));
			$this->_generic->useModel(SLS_String::substrAfterFirstDelimiter($attributes["attributes"][2]["value"],"_"),ucfirst(SLS_String::substrBeforeFirstDelimiter($attributes["attributes"][2]["value"],"_")),"user");
			$className = ucfirst($attributes["attributes"][2]["value"]);
			$objectN = new $className();
			$columns = $objectN->getColumns();
			$specificPattern = true;
			foreach($columns as $key)
				if ($key == $attributes["attributes"][1]["value"])
					$specificPattern = false;
			
			$xml->startTag("current_values");
				$xml->addFullTag("tableFk",$db."_".SLS_String::tableToClass($table),true);
				$xml->addFullTag("columnFk",$column,true);
				$xml->addFullTag("multilanguage",$attributes["attributes"][0]["value"],true);
				$xml->addFullTag("labelPk",$attributes["attributes"][1]["value"],true);
				$xml->addFullTag("tablePk",$attributes["attributes"][2]["value"],true);
				$xml->addFullTag("ondelete",$attributes["attributes"][3]["value"],true);
				$xml->addFullTag("specific_pattern",($specificPattern) ? "true" : "false",true);
			$xml->endTag("current_values");
			
			$tables = $this->getAllModels();
			
			sort($tables,SORT_REGULAR);			
				
			$xml->startTag("tables");			
			for($i=0 ; $i<$count=count($tables) ; $i++)
			{
				if (SLS_String::startsWith($tables[$i],$db))
				{
					$xml->startTag("table");
					$xml->addFullTag("name",SLS_String::substrAfterFirstDelimiter($tables[$i],"."));
					$xml->addFullTag("db",SLS_String::substrBeforeFirstDelimiter($tables[$i],"."));
					$tableN = SLS_String::substrAfterFirstDelimiter($tables[$i],".");
					$dbN = SLS_String::substrBeforeFirstDelimiter($tables[$i],".");
					$classN = ucfirst($dbN)."_".SLS_String::tableToClass($tableN);								
					$this->_generic->useModel($tableN,$dbN,"user");				
					$obj = new $classN();
					$properties = $obj->getParams();
					$xml->startTag("columns");
					foreach($properties as $key => $value)
						if ($key != "pk_lang")
							$xml->addFullTag("column",$key,true);
					$xml->endTag("columns");
					$xml->endTag("table");
				}
			}
				
			$xml->endTag("tables");	
			$xml->endTag("model");
		}
		else
		{
			$xml->addFullTag("error","Sorry this table doesn't exist anymore",true);
		}
		
		$this->saveXML($xml);
	}
示例#30
0
	/**
	 * Flush cache
	 * 
	 * @access private
	 * @param string $query the sql query you have to analyze
	 * @param string $delimiter the delimiter after table name
	 * @since 1.0.9
	 */
	private function flushCache($query,$delimiter="update")
	{		
		$query = strtolower($query);
		$table = str_replace('`','',SLS_String::substrBeforeFirstDelimiter(trim(SLS_String::substrAfterFirstDelimiter($query,$delimiter))," "));
		
		if ($this->tableExists($table))		
			$this->_cache->flushFromTable($table);		
	}