public function action()
	{
		$user 	= $this->hasAuthorative();
		$plugId = $this->_http->getParam('Plugin');
		$field 	= $this->_http->getParam('Field');
		$action = $this->_http->getParam('Action');
		$controllers = $this->_generic->getTranslatedController('SLS_Bo', 'EditPlugin');
		
		if (empty($plugId) || SLS_PluginsManager::isExists($plugId) === false)
			$this->dispatch('SLS_Bo', 'Plugins');
		
		$plugin = new SLS_PluginsManager($plugId);
		$xmlPlug = $plugin->getXML();
		
		if (empty($field) || empty($action))
			$this->redirect($controllers['controller']."/".$controllers['scontroller']."/Plugin/".$plugId.".sls");
		
				
		$xpath = "//".str_replace("|||", "/", str_replace("|$|", "]", str_replace("$|$", "[", $field)));
		
		$clonable = array_shift($xmlPlug->getTags($xpath."/@clonable"));
		if ($clonable != 1)
			$this->redirect($controllers['controller']."/".$controllers['scontroller']."/Plugin/".$plugId.".sls");
		
		$nodeName = SLS_String::substrBeforeLastDelimiter($xpath, "[");
			
		if ($action == "del" && count($xmlPlug->getTags($nodeName)) > 1)
		{
			$xmlPlug->deleteTags($xpath, 1);
		}
		if ($action == "add")
		{
			$node = new SLS_XMLToolbox($xmlPlug->getNode($xpath));
			$parent = SLS_String::substrBeforeLastDelimiter($xpath, "/");
			$xmlPlug->appendXMLNode($xpath, $node->getXml('noHeader'), 1, "after");
			$newIndex = SLS_String::substrBeforeLastDelimiter(SLS_String::substrAfterLastDelimiter($xpath, "["), "]");
			$newIndex++;
			$newNode = SLS_String::substrBeforeLastDelimiter($xpath, "[")."[".$newIndex."]";
			if ($xmlPlug->countChilds($newNode) == 0)
				$xmlPlug->setTag($newNode, "", false);
			else 
				$xmlPlug = $this->removeRecursiveValues($newNode, $xmlPlug);
			

			
			$xmlPlug->setTagAttributes($newNode, array("alias"=>uniqid()));
			
			
		}
		$plugin->saveXML($xmlPlug);		
		$this->redirect($controllers['controller']."/".$controllers['scontroller']."/Plugin/".$plugId.".sls");
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		
		$xml->startTag("templates");
		$handle = opendir($this->_generic->getPathConfig("viewsTemplates"));
		while($file = readdir($handle))
		{
			if (is_file($this->_generic->getPathConfig("viewsTemplates").$file) && substr($file, 0, 1) != ".")
			{
				$fileName 	= SLS_String::substrBeforeLastDelimiter($file,".");
				$extension 	= SLS_String::substrAfterLastDelimiter($file,".");
				
				if ($extension == "xsl" && $fileName != "__default")
				{
					$xml->startTag("template");
					$xml->addFullTag("name",$fileName,true);					
					$xml->endTag("template");
				}
			}
		}
		closedir($handle);
		$xml->addFullTag("url_add",$this->_generic->getFullPath("SLS_Bo","AddTemplate"),true);
		$xml->addFullTag("url_delete",$this->_generic->getFullPath("SLS_Bo","DeleteTemplate",array(),false),true);
		$xml->endTag("templates");		
		
		$xml->startTag("generics");
		$handle = opendir($this->_generic->getPathConfig("viewsGenerics"));
		while($file = readdir($handle))
		{
			if (is_file($this->_generic->getPathConfig("viewsGenerics").$file) && substr($file, 0, 1) != ".")
			{
				$fileName 	= SLS_String::substrBeforeLastDelimiter($file,".");
				$extension 	= SLS_String::substrAfterLastDelimiter($file,".");
				
				if ($extension == "xsl")
				{
					$xml->startTag("generic");
					$xml->addFullTag("name",$fileName,true);					
					$xml->endTag("generic");
				}
			}
		}
		closedir($handle);
		$xml->addFullTag("url_add",$this->_generic->getFullPath("SLS_Bo","AddGeneric"),true);
		$xml->addFullTag("url_delete",$this->_generic->getFullPath("SLS_Bo","DeleteGeneric",array(),false),true);
		$xml->endTag("generics");		
		
		$this->saveXML($xml);		
	}
Example #3
0
	/**
	 * Bind dependencies between mysql table and static|component|controller|action into controller_bind.json.
	 * This file is used to know if we need to flush cached files when we insert/update/delete datas into tables.
	 * 
	 * @access private
	 * @param string $query the sql select query you have to analyze
	 * @since 1.0.9
	 */
	private function logDependencies($query)
	{
		// If cache enabled, don't log dependencies
		if ($this->_generic->isCache())
			return true;
		
		// Objects
		$log = false;
		$query = strtolower($query);
		$tables = array();
				
		// Force explain on the query to grep tables
		$explains = $this->select("EXPLAIN ".$query);		
		for($i=0 ; $i<$count=count($explains) ; $i++)
			$tables[] = $explains[$i]->table;
		
		// Check all tables > real table name or f****n alias ?
		for($i=0 ; $i<$count=count($tables) ; $i++)
		{		
			if (!in_array($tables[$i],$this->_tables))
			{				
				if (SLS_String::endsWith($query," ".$tables[$i]))				
					$tables[$i] = str_replace('`','',SLS_String::substrAfterLastDelimiter(trim(SLS_String::substrBeforeLastDelimiter($query," ".$tables[$i]))," "));				
				else	
					$tables[$i] = str_replace('`','',SLS_String::substrAfterLastDelimiter(trim(SLS_String::substrBeforeFirstDelimiter($query," ".$tables[$i]." "))," "));
				
					
				if (!in_array($tables[$i],$this->_tables))
					unset($tables[$i]);
			}
		}
		
		if (!empty($tables))
		{			
			$traces = debug_backtrace();		
			for($i=0 ; $i<$count=count($traces) ; $i++)
			{
				$file = $traces[$i]["file"];
				if (SLS_String::contains($file,$this->_generic->getPathConfig("staticsControllers")))
				{
					$log = true;
					$name = strtolower(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($file,$this->_generic->getPathConfig("staticsControllers")),".controller.php"));
					foreach($tables as $table)
						$this->_cache->addBind($table,"statics",$name);
					break;
				}
				if (SLS_String::contains($file,$this->_generic->getPathConfig("componentsControllers")))
				{
					$log = true;					 
					$name = strtolower(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($file,$this->_generic->getPathConfig("componentsControllers")),".controller.php"));
					foreach($tables as $table)
						$this->_cache->addBind($table,"components",$name);
					break;
				}
				if (SLS_String::contains($file,$this->_generic->getPathConfig("actionsControllers")))
				{
					$log = true;
					if (SLS_String::contains($file,"/__") && SLS_String::contains($file,".protected.php"))
					{
						$name = strtolower(SLS_String::substrAfterFirstDelimiter($this->_generic->getControllerId(),"_"));
						foreach($tables as $table)
							$this->_cache->addBind($table,"controllers",$name);
						break;
					}
					else
					{
						$name = strtolower(SLS_String::substrAfterFirstDelimiter($this->_generic->getActionId(),"_"));
						foreach($tables as $table)
							$this->_cache->addBind($table,"actions",$name);
						break;
					}
				}
			}
			if ($log)			
				$this->_cache->saveBind();				
		}
	}
	/**
	 * 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);
		$errors = 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;
		
		if ($this->_http->getParam('reload') == 'true')
		{
			$controller = SLS_String::trimSlashesFromString($this->_http->getParam('controllerName'));
			$cache_visibility = SLS_String::trimSlashesFromString($this->_http->getParam('cache_visibility'));
			$cache_expiration = SLS_String::trimSlashesFromString($this->_http->getParam('cache_expiration'));
			$cache_responsive = SLS_String::trimSlashesFromString($this->_http->getParam('cache_responsive'));
			
			// 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($controller))
				array_push($errors, "You must fill the component controller name");
			if (in_array($cache_visibility,array("public","private")) && (!is_numeric($cache_expiration) || $cache_expiration < 0))
				array_push($errors, "Your expiration cache must be a positive time or 0");
			
			$controller = str_replace(" ", "", ucwords(trim(SLS_String::getAlphaString($controller))));
			
			$components = $this->_generic->recursiveReadDir($this->_generic->getPathConfig("componentsControllers"), array(), array(0=>"php"));
			foreach ($components as $component)
			{
				if (SLS_String::substrBeforeLastDelimiter(SLS_String::substrAfterLastDelimiter($component, "/"), ".controller.php") == $controller)
				{
					array_push($errors, "The name '".$controller."' is already in use for a component controller");
					break;
				}
			}
			
			if (empty($errors))
			{
				$strNewComponent = '<?php'."\n".
						   '/**'."\n".
						   '* Controller Component '.$controller.'Controller'."\n".
						   '*'."\n".
						   '* @author SillySmart'."\n".
						   '* @copyright SillySmart'."\n".
						   '* @package Mvc.Controllers.Components.'.$controller.'Controller'."\n".
						   '* @see Sls.Controllers.Core.SLS_FrontComponent'."\n".
						   '* @since 1.0'."\n".
						   '*/'."\n".
						   'class '.$controller.'Controller extends SLS_FrontComponent implements SLS_IComponent '."\n".
						   '{'."\n".
						   ''."\n".
						   t(1).'public function __construct()'."\n".
						   t(1).'{'."\n".
						   		t(2).'parent::__construct(true);'."\n".
						   t(1).'}'."\n".
						   ''."\n".
						   t(1).'public function constructXML()'."\n".
						   t(1).'{'."\n".
						   		t(2).'// Write here all your instructions to make your Component configuration with xml by $this->_xmlToolBox'."\n".
						   t(1).'}'."\n".
						   ''."\n".
						   '}'."\n".
						   '?>'; 
				file_put_contents($this->_generic->getPathConfig("componentsControllers").$controller.".controller.php", $strNewComponent);

				// Cache
				if (in_array($cache_visibility,array("public","private")))
				{
					$this->_cache->addObject(strtolower($controller),"components",$cache_visibility,($cache_responsive=="true") ? "responsive" : "no_responsive",$cache_expiration);
					$this->_cache->saveObject();
				}
				
				$this->_generic->forward('SLS_Bo', 'Controllers'); 
		
			}
			
			if (!empty($errors))
			{
				$xml->startTag("errors");
					foreach ($errors as $error)
						$xml->addFullTag("error", $error, true);
				$xml->endTag("errors");
				$xml->startTag('form');
					$xml->addFullTag("controllerName", $controller);
					$xml->addFullTag("cache_visibility", $cache_visibility,true);
					$xml->addFullTag("cache_expiration", $cache_expiration,true);
					$xml->addFullTag("cache_responsive", $cache_responsive,true);						
				$xml->endTag('form');
			}
		}
		else
		{
			$xml->startTag('form');
				$xml->addFullTag("controllerName", $controller,true);
				$xml->addFullTag("cache_visibility", "",true);
				$xml->addFullTag("cache_expiration", "0",true);
				$xml->addFullTag("cache_responsive", "",true);
			$xml->endTag('form');
		}
		
		$this->saveXML($xml);
	}
	public function action()
	{
		$user 	= $this->hasAuthorative();
		$xml = $this->makeMenu($this->getXML());
		$slsXml = $this->_generic->getCoreXML('sls');
		$errors = array();
		$syncServer = array_shift($slsXml->getTags("slsnetwork"));
		$action = $this->_http->getParam('Action');
		$serverID = $this->_http->getParam("Server");
		$pluginID = $this->_http->getParam("Plugin");
		$this->registerLink("CREATE", "SLS_Bo", "CreatePlugin");
		$controllers = $this->_generic->getTranslatedController('SLS_Bo', 'SearchPlugin');
		
		$serversJSON = @file_get_contents($syncServer);
		if ($serversJSON === false ||empty($serversJSON))
			$errors[] = "You are not connected to internet or synchronisation server is temporaly unavailable";
		else 
		{			
			$servers = json_decode($serversJSON);
			$pluginsServers = $servers->servers->plugins;
			$plugins = array();
			
			$xml->startTag("servers");
			
			foreach ($pluginsServers as $pluginsServer)
			{				
				$serverContent = @file_get_contents($pluginsServer->url);				
				
				$xml->startTag("server", array("name"=>$pluginsServer->name,"id"=>$pluginsServer->id));
					$xml->addFullTag("url", $pluginsServer->url, true, array("status"=>($serverContent === false || empty($serverContent)) ? "0" : "1"));

					if ($serverContent !== false && !empty($serverContent))
					{
						$serverContent = json_decode($serverContent);
						
						
						$xml->startTag("plugins");
						$plugs = $serverContent->plugins;
						foreach ($plugs as $plug)
						{
							
							// If we want to download this Plugin
							if ($action == "Download" && $pluginsServer->id == $serverID && $plug->id == $pluginID)
							{
								$way = $this->_http->getParam('Way');
								$pluginXML = $this->_generic->getPluginXml("plugins");
								if (count($pluginXML->getTags("//plugins/plugin[@id = '".$plug->id."']")) == 0 && count($pluginXML->getTags("//plugins/plugin[@code = '".$plug->code."' and @beta='1']")) == 0)
								{
									if (SLS_Remote::remoteFileExists($plug->file) != 0)
										$errors[] = $plug->name." is unavailable";
									else 
									{
										$filename = $this->_generic->getPathConfig("coreTmpDownload")."Plugins/".SLS_String::substrAfterLastDelimiter($plug->file, "/");
										if (!is_dir($this->_generic->getPathConfig("coreTmpDownload")."Plugins"))
											mkdir($this->_generic->getPathConfig("coreTmpDownload")."Plugins");
										$result = @copy($plug->file, $filename);
										if ($result === false)
											$errors[] = "The download of ".$plug->name." has failed";
										else 
										{
											$tar = new SLS_Tar();
											if ($tar->openTAR($filename) === false)
												$errors[] = "Plugin archive is corrupted";
											else 
											{
												$hasConf = false;
												$isFile = true;
												$pathName = "";
												foreach ($tar->directories as $directory)
												{
													if (SLS_String::startsWith($directory['name'], "Sources/"))
													{
														$dirName = SLS_String::substrAfterFirstDelimiter($directory['name'], "Sources/");
														if (!empty($dirName))
														{
															if (!is_dir($this->_generic->getPathConfig("plugins").$dirName))
																mkdir($this->_generic->getPathConfig("plugins").$dirName);
															if (empty($pathName))
																$pathName = (strpos($dirName, "/") !== false) ? SLS_String::substrBeforeLastDelimiter($dirName, "/") : $dirName;
															
															$isFile = false;
														}
													}
												}
												
												foreach ($tar->files as $file)
												{
													
													$copy = true;
													if (SLS_String::startsWith($file['name'], "Configs/") && SLS_String::endsWith($file['name'], ".xml"))
													{
														$hasConf = true;
														$copy = @file_put_contents($this->_generic->getPathConfig("configPlugins").$plug->id."_".$plug->code.".xml", $file['file']);
													}
													if (SLS_String::startsWith($file['name'], 'Sources/'))
													{
														if ($isFile === true && $pathName == "")
															$pathName = SLS_String::substrAfterFirstDelimiter($file['name'], "Sources/");
														$realPathFile = $this->_generic->getPathConfig("plugins").SLS_String::substrAfterFirstDelimiter($file['name'], "Sources/");
														$copy = @file_put_contents($realPathFile, $file['file']);
													}
													if ($copy === false)
													{
														$errors[] = "The copy of ".$file['name']." has failed";
													}
												}
												
												if (empty($errors))
												{
													$newPlugin = new SLS_XMLToolbox(false);
													$newPlugin->startTag("plugin", array("code"=>$plug->code,"id"=>$plug->id,"version"=>$plug->version,"compability"=>$plug->compability,"customizable"=>($hasConf) ? "1" : "0","file"=>($isFile)?"1":"0","path"=>$pathName));
														$newPlugin->addFullTag("name", $plug->name, true);
														$newPlugin->addFullTag("description", $plug->desc, true);
														$newPlugin->addFullTag("author", $plug->author, true);
														$newPlugin->addFullTag("dependencies", "", false);
													$newPlugin->endTag("plugin");
													$pluginXML->appendXMLNode("//plugins", $newPlugin->getXML('noHeader'));
													file_put_contents($this->_generic->getPathConfig("configPlugins")."plugins.xml", $pluginXML->getXML());
												}
												if (is_file($filename))
													unlink($filename);
											}
										}
									}
								}
								if ($way == "Maj")
								{
									$this->goDirectTo("SLS_Bo", "Plugins");
								}
								
							}//  /If we want to download this Plugin
							
							// We list all Plugins available on this server
							$exist = SLS_PluginsManager::isExists($plug->id);
							if ($exist)
							{
								$plugin = new SLS_PluginsManager($plug->id);
							}
							$xml->startTag("plugin", array("version"=>$plug->version,"code"=>$plug->code,"id"=>$plug->id,"compability"=>((float)$plug->compability<=(float)array_shift($slsXml->getTags("version"))) ? "1" : "0","has"=>($exist)?"1":"0"));
							$xml->addFullTag("name", $plug->name, true);
							$xml->addFullTag("doc", $pluginsServer->domain.$plug->doc, true);
							$xml->addFullTag("dl", $controllers['protocol']."://".$this->_generic->getSiteConfig("domainName")."/".$controllers['controller']."/".$controllers['scontroller']."/Action/Download/Server/".$pluginsServer->id."/Plugin/".$plug->id.".sls");
							$xml->addFullTag("desc", $plug->desc, true);
							$xml->addFullTag("author", $plug->author, true);
							$xml->endTag("plugin");
						}
						$xml->endTag("plugins");
					}
					
				$xml->endTag("server");
			}
			$xml->endTag("servers");
		}
		if (!empty($errors))
		{
			$xml->startTag("errors");
			foreach ($errors as $error)
				$xml->addFullTag("error", $error, true);
			$xml->endTag("errors");
		}		
		$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;
	}
	/**
	 * Get the source code of a model from his table
	 * 
	 * @param string $tableName the table name 
	 * @param string $db the alias of the database on which the model is located
	 * @return string $contentM the source code
	 */
	protected function getModelSource($tableName,$db)
	{
		$arrayConvertTypes = array(
			'varchar'	=>	'string',
			'tinyint'	=>	'int',
			'text'		=>	'string',
			'date'		=>	'string',
			'smallint'	=>	'int',
			'mediumint'	=>	'int',
			'int'		=>	'int',
			'bigint'	=>	'int',
			'float'		=>	'float | int',
			'double'	=>	'float | int',
			'decimal'	=>	'float',
			'datetime'	=>	'string',
			'timestamp'	=>	'int',
			'time'		=>	'string | int',
			'year'		=>	'int',
			'char'		=>	'string',
			'tinyblob'	=>	'string',
			'tinytext'	=>	'string',
			'blob'		=>	'string',
			'mediumblob'=>	'string',
			'mediumtext'=>	'string',
			'longblob'	=>	'string',
			'longtext'	=>	'string',
			'enum'		=>	'string',
			'set'		=>	'string',
			'bool'		=>	'int',
			'binary'	=>	'string',
			'varbinary'	=>	'string'
		);
		$sql 		= SLS_Sql::getInstance();
		$className 	= ucfirst($db)."_".SLS_String::tableToClass($tableName);
		$file 		= ucfirst($db).".".SLS_String::tableToClass($tableName);
		
		// Create empty source
		$contentM = "";
		$primaryKey = "";
		$multiLanguage = 'false';
		$sql->changeDb($db);
		$columns = $sql->showColumns($tableName);
		$fileName = ucfirst($db).".".SLS_String::tableToClass($tableName).".model.php";
		$primaryKey = "";
		$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);
		$fkMethods = array();
		$uniquesMultilang = array();
				
		// Create Model		
		$contentM = '<?php'."\n".
				   '/**'."\n".
				   ' * Object '.$className.''."\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.' extends SLS_FrontModel'."\n".
				   '{'."\n".
					   t(1).'/**'."\n".
				       t(1).' * Class variables'."\n".
					   t(1).' */'."\n";				   
		$pkFound = false;
		for($i=0 ; $i<$count=count($columns) ; $i++)
		{
			if (!$pkFound && $columns[$i]->Key == "PRI")
			{
				$primaryKey = SLS_String::removePhpChars($columns[$i]->Field);
				$pkFound = true;
			}
			if ($columns[$i]->Field == "pk_lang" && $columns[$i]->Key == "PRI")
				$multiLanguage = 'true';
			$contentM .= t(1).'protected $__'.SLS_String::removePhpChars($columns[$i]->Field).';'."\n";
		}
		
		$contentM .= t(1).'protected $_table = "'.$tableName.'";'."\n".
					 t(1).'protected $_db = "'.$db.'";'."\n".
					 t(1).'protected $_primaryKey = "'.$primaryKey.'";'."\n";
		
		// Show create table
		if ($multiLanguage == 'true')
		{
			$create = array_shift($sql->select("SHOW CREATE TABLE `".$tableName."`"));
			$instructions = array_map("trim",explode("\n",$create->{Create." ".Table}));						
			foreach($instructions as $instruction)
			{
				if (SLS_String::startsWith($instruction,"UNIQUE KEY"))
				{
					$uniqueColumns = explode(",",SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($instruction,"("),")"));
					if (count($uniqueColumns) == 2 && in_array("`pk_lang`",$uniqueColumns))
					{
						$uniqueColumn = array_shift($uniqueColumns);
						if ($uniqueColumn == "`pk_lang`")
							$uniqueColumn = array_shift($uniqueColumns);
							
						$uniquesMultilang[] = str_replace("`","",$uniqueColumn);
					}
				}
			}
		}
					 
		// Get FKs to create access reference functions
		$fks = $xmlFk->getTagsAttributes("//sls_configs/entry[@tableFk='".$db."_".$tableName."']",array("columnFk","tablePk"));
		$fkFunctions = "";
		$fkCursor = "";
		for($i=0 ; $i<$count=count($fks) ; $i++)
		{
			$tablePk = $fks[$i]["attributes"][1]["value"];
			$functionName = SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($tablePk,"_"))," ",false)),"");
			$functionName{0} = strtolower($functionName{0});
			$functionNameModified = $functionName;
			while(in_array($functionNameModified,$fkMethods))							
				$functionNameModified = $functionName."_".($fkCursor = (empty($fkCursor)) ? 2 : $fkCursor+1);			
			$fkMethods[] = $functionNameModified;
			$fkFunctions .= "'".$functionNameModified."'";
			if ($i < ($count - 1))
				$fkFunctions .= ", ";
		}
				
		$contentM .= t(1).'protected $_fks = array('.$fkFunctions.');'."\n";
		
		$contentM .= t(1).'public $_typeErrors = array();'."\n\n".
					 t(1).'/**'."\n".
				     t(1).' * Constructor '.$className.''."\n".
				     t(1).' * @author SillySmart'."\n".
				     t(1).' * @copyright SillySmart'."\n".
				     t(1).' * @param bool $mutlilanguage true if multilanguage content, else false'."\n".
				     t(1).' */'."\n".
					 t(1).'public function __construct($multilanguage='.$multiLanguage.')'."\n".
					 t(1).'{'."\n".
						 t(2).'parent::__construct($multilanguage);'."\n".
						 t(2).'$this->buildDefaultValues();'."\n".
					 t(1).'}'."\n\n";
		
		$contentM .= t(1).'/**'."\n".
				     t(1).' * Build default values for specific columns'."\n".
				     t(1).' * @author SillySmart'."\n".
				     t(1).' * @copyright SillySmart'."\n".
				     t(1).' */'."\n".
					 t(1).'public function buildDefaultValues()'."\n".
					 t(1).'{'."\n";
		
		for($i=0 ; $i<$count=count($columns) ; $i++)
		{
			$columnType = (strpos($columns[$i]->Type, "(")) ? SLS_String::substrBeforeFirstDelimiter(strtolower($columns[$i]->Type), "(") : $columns[$i]->Type;
			$functionName = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",SLS_String::removePhpChars($columns[$i]->Field))," ",false)),"");
			
			if ($columns[$i]->Null == "NO")
			{			
				// Dates
				if ($columnType == "date" || $columnType == "datetime" || $columnType == "timestamp" || $columnType == "year" || $columnType == "time")
				{
					switch ($columnType)
					{
						case "date":
							$contentM .= t(2).'$this->__'.$columns[$i]->Field.' = date("Y-m-d");'."\n";
							break;
						case "time":
							$contentM .= t(2).'$this->__'.$columns[$i]->Field.' = date("H:i:s");'."\n";
							break;
						case "datetime":
							$contentM .= t(2).'$this->__'.$columns[$i]->Field.' = date("Y-m-d H:i:s");'."\n";
							break;
						case "timestamp":
							$contentM .= t(2).'$this->__'.$columns[$i]->Field.' = date("Y-m-d H:i:s");'."\n";
							break;
						case "year":
							$contentM .= t(2).'$this->__'.$columns[$i]->Field.' = date("Y");'."\n";
							break;
					}
				}
				
				// Uniqid
				$result = $xmlType->getTags("//sls_configs/entry[@table='".$db."_".$tableName."' and @column='".SLS_String::removePhpChars($columns[$i]->Field)."' and @type='uniqid']");
				if (!empty($result))
				{
					$contentM .= t(2).'$this->__'.$columns[$i]->Field.' = substr(md5(time().substr(sha1(microtime()),0,rand(12,25))),mt_rand(1,20),40);'."\n";
				}
				
				// IP Address
				$result = array_shift($xmlType->getTags("//sls_configs/entry[@table='".$db."_".$tableName."' and @column='".SLS_String::removePhpChars($columns[$i]->Field)."' and (@type='ip_both' or @type='ip_v4' or @type='ip_v6')]/@type"));
				if (!empty($result))
				{
					$contentM .= t(2).'$this->__'.$columns[$i]->Field.' = $_SERVER["REMOTE_ADDR"];'."\n";
				}
			}
		}
		$contentM .= t(1).'}'."\n\n";
		
		for($i=0 ; $i<$count=count($columns) ; $i++)
		{
			$isPassword = false;
			
			if ($columns[$i]->Key != "PRI")
			{
				$column = SLS_String::removePhpChars($columns[$i]->Field);
				$columnType = (strpos($columns[$i]->Type, "(")) ? SLS_String::substrBeforeFirstDelimiter(strtolower($columns[$i]->Type), "(") : $columns[$i]->Type;
				$functionName = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$column)," ",false)),"");
				
				$contentM .= t(1).'/**'."\n".
						     t(1).' * Set the value of '.$column.''."\n".
						     t(1).' * Errors can be catched with the public variable $this->_typeErrors[\''.$column.'\']'."\n".
						     t(1).' * @author SillySmart'."\n".
						     t(1).' * @copyright SillySmart'."\n".
						     t(1).' * @param '.$arrayConvertTypes[$columnType].' $value'."\n".
						     t(1).' * @return bool true if updated, false if not'."\n".
						     t(1).' */'."\n".
							 t(1).'public function '.$functionName.'($value';
				
				if ($columns[$i]->Default !== null)
					$contentM .= '="'.SLS_String::addSlashesToString($columns[$i]->Default,false).'"';
					
				$contentM .= ')'."\n";
				$contentM .= t(1).'{'."\n";
				
				// Nullable case
				if ($columns[$i]->Null == "YES")
				{
					$contentM .= t(2).'if (empty($value))'."\n".
								 t(2).'{'."\n".
									 t(3).'$this->__set(\''.$column.'\', $value);'."\n".
									 t(3).'$this->flushError(\''.$column.'\');'."\n".
									 t(3).'return true;'."\n".
								 t(2).'}'."\n\n";
				}
				
				// Recover Fk
				$res = $xmlFk->getTagsByAttributes("//sls_configs/entry",array("tableFk","columnFk"),array($db."_".$tableName,$column));
				if (!empty($res))
				{
					$tableTm = substr($res,(strpos($res,'tablePk="')+9),(strpos($res,'"/>')-(strpos($res,'tablePk="')+9)));							
					$tablePk = SLS_String::substrAfterFirstDelimiter($tableTm,"_");
					$dbPk 	 = SLS_String::substrBeforeFirstDelimiter($tableTm,"_");
					$contentM .= 	 t(2).'$this->_generic->useModel("'.SLS_String::tableToClass($tablePk).'","'.$dbPk.'","user");'."\n".
									 t(2).'$object = new '.ucfirst($dbPk).'_'.SLS_String::tableToClass($tablePk).'();'."\n".
									 t(2).'if ($object->getModel($value) === false)'."\n".										 
									 t(2).'{'."\n".
										 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_KEY";'."\n".
										 t(3).'return false;'."\n".
									 t(2).'}'."\n".										 
									 t(2).'$this->__set(\''.$column.'\', $value);'."\n".
									 t(2).'$this->flushError(\''.$column.'\');'."\n".
									 t(2).'return true;'."\n".
								 t(1).'}'."\n\n";
				}
				
				// If not a fk
				else
				{
					// Check filters
					$results = $xmlFilter->getTags("//sls_configs/entry[@table='".$db."_".$tableName."' and @column='".$column."']/@filter");														
					for($j=0 ; $j<$countJ=count($results) ; $j++)
					{									
						switch($results[$j])
						{
							case "hash":
								$isPassword = true;
								$contentM .= t(2).'if (empty($value))'."\n".
										 	 	t(3).'$value = $this->__'.$column.';'."\n";
								break;
							default:
								$contentM .= t(2).'$value = SLS_String::filter($value,"'.$results[$j].'");'."\n";
								break;
						}
					}
					if (count($results) > 0)
						$contentM .= "\n";
						
					$result = $xmlType->getTags("//sls_configs/entry[@table='".$db."_".$tableName."' and @column='".$column."']");
					
					// Force specific type numeric
					if ($this->containsRecursive($columnType,array("int","float","double","decimal","real")))
					{
						$typeExists =($xmlType->getTag("//sls_configs/entry[@table='".$db."_".$tableName."' and @column='".$column."']/@type"));
						if (empty($typeExists))
						{
							file_get_contents($this->_generic->getFullPath("SLS_Bo",
																		  "AddType",
																		  array("name" => strtolower($db."_".$tableName),
																		  		"column" => $column,
																		  		"reload" => "true",
																		  		"type" => "num",
																		  		"num" => (SLS_String::contains($columns[$i]->Type,"unsigned")) ? "gte" : "all",
																		  		"token"	 => sha1(substr($this->_generic->getSiteConfig("privateKey"), 0, 3).substr($this->_generic->getSiteConfig("privateKey"), strlen($this->_generic->getSiteConfig("privateKey"))-3))),
																		  true));
							$xmlType->refresh();
						}
					}
					if (!empty($result))
					{
						$type = "";
						$array = array('color','uniqid','email','ip_both','ip_v4','ip_v6','url','file_all','file_img','position','num_all','num_gt','num_gte','num_lt','num_lte','complexity');
						for($j=0 ; $j<count($array) ; $j++)
						{
							$result = $xmlType->getTags("//sls_configs/entry[@table='".$db."_".$tableName."' and @column='".$column."' and @type='".$array[$j]."']");
							if (!empty($result))
							{
								$type = $array[$j];
								switch($type)
								{
									case "position":
										$contentM .= t(2).'if ($value == "" || $value == null || !is_int(intval($value)) || intval($value) < 0)'."\n".
											         t(2).'{'."\n".
												         t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
												         t(3).'return false;'."\n".
											         t(2).'}'."\n\n".
													 t(2).'$qbd = new SLS_QueryBuilder();'."\n".
													 t(2).'$old_'.$column.' = $this->__'.$column.';'."\n".
													 t(2).'if (empty($old_'.$column.'))'."\n".
											         t(2).'{'."\n".
											         	t(3).'$qbd->update()'."\n".
													         t(4).'->from("'.$tableName.'")'."\n".
													         t(4).'->set("`'.$column.'` = `'.$column.'` + 1")'."\n".
													         t(4).'->where($qbd->expr()->gte("'.$column.'",$value))'."\n".
															 t(4).'->groupBy("`'.$primaryKey.'`")'."\n".
													         t(4).'->execute();'."\n".
											         t(2).'}'."\n".
											         t(2).'else'."\n".
											         t(2).'{'."\n".
												    	 t(3).'if ($old_'.$column.' != $value)'."\n".
												    	 t(3).'{'."\n".
											    		 	t(4).'$qbd->update()'."\n".
													    		 t(5).'->from("'.$tableName.'")'."\n".
													    		 t(5).'->set("`'.$column.'` = `'.$column.'` ".(($old_'.$column.' < $value) ? "-" : "+")." 1")'."\n".
													    		 t(5).'->where($qbd->expr()->{($old_'.$column.' < $value) ? "gt" : "gte"}("'.$column.'",($old_'.$column.' < $value) ? $old_'.$column.' : $value))'."\n".
													    		 t(5).'->whereAnd($qbd->expr()->{($old_'.$column.' < $value) ? "lte" : "lt"}("'.$column.'",($old_'.$column.' < $value) ? $value : $old_'.$column.'))'."\n".
																 t(5).'->groupBy("`'.$primaryKey.'`")'."\n".
													    		 t(5).'->execute();'."\n".
														 	t(4).'$qbd->update()'."\n".
													    		 t(5).'->from("'.$tableName.'")'."\n".
													    		 t(5).'->set($qbd->expr()->eq("'.$column.'",$value))'."\n".
													    		 t(5).'->where($qbd->expr()->eq("'.$primaryKey.'",$this->__'.$primaryKey.'))'."\n".
																 t(5).'->groupBy("`'.$primaryKey.'`")'."\n".
													    		 t(5).'->execute();'."\n".
											    		 t(3).'}'."\n".													 
											    	 t(2).'}'."\n\n";
										break;
									case "color":
										$contentM .= t(2).'if (!ctype_xdigit($value))'."\n";
										$contentM .= t(2).'{'."\n".
														 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
														 t(3).'return false;'."\n".
													 t(2).'}'."\n\n";
										break;
									case "uniqid":										
										$contentM .= t(2).'if (empty($value))'."\n".
													 	t(3).'$value = substr(md5(time().substr(sha1(microtime()),0,rand(12,25))),mt_rand(1,20),40);'."\n\n";
										break;
									case "email":
										$contentM .= t(2).'if (!SLS_String::validateEmail($value))'."\n";
										$contentM .= t(2).'{'."\n".
												 		 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
												 		 t(3).'return false;'."\n".
											 		 t(2).'}'."\n\n";
										break;
									case "url":
										$contentM .= t(2).'if (!SLS_String::isValidUrl($value))'."\n";
										$contentM .= t(2).'{'."\n".
												 		 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
												 		 t(3).'return false;'."\n".
											 		 t(2).'}'."\n\n";
										break;
									case (in_array($type,array("ip_both","ip_v4","ip_v6"))):
										$type = SLS_String::substrAfterLastDelimiter($type,"_");
										
										$contentM .= t(2).'if (empty($value))'."\n".
													 	t(3).'$value = $_SERVER["REMOTE_ADDR"];'."\n\n";
										$contentM .= t(2).'if (!SLS_String::isIp($value,"'.$type.'"))'."\n";
										$contentM .= t(2).'{'."\n".
														 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
														 t(3).'return false;'."\n".
													 t(2).'}'."\n\n";												
										break;
									case (in_array($type,array("num_all","num_gt","num_gte","num_lt","num_lte"))):
										$type = SLS_String::substrAfterLastDelimiter($type,"_");										
										switch($type)
										{
											case "gt": 	$operator = "<="; 	break;
											case "gte": $operator = "<"; 	break;
											case "lt": 	$operator = ">="; 	break;
											case "lte": $operator = ">"; 	break;
										}
										if ($type != 'all')
										{
											$contentM .= t(2).'if ($value '.$operator.' 0)'."\n";
											$contentM .= t(2).'{'."\n".
													 		 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
													 		 t(3).'return false;'."\n".
												 		 t(2).'}'."\n\n";
										}
										break;
									case "complexity":
										$rules = $xmlType->getTag("//sls_configs/entry[@table='".$db."_".$tableName."' and @column='".$column."']/@rules");										
										$rules = explode("|",$rules);
										$complexityMin = false; 
										foreach($rules as $rule)
										{
											if (SLS_String::startsWith($rule,"min"))
											{
												$complexityMin = SLS_String::substrAfterFirstDelimiter($rule,"min");
												unset($rules[array_shift(array_keys($rules,$rule))]);
											}
											else
												$rules[array_shift(array_keys($rules,$rule))] = '"'.$rule.'"';
										}
										$rules = implode(",",$rules);
										$contentM .= t(2).'$complexity = array('.$rules.');'."\n".
													 t(2).'if ((in_array("lc",$complexity) && preg_match(\'`[[:lower:]]`\', $value) === 0) || (in_array("uc",$complexity) && preg_match(\'`[[:upper:]]`\', $value) === 0) || (in_array("digit",$complexity) && preg_match(\'`[[:digit:]]`\', $value) === 0) || (in_array("wild",$complexity) && preg_match(\'`[^a-zA-Z0-9]`\', $value) === 0))'."\n".
													 t(2).'{'."\n".
														t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_COMPLEXITY";'."\n".
														t(3).'return false;'."\n".
													 t(2).'}'."\n\n";
										if (is_numeric($complexityMin))
											$contentM .= t(2).'if (strlen(utf8_decode($value)) < '.$complexityMin.')'."\n".
														 t(2).'{'."\n".
															t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_LENGTH";'."\n".
															t(3).'return false;'."\n".
														 t(2).'}'."\n\n";
										break;
									case "file_all":
										$contentM .= t(2).'if (!empty($this->__'.$column.') && $this->__'.$column.' != "'.$columns[$i]->Default.'" && $this->__'.$column.' != $value && SLS_String::startsWith((is_array($value)) ? ((array_key_exists("data",$value)) ? $value["data"]["tmp_name"] : $value["tmp_name"]) : $value, $this->getTable()."/"))'."\n".
													 t(2).'{'."\n".
														 t(3).'$this->deleteFiles(array("'.$column.'"));'."\n".
														 t(3).'$this->__'.$column.' = "__Uploads/__Deprecated/".$this->__'.$column.';'."\n".
														 t(3).'$this->save();'."\n".
													 t(2).'}'."\n\n".
													 t(2).'if (is_array($value))'."\n".
													 t(2).'{'."\n".
													 	t(3).'if (array_key_exists("size",$value) && is_array($value["size"]))'."\n".
															t(4).'$size = $value["size"];'."\n".
														t(3).'if (array_key_exists("data",$value))'."\n".
															t(4).'$value = $value["data"];'."\n";
										if ($columns[$i]->Null == "YES") 
											$contentM .= t(3).'if ($value["error"] == 4)'."\n".
														 t(3).'{'."\n".
															 t(4).'$this->__set(\''.$column.'\',(empty($this->__'.$column.')) ? "" : $this->__'.$column.');'."\n".
															 t(4).'$this->flushError(\''.$column.'\');'."\n".
															 t(4).'return true;'."\n".
														 t(3).'}'."\n";
										$contentM .= t(3).'if ($value["error"] == 1 || $value["error"] == 2)'."\n".
													 t(3).'{'."\n".
														 t(4).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_SIZE";'."\n".
														 t(4).'return false;'."\n".
													 t(3).'}'."\n".
													 t(3).'else'."\n".
													 t(3).'{'."\n".
														 t(4).'try {'."\n".
															 t(5).'if (!file_exists($this->_generic->getPathConfig("files").$this->_table))'."\n".
														 	 	t(6).'mkdir($this->_generic->getPathConfig("files").$this->_table,0755);'."\n\n".
															 t(5).'$token = substr(md5(time().substr(sha1(microtime()),0,rand(5,12))),mt_rand(1,20),10);'."\n".
															 t(5).'$fileName = SLS_String::sanitize(SLS_String::substrBeforeLastDelimiter($value["name"],"."),"_")."_".$token.".".SLS_String::substrAfterLastDelimiter($value["name"],".");'."\n".
															 t(5).'rename($value["tmp_name"],$this->_generic->getPathConfig("files").$this->_table."/".$fileName);'."\n".
															 t(5).'$value = $this->_table."/".$fileName;'."\n".
														 t(4).'}'."\n".
														 t(4).'catch (Exception $e) {'."\n".
															 t(5).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_WRITE";'."\n".
															 t(5).'return false;'."\n".
														 t(4).'}'."\n".
													 t(3).'}'."\n".
													 t(2).'}'."\n\n";
										break;
									case "file_img":
										$contentM .= t(2).'if (!empty($this->__'.$column.') && $this->__'.$column.' != "'.$columns[$i]->Default.'" && $this->__'.$column.' != $value && SLS_String::startsWith((is_array($value)) ? ((array_key_exists("data",$value)) ? $value["data"]["tmp_name"] : $value["tmp_name"]) : $value, $this->getTable()."/"))'."\n".
													 t(2).'{'."\n".
														 t(3).'$this->deleteFiles(array("'.$column.'"));'."\n".
														 t(3).'$this->__'.$column.' = "__Uploads/__Deprecated/".$this->__'.$column.';'."\n".
														 t(3).'$this->save();'."\n".
													 t(2).'}'."\n\n".
													 t(2).'if (is_array($value))'."\n".
													 t(2).'{'."\n".
													 	t(3).'if (array_key_exists("size",$value) && is_array($value["size"]))'."\n".
															t(4).'$size = $value["size"];'."\n".
														t(3).'if (array_key_exists("data",$value))'."\n".
															t(4).'$value = $value["data"];'."\n";
										if ($columns[$i]->Null == "YES")
											$contentM .= t(3).'if ($value["error"] == 4)'."\n".
														 t(3).'{'."\n".
															 t(4).'$this->__set(\''.$column.'\',(empty($this->__'.$column.')) ? "" : $this->__'.$column.');'."\n".
															 t(4).'$this->flushError(\''.$column.'\');'."\n".
															 t(4).'return true;'."\n".
														 t(3).'}'."\n";
										$contentM .= t(3).'if ($value["error"] == 1 || $value["error"] == 2)'."\n".
													 t(3).'{'."\n".
														 t(4).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_SIZE";'."\n".
														 t(4).'return false;'."\n".
													 t(3).'}'."\n".
													 t(3).'else'."\n".
													 t(3).'{'."\n".
														 t(4).'try {'."\n".
															 t(5).'if (!file_exists($this->_generic->getPathConfig("files").$this->_table))'."\n".
												 			 	t(6).'mkdir($this->_generic->getPathConfig("files").$this->_table,0755);'."\n\n".
															 t(5).'$tmpName = $value["tmp_name"];'."\n".
															 t(5).'if (!SLS_String::startsWith($tmpName,$this->_generic->getPathConfig("files")) || !SLS_String::contains($tmpName,"."))'."\n".
															 t(5).'{'."\n".
																 t(6).'if (!file_exists($this->_generic->getPathConfig("files")."__Uploads"))'."\n".
																 	t(7).'@mkdir($this->_generic->getPathConfig("files")."__Uploads");'."\n".
																 t(6).'if (!file_exists($this->_generic->getPathConfig("files")."__Uploads/__Deprecated"))'."\n".
																 	t(7).'@mkdir($this->_generic->getPathConfig("files")."__Uploads/__Deprecated");'."\n".
																 t(6).'$newName = $this->_generic->getPathConfig("files")."__Uploads/__Deprecated/".SLS_String::substrAfterLastDelimiter($tmpName,"/").((!SLS_String::contains($tmpName,".")) ? ".".SLS_String::substrAfterLastDelimiter($value["name"],".") : "");'."\n".
																 t(6).'rename($tmpName,$newName);'."\n".
																 t(6).'$tmpName = $newName;'."\n".
															 t(5).'}'."\n".
															 t(5).'$token = substr(md5(time().substr(sha1(microtime()),0,rand(5,12))),mt_rand(1,20),10);'."\n".
															 t(5).'$fileName = SLS_String::sanitize(SLS_String::substrBeforeLastDelimiter($value["name"],"."),"_")."_".$token;'."\n".
														 	 t(5).'$extension = pathinfo($tmpName, PATHINFO_EXTENSION);'."\n\n".
															 t(5).'// Check img'."\n".
															 t(5).'$img = new SLS_Image($tmpName);'."\n".
															 t(5).'if ($img->getParam("existed"))'."\n".
															 t(5).'{'."\n".
																 t(6).'// Default crop'."\n".
																 t(6).'if (empty($size))'."\n".
																 	t(7).'$size = array("x" => "0", "y" => "0", "w" => $img->getParam("width"), "h" => $img->getParam("height"));'."\n\n".
																 t(6).'// Crop image'."\n".
																 t(6).'$img->crop($size["x"],$size["y"],$size["w"],$size["h"]);'."\n".											 
																 t(6).'// Check thumbs'."\n".
																 t(6).'$xmlType = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/types.xml"));'."\n".
																 t(6).'$result = array_shift($xmlType->getTagsAttribute("//sls_configs/entry[@table=\'".$this->getDatabase()."_".$this->getTable()."\' and @column=\''.$column.'\' and @type=\'file_img\']","thumbs"));'."\n".
																 t(6).'$thumbs = unserialize(str_replace("||#||",\'"\',$result["attribute"]));'."\n".
																 t(6).'if (!empty($thumbs))'."\n".
																 t(6).'{'."\n".
																	 t(7).'for($i=0 ; $i<$count=count($thumbs) ; $i++)'."\n".
																	 t(7).'{'."\n".
															 			t(8).'$img->transform($thumbs[$i]["width"],$thumbs[$i]["height"],$this->_generic->getPathConfig("files").$this->_table."/".$fileName.$thumbs[$i]["suffix"].".".$extension,$extension);'."\n".
																	 t(7).'}'."\n".
															 	 t(6).'}'."\n\n".
															 	 t(6).'// Move original'."\n".
															 	 t(6).'rename($tmpName,$this->_generic->getPathConfig("files").$this->_table."/".$fileName.".".$extension);'."\n".
															 t(5).'}'."\n".
															 t(5).'else'."\n".
															 t(5).'{'."\n".
																 t(6).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
																 t(6).'return false;'."\n".
															 t(5).'}'."\n".
															 t(5).'$value = $this->_table."/".$fileName.".".$extension;'."\n".
														 t(4).'}'."\n".
														 t(4).'catch (Exception $e) {'."\n".
															 t(5).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_WRITE";'."\n".
															 t(5).'return false;'."\n".
														 t(4).'}'."\n".
													 t(3).'}'."\n".
												t(2).'}'."\n\n";
										break;
								}
								break;
							}
						}
					}
					 			 
					// Not Nullable
					if ($columns[$i]->Null == "NO")
					{
						$contentM .= t(2).'if ($value === "")'."\n".
									 t(2).'{'."\n".
										 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_EMPTY";'."\n".
										 t(3).'return false;'."\n".
									 t(2).'}'."\n\n";
					}
					
					if ($isPassword)
					{
						$result = array_shift($xmlFilter->getTagsAttribute("//sls_configs/entry[@table='".$db."_".$tableName."' and @column='".$column."']","hash"));
						$hash = (empty($result["attribute"])) ? "sha1" : $result["attribute"];
						$contentM .= t(2).'if ($value != $this->__'.$column.')'."\n".
									 	t(3).'$value = SLS_String::filter($value,"hash","'.$hash.'");'."\n\n";
					}
					
					// Not Nullable
					if ($columns[$i]->Null == "NO")
					{
						$contentM .= t(2).'if (is_null($value))'."\n".
									 t(2).'{'."\n".
										 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_NULL";'."\n".
										 t(3).'return false;'."\n".
									 t(2).'}'."\n\n";
					}
					
					// Check change
					$contentM .= t(2).'if ($this->__'.$column.' == $value)'."\n".
								 t(2).'{'."\n".
									t(3).'$this->flushError(\''.$column.'\');'."\n".								 
					 			 	t(3).'return true;'."\n".
					 			 t(2).'}'."\n\n";
					
					// Unique
					if ($columns[$i]->Key == "UNI" || in_array($column,$uniquesMultilang))
					{
						$contentM .= t(2).'if (!$this->isUnique(\''.SLS_String::addSlashes($column, 'QUOTES').'\',$value))'."\n".
									 t(2).'{'."\n".
										 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_UNIQUE";'."\n".
										 t(3).'return false;'."\n".
									 t(2).'}'."\n\n";
					}
					
					// Float types
					if (SLS_String::startsWith($columnType,"float") || SLS_String::startsWith($columnType,"double") || SLS_String::startsWith($columnType,"decimal"))
					{
						$length = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter(SLS_String::substrBeforeLastDelimiter($columns[$i]->Type, ')'), '('), ",");
						if (empty($length))
							$length = "25";
						$contentM .= t(2).'$decimal = (strpos($value, \',\')) ? str_replace(\',\', \'.\', $value) : (!strpos($value, \'.\')) ? $value.\'.0\' : $value;'."\n".									
									 t(2).'if (!is_numeric($decimal))'."\n".
									 t(2).'{'."\n".
										 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
										 t(3).'return false;'."\n".
									 t(2).'}'."\n\n".
									 t(2).'if ((strlen($decimal)-1) > '.$length.')'."\n".
									 t(2).'{'."\n".
										 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_LENGTH";'."\n".
										 t(3).'return false;'."\n".
									 t(2).'}'."\n\n";
					}
					
					// Enum types
					else if ($columnType == "enum" || $columnType == "set")
					{						
						$values = SLS_String::substrAfterFirstDelimiter(SLS_String::substrBeforeLastDelimiter($columns[$i]->Type, "')"), "('");
						
						if ($columnType == "enum")
						{
							$contentM .= t(2).'$values = explode("\',\'", "'.str_replace("''", "\'", $values).'");'."\n".									
										 t(2).'if (!in_array($value, $values))'."\n".
										 t(2).'{'."\n".
											 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_CONTENT";'."\n".
											 t(3).'return false;'."\n".
										 t(2).'}'."\n\n";
						}
						else
						{
							$contentM .= t(2).'$values = explode("\',\'", "'.str_replace("''", "\'", $values).'");'."\n".
										 t(2).'$valueE = explode(",",$value);'."\n".
								         t(2).'foreach($valueE as $set)'."\n".
								         t(2).'{'."\n".
											 t(3).'if (!in_array($set, $values))'."\n".
											 t(3).'{'."\n".
												 t(4).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_CONTENT";'."\n".
												 t(4).'return false;'."\n".
											 t(3).'}'."\n".
										 t(2).'}'."\n\n";
						}									 
					}
					else 
					{						
						if (strpos($columns[$i]->Type, "("))
						{
							$length = SLS_String::substrAfterFirstDelimiter(SLS_String::substrBeforeLastDelimiter($columns[$i]->Type, ")"), "(");
							$contentM .= t(2).'if (strlen(utf8_decode($value)) > '.$length.')'."\n".
										 t(2).'{'."\n".
											 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_LENGTH";'."\n".
											 t(3).'return false;'."\n".
										 t(2).'}'."\n\n";
						}
						if(SLS_String::endsWith($columnType, "int"))
						{
							$contentM .= t(2).'if (!is_numeric($value))'."\n".
										 t(2).'{'."\n".
											 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
											 t(3).'return false;'."\n".
										 t(2).'}'."\n\n";
						}
						else if ($columnType == "date" || $columnType == "datetime" || $columnType == "timestamp")
						{
							switch ($columnType)
							{
								case "date":
									$contentM .= t(2).'if (!SLS_Date::isDate($value))'."\n";
									break;
								case "datetime":
									$contentM .= t(2).'if (!SLS_Date::isDateTime($value))'."\n";
									break;
								case "timestamp":
									$contentM .= t(2).'if (!SLS_Date::isDateTime($value))'."\n";
									break;
							}
							$contentM .= t(2).'{'."\n".
											 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
											 t(3).'return false;'."\n".
										 t(2).'}'."\n\n";
						}
						else if ($columnType == "time" || $columnType == "year")
						{
							switch ($columnType)
							{
								case "time":
									$contentM .= t(2).'if (strpos(\':\', $value) && substr_count($value, \':\') != 2)'."\n".
	 											 t(2).'{'."\n".
		 											 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
													 t(3).'return false;'."\n".
												 t(2).'}'."\n\n".
												 t(2).'$check = explode(\':\', $value);'."\n".	
												 t(2).'if (count($check) == 1 && !is_numeric($check[0]))'."\n".	
												 t(2).'{'."\n".
		 											 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
													 t(3).'return false;'."\n".
												 t(2).'}'."\n".
												 t(2).'else if ((count($check) > 1) && (!is_numeric($check[0]) || (!is_numeric($check[1]) || strlen($check[1]) > 2) || (!is_numeric($check[2]) || strlen($check[2]) > 2)))'."\n".	
												 t(2).'{'."\n".
		 											 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
													 t(3).'return false;'."\n".
												 t(2).'}'."\n\n";
									break;
								case "year":
									$contentM .= t(2).'if (!mktime(0, 0, 0, 0, 0, $value))'."\n".
	 											 t(2).'{'."\n".
		 											 t(3).'$this->_typeErrors[\''.SLS_String::addSlashes($column, 'QUOTES').'\'] = "E_TYPE";'."\n".
													 t(3).'return false;'."\n".
												 t(2).'}'."\n\n";
									break;
							}
						}
						
					}
					$contentM .= 		t(2).'$this->__set(\''.$column.'\', $value);'."\n".
										t(2).'$this->flushError(\''.$column.'\');'."\n".
										t(2).'return true;'."\n".
									t(1).'}'."\n\n";
				}
			}						
		}
		
		// Get FKs to create access reference functions
		$fks = $xmlFk->getTagsAttributes("//sls_configs/entry[@tableFk='".$db."_".$tableName."']",array("columnFk","tablePk"));
		$fkMethods = array();
		$fkCursor = "";
		for($i=0 ; $i<$count=count($fks) ; $i++)
		{
			$columnFk = $fks[$i]["attributes"][0]["value"];
			$tablePk = $fks[$i]["attributes"][1]["value"];
			
			$functionName = SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($tablePk,"_"))," ",false)),"");
			$functionName{0} = strtolower($functionName{0});
			$functionNameModified = $functionName;
			while(in_array($functionNameModified,$fkMethods))							
				$functionNameModified = $functionName."_".($fkCursor = (empty($fkCursor)) ? 2 : $fkCursor+1);			
			$fkMethods[] = $functionNameModified;
			$contentM .= t(1).'/**'."\n".
					     t(1).' * Get the instance of '.SLS_String::substrAfterFirstDelimiter($tablePk,"_").'\'s Model described by '.$columnFk.''."\n".  
					     t(1).' * @author SillySmart'."\n".
					     t(1).' * @copyright SillySmart'."\n".
					     t(1).' * @return '.SLS_String::tableToClass($tablePk).' $object the instance of '.SLS_String::substrAfterFirstDelimiter($tablePk,"_").'\'s Model'."\n".
					     t(1).' */'."\n".
						 t(1).'public function '.$functionNameModified.'()'."\n".
						 t(1).'{'."\n".
							 t(2).'$this->_generic->useModel("'.SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($tablePk,"_")).'","'.SLS_String::substrBeforeFirstDelimiter($tablePk,"_").'","user");'."\n".
						     t(2).'$object = new '.ucfirst(SLS_String::substrBeforeFirstDelimiter($tablePk,"_")).'_'.SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($tablePk,"_")).'();'."\n".
						     t(2).'$object->getModel($this->__'.$columnFk.');'."\n".
						     t(2).'return $object;'."\n".
						 t(1).'}';
			$contentM .= ($i == ($count-1)) ? "\n" : "\n\n";
		}
		
		$contentM .= '}'."\n".
					 '?>';
		
		return $contentM;
	}
	/**
	 * Get columns of a given table
	 * 
	 * @param string $db the db alias of the table
	 * @param string $table the wanted table you want to extract columns infos
	 * @param string $boPath xPath of the table in bo.xml
	 * @param string $classFather the father model (if children)
	 * @param bool $needPk if you want primary_key
	 * @param bool $needBoSettings if you want bo listing privileges (list|edit|filter)
	 * @return array $columns columns of the table
	 */
	public function getTableColumns($db,$table,$boPath="",$classFather="",$needPk=false,$needBoSettings=false)
	{
		$infosTable = $this->_db->showColumns($table);
		$isMultilanguage = false; 
		$uniquesMultilang = array();
		$columns = array();
		foreach((is_array($infosTable)) ? $infosTable : array($infosTable) as $infoTable)
		{
			if ($infoTable->Key == "PRI" && $infoTable->Field == "pk_lang")
			{
				$isMultilanguage = true;
				break;
			}
		}
		
		// Show create table
		if ($isMultilanguage)
		{
			$create = array_shift($this->_db->select("SHOW CREATE TABLE `".$table."`"));
			$instructions = array_map("trim",explode("\n",$create->{Create." ".Table}));						
			foreach($instructions as $instruction)
			{
				if (SLS_String::startsWith($instruction,"UNIQUE KEY"))
				{
					$uniqueColumns = explode(",",SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($instruction,"("),")"));
					if (count($uniqueColumns) == 2 && in_array("`pk_lang`",$uniqueColumns))
					{
						$uniqueColumn = array_shift($uniqueColumns);
						if ($uniqueColumn == "`pk_lang`")
							$uniqueColumn = array_shift($uniqueColumns);
							
						$uniquesMultilang[] = str_replace("`","",$uniqueColumn);
					}
				}
			}
		}
		
		// Get columns
		if (is_array($infosTable))
		{
			foreach($infosTable as $infoTable)
			{
				$pk = "false";
				
				// Switch primary keys
				if ($infoTable->Key == "PRI")
				{
					if (!$needPk)
						continue;
					else
						$pk = "true";
				}
				
				// Column
				$column = array("db" 						=> $db,
								"table" 					=> $table,
								"name" 						=> $infoTable->Field,
								"pk" 						=> $pk,
								"label" 					=> $infoTable->Field,
								"multilanguage" 			=> ($this->_object->isMultilanguage()) ? "true" : "false",
								"native_type" 				=> "string",
								"html_type" 				=> "input_text",
								"specific_type" 			=> "",
								"specific_type_extended" 	=> "",
								"file_uid"					=> uniqid(),
								"image_ratio" 				=> "*",
								"image_thumb"				=> "",
								"image_min_width" 			=> "*",
								"image_min_height" 			=> "*",
								"html" 						=> "false",
								"choices" 					=> array(),	
								"values" 					=> (empty($classFather)) ? $this->_langsValues : array(),
								"errors" 					=> array(),
								"required" 					=> "true",
								"unique" 					=> "false",				
								"default" 					=> "",
								"ac_db" 					=> "",
								"ac_entity" 				=> "",
								"ac_fk"						=> "",
								"ac_column" 				=> "",
								"ac_label" 					=> "",
								"ac_pattern" 				=> "",
								"ac_multiple" 				=> "",
								"min_length" 				=> "",
								"max_length" 				=> "",
								"filters" 					=> "");
				if ($needBoSettings)
				{
					$column["list"] = "true";
					$column["edit"] = "false";
					$column["filter"] = "true";
					
					if (!empty($boPath))
					{
						$columnBoAttributes = array_shift($this->_xmlBo->getTagsAttributes($boPath."/columns/column[@name='".$column["name"]."']",array("displayList","allowEdit","displayFilter")));
						if (!empty($columnBoAttributes))
						{
							$columnBoAttributesOptions 	= array("true","false");
							$column["list"] 			= (in_array($columnBoAttributes["attributes"][0]["value"],$columnBoAttributesOptions)) ? $columnBoAttributes["attributes"][0]["value"] : "true";
							$column["edit"] 			= (in_array($columnBoAttributes["attributes"][1]["value"],$columnBoAttributesOptions)) ? $columnBoAttributes["attributes"][1]["value"] : "false";
							$column["filter"] 			= (in_array($columnBoAttributes["attributes"][2]["value"],$columnBoAttributesOptions)) ? $columnBoAttributes["attributes"][2]["value"] : "true";
						}
					}	
				}
				
				// Comment
				$comment = empty($infoTable->Comment) ? $infoTable->Field : $infoTable->Comment;
				if (SLS_String::startsWith($comment,"sls:lang:"))
				{
					$key = strtoupper(SLS_String::substrAfterFirstDelimiter($comment,"sls:lang:"));
					$comment = (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$key])) ? (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$key]) ? $infoTable->Field : $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$key]) : $GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$key];
				}
				if (!empty($comment))
					$column["label"] = $comment;
				
				// Native type, possible choices
				$nativeType = $infoTable->Type;
				$columnValues = array();
				switch($nativeType)
				{
					case (false !== $typeMatch = $this->containsRecursive($nativeType,array("int"))):
						$columnType = "int";
						$column["html_type"] = "input_number";
						break;
					case (false !== $typeMatch = $this->containsRecursive($nativeType,array("float","double","decimal","real"))):
						$columnType = "float";
						$column["html_type"] = "input_number";
						break;
					case (false !== $typeMatch = $this->containsRecursive($nativeType,array("year","datetime","timestamp","time","date"))):
						$columnType = ($typeMatch == "timestamp") ? "datetime" : $typeMatch;
						$column["html_type"] = "input_".$typeMatch;
						if ($infoTable->Null == "NO")
						{
							switch ($typeMatch)
							{
								case "year": $column["default"] = date("Y"); 			break;
								case "time": $column["default"] = date("H:i:s"); 		break;
								case "date": $column["default"] = date("Y-m-d"); 		break;
								default: 	 $column["default"] = date("Y-m-d H:i:s"); 	break;
							}
						}
						break;
					case (false !== $typeMatch = $this->containsRecursive($nativeType,array("enum","set"))):
						$columnType = "string";
						$column["html_type"] = ($typeMatch == "enum") ? "input_radio" : "input_checkbox";
						$columnValues = explode("','",SLS_String::substrAfterFirstDelimiter(SLS_String::substrBeforeLastDelimiter($nativeType, "')"), "('"));
						break;
					case (false !== $typeMatch = $this->containsRecursive($nativeType,array("text"))):
						$columnType = "string";
						$column["html_type"] = "input_textarea";
						break;
					default:
						$columnType = "string";
						$column["html_type"] = "input_text";
						break;
				}
				$column["native_type"] = $columnType;
				$column["choices"] = $columnValues;
				
				// MaxLength
				if (SLS_String::contains($infoTable->Type,"(") && SLS_String::endsWith(trim($infoTable->Type),")"))
				{
					$maxLength = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($infoTable->Type,"("),")");
					$column["max_length"] = (is_numeric($maxLength) && $maxLength > 0) ? $maxLength : "";
				}
				
				// Nullable ? unique ? default value ?
				$column["required"] = ($infoTable->Null == "NO") ? "true" : "false";
				$column["unique"] = ($infoTable->Key == "UNI" || in_array($column["name"],$uniquesMultilang)) ? "true" : "false";
				if (empty($column["default"]))
					$column["default"] = (empty($infoTable->Default)) ? "" : $infoTable->Default;
				
				// Allow HTML & i18n
				if (!empty($boPath))
				{
					$columnBoAttributes = array_shift($this->_xmlBo->getTagsAttributes($boPath."/columns/column[@name='".$column["name"]."']",array("allowHtml","multilanguage")));				
					if (!empty($columnBoAttributes))
					{
						$allowHtml = $columnBoAttributes["attributes"][0]["value"];
						$isMultilang = $columnBoAttributes["attributes"][1]["value"];
						$column["html"] = ($allowHtml == "true") ? "true" : "false";
						$column["multilanguage"] = ($isMultilang == "true") ? "true" : "false";
					}
				}
				
				// Specific type & extended
				$typeExists = array_shift($this->_xmlType->getTagsAttributes("//sls_configs/entry[@table='".$this->_db_alias."_".$table."' and @column='".$column["name"]."']",array("type","rules","thumbs")));
				if (!empty($typeExists))
				{
					$specificType = $typeExists["attributes"][0]["value"];
					$specificRules = $typeExists["attributes"][1]["value"];
					$specificThumbs = unserialize(str_replace("||#||",'"',$typeExists["attributes"][2]["value"]));
					$specificTypeExtended = "";
					
					switch($specificType)
					{
						case "address": 	/* Nothing */ 		break;
						case "color": 		/* Nothing */ 		break;
						case "email": 		/* Nothing */ 		break;
						case "url": 		/* Nothing */ 		break;
						case "position":
							$record = array_shift($this->_db->select("SELECT MAX(`".$column["name"]."`) AS max_position FROM `".$table."` "));
							$column["default"] = (!empty($record->max_position) && is_numeric($record->max_position) && $record->max_position > 0) ? ($record->max_position+1) : 1;
							break;
						case "uniqid":
							// Generate uid
							$column["default"] = substr(md5(time().substr(sha1(microtime()),0,rand(12,25))),mt_rand(1,20),(!empty($column["max_length"])) ? $column["max_length"] : 40);
							break;
						case (SLS_String::startsWith($specificType,"num_")):
							// Get numeric settings
							$specificTypeExtended = SLS_String::substrAfterFirstDelimiter($specificType,"num_");
							$specificType = "numeric";
							break;
						case (SLS_String::startsWith($specificType,"ip_")):
							// Get IP settings
							$specificTypeExtended = SLS_String::substrAfterFirstDelimiter($specificType,"ip_");
							$specificType = "ip";
							$column["default"] = $_SERVER['REMOTE_ADDR'];
							break;
						case (SLS_String::startsWith($specificType,"file_")):
							// Get file settings
							$specificTypeExtended = SLS_String::substrAfterFirstDelimiter($specificType,"file_");
							$specificType = "file";
							$column["html_type"] = "input_file";
							if ($specificTypeExtended == "img")
							{	
								if (!empty($specificThumbs))
								{	
									usort($specificThumbs,array($this,'sortThumbsMin'));
									$thumb = array_shift($specificThumbs);
									if (!empty($thumb["suffix"]))
										$column["image_thumb"] =  $thumb["suffix"];
								}
								$column["image_ratio"] = SLS_String::substrBeforeFirstDelimiter($specificRules,"|");
								$column["image_min_width"] = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($specificRules,"|"),"|");
								$column["image_min_height"] = SLS_String::substrAfterLastDelimiter($specificRules,"|");
							}
							break;
						case ($specificType == "complexity" && (!empty($specificRules))):
							// Get complexity settings & minLength
							if (SLS_String::contains($specificRules,"min"))
							{
								$column["min_length"] = SLS_String::substrAfterFirstDelimiter($specificRules,"min");
								$specificRules = SLS_String::substrBeforeFirstDelimiter($specificRules,"min");
								if (SLS_String::endsWith($specificRules,"|"))
									$specificRules = SLS_String::substrBeforeLastDelimiter($specificRules,"|");
							}
							$specificTypeExtended = $specificRules;							
							break;
						default: 			$specificType = "";		break;
					}
					$column["specific_type"] 			= $specificType;
					$column["specific_type_extended"] 	= $specificTypeExtended;
				}
				
				if (!empty($column["default"]) && SLS_String::startsWith($column["html_type"],"input_file"))
					$column["default"] = (file_exists($this->_generic->getPathConfig("files").$column["default"])) ? SLS_String::getUrlFile($column["default"]) : "";
				
				// Filters
				$filters = $this->_xmlFilter->getTags("//sls_configs/entry[@table='".$this->_db_alias."_".$table."' and @column='".$column["name"]."']/@filter");
				for($i=0 ; $i<$count=count($filters) ; $i++)
				{
					if ($filters[$i] == "hash")
						$column["html_type"] = "input_password";
					else
						$column["filters"] .= (((!empty($column["filters"])) ? "|" : "").$filters[$i]);
				}
				
				// pk_lang
				if ($needPk && $isMultilanguage && $infoTable->Field == "pk_lang")
				{
					$column["html_type"] = "input_radio";
					$column["choices"] = $this->_lang->getSiteLangs();
				}
				
				// Fk
				$columnFk = array();
				$fkExists = array_shift($this->_xmlFk->getTagsAttributes("//sls_configs/entry[@tableFk='".$this->_db_alias."_".$table."' and @columnFk='".$column["name"]."']",array("tablePk","labelPk")));
				if (!empty($fkExists))
				{
					$tableAlias = $this->_db_alias;
					$tableFk = $table;
					$tablePk = $fkExists["attributes"][0]["value"];
					$labelPk = $fkExists["attributes"][1]["value"];
					
					$this->_generic->useModel(SLS_String::substrAfterFirstDelimiter($tablePk,"_"),$tableAlias,"user");
					$classFk = ucfirst($tableAlias)."_".SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($tablePk,"_"));
					$objectFk = new $classFk();
					$pk = $objectFk->getPrimaryKey();								
					$str = $labelPk;
					$labelPkReal = $labelPk;
					$params = $objectFk->getParams(true,true);								
					foreach($params as $key => $value)
					{
						if (is_array($value))
						{
							foreach($value as $key2 => $value2)
							{
								if (SLS_String::contains($str,$key2))
								{
									$this->_generic->useModel($key,$tableAlias,"user");
									$classFk2 = ucfirst($tableAlias)."_".SLS_String::tableToClass($key);
									$object2 = new $classFk2();
									$str = str_replace($key2,$object2->getColumnComment($key2),$str);
								}
							}
						}
						else
						{			
							if (SLS_String::contains($str,$key))
								$str = str_replace($key,$objectFk->getColumnComment($key),$str);
						}
					}
					$labelPk = $str;
										
					$column["html_type"] = "input_ac";
					$column["ac_db"] = strtolower($tableAlias);
					$column["ac_entity"] = strtolower($tableFk);
					$column["ac_fk"] = $tablePk;
					$column["ac_column"] = $column["name"];
					if (SLS_String::startsWith($labelPk,"sls:lang:"))
					{	
						$globalKey = strtoupper(SLS_String::substrAfterFirstDelimiter($labelPk,"sls:lang:"));
						$labelPk = (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$globalKey])) ? (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$globalKey]) ? $labelPk : $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$globalKey]) : $GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$globalKey];
					}
					$column["ac_label"] = $labelPk;
					$column["ac_pattern"] = $labelPkReal;
					$column["ac_multiple"] = "false";
					if ($column["required"] == "false")
						$column["default"] = "0";
				}
				else
					$tablePk = null;
				
				if (empty($classFather) || (!empty($classFather) && $classFather != ucfirst($tablePk)))
					$columns[$column["name"]] = $column;
			}
		}
		
		return $columns;
	}
	/**
	 * Delete n objects of models
	 * 
	 * @param string $table the current table to delete (default: empty => current model)
	 * @param array $joins the table(s) to join with current table (default: empty => no join)
	 * If you want to natural join: 
	 * <code>array("table_2","table_3","...","table_n")</code> will give 'DELETE FROM table_1 NATURAL JOIN table_2 NATURAL JOIN table_3 ... NATURAL JOIN table_n'
	 * If you want to join with a specific column: 
	 * <code>array(0=>array("table"=>"table_2","column"=>"column_2"),1=>array("table"=>"table_3","column"=>"column_3"))</code>
	 * If you want to inner/left/right join:
	 * <code>array(0=>array("table"=>"table_2","column"=>"column_2","mode"=>"natural"),1=>array("table"=>"table_3","column"=>"column_3","mode"=>"left"))</code>
	 * @param array $clause the clause wanted (default: empty => no clause)
	 * <code>
	 * array
	 * (
	 *		[0] => array
	 *				(
	 *					["column"] = "column_1",
	 *					["value"] = "value_1",
	 *					["mode"] = "like" or "notlike" or "beginwith" or "endwith" or "equal" or "notequal" or "lt" or "le" or "ge" or "gt" or "null" or "notnull"
	 *				)
	 *		[1] => array
	 *				(
	 *					["column"] = "user_department",
	 *					["value"] = "75",
	 *					["mode"] = "like" or "notlike" or "beginwith" or "endwith" or "equal" or "notequal" or "lt" or "le" or "ge" or "gt" or "null" or "notnull"
	 *				)
	 * )
	 * </code>
	 * @return int $count the number of lines deleted
	 * @see SLS_FrontModel::searchModels
	 * @since 1.0.6
	 */
	public function deleteModels($table,$joins,$clause)
	{
		$allowToJoin = false;
		$modeJoin = "inner";
		$modesJoin = array("inner","left","right");
		$columns = array();
		
		/**
		 * TABLE NAME
		 */
		// If table name haven't been filled, try to recover table name from the current model
		if (empty($table))
		{
			$table = (empty($this->_table)) ? substr(get_class($this),0,strlen(get_class($this))-3) : $this->_table;
		}
		// If table name is again empty, throw a Sls Exception
		if (empty($table))
		{
			SLS_Tracing::addTrace(new Exception("Error: Table's name has been omitted"),true);
			return false;
		}
		// If model doesn't exists
		if ($this->_generic->useModel(SLS_String::tableToClass($table),$this->_db->getCurrentDb(),"user") || $this->_generic->useModel(SLS_String::tableToClass($table),$this->_db->getCurrentDb(),"sls"))
		{
			$className = ucfirst(strtolower($this->_db->getCurrentDb()))."_".SLS_String::tableToClass($table);
			$object = new $className();
			foreach($object->getParams() as $key => $value)
				array_push($columns,$key);
		}
		else
		{
			SLS_Tracing::addTrace(new Exception("Error: Table `".$table."` doesn't exist in database `".($this->_db->getCurrentDb())."`"),true);
			return false;
		}
		/**
		 * /TABLE NAME
		 */

		
		/**
		 * JOINS
		 */
		// Get all the columns of the current table
		$columnsMain = $columns;
		$joinMain = $table;
		
		// If we want to join tables
		if (is_array($joins) && !empty($joins))
		{
			// Foreach tables to join
			foreach ($joins as $currentJoin)
			{
				// If we want joins with the clause "using"
				if (is_array($currentJoin))
				{
					// Override join mode ?
					if (array_key_exists("mode",$currentJoin))					
						$modeJoin = (in_array(strtolower($currentJoin["mode"]),$modesJoin)) ? strtolower($currentJoin["mode"]) : array_shift($modesJoin);
					
					$currentJoin = $currentJoin["table"];
				}
				
				// If the table to join doesn't exists in MySQL, throw a Sls Exception
				if (!$this->_generic->useModel(SLS_String::tableToClass($currentJoin),$this->_db->getCurrentDb(),"user") && !$this->_generic->useModel(SLS_String::tableToClass($currentJoin),$this->_db->getCurrentDb(),"sls"))
					SLS_Tracing::addTrace(new Exception("Warning: Table `".$currentJoin."` to join with `".$joinMain."` doesn't exist in database `".(SLS_Generic::getInstance()->getDbConfig("base"))."`"),true);			
				// Else check if we can join
				else 
				{
					$className = ucfirst(strtolower($this->_db->getCurrentDb()))."_".SLS_String::tableToClass($currentJoin);
					$objectJoin = new $className();
					$columnsJoin = array();
					
					// Get all the columns of the table to join
					foreach($objectJoin->getParams() as $key => $value)
						array_push($columnsJoin,$key);
					
					// If we want joins with the clause "using", allow to join and merge the columns of the table to join with all the columns already listed
					if (is_array($currentJoin))
					{
						$allowToJoin = true;
						$columnsMain = array_merge($columnsMain,$columnsJoin);	
					}
					// Else if we want a "NATURAL JOIN", check if we have a common key
					else
					{
						// Foreach columns of the current table
						foreach($columnsMain as $tMain)
						{
							// Foreach columns of the table to join
							foreach($columnsJoin as $tJoin)
							{
								// If we have a common column, allow to join and merge the columns of the table to join with all the columns already listed
								if ($tJoin == $tMain)
								{
									$allowToJoin = true;
									$columnsMain = array_merge($columnsMain,$columnsJoin);
								}
							}
						}
					}
					
					// If we can't join, throw a Sls Exception
					if (!$allowToJoin)
					{
						SLS_Tracing::addTrace(new Exception("Warning: Table `".$currentJoin."` to join with `".$joinMain."` doesn't have a common key"),true);
						$joins = array();
						break;
					}
					
					// Move the reference table
					$joinMain = $currentJoin;
				}
			}
		}
		
		// Build the start of the query
		$sql = "DELETE `".$table."` FROM `".$table."` ";
		
		// If we can join, build the join
		if ($allowToJoin && is_array($joins) && !empty($joins))
		{
			foreach ($joins as $currentJoin)
			{
				if (is_array($currentJoin))
					$sql .= strtoupper($modeJoin)." JOIN "."\n".
					"    `".$currentJoin["table"]."` USING(".$currentJoin["column"].") ";
				else
					$sql .= "NATURAL JOIN "."\n".
					"    `".$currentJoin."` ";
			}
		}
		/**
		 * /JOINS
		 */
				
		
		/**
		 * CLAUSE
		 */
		// If we want a clause where
		if (!empty($clause))
		{			
			$lastSucceeded = false;
			// Foreach items to restrict
			for($i=0 ; $i<count($clause) ; $i++)
			{
				// If column on which you want to apply a restrict clause is in the list of columns collected on the tables
				$columnName = (SLS_String::contains($clause[$i]["column"],".")) ? SLS_String::substrAfterLastDelimiter($clause[$i]["column"],".") : $clause[$i]["column"];				
				if (in_array($columnName,$columnsMain))
				{
					$sql .= ($lastSucceeded) ? " AND " : " WHERE ";
					
					// Build the correct statement
					$clause[$i]["column"] = "`".$clause[$i]["column"]."`";
					switch($clause[$i]["mode"])
					{
						case "like":
							$sql .= ("LOWER(".$clause[$i]["column"].") LIKE ".$this->_db->quote("%".strtolower($clause[$i]["value"])."%"));
							break;
						case "notlike":
							$sql .= ("LOWER(".$clause[$i]["column"].") NOT LIKE ".$this->_db->quote("%".strtolower($clause[$i]["value"])."%"));
							break;							
						case "beginwith":
							$sql .= ("LOWER(".$clause[$i]["column"].") LIKE ".$this->_db->quote(strtolower($clause[$i]["value"])."%"));
							break;
						case "endwith":
							$sql .= ("LOWER(".$clause[$i]["column"].") LIKE ".$this->_db->quote("%".strtolower($clause[$i]["value"])));
							break;
						case "equal":
							$sql .= ("".$clause[$i]["column"]." = ".$this->_db->quote($clause[$i]["value"]));	
							break;
						case "notequal":
							$sql .= ("".$clause[$i]["column"]." != ".$this->_db->quote($clause[$i]["value"]));	
							break;
						case "lt":
							$sql .= ("".$clause[$i]["column"]." < ".$this->_db->quote($clause[$i]["value"]));
							break;
						case "le":
							$sql .= ("".$clause[$i]["column"]." <= ".$this->_db->quote($clause[$i]["value"]));
							break;
						case "ge":
							$sql .= ("".$clause[$i]["column"]." >= ".$this->_db->quote($clause[$i]["value"]));
							break;
						case "gt":
							$sql .= ("".$clause[$i]["column"]." > ".$this->_db->quote($clause[$i]["value"]));
							break;
						case "null":
							$sql .= ("".$clause[$i]["column"]." IS NULL ");
							break;
						case "notnull":
							$sql .= ("".$clause[$i]["column"]." IS NOT NULL ");
							break;
						case "in":
							$clause[$i]["value"] = (is_array($clause[$i]["value"])) ? array_map(array($this->_db, 'quote'),$clause[$i]["value"]) : $clause[$i]["value"];
							$sql .= ("".$clause[$i]["column"]." IN (".((is_array($clause[$i]["value"]) ? implode(",",$clause[$i]["value"]) : $this->_db->quote($clause[$i]["value"]))).") ");
							break;
						case "notin":
							$clause[$i]["value"] = (is_array($clause[$i]["value"])) ? array_map(array($this->_db, 'quote'),$clause[$i]["value"]) : $clause[$i]["value"];
							$sql .= ("    ".$clause[$i]["column"]." NOT IN (".((is_array($clause[$i]["value"]) ? implode(",",$clause[$i]["value"]) : $this->_db->quote($clause[$i]["value"]))).") ");
							break;
						default:
							$sql .= ("LOWER(".$clause[$i]["column"].") LIKE ".$this->_db->quote("%".strtolower($clause[$i]["value"])."%"));
							break;
					}						
					$lastSucceeded = true;
				}
				// Else, throw a Sls Exception
				else
					SLS_Tracing::addTrace(new Exception("Warning: Column ".$clause[$i]["column"]." in clause where doesn't exist in table `".$table."` (and collected tables to join)"),true);
			}
		}
		/**
		 * /CLAUSE
		 */
				
		
		// Try to execute the built query
		try
		{
			return $this->_db->delete($sql);		
		}
		catch (Exception $e)
		{			
			SLS_Tracing::addTrace($e,true);
			return false;
		}
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$confirmation = $this->_http->getParam("confirm", 'post');
		$password = SLS_String::trimSlashesFromString($this->_http->getParam("password", 'post'));
		$login = SLS_String::trimSlashesFromString($this->_http->getParam("login", 'post'));
		$stepPassword = false;
		if ($confirmation == 'reset')
		{
			$stepPassword = true;
			if (!empty($password) && !empty($login))
			{
				$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))
				{
					
					 $paths = array(
						'actionsControllers',
					 	'staticsControllers',
					 	'componentsControllers',
						'viewsBody',
						'viewsHeaders',
					 	'viewsGenerics',
						'models',
						'modelsSql',
					 	'coreSlsModels',
					 	'coreSlsModelsSql',
						'actionLangs',
						'genericLangs',
						'plugins',
						'jsStatics',
						'jsDyn',
						'img',
						'css',
						'fonts',
						'configPlugins',
					 	'files',
					 	'cache',
					 	'logs'
					); 
					
					// Destroy Files
					foreach ($paths as $path)
					{
						if (!is_dir($this->_generic->getPathConfig($path)))
							continue;
						$files = scandir($this->_generic->getPathConfig($path));
						for($i=0;$i<$count=count($files);$i++)
						{
							if ($files[$i] != "." && $files[$i] != ".." && $files[$i] != ".svn")
								(is_file($this->_generic->getPathConfig($path).$files[$i])) ? @unlink($this->_generic->getPathConfig($path).$files[$i]) : $this->_generic->rm_recursive($this->_generic->getPathConfig($path).$files[$i]);							
						}
					}
					
					// Destroy xsl templates except __default
					$files = scandir($this->_generic->getPathConfig("viewsTemplates"));
					for($i=0;$i<$count=count($files);$i++)
					{
						if (!SLS_String::startsWith($files[$i],".") && $files[$i] != "__default.xsl" && is_file($this->_generic->getPathConfig("viewsTemplates").$files[$i]))
							@unlink($this->_generic->getPathConfig("viewsTemplates").$files[$i]);						
					}
					
					// Destroy Generics Translations
					$files = scandir($this->_generic->getPathConfig("coreGenericLangs"));
					for($i=0;$i<$count=count($files);$i++)
					{
						if ($files[$i] != "." && $files[$i] != ".." && $files[$i] != ".svn")
							(is_file($this->_generic->getPathConfig("coreGenericLangs").$files[$i])) ? @unlink($this->_generic->getPathConfig("coreGenericLangs").$files[$i]) : $this->_generic->rm_recursive($this->_generic->getPathConfig("coreGenericLangs").$files[$i]);
					}
					
					// Deploy the sls Generic En Lang
					@copy($this->_generic->getPathConfig('installDeployement')."Langs/Generics/generic.en.lang.php", $this->_generic->getPathConfig("coreGenericLangs")."generic.en.lang.php");
					
					// Update Controllers XML
					$controllersXML = $this->_generic->getControllersXML();
					$controllersXML->deleteTags("//controllers/controller[@side='user']");
										
					// Reset Metas
					$metasXML = new SLS_XMLToolBox(file_get_contents($this->_generic->getPathConfig("configSls")."metas.xml"));
					$slsControllers = $controllersXML->getTags("//controllers/controller[@side='sls']/@id");	
					$slsLangs = $controllersXML->getTags("//controllers/controller[@side='sls'][1]/scontrollers/scontroller[1]/scontrollerLangs/scontrollerLang/@lang");
					foreach ($slsControllers as $controller)
					{
						$slsActions = $controllersXML->getTags("//controllers/controller[@side='sls' and @id='".$controller."']/scontrollers/scontroller/@id");
						foreach ($slsActions as $slsAction)
						{
							foreach ($slsLangs as $lang)
							{
								$title = array_shift($metasXML->getTags("//sls_configs/action[@id='".$slsAction."']/title[@lang='".$lang."']"));
								$controllersXML->setTagAttributes("//controllers/controller[@side='sls' and @id='".$controller."']/scontrollers/scontroller[@id='".$slsAction."']/scontrollerLangs/scontrollerLang[@lang='".$lang."']", array("title"=>$title));
							}
							$controllersXML->deleteTagAttribute("//controllers/controller[@side='sls' and @id='".$controller."']/scontrollers/scontroller[@id='".$slsAction."']", "id");
						}
						$controllersXML->deleteTagAttribute("//controllers/controller[@side='sls' and @id='".$controller."']", "id");
					}
										
					// Reset Bo Access
					$controllersXML->deleteContentTag("//controllers/controller[@side='sls' and @name='SLS_Bo']/controllerLangs/controllerLang[@lang='en']");
					$controllersXML->saveXML($this->_generic->getPathConfig("configSecure")."controllers.xml",$controllersXML->getXML());
					$controllersXML->refresh();
					
					// Upate Others XML
					$configs = scandir($this->_generic->getPathConfig("configSecure"));
					foreach($configs as $config)
					{
						if (!SLS_String::startsWith($config,".") && $config != "controllers.xml" && $config != "paths.xml")
							@unlink($this->_generic->getPathConfig("configSecure").$config);
					}
					@copy($this->_generic->getPathConfig('installDeployement')."Configs/Site/cache.xml", $this->_generic->getPathConfig("configSecure")."cache.xml");
					@copy($this->_generic->getPathConfig('installDeployement')."Configs/Site/db.xml", $this->_generic->getPathConfig("configSecure")."db.xml");
					@copy($this->_generic->getPathConfig('installDeployement')."Configs/Site/mail.xml", $this->_generic->getPathConfig("configSecure")."mail.xml");
					@copy($this->_generic->getPathConfig('installDeployement')."Configs/Site/site.xml", $this->_generic->getPathConfig("configSecure")."site.xml");
					@copy($this->_generic->getPathConfig('installDeployement')."Configs/Site/project.xml", $this->_generic->getPathConfig("configSecure")."project.xml");
					
					// Reset the SLS Config Files					
					$xmls = $this->_generic->recursiveReadDir($this->_generic->getPathConfig('installDeployement')."Configs/Sls/", array(), array("xml","json"));
					foreach ($xmls as $file)
					{
						$fileName = SLS_String::substrAfterLastDelimiter($file, "/");
						@unlink($this->_generic->getPathConfig("configSls").$fileName);
						@copy($file, $this->_generic->getPathConfig("configSls").$fileName);
					}
					
					// Reset Plugins Config
					$xmls = $this->_generic->recursiveReadDir($this->_generic->getPathConfig('installDeployement')."Configs/Plugins/", array(), array("xml"));
					foreach ($xmls as $file)
					{
						$fileName = SLS_String::substrAfterLastDelimiter($file, "/");
						@copy($file, $this->_generic->getPathConfig("configPlugins").$fileName);
					}
					
					// Reset session
					$this->_generic->getObjectSession()->destroy();
					 
					header("Location: /");
					exit; 
				}
			}
		}
		$xml->addFullTag('stepPassword', ($stepPassword) ? 'yes' : 'no', true);
		$this->saveXML($xml);
	}
	/**
	 * Format recordsets
	 * 
	 * @param SLS_XMLToolBox $xml
	 * @param array PDO $recordsets
	 * @param string $fkRecursiveExists
	 * @return SLS_XMLToolBox $xml modified
	 */
	public function formatRecordsets($xml,$recordsets,$fkRecursiveExists="")
	{	
		$xml->startTag("entities");
		for($i=0 ; $i<$count=count($recordsets) ; $i++)
		{
			$xml->startTag("entity",array("gap" => $this->_gap));
			foreach($recordsets[$i] as $key => $value)
			{	
				if (array_key_exists($key,$this->_columns) && ($this->_columns[$key]["list"] == "true" || $key == $this->_object->getPrimaryKey()))
				{
					$hashExists = $this->_xmlFilter->getTag("//sls_configs/entry[@table='".strtolower($this->_db_alias."_".$this->_columns[$key]["table"])."' and @column='".$key."' and @filter='hash']/@hash");
					
					if (!empty($this->_columns[$key]["specific_type"]))
					{
						switch($this->_columns[$key]["specific_type"])
						{
							case "email":
								if (SLS_String::validateEmail($value))
									$value = "<a href='mailto:".$value."' target='_blank' class='sls-bo-color-text'>".$value."</a>";
								break;
							case "url":
								if (SLS_String::isValidUrl($value))
									$value = "<a href='".$value."' target='_blank' class='sls-bo-color-text'>".SLS_String::substrAfterLastDelimiter($value,"://")."</a>";
								break;
							case "file";
								switch($this->_columns[$key]["specific_type_extended"])
								{
									case "all":
										if (!empty($value) && file_exists($this->_generic->getPathConfig("files").$value))
											$value = "<a href='".SLS_String::getUrlFile($value)."' target='_blank' class='sls-bo-color-text'>".SLS_String::substrAfterLastDelimiter($value,"/")."</a>";
										break;
									case "img":
										if (!empty($value) && file_exists($this->_generic->getPathConfig("files").$value))
											$value = "<a href='".SLS_String::getUrlFile($value)."' target='_blank'><img class='sls-image' sls-image-src='".((!empty($this->_columns[$key]["image_thumb"])) ? SLS_String::getUrlFileImg($value,$this->_columns[$key]["image_thumb"]) : SLS_String::getUrlFile($value))."' alt='".SLS_String::substrAfterLastDelimiter($value,"/")."' title='".SLS_String::substrAfterLastDelimiter($value,"/")."' /></a>";
										break;
								}
								break;
							case "color":
								$rgb = SLS_String::hex2RGB($value);
								$value = "<div class='sls-bo-box-color' style='color:".((((0.213 * $rgb["red"]) + (0.715 * $rgb["green"]) + (0.072 * $rgb["blue"])) < 0.5) ? "#FFF" : "#000").";background-color:#".$value."'>#".$value."</div>";
								break;
						}
					}
					if ($this->_columns[$key]["html_type"] == "input_textarea")
						$value = "<p>".SLS_String::trimStringToLength(strip_tags($value),150)."</p>";
					if (!empty($hashExists))
						$value = "********";
						
					$xml->addFullTag($key,$value,true);
				}
			}			
			if (!empty($fkRecursiveExists))
			{
				$this->_gap++;
				$xml = $this->getFkChildrens($xml,$fkRecursiveExists,$recordsets[$i]->{$this->_object->getPrimaryKey()});
				$this->_gap--;
			}
			$xml->endTag("entity");
		}
		$xml->endTag("entities");
		
		return $xml;
	}
Example #13
0
	public function getXML()
	{
		# Objects
		$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->_table = $this->_object->getTable();
		$this->_langsValues = array();
		if ($this->_object->isMultilanguage())
		{
			$this->_object->setModelLanguage($this->_lang->getLang());
			foreach($this->_langs as $lang)
				$this->_langsValues[$lang] = array();
		}
		else
			$this->_langsValues[$this->_defaultLang] = array();
		$this->_boPath = "//sls_configs/entry[@type='table' and @name='".strtolower($className)."']";
		$boExists = $this->_xmlBo->getTag($this->_boPath);
		if (empty($boExists))		
			$this->_boPath = "//sls_configs/entry/entry[@type='table' and @name='".strtolower($className)."']";
		$this->_db->changeDb($this->_db_alias);
		$redirects = array("list","add","edit");
		# /Objects
		
		# Model comment
		$this->_tableComment = $this->_object->getTableComment($this->_table,$this->_db_alias);		
		if (SLS_String::startsWith($this->_tableComment,"sls:lang:"))
		{
			$key = strtoupper(SLS_String::substrAfterFirstDelimiter($this->_tableComment,"sls:lang:"));
			$this->_tableComment = (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$key])) ? (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$key]) ? $this->_table : $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$key]) : $GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$key];
		}
		if (empty($this->_tableComment))
			$this->_tableComment = $this->_table;
		# /Model comment
		
		# Params
		$this->_object_id = $this->_http->getParam("id");
		# /Params
		
		# Columns definitions
		$this->_columns = array();
		$this->_bearers = array();
		$this->_children = array();

		// Model exists ?
		if ($this->_object->getModel($this->_object_id) === false)
			$this->_generic->forward($this->_boController,"List".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table));
		
		// Columns
		$this->_columns = $this->getTableColumns($this->_db_alias,$this->_table,$this->_boPath,"",true);
		// Existing model
		$modelDatas = $this->_object->searchModels($this->_table,array(),array(0=>array("column"=>$this->_object->getPrimaryKey(),"value"=>$this->_object_id,"mode"=>"equal")),array(),array($this->_object->getPrimaryKey()=>"ASC"));
		for($i=0 ; $i<$count=count($modelDatas) ; $i++)
		{
			$lang = ($this->_object->isMultilanguage()) ? $modelDatas[$i]->pk_lang : $this->_defaultLang;
								
			foreach($modelDatas[$i] as $modelKey => $modelValue)
			{
				// If pk_lang
				if (in_array($modelKey,array("pk_lang")))
					continue;
											
				// Files
				if (!empty($modelValue) && $this->_columns[$modelKey]["html_type"] == 'input_file')
					$modelValue = SLS_String::getUrlFile($modelValue);
				
				// MySQL Type Set
				if (!empty($modelValue) && $this->_columns[$modelKey]["html_type"] == 'input_checkbox')
					$modelValue = explode(",",$modelValue);
					
				// Fk
				if (!empty($modelValue) && $this->_columns[$modelKey]["html_type"] == 'input_ac')
				{
					$fkAlias = ucfirst(strtolower(SLS_String::substrBeforeFirstDelimiter($this->_columns[$modelKey]["ac_fk"],"_")));
					$fkModel = SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($this->_columns[$modelKey]["ac_fk"],"_"));
					$fkClass = $fkAlias."_".$fkModel;
					$this->_generic->useModel($fkModel,$fkAlias,"user");
					$fkObject = new $fkClass();
					
					if ($fkObject->getModel($modelValue) == true)
					{
						$replacements = $fkObject->getParams();
						$fkLabel = $this->_columns[$modelKey]["ac_pattern"];
						foreach($replacements as $keyFk => $valueFk)
							$fkLabel = str_replace($keyFk, $valueFk, $fkLabel);
						
						$this->_columns[$modelKey]["values"][$lang][] = array("label" => $fkLabel, "value" => $modelValue);
					}
					else
						$this->_columns[$modelKey]["values"][$lang][] = "";
				}
				else
				{
					if (!empty($modelValue) && $this->_columns[$modelKey]["html_type"] == 'input_checkbox')
						$this->_columns[$modelKey]["values"][$lang] = $modelValue;
					else
					{
						if ($this->_columns[$modelKey]["html_type"] == 'input_password')
							$this->_columns[$modelKey]["values"][$lang][] = "";
						else
							$this->_columns[$modelKey]["values"][$lang][] = $modelValue;
					}
				}
			}
		}
		
		// Bearers
		$bearers = $this->_xmlBearer->getTagsAttributes("//sls_configs/entry[@table1='".$className."']",array("tableBearer","table2"));
		if (!empty($bearers))
		{
			for($i=0 ; $i<$count=count($bearers) ; $i++)
			{
				$bearerDb = ucfirst(SLS_String::substrBeforeFirstDelimiter($bearers[$i]["attributes"][0]["value"],"_"));
				$bearerTable = SLS_String::substrAfterFirstDelimiter($bearers[$i]["attributes"][0]["value"],"_");
				$bearerClass = $bearers[$i]["attributes"][0]["value"];
				$bearerTargetDb = ucfirst(SLS_String::substrBeforeFirstDelimiter($bearers[$i]["attributes"][1]["value"],"_"));
				$bearerTargetUse = SLS_String::substrAfterFirstDelimiter($bearers[$i]["attributes"][1]["value"],"_");
				$bearerTargetClass = $bearers[$i]["attributes"][1]["value"];
				$this->_generic->useModel($bearerTable,$bearerDb,"user");
				$this->_generic->useModel($bearerTargetUse,$bearerTargetDb,"user");
				$bearerObject = new $bearerClass();
				$bearerTargetObject = new $bearerTargetClass();
				$bearerTargetPk = $bearerTargetObject->getPrimaryKey();
				$resultFk = array_shift($this->_xmlFk->getTagsAttribute("//sls_configs/entry[@tableFk='".strtolower($bearerClass)."' and @columnFk='".$bearerTargetObject->getPrimaryKey()."' and @tablePk = '".strtolower($bearerTargetDb)."_".$bearerTargetUse."']","labelPk"));
				$labelFk = (empty($resultFk)) ? $bearerTargetObject->getPrimaryKey() : $resultFk["attribute"];
				$labelFkReal = $labelFk;
				$str = $labelFk;
				$values = array();
				$masks = array();
				foreach($bearerTargetObject->getParams() as $key => $value)		
					array_push($masks,$key);				
				foreach($bearerTargetObject->getParams() as $key => $value)					
					if (SLS_String::contains($labelFk,$key))
						$labelFk = str_replace($key,$bearerTargetObject->getColumnComment($key),$labelFk);
				
				$this->_bearers[$bearerObject->getTable()] = array("table" 						=> $bearerObject->getTable(),
																   "name" 						=> $bearerTargetPk,
																   "label" 						=> $bearerObject->getTableComment($bearerObject->getTable(),$bearerDb),
																   "multilanguage" 				=> "false",
																   "native_type" 				=> "int",
																   "html_type" 					=> "input_ac",
																   "specific_type" 				=> "",
																   "specific_type_extended" 	=> "",
																   "file_uid"					=> uniqid(),
																   "image_ratio" 				=> "*",
																   "image_min_width" 			=> "*",
																   "image_min_height" 			=> "*",
																   "html" 						=> "false",
																   "choices" 					=> array(),
																   "values" 					=> array(),
																   "errors"						=> array(),
																   "required" 					=> "false",
																   "unique" 					=> "false",				
																   "default" 					=> "",
																   "ac_db" 						=> strtolower($bearerDb),
																   "ac_entity" 					=> strtolower($bearerTable),
																   "ac_fk"						=> $bearerTargetClass,
																   "ac_column" 					=> $bearerTargetPk,
																   "ac_label" 					=> $labelFk,
																   "ac_pattern" 				=> $labelFkReal,
																   "ac_multiple" 				=> "true",
																   "min_length" 				=> "",
																   "max_length" 				=> "",
																   "filters" 					=> "");
				
				// Existing bearers
				$columnFkSource = $this->_xmlFk->getTag("//sls_configs/entry[@tableFk='".strtolower($bearerClass)."' and @tablePk = '".$this->_db_alias."_".SLS_String::tableToClass($this->_table)."']/@columnFk");
				$columnFkTarget = $this->_xmlFk->getTag("//sls_configs/entry[@tableFk='".strtolower($bearerClass)."' and @tablePk = '".$this->_db_alias."_".SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($bearerTargetClass,"_"))."']/@columnFk");
				$clause = array(0=>array("column"=>$bearerObject->getTable().".".$columnFkSource,"value"=>$this->_object_id,"mode"=>"equal"));
				if ($bearerTargetObject->isMultilanguage())
					$clause[] = array("column"=>$bearerTargetObject->getTable().".pk_lang","value" => $this->_defaultLang,"mode"=>"equal");
				$bearerRecordsets = $bearerObject->searchModels($bearerObject->getTable(),array(0=>array("table"=>$bearerTargetObject->getTable(),"column"=>$columnFkTarget,"mode"=>"inner")),$clause,array(),array($bearerObject->getPrimaryKey()=>"ASC"));
				for($j=0 ; $j<$countJ=count($bearerRecordsets) ; $j++)
				{
					$bearerLabel = $labelFkReal;
					foreach($bearerRecordsets[$j] as $keyBearer => $valueBearer)
						$bearerLabel = str_replace($keyBearer, $valueBearer, $bearerLabel);
					
					$this->_bearers[$bearerObject->getTable()]["values"][] = array("label" => $bearerLabel, "value" => $bearerRecordsets[$j]->{$bearerTargetObject->getPrimaryKey()});
				}
			}
		}
		
		// Children
		$children = $this->_xmlBo->getTagsAttributes($this->_boPath."/children/child",array("table","column"));
		for($i=0 ; $i<$count=count($children) ; $i++)
		{
			$childTable = SLS_String::substrAfterFirstDelimiter($children[$i]["attributes"][0]["value"],"_");
			$childDb = ucfirst(strtolower(SLS_String::substrBeforeFirstDelimiter($children[$i]["attributes"][0]["value"],"_")));
			if ($this->_db->tableExists($childTable))
			{
				$this->_generic->useModel(SLS_String::tableToClass($childTable),$childDb,"user");
				$childClassName = $childDb."_".SLS_String::tableToClass($childTable);
				$childObject = new $childClassName();
				$childPath = "//sls_configs/entry[@type='table' and @name='".strtolower($childClassName)."']";
				$childExists = $this->_xmlBo->getTag($childPath);
				if (empty($childExists))		
					$childPath = "//sls_configs/entry/entry[@type='table' and @name='".strtolower($childClassName)."']";
				
				$childComment = $this->_object->getTableComment($childTable,$this->_db_alias);		
				if (SLS_String::startsWith($childComment,"sls:lang:"))
				{
					$key = strtoupper(SLS_String::substrAfterFirstDelimiter($childComment,"sls:lang:"));
					$childComment = (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$key])) ? (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$key]) ? $childTable : $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$key]) : $GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$key];
				}
				if (empty($childComment))
					$childComment = $childTable;
				$this->_children[$childTable] = array("model" 	=> array("db" 				=> strtolower($childDb),
																		 "table" 			=> $childTable,
																		 "label" 			=> $childComment,
																		 "nbChildren" 		=> 0,
																		 "multilanguage" 	=> ($childObject->isMultilanguage()) ? "true" : "false",
																		 "pk" 				=> $childObject->getPrimaryKey()),
													  "urls"	=> array("list" 		=> array("url" => ($this->_generic->getActionId($this->_boController,"List".ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable)) != null) 		? $this->_generic->getFullPath($this->_boController,"List".ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable),array(),true) 			: "", "authorized" => (SLS_BoRights::isAuthorized("read",ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable))) ? "true" : "false"),
													  					 "add" 			=> array("url" => ($this->_generic->getActionId($this->_boController,"Add".ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable)) != null) 		? $this->_generic->getFullPath($this->_boController,"Add".ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable),array(),true) 			: "", "authorized" => (SLS_BoRights::isAuthorized("add",ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable))) ? "true" : "false"),
																		 "populate"		=> array("url" => ($this->_generic->getActionId($this->_boController,"BoPopulate".ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable)) != null) 	? $this->_generic->getFullPath($this->_boController,"Populate".ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable),array(),true) 		: "", "authorized" => (SLS_BoRights::getAdminType() == "developer") ? "true" : "false"),
																		 "edit" 		=> array("url" => ($this->_generic->getActionId($this->_boController,"Modify".ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable)) != null) 	? $this->_generic->getFullPath($this->_boController,"Modify".ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable),array("id"=>""),false) : "", "authorized" => (SLS_BoRights::isAuthorized("edit",ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable))) ? "true" : "false"),
																		 "clone" 		=> array("url" => ($this->_generic->getActionId($this->_boController,"Clone".ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable)) != null) 	? $this->_generic->getFullPath($this->_boController,"Clone".ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable),array("id"=>""),false) 		: "", "authorized" => (SLS_BoRights::isAuthorized("clone",ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable))) ? "true" : "false"),
																		 "delete" 		=> array("url" => ($this->_generic->getActionId($this->_boController,"Delete".ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable)) != null) 	? $this->_generic->getFullPath($this->_boController,"Delete".ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable),array("id"=>""),false) : "", "authorized" => (SLS_BoRights::isAuthorized("delete",ucfirst(strtolower($childDb))."_".SLS_String::tableToClass($childTable))) ? "true" : "false")),
													  "columns" => $this->getTableColumns($this->_db_alias,$childTable,$childPath,$className,true),
													  "bearers" => array());
				
				// Existing children
				$columnFk = $this->_xmlFk->getTag("//sls_configs/entry[@tableFk='".strtolower($childClassName)."' and @tablePk = '".$this->_db_alias."_".SLS_String::tableToClass($this->_table)."']/@columnFk");
				$childrenRecordsets = $childObject->searchModels($childObject->getTable(),array(),array(0=>array("column"=>$columnFk,"value"=>$this->_object_id,"mode"=>"equal")),array(),array($childObject->getPrimaryKey()=>"ASC"));
				$this->_children[$childTable]["model"]["nbChildren"] = ($childObject->isMultilanguage()) ? count($childrenRecordsets) / count($this->_langs) : count($childrenRecordsets);
				$childrenIds = array();
				for($j=0 ; $j<$countJ=count($childrenRecordsets) ; $j++)
				{
					$lang = ($childObject->isMultilanguage()) ? $childrenRecordsets[$j]->pk_lang : $this->_defaultLang;
					if (!in_array($childrenRecordsets[$j]->{$childObject->getPrimaryKey()},$childrenIds))
						$childrenIds[] = $childrenRecordsets[$j]->{$childObject->getPrimaryKey()};
					
					$childrenItem = array_shift(array_keys($childrenIds,$childrenRecordsets[$j]->{$childObject->getPrimaryKey()}));
						
					foreach($childrenRecordsets[$j] as $childRecordKey => $childRecordValue)
					{
						// If pk_lang or current father fk, skip
						if (in_array($childRecordKey,array("pk_lang",$columnFk)))
							continue;
													
						// Files
						if (!empty($childRecordValue) && $this->_children[$childTable]["columns"][$childRecordKey]["html_type"] == 'input_file')
							$childRecordValue = SLS_String::getUrlFile($childRecordValue);
						
						// MySQL Type Set
						if (!empty($childRecordValue) && $this->_children[$childTable]["columns"][$childRecordKey]["html_type"] == 'input_checkbox')
							$childRecordValue = explode(",",$childRecordValue);
							
						// Fk
						if (!empty($childRecordValue) && $this->_children[$childTable]["columns"][$childRecordKey]["html_type"] == 'input_ac')
						{
							$fkAlias = ucfirst(strtolower(SLS_String::substrBeforeFirstDelimiter($this->_children[$childTable]["columns"][$childRecordKey]["ac_fk"],"_")));
							$fkModel = SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($this->_children[$childTable]["columns"][$childRecordKey]["ac_fk"],"_"));
							$fkClass = $fkAlias."_".$fkModel;
							$this->_generic->useModel($fkModel,$fkAlias,"user");
							$fkObject = new $fkClass();
							
							if ($fkObject->getModel($childRecordValue) == true)
							{
								$replacements = $fkObject->getParams();
								$fkLabel = $this->_children[$childTable]["columns"][$childRecordKey]["ac_pattern"];
								foreach($replacements as $keyFk => $valueFk)
									$fkLabel = str_replace($keyFk, $valueFk, $fkLabel);
									
								$this->_children[$childTable]["columns"][$childRecordKey]["values"][$childrenItem][$lang][] = array("label" => $fkLabel, "value" => $childRecordValue);
							}
							else
								$this->_children[$childTable]["columns"][$childRecordKey]["values"][$childrenItem][$lang][] = "";
						}
						else
						{
							if (!empty($childRecordValue) && $this->_children[$childTable]["columns"][$childRecordKey]["html_type"] == 'input_checkbox')
								$this->_children[$childTable]["columns"][$childRecordKey]["values"][$childrenItem][$lang] = $childRecordValue;
							else
								$this->_children[$childTable]["columns"][$childRecordKey]["values"][$childrenItem][$lang][] = $childRecordValue;
						}
					}
				}

				// Bearers
				$bearers = $this->_xmlBearer->getTagsAttributes("//sls_configs/entry[@table1='".$childClassName."']",array("tableBearer","table2"));
				if (!empty($bearers))
				{
					for($i=0 ; $i<$count=count($bearers) ; $i++)
					{
						$bearerDb = ucfirst(SLS_String::substrBeforeFirstDelimiter($bearers[$i]["attributes"][0]["value"],"_"));
						$bearerTable = SLS_String::substrAfterFirstDelimiter($bearers[$i]["attributes"][0]["value"],"_");
						$bearerClass = $bearers[$i]["attributes"][0]["value"];
						$bearerTargetDb = ucfirst(SLS_String::substrBeforeFirstDelimiter($bearers[$i]["attributes"][1]["value"],"_"));
						$bearerTargetUse = SLS_String::substrAfterFirstDelimiter($bearers[$i]["attributes"][1]["value"],"_");
						$bearerTargetClass = $bearers[$i]["attributes"][1]["value"];
						$this->_generic->useModel($bearerTable,$bearerDb,"user");
						$this->_generic->useModel($bearerTargetUse,$bearerTargetDb,"user");
						$bearerObject = new $bearerClass();
						$bearerTargetObject = new $bearerTargetClass();
						$bearerTargetPk = $bearerTargetObject->getPrimaryKey();
						$resultFk = array_shift($this->_xmlFk->getTagsAttribute("//sls_configs/entry[@tableFk='".strtolower($bearerClass)."' and @columnFk='".$bearerTargetObject->getPrimaryKey()."' and @tablePk = '".strtolower($bearerTargetDb)."_".$bearerTargetUse."']","labelPk"));
						$labelFk = (empty($resultFk)) ? $bearerTargetObject->getPrimaryKey() : $resultFk["attribute"];
						$labelFkReal = $labelFk;
						$str = $labelFk;
						$values = array();
						$masks = array();
						foreach($bearerTargetObject->getParams() as $key => $value)		
							array_push($masks,$key);				
						foreach($bearerTargetObject->getParams() as $key => $value)					
							if (SLS_String::contains($labelFk,$key))
								$labelFk = str_replace($key,$bearerTargetObject->getColumnComment($key),$labelFk);
						
						$this->_children[$childTable]["bearers"][$bearerObject->getTable()] = array("table" 					=> $bearerObject->getTable(),
																					 				"name" 						=> $bearerTargetPk,
																					 				"label" 					=> $bearerObject->getTableComment($bearerObject->getTable(),$bearerDb),
																					 				"multilanguage" 			=> "false",
																					 				"native_type" 				=> "int",
																					 				"html_type" 				=> "input_ac",
																					 				"specific_type" 			=> "",
																					 				"specific_type_extended" 	=> "",
																					 				"file_uid"					=> uniqid(),
																					 				"image_ratio" 				=> "*",
																					 				"image_min_width" 			=> "*",
																					 				"image_min_height" 			=> "*",
																					 				"html" 						=> "false",
																					 				"choices" 					=> array(),
																					 				"values" 					=> array(),
																					 				"errors"					=> array(),
																					 				"required" 					=> "false",
																					 				"unique" 					=> "false",				
																					 				"default" 					=> "",
																					 				"ac_db" 					=> strtolower($bearerDb),
																					 				"ac_entity" 				=> strtolower($bearerTable),
																					 				"ac_fk"						=> $bearerTargetClass,
																					 				"ac_column" 				=> $bearerTargetPk,
																					 				"ac_label" 					=> $labelFk,
																					 				"ac_pattern" 				=> $labelFkReal,
																					 				"ac_multiple" 				=> "true",
																					 				"min_length" 				=> "",
																					 				"max_length" 				=> "",
																					 				"filters" 					=> "");
						$columnFkSource = $this->_xmlFk->getTag("//sls_configs/entry[@tableFk='".strtolower($bearerClass)."' and @tablePk = '".$this->_db_alias."_".SLS_String::tableToClass($childObject->getTable())."']/@columnFk");
						$columnFkTarget = $this->_xmlFk->getTag("//sls_configs/entry[@tableFk='".strtolower($bearerClass)."' and @tablePk = '".$this->_db_alias."_".SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($bearerTargetClass,"_"))."']/@columnFk");
						$clause = (!empty($childrenIds)) ? array(0=>array("column"=>$bearerObject->getTable().".".$columnFkSource,"value"=>$childrenIds,"mode"=>"in")) : array();
						if ($bearerTargetObject->isMultilanguage())
							$clause[] = array("column"=>$bearerTargetObject->getTable().".pk_lang","value" => $this->_defaultLang,"mode"=>"equal");
						$bearerRecordsets = $bearerObject->searchModels($bearerObject->getTable(),array(0=>array("table"=>$bearerTargetObject->getTable(),"column"=>$columnFkTarget,"mode"=>"inner")),$clause,array(),array($bearerObject->getPrimaryKey()=>"ASC"));
						for($j=0 ; $j<$countJ=count($bearerRecordsets) ; $j++)
						{
							$bearerLabel = $labelFkReal;
							foreach($bearerRecordsets[$j] as $keyBearer => $valueBearer)
								$bearerLabel = str_replace($keyBearer, $valueBearer, $bearerLabel);
							
							$this->_children[$childTable]["bearers"][$bearerObject->getTable()]["values"][array_shift(array_keys($childrenIds,$bearerRecordsets[$j]->{$columnFkSource}))][] = array("label" => $bearerLabel, "value" => $bearerRecordsets[$j]->{$bearerTargetObject->getPrimaryKey()});
						}
					}
				}
			}
		}
		# /Columns definitions

		# Reload
		$this->_error = false;
		$this->_recordsets = array();
		if ($this->_http->getParam("reload-edit") == "true")
		{	
			$modelParams 		= (is_array($this->_http->getParam($this->_table))) ? $this->_http->getParam($this->_table) : array();
			$properties 		= (is_array($modelParams["properties"])) ? $modelParams["properties"] : array();
			$bearers 			= (is_array($modelParams["bearers"])) ? $modelParams["bearers"] : array();
			$children 			= (is_array($modelParams["children"])) ? $modelParams["children"] : array();
			$childrenToDelete	= (is_array($modelParams["children-to-delete"])) ? $modelParams["children-to-delete"] : array();
			$redirect 			= (in_array(strtolower($this->_http->getParam("redirect")),$redirects)) ? strtolower($this->_http->getParam("redirect")) : array_shift($redirects);
			
			# MAIN MODEL
			uksort($properties,array($this, 'unshiftDefaultLang'));
			foreach($properties as $lang => $columns)
			{
				$this->_object->setModelLanguage($lang);
				
				if (!empty($columns))
				{
					foreach(((is_array($columns)) ? $columns : array($columns)) as $column => $value)
					{
						// Reset old value
						$this->_columns[$column]["values"][$lang] = array();
						
						$functionName = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$column)," ",false)),"");
						
						// Remember values
						if (is_array($value) && array_key_exists("file",$value))
						{
							$value = $value["file"];
							
							if (!is_array($value))
								$value = SLS_String::substrAfterFirstDelimiter($value,$this->_generic->getPathConfig("files"));
						}
						else if (is_array($value))
						{
							$this->_columns[$column]["values"][$lang] = $value;
							
							// MySQL Type Set
							if ($this->_columns[$column]["specific_type"] != 'file')
								$value = implode(",",$value);
						}
						else
						{	
							// Check FK
							if (!empty($value) && $this->_columns[$column]["html_type"] == 'input_ac')
							{
								$fkAlias = ucfirst(strtolower(SLS_String::substrBeforeFirstDelimiter($this->_columns[$column]["ac_fk"],"_")));
								$fkModel = SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($this->_columns[$column]["ac_fk"],"_"));
								$fkClass = $fkAlias."_".$fkModel;
								$this->_generic->useModel($fkModel,$fkAlias,"user");
								$fkObject = new $fkClass();
								
								if ($fkObject->getModel($value) == true)
								{
									$replacements = $fkObject->getParams();
									$fkLabel = $this->_columns[$column]["ac_pattern"];
									foreach($replacements as $keyFk => $valueFk)
										$fkLabel = str_replace($keyFk, $valueFk, $fkLabel);
										
									$this->_columns[$column]["values"][$lang][] = array("label" => $fkLabel, "value" => $value);
								}
								else
									$this->_columns[$column]["values"][$lang][] = "";
							}
							else
								$this->_columns[$column]["values"][$lang][] = $value;
						}
						
						// Setter
						if (!$this->_object->$functionName($value))
						{
							$this->_error = true;
							$this->_columns[$column]["errors"][$lang] = $this->_object->getError($column);
							if ($this->_async)
								$this->_render["errors"][$column] = $this->_columns[$column]["label"]." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_'.strtoupper($this->_columns[$column]["errors"][$lang])];
						}
						
						// Remember value type file
						if ($this->_columns[$column]["html_type"] == 'input_file')
						{
							// No error, take model value
							if (empty($this->_columns[$column]["errors"][$lang]))
							{
								$fileValue = $this->_object->__get($column);
								$this->_columns[$column]["values"][$lang][] = (!empty($fileValue)) ? SLS_String::getUrlFile($fileValue) : "";
							}
							// Else, take uploaded file
							else
							{
								// Modern browsers
								if (array_key_exists("data",$value))
									$value = $value["data"];
								
								if (is_array($value) && array_key_exists("tmp_name",$value))
									$this->_columns[$column]["values"][$lang][] = $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$value["tmp_name"];
							}
						}
					}
				}
				
				$this->_object->save();
			}
			# /MAIN MODEL
			
			# CHILDREN
			foreach($children as $childTable => $childValues)
			{
				$this->_generic->useModel(SLS_String::tableToClass($childTable),$this->_db_alias,"user");
				$childClassName = $this->_db_alias."_".SLS_String::tableToClass($childTable);
				$childObject = new $childClassName();
				$this->_recordsets[$childTable]["pk"] = $childObject->getPrimaryKey();
				$this->_children[$childTable]["model"]["nbChildren"] = (is_array($childValues)) ? count($childValues) : 1;
				
				foreach(((is_array($childValues)) ? $childValues : array($childValues)) as $childItem => $infos)
				{	
					// Child
					$properties = (is_array($infos["properties"])) ? $infos["properties"] : array($infos["properties"]);
					uksort($properties,array($this, 'unshiftDefaultLang'));
					
					$childId = $properties[$this->_defaultLang][$childObject->getPrimaryKey()];
					$needToCreate = (empty($childId)) ? true : false;
					if ($needToCreate)
						$this->_recordsets[$childTable]["ids"][] = $childId = $childObject->giveNextId();
					
					foreach($properties as $lang => $columns)
					{		
						$childObject->setModelLanguage($lang);
						if (!$needToCreate)
							$childObject->getModel($childId);
						
						foreach(((is_array($columns)) ? $columns : array($columns)) as $column => $value)
						{
							// Exclude pk if existed (update)
							if ($column == $this->_recordsets[$childTable]["pk"])
								continue;
							
							$functionName = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$column)," ",false)),"");
							
							// Remember values
							if (is_array($value) && array_key_exists("file",$value))
							{
								$value = $value["file"];
								
								if (!is_array($value))
									$value = SLS_String::substrAfterFirstDelimiter($value,$this->_generic->getPathConfig("files"));
							}
							else if (is_array($value))
							{
								$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang] = $value;
								
								// MySQL Type Set
								if ($this->_children[$childTable]["columns"][$column]["specific_type"] != 'file')
									$value = implode(",",$value);
							}
							else
							{
								// Check FK
								if (!empty($value) && $this->_children[$childTable]["columns"][$column]["html_type"] == 'input_ac')
								{
									$fkAlias = ucfirst(strtolower(SLS_String::substrBeforeFirstDelimiter($this->_children[$childTable]["columns"][$column]["ac_fk"],"_")));
									$fkModel = SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($this->_children[$childTable]["columns"][$column]["ac_fk"],"_"));
									$fkClass = $fkAlias."_".$fkModel;
									$this->_generic->useModel($fkModel,$fkAlias,"user");
									$fkObject = new $fkClass();
									
									if ($fkObject->getModel($value) == true)
									{
										$replacements = $fkObject->getParams();
										$fkLabel = $this->_children[$childTable]["columns"][$column]["ac_pattern"];
										foreach($replacements as $keyFk => $valueFk)
											$fkLabel = str_replace($keyFk, $valueFk, $fkLabel);
											
										$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang][] = array("label" => $fkLabel, "value" => $value);
									}
									else
										$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang][] = "";
								}
								else
									$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang][] = $value;
							}
							
							// Setter
							if (!$childObject->$functionName($value))
							{
								$this->_error = true;
								$this->_children[$childTable]["columns"][$column]["errors"][$childItem][$lang] = $childObject->getError($column);
							}
							else
								$this->_children[$childTable]["columns"][$column]["errors"][$childItem][$lang] = "";
							
							// Remember value type file
							if ($this->_children[$childTable]["columns"][$column]["html_type"] == 'input_file')
							{
								// No error, take model value
								if (empty($this->_children[$childTable]["columns"][$column]["errors"][$childItem][$lang]))
								{
									$fileValue = $childObject->__get($column);
									$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang][] = (!empty($fileValue)) ? SLS_String::getUrlFile($fileValue) : "";
								}
								// Else, take uploaded file
								else
								{
									// Modern browsers
									if (is_array($value) && array_key_exists("data",$value))
										$value = $value["data"];
									
									if (is_array($value) && array_key_exists("tmp_name",$value))
										$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang][] = $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$value["tmp_name"];
									else
										$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang][] = "";
								}
							}
						}
						
						// Force fk setter
						$fkColumn = $this->_xmlFk->getTag("//sls_configs/entry[@tableFk='".strtolower($childClassName)."' and @tablePk='".$this->_db_alias."_".SLS_String::tableToClass($this->_table)."']/@columnFk");
						if (!empty($fkColumn))
						{
							$functionName = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$fkColumn)," ",false)),"");
							$childObject->$functionName($this->_object_id);
						}
						// Create or save
						if ($needToCreate)
							$childObject->create();
						else
							$childObject->save();
					}
					
					$childObject->clear();
					
					// Bearers
					$childBearers = (!empty($infos["bearers"])) ? ((is_array($infos["bearers"])) ? $infos["bearers"] : array($infos["bearers"])) : array();
					foreach($childBearers as $bearerTable => $bearerValues)
					{
						// Bearer object
						$bearerClass = ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($bearerTable);
						$bearerAttributes = array_shift($this->_xmlBearer->getTagsAttributes("//sls_configs/entry[@tableBearer='".$bearerClass."']",array("table1","table2")));
						$this->_generic->useModel(SLS_String::tableToClass($bearerTable),$this->_db_alias,"user");
						$this->_generic->useModel(SLS_String::substrAfterFirstDelimiter($bearerAttributes["attributes"][0]["value"],"_"),SLS_String::substrBeforeFirstDelimiter($bearerAttributes["attributes"][0]["value"],"_"));
						$this->_generic->useModel(SLS_String::substrAfterFirstDelimiter($bearerAttributes["attributes"][1]["value"],"_"),SLS_String::substrBeforeFirstDelimiter($bearerAttributes["attributes"][1]["value"],"_"));
						$bearerObject = new $bearerClass();
						$this->_recordsets[$bearerObject->getTable()]["pk"] = $bearerObject->getPrimaryKey();
						$objectBearerTarget1 = new $bearerAttributes["attributes"][0]["value"]();
						$objectBearerTarget2 = new $bearerAttributes["attributes"][1]["value"]();				
						$setterBearerTarget1 = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$objectBearerTarget1->getPrimaryKey())," ",false)),"");
						$setterBearerTarget2 = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$objectBearerTarget2->getPrimaryKey())," ",false)),"");
						$fkColumn = $this->_xmlFk->getTag("//sls_configs/entry[@tableFk='".strtolower($bearerObject->getDatabase())."_".$bearerObject->getTable()."' and @tablePk='".strtolower($bearerObject->getDatabase())."_".SLS_String::substrAfterFirstDelimiter($bearerAttributes["attributes"][0]["value"],"_")."']/@columnFk");
						
						// Delete old bearers
						$bearerObject->deleteModels($bearerObject->getTable(),array(),array(0=>array("column"=>$fkColumn,"value"=>$childId,"mode"=>"equal")));
						
						// Save new bearers
						foreach($bearerValues as $bearerValue)
						{	
							if ($objectBearerTarget2->getModel($bearerValue) === true)
							{
								$replacements = $objectBearerTarget2->getParams();
								$bearerLabel = $this->_children[$childTable]["bearers"][$bearerObject->getTable()]["ac_pattern"];
								foreach($replacements as $keyBearer => $valueBearer)
									$bearerLabel = str_replace($keyBearer, $valueBearer, $bearerLabel);
								
								$this->_children[$childTable]["bearers"][$bearerObject->getTable()]["values"][$childItem][] = array("label" => $bearerLabel, "value" => $bearerValue);
								
								if (!$this->_error)
								{
									$bearerObject->$setterBearerTarget1($childId);
									$bearerObject->$setterBearerTarget2($bearerValue);
									$bearerObjectId = $bearerObject->create();
									$this->_recordsets[$bearerObject->getTable()]["ids"][] = $bearerObjectId;
									$bearerObject->clear();
								}
							}
						}
					}
				}
			}
			# /CHILDREN
			
			# BEARERS
			foreach($bearers as $bearerTable => $bearerValues)
			{
				// Bearer object
				$bearerClass = ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($bearerTable);
				$bearerAttributes = array_shift($this->_xmlBearer->getTagsAttributes("//sls_configs/entry[@tableBearer='".$bearerClass."']",array("table1","table2")));
				$this->_generic->useModel(SLS_String::tableToClass($bearerTable),$this->_db_alias,"user");
				$this->_generic->useModel(SLS_String::substrAfterFirstDelimiter($bearerAttributes["attributes"][0]["value"],"_"),SLS_String::substrBeforeFirstDelimiter($bearerAttributes["attributes"][0]["value"],"_"));
				$this->_generic->useModel(SLS_String::substrAfterFirstDelimiter($bearerAttributes["attributes"][1]["value"],"_"),SLS_String::substrBeforeFirstDelimiter($bearerAttributes["attributes"][1]["value"],"_"));
				$bearerObject = new $bearerClass();
				$this->_recordsets[$bearerObject->getTable()]["pk"] = $bearerObject->getPrimaryKey();
				$objectBearerTarget1 = new $bearerAttributes["attributes"][0]["value"]();
				$objectBearerTarget2 = new $bearerAttributes["attributes"][1]["value"]();				
				$setterBearerTarget1 = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$objectBearerTarget1->getPrimaryKey())," ",false)),"");
				$setterBearerTarget2 = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$objectBearerTarget2->getPrimaryKey())," ",false)),"");
				$fkColumn = $this->_xmlFk->getTag("//sls_configs/entry[@tableFk='".strtolower($bearerObject->getDatabase())."_".$bearerObject->getTable()."' and @tablePk='".strtolower($bearerObject->getDatabase())."_".SLS_String::substrAfterFirstDelimiter($bearerAttributes["attributes"][0]["value"],"_")."']/@columnFk");
				
				// Delete old bearers
				$bearerObject->deleteModels($bearerObject->getTable(),array(),array(0=>array("column"=>$fkColumn,"value"=>$this->_object_id,"mode"=>"equal")));
				
				// Save new bearers
				foreach($bearerValues as $bearerValue)
				{	
					if ($objectBearerTarget2->getModel($bearerValue) === true)
					{
						$replacements = $objectBearerTarget2->getParams();
						$bearerLabel = $this->_bearers[$bearerObject->getTable()]["ac_pattern"];
						foreach($replacements as $keyBearer => $valueBearer)
							$bearerLabel = str_replace($keyBearer, $valueBearer, $bearerLabel);
						
						$this->_bearers[$bearerObject->getTable()]["values"][] = array("label" => $bearerLabel, "value" => $bearerValue);
						
						if (!$this->_error)
						{
							$bearerObject->$setterBearerTarget1($this->_object_id);
							$bearerObject->$setterBearerTarget2($bearerValue);
							$bearerObjectId = $bearerObject->create();
							$this->_recordsets[$bearerObject->getTable()]["ids"][] = $bearerObjectId;
							$bearerObject->clear();
						}
					}
				}
			}
			# /BEARERS
			
			# CHILDREN-TO-DELETE
			foreach($childrenToDelete as $childTable => $childValues)
			{
				$this->_generic->useModel(SLS_String::tableToClass($childTable),$this->_db_alias,"user");
				$childClassName = $this->_db_alias."_".SLS_String::tableToClass($childTable);
				$childObject = new $childClassName();
				
				foreach(((is_array($childValues)) ? $childValues : array($childValues)) as $childToDelete)
				{
					if ($childObject->getModel($childToDelete) === true)
						$childObject->delete(true);
				}
			}
			# /CHILDREN-TO-DELETE
			
			# If error, delete model & linked recordsets
			if ($this->_error && $this->_object->getModel($this->_object_id))
			{
				if ($this->_async)
				{
					$this->_render["message"] = sprintf($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_ERROR'],$this->_lang->getLang()); 
					// Render
					echo json_encode($this->_render);
					die();
				}
			}
			# /Errors
			
			# All good dude !
			if (!$this->_error)
			{
				if ($this->_async)
				{
					$this->_render["status"] = "OK";
					$this->_render["message"] = $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_GENERIC_SUBMIT_SUCCESS_EDIT'];
				}
				
				else
				{
					$this->pushNotif("success",$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_GENERIC_SUBMIT_SUCCESS_EDIT']);
					
					if ($this->_forward)
					{
						switch ($redirect)
						{
							case "edit":
								# Remember admin settings
								$nodeExists = $this->_xmlRight->getTag("//sls_configs/entry[@login='******']/@login");
								if (!empty($nodeExists))
								{
									$this->_xmlRight->setTag("//sls_configs/entry[@login='******']/settings/setting[@key='edit_callback']","edit");
									$this->_xmlRight->saveXML($this->_generic->getPathConfig("configSls")."/rights.xml");
									$this->_xmlRight->refresh();
								}
								# /Remember admin settings
								$this->_generic->forward($this->_boController,"Modify".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table),array("id"=>$this->_object_id));
								break;
							case "list":
								# Remember admin settings
								$nodeExists = $this->_xmlRight->getTag("//sls_configs/entry[@login='******']/@login");
								if (!empty($nodeExists))
								{
									$this->_xmlRight->setTag("//sls_configs/entry[@login='******']/settings/setting[@key='edit_callback']","list");
									$this->_xmlRight->saveXML($this->_generic->getPathConfig("configSls")."/rights.xml");
									$this->_xmlRight->refresh();
								}
								# /Remember admin settings
								$rememberList = (is_array($this->_session->getParam("SLS_BO_LIST"))) ? $this->_session->getParam("SLS_BO_LIST") : array();
								if (array_key_exists($this->_db_alias."_".$this->_table,$rememberList) && !empty($rememberList[$this->_db_alias."_".$this->_table]))
									$this->_generic->redirect($rememberList[$this->_db_alias."_".$this->_table]);
								else
									$this->_generic->forward($this->_boController,"List".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table));
								break;
						}
					}
				}
			}
			# /All good dude !
		}
		# /Reload
		
		# Page infos
		$langsError = array();
		$columnValues = array();
		$this->_xml->startTag("page");	
			$this->_xml->startTag("model");
				$this->_xml->addFullTag("db",$this->_db_alias,true);
				$this->_xml->addFullTag("table",$this->_table,true);				
				$this->_xml->addFullTag("label",$this->_tableComment,true);
				$this->_xml->addFullTag("multilanguage",($this->_object->isMultilanguage()) ? "true" : "false",true);
				$this->_xml->addFullTag("pk",$this->_object->getPrimaryKey(),true);
			$this->_xml->endTag("model");
			$this->_xml->startTag("urls");
				$this->_xml->addFullTag("list",($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController,"List".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)))) ? $this->_generic->getFullPath($this->_boController,"List".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)) : "",true,array("authorized" => (SLS_BoRights::isAuthorized("read",ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table))) ? "true" : "false"));
				$this->_xml->addFullTag("add",($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController,"Add".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)))) ? $this->_generic->getFullPath($this->_boController,"Add".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)) : "",true,array("authorized" => (SLS_BoRights::isAuthorized("add",ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table))) ? "true" : "false"));
				$this->_xml->addFullTag("populate",$this->_generic->getFullPath($this->_boController,"BoPopulate",array("Db" => ucfirst(strtolower($this->_db_alias)), "Table" => $this->_table)),true,array("authorized" => (SLS_BoRights::getAdminType() == "developer") ? "true" : "false"));
				$this->_xml->addFullTag("edit",($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController,"Modify".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)))) ? $this->_generic->getFullPath($this->_boController,"Modify".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table),array("id" => ""),false) : "",true,array("authorized" => (SLS_BoRights::isAuthorized("edit",ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table))) ? "true" : "false"));
				$this->_xml->addFullTag("clone",($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController,"Clone".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)))) ? $this->_generic->getFullPath($this->_boController,"Clone".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table),array("id" => ""),false) : "",true,array("authorized" => (SLS_BoRights::isAuthorized("clone",ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table))) ? "true" : "false"));
				$this->_xml->addFullTag("delete",($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController,"Delete".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)))) ? $this->_generic->getFullPath($this->_boController,"Delete".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table),array("id" => ""),false) : "",true,array("authorized" => (SLS_BoRights::isAuthorized("delete",ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table))) ? "true" : "false"));
			$this->_xml->endTag("urls");
			$this->_xml->startTag("columns");
			foreach($this->_columns as $columnName => $infosColumn)
			{
				$this->_xml->startTag("column");
				foreach($infosColumn as $key => $value)
				{
					if (is_array($value) && !in_array($key,array("choices","values","errors")))
						continue;
						
					if ($key == "choices")
					{
						$this->_xml->startTag("choices");
						foreach($value as $currentValue)
							$this->_xml->addFullTag("choice",$currentValue,true);
						$this->_xml->endTag("choices");
					}
					else if ($key == "values")
					{
						$this->_xml->startTag("values");
						foreach($value as $currentLang => $values)
						{	
							if ($this->_async)
							{	
								if (empty($columnValues[$columnName]))
								{
									if ($this->_object->isMultilanguage() && $this->_columns[$columnName]["multilanguage"] == "true" && $currentLang == $this->_lang->getLang())
									{
										$columnValues[$columnName] = ($columnName == "pk_lang") ? $this->_lang->getLang() : $values;
									}
									else if ($currentLang == $this->_defaultLang)
									{
										$columnValues[$columnName] = ($columnName == "pk_lang") ? $this->_lang->getLang() : $values;
									}
								}
							}
								
							foreach($values as $currentValue)
							{
								if (is_array($currentValue))
									$this->_xml->addFullTag("value",$currentValue["value"],true,array("lang"=>$currentLang,"label"=>$currentValue["label"]));
								else
								{
									if ($this->_columns[$columnName]["specific_type"] == 'file' && $this->_columns[$columnName]["specific_type_extended"] == 'all')
									{
										$img = "false";
										if (file_exists($this->_generic->getPathConfig("coreImg")."BO-2014/Mime-Types/".strtolower(str_replace("/","-",SLS_String::getExtensionMimeType(SLS_String::substrAfterLastDelimiter($currentValue,"."))).".png")))
										{
											$mime = $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$this->_generic->getPathConfig("coreImg")."BO-2014/Mime-Types/".strtolower(str_replace("/","-",SLS_String::getExtensionMimeType(SLS_String::substrAfterLastDelimiter($currentValue,"."))).".png");
											if (SLS_String::startsWith(SLS_String::getExtensionMimeType(SLS_String::substrAfterLastDelimiter($currentValue,".")),"image/"))
												$img = "true";
										}
										else
											$mime = $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$this->_generic->getPathConfig("coreImg")."BO-2014/Mime-Types/application-octet-stream.png";
										$this->_xml->addFullTag("value",$currentValue,true,array("lang"=>$currentLang,"img"=>$img,"mime"=>$mime));
									}
									else if ($this->_columns[$columnName]["specific_type"] == 'file' && $this->_columns[$columnName]["specific_type_extended"] == 'img')
									{
										$image = $currentValue;
										if (SLS_String::contains($image,$this->_generic->getSiteConfig("domainName")."/"))
											$image = SLS_String::substrAfterFirstDelimiter($image,$this->_generic->getSiteConfig("domainName")."/");
										$this->_xml->addFullTag("value",$currentValue,true,array("lang"=>$currentLang,"size"=>(file_exists($image)) ? filesize($image) : 0));
									}
									else
										$this->_xml->addFullTag("value",$currentValue,true,array("lang"=>$currentLang));
								}
							}
						}
						$this->_xml->endTag("values");
					}
					else if ($key == "errors")
					{
						$this->_xml->startTag("errors");
						foreach($value as $currentLang => $currentValue)
						{
							$this->_xml->addFullTag("error",$infosColumn["label"]." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_'.strtoupper($currentValue)],true,array("lang"=>$currentLang));
							if (!in_array($currentLang,$langsError))
							{
								$this->pushNotif("error",sprintf($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_ERROR'],$currentLang));
								$langsError[] = $currentLang;
							}
						}
						$this->_xml->endTag("errors");
					}
					else
						$this->_xml->addFullTag($key,$value,true);
				}
				$this->_xml->endTag("column");
			}
			$this->_xml->endTag("columns");
			
			// If quick-edit view
			if ($this->_async)
			{
				// Render
				$this->_render["status"] = "OK";
				$this->_render["result"] = $columnValues;
				echo json_encode($this->_render);
				die();
			}
			
			$this->_xml->startTag("bearers");
			foreach($this->_bearers as $bearerTable => $infosColumn)
			{
				$this->_xml->startTag("column");
				foreach($infosColumn as $key => $value)
				{
					if (is_array($value) && !in_array($key,array("choices","values")))
						continue;
						
					if ($key == "choices")
					{
						$this->_xml->startTag("choices");
						foreach($value as $currentValue)
							$this->_xml->addFullTag("choice",$currentValue,true);
						$this->_xml->endTag("choices");
					}
					else if ($key == "values")
					{
						$this->_xml->startTag("values");
						foreach($value as $currentValue => $currentValues)
							$this->_xml->addFullTag("value",$currentValues["value"],true,array("lang"=>$this->_defaultLang,"label"=>$currentValues["label"]));
						$this->_xml->endTag("values");
					}
					else
						$this->_xml->addFullTag($key,$value,true);
				}
				$this->_xml->endTag("column");
			}
			$this->_xml->endTag("bearers");
			$this->_xml->startTag("children");
			foreach($this->_children as $childTable => $childInfos)
			{
				$this->_xml->startTag("child");
					$this->_xml->startTag("model");
					foreach($childInfos["model"] as $key => $value)
						$this->_xml->addFullTag($key,$value,true);
					$this->_xml->endTag("model");
					$this->_xml->startTag("urls");
					foreach($childInfos["urls"] as $key => $value)
						$this->_xml->addFullTag($key,$value["url"],true,array("authorized" => $value["authorized"]));
					$this->_xml->endTag("urls");
					$this->_xml->startTag("columns");
					foreach($childInfos["columns"] as $columnName => $infosColumn)
					{
						$this->_xml->startTag("column");
						foreach($infosColumn as $key => $value)
						{
							if (is_array($value) && !in_array($key,array("choices","values","errors")))
								continue;
								
							if ($key == "choices")
							{
								$this->_xml->startTag("choices");
								foreach($value as $currentValue)
									$this->_xml->addFullTag("choice",$currentValue,true);
								$this->_xml->endTag("choices");
							}
							else if ($key == "values")
							{
								$this->_xml->startTag("values");
								foreach($value as $offset => $valuesChildren)
								{
									$this->_xml->startTag("record");
									foreach($valuesChildren as $currentLang => $values)
									{
										foreach($values as $currentValue)
										{
											if (is_array($currentValue))
												$this->_xml->addFullTag("value",$currentValue["value"],true,array("lang"=>$currentLang,"label"=>$currentValue["label"]));
											else
											{
												if ($this->_children[$childTable]["columns"][$columnName]["specific_type"] == 'file' && $this->_children[$childTable]["columns"][$columnName]["specific_type_extended"] == 'all')
												{
													$img = "false";
													if (file_exists($this->_generic->getPathConfig("coreImg")."BO-2014/Mime-Types/".strtolower(str_replace("/","-",SLS_String::getExtensionMimeType(SLS_String::substrAfterLastDelimiter($currentValue,"."))).".png")))
													{
														$mime = $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$this->_generic->getPathConfig("coreImg")."BO-2014/Mime-Types/".strtolower(str_replace("/","-",SLS_String::getExtensionMimeType(SLS_String::substrAfterLastDelimiter($currentValue,"."))).".png");
														if (SLS_String::startsWith(SLS_String::getExtensionMimeType(SLS_String::substrAfterLastDelimiter($currentValue,".")),"image/"))
															$img = "true";
													}
													else
														$mime = $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$this->_generic->getPathConfig("coreImg")."BO-2014/Mime-Types/application-octet-stream.png";
													$this->_xml->addFullTag("value",$currentValue,true,array("lang"=>$currentLang,"img"=>$img,"mime"=>$mime));
												}
												else if ($this->_children[$childTable]["columns"][$columnName]["specific_type"] == 'file' && $this->_children[$childTable]["columns"][$columnName]["specific_type_extended"] == 'img')
												{
													$image = $currentValue;
													if (SLS_String::contains($image,$this->_generic->getSiteConfig("domainName")."/"))
														$image = SLS_String::substrAfterFirstDelimiter($image,$this->_generic->getSiteConfig("domainName")."/");
													$this->_xml->addFullTag("value",$currentValue,true,array("lang"=>$currentLang,"size"=>(file_exists($image)) ? filesize($image) : 0));
												}
												else
													$this->_xml->addFullTag("value",$currentValue,true,array("lang"=>$currentLang));
											}
										}
									}
									$this->_xml->endTag("record");
								}
								$this->_xml->endTag("values");
							}
							else if ($key == "errors")
							{
								$this->_xml->startTag("errors");
								foreach($value as $currentLang => $currentValues)
								{
									$this->_xml->startTag("record");
									foreach($currentValues as $currentLang => $currentValue)
									{
										if (!empty($currentValue))
										{
											$this->_xml->addFullTag("error",$infosColumn["label"]." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_'.strtoupper($currentValue)],true,array("lang"=>$currentLang));
											if (!in_array($currentLang,$langsError))
											{
												$this->pushNotif("error",sprintf($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_ERROR'],$currentLang));
												$langsError[] = $currentLang;
											}
										}
										else
											$this->_xml->addFullTag("error","",true,array("lang"=>$currentLang));
									}
									$this->_xml->endTag("record");
								}
								$this->_xml->endTag("errors");
							}
							else
								$this->_xml->addFullTag($key,$value,true);
						}
						$this->_xml->endTag("column");
					}
					$this->_xml->endTag("columns");
					$this->_xml->startTag("bearers");
					foreach($this->_children[$childTable]["bearers"] as $bearerTable => $infosColumn)
					{
						$this->_xml->startTag("column");
						foreach($infosColumn as $key => $value)
						{
							if (is_array($value) && !in_array($key,array("choices","values")))
								continue;
								
							if ($key == "choices")
							{
								$this->_xml->startTag("choices");
								foreach($value as $currentValue)
									$this->_xml->addFullTag("choice",$currentValue,true);
								$this->_xml->endTag("choices");
							}
							else if ($key == "values")
							{
								$this->_xml->startTag("values");
								foreach($value as $childItem => $values)
								{
									$this->_xml->startTag("record");
									foreach($values as $currentValue => $currentValues)
										$this->_xml->addFullTag("value",$currentValues["value"],true,array("lang"=>$this->_defaultLang,"label"=>$currentValues["label"]));
									$this->_xml->endTag("record");
								}
								$this->_xml->endTag("values");
							}
							else
								$this->_xml->addFullTag($key,$value,true);
						}
						$this->_xml->endTag("column");
					}
					$this->_xml->endTag("bearers");
				$this->_xml->endTag("child");
			}
			$this->_xml->endTag("children");
		$this->_xml->endTag("page");
		# /Page infos
		
		return $this->_xml;
	}
	public function action()
	{
		$user 	= $this->hasAuthorative();
		$xml 	= $this->getXML();
		$xml	= $this->makeMenu($xml);		
		
		$plugId = $this->_http->getParam('Plugin');
		$reload = $this->_http->getParam('reload', 'post');
		$controllers = $this->_generic->getTranslatedController('SLS_Bo', 'Plugins');
		
		
		if(SLS_PluginsManager::isExists($plugId) === false)
			$this->redirect($controllers['controller']."/".$controllers['scontroller']);
		
		$plugin = new SLS_PluginsManager($plugId);
		$xmlPlug = $plugin->getXML();
		
		
		if (!$plugin->isCustomizable())
			$this->redirect($controllers['controller']."/".$controllers['scontroller']);
		
		$xml->startTag("plugin_infos");
			$xml->addFullTag('name', $plugin->_name);
			$xml->addFullTag('code', $plugin->_code);
			$xml->addFullTag('id', $plugin->_id);
			$xml->addFullTag('version', $plugin->_version);
		$xml->endTag("plugin_infos");
		
		if ($reload == 'true')
		{
			$errors = array();
			$form_memory = array();
			$form_memory = $this->recoverFormValues("//plugin", $xmlPlug, $form_memory);
			$xml->startTag("memory");
			foreach ($form_memory as $key=>$field)
			{
				$xml->startTag("values");
				$xml->addFullTag("name", $key, true);
				$xml->addFullTag("value", $field['value'], true);
				$xml->endTag("values");
				$xpath = $field['xpath'];
				$index = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($xpath, "["), "]");
				$xpathNoIndex = SLS_String::substrBeforeLastDelimiter($xpath, "[");
				if (SLS_String::endsWith($key, "_alias"))
				{
					if (count($xmlPlug->getTags($xpathNoIndex."[position() != ".$index." and @alias='".$field['value']."']")) != 0)
						$errors[] = array_shift($xmlPlug->getTags($xpath."/@label"))." alias ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_E_UNIQUE'];
					else 
						$xmlPlug->setTagAttributes($xpath, array("alias"=>$field['value']));
				}
				else {
					$is_null = (array_shift($xmlPlug->getTags($xpath."/@null")) == "1") ? true : false;
					switch (array_shift($xmlPlug->getTags($xpath."/@type")))
					{
						case "string" :
							if (!SLS_String::validateString($field['value']) && !$is_null)
								$errors[] = array_shift($xmlPlug->getTags($xpath."/@label"))." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_E_TYPE'];
							else 
								$xmlPlug->setTag($xpath, $field['value']);
							break;
						case "password" :
								if (isset($field['value']))
									$xmlPlug->setTag($xpath, SLS_Security::encrypt($field['value'], $this->_generic->getSiteConfig("privateKey")));
							break;
						case "int" : 
							if (!is_int($field['value']) && !$is_null)
								$errors[] = array_shift($xmlPlug->getTags($xpath."/@label"))." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_E_TYPE'];
							else 
								$xmlPlug->setTag($xpath, $field['value']);
							break;
						case "float" :
							if (!is_float($field['value']) && !$is_null)
								$errors[] = array_shift($xmlPlug->getTags($xpath."/@label"))." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_E_TYPE'];
							else 
								$xmlPlug->setTag($xpath, $field['value']);
							break;
						case "select" : 
							$values = explode("|||", array_shift($xmlPlug->getTags($xpath."/@values")));
							if (!in_array($field['value'], $values))
								$errors[] = array_shift($xmlPlug->getTags($xpath."/@label"))." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_E_CONTENT'];
							else 
								$xmlPlug->setTag($xpath, $field['value']);
							break;
						default:
							break;
					}
				}
				
			}
			$xml->endTag("memory");
			if (!empty($errors))
			{
				$xml->startTag("errors");
					foreach ($errors as $error)
						$xml->addFullTag("error", $error, true);
				$xml->endTag("errors");
			}
			else 
			{
				$xml->addFullTag("success", "ok", true);
				$plugin->saveXML($xmlPlug);
			}
		}
		
		$xml->addFullTag("fields", $plugin->getFields()->getXML('noHeader'), false);	
				
		$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);
		$errors = 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;
		
		$controller = SLS_String::trimSlashesFromString($this->_http->getParam('Controller'));
				
		if (is_file($this->_generic->getPathConfig("staticsControllers").$controller.".controller.php"))
		{
			if ($this->_http->getParam('reload') == 'true')
			{
				$newController = SLS_String::trimSlashesFromString($this->_http->getParam('controllerName'));
				$oldController = SLS_String::trimSlashesFromString($this->_http->getParam('oldName'));
				$cache_visibility = SLS_String::trimSlashesFromString($this->_http->getParam('cache_visibility'));
				$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 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($newController))
					array_push($errors, "You must fill the static controller name");
				if (in_array($cache_visibility,array("public","private")) && (!is_numeric($cache_expiration) || $cache_expiration < 0))
					array_push($errors, "Your expiration cache must be a positive time or 0");
				
				$newController = str_replace(" ", "", ucwords(trim(SLS_String::getAlphaString($newController))));
				
				$statics = $this->_generic->recursiveReadDir($this->_generic->getPathConfig("staticsControllers"), array(), array(0=>"php"));
				foreach ($statics as $static)
				{
					if (SLS_String::substrBeforeLastDelimiter(SLS_String::substrAfterLastDelimiter($static, "/"), ".controller.php") == $newController && SLS_String::substrBeforeLastDelimiter(SLS_String::substrAfterLastDelimiter($static, "/"), ".controller.php") != $oldController)
					{
						array_push($errors, "The name '".$newController."' is already in use for a static controller");
						break;
					}
				}
				
				if (empty($errors))
				{
					if ($newController != $oldController)
					{
						$strController = file_get_contents($this->_generic->getPathConfig("staticsControllers").$oldController.".controller.php");
						$strController = str_replace($oldController."Controller", $newController."Controller", $strController);
						file_put_contents($this->_generic->getPathConfig("staticsControllers").$newController.".controller.php", $strController);					
						unlink($this->_generic->getPathConfig("staticsControllers").$oldController.".controller.php");
					}
					
					// Cache
					if (in_array($cache_visibility,array("public","private")))
					{
						$this->_cache->addObject(strtolower($newController),"statics",$cache_visibility,($cache_responsive=="true") ? "responsive" : "no_responsive",$cache_expiration);
						$this->_cache->saveObject();
					}
					else
					{
						$this->_cache->deleteObject(strtolower($newController),"statics");
						$this->_cache->saveObject();
					}
					
					$this->_generic->forward("SLS_Bo", "Controllers");
				}		
				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);
					$xml->addFullTag("cache_visibility", $cache_visibility,true);
					$xml->addFullTag("cache_expiration", $cache_expiration,true);
					$xml->addFullTag("cache_responsive", $cache_expiration,true);					
				$xml->endTag('form');
			}
			else
			{
				$xml->startTag('form');
					$xml->addFullTag("controllerName", $controller);
					$xml->addFullTag("cache_visibility", $this->_cache->getObject(strtolower($controller),"statics","visibility"),true);
					$xml->addFullTag("cache_expiration", $this->_cache->getObject(strtolower($controller),"statics","expire"),true);
					$xml->addFullTag("cache_responsive", $this->_cache->getObject(strtolower($controller),"components","responsive"),true);
				$xml->endTag('form');
			}
			
			$xml->startTag('controller');
				$xml->addFullTag("name", $controller, true);
			$xml->endTag('controller');
		}
		else 
		{
			$this->_generic->forward('SLS_Bo', 'Controllers');
		}
		
		$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);		
	}
	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();
		$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);
	}
	/**
	 * 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);
	}
	/**
	 * Constructor
	 *
	 * @access public
	 * @since 1.0
	 */
	public function __construct($xml,$db,$table,$forward=true)
	{
		parent::__construct();
		
		$this->_xml = $xml;
		$this->_db_alias = $db;
		$this->_table = $table;
		$this->_forward = $forward;
		
		# Objects
		$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->_table = $this->_object->getTable();
		$this->_clone = new $className();
		$this->_columns = array();
		$this->_filters = array();
		$this->_types = array();
		# /Objects
				
		# Params
		$ids = $this->_http->getParam("id");
		$ids = (SLS_String::contains($ids,"|")) ? explode("|",$ids) : array($ids);
		# /Params
		
		# Types
		$types = $this->_db->showColumns($this->_table);
		for($i=0 ; $i<$count=count($types) ; $i++)
		{
			$nativeType = "text";
			switch($types[$i]->Type)
			{
				case (false !== $typeMatch = $this->containsRecursive($types[$i]->Type,array("int","float","double","decimal","real"))):
					$nativeType = "number";
					break;
				case (false !== $typeMatch = $this->containsRecursive($types[$i]->Type,array("year","datetime","timestamp","time","date"))):
					$nativeType = "date_".$typeMatch;
					break;
			}
			$this->_types[$types[$i]->Field] = $nativeType;
		}
		# /Types
		
		# Blocking specificities
		$specificities = $this->_xmlType->getTagsAttributes("//sls_configs/entry[@table='".$this->_db_alias."_".$this->_table."' and (@type='position' or @type='uniqid' or @type='email')]",array("column","type"));
		for($i=0 ; $i<$count=count($specificities) ; $i++)
		{	
			$column = $specificities[$i]["attributes"][0]["value"];
			$type = $specificities[$i]["attributes"][1]["value"];
			if (!array_key_exists($column,$this->_columns))
				$this->_columns[$column] = $type;
		}
		$filters = $this->_xmlFilter->getTags("//sls_configs/entry[@table='".$this->_db_alias."_".$this->_table."' and @filter='hash']/@column");
		# Blocking specificities
		
		# Perform clone
		if ($this->_object->isMultilanguage())
		{
			$siteLangs = $this->_lang->getSiteLangs();
			unset($siteLangs[array_search($this->_defaultLang,$siteLangs)]);
			array_unshift($siteLangs,$this->_defaultLang);
			$langs = $siteLangs;
		}
		else
			$langs =  array($this->_defaultLang);
		
		// Recordsets to clone
		$nbClone = 0;
		foreach($ids as $id)
		{
			// Next id
			$cloneId = $this->_object->giveNextId();
			
			// Each lang
			foreach($langs as $lang)
			{
				if ($this->_object->isMultilanguage())
					$this->_clone->setModelLanguage($lang);
					
				// Get recordset
				if ($this->_object->getModel($id) === true)
				{
					// Foreach column
					foreach($this->_object->getParams() as $key => $value)
					{
						if ($key == $this->_object->getPrimaryKey() || $key == "pk_lang")
							continue;
						
						// Setter
						$functionName = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$key)," ",false)),"");
						
						// Specific type ?
						if (array_key_exists($key,$this->_columns) && $this->_columns[$key] != "email")
						{
							// Default lang
							if ($lang == $this->_defaultLang && in_array($this->_columns[$key],array("uniqid","position")))
							{
								// Regenerate uniqid
								if ($this->_columns[$key] == "uniqid")
									$value = substr(md5(time().substr(sha1(microtime()),0,rand(12,25))),mt_rand(1,20),40);
								// Get next position
								else if ($this->_columns[$key] == "position")
								{
									$record = array_shift($this->_db->select("SELECT MAX(`".$key."`) AS max_position FROM `".$this->_table."` "));
									$value = (!empty($record->max_position) && is_numeric($record->max_position) && $record->max_position > 0) ? ($record->max_position+1) : 1;
								}
							}
							// Take the default lang value
							else
								$value = $this->_clone->__get($key);
						}
						
						// Set
						if (in_array($key,$filters))
							$this->_clone->__set($key,$value);
						else
							$this->_clone->$functionName($value);
						
						// Unique error ?
						if ($this->_clone->getError($key) == "E_UNIQUE")
						{	
							if (array_key_exists($key,$this->_columns) && $this->_columns[$key] == "email")
								$value = "clone_".time()."@".((substr_count($this->_generic->getSiteConfig("domainName"),".") > 1) ? SLS_String::substrAfterLastDelimiter(SLS_String::substrBeforeLastDelimiter($this->_generic->getSiteConfig("domainName"),"."),".").".".SLS_String::substrAfterLastDelimiter($this->_generic->getSiteConfig("domainName"),".") : $this->_generic->getSiteConfig("domainName"));
							else
							{
								switch($this->_types[$key])
								{
									case "number":
										$record = array_shift($this->_db->select("SELECT MAX(`".$key."`) AS max_nb FROM `".$this->_table."` "));
										$value = (!empty($record->max_nb) && is_numeric($record->max_nb)) ? ($record->max_nb+1) : 1;
										break;
									case (SLS_String::startsWith($this->_types[$key],"date_")):
										$record = array_shift($this->_db->select("SELECT MAX(`".$key."`) AS max_date FROM `".$this->_table."` "));
										$value = (!empty($record->max_date)) ? ($record->max_date) : "";
										$dateType = SLS_String::substrAfterFirstDelimiter($this->_types[$key],"date_");
										switch($dateType)
										{
											case (in_array($dateType,array("year","timestamp"))):
												$value = $value + 1;
												break;
											case "date":
												$value = SLS_Date::timestampToDate(strtotime("+ 1 second",SLS_Date::dateToTimestamp($value)));
												break;
											case "datetime":
												$value = SLS_Date::timestampToDateTime(strtotime("+ 1 second",SLS_Date::dateTimeToTimestamp($value)));
												break;
											case "time":
												$value = sls_string::substrAfterFirstDelimiter(SLS_Date::timestampToDateTime(strtotime("+ 1 second",SLS_Date::dateTimeToTimestamp(date("Y-m-d")." ".$value)))," ");
												break;
										}
										break;
									default:
										$value = substr(md5(time().substr(sha1(microtime()),0,rand(12,5))),mt_rand(1,5),10);
										break;
								}
							}
							
							$this->_clone->$functionName($value);
						}
					}
					
					$errors = $this->_clone->getErrors();
					
					if (empty($errors))
					{
						$this->_clone->create($cloneId);
						$nbClone += 1;
					}
				}
			}
			$this->_clone->clear();
		}
		if ($this->_object->isMultilanguage() && is_numeric($nbClone) && $nbClone > 0)
			$nbClone = floor($nbClone / count($langs));
		# Perform clone
		
		# Notif
		if (!empty($nbClone) && $nbClone !== false && is_numeric($nbClone))
			$this->pushNotif("success",($nbClone==1) ? $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_GENERIC_SUBMIT_SUCCESS_CLONE'] : sprintf($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_GENERIC_SUBMIT_SUCCESS_CLONES'],$nbClone));
		else
			$this->pushNotif("error",$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_GENERIC_SUBMIT_ERROR_CLONE']);
		# /Notif
			
		if ($this->_async)
		{
			if ($nbClone !== false && is_numeric($nbClone) && $nbClone > 0)
			{
				$this->_render["status"] = "OK";
				$this->_render["result"]["message"] = ($nbClone==1) ? $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_GENERIC_SUBMIT_SUCCESS_CLONE'] : sprintf($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_GENERIC_SUBMIT_SUCCESS_CLONES'],$nbClone);
				$rememberList = (is_array($this->_session->getParam("SLS_BO_LIST"))) ? $this->_session->getParam("SLS_BO_LIST") : array();
				if (array_key_exists($this->_db_alias."_".$this->_table,$rememberList) && !empty($rememberList[$this->_db_alias."_".$this->_table]))
					$this->_render["forward"] = $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$rememberList[$this->_db_alias."_".$this->_table];
				else
					$this->_render["forward"] = $this->_generic->getFullPath($this->_boController,"List".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table));
			}
			else
				$this->_render["result"]["message"] = $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_ASYNC_ERROR'];
			echo json_encode($this->_render);
			die();
		}
		else
		{	
			# Forward
			if ($this->_forward)
			{
				$rememberList = (is_array($this->_session->getParam("SLS_BO_LIST"))) ? $this->_session->getParam("SLS_BO_LIST") : array();
				if (array_key_exists($this->_db_alias."_".$this->_table,$rememberList) && !empty($rememberList[$this->_db_alias."_".$this->_table]))
					$this->_generic->redirect($rememberList[$this->_db_alias."_".$this->_table]);
				else
					$this->_generic->forward($this->_boController,"List".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table));
			}
			# /Forward
		}
	}
	/**
	 * Set the current template you want to use with your action
	 *
	 * @access public
	 * @param string $tpl the template name
	 * @return bool $set true if ok, else false
	 * @see SLS_Generic::getCurrentTpl
	 * @since 1.0.1
	 */
	public function setCurrentTpl($tpl)
	{
		$templates = array();
		
		$handle = opendir($this->getPathConfig(($this->_side == "user") ? "viewsTemplates" : "coreViewsTemplates"));
		while($file = readdir($handle))
		{
			if (is_file($this->getPathConfig(($this->_side == "user") ? "viewsTemplates" : "coreViewsTemplates").$file) && substr($file, 0, 1) != ".")
			{
				$fileName 	= SLS_String::substrBeforeLastDelimiter($file,".");
				$extension 	= SLS_String::substrAfterLastDelimiter($file,".");
				
				if ($extension == "xsl")
					array_push($templates,$fileName);
			}
		}
		closedir($handle);
		
		if (in_array($tpl,$templates))
		{
			$this->_currentTpl = $tpl;
			return true;
		}
		else
		{			
			SLS_Tracing::addTrace(new Exception("Warning: you choose an unknown template ('".$tpl."')"));
			return false;
		}
	}