public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		
		$table 		= SLS_String::substrAfterFirstDelimiter(SLS_String::trimSlashesFromString($this->_http->getParam("__table")),"_");
		$db			= SLS_String::substrBeforeFirstDelimiter(SLS_String::trimSlashesFromString($this->_http->getParam("__table")),"_");
		$columns 	= $this->_http->getParams();
		$class		= ucfirst($db)."_".SLS_String::tableToClass($table);
		$desc		= SLS_String::trimSlashesFromString($this->_http->getParam("description"));
		
		$this->_generic->useModel($table,$db,"user");
		$object = new $class();
		if (!empty($desc))
			$object->setTableComment($desc,$table,$db);
		
		// Descriptions
		foreach($columns as $key => $value)
		{
			if (SLS_String::startsWith($key,"col_"))
			{
				$column = SLS_String::substrAfterFirstDelimiter($key,"_");
				$object->setColumnComment($column,SLS_String::trimSlashesFromString($value),$table);
			}
		}
		
		$controllers = $this->_generic->getTranslatedController("SLS_Bo","EditModel");
		$this->_generic->redirect($controllers["controller"]."/".$controllers["scontroller"]."/name/".$db."_".$table);
		
		$this->saveXML($xml);
	}
	public function action()
	{
		$user 	= $this->hasAuthorative();
		$xml = $this->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);
	}
	public function action()
	{
		
		$user 	= $this->hasAuthorative();
		$xml 	= $this->getXML();
		$xml	= $this->makeMenu($xml);
		$this->_generic->loadProjectSettings();
		
		$env = $this->_http->getParam("Env");
		if (empty($env))
			$env = "prod";
		
		if ($this->_http->getParam("ProdDeployment") == "true" && file_exists($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/project_".$env.".xml"))					
			$projectXML = new SLS_XMLToolbox(file_get_contents($this->_generic->getRoot().$this->_generic->getPathConfig("configSecure")."/project_".$env.".xml"));
		else
			$projectXML = $this->_generic->getProjectXML();
		
		$errors = array();
		
		// Prod Deployment		
		$finalFile = ($this->_http->getParam("ProdDeployment") == "true") ? "project_".$env.".xml" : "project.xml";
		$isInBatch = ($this->_http->getParam("CompleteBatch") == "true") ? true : false;
		$xml->addFullTag("is_batch",($isInBatch) ? "true" : "false",true);
		$xml->addFullTag("is_prod",($this->_http->getParam("ProdDeployment") == "true") ? "true" : "false",true);		
		$reload = $this->_http->getParam("reload");
		
		if ($reload == "true")
		{
			
			$postProject = SLS_String::trimSlashesFromString($this->_http->getParam("project", "post"));
			$newXML = (SLS_String::startsWith(trim($postProject),"<?xml")) ? new SLS_XMLToolbox($postProject) : new SLS_XMLToolbox("<?xml version=\"1.0\" encoding=\"utf-8\"?>".$postProject);
			
			if (!$this->_generic->isValidXML($newXML->getXML()))
				array_push($errors, "The XML is incorrect");
					
			if (empty($errors))
			{
				if (count($newXML->getTags("//project")) != 1)
					array_push($errors, "The Root node should be called 'project'");
				
				$newXML = $this->checkNode("//project", $newXML);
				
				if (empty($errors))
				{
					$xmlStr = trim($newXML->getXML());
					if (substr($xmlStr, 0, 2)!= "<?")
						$xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?>".$xmlStr;
					$projectXML->refresh();
					@file_put_contents($this->_generic->getPathConfig("configSecure").$finalFile, $xmlStr);
					if ($isInBatch)
						$this->_generic->forward("SLS_Bo","ProductionDeployment");
					else if ($this->_http->getParam("ProdDeployment") == "true")
						$this->_generic->forward("SLS_Bo","ProductionDeployment");
					$projectXML = new SLS_XMLToolbox($xmlStr);
				}
				
			}
			
			if (!empty($errors))
			{ 
				$xml->startTag('errors');
				foreach ($errors as $error)
				{
					$xml->addFullTag('error', $error, true);
				}
				$xml->endTag('errors');
			}
	
		}
		$this->_generic->eraseCache('Project');
		
		$value = (count($projectXML->getTags('//project/*')) == 0) ? "<project>\n</project>" : $projectXML->getXML('noHeader');
		
		$xml->startTag("current_values");
			$xml->addFullTag("project", str_replace(array('<![CDATA[', ']]>'), array('&#139;![CDATA[',']]&#155;'), $value), true);
		$xml->endTag("current_values");
		
		$this->saveXML($xml);		
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$sql = SLS_Sql::getInstance();
		
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$errors = array();
		
		// Get the table name
		$table = SLS_String::substrAfterFirstDelimiter($this->_http->getParam("name"),"_");
		$db	   = SLS_String::substrBeforeFirstDelimiter($this->_http->getParam("name"),"_");
		$column= $this->_http->getParam("column");		
		$class = ucfirst($db)."_".SLS_String::tableToClass($table);
		$file  = ucfirst($db).".".SLS_String::tableToClass($table);
		
		// If current db is not this one
		if ($sql->getCurrentDb() != $db)
			$sql->changeDb($db);
		
		if ($sql->tableExists($table))
		{
			if ($this->_http->getParam("reload") == "true")
			{
				$replacements = array('&amp;','&gt;','&lt;','&#61;','"',"'");
				$masks = array('&','>','<','=','','','');
				
				$columnWanted 	= $this->_http->getParam("column");
				$tableWanted 	= $this->_http->getParam("table");
				$labelWanted 	= $this->_http->getParam($tableWanted.'_fkLabel');
				$labelSpecified = SLS_String::trimSlashesFromString($this->_http->getParam("fkLabel_specified"));				
				$multilang 		= $this->_http->getParam("multilanguage");
				$onDelete 		= $this->_http->getParam("ondelete");
								
				$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml");
				$xmlFk = new SLS_XMLToolbox($pathsHandle);
				$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/types.xml");
				$xmlType = new SLS_XMLToolbox($pathsHandle);
				$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/filters.xml");
				$xmlFilter = new SLS_XMLToolbox($pathsHandle);
				if (!empty($labelSpecified))
					$labelSpecified = str_replace(array('='),array('&#61;'),htmlentities(strtolower($labelSpecified),ENT_QUOTES,"UTF-8"));				
				$result = $xmlFk->getTags("//sls_configs/entry[@tableFk='".$db."_".$table."' and @columnFk='".$columnWanted."' and @tablePk='".$tableWanted."']");
				
				// If an entry already exists in the XML, delete this record
				if (!empty($result))
				{
					$xmlTmp = $xmlFk->deleteTags("//sls_configs/entry[@tableFk='".$db."_".$table."' and @columnFk='".$columnWanted."' and @tablePk='".$tableWanted."']");					
					$xmlFk->saveXML($this->_generic->getPathConfig("configSls")."/fks.xml",$xmlTmp);
					$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml");
					$xmlFk = new SLS_XMLToolbox($pathsHandle);
				}
				
				// Save it into the XML
				$xmlNode = '<entry tableFk="'.$db."_".$table.'" columnFk="'.$columnWanted.'" multilanguage="'.$multilang.'" ondelete="'.$onDelete.'" labelPk="'.(empty($labelSpecified) ? $labelWanted : $labelSpecified).'" tablePk="'.$tableWanted.'" />';					
				$xmlFk->appendXMLNode("//sls_configs",$xmlNode);
				$xmlFk->saveXML($this->_generic->getPathConfig("configSls")."/fks.xml",$xmlFk->getXML());
				
				// Update model
				$this->_generic->goDirectTo("SLS_Bo","UpdateModel",array(array("key"=>"name","value"=>$this->_http->getParam("name"))));
			}
			
			// Get generic object
			$this->_generic->useModel(SLS_String::tableToClass($table),$db,"user");
			$object = new $class();
			
			// Get object's infos
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml");
			$xmlFk = new SLS_XMLToolbox($pathsHandle);
			$columnsP = $object->getParams();
			$pk = $object->getPrimaryKey();
			$multilanguage = $object->isMultilanguage();		
			$xml->startTag("model");
			$xml->addFullTag("table",$table,true);
			$xml->addFullTag("db",$db,true);
			$xml->addFullTag("class",$class,true);
			$xml->addFullTag("pk",$pk,true);
			$xml->addFullTag("multilanguage",($multilanguage) ? "true" : "false",true);
			$xml->startTag("columns");
			foreach($columnsP as $key => $value)
			{							
				if ($object->getPrimaryKey() != $key && $key != "pk_lang")			
					$xml->addFullTag("column",$key,true);
			}
			$xml->endTag("columns");
						
			$attributes = array_shift($xmlFk->getTagsAttributes("//sls_configs/entry[@tableFk='".strtolower($db."_".$table)."' and @ columnFk='".$column."']",array("multilanguage","labelPk","tablePk","ondelete")));
			$this->_generic->useModel(SLS_String::substrAfterFirstDelimiter($attributes["attributes"][2]["value"],"_"),ucfirst(SLS_String::substrBeforeFirstDelimiter($attributes["attributes"][2]["value"],"_")),"user");
			$className = ucfirst($attributes["attributes"][2]["value"]);
			$objectN = new $className();
			$columns = $objectN->getColumns();
			$specificPattern = true;
			foreach($columns as $key)
				if ($key == $attributes["attributes"][1]["value"])
					$specificPattern = false;
			
			$xml->startTag("current_values");
				$xml->addFullTag("tableFk",$db."_".SLS_String::tableToClass($table),true);
				$xml->addFullTag("columnFk",$column,true);
				$xml->addFullTag("multilanguage",$attributes["attributes"][0]["value"],true);
				$xml->addFullTag("labelPk",$attributes["attributes"][1]["value"],true);
				$xml->addFullTag("tablePk",$attributes["attributes"][2]["value"],true);
				$xml->addFullTag("ondelete",$attributes["attributes"][3]["value"],true);
				$xml->addFullTag("specific_pattern",($specificPattern) ? "true" : "false",true);
			$xml->endTag("current_values");
			
			$tables = $this->getAllModels();
			
			sort($tables,SORT_REGULAR);			
				
			$xml->startTag("tables");			
			for($i=0 ; $i<$count=count($tables) ; $i++)
			{
				if (SLS_String::startsWith($tables[$i],$db))
				{
					$xml->startTag("table");
					$xml->addFullTag("name",SLS_String::substrAfterFirstDelimiter($tables[$i],"."));
					$xml->addFullTag("db",SLS_String::substrBeforeFirstDelimiter($tables[$i],"."));
					$tableN = SLS_String::substrAfterFirstDelimiter($tables[$i],".");
					$dbN = SLS_String::substrBeforeFirstDelimiter($tables[$i],".");
					$classN = ucfirst($dbN)."_".SLS_String::tableToClass($tableN);								
					$this->_generic->useModel($tableN,$dbN,"user");				
					$obj = new $classN();
					$properties = $obj->getParams();
					$xml->startTag("columns");
					foreach($properties as $key => $value)
						if ($key != "pk_lang")
							$xml->addFullTag("column",$key,true);
					$xml->endTag("columns");
					$xml->endTag("table");
				}
			}
				
			$xml->endTag("tables");	
			$xml->endTag("model");
		}
		else
		{
			$xml->addFullTag("error","Sorry this table doesn't exist anymore",true);
		}
		
		$this->saveXML($xml);
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$langs = $this->_lang->getSiteLangs();
		$listing = true;
		$errors = array();
		$controllersXML = $this->_generic->getControllersXML();
		$controller = $this->_http->getParam('Controller');
		$protocol = $this->_generic->getSiteConfig("protocol");
				
		// Check if bo controller
		$isBo = ($this->_http->getParam('isBo')=="true") ? true : false;
				
		if ($this->_http->getParam('reload') == 'true')
		{
			$postControllerName = SLS_String::trimSlashesFromString($this->_http->getParam('controllerName'));
			$newControllerName = SLS_String::stringToUrl(ucwords($postControllerName), "", false);
			$postProtocol = SLS_String::trimSlashesFromString($this->_http->getParam('protocol'));
			$tpl = SLS_String::trimSlashesFromString($this->_http->getParam('template'));
			$postControllerLangs = array();
			if (empty($newControllerName))
				array_push($errors, "The generic controller name is required to add a new Controller");
			if (empty($postProtocol) || ($postProtocol != 'http' && $postProtocol != 'https'))
				array_push($errors, "Protocol must be http or https");
			else 
				$protocol = $postProtocol;
			foreach ($langs as $lang)
			{
				$langController = SLS_String::stringToUrl(SLS_String::trimSlashesFromString($this->_http->getParam($lang."-controller")), "", false);
				if (empty($langController))
					array_push($errors, "The translation in ".$lang." is required to add a new Controller");
				else
					$postControllerLangs[$lang] = $langController;
			}
			
							
			if (empty($errors))
			{
				$test = $controllersXML->getTags("//controllers/controller[@name='".$newControllerName."']");
				if (count($test) != 0)
					array_push($errors, ($newControllerName == $postControllerName) ? "The controller Name '".$postControllerName."' already exist" : "The controller Name '".$postControllerName."' (".$newControllerName.") already exist");
			}
			if (empty($errors))
			{
				$translatedController = $controllersXML->getTags("//controllers/controller/controllerLangs/controllerLang",  'id');
				foreach ($postControllerLangs as $key=>$value)
				{
					if (in_array($value, $translatedController))
						array_push($errors, "The translated name '".$value."' for this controller is alredy used");
				}
				if (empty($errors))
				{
				
					$controllerID = $this->_generic->generateControllerId();
					$str = "<controller name=\"".$newControllerName."\" side=\"user\" protocol=\"".$protocol."\" id=\"".$controllerID."\"";
					
					if (!$isBo && $tpl != -1)
						$str .= " tpl=\"".$tpl."\"";
					if ($isBo)
						$str .= " isBo=\"true\" tpl=\"bo\"";
					
					$str .= "><controllerLangs>";

					foreach ($postControllerLangs as $key=>$value)
						$str .= "<controllerLang lang=\"".$key."\"><![CDATA[".$value."]]></controllerLang>";
					
					$str .= "</controllerLangs><scontrollers></scontrollers></controller>";
					$controllersXML->appendXMLNode("//controllers", $str);
					
					$strControllerProtected = '<?php'."\n".
						   '/**'."\n".
						   '* Class generic for the controller '.$newControllerName.''."\n".
						   '* Write here all your generic functions you need in your '.$newControllerName.' Actions'."\n".
						   '* @author SillySmart'."\n".
						   '* @copyright SillySmart'."\n".
						   '* @package Mvc.Controllers.'.$newControllerName.''."\n".
						   '* @see Mvc.Controllers.SiteProtected'."\n".
						   '* @see Sls.Controllers.Core.SLS_GenericController'."\n".
						   '* @since 1.0'."\n".
						   '*/'."\n".
						   'class '.$newControllerName.'ControllerProtected extends SiteProtected'."\n".
						   '{'."\n".
						   t(1).'public function init()'."\n".
						   t(1).'{'."\n".
						   		t(2).'parent::init();'."\n".
						   t(1).'}'."\n".
						   '}'."\n".
						   '?>';
					
					// Create the Controller Directory and Protected Function file					
					mkdir($this->_generic->getPathConfig("actionsControllers").$newControllerName);					
					file_put_contents($this->_generic->getPathConfig("actionsControllers").$newControllerName."/__".$newControllerName.".protected.php", $strControllerProtected);
					// Create Lang Directory
					mkdir($this->_generic->getPathConfig("actionLangs").$newControllerName);
					
					// Create Lang Files
					foreach ($langs as $lang)
					{
						$strLang = '<?php'."\n".
											'/**'."\n".
											'* '.strtoupper($lang).' File for all the Controller '.$newControllerName."\n".
											'* You can create all your sentences variables here. To create it, follow the exemple :'."\n".
											'* '.t(1).'Access it with JS and XSL variable : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'JS\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
											'* '.t(1).'Access it with XSL variable only   : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'XSL\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
											'*'."\n".
											'* '."\t".'You can customise the value \'KEY_OF_YOUR_VARIABLE\' and "value of your sentence in '.strtoupper($lang).'" '."\n".
											'* @author SillySmart'."\n".
											'* @copyright SillySmart'."\n".
											'* @package Langs.Actions.'.$newControllerName."\n".
											'* @since 1.0'."\n".
											'*'."\n".
											'*/'."\n".
											'?>';
						file_put_contents($this->_generic->getPathConfig("actionLangs").$newControllerName."/__".$newControllerName.".".strtolower($lang).".lang.php", $strLang);
					}	
						
					// Create Views Directory
					mkdir($this->_generic->getPathConfig("viewsHeaders").$newControllerName);
					mkdir($this->_generic->getPathConfig("viewsBody").$newControllerName);
					// Save the new XML
					file_put_contents($this->_generic->getPathConfig('configSecure')."controllers.xml", $controllersXML->getXML());
					// Insert Into Meta
					$metasXML = $this->_generic->getCoreXML('metas');
					$strMetas = "<action id=\"".$controllerID."\" />";
					$metasXML->appendXMLNode("//sls_configs", $strMetas);
					file_put_contents($this->_generic->getPathConfig('configSls')."metas.xml", $metasXML->getXML());
					
					# isBo
					if ($isBo)
					{
						# Public/Files/__Uploads/images/bo
						if (!file_exists($this->_generic->getPathConfig("files")."__Uploads") && !is_dir($this->_generic->getPathConfig("files")."__Uploads"))
							mkdir($this->_generic->getPathConfig("files")."__Uploads");
						if (!file_exists($this->_generic->getPathConfig("files")."__Uploads/images") && !is_dir($this->_generic->getPathConfig("files")."__Uploads/images"))
							mkdir($this->_generic->getPathConfig("files")."__Uploads/images");
						if (!file_exists($this->_generic->getPathConfig("files")."__Uploads/images/bo") && !is_dir($this->_generic->getPathConfig("files")."__Uploads/images/bo"))
							mkdir($this->_generic->getPathConfig("files")."__Uploads/images/bo");
						if (file_exists($this->_generic->getPathConfig("installDeployement")."Public/Files/__Uploads/images/bo") && is_dir($this->_generic->getPathConfig("installDeployement")."Public/Files/__Uploads/images/bo"))
						{
							$files = scandir($this->_generic->getPathConfig("installDeployement")."Public/Files/__Uploads/images/bo");
							foreach($files as $file)
							{
								if (!SLS_String::startsWith($file,"."))
								{
									@copy($this->_generic->getPathConfig("installDeployement")."Public/Files/__Uploads/images/bo/".$file, $this->_generic->getPathConfig("files")."__Uploads/images/bo/".$file);
								}
							}
						}
						# /Public/Files/__Uploads/images/bo
						
						# Controller langs
						foreach($langs as $lang)
						{
							if (file_exists($this->_generic->getPathConfig("installDeployement")."Langs/Actions/{{USER_BO}}/__{{USER_BO}}.".$lang.".lang.php"))
								$langContent = str_replace(array("{{USER_BO}}"),array($newControllerName),file_get_contents($this->_generic->getPathConfig("installDeployement")."Langs/Actions/{{USER_BO}}/__{{USER_BO}}.".$lang.".lang.php"));
							else
								$langContent = str_replace(array("{{USER_BO}}"),array($newControllerName),file_get_contents($this->_generic->getPathConfig("installDeployement")."Langs/Actions/{{USER_BO}}/__{{USER_BO}}.en.lang.php"));
							if (!empty($langContent))
								file_put_contents($this->_generic->getPathConfig("actionLangs").$newControllerName."/__".$newControllerName.".".$lang.".lang.php",$langContent);
						}
						# /Controller langs
						
						# XSL Templates
						$boTemplates = array("bo.xsl","bo_light.xsl","bo_blank.xsl");
						foreach($boTemplates as $boTemplate)
						{
							if (file_exists($this->_generic->getPathConfig("installDeployement")."Views/Templates/".$boTemplate) && !is_dir($this->_generic->getPathConfig("installDeployement")."Views/Templates/".$boTemplate))
							{
								@copy($this->_generic->getPathConfig("installDeployement")."Views/Templates/".$boTemplate, $this->_generic->getPathConfig("viewsTemplates").$boTemplate);
							}
						}
						# /XSL Templates
						
						# XSL Generics
						$boGenerics = array("Boactionsbar.xsl","Boheaders.xsl","Bomenu.xsl");
						foreach($boGenerics as $boGeneric)
						{
							if (file_exists($this->_generic->getPathConfig("installDeployement")."Views/Generics/".$boGeneric) && !is_dir($this->_generic->getPathConfig("installDeployement")."Views/Generics/".$boGeneric))
							{
								@copy($this->_generic->getPathConfig("installDeployement")."Views/Generics/".$boGeneric, $this->_generic->getPathConfig("viewsGenerics").$boGeneric);
							}
						}
						# /XSL Generics
						
						# Controllers Statics
						$boStatics = array("BoMenu.controller.php");
						foreach($boStatics as $boStatic)
						{
							if (file_exists($this->_generic->getPathConfig("installDeployement")."Controllers/Statics/".$boStatic) && !is_dir($this->_generic->getPathConfig("installDeployement")."Controllers/Statics/".$boStatic))
							{
								@copy($this->_generic->getPathConfig("installDeployement")."Controllers/Statics/".$boStatic, $this->_generic->getPathConfig("staticsControllers").$boStatic);
							}
						}
						# /Controllers Statics
						
						# __{{USER_BO}}.protected.php
						if (file_exists($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/{{USER_BO}}/__{{USER_BO}}.protected.php") && !is_dir($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/{{USER_BO}}/__{{USER_BO}}.protected.php"))
						{
							@copy($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/{{USER_BO}}/__{{USER_BO}}.protected.php", $this->_generic->getPathConfig("actionsControllers").$newControllerName."/__".$newControllerName.".protected.php");
							@file_put_contents($this->_generic->getPathConfig("actionsControllers").$newControllerName."/__".$newControllerName.".protected.php",str_replace(array("{{USER_BO}}"),array($newControllerName),file_get_contents($this->_generic->getPathConfig("actionsControllers").$newControllerName."/__".$newControllerName.".protected.php")));
						}
						# /__{{USER_BO}}.protected.php
						
						# Native actions
						$controllerPath = $this->_generic->getPathConfig("installDeployement")."Controllers/Actions/{{USER_BO}}";
						$boActions = scandir($controllerPath);
						$boLightActions = array("BoLogin","BoRenewPwd","BoForgottenPwd");
						$boBlankActions = array("BoMenu");
						$tokenSecret = sha1(substr($this->_generic->getSiteConfig("privateKey"), 0, 3).substr($this->_generic->getSiteConfig("privateKey"), strlen($this->_generic->getSiteConfig("privateKey"))-3));
						foreach($boActions as $boAction)
						{
							if ( SLS_String::startsWith($boAction,"Bo") 			&& // Real boAction
								 file_exists($controllerPath."/".$boAction) 		&& // File exist
								!is_dir($controllerPath."/".$boAction)				&& // Not a directory 
								!SLS_String::startsWith($boAction,"BoUser") 		&& // Exclude custom action "BoUser(*)" 
								!SLS_String::startsWith($boAction,"Boi18n") 		&& // Exclude custom action "Boi18n" 
								!SLS_String::startsWith($boAction,"BoFileUpload") 	&& // Exclude custom action "BoFileUpload"
								!SLS_String::startsWith($boAction,"BoProjectSettings") // Exclude custom action "BoProjectSettings"
							)
							{
								// Generate Action
								$action = SLS_String::substrBeforeFirstDelimiter($boAction,".");
								$params = array(0 => array("key" 	=> "reload",
										  				   "value" 	=> "true"),
										  		1 => array("key" 	=> "Controller",
										  				   "value" 	=> $newControllerName),
											 	2 => array("key" 	=> "actionName",
										  				   "value" 	=> $action),
										  		3 => array("key"	=> "token",
										  				   "value"	=> $tokenSecret),
										  		4 => array("key"	=> "template",
										  				   "value" 	=> (in_array($action,$boLightActions)) ? "bo_light" : ((in_array($action,$boBlankActions)) ? "bo_blank" : "bo")),
										  		5 => array("key"	=> "dynamic",
										  				   "value" 	=> "on"),
										  		6 => array("key"	=> "indexes",
										  				   "value"	=> "noindex,nofollow")
											    );
								if ($action == "BoLogin")
									$params[] = array("key" 	=> "default",
										  			  "value"  => "on");
								foreach($langs as $lang)
								{
									$tmpParam = array("key" 	=> $lang."-action",
													  "value" 	=> $action."_".$lang);
									$tmpTitle = array("key" 	=> $lang."-title",
													  "value" 	=> $action);
									array_push($params,$tmpParam);
									array_push($params,$tmpTitle);
								}
								file_get_contents($this->_generic->getFullPath("SLS_Bo",
																			  "AddAction",
																			  $params,
																			  true));
								
								// Erase Action
								$source = str_replace(array("{{USER_BO}}"),array($newControllerName),file_get_contents($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/{{USER_BO}}/".$action.".controller.php"));
								file_put_contents($this->_generic->getPathConfig("actionsControllers").$newControllerName."/".$action.".controller.php",$source);
								
								// Erase View Head
								if (file_exists($this->_generic->getPathConfig("installDeployement")."Views/Headers/{{USER_BO}}/".$action.".xsl"))
									file_put_contents($this->_generic->getPathConfig("viewsHeaders").$newControllerName."/".$action.".xsl",file_get_contents($this->_generic->getPathConfig("installDeployement")."Views/Headers/{{USER_BO}}/".$action.".xsl"));
								
								// Erase View Body
								if (file_exists($this->_generic->getPathConfig("installDeployement")."Views/Body/{{USER_BO}}/".$action.".xsl"))
									file_put_contents($this->_generic->getPathConfig("viewsBody").$newControllerName."/".$action.".xsl",file_get_contents($this->_generic->getPathConfig("installDeployement")."Views/Body/{{USER_BO}}/".$action.".xsl"));
							}
						}
						# /Native actions
					}
					# /isBo
						
					$controllersRedirect = $this->_generic->getTranslatedController('SLS_Bo', 'Controllers');
					$this->_generic->redirect($controllersRedirect['controller']."/".$controllersRedirect['scontroller']);
				}
			}
			
			if (!empty($errors))
			{
				$xml->startTag("errors");
					foreach ($errors as $error)
						$xml->addFullTag("error", $error, true);
				$xml->endTag("errors");
				$xml->startTag('form');
				$xml->addFullTag("controllerName", $postControllerName);
					foreach ($postControllerLangs as $key=>$value)
						$xml->addFullTag($key."-controller", $value, true);
						
				$xml->endTag('form');
			}
			
		}
		// Build all tpls
		$tpls = $this->getAppTpls();
		$xml->startTag("tpls");
		foreach($tpls as $template)
			$xml->addFullTag("tpl",$template,true);
		$xml->endTag("tpls");
		
		$xml->startTag('controller');
		$xml->addFullTag('isBo',($isBo) ? "true" : "false",true);
			$xml->startTag('translations');
			foreach ($langs as $lang)
			{
				$xml->startTag('translation');
					$xml->addFullTag("lang", $lang, true);	
				$xml->endTag('translation');
			}
			$xml->endTag('translations');
		$xml->endTag('controller');
		$listing = false;
		$xml->addFullTag('request', 'addController', true);
		$xml->addFullTag('protocol', $protocol, true);
		$xml->addFullTag('template', $tpl, true);
		$this->saveXML($xml);
	}
	/**
	 * Get trace infos	 
	 *
	 * @access public static
	 * @param array $traceElt associative array contained trace informations recovered by the raise of the exception
	 * @param bool $html if we want a HTML render (version dev)
	 * @return string $trace trace infos shaped (html ou plain)
	 * @since 1.0
	 */
	public static function getTraceInfo($traceElt,$html=false) 
	{
		$info = $traceElt['class'] . $traceElt['type'] . $traceElt['function'];
		$info .= '(';
		if ($traceElt['args']) 
		{			
			for ($i = 0; $i < count($traceElt['args']); $i++) 
			{
				$arg = $traceElt['args'][$i];				
				if ($html)
				{
					if (is_array($arg))
						$info .= '<a href="#" onclick="return false;" class="tooltip" title="'.gettype($arg).'" rel="<pre name=\'highlight_'.uniqid().'\' class=\'brush:php\'>'.SLS_String::printArray($arg).'</pre>">'.gettype($arg).'</a>';
					else if (is_object($arg))
						$info .= '<a href="#" onclick="return false;" class="tooltip" title="'.get_class($arg).'" rel="<pre name=\'highlight_'.uniqid().'\' class=\'brush:js\'>'.SLS_String::printObject(str_replace(array('"',':'),array("'",': '),json_encode($arg))).'</pre>">'.gettype($arg).'</a>';
					else 
					{
						if (is_string($arg) && (SLS_String::startsWith(trim(strtolower($arg)),"select") || SLS_String::startsWith(trim(strtolower($arg)),"update") || SLS_String::startsWith(trim(strtolower($arg)),"insert") || SLS_String::startsWith(trim(strtolower(arg)),"delete")))
							$info .= '<a href="#" onclick="return false;" class="tooltip" title="'.gettype($arg).'" rel="<pre name=\'highlight_'.uniqid().'\' class=\'brush:sql\'>'.(is_string($arg) ? trim($arg) : $arg).'</pre>">'.gettype($arg).'</a>';
						else	
							$info .= '<a href="#" onclick="return false;" class="tooltip" title="'.gettype($arg).'" rel="<pre name=\'highlight_'.uniqid().'\' class=\'brush:php\'>&#34;'.(is_string($arg) ? trim($arg) : $arg).'&#34;</pre>">'.gettype($arg).'</a>';
					}					
				}
				else
					$info .= is_object($arg) ? get_class($arg) : ''.gettype($arg).'';
				if ($i < count($traceElt['args']) - 1)
					$info .= ', ';				
			}
		}
		$info .= ')';
		return $info;
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$sql = SLS_Sql::getInstance();
		$dbs = $sql->getDbs();
		$results = array();
		$error = "";
		$success = "";
		
		$xml->startTag("dbs");
		foreach($dbs as $db)
			$xml->addFullTag("db",$db,true);
		$xml->endTag("dbs");		
		
		if ($this->_http->getParam("reload") == "true")
		{
			$db = $this->_http->getParam("db");
			$query = trim(SLS_String::trimSlashesFromString($this->_http->getParam("query")));
			
			$sql->changeDb($db);
			
			switch($query)
			{
				case (SLS_String::startsWith(strtolower($query),"select") || 
					  SLS_String::startsWith(strtolower($query),"show") ||
					  SLS_String::startsWith(strtolower($query),"explain") ||
					  SLS_String::startsWith(strtolower($query),"describe")):					
					$results = $sql->select($query);
					if ($results !== false)
						$success = count($results)." row(s) selected";
					break;
				case (SLS_String::startsWith(strtolower($query),"insert")):
					$results = $sql->exec($query);
					if ($results !== false)
						$success = $results." row(s) inserted";
					break;
				case (SLS_String::startsWith(strtolower($query),"update")):
					$results = $sql->update($query);
					if ($results !== false)
						$success = $results." row(s) updated";
					break;
				case (SLS_String::startsWith(strtolower($query),"delete")):
					$results = $sql->delete($query);
					if ($results !== false)
						$success = $results." row(s) deleted";
					break;
				default:
					$results = $sql->query($query);
					if ($results !== false)
						$success = $results;
					break;
			}
			
			if (!empty($success))
				$xml->addFullTag("success",$success,true);
			if ($results === false)
				$xml->addFullTag("error","SQL syntax error",true);
			else if (!empty($results) && is_array($results))
			{
				$xml->startTag("legends");
				foreach($results[0] as $key => $value)
					$xml->addFullTag("legend",strtolower($key),true);
				$xml->endTag("legends");
				
				$xml->startTag("results");
				for($i=0 ; $i<$count=count($results) ; $i++)
				{
					$xml->startTag("result");
					foreach($results[$i] as $key => $value)
						$xml->addFullTag(strtolower($key),$value,true);
					$xml->endTag("result");
				}
				$xml->endTag("results");
			}
			
			$xml->addFullTag("query",$query,true);
		}
		
		$this->saveXML($xml);
	}
Example #8
0
	/**
	 * Compile plain txt part
	 * 
	 * @access public
	 * @param array $matchesA <a href
	 * @return string txt updated
	 * @since 1.0.9
	 */
	public function compilePlain($matchesA)
	{
		$matchesImg = array();
		if(preg_match('/alt="([^"]*)"/i', $matchesA[4], $matchesImg))
			$label = $matchesImg[1];
		else
			$label = $matchesA[4];
		return SLS_String::startsWith($label, 'http') ? $matchesA[2] : $label.' ('.$matchesA[2].')';
	}
	/**
	 * Check if the given string is a valid url	(check dns & headers)
	 *
	 * @access public static
	 * @param string $url the string to test
	 * @return bool true if the string match with the url, else false
	 * @see SLS_String::isIp
	 * @see SLS_String::validateEmail
	 * @since 1.0
	 * @example 
	 * var_dump(SLS_String::isValidUrl("http://www.sillysmart.org"));
	 * // will produce : true
	 * @example 
	 * var_dump(SLS_String::isValidUrl("http://www.sillysmart.org/fake"));
	 * // will produce : false
	 */
	public static function isValidUrl($url) 
	{
		if (!SLS_String::startsWith($url,"http://") && !SLS_String::startsWith($url,"https://"))
			$url = "http://".$url;
		
		return (preg_match("/^(http:\/\/|https:\/\/)(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z]{2,6}/i",$url) == 1) ? true : false;
	}
	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->_gap = 0;
		$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
		
		# User params
		$this->_join = array();
		$this->_where = array();
		$this->_group = array();
		$this->_order = array();
		$this->_limit = array();
		$this->_reload = ($this->_http->getParam("reload-filters") == "true") ? true : false;
		$joins = $this->_xmlBo->getTagsAttributes($boPath."/joins/join",array("table","column"));
		$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 = array_shift($this->_xmlBo->getTagsAttributes($boPath."/limits/limit",array("start","length")));
		if (!empty($joins))
			for($i=0 ; $i<$count=count($joins) ; $i++)
				$this->_join[] = array("table" => SLS_String::substrAfterFirstDelimiter($joins[$i]["attributes"][0]["value"],"_"), "column" => $joins[$i]["attributes"][1]["value"], "mode" => "left");
		if (!empty($wheres) && !$this->_reload)		
			for($i=0 ; $i<$count=count($wheres) ; $i++)
				$this->_where[] = array("column" => SLS_String::substrAfterFirstDelimiter($wheres[$i]["attributes"][0]["value"],"_").".".$wheres[$i]["attributes"][1]["value"], "value" => $wheres[$i]["attributes"][2]["value"], "mode" => $wheres[$i]["attributes"][3]["value"]);
		if (!empty($groups))		
			for($i=0 ; $i<$count=count($groups) ; $i++)
				$this->_group[] = SLS_String::substrAfterFirstDelimiter($groups[$i]["attributes"][0]["value"],"_").".".$groups[$i]["attributes"][1]["value"];
		if (!empty($orders))		
			for($i=0 ; $i<$count=count($orders) ; $i++)
				$this->_order[] = array("column" => SLS_String::substrAfterFirstDelimiter($orders[$i]["attributes"][0]["value"],"_").".".$orders[$i]["attributes"][1]["value"], "order" => $orders[$i]["attributes"][2]["value"]);
		if (!empty($limits))
		{
			$this->_limit["start"] = $limits["attributes"][0]["value"];
			$this->_limit["length"] = $limits["attributes"][1]["value"];
		}		
		# /User params
		
		# Comments
		$this->_comments = array();
		$this->_types = array();
		$commentsTable = array();
		$tables = array($this->_table);
		foreach($this->_join as $joinTable)
			$tables[] = $joinTable["table"];
		foreach($tables as $commentTable)
		{
			if (!array_key_exists($commentTable,$commentsTable))
			{
				$comment = $this->_object->getTableComment($commentTable,$this->_db_alias);
				if (empty($comment))
					$comment = $commentTable;
				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]) ? $commentTable : $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$key]) : $GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$key];
				}
				$commentsTable[$commentTable] = $comment;
			}
		}		
		# /Comments
		
		# Columns
		$this->_columns = array();
		$this->_columns = array_merge($this->_columns, $this->getTableColumns($this->_db_alias,$this->_table,$boPath,"",true,true));
		foreach($this->_join as $joinTable)
			$this->_columns = array_merge($this->_columns, $this->getTableColumns($this->_db_alias,$joinTable["table"],$boPath,"",false,true));
		$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"))) || in_array($key,array("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 == "label")
				{
					$this->_xml->addFullTag($key,$value,true);
					$this->_xml->startTag("labels_html");
					$labels = explode(" ",trim($value));
					foreach($labels as $label)
						$this->_xml->addFullTag("label_html",$label,true);
					$this->_xml->endTag("labels_html");
				}
				else
					$this->_xml->addFullTag($key,$value,true);
			}
			$this->_xml->endTag("column");
		}
		$this->_xml->endTag("columns");
		# /Columns
		
		# Reload params		
		// Where
		$filters = $this->_http->getParam("filters");
		if (is_array($filters))
		{
			foreach($filters as $filterTable => $filterColumns)
			{
				foreach($filterColumns as $filterColumn => $infos)
				{	
					$values = (is_array($infos["values"]) && $this->_columns[$filterColumn]["html_type"] != 'input_checkbox') ? $infos["values"] : array($infos["values"]);
					$modes = (is_array($infos["mode"])) ? $infos["mode"] : array($infos["mode"]);
					for($i=0 ; $i<$count=count($values) ; $i++)
					{
						$value = $values[$i];
						$mode = (isset($modes[$i])) ? $modes[$i] : ((isset($modes[0])) ? ($modes[0]) : "");
						$mode = (empty($mode)) ? "equal" : $mode;
						if (is_array($value) && $this->_columns[$filterColumn]["html_type"] == 'input_checkbox')
							$mode = "in";
						
						if (in_array($mode,array("null","notnull")) || (!in_array($mode,array("null","notnull")) && !empty($value)))
						{
							$whereFound = false;
							foreach($this->_where as $where)
							{
								if (SLS_String::contains($where["column"],$filterColumn) && $where["value"] == $value && $where["mode"] == $mode)
								{
									$whereFound = true;
									break;
								}
							}
							if (!$whereFound)
								$this->_where[] = array("column" => $filterTable.".".$filterColumn, "value" => $value, "mode" => $mode);
						}
					}
				}
			}
		}
		// Order
		$orderP = $this->_http->getParam("Order");
		if (!empty($orderP))
		{
			$orderWays = array("ASC","DESC");			
			$orderColumn = SLS_String::substrBeforeLastDelimiter($orderP,"_");
			$orderWay = SLS_String::substrAfterLastDelimiter($orderP,"_");
			if (array_key_exists($orderColumn,$this->_columns))
			{
				if (!in_array(strtoupper($orderWay),$orderWays))
					$orderWay = array_shift($orderWays);
					
				$this->_order = array(array("column" => $orderColumn, "order" => $orderWay));
			}
		}
		// Limit
		$length = $this->_http->getParam("Length");
		if (!empty($length) && $length > 0)
			$this->_limit["length"] = $length;
		# /Reload params
		
		# Default params
		$positionExists = $this->_xmlType->getTag("//sls_configs/entry[@table='".$this->_table."' and @type='position']/@column");
		$lengthExists = $this->_xmlRight->getTag("//sls_configs/entry[@login='******']/settings/setting[@key='list_nb_by_page']");
		$fkRecursiveExists = $this->_xmlFk->getTag("//sls_configs/entry[@tableFk='".strtolower($this->_db_alias."_".$this->_table)."' and @tablePk='".strtolower($this->_db_alias)."_".SLS_String::tableToClass($this->_table)."']/@columnFk");
		// i18n > restrict on current language
		if ($this->_object->isMultilanguage())
		{
			$whereLang = false;
			foreach($this->_where as $where)
			{
				if (SLS_String::contains($where["column"],"pk_lang"))
				{
					$whereLang = true;
					break;
				}
			}
			if (!$whereLang)
				array_unshift($this->_where, array("column" => $this->_table.".pk_lang", "value" => $this->_lang->getLang(), "mode" => "equal"));
				
			if (!empty($this->_join))
			{
				foreach($this->_join as $join)
				{
					$join = (is_array($join) && array_key_exists("table",$join)) ? $join["table"] : $join;
					$this->_generic->useModel(SLS_String::tableToClass($join),$this->_db_alias,"user");
					$joinClass = ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($join);
					$joinObject = new $joinClass();
					$joinColumns = $joinObject->getColumns();
					if (is_array($joinColumns) && in_array("pk_lang",$joinColumns))
						array_push($this->_where, array("column" => $join.".pk_lang", "value" => $this->_lang->getLang(), "mode" => "equal"));
				}
			}
		}
		// fk on the same model
		if (!empty($fkRecursiveExists))
			$this->_where[] = array("column" => $this->_table.".".$fkRecursiveExists, "value" => "", "mode" => "null");
		// group by PK
		if (empty($this->_group))
			$this->_group = array($this->_object->getPrimaryKey());
		// order by position asc or PK desc
		if (empty($this->_order))
			$this->_order = (empty($positionExists)) ? array(array("column" => $this->_object->getPrimaryKey(), "order" => "DESC")) : array(array("column" => $positionExists, "order" => "ASC"));
		// limit at 0, 20
		if (empty($this->_limit))
		{
			if (!empty($lengthExists) && $lengthExists > 0)
				$this->_limit = array("start" => "0", "length" => $lengthExists);
			else
				$this->_limit = array("start" => "0", "length" => "20");
		}
		# /Default params
		
		# Page infos
		$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",$comment = trim((empty($commentsTable[$this->_table])) ? $this->_table : $commentsTable[$this->_table]),true);
				$this->_xml->startTag("labels_html");
				$comments = explode(" ",$comment);
				foreach($comments as $comment)
					$this->_xml->addFullTag("label_html",$comment,true);
				$this->_xml->endTag("labels_html");
				$this->_xml->addFullTag("pk",$this->_object->getPrimaryKey(),true);
			$this->_xml->endTag("model");
			$this->_xml->startTag("joins");
			foreach($this->_join as $joinTable)
			{
				$this->_xml->startTag("join");
					$this->_xml->addFullTag("db",$this->_db_alias,true);
					$this->_xml->addFullTag("table",$joinTable["table"],true);
					$this->_xml->addFullTag("column",$joinTable["column"],true);
					$this->_xml->addFullTag("label",$comment = trim((empty($commentsTable[$joinTable["table"]])) ? $joinTable["table"] : $commentsTable[$joinTable["table"]]),true);
					$this->_xml->startTag("labels_html");
					$comments = explode(" ",$comment);
					foreach($comments as $comment)
						$this->_xml->addFullTag("label_html",$comment,true);
					$this->_xml->endTag("labels_html");
				$this->_xml->endTag("join");
			}
			$this->_xml->endTag("joins");
			$pkLangWhereFound = false;
			$this->_xml->startTag("wheres");
			foreach($this->_where as $clause)
			{
				$table  = (SLS_String::contains($clause["column"],".")) ? SLS_String::substrBeforeFirstDelimiter($clause["column"],".") : $this->_table;
				$column = (SLS_String::contains($clause["column"],".")) ? SLS_String::substrAfterFirstDelimiter($clause["column"],".") : $clause["column"];
				if ($column != "pk_lang" || ($column == "pk_lang" && !$pkLangWhereFound))
				{
					if ($column == "pk_lang" && !$pkLangWhereFound)
						$pkLangWhereFound = true;
					
					$this->_xml->startTag("where");
						$this->_xml->addFullTag("table",$table,true);
						$this->_xml->addFullTag("column",$column,true);
						$this->_xml->startTag("values");
						if (is_array($clause["value"]))
						{
							foreach($clause["value"] as $clauseValue)
								$this->_xml->addFullTag("value",$clauseValue,true);
						}
						else
							$this->_xml->addFullTag("value",$clause["value"],true);
						$this->_xml->endTag("values");
						$this->_xml->addFullTag("mode",$clause["mode"],true);
					$this->_xml->endTag("where");
				}
			}
			$this->_xml->endTag("wheres");
			$this->_xml->startTag("groups");
				foreach($this->_group as $groupColumn)
					$this->_xml->addFullTag("group",(SLS_String::contains($groupColumn,".")) ? SLS_String::substrAfterFirstDelimiter($groupColumn,".") : $groupColumn,true);
			$this->_xml->endTag("groups");
			$this->_xml->startTag("order");
				$this->_xml->addFullTag("column",(SLS_String::contains($this->_order[0]["column"],".")) ? SLS_String::substrAfterFirstDelimiter($this->_order[0]["column"],".") : $this->_order[0]["column"],true);
				$this->_xml->addFullTag("way",$this->_order[0]["order"],true);
			$this->_xml->endTag("order");
			$page = ($this->_http->getParam("page") > 1) ? $this->_http->getParam("page") : 1;
			$this->_xml->startTag("limit");
				$this->_xml->addFullTag("start",$this->_limit["start"] = ($page < 2) ? 0 : (($page-1) * $this->_limit["length"]),true);
				$this->_xml->addFullTag("length",$this->_limit["length"],true);
			$this->_xml->endTag("limit");
			$countWhere = $this->_where;
			if (!empty($fkRecursiveExists))
			{
				for($i=0 ; $i<$count=count($countWhere) ; $i++)
				{
					if ($countWhere[$i]["column"] == $this->_table.".".$fkRecursiveExists)
					{
						unset($countWhere[$i]);
						break;
					}
				}
			}
			$this->_xml->addFullTag("total",$this->_object->countModels($this->_table,$this->_join,$countWhere,$this->_group),true);
		$this->_xml->endTag("page");
		# /Page infos
				
		# Recordsets
		$recordsets = $this->_object->searchModels($this->_table,$this->_join,$this->_where,$this->_group,$this->_order,$this->_limit);
		$this->_xml = $this->formatRecordsets($this->_xml,$recordsets,$fkRecursiveExists);
		# Recordsets
		
		# Urls
		$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");
		# /Urls
		
		# 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='list_nb_by_page']",$this->_limit["length"]);
			$this->_xmlRight->saveXML($this->_generic->getPathConfig("configSls")."/rights.xml");
			$this->_xmlRight->refresh();
		}
		# /Remember admin settings
		
		# Session remember
		$rememberList = $this->_session->getParam("SLS_BO_LIST");
		if (empty($rememberList))
			$rememberList = array();
		$url = SLS_String::substrAfterFirstDelimiter($_SERVER["REQUEST_URI"],(($_SERVER['SCRIPT_NAME'] != "/index.php") ? SLS_String::substrBeforeFirstDelimiter($_SERVER['SCRIPT_NAME'],"/index.php")."/" : "/"));
		if (SLS_String::endsWith($url,$this->_generic->getSiteConfig("defaultExtension")))
			$url = SLS_String::substrBeforeLastDelimiter($url,".".$this->_generic->getSiteConfig("defaultExtension"));
		$query = http_build_query($_POST,"","/");
		$query = str_replace(array("%5B","%5D","=/","="),array("[","]","=|sls_empty|/","/"),preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query));		
		if (SLS_String::endsWith(trim($query),"/"))
			$query = SLS_String::substrBeforeLastDelimiter(trim($query),"/");
		if (!empty($query))
			$url .= "/".$query.((count(explode("/",$query))%2 != 0) ? "/|sls_empty|" : "");		
		if (SLS_String::endsWith($url,"/"))
			$url = SLS_String::substrBeforeLastDelimiter($url,"/");
		$url .= ".".$this->_generic->getSiteConfig("defaultExtension");
		$rememberList[$this->_db_alias."_".$this->_table] = $url;
		$this->_session->setParam("SLS_BO_LIST",$rememberList);		
		# /Session remember
		
		return $this->_xml;
	}
Example #11
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;
	}
Example #12
0
	/**
	 * Flush action's cached files
	 * 
	 * @access public
	 * @param string $action the action id (controllers.xml @id="a_{id}") - current if empty
	 * @return bool true if deleted, else false
	 * @since 1.0.9
	 */
	public function flushAction($action="")
	{
		$this->_generic->_time_checkpoint = microtime(true);
		
		if (empty($action))
			$action = $this->_generic->getActionId();
		if (SLS_String::startsWith($action,"a_"))
			$action = SLS_String::substrAfterFirstDelimiter($action,"a_");
		return self::deleteDir($this->_generic->getPathConfig("cache")."controller_".SLS_String::substrAfterFirstDelimiter($this->_generic->getControllerIdFromActionId("a_".$action),"_")."/action_".strtolower($action));
		
		$this->_generic->logTime($this->_generic->monitor($this->_generic->_time_checkpoint),"Flush Cache","Action `".strtolower($action)."`","Flush Cache");
	}
Example #13
0
	/**
	 * StartsWith recursive
	 * 
	 * @access private
	 * @param string $hay the string in which you search
	 * @param mixed $needles the string or the array of occurences searched
	 * @return bool false if not starts with, else true
	 * @since 1.1
	 */
	private function startsWithRecursive($hay,$needles)
	{
		if (is_array($needles))
		{
			foreach($needles as $needle)
			{				
				if (SLS_String::startsWith($hay,$needle))				
					return true;
			}
		}
		else
			return SLS_String::startsWith($hay,$needles);
			
		return false;
	}
	public function action() 
	{		
		// Objects
		$xml = $this->getXML();
		$user = $this->hasAuthorative();
		$xml = $this->makeMenu($xml);
		$actions = array("read"   => array(),
						 "add" 	  => array(),
						 "edit"   => array(),
						 "delete" => array(),
						 "clone"  => array(),
						 "email"  => array(),
						 "custom" => array());
		$autoActions = array("BoDashBoard", "BoDeleteFile", "BoExport", "BoFkAc", "BoIsLogged", "BoLike", "BoSetting", "BoUnique", "BoUpload", "BoUploadProgress");
		$_publicActions = array("BoLogin",
								"BoLogout",
								"BoForgottenPwd",
								"BoMenu", 
								"BoRenewPwd",
								"BoSwitchLang");
		$_forbiddenActions = array("BoPopulate");
		$db = SLS_Sql::getInstance();
		$color = "pink";
		$xmlColors = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/bo_colors.xml"));
		$errors = array();
		
		if ($db->tableExists("sls_graph"))
		{
			$actions["dashboard"] = array();
			$dashboardId = $this->_generic->getControllersXML()->getTag("//controllers/controller[@isBo='true']/scontrollers/scontroller[@name='BoDashBoard']/@id");
			$this->_generic->useModel("Sls_graph",$this->defaultDb,"sls");
			$className = ucfirst($this->defaultDb)."_Sls_graph";
			$slsGraph = new $className;
			$slsGraphs = $slsGraph->searchModels("sls_graph",array(),array(),array(),array("sls_graph_title" => "asc"));
			for($i=0 ; $i<$count=count($slsGraphs) ; $i++)
				$actions["dashboard"][$dashboardId."_sls_graph_".$slsGraphs[$i]->sls_graph_id] = "_".$slsGraphs[$i]->sls_graph_title;
		}
		
		$results = $this->_generic->getControllersXML()->getTagsAttributes("//controllers/controller[@isBo='true']/scontrollers/scontroller",array("name","id"));
		for($i=0 ; $i<$count=count($results) ; $i++)
		{
			$name = $results[$i]["attributes"][0]["value"];
			$aid = $results[$i]["attributes"][1]["value"];
			switch($name)
			{
				case (SLS_String::startsWith($name,"List") && SLS_String::contains($name,"_")):
					$actions["read"][$aid] = $name;		
					break;
				case (SLS_String::startsWith($name,"Add") && SLS_String::contains($name,"_")):
					$actions["add"][$aid] = $name;		
					break;
				case (SLS_String::startsWith($name,"Modify") && SLS_String::contains($name,"_")):
					$actions["edit"][$aid] = $name;		
					break;
				case (SLS_String::startsWith($name,"Delete") && SLS_String::contains($name,"_")):
					$actions["delete"][$aid] = $name;		
					break;
				case (SLS_String::startsWith($name,"Clone") && SLS_String::contains($name,"_")):
					$actions["clone"][$aid] = $name;		
					break;
				case (SLS_String::startsWith($name,"Email") && SLS_String::contains($name,"_")):
					$actions["email"][$aid] = $name;		
					break;
				default:
					if (!in_array($name,$_publicActions) && !in_array($name,$_forbiddenActions) && !in_array($name,$autoActions))
					{
						$id = array_shift($this->_generic->getControllersXML()->getTags("//controllers/controller[@isBo='true']/scontrollers/scontroller[@name='".$name."']/@id"));
						if (!empty($id))
							$actions["custom"][$id] = "_".$name;
					}
					break;
			}
		}
		$xml->startTag("bo_groups");
		foreach($actions as $action => $values)
		{
			$xml->startTag("bo_group");
			$xml->addFullTag("name",$action,true);
			foreach($values as $aid => $name)
			{
				$model = "";
				switch ($name)
				{
					case (SLS_String::startsWith($name,"List")): 	$model = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($name,"List"),"_"); 	break;
					case (SLS_String::startsWith($name,"Add")): 	$model = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($name,"Add"),"_"); 	break;
					case (SLS_String::startsWith($name,"Modify")): 	$model = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($name,"Modify"),"_"); break;
					case (SLS_String::startsWith($name,"Delete")): 	$model = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($name,"Delete"),"_"); break;
					case (SLS_String::startsWith($name,"Clone")): 	$model = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($name,"Clone"),"_"); 	break;
					case (SLS_String::startsWith($name,"Email")): 	$model = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($name,"Email"),"_"); 	break;
					default:										$model = "";
				}
				$xml->startTag("action");
					$xml->addFullTag("name",SLS_String::substrAfterFirstDelimiter($name,"_"),true);
					$xml->addFullTag("model",$model,true);
					$xml->addFullTag("id",$aid,true);
				$xml->endTag("action");
			}
			$xml->endTag("bo_group");
		}
		$xml->endTag("bo_groups");
		
		$complexity_pwd_min_char_nb = 8;
		$renew_pwd_nb = 2;
		$renew_pwd_unite = "month";
		$renew_pwd_log_nb = 3;
		$complexity = array();
		$privilegeChoose = false;
		$minChars = "";
		$enabled = "true";
		
		if ($this->_http->getParam("reload") == "true")
		{
			$login 							= SLS_String::trimSlashesFromString($this->_http->getParam("login"));
			$name 							= SLS_String::trimSlashesFromString($this->_http->getParam("name"));
			$firstname						= SLS_String::trimSlashesFromString($this->_http->getParam("firstname"));
			$pwd 							= SLS_String::trimSlashesFromString($this->_http->getParam("password"));
			$enabled						= SLS_String::trimSlashesFromString($this->_http->getParam("enabled"));
			$complexity_pwd_lc 				= SLS_String::trimSlashesFromString($this->_http->getParam("complexity_pwd_lc"));
			$complexity_pwd_uc 				= SLS_String::trimSlashesFromString($this->_http->getParam("complexity_pwd_uc"));
			$complexity_pwd_digit 			= SLS_String::trimSlashesFromString($this->_http->getParam("complexity_pwd_digit"));
			$complexity_pwd_special_char 	= SLS_String::trimSlashesFromString($this->_http->getParam("complexity_pwd_special_char"));
			$complexity_pwd_min_char 		= SLS_String::trimSlashesFromString($this->_http->getParam("complexity_pwd_min_char"));
			$complexity_pwd_min_char_nb 	= SLS_String::trimSlashesFromString($this->_http->getParam("complexity_pwd_min_char_nb"));
			$reset_pwd 						= SLS_String::trimSlashesFromString($this->_http->getParam("reset_pwd"));
			$renew_pwd 						= SLS_String::trimSlashesFromString($this->_http->getParam("renew_pwd"));
			$renew_pwd_nb 					= SLS_String::trimSlashesFromString($this->_http->getParam("renew_pwd_nb"));
			$renew_pwd_unite 				= SLS_String::trimSlashesFromString($this->_http->getParam("renew_pwd_unite"));
			$renew_pwd_log 					= SLS_String::trimSlashesFromString($this->_http->getParam("renew_pwd_log"));
			$renew_pwd_log_nb 				= SLS_String::trimSlashesFromString($this->_http->getParam("renew_pwd_log_nb"));
			$color 							= SLS_String::trimSlashesFromString($this->_http->getParam("color"));
			$params 						= $this->_http->getParams();
			
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/rights.xml");
			$xmlRights = new SLS_XMLToolbox($pathsHandle);
			$result = $xmlRights->getTags("//sls_configs/entry[@login='******']");
			
			if (!empty($result))			
				array_push($errors,"This account already exists, please choose another login.");
			if (empty($name) || empty($firstname))
				array_push($errors,"You must fill name and firstname.");
			if (empty($login) || empty($pwd))
				array_push($errors,"You must choose username and password.");
			
			foreach($params as $key => $value)
			{				
				if (SLS_String::startsWith($key,"bo_action"))
				{
					$privilegeChoose = true;
					break;
				}
			}
			if (!$privilegeChoose)			
				array_push($errors,"You must choose at least 1 privilege.");
			
			if (empty($errors))
			{
				if ($complexity_pwd_lc == "true")
					array_push($complexity,"lc");
				if ($complexity_pwd_uc == "true")
					array_push($complexity,"uc");
				if ($complexity_pwd_digit == "true")
					array_push($complexity,"digit");
				if ($complexity_pwd_special_char == "true")
					array_push($complexity,"special_char");
					
				if ($complexity_pwd_min_char == "true")
					$minChars = $complexity_pwd_min_char_nb;
								
				$xmlNew = '<entry login="******" name="'.SLS_String::stringToUrl($name," ").'" firstname="'.SLS_String::stringToUrl($firstname," ").'" enabled="'.$enabled.'" password="******" password_old="" last_connection="" last_renew_pwd="'.date("Y-m-d").'" complexity_pwd="'.implode("|",$complexity).'" min_chars_pwd="'.$minChars.'" reset_pwd="'.(($reset_pwd=="true") ? "true" : "").'" renew_pwd="'.(($renew_pwd=="true") ? $renew_pwd_nb." ".$renew_pwd_unite : "").'" renew_pwd_nb="'.(($renew_pwd_log=="true") ? $renew_pwd_log_nb : "").'">'."\n";
				
				// Default settings
				$xmlNew .= '    <settings>'."\n".
							'      <setting key="nav_filter"><![CDATA[default]]></setting>'."\n".
							'      <setting key="list_view"><![CDATA[collapse]]></setting>'."\n".
							'      <setting key="list_nb_by_page"><![CDATA[20]]></setting>'."\n".
							'      <setting key="add_callback"><![CDATA[list]]></setting>'."\n".
							'      <setting key="edit_callback"><![CDATA[list]]></setting>'."\n".
							'      <setting key="export_format"><![CDATA[excel]]></setting>'."\n".
							'      <setting key="export_all_column"><![CDATA[true]]></setting>'."\n".
							'      <setting key="export_all_table"><![CDATA[true]]></setting>'."\n".
							'      <setting key="export_display_legend"><![CDATA[true]]></setting>'."\n".
							'      <setting key="quick_edit"><![CDATA[disabled]]></setting>'."\n".
							'      <setting key="dashboard_ga"><![CDATA[visible]]></setting>'."\n".
							'      <setting key="dashboard_metric"><![CDATA[visible]]></setting>'."\n".
							'      <setting key="dashboard_monitoring"><![CDATA[visible]]></setting>'."\n".
							'      <setting key="dashboard_graph"><![CDATA[visible]]></setting>'."\n".
							'      <setting key="dashboard_email"><![CDATA[visible]]></setting>'."\n".
							'      <setting key="color"><![CDATA['.((empty($color)) ? "pink" : $color).']]></setting>'."\n".
							'    </settings>'."\n";
				foreach($autoActions as $actionName)
				{
					$aid = $this->_generic->getControllersXML()->getTag("//controllers/controller[@isBo='true']/scontrollers/scontroller[@name='".$actionName."']/@id");
					$xmlNew .= '    <action id="'.$aid.'" role="custom" entity="" />'."\n";
				}
				foreach($params as $key => $value)
				{
					if (SLS_String::startsWith($key,"bo_action"))
					{
						$xmlNew .= '    <action id="'.$value.'" role="'.SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($key,"bo_action_"),"_").'" entity="'.((SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($key,"bo_action_"),"_") == "custom") ? "" : SLS_String::substrAfterFirstDelimiter(SLS_String::substrAfterFirstDelimiter($key,"bo_action_"),"_")).'" />'."\n";
					}
				}
				
				$xmlNew .= '  </entry>';				
				$xmlRights->appendXMLNode("//sls_configs",$xmlNew);
				$xmlRights->saveXML($this->_generic->getPathConfig("configSls")."/rights.xml",$xmlRights->getXML());
				$this->_generic->redirect("Manage/Rights");				
			}
			else
			{
				$xml->startTag("errors");
				foreach($errors as $error)
					$xml->addFullTag("error",$error,true);
				$xml->endTag("errors");
			}
		}
		
		$xml->addFullTag("complexity_pwd_lc",$complexity_pwd_lc,true);
		$xml->addFullTag("complexity_pwd_uc",$complexity_pwd_uc,true);
		$xml->addFullTag("complexity_pwd_digit",$complexity_pwd_digit,true);
		$xml->addFullTag("complexity_pwd_special_char",$complexity_pwd_special_char,true);
		$xml->addFullTag("complexity_pwd_min_char",$complexity_pwd_min_char,true);
		$xml->addFullTag("complexity_pwd_min_char_nb",$complexity_pwd_min_char_nb,true);
		$xml->addFullTag("reset_pwd",$reset_pwd,true);
		$xml->addFullTag("renew_pwd",$renew_pwd,true);
		$xml->addFullTag("renew_pwd_nb",$renew_pwd_nb,true);
		$xml->addFullTag("renew_pwd_unite",$renew_pwd_unite,true);
		$xml->addFullTag("renew_pwd_log",$renew_pwd_log,true);
		$xml->addFullTag("renew_pwd_log_nb",$renew_pwd_log_nb,true);
		$xml->addFullTag("enabled",$enabled,true);
		$xml->addFullTag("color",(empty($color)) ? "pink" : $color,true);
		$colors = $xmlColors->getTagsAttributes("//sls_configs/template",array("name","hexa"));
		$xml->startTag("colors");
		for($i=0 ; $i<$count=count($colors) ; $i++)
			$xml->addFullTag("color",$colors[$i]["attributes"][0]["value"],true,array("hexa" => $colors[$i]["attributes"][1]["value"]));
		$xml->endTag("colors");
		
		$xml->addFullTag("url_generate_bo",$this->_generic->getFullPath("SLS_Bo","GenerateBo"),true);
		
		$this->saveXML($xml);
	}
	public function action()
	{
		// Objects
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);		
		$errors = array();
		$successes = array();
		$js = false;
		$css = false;
		$totalOldSize = 0;
		$totalNewSize = 0;
		$totalRatio = 0;
		$files = array("js" 	=> array(),
					   "css" 	=> array());
		
		# Step 1: extension choice
		if ($this->_http->getParam("reload_type") == "true")
		{
			switch($this->_http->getParam("type"))
			{
				case "both":	$js = true;		$css = true;	break;
				case "js":		$js = true; 	$css = false;	break;
				case "css":		$js = false;	$css = true;	break;
			}			
			
			# Fetching files
			if ($js)
			{
				$files["js"] = $this->recursiveList($files["js"],$this->_generic->getPathConfig("jsStatics"),".js");
				$files["js"] = $this->recursiveList($files["js"],$this->_generic->getPathConfig("jsDyn"),".js");
			}
			if ($css)
			{
				$files["css"] = $this->recursiveList($files["css"],$this->_generic->getPathConfig("css"),".css");
			}
			
			$xml->startTag("files");
			foreach($files as $type => $list)
			{
				$xml->startTag($type);
				foreach($list as $file)
					$xml->addFullTag("file",$file,true);
				$xml->endTag($type);
			}
			$xml->endTag("files");
			# /Fetching files
		}
		# /Step 1: extension choice
		
		# Step 2: files choice
		if ($this->_http->getParam("reload_files") == "true")
		{
			$compress = $this->_http->getParam("compress");
			$params = $this->_http->getParams();
			
			# Compress
			if ($compress == "compress")
			{
				foreach($params as $param => $file)
				{
					if (SLS_String::startsWith($param,"file_compress_"))
					{
						include_once 'Sls/Plugins/CSSmin.php';
						include_once 'Sls/Plugins/JSMinPlus.php';
						$cssMin = new CSSmin();
						$extension = (SLS_String::endsWith($file,"js")) ? "js" : "css";
						
						try 
						{
							if ($extension == "css")
								$compressed = $cssMin->run(file_get_contents($file));
							else
								$compressed = JSMinPlus::minify(file_get_contents($file));
							
							// Rename old file to uncompressed and replace old file by compressed file
							if (!file_exists($file.".uncompressed"))
							{
								copy($file,$file.".uncompressed");
								$oldSize = filesize($file.".uncompressed");
								$totalOldSize += $oldSize;
								file_put_contents($file,$compressed);
								$newSize = filesize($file);
								$totalNewSize += $newSize;
								array_push($successes,array("file"		=> $file,
															"old_size"	=> $oldSize,
														  	"new_size"	=> $newSize,
														  	"ratio"		=> ($oldSize > 0 && $newSize > 0) ? 100 - round($newSize*100/$oldSize,2) : 0));
							}
							else
							{
								$oldSize = filesize($file);
								$totalOldSize += $oldSize;
								$newSize = filesize($file);
								$totalNewSize += $newSize;
								array_push($successes,array("file"		=> $file,
															"old_size"	=> $oldSize,
														  	"new_size"	=> $newSize,
														  	"ratio"		=> ($oldSize > 0 && $newSize > 0) ? 100 - round($newSize*100/$oldSize,2) : 0));
							}							
							
						}
						catch (Exception $e)
						{
							array_push($errors,$file);
						}
					}
				}
			}
			# /Compress
			
			# Uncompress
			else
			{
				foreach($params as $param => $file)
				{
					if (SLS_String::startsWith($param,"file_compress_"))
					{
						$extension = (SLS_String::endsWith($file,"js")) ? "js" : "css";
						
						if (!file_exists($file.".uncompressed"))
							array_push($errors,$file.".uncompressed");
						else
						{
							$oldSize = filesize($file);
							$totalOldSize += $oldSize;														
							$newSize = filesize($file.".uncompressed");
							$totalNewSize += $newSize;
							@unlink($file);
							rename($file.".uncompressed",$file);
							array_push($successes,array("file"		=> $file,
														"old_size"	=> $oldSize,
													  	"new_size"	=> $newSize,
													  	"ratio"		=> ($oldSize > 0 && $newSize > 0) ? 100 - round($newSize*100/$oldSize,2) : 0));	
						}
					}
				}
			}
			# /Uncompress
			
			# Successes files
			$xml->startTag("successes");
			foreach($successes as $success)
			{			
				$xml->startTag("success");
					foreach($success as $key => $value)
						$xml->addFullTag($key,$value,true);
				$xml->endTag("success");
				
				$xml->startTag("total");
					$xml->addFullTag("old_size",$totalOldSize,true);
					$xml->addFullTag("new_size",$totalNewSize,true);
					$xml->addFullTag("ratio", ($totalOldSize > 0 && $totalNewSize > 0) ? 100 - round($totalNewSize*100/$totalOldSize,2) : 0,true);
				$xml->endTag("total");
			}
			$xml->endTag("successes");
			# /Successes files
			
			# Errors files
			$xml->startTag("errors");
			foreach($errors as $error)
				$xml->addFullTag("error",$error,true);
			$xml->endTag("errors");
			# /Errors files
			
			// Action wanted ('compress'||'uncompress')
			$xml->addFullTag("compress",$compress,true);
		}
		# /Step 2: files choice
		
		$xml->addFullTag("current_step",($this->_http->getParam("reload_type") == "" && $this->_http->getParam("reload_files") == "") ? "0" : (($this->_http->getParam("reload_files") == "true") ? "2" : "1"),true);
		$this->saveXML($xml);
	}
	public function action()
	{
		$user 	= $this->hasAuthorative();
		$xml 	= $this->getXML();
		$xml 	= $this->makeMenu($xml);
		$langs 	= array();
		$appli_langs = array();
		$handle = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."international.xml"));
		$step = 0;
		$errors = array();
		$controllerXML = $this->_generic->getControllersXML();
		$metaXML = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."metas.xml"));
		$appli_langs = $this->_generic->getObjectLang()->getSiteLangs();
		$defaultLang = $this->_generic->getObjectLang()->getDefaultLang();
		
		// If lang have been choose
		if ($this->_http->getParam("step") == "1")
		{
			$lang1 = SLS_String::trimSlashesFromString($this->_http->getParam("lang"));
			$lang  = array_shift($handle->getTags("//sls_configs/sls_country/sls_country_langs/sls_country_lang[node()='".$lang1."']/@iso"));			
			
			if (!in_array($lang,$appli_langs))
			{
				$step = 2;
				$xml->addFullTag("step","2",true);
				$xml->addFullTag("lang_to_add",$lang,true);
			}
			else
			{
				$xml->addFullTag("lang_selected",$lang1,true);
				$xml->startTag("errors");
				$xml->addFullTag("error","This lang already exist in your application",true);
				$xml->endTag("errors");
			}		
		}
		if ($this->_http->getParam("step") == "2" || $step == 2)
		{			
			$lang = (empty($lang)) ? $this->_http->getParam("lang_to_add") : $lang;
			$xml->addFullTag("step","2",true);
			$xml->addFullTag("lang_to_add",$lang,true);
			
			$generics = array(	"MONDAY" 							=> "",
								"TUESDAY" 							=> "",
								"WEDNESDAY" 						=> "",
								"THURSDAY" 							=> "",
								"FRIDAY" 							=> "",
								"SATURDAY" 							=> "",
								"SUNDAY" 							=> "",
								"JANUARY" 							=> "",
								"FEBRUARY" 							=> "",
								"MARCH" 							=> "",
								"APRIL" 							=> "",
								"MAY" 								=> "",
								"JUNE" 								=> "",
								"JULY" 								=> "",
								"AUGUST" 							=> "",
								"SEPTEMBER" 						=> "",
								"OCTOBER" 							=> "",
								"NOVEMBER" 							=> "",
								"DECEMBER" 							=> "",
								"DATE_PATTERN_TIME" 				=> "",
								"DATE_PATTERN_FULL_TIME" 			=> "",
								"DATE_PATTERN_DATE" 				=> "",
								"DATE_PATTERN_MONTH_LITTERAL" 		=> "",
								"DATE_PATTERN_FULL_LITTERAL" 		=> "",
								"DATE_PATTERN_FULL_LITTERAL_TIME" 	=> "",
								"DATE_PATTERN_MONTH_LITTERAL_TIME" 	=> "",
								"DATE_DIFF_Y"						=> "",
								"DATE_DIFF_M"						=> "",
								"DATE_DIFF_W"						=> "",
								"DATE_DIFF_D"						=> "",
								"DATE_DIFF_H"						=> "",
								"DATE_DIFF_I"						=> "",
								"DATE_DIFF_S"						=> "",
								"E_CONTENT" 						=> "",
								"E_EMPTY" 							=> "",
								"E_KEY" 							=> "",
								"E_COMPLEXITY" 						=> "",
								"E_LENGTH" 							=> "",
								"E_NULL" 							=> "",
								"E_UNIQUE" 							=> "",
								"E_TYPE" 							=> "",
								"E_SIZE" 							=> "",
								"E_EXIST" 							=> "",
								"E_WRITE" 							=> "",
								"E_LOGGED" 							=> "",
								"E_AUTHORIZED" 						=> ""
							);									
			// Try to recover generic langs from Deployement
			if (file_exists($this->_generic->getPathConfig("installDeployement")."Langs/Generics/generic.".$lang.".lang.php"))
				include($this->_generic->getPathConfig("installDeployement")."Langs/Generics/generic.".$lang.".lang.php");			
			// Set the default value by english or current lang if has been found in Deployement
			foreach($generics as $key => $value)			
				$generics[$key] = SLS_String::trimSlashesFromString($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_'.$key]);
			
			$controllers = array();
				
			// Recover all controllers
			$controllersA = $controllerXML->getTags("//controllers/controller[@side='user']/@name");
			foreach($controllersA as $controller)
			{
				$id = array_shift($controllerXML->getTags("//controllers/controller[@name='".$controller."']/@id"));
				
				$values = array();
				foreach($appli_langs as $appli_lang)				
					$values[$appli_lang] = array_shift($controllerXML->getTags("//controllers/controller[@name='".$controller."']/controllerLangs/controllerLang[@lang='".$appli_lang."']"));					
				$values[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam($id."_".$lang));
				
				$result = array("id" => $id, "key" => $controller, "values" => $values, "actions" => array());
				array_push($controllers,$result);
			}
			
			// Foreach controllers, recover all actions
			for($i=0 ; $i<$count=count($controllers) ; $i++)
			{
				$controller = $controllers[$i]["key"];
				$actions = $controllerXML->getTags("//controllers/controller[@name='".$controller."']/scontrollers/scontroller/@name");
				$actionsA = array();
				
				foreach($actions as $action)
				{
					$id = array_shift($controllerXML->getTags("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."']/@id"));
					
					$values = array();
					foreach($appli_langs as $appli_lang)				
						$values[$appli_lang] = array_shift($controllerXML->getTags("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."']/scontrollerLangs/scontrollerLang[@lang='".$appli_lang."']"));
					$values[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam($id."_".$lang));
					
					$metas = array("title" => array(), "description" => array(), "keywords" => array());
					$titles = array();
					$descriptions = array();
					$keywords = array();
					foreach($appli_langs as $appli_lang)
					{	
						$titles[$appli_lang] = array_shift($metaXML->getTags("//sls_configs/action[@id='".$id."']/title[@lang='".$appli_lang."']"));						
						$descriptions[$appli_lang] = array_shift($metaXML->getTags("//sls_configs/action[@id='".$id."']/description[@lang='".$appli_lang."']"));						
						$keywords[$appli_lang] = array_shift($metaXML->getTags("//sls_configs/action[@id='".$id."']/keywords[@lang='".$appli_lang."']"));										
					}
					$titles[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam("meta_title-".$id."_".$lang));
					$descriptions[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam("meta_description-".$id."_".$lang));
					$keywords[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam("meta_keywords-".$id."_".$lang));
					$metas["title"] = $titles;
					$metas["description"] = $descriptions;
					$metas["keywords"] = $keywords;
					
					$result = array("id" => $id,"key" => $action, "values" => $values, "metas" => $metas);
					array_push($actionsA,$result);
				}
				$controllers[$i]["actions"] = $actionsA;
			}
			
			// If informations have been sent, check if it's good
			if ($this->_http->getParam("reload") == "true")
			{
				$mods = array();
				$smods = array();
				
				// Get all controllers
				foreach($this->_http->getParams() as $key => $value)
				{
					// Controllers case
					if (SLS_String::startsWith($key,"c_"))
					{
						$id = SLS_String::substrBeforeLastDelimiter($key,"_".$lang);
						$mod = array_shift($controllerXML->getTags("//controllers/controller[@id='".$id."']/@name"));
						$mods[$id] = SLS_String::stringToUrl(SLS_String::trimSlashesFromString($value),"",false);						
						if (empty($mods[$id]))
							array_push($errors,"You have to fill the rewrite of the controller '".$mod."'.");
						$modsExisted = $controllerXML->getTags("//controllers/controller/controllerLangs/controllerLang");
						if (in_array($mods[$id],$modsExisted))
							array_push($errors,"The name for rewrite of the controller '".$mod."' is already used, please choose another one.");
					}
					// Actions case
					else if (SLS_String::startsWith($key,"a_"))
					{
						$id = SLS_String::substrBeforeLastDelimiter($key,"_".$lang);
						$smod = array_shift($controllerXML->getTags("//controllers/controller/scontrollers/scontroller[@id='".$id."']/@name"));
						$mod = array_shift($controllerXML->getTags("//controllers/controller[scontrollers/scontroller[@id='".$id."']]/@name"));
						$idC = array_shift($controllerXML->getTags("//controllers/controller[scontrollers/scontroller[@id='".$id."']]/@id"));
						$smods[$id] = SLS_String::stringToUrl(SLS_String::trimSlashesFromString($value),"",false);						
						if (empty($smods[$id]))
							array_push($errors,"You have to fill the rewrite of the action '".$smod."' (controller '".$mod."').");
						$smodsExisted = $controllerXML->getTags("//controllers/controller[@id='".$idC."']/scontrollers/scontroller/scontrollerLangs/scontrollerLang[@lang='".$lang."']");
						if (in_array($smods[$id],$smodsExisted))
							array_push($errors,"The name for rewrite of the action '".$smod."' (controller '".$mod."') is already used by another action of the same controller, please choose another one.");
					}
					// Generics case
					else if (SLS_String::startsWith($key,"generic_"))
					{
						$label = SLS_String::substrAfterFirstDelimiter($key,"generic_");
						if (empty($value))
							array_push($errors,"You have to fill the content of the variable '".$label."'");
						$generics[$label] = strtolower(SLS_String::trimSlashesFromString($value));
					}
				}
				
				// If all cool
				if (empty($errors))
				{
					// controllers.xml
					foreach($mods as $key => $value)
					{
						$str = '<controllerLang lang="'.$lang.'"><![CDATA['.$value.']]></controllerLang>';
						$controllerXML->appendXMLNode("//controllers/controller[@id='".$key."']/controllerLangs",$str);
					}
					foreach($smods as $key => $value)
					{
						$str = '<scontrollerLang lang="'.$lang.'"><![CDATA['.$value.']]></scontrollerLang>';
						$controllerXML->appendXMLNode("//controllers/controller/scontrollers/scontroller[@id='".$key."']/scontrollerLangs",$str);
						
						// metas.xml
						$title = SLS_String::trimSlashesFromString($this->_http->getParam("meta_title-".$key."_".$lang));
						if (empty($title))
							$str = '<title lang="'.$lang.'"/>';
						else 
							$str = '<title lang="'.$lang.'"><![CDATA['.$title.']]></title>';
						$metaXML->appendXMLNode("//sls_configs/action[@id='".$key."']",$str);
						$description = SLS_String::trimSlashesFromString($this->_http->getParam("meta_description-".$key."_".$lang));
						if (empty($description))
							$str = '<description lang="'.$lang.'"/>';
						else 
							$str = '<description lang="'.$lang.'"><![CDATA['.$description.']]></description>';
						$metaXML->appendXMLNode("//sls_configs/action[@id='".$key."']",$str);
						$keyword = SLS_String::trimSlashesFromString($this->_http->getParam("meta_keywords-".$key."_".$lang));
						if (empty($keyword))
							$str = '<keywords lang="'.$lang.'"/>';
						else 
							$str = '<keywords lang="'.$lang.'"><![CDATA['.$keyword.']]></keywords>';
						$metaXML->appendXMLNode("//sls_configs/action[@id='".$key."']",$str);
						// /metas.xml
					}
					$controllerXML->saveXML($this->_generic->getPathConfig("configSecure")."controllers.xml");
					$metaXML->saveXML($this->_generic->getPathConfig("configSls")."metas.xml");
					// /controllers.xml
					
					// site.xml
					$siteXML = $this->_generic->getSiteXML();
					$str = '<name isSecure="false" js="false" active="false"><![CDATA['.$lang.']]></name>';
					$siteXML->appendXMLNode("//configs/langs",$str);
					$siteXML->saveXML($this->_generic->getPathConfig("configSecure")."site.xml");
					// /site.xml
					
					// generic.iso.lang.php
					$fileContent = '<?php'."\n".
								   '/**'."\n".
								   ' * Generic Sls Vars'."\n".
								   ' */'."\n";
					foreach($generics as $key => $value)					
						$fileContent .= '$GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'JS\'][\'SLS_'.$key.'\'] = "'.str_replace('"','\"',$value).'";'."\n";
					$fileContent .= '?>';
					file_put_contents($this->_generic->getPathConfig("coreGenericLangs")."generic.".$lang.".lang.php",$fileContent);
					// /generic.iso.lang.php
					
					// site.iso.lang.php
					$fileContent =  '<?php'."\n".
									'/**'."\n".
									' * SillySmart Translations'."\n".
									' * Language : '.array_shift($handle->getTags("//sls_configs/sls_country/sls_country_langs/sls_country_lang[node()='".$lang."']/@iso")).' ('.strtoupper($lang).')'."\n".
									' */'."\n\n".
									'?>';
					file_put_contents($this->_generic->getPathConfig("genericLangs")."site.".$lang.".lang.php",str_replace(array("Translations in '".strtoupper($defaultLang)."'","site.".$defaultLang.".lang.php","sentence in ".strtoupper($defaultLang)),array("Translations in '".strtoupper($lang)."'","site.".$lang.".lang.php","sentence in ".strtoupper($lang)),file_get_contents($this->_generic->getPathConfig("genericLangs")."site.".$defaultLang.".lang.php")));
					// /site.iso.lang.php
										
					// Actions langs files
					$directories = array();
					foreach($mods as $key => $value)					
						array_push($directories,array_shift($controllerXML->getTags("//controllers/controller[@id='".$key."']/@name")));
					$this->copyActionsLang($directories,$lang);
					// /Actions langs files
					
					// User_Bo langs
					$controllerBo = $controllerXML->getTag("//controllers/controller[@side='user' and @isBo='true']/@name");
					if (!empty($controllerBo))
					{
						if (file_exists($this->_generic->getPathConfig("installDeployement")."Langs/Actions/{{USER_BO}}/__{{USER_BO}}.".$lang.".lang.php"))
							$langContent = str_replace(array("{{USER_BO}}"),array($controllerBo),file_get_contents($this->_generic->getPathConfig("installDeployement")."Langs/Actions/{{USER_BO}}/__{{USER_BO}}.".$lang.".lang.php"));
						else
							$langContent = str_replace(array("{{USER_BO}}"),array($controllerBo),file_get_contents($this->_generic->getPathConfig("installDeployement")."Langs/Actions/{{USER_BO}}/__{{USER_BO}}.en.lang.php"));
						if (!empty($langContent))
							file_put_contents($this->_generic->getPathConfig("actionLangs").$controllerBo."/__".$controllerBo.".".$lang.".lang.php",$langContent);
					}
					
					// MySQL multilanguage tables
					$handle = opendir($this->_generic->getPathConfig("models"));
					
					// Disable explain
					SLS_Sql::getInstance()->_explain = false;
					
					// Foreach models 
					while (false !== ($file = readdir($handle))) 
					{
						if (!is_dir($this->_generic->getPathConfig("models")."/".$file) && substr($file, 0, 1) != ".") 
						{
							$fileExploded = explode(".",$file);
							if (is_array($fileExploded) && count($fileExploded) == 4)
							{ 
								$db = $fileExploded[0];
								$class = $fileExploded[1];
								$className = $db."_".$class;
								$this->_generic->useModel($class,$db,"user");
								$object = new $className();								
								if ($object->isMultilanguage())
								{
									$results = $object->searchModels($object->getTable(),array(),array(0=>array("column"=>"pk_lang","value"=>$defaultLang,"mode"=>"equal")));
									
									for($i=0 ; $i<$count=count($results) ; $i++)
									{
										$object = new $className();
										$object->setModelLanguage($lang);
										foreach($results[$i] as $column => $col_value)
										{
											if ($column != "pk_lang" && $column != $object->getPrimaryKey())
											{													
												$object->__set($column,$col_value);
											}
										}
										try {
											$object->create($results[$i]->{$object->getPrimaryKey()});
										}
										catch (Exception $e){}
									}									
								}								
							}
						}
					}
					// /MySQL multilanguage tables
					
					// Redirect
					$controllers = $this->_generic->getTranslatedController("SLS_Bo","Langs");
					$this->_generic->redirect($controllers["controller"]."/".$controllers["scontroller"].".sls");
				}
				// Else, form errors
				else
				{
					$xml->startTag("errors");
					foreach($errors as $error)
						$xml->addFullTag("error",$error,true);
					$xml->endTag("errors");
				}				
			}
			
			$xml->startTag("generic_langs");
			foreach($generics as $key => $value)
			{
				$xml->startTag("generic_lang");	
				$xml->addFullTag("key",$key,true);
				$xml->addFullTag("value",$value,true);
				$xml->endTag("generic_lang");
			}
			$xml->endTag("generic_langs");
						
			$xml->startTag("controllers");
			for($i=0 ; $i<$count=count($controllers) ; $i++)
			{
				$xml->startTag("controller");
				$xml->addFullTag("id",$controllers[$i]["id"],true);
				$xml->addFullTag("key",$controllers[$i]["key"],true);
				$xml->startTag("values");
				foreach($controllers[$i]["values"] as $key2 => $value2)
				{
					$xml->startTag("value");
					$xml->addFullTag("key",$key2,true);
					$xml->addFullTag("value",$value2,true);
					$xml->endTag("value");
				}
				$xml->endTag("values");
				$xml->startTag("actions");
				for($j=0 ; $j<$count2=count($controllers[$i]["actions"]) ; $j++)
				{
					$action = $controllers[$i]["actions"];
					$xml->startTag("action");
					$xml->addFullTag("id",$action[$j]["id"],true);
					$xml->addFullTag("key",$action[$j]["key"],true);
					$xml->startTag("values");
					foreach($action[$j]["values"] as $key3 => $value3)
					{
						$xml->startTag("value");
						$xml->addFullTag("key",$key3,true);
						$xml->addFullTag("value",$value3,true);
						$xml->endTag("value");
					}
					$xml->endTag("values");
					$xml->startTag("metas");
					foreach($action[$j]["metas"] as $key4 => $value4)
					{
						$xml->startTag("meta");
						$xml->addFullTag("key",$key4,true);
						$xml->startTag("values");
						foreach($value4 as $key5 => $value5)
						{
							$xml->startTag("value");
							$xml->addFullTag("key",$key5,true);
							$xml->addFullTag("value",$value5,true);
							$xml->endTag("value");
						}
						$xml->endTag("values");
						$xml->endTag("meta");
					}
					$xml->endTag("metas");
					$xml->endTag("action");
				}
				$xml->endTag("actions");
				$xml->endTag("controller");
			}
			$xml->endTag("controllers");
		}
		
		$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");
		
		$this->saveXML($xml);
	}	
	/**
	 * Action Home
	 *
	 */
	public function action() 
	{
		$this->secureURL();
		
		$this->_generic->registerLink('GlobalSettings', 'SLS_Init', 'GlobalSettings');
		$handle = file_get_contents($this->_generic->getPathConfig("configSls").'charset.xml');
		$handle2 = file_get_contents($this->_generic->getPathConfig("configSls").'timezone.xml');
		$xml = $this->getXML();
		$xml->addFullTag("charsets", SLS_String::substrBeforeLastDelimiter(SLS_String::substrAfterFirstDelimiter($handle, "<sls_configs>"), "</sls_configs>"), false);
		$xml->addFullTag("timezones", SLS_String::substrBeforeLastDelimiter(SLS_String::substrAfterFirstDelimiter($handle2, "<sls_configs>"), "</sls_configs>"), false);
				
		$errors = array();
		
		$domain 		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_domain'));
		$protocol 		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_protocol'));
		$project 		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_project'));
		$description 	= SLS_String::trimSlashesFromString($this->_http->getParam('settings_description'));
		$keywords 		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_keywords'));
		$author		 	= SLS_String::trimSlashesFromString($this->_http->getParam('settings_author'));
		$copyright	 	= SLS_String::trimSlashesFromString($this->_http->getParam('settings_copyright'));
		$extension 		= ($this->_http->getParam('settings_extension') == "") ? "sls" : SLS_String::trimSlashesFromString($this->_http->getParam('settings_extension'));
		$charset 		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_charset'));
		$doctype 		= SLS_String::trimSlashesFromString($this->_http->getParam('settings_doctype'));
		$bo 			= SLS_String::trimSlashesFromString($this->_http->getParam('settings_bo'));
		$timezone_area	= SLS_String::trimSlashesFromString($this->_http->getParam('settings_timezone_area'));
		$timezone_city	= SLS_String::trimSlashesFromString($this->_http->getParam('settings_timezone_area_'.$timezone_area));
		
		$xmlTmp = new SLS_XMLToolbox($handle);		
		$allowedCharsets = $xmlTmp->getTags("//sls_configs/charset/code");
		
		if ($this->_http->getParam('globalSettings_reload') == "true")
		{	
			if (empty($domain))
				array_push($errors,"You must fill your main domain name");
			if ($protocol != 'http' && $protocol != 'https')
				array_push($errors,"You must choose a correct Protocol");
			if (empty($project))
				array_push($errors,"You must fill your project name");
			if (empty($description))
				array_push($errors,"You must fill your project description");
			if (empty($author))
				$author = $project;
			if (empty($copyright))
				$copyright = $domain;
			if (empty($extension))
				array_push($errors,"You must fill your default extension");
			if (empty($bo))
				array_push($errors,"You must fill your access to your SillySmart's Back-Office");
			if (!in_array($charset,$allowedCharsets))
				array_push($errors,"You must choose a valid charset");
			if (empty($doctype))
				array_push($errors,"You must choose your default doctype");
			if (empty($timezone_area) || empty($timezone_city))
				array_push($errors,"You must choose your default timezone");
							
			if (empty($errors))
			{
				$key = substr(md5($domain).sha1($project).uniqid(microtime()),mt_rand(5,10),mt_rand(20,32));
				$coreXml = $this->_generic->getSiteXML();
				$coreXml->setTag('//configs/domainName', "<domain alias='__default' default='1' js='true' isSecure='false' lang=''><![CDATA[".$domain."]]></domain>", false);
				$coreXml->setTag('//configs/protocol',$protocol);
				$coreXml->setTag('//configs/defaultExtension',$extension);
				$coreXml->setTag('//configs/projectName',$project);
				$coreXml->setTag('//configs/versionName',date("Ymd")."-dev");
				$coreXml->setTag('//configs/metaDescription',$description);
				$coreXml->setTag('//configs/metaKeywords',$keywords);
				$coreXml->setTag('//configs/metaAuthor',$author);
				$coreXml->setTag('//configs/metaCopyright',$copyright);
				$coreXml->setTag('//configs/privateKey',$key);
				$coreXml->setTag('//configs/defaultCharset',strtoupper($charset));
				$coreXml->setTag('//configs/defaultDoctype',$doctype);
				$coreXml->setTag('//configs/defaultTimezone',$timezone_area."/".$timezone_city);
				file_put_contents($this->_generic->getPathConfig("configSecure")."site.xml", $coreXml->getXML());
				$controllersXml = $this->_generic->getControllersXML();
				$controllersXml->setTag("//controllers/controller[@name='SLS_Bo']/controllerLangs/controllerLang",$bo);
				
				$uniqs = array();
				$metas = array();
				
				// Generate Controllers IDS
				$slsControllers = $controllersXml->getTags("//controllers/controller[@side='sls']/@name");	
				$slsLangs = $controllersXml->getTags("//controllers/controller[@side='sls'][1]/scontrollers/scontroller[1]/scontrollerLangs/scontrollerLang/@lang");
				foreach ($slsControllers as $slsController)
				{
					// Take a random id and set it
					$uniq = uniqid("c_");
					while(in_array($uniq, $uniqs))					
						$uniq = uniqid("c_");					
					array_push($uniqs, $uniq);
					$controllersXml->setTagAttributes("//controllers/controller[@name='".$slsController."' and @side='sls']", array("id"=>$uniq));
					
					// Generate Actions IDS
					$slsActions = $controllersXml->getTags("//controllers/controller[@side='sls' and @name='".$slsController."']/scontrollers/scontroller/@name");					
					foreach ($slsActions as $slsAction)
					{
						// Take a random id and set it
						$uniq = uniqid("a_");
						while(in_array($uniq, $uniqs))						
							$uniq = uniqid("a_");						
						array_push($uniqs, $uniq);
						$controllersXml->setTagAttributes("//controllers/controller[@name='".$slsController."' and @side='sls']/scontrollers/scontroller[@name='".$slsAction."']", array("id"=>$uniq));
						
						// Get title attribute, save it into array and delete this attribute
						$tmpArray = array();
						foreach ($slsLangs as $lang)
						{
							$tmpArray[$lang] = array_shift($controllersXml->getTags("//controllers/controller[@name='".$slsController."' and @side='sls']/scontrollers/scontroller[@name='".$slsAction."']/scontrollerLangs/scontrollerLang[@lang='".$lang."']/@title"));
							$controllersXml->deleteTagAttribute("//controllers/controller[@name='".$slsController."' and @side='sls']/scontrollers/scontroller[@name='".$slsAction."']/scontrollerLangs/scontrollerLang[@lang='".$lang."']","title");
						}
						$metas[$uniq] = $tmpArray;
					}	
				}
				
				// Update metas.xml
				$metaXml = '';
				foreach($metas as $key => $value)
				{
					$metaXml .= '<action id="'.$key.'">';
					foreach ($value as $lang => $title)
						$metaXml .=	'<title lang="'.$lang.'"><![CDATA['.$title.']]></title>';
					$metaXml .=	'<robots><![CDATA[noindex, nofollow]]></robots>';
					$metaXml .= '</action>';
				}
				$metaO = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."metas.xml"));
				$metaO->appendXML("//sls_configs",$metaXml);
				$metaO->saveXML($this->_generic->getPathConfig("configSls")."metas.xml");
				
				// Overwrite template __default
				$this->createXslTemplate("__default",$doctype);
				
				file_put_contents($this->_generic->getPathConfig("configSecure")."controllers.xml", $controllersXml->getXML());
				$this->setInstallationStep(array(0=>"SLS_Init",1=>"Initialization"), array(0=>"International",1=>"International"));
				return $this->_generic->dispatch("SLS_Init", "International");
			}
			else
			{
				$xml->startTag("errors");
				foreach ($errors as $error)
					$xml->addFullTag("error", $error, true);
				$xml->endTag("errors");
				
				$xml->addFullTag("domain",$domain,true);
				$xml->addFullTag("protocol",$protocol,true);
				$xml->addFullTag("project",$project,true);
				$xml->addFullTag("description",$description,true);
				$xml->addFullTag("keywords",$keywords,true);
				$xml->addFullTag("author",$author,true);
				$xml->addFullTag("copyright",$copyright,true);
				$xml->addFullTag("extension",$extension,true);
				$xml->addFullTag("charset",$charset,true);
				$xml->addFullTag("doctype",$doctype,true);
				$xml->addFullTag("bo",$bo,true);
				$xml->startTag("timezone");
					$xml->addFullTag("area",$timezone_area,true);
					$xml->addFullTag("city",$timezone_city,true);
				$xml->endTag("timezone");				
			}
		}
		else
		{
			$timezone = date_default_timezone_get();
			$xml->addFullTag("domain",$_SERVER['HTTP_HOST'].(($_SERVER['SCRIPT_NAME'] != "/index.php") ? SLS_String::substrBeforeFirstDelimiter($_SERVER['SCRIPT_NAME'],"/index.php") : ""),true);
			$xml->addFullTag("protocol",(SLS_String::startsWith($_SERVER['SERVER_PROTOCOL'],'HTTPS')) ? 'https' : 'http',true);
			$xml->addFullTag("author","SillySmart",true);
			$xml->addFullTag("extension","sls",true);
			$xml->startTag("timezone");
				$xml->addFullTag("area",(empty($timezone) || !SLS_String::contains($timezone,'/')) ? 'Europe' : SLS_String::substrBeforeFirstDelimiter($timezone,'/'),true);
				$xml->addFullTag("city",(empty($timezone) || !SLS_String::contains($timezone,'/')) ? 'Paris' : SLS_String::substrAfterFirstDelimiter($timezone,'/'),true);
			$xml->endTag("timezone");
			$xml->addFullTag("bo","Manage",true);
		}
		
		$this->saveXML($xml);
	}
	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);
	}
	public function action()
	{
		$user 	= $this->hasAuthorative();
		$xml 	= $this->getXML();
		$xml	= $this->makeMenu($xml);
		$siteXML = $this->_generic->getSiteXML();
		
		$googleSettings = array();
		
		if ($this->_http->getParam("reload") == "true")
		{
			$googleSettings = $this->_http->getParam("ga");
			
			$siteXML->setTag("//configs/google/setting[@name='ua']",trim($googleSettings["ua"]));
			$siteXML->setTag("//configs/google/setting[@name='apiKey']",trim($googleSettings["apiKey"]));
			$siteXML->setTag("//configs/google/setting[@name='clientId']",trim($googleSettings["clientId"]));
			$siteXML->setTag("//configs/google/setting[@name='accountId']",trim($googleSettings["accountId"]));
			$siteXML->saveXML($this->_generic->getPathConfig("configSecure")."site.xml");
			$siteXML->refresh();
			
			if (!empty($googleSettings["ua"]))
			{
				$googleSettings["ua"] = (SLS_String::startsWith(trim(strtolower($googleSettings["ua"])),"ua-")) ? $googleSettings["ua"] : "UA-".$googleSettings["ua"];
				$templates = scandir($this->_generic->getPathConfig("viewsTemplates"));
				foreach($templates as $template)
				{
					if (!SLS_String::startsWith($template,"."))
					{
						$templateContent = file_get_contents($this->_generic->getPathConfig("viewsTemplates").$template);
						
						if (SLS_String::contains($templateContent,"<!-- GA loading -->") && SLS_String::contains($templateContent,"_gaq.push(['_setAccount'"))
						{
							$oldUa = trim(str_replace("'","",SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($templateContent,"_gaq.push(['_setAccount',"),"]")));
							if ($oldUa != $googleSettings["ua"])
							{
								$templateContent = str_replace("_gaq.push(['_setAccount', '".$oldUa."']);","_gaq.push(['_setAccount', '".$googleSettings["ua"]."']);",$templateContent);
								file_put_contents($this->_generic->getPathConfig("viewsTemplates").$template,$templateContent);
							}
						}
						else
						{
							$newContent = "";
							$templateLines = explode("\n",$templateContent);
							
							for($i=0 ; $i<$count=count($templateLines) ; $i++)
							{
								$line = $templateLines[$i];
								
								if (SLS_String::contains($line,"</body>"))
								{
									$newContent .= t(4)."<!-- GA loading -->"."\n".
													t(4)."<xsl:if test=\"//Statics/Sls/Configs/site/isProd = '1'\">"."\n".
														t(5)."<script type=\"text/javascript\">"."\n".
															t(6)."var _gaq = _gaq || [];"."\n".
															t(6)."_gaq.push(['_setAccount', '".$googleSettings["ua"]."']);"."\n".
															t(6)."_gaq.push(['_trackPageview']);"."\n".
															t(6)."(function() {"."\n".
																t(7)."var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;"."\n".
																t(7)."ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';"."\n".
																t(7)."var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);"."\n".
															t(6)."})();"."\n".
														t(5)."</script>"."\n".
													t(4)."</xsl:if>"."\n".
													t(4)."<!-- /GA loading -->"."\n\n";
								}
								
								$newContent .= $line."\n";
							}
							
							file_put_contents($this->_generic->getPathConfig("viewsTemplates").$template,$newContent);
						}
					}
				}
			}
			
			$xml->addFullTag("success","Your settings have been saved.",true);
		}
		else
		{
			$googleSettings["ua"] = $siteXML->getTag("//configs/google/setting[@name='ua']");
			$googleSettings["apiKey"] = $siteXML->getTag("//configs/google/setting[@name='apiKey']");
			$googleSettings["clientId"] = $siteXML->getTag("//configs/google/setting[@name='clientId']");
			$googleSettings["accountId"] = $siteXML->getTag("//configs/google/setting[@name='accountId']");
		}
		
		$xml->startTag("google");
		foreach($googleSettings as $key => $value)
			$xml->addFullTag($key,$value,true);
		$xml->endTag("google");
		
		$this->saveXML($xml);		
	}
	/**
	 * 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;
	}
	public function getEnvironments()
	{
		$environments = array();
		$filesToCheck = array("site","db","project","mail");
		if ($handle = opendir($this->_generic->getPathConfig("configSecure")))
		{
			while (false !== ($entry = readdir($handle)))
			{
				foreach($filesToCheck as $file)
				{
			        if (SLS_String::startsWith($entry,$file."_") && SLS_String::endsWith($entry,".xml"))
			        {
			        	$environment = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($entry,$file."_"),".xml");
			        	if (!in_array($environment,$environments))
			        		$environments[] = $environment;
			        }
				}
			}
		}
		return $environments;
	}
	/**
	 * Action Home
	 *
	 */
	public function action() 
	{
		$this->secureURL();
		$this->_generic->registerLink('International', 'SLS_Init', 'International');
		$errors = array();
		$giveDataStep1 = false;
		$xml = $this->getXML();
		$step = 0;
		$langs = array();
		$handle = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."international.xml"));
		$xpathLangs = $handle->getTags("//sls_configs/sls_country/sls_country_langs/sls_country_lang[@iso != '']");
		foreach ($xpathLangs as $lang)
			if (!in_array(trim($lang), $langs))
				array_push($langs, trim($lang));
		array_multisort($langs, SORT_STRING, SORT_ASC);
		$xml->startTag("langs");
		foreach ($langs as $lang)
			$xml->addFullTag("lang", $lang, true);
		$xml->endTag("langs");
				
		// If reload
		if ($this->_http->getParam('reload_international_step1') == "true")
		{
			// If one lang at least
			$listLangs = SLS_String::trimSlashesFromString($this->_http->getParam("international_langs"));			
			if (empty($listLangs))
				array_push($errors,"You must choose at least one language");
			else
			{
				$xmlIsos = "";
				
				foreach($listLangs as $listLang)
				{
					$iso = array_shift($handle->getTags("//sls_configs/sls_country/sls_country_langs/sls_country_lang[node()='".$listLang."']/@iso"));
					$xmlIsos .= '<name isSecure="false" js="false" active="true"><![CDATA['.$iso.']]></name>';
					if (is_file($this->_generic->getPathConfig("installDeployement")."Langs/Generics/generic.".$iso.".lang.php"))
						copy($this->_generic->getPathConfig("installDeployement")."Langs/Generics/generic.".$iso.".lang.php", $this->_generic->getPathConfig("coreGenericLangs")."generic.".$iso.".lang.php");
				}
				
			}
			if (empty($errors))
			{
				$step = 1;
				$coreXml = $this->_generic->getSiteXML();
				$coreXml->setTag('langs',$xmlIsos,false);
				file_put_contents($this->_generic->getPathConfig("configSecure")."site.xml", $coreXml->getXML());
				$giveDataStep1 = true;
			}
			else
			{
				$step = 0;
				$xml->startTag("errors");
				foreach ($errors as $error)
					$xml->addFullTag("error", $error, true);
				$xml->endTag("errors");
			}
		}
		// Set controllers.xml
		else if ($this->_http->getParam('reload_international_step2') == "true")
		{
			$langs = $this->_generic->getSiteXML()->getTags("//configs/langs/name");
			$listLangs = explode("-", SLS_String::trimSlashesFromString($this->_http->getParam("international_languages")));
			$params = $this->_http->getParams('post');
			
			$userValues = array();
			foreach ($langs as $lang)
				$userValues[$lang] = array();
			
			foreach ($params as $key=>$param)
				if (array_key_exists(SLS_String::substrBeforeFirstDelimiter($key, '_'), $userValues))
					$userValues[SLS_String::substrBeforeFirstDelimiter($key, '_')][SLS_String::substrAfterFirstDelimiter($key, '_')] = SLS_String::trimSlashesFromString($param);
			
			// Check errors
			$errors = array();
			$xml->startTag("InternationalMemory");
			$xml->addFullTag("default", SLS_String::trimSlashesFromString($this->_http->getParam("default_lang")), true);
			foreach ($userValues as $key=>$values) 
			{
				$mods[$key] = array();
				$smods[$key]['home'] = array();
				$smods[$key]['error'] = array();
				
				foreach ($values as $name=>$value)
				{
					$xml->startTag("row");
					$xml->addFullTag("name", $key."_".$name, true);
					$xml->addFullTag("value", SLS_String::trimSlashesFromString($value), true);
					$xml->endTag("row");
					if (substr($name, 0, 11) == "TRANSLATION")
					{
						if (empty($value))
							array_push($errors, "You must fill the translation for ".ucwords(strtolower(str_replace("_", " ", substr($name, 11))))." in ".strtoupper($key));
					}					
				}
				
				if (empty($values['home_mod']))
					array_push($errors, "You must fill a value for the URL of Main Controller in ".strtoupper($key));				
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['home_mod']),"")!=strtolower($values['home_mod']))
					array_push($errors, "You must fill a value for the URL of Main Controller without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($mods[$key], $values['home_mod']);				
				if (empty($values['home_desc']))
					array_push($errors, "You must fill a page title for your home page in ".strtoupper($key));
				if (empty($values['home_index']))
					array_push($errors, "You must fill an action value for your home page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['home_index']),"")!=strtolower($values['home_index']))
					array_push($errors, "You must fill an action value for your home page without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['home'], $values['home_index']);
				if (empty($values['error_mod']))
					array_push($errors, "You must fill a value for the URL of Error Controller in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_mod']),"")!=strtolower($values['error_mod']))
					array_push($errors, "You must fill a value for the URL of Error Controller without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($mods[$key], $values['error_mod']);
				if (empty($values['error_400_desc']))
					array_push($errors, "You must fill a page title for your 400 page in ".strtoupper($key));
				if (empty($values['error_401_desc']))
					array_push($errors, "You must fill a page title for your 401 page in ".strtoupper($key));
				if (empty($values['error_403_desc']))
					array_push($errors, "You must fill a page title for your 403 page in ".strtoupper($key));
				if (empty($values['error_404_desc']))
					array_push($errors, "You must fill a page title for your 404 page in ".strtoupper($key));
				if (empty($values['error_500_desc']))
					array_push($errors, "You must fill a page title for your 500 page in ".strtoupper($key));
				if (empty($values['error_307_desc']))
					array_push($errors, "You must fill a page title for your 307 page in ".strtoupper($key));
				if (empty($values['error_302_desc']))
					array_push($errors, "You must fill a page title for your 302 page in ".strtoupper($key));
					
				if (empty($values['error_400_url']))
					array_push($errors, "You must fill a value for the URL of your 400 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_400_url']),"")!=strtolower($values['error_400_url']))
					array_push($errors, "You must fill an action value for the URL of you 400 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_400_url']);
				if (empty($values['error_401_url']))
					array_push($errors, "You must fill a value for the URL of your 401 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_401_url']),"")!=strtolower($values['error_401_url']))
					array_push($errors, "You must fill an action value for the URL of you 401 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_401_url']);
				if (empty($values['error_403_url']))
					array_push($errors, "You must fill a value for the URL of your 403 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_403_url']),"")!=strtolower($values['error_403_url']))
					array_push($errors, "You must fill an action value for the URL of you 403 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_403_url']);
				if (empty($values['error_404_url']))
					array_push($errors, "You must fill a value for the URL of your 404 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_404_url']),"")!=strtolower($values['error_404_url']))
					array_push($errors, "You must fill an action value for the URL of you 404 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_404_url']);
				if (empty($values['error_500_url']))
					array_push($errors, "You must fill a value for the URL of your 500 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_500_url']),"")!=strtolower($values['error_500_url']))
					array_push($errors, "You must fill an action value for the URL of you 500 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_500_url']);
				if (empty($values['error_307_url']))
					array_push($errors, "You must fill a value for the URL of your 307 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_307_url']),"")!=strtolower($values['error_307_url']))
					array_push($errors, "You must fill an action value for the URL of you 307 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_307_url']);
				if (empty($values['error_302_url']))
					array_push($errors, "You must fill a value for the URL of your 302 page in ".strtoupper($key));
				else if (SLS_String::stringToUrl(SLS_String::trimSlashesFromString($values['error_302_url']),"")!=strtolower($values['error_302_url']))
					array_push($errors, "You must fill an action value for the URL of you 302 without spaces, accented characters or specials characters in ".strtoupper($key));
				else 
					array_push($smods[$key]['error'], $values['error_302_url']);
				
				$unikUrl = array();
				foreach ($smods[$key]['error'] as $smod)
					if (!in_array($smod, $unikUrl))
						array_push($unikUrl, $smod);
				
				if (count($unikUrl) != count($smods[$key]['error']))
					array_push($errors, "You cannot set the same Action name for two differents actions in the same language : ".strtoupper($key));
					
			}
			
			$xml->endTag("InternationalMemory");
			if (empty($errors))
			{
				$caIds = array();
				// Set defaut lang
				$siteXML = $this->_generic->getSiteXML();
				$siteXML->setTag("defaultLang", SLS_String::trimSlashesFromString($this->_http->getParam("default_lang")));
				$siteXML->setTagAttributes("//configs/domainName/domain[@default='1']",array("lang" => SLS_String::trimSlashesFromString($this->_http->getParam("default_lang"))));
				file_put_contents($this->_generic->getPathConfig("configSecure")."site.xml", $siteXML->getXML());
				$langs = $this->_generic->getSiteXML()->getTags("//configs/langs/name");
				
				$xmlControllers = $this->_generic->getControllersXML();
				
				// Generate the Home Controller ID and the Default Controller ID
				$homeID = $this->_generic->generateControllerId();
				array_push($caIds, $homeID);
				
				$defaultID = $this->_generic->generateControllerId();
				while (in_array($defaultID, $caIds))
					$defaultID = $this->_generic->generateControllerId();
				array_push($caIds, $defaultID);
				
				// Generate Actions IDs
				// Home/Index
				$indexID = $this->_generic->generateActionId();
				array_push($caIds, $indexID);
				
				// Default/UrlError
				$urlErrorID = $this->_generic->generateActionId();
				while (in_array($urlErrorID, $caIds))
					$urlErrorID = $this->_generic->generateActionId();
				array_push($caIds, $urlErrorID);
				
				// Default/BadRequestError
				$badRequestID = $this->_generic->generateActionId();
				while (in_array($badRequestID, $caIds))
					$badRequestID = $this->_generic->generateActionId();
				array_push($caIds, $badRequestID);
				
				// Default/AuthorizationError
				$authorizationID = $this->_generic->generateActionId();
				while (in_array($authorizationID, $caIds))
					$authorizationID = $this->_generic->generateActionId();
				array_push($caIds, $authorizationID);
				
				// Default/ForbiddenError
				$forbiddenID = $this->_generic->generateActionId();
				while (in_array($forbiddenID, $caIds))
					$forbiddenID = $this->_generic->generateActionId();
				array_push($caIds, $forbiddenID);
				
				// Default/InternalServerError	
				$serverID = $this->_generic->generateActionId();
				while (in_array($serverID, $caIds))
					$serverID = $this->_generic->generateActionId();
				array_push($caIds, $serverID);
				
				// Default/TemporaryRedirectError	
				$redirectID = $this->_generic->generateActionId();
				while (in_array($redirectID, $caIds))
					$redirectID = $this->_generic->generateActionId();
				array_push($caIds, $redirectID);
				
				// Default/MaintenanceError	
				$maintenanceID = $this->_generic->generateActionId();
				while (in_array($maintenanceID, $caIds))
					$maintenanceID = $this->_generic->generateActionId();
				array_push($caIds, $maintenanceID);
								
				$controllerUser['home']['mod'] = "<controller name=\"Home\" side=\"user\" id=\"".$homeID."\"><controllerLangs>";
				$controllerUser['home']['smod'] = "<scontrollers><scontroller name=\"Index\" needParam=\"0\" id=\"".$indexID."\" default=\"1\"><scontrollerLangs>";
				$controllerUser['default']['mod'] = "<controller name=\"Default\" side=\"user\" id=\"".$defaultID."\"><controllerLangs>";
				$controllerUser['default']['smod']['404'] = "<scontrollers><scontroller name=\"UrlError\" needParam=\"0\" id=\"".$urlErrorID."\"><scontrollerLangs>";
				$controllerUser['default']['smod']['400'] = "<scontroller name=\"BadRequestError\" needParam=\"0\" id=\"".$badRequestID."\"><scontrollerLangs>";
				$controllerUser['default']['smod']['401'] = "<scontroller name=\"AuthorizationError\" needParam=\"0\" id=\"".$authorizationID."\"><scontrollerLangs>";
				$controllerUser['default']['smod']['403'] = "<scontroller name=\"ForbiddenError\" needParam=\"0\" id=\"".$forbiddenID."\"><scontrollerLangs>";
				$controllerUser['default']['smod']['500'] = "<scontroller name=\"InternalServerError\" needParam=\"0\" id=\"".$serverID."\"><scontrollerLangs>";
				$controllerUser['default']['smod']['307'] = "<scontroller name=\"TemporaryRedirectError\" needParam=\"0\" id=\"".$redirectID."\"><scontrollerLangs>";
				$controllerUser['default']['smod']['302'] = "<scontroller name=\"MaintenanceError\" needParam=\"0\" id=\"".$maintenanceID."\"><scontrollerLangs>";
				
				$paramsPost = $this->_http->getParams('post');
				
				$handleLangs = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."international.xml"));
				$projectName = array_shift($this->_generic->getSiteXML()->getTags("projectName"));
				
				/* Create Lang files and Lang Directory
				mkdir($this->_generic->getPathConfig("actionLangs")."Home");
				mkdir($this->_generic->getPathConfig("actionLangs")."Default");	
				*/
				$metasXML = $this->_generic->getCoreXML('metas');
				// Add Empty Actions in metas
				foreach ($caIds as $aId)
				{
					$str = "<action id=\"".$aId."\"></action>";
					$metasXML->appendXMLNode("//sls_configs", $str);
				}
				
				// Foreach langs
				foreach ($langs as $lang) 
				{
					// Home controller
					$controllerUser['home']['mod'] 		.= "<controllerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_home_mod"))."]]></controllerLang>";
					$controllerUser['home']['smod'] 	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_home_index"))."]]></scontrollerLang>";
					
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_home_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_home_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_home_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$indexID."']", $strTitle);
					
					// Default controller
					$controllerUser['default']['mod'] 			.= "<controllerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_mod"))."]]></controllerLang>";
					$controllerUser['default']['smod']['404']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_404_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_404_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_404_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_404_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$urlErrorID."']", $strTitle);
					
					$controllerUser['default']['smod']['400']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_400_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_400_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_400_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_400_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$badRequestID."']", $strTitle);
					
					$controllerUser['default']['smod']['401']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_401_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_401_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_401_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_401_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$authorizationID."']", $strTitle);
					
					$controllerUser['default']['smod']['403']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_403_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_403_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_403_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_403_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$forbiddenID."']", $strTitle);
					
					$controllerUser['default']['smod']['500']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_500_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_500_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_500_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_500_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$serverID."']", $strTitle);
					
					$controllerUser['default']['smod']['307']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_307_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_307_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_307_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_307_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$redirectID."']", $strTitle);
					
					$controllerUser['default']['smod']['302']	.= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_302_url"))."]]></scontrollerLang>";
					$strTitle = "<title lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_302_desc"))."]]></title>";
					$strTitle .= "<description lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_302_description"))."]]></description>";
					$strTitle .= "<keywords lang=\"".$lang."\"><![CDATA[".SLS_String::trimSlashesFromString($this->_http->getParam($lang."_error_302_keywords"))."]]></keywords>";
					$metasXML->appendXMLNode("//sls_configs/action[@id='".$maintenanceID."']", $strTitle);
					
					// Generic langs					
					$genericFile = "<?php\n/**\n * Generic Sls Vars\n */\n";
					$length = strlen($lang."_TRANSLATION");
					foreach ($paramsPost as $key=>$value)
					{
						$value = SLS_String::trimSlashesFromString($value);
						
						if (substr($key, 0, $length) == $lang."_TRANSLATION")
						{
							$genericFile .= '$GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'JS\'][\'SLS_'.substr($key, $length+1).'\'] = "'.$value.'";';
							$genericFile .= "\n";
						}	
						
					}
					$genericFile .= "?>";
					file_put_contents($this->_generic->getPathConfig("coreGenericLangs")."generic.".$lang.".lang.php", $genericFile);
					
					// Generic lang site
					$language = array_shift($handleLangs->getTags("//sls_configs/sls_country/sls_country_langs/sls_country_lang[@iso = '".$lang."']"));
					$contentSiteLang = "<?php\n/**\n * ".$projectName." Translations\n * Language : ".ucwords($language)." (".strtoupper($lang).")\n */\n\n?>";
					file_put_contents($this->_generic->getPathConfig('genericLangs')."site.".$lang.".lang.php", $contentSiteLang);
				}
				
				// Controllers
				$controllerUser['home']['mod'] 				.= "</controllerLangs>";
				$controllerUser['home']['smod']				.= "</scontrollerLangs></scontroller></scontrollers></controller>";
				
				$controllerUser['default']['mod']			.= "</controllerLangs>";
				$controllerUser['default']['smod']['404']	.= "</scontrollerLangs></scontroller>";
				$controllerUser['default']['smod']['400']	.= "</scontrollerLangs></scontroller>";
				$controllerUser['default']['smod']['401']	.= "</scontrollerLangs></scontroller>";
				$controllerUser['default']['smod']['403']	.= "</scontrollerLangs></scontroller>";
				$controllerUser['default']['smod']['307']	.= "</scontrollerLangs></scontroller>";
				$controllerUser['default']['smod']['302']	.= "</scontrollerLangs></scontroller>";
				$controllerUser['default']['smod']['500']	.= "</scontrollerLangs></scontroller></scontrollers></controller>";
				
				// Formation du Flux Final a append
				$flux = $controllerUser['home']['mod'].$controllerUser['home']['smod'].$controllerUser['default']['mod'].$controllerUser['default']['smod']['404'].$controllerUser['default']['smod']['400'].$controllerUser['default']['smod']['401'].$controllerUser['default']['smod']['403'].$controllerUser['default']['smod']['307'].$controllerUser['default']['smod']['302'].$controllerUser['default']['smod']['500'];
				$xmlControllers->appendXMLNode('//controllers', $flux);
				file_put_contents($this->_generic->getPathConfig("configSecure")."controllers.xml", $xmlControllers->getXML());
				
				// Add meta Tags
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$indexID."']", "<robots><![CDATA[index, follow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$urlErrorID."']", "<robots><![CDATA[noindex, follow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$authorizationID."']", "<robots><![CDATA[noindex, nofollow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$serverID."']", "<robots><![CDATA[noindex, nofollow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$forbiddenID."']", "<robots><![CDATA[noindex, nofollow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$badRequestID."']", "<robots><![CDATA[noindex, nofollow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$redirectID."']", "<robots><![CDATA[noindex, nofollow]]></robots>");
				$metasXML->appendXMLNode("//sls_configs/action[@id='".$maintenanceID."']", "<robots><![CDATA[noindex, nofollow]]></robots>");
				file_put_contents($this->_generic->getPathConfig("configSls")."metas.xml", $metasXML->getXML());
				// Déplacement des Fichiers de déploiement
				
				// Controllers
				if (!is_dir($this->_generic->getPathConfig("actionsControllers")."Home"))
					mkdir($this->_generic->getPathConfig("actionsControllers")."Home");
				if (!is_dir($this->_generic->getPathConfig("actionsControllers")."Default"))
					mkdir($this->_generic->getPathConfig("actionsControllers")."Default");
					
				// Langs
				if (!is_dir($this->_generic->getPathConfig("actionLangs")."Home"))
					mkdir($this->_generic->getPathConfig("actionLangs")."Home");
				if (!is_dir($this->_generic->getPathConfig("actionLangs")."Default"))
					mkdir($this->_generic->getPathConfig("actionLangs")."Default");
				
					
				// Generic Site Protected functions
				copy($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/__site.protected.php", $this->_generic->getPathConfig("actionsControllers")."__site.protected.php");
				
				$homeFiles = scandir($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/Home");
				$defaultFiles = scandir($this->_generic->getPathConfig("installDeployement")."Controllers/Actions/Default");

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

				// Copy Home Body Views
				foreach ($homeBodyFiles as $file)
					(substr($file, (strlen($file)-3)) == "xsl") ? copy($this->_generic->getPathConfig("installDeployement")."Views/Body/Home/".$file, $this->_generic->getPathConfig("viewsBody")."Home/".$file) : "";
				
				// Copy Default Body Views
				foreach ($defaultBodyFiles as $file)
					(substr($file, (strlen($file)-3)) == "xsl") ? copy($this->_generic->getPathConfig("installDeployement")."Views/Body/Default/".$file, $this->_generic->getPathConfig("viewsBody")."Default/".$file) : "";	
					
				// Copy Home Headers Views
				foreach ($homeHeadersFiles as $file)
					(substr($file, (strlen($file)-3)) == "xsl") ? copy($this->_generic->getPathConfig("installDeployement")."Views/Headers/Home/".$file, $this->_generic->getPathConfig("viewsHeaders")."Home/".$file) : "";
				
				// Copy Default Headers Views
				foreach ($defaultHeadersFiles as $file)
					(substr($file, (strlen($file)-3)) == "xsl") ? copy($this->_generic->getPathConfig("installDeployement")."Views/Headers/Default/".$file, $this->_generic->getPathConfig("viewsHeaders")."Default/".$file) : "";	
				
				
								
				$this->setInstallationStep(array(0=>"SLS_Init",1=>"Initialization"), array(0=>"DataBase",1=>"DataBase"));
				return $this->_generic->dispatch("SLS_Init", "DataBase");				
			}
			else 
			{
				$xml->startTag('errors');			
				foreach ($errors as $error)
					$xml->addFullTag('error', $error, true);
				$xml->endTag('errors');
				$giveDataStep1 = true;
				$step = 1;
			}
			
		}
		// Sinon, default
		else
		{
			$step = 0;
		}
		if ($giveDataStep1 == true)
		{
			$xml->startTag("choose_langs");
			$valueToHidden = "";
			$isos = array();
			foreach($listLangs as $listLang)
			{
				$iso = array_shift($handle->getTags("//sls_configs/sls_country/sls_country_langs/sls_country_lang[node()='".$listLang."']/@iso"));
				array_push($isos, $iso);
				$xml->startTag("choose_lang");					
				$xml->addFullTag("iso",$iso,true);
				$xml->addFullTag("label",$listLang,true);
				$xml->endTag("choose_lang");
				$valueToHidden .= "-".$listLang;
			}
			$xml->endTag("choose_langs");
			$xml->addFullTag("hidden_langs", substr($valueToHidden, 1), true);
			// Récupération des mots à traduire
			$xml->startTag("translate");
			foreach ($isos as $iso)
			{
				$xml->startTag($iso);
					if (is_file($this->_generic->getPathConfig("coreGenericLangs")."generic.".$iso.".lang.php"))
						$handle = fopen($this->_generic->getPathConfig("coreGenericLangs")."generic.".$iso.".lang.php", 'r');
					else 
						$handle = fopen($this->_generic->getPathConfig("coreGenericLangs")."generic.en.lang.php", 'r');
					$array = array();
					while (!feof($handle)) 
					{
						$line = fgets($handle, 4096);
						if (substr($line, 0, 1) == "$")
						{
							$tmpArray = array();
							$tmpArray['name'] =  str_replace("SLS_", "", SLS_String::substrAfterLastDelimiter(SLS_String::substrBeforeLastDelimiter($line, "']"), "['"));
							$tmpArray['value'] = SLS_String::substrBeforeLastDelimiter(SLS_String::substrAfterFirstDelimiter(trim(SLS_String::substrAfterLastDelimiter($line, " = ")), '"'), '"');
							array_push($array, $tmpArray);
						}
					}
					
					foreach ($array as $row)
					{
						$xml->startTag("sentence");
							$xml->addFullTag('name', strtolower(str_replace("_", " ", $row['name'])), true);
							$xml->addFullTag('code', $row['name'], true);
							$xml->addFullTag('value', $row['value'], true);
						$xml->endTag("sentence");
					}
				$xml->endTag($iso);
			}
			$xml->endTag("translate");
		}
		$xml->addFullTag("step", $step, true);
		$this->saveXML($xml);
	}
	public function action()
	{
		$user 	= $this->hasAuthorative();
		$xml 	= $this->getXML();
		$xml 	= $this->makeMenu($xml);
		$dbXML 	= $this->_generic->getDbXML();
		
		// Check if db exists
		$alias = rawurldecode($this->_http->getParam("alias"));
		$result = $dbXML->getTagsAttribute("//dbs/db","alias");
		$dbs = array();
		for($i=0 ; $i<$count=count($result) ; $i++)
			array_push($dbs,$result[$i]["attribute"]);
			
		if (in_array($alias,$dbs))
		{
			// Check if it is not the default db
			$result = array_shift($this->_generic->getDbXML()->getTagsAttribute("//dbs/db[@isDefault='true']","alias"));
			if ($alias != $result["attribute"])
			{	
				$files = array();
				$bos = array();
				$xml->addFullTag("db_exists","true",true);
				
				$controllerXML = $this->_generic->getControllersXML();
				$genericBo = array_shift($controllerXML->getTags("//controllers/controller[@isBo='true']/@name"));
				
				// List files which will be deleted
				$models = $this->getAllModels();
				$xml->startTag("models");
				foreach($models as $model)
				{
					if (SLS_String::startsWith($model,$alias))
					{
						$xml->startTag("model");
						$xml->addFullTag("label",SLS_String::substrAfterFirstDelimiter($model,"."),true);
						$xml->addFullTag("file",ucfirst($model),true);
						array_push($files,$this->_generic->getPathConfig("models").ucfirst($model).".model.php");
						array_push($files,$this->_generic->getPathConfig("modelsSql").ucfirst($model).".sql.php");
						
						$actionsBo = $this->getActionsBo(SLS_String::substrAfterFirstDelimiter($model,"."),$alias);
						$xml->startTag("bos");
						foreach($actionsBo as $actionBo)
						{
							$tmp = array("model"=>SLS_String::substrAfterFirstDelimiter($model,"."),"action"=>strtolower(SLS_String::substrBeforeFirstDelimiter($actionBo,ucfirst($alias)."_")),"alias"=>$alias);							
							array_push($bos,$tmp);
							$xml->startTag("bo");
							$xml->addFullTag("label",SLS_String::substrBeforeFirstDelimiter($actionBo,ucfirst($alias)."_"),true);
							$xml->addFullTag("file",$actionBo.".controller.php",true);
							$xml->endTag("bo");
						}
						$xml->endTag("bos");
						$xml->endTag("model");
					}
				}
				$xml->endTag("models");
				
				if ($this->_http->getParam("reload") == "true")
				{
					$password = SLS_String::trimSlashesFromString($this->_http->getParam("password", 'post'));
					$login = SLS_String::trimSlashesFromString($this->_http->getParam("login", 'post'));
					
					$slsXml = $this->_generic->getCoreXML('sls');
					$passXML = array_shift($slsXml->getTags("//sls_configs/auth/users/user[@login='******' and @level='0']/@pass"));
					
					if (!empty($passXML) && $passXML == sha1($password))
					{						
						// Delete files bo
						foreach($bos as $bo)
							$this->deleteActionBo($bo["model"],$bo["action"],$bo["alias"]);
						// Delete files model
						foreach($files as $file)
							@unlink($file);
						// Delete config
						$dbXML->deleteTags("//dbs/db[@alias='".$alias."']");						
						$dbXML->saveXML($this->_generic->getPathConfig("configSecure")."db.xml");
						
						$controllers = $this->_generic->getTranslatedController("SLS_Bo","DataBaseSettings");
						$this->_generic->redirect($controllers["controller"]."/".$controllers["scontroller"].".sls");
					}
					else					
						$xml->addFullTag("incorrect_account","true",true);					
				}
				
				
				$xml->addFullTag("database",$alias,true);
			}
			else
			{
				$xml->startTag("errors");
				$xml->addFullTag("error","You can't delete the default database",true);
				$xml->endTag("errors");
			}
		}
		else
		{
			$xml->startTag("errors");
			$xml->addFullTag("error","This database can't be found",true);
			$xml->endTag("errors");
		}
		
		$this->saveXML($xml);
	}	
	public function action()
	{
		set_time_limit(0);
		
		$user = $this->hasAuthorative();
		$errors = array();
		$sql = SLS_Sql::getInstance();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);

		// Get all models
		$models = array();
		$handle = opendir($this->_generic->getPathConfig("models"));
		while (false !== ($file = readdir($handle)))
		{
			if (!is_dir($this->_generic->getPathConfig("models")."/".$file) && substr($file, 0, 1) != ".") 
			{
				$modelExploded = explode(".",$file);
				array_push($models,strtolower($modelExploded[0]).".".$modelExploded[1]);
			}
		}
		
		// If reload
		if ($this->_http->getParam("reload")=="true")
		{
			// Get the tables dude wants to generate
			$tablesG = ($this->_http->getParam("tables")=="") ? array() : $this->_http->getParam("tables");
			
			// Foreach tables, generate model
			foreach($tablesG as $tableG)
			{
				$db = Sls_String::substrBeforeFirstDelimiter($tableG,".");
				$table = Sls_String::substrAfterFirstDelimiter($tableG,".");
				
				// Change db if it's required
				if ($sql->getCurrentDb() != $db)
					$sql->changeDb($db);
				
				// If table exists
				if ($sql->tableExists($table))
				{					
					$columns = $sql->showColumns($table);
					$tableName = $table;
					$currentTable = array("table"=>$db.".".$tableName,"errors"=>array());
					$fieldsOk = true;
					$className = ucfirst($db)."_".SLS_String::tableToClass($tableName);
					$fileName  = ucfirst($db).".".SLS_String::tableToClass($table).".model.php";					
															
					for($i=0 ; $i<$count=count($columns) ; $i++)
					{						
						// Check forbidden chars
						if (SLS_String::removePhpChars($columns[$i]->Field) != $columns[$i]->Field)
						{
							$error = array("column"=>$columns[$i]->Field,"column_clean"=>SLS_String::removePhpChars($columns[$i]->Field));
							array_push($currentTable["errors"],$error);
							$fieldsOk = false;
						}
					}
					
					// If all ok with special chars for the current model
					if ($fieldsOk)
					{
						// Check real fks
						$create = array_shift($sql->select("SHOW CREATE TABLE `".$table."`"));						
						$queries = array_map("trim",explode("\n",$create->{Create." ".Table}));						
						foreach($queries as $query)
						{
							if (SLS_String::startsWith($query,"CONSTRAINT"))
							{
								$tableFk = strtolower($db."_".$tableName);
								$columnFk = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($query,"FOREIGN KEY (`"),"`)");
								$tablePk = $db."_".SLS_String::tableToClass(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($query,"REFERENCES `"),"`"));
								$onDelete = strtolower(SLS_String::stringToUrl(trim(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($query,"ON DELETE"),"ON UPDATE")),"_"));
								$labelPk = "";
								$columns = $sql->showColumns(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($query,"REFERENCES `"),"`"));
								for($i=0 ; $i<$count=count($columns) ; $i++)
								{
									if ($columns[$i]->Key != "PRI" && $columns[$i]->Field != "pk_lang" && SLS_String::contains($columns[$i]->Type,"char"))
									{
										$labelPk = $columns[$i]->Field;
										break;
									}
								}
								if (empty($labelPk))
									$labelPk = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($query,"REFERENCES `".SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($query,"REFERENCES `"),"`")."` (`"),"`)");
								$xmlNode = '<entry tableFk="'.$tableFk.'" columnFk="'.$columnFk.'" multilanguage="false" ondelete="'.$onDelete.'" labelPk="'.$labelPk.'" tablePk="'.$tablePk.'" />';
								
								$xmlFk = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml"));
								$result = $xmlFk->getTags("//sls_configs/entry[@tableFk='".$tableFk."' and @columnFk='".$columnFk."' and @tablePk='".$tablePk."']");
								if (!empty($result))
								{
									$xmlTmp = $xmlFk->deleteTags("//sls_configs/entry[@tableFk='".$tableFk."' and @columnFk='".$columnFk."' and @tablePk='".$tablePk."']");
									$xmlFk->saveXML($this->_generic->getPathConfig("configSls")."/fks.xml",$xmlTmp);
									$xmlFk = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml"));
								}
								
								$xmlFk->appendXMLNode("//sls_configs",$xmlNode);
								$xmlFk->saveXML($this->_generic->getPathConfig("configSls")."/fks.xml",$xmlFk->getXML());
							}
						}
						
						// Generate Model						
						$contentM = $this->getModelSource($tableName,$db);						
						$status = touch($this->_generic->getPathConfig("models")."/".$fileName);
						if ($status)					
							file_put_contents($this->_generic->getPathConfig("models").$fileName,$contentM);
						
						// Create SQL
						$fileNameS = ucfirst($db).".".SLS_String::tableToClass($table).".sql.php";
						$contentS = '<?php'."\n".
								   '/**'."\n".
								   '* Object '.$className.'Sql'."\n".
								   '* @author SillySmart'."\n".
								   '* @copyright SillySmart'."\n".
								   '* @package Mvc.Models.Objects'."\n".
								   '* @see Sls.Models.Core.SLS_FrontModel'."\n".
								   '* @since 1.0'."\n".
								   '*/'."\n".
								   'class '.$className.'Sql extends SLS_FrontModelSql'."\n".
								   '{'."\n".
								   ''."\n".
								   '}'."\n".
								   '?>';
						if ($status)
							$status2 = touch($this->_generic->getPathConfig("modelsSql")."/".$fileNameS);
						if ($status2)					
							file_put_contents($this->_generic->getPathConfig("modelsSql")."/".$fileNameS,$contentS);					 
					}
					else					
						array_push($errors,$currentTable);					
				}
			}
			// If no errors
			if (empty($errors))
			{
				$controllers = $this->_generic->getTranslatedController("SLS_Bo","Models");
				$this->_generic->redirect($controllers['controller']."/".$controllers['scontroller']);
			}
			else
			{	
				// Get all models
				$models = array();
				$handle = opendir($this->_generic->getPathConfig("models"));
				while (false !== ($file = readdir($handle))) 			
					if (!is_dir($this->_generic->getPathConfig("models")."/".$file) && substr($file, 0, 1) != ".") 
					{
						$modelExploded = explode(".",$file);
						array_push($models,strtolower($modelExploded[0]).".".$modelExploded[1]);
					}
					
				// Form errors
				$xml->startTag("errors");
				for($i=0 ; $i<$count=count($errors) ; $i++)
				{
					$xml->startTag("error");
					$xml->addFullTag("table",SLS_String::substrAfterFirstDelimiter($errors[$i]["table"],"."),true);
					$xml->addFullTag("db",SLS_String::substrBeforeFirstDelimiter($errors[$i]["table"],"."),true);
					$xml->startTag("columns");
					for($j=0 ; $j<$count2=count($errors[$i]["errors"]) ; $j++)
					{
						$xml->startTag("column");
						$xml->addFullTag("old",$errors[$i]["errors"][$j]["column"],true);
						$xml->addFullTag("new",$errors[$i]["errors"][$j]["column_clean"],true);
						$xml->endTag("column");
					}
					$xml->endTag("columns");
					$xml->endTag("error");
				}
				$xml->endTag("errors");				
			}
		}
		
		// Foreach db
		$dbs = $sql->getDbs();
		$allDbs = array();	
		
		foreach($dbs as $db)
		{
			$allDbs[$db] = array();
			
			// Change db
			$sql->changeDb($db);
			
			// Get all tables
			$tables = $sql->showTables();						
			for($i=0 ; $i<$count=count($tables) ; $i++)
			{
				$allDbs[$db][$tables[$i]->Name] = array("name" 	=> $tables[$i]->Name,
														"existed" => (in_array($db.".".SLS_String::tableToClass($tables[$i]->Name),$models)) ? 'true' : 'false');				
			}
		}
		
		asort($allDbs,SORT_REGULAR);
		uksort($allDbs,array($this, 'unshiftDefaultDb'));
		
		$xml->startTag("dbs");
		foreach($allDbs as $key => $db)
		{
			asort($db,SORT_REGULAR);
			
			$xml->startTag("db");
			$xml->addFullTag("name",$key,true);
			$xml->startTag("tables");
			foreach($db as $tableCur)
			{
				if (!SLS_String::startsWith(strtolower($tableCur["name"]),"sls_graph"))
				{
					$xml->startTag("table");				
					$xml->addFullTag("name",$tableCur["name"]);
					$xml->addFullTag("existed",$tableCur["existed"]);
					$xml->endTag("table");
				}
			}
			$xml->endTag("tables");
			$xml->endTag("db");
		}
		$xml->endTag("dbs");
			
		$this->saveXML($xml);
	}
	/**
	 * Format XML for the current recordset
	 * 
	 * @access public
	 * @param SLS_XMLToolbox $xml current controller's XML
	 * @param array $options transformations on some columns - delimited by ":". each function can be methods of SLS' classes or php standard function
	 * <code>
     * // Complete example
	 * $xml = $news->toXML($xml, 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",
	 *									"news_link"		=> array("/Item/",
	 *															 "news_title" => "SLS_String:stringToUrl:_",
	 *															 "-",
	 *															 "news_id" => array("php:intval","php:pow:2"),
	 *															 "/User/",
	 *															 "user_id"))
	 *						, true, "news");
	 * </code>    
	 * @param mixed $fks (bool: if true all fks, if false only current Model) - array fks you want to extract params
	 * @param string $nodeName the root node of your model, by default it's your classname in lowercase
	 * @param array $properties all columns/values of your choice if you don't want to take it from getParams() function of the current instance
	 * @return SLS_XMLToolbox $xml current controller's XML updated
	 * @see SLS_FrontModel::getParams
	 * @see SLS_FrontModel::pdoToXML
	 * @since 1.0.8	 
	 */
	public function toXML($xml,$options=array(),$fks=false,$nodeName="",$properties=array())
	{
		$nodeName 	= (empty($nodeName)) ? strtolower($this->getTable()) : $nodeName;
		$properties = (empty($properties)) ? $this->getParams($fks) : $properties;
		
		$xml->startTag($nodeName);
		foreach($properties as $column => $value)
		{
			if (in_array($column,$columns=array_keys($options)))
			{
				$filters = (is_array($options[$column])) ? $options[$column] : array($options[$column]);
				
				foreach($filters as $filter)
				{
					$option = explode(":",$filter);
					switch($option[0])
					{
						case SLS_String::startsWith($option[0],"SLS_"):
							if (!class_exists($option[0]))
								SLS_Tracing::addTrace(new Exception("Error: you want to use an undefined class `".$option[0]."` for the column `".$column."` of `".$this->getTable()."` table"));
							else
							{
								if (!method_exists($option[0],((count($option)> 1) ? $option[1] : "")))
									SLS_Tracing::addTrace(new Exception("Error: you want to use an undefined function `".$option[1]."` of class `".$option[0]."` for the column `".$column."` of `".$this->getTable()."` table"));
								else
								{
									$ref = new ReflectionMethod($option[0],$option[1]);
									$nbRequiredParams = $ref->getNumberOfRequiredParameters();
									if ($nbRequiredParams > (count($option)-1))									
										SLS_Tracing::addTrace(new Exception("Error: function `".$option[1]."` of class `".$option[0]."` needs ".$nbRequiredParams." required parameters for the column `".$column."` of `".$this->getTable()."` table"),true);
									else
									{										
										$params = array_slice($option,2);
										array_unshift($params,$value);
										
										// Case "SLS_Date::getDate"
										if ($option[0] == "SLS_Date" && $option[1] == "getDate")
										{											
											$option[0] = new SLS_Date($value);
											array_shift($params);											
										}
										// Case "SLS_String::getUrlFileImg"
										if ($option[0] == "SLS_String" && $option[1] == "getUrlFileImg" && count($option) > 2)
										{
											$xml->addFullTag($column."_original",SLS_String::getUrlFile($value,(count($option) > 3) ? $option[3] : ""),true);
											$column = $column.$option[2];											
										}
										
										$value = $ref->invokeArgs(($ref->isStatic()) ? null : $option[0],$params);
										
									}									
								}	
							}	
							break;				
						case "php":
							if (count($option) < 2)
								SLS_Tracing::addTrace(new Exception("Error: you must specify the name of the PHP's function you want to apply on the column `".$column."` of `".$this->getTable()."` table"));
							else
							{
								if (function_exists($option[1]))
								{
									$ref = new ReflectionFunction($option[1]);
									$nbRequiredParams = $ref->getNumberOfRequiredParameters();
									if ($nbRequiredParams > (count($option)-1))									
										SLS_Tracing::addTrace(new Exception("Error: the PHP's function `".$option[1]."` needs ".$nbRequiredParams." required parameters for the column `".$column."` of `".$this->getTable()."` table"),true);
									else
									{
										$params = array_slice($option,2);
										array_unshift($params,$value);
										$value = $ref->invokeArgs($params);
									}
								}
								else
									SLS_Tracing::addTrace(new Exception("Error: the PHP's function '".$option[1]."' you want to use on the column `".$column."` of `".$this->getTable()."` table doesn't exist"));
							}
							break;
						default:
							SLS_Tracing::addTrace(new Exception("Error: you want to apply an unknown filter on the column `".$column."` of `".$this->getTable()."` table doesn't exist"));
							break;
					}
				}
			}
			$xml->addFullTag($column,$value,true);
		}		
		foreach($options as $col => $concat)
		{
			if (!in_array($col,array_keys($properties)) && is_array($concat))
			{
				$values = array();				
				foreach($concat as $column => $filter)
				{
					if (is_int($column) && !empty($filter) && !is_array($filter))
					{
						$column = $filter;
						$filter = "";
					}
					$value = "";
					$filters = (is_array($filter)) ? $filter : ((empty($filter)) ? "" : array($filter));					
					if (in_array($column,array_keys($properties)))
						$value .= $properties[$column];
					else
						$value .= $column;
					
					if (!empty($filters))
					{
						foreach($filters as $filter)
						{
							$option = explode(":",$filter);
							
							switch($option[0])
							{
								case SLS_String::startsWith($option[0],"SLS_"):
									if (!class_exists($option[0]))
										SLS_Tracing::addTrace(new Exception("Error: you want to use an undefined class `".$option[0]."` for the column `".$column."` of `".$this->getTable()."` table"));
									else
									{
										if (!method_exists($option[0],((count($option)> 1) ? $option[1] : "")))
											SLS_Tracing::addTrace(new Exception("Error: you want to use an undefined function `".$option[1]."` of class `".$option[0]."` for the column `".$column."` of `".$this->getTable()."` table"));
										else
										{
											$ref = new ReflectionMethod($option[0],$option[1]);
											$nbRequiredParams = $ref->getNumberOfRequiredParameters();
											if ($nbRequiredParams > (count($option)-1))									
												SLS_Tracing::addTrace(new Exception("Error: function `".$option[1]."` of class `".$option[0]."` needs ".$nbRequiredParams." required parameters for the column `".$column."` of `".$this->getTable()."` table"),true);
											else
											{										
												$params = array_slice($option,2);
												array_unshift($params,$value);
												
												// Case "SLS_Date::getDate"
												if ($option[0] == "SLS_Date" && $option[1] == "getDate")
												{											
													$option[0] = new SLS_Date($value);
													array_shift($params);											
												}
												// Case "SLS_String::getUrlFileImg"
												if ($option[0] == "SLS_String" && $option[1] == "getUrlFileImg" && count($option) > 2)
												{
													$xml->addFullTag($column."_original",SLS_String::getUrlFile($value),true);
													$column = $column.$option[2];											
												}
												
												$value = $ref->invokeArgs(($ref->isStatic()) ? null : $option[0],$params);
												
											}									
										}	
									}	
									break;				
								case "php":
									if (count($option) < 2)
										SLS_Tracing::addTrace(new Exception("Error: you must specify the name of the PHP's function you want to apply on the column `".$column."` of `".$this->getTable()."` table"));
									else
									{
										if (function_exists($option[1]))
										{
											$ref = new ReflectionFunction($option[1]);
											$nbRequiredParams = $ref->getNumberOfRequiredParameters();
											if ($nbRequiredParams > (count($option)-1))									
												SLS_Tracing::addTrace(new Exception("Error: the PHP's function `".$option[1]."` needs ".$nbRequiredParams." required parameters for the column `".$column."` of `".$this->getTable()."` table"),true);
											else
											{
												$params = array_slice($option,2);
												array_unshift($params,$value);
												$value = $ref->invokeArgs($params);
											}
										}
										else
											SLS_Tracing::addTrace(new Exception("Error: the PHP's function '".$option[1]."' you want to use on the column `".$column."` of `".$this->getTable()."` table doesn't exist"));
									}
									break;
								default:
									SLS_Tracing::addTrace(new Exception("Error: you want to apply an unknown filter on the column `".$column."` of `".$this->getTable()."` table doesn't exist"));
									break;
							}
						}
					}
					$values[] = $value;
				}
				$xml->addFullTag($col,implode("",$values),true);
			}
		}
		$xml->endTag($nodeName);
		
		return $xml;
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		
		// Objects
		$sql = SLS_Sql::getInstance();		
		$xml = $this->getXML();		
		$xml = $this->makeMenu($xml);
		
		// Actions
		$xml->addFullTag("delete",$this->_generic->getFullPath("SLS_Bo","DeleteModel",array(),false));
		$xml->addFullTag("delete_bearer",$this->_generic->getFullPath("SLS_Bo","DeleteBearerTable",array(),false));
		$xml->addFullTag("delete_type",$this->_generic->getFullPath("SLS_Bo","DeleteType",array(),false));
		$xml->addFullTag("edit_type",$this->_generic->getFullPath("SLS_Bo","EditType",array(),false));
		$xml->addFullTag("delete_fk",$this->_generic->getFullPath("SLS_Bo","DeleteForeignKey",array(),false));
		$xml->addFullTag("edit_fk",$this->_generic->getFullPath("SLS_Bo","EditForeignKey",array(),false));
		$xml->addFullTag("update",$this->_generic->getFullPath("SLS_Bo","UpdateModel",array(),false));		
		$xml->addFullTag("descriptions",$this->_generic->getFullPath("SLS_Bo","UpdateDescription",array(),false));
		
		// Get the table & class name
		$table = SLS_String::substrAfterFirstDelimiter($this->_http->getParam("name"),"_");
		$db	   = SLS_String::substrBeforeFirstDelimiter($this->_http->getParam("name"),"_");
		$class = ucfirst($db)."_".SLS_String::tableToClass($table);
		$file  = ucfirst($db).".".SLS_String::tableToClass($table);
		
		// If current db is not this one
		if ($sql->getCurrentDb() != $db)
			$sql->changeDb($db);
		
		// Get generic object
		$this->_generic->useModel(SLS_String::tableToClass($table),$db,"user");
		$object = new $class();
		
		// Get description's table
		$description = $object->getTableComment($table);	
		$columnsInfos = $sql->showColumns($table);
		
		// Get object's infos
		$columns = array();
		$columnsP = $object->getParams();
		$pk = $object->getPrimaryKey();
		$multilanguage = $object->isMultilanguage();
		$xml->startTag("model");
		$xml->addFullTag("table",$table,true);
		$xml->addFullTag("description",(SLS_String::contains($description,"InnoDB free")) ? SLS_String::substrBeforeFirstDelimiter($description,"; InnoDB free") : $description,true);
		$xml->addFullTag("db",$db,true);
		$xml->addFullTag("class",$class,true);
		$xml->addFullTag("pk",$pk,true);
		$xml->addFullTag("multilanguage",($multilanguage) ? "true" : "false",true);
		$xml->startTag("columns");
		$cursor = 0;
		foreach($columnsP as $column => $value)
		{
			$xml->startTag("column");
			$xml->addFullTag("name",$column,true);
			array_push($columns,$column);
			$fk = "";
			$sType = "";
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml");
			$xmlFk = new SLS_XMLToolbox($pathsHandle);			
			$res = $xmlFk->getTagsByAttributes("//sls_configs/entry",array("tableFk","columnFk"),array($db."_".$table,$column));
			if (!empty($res))
			{
				$tableTmp = substr($res,(strpos($res,'tablePk="')+9),(strpos($res,'"/>')-(strpos($res,'tablePk="')+9)));
				$fk = SLS_String::substrAfterFirstDelimiter($tableTmp,"_");				
			}
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/types.xml");
			$xmlType = new SLS_XMLToolbox($pathsHandle);						
			$res = $xmlType->getTagsByAttributes("//sls_configs/entry",array("table","column"),array($db."_".$table,$column));
			if (!empty($res))
			{
				$sType = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($res,'type="'),'"/>');
				// If specific type numeric and native type too
				if (SLS_String::startsWith($sType,"num_") && $this->containsRecursive($columnsInfos[$cursor]->Type,array("int","float","double","decimal","real")))
					$xml->addFullTag("allow_to_delete_type","false",true);
			}
			
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/filters.xml");
			$xmlFilter = new SLS_XMLToolbox($pathsHandle);			
			$results = $xmlFilter->getTagsAttributes("//sls_configs/entry[@table='".$db."_".$table."' and @column='".$column."']",array("filter","hash"));			
			$xml->startTag("filters");
			for($i=0 ; $i<$count=count($results) ; $i++)
			{
				$filter = $results[$i]["attributes"][0]["value"];
				$result = $results[$i]["attributes"][1]["value"];
				
				$xml->startTag("filter");
					$xml->addFullTag("name",$filter.((!empty($result)) ? ' ['.$result.']' : ''),true);
					$xml->addFullTag("url_delete",$this->_generic->getFullPath("SLS_Bo","DeleteFilter",array(array("key"=>"table","value"=>$this->_http->getParam("name")),array("key"=>"column","value"=>$column),array("key"=>"filter","value"=>$filter))),true);
				$xml->endTag("filter");
			}
			$xml->endTag("filters");
			$xml->addFullTag("fk",$fk,true);
			$xml->addFullTag("type",ucfirst($sType),true);
			$xml->addFullTag("comment",$object->getColumnComment($column),true);
			$xml->endTag("column");
			
			$cursor++;
		}
		$xml->endTag("columns");
		$xml->addFullTag("url_add_type",$this->_generic->getFullPath("SLS_Bo","AddType",array(0=>array("key"=>"name","value"=>$db."_".$table))),true);
		$xml->addFullTag("url_add_filter",$this->_generic->getFullPath("SLS_Bo","AddFilter",array(0=>array("key"=>"name","value"=>$db."_".$table))),true);
		$xml->addFullTag("url_add_fk",$this->_generic->getFullPath("SLS_Bo","AddForeignKey",array(0=>array("key"=>"name","value"=>$db."_".$table))),true);
		
		// Get the source of the current model
		$xml->addFullTag("current_source",str_replace("\t","    ",file_get_contents($this->_generic->getPathConfig("models").$file.".model.php")),true);
		
		// Get the source of the current table
		if (!$sql->tableExists($table))
			$xml->addFullTag("current_table",-1,true);
		else
		{
			$columns = $sql->showColumns($table);					
			$tableName = $table;
			$currentTable = array("table"=>$db.".".$tableName,"errors"=>array());			
			$className = ucfirst($db)."_".SLS_String::tableToClass($tableName);
			$fileName = ucfirst($db).".".SLS_String::tableToClass($table).".model.php";
			$primaryKey = "";
			$multiLanguage = 'false';
			
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/types.xml");
			$xmlType = new SLS_XMLToolbox($pathsHandle);
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/fks.xml");
			$xmlFk = new SLS_XMLToolbox($pathsHandle);
			$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/filters.xml");
			$xmlFilter = new SLS_XMLToolbox($pathsHandle);
			
			// Get source
			$contentM = $this->getModelSource($tableName,$db);
			
			// Is data bearer
			$xmlBearer = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/bearers.xml"));
			$result = array_shift($xmlBearer->getTagsAttributes("//sls_configs/entry[@tableBearer='".$class."']",array("table1")));
			$xml->addFullTag("is_data_bearer",(!empty($result)) ? $result["attributes"][0]["value"] : "false",true);
			
			// Save the new source
			$xml->addFullTag("current_table",str_replace("\t","    ",$contentM),true);
			$xml->addFullTag("url_data_bearer",$this->_generic->getFullPath("SLS_Bo","AddBearerTable",array(array("key"=>"name","value"=>$this->_http->getParam("name")))),true);
		}		
		$xml->endTag("model");
		$this->saveXML($xml);
	}
	/**
	 * 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
		}
	}
Example #28
0
	/**
	 * Sql Delete
	 *
	 * @access public
	 * @param string $delete the sql query
	 * @return mixed nb recordsets deleted if success, else false
	 * @see SLS_Sql::select
	 * @see SLS_Sql::insert
	 * @see SLS_Sql::update
	 * @since 1.0
	 */
	public function delete($delete) 
	{		
		$this->flushCache($delete,"from");
		
		if (!$this->checkConnexion())
			return false;		
		try
		{
			$this->_generic->_time_checkpoint = microtime(true);
			$count = $this->_dbh[$this->_currentDb]->exec($delete);
			if (!SLS_String::startsWith(strtolower(trim($delete)),"explain"))
				$this->_generic->logTime($this->_generic->monitor($this->_generic->_time_checkpoint),"MySQL Query DELETE","Query: ".$delete,"MySQL Query");
			return $count;
		}
		catch (Exception $e)
		{			
			SLS_Tracing::addTrace($e,true);
			return false;
		}
	}
    /**
     * Calculate xPath of the given DOMNode
     * 
     * @access public static
     * @param DOMNode $node
     * @return string $xpath xPath
     * @since 1.1
     */
	public static function calculateXPath(DOMNode $node)
	{
		// Easy
		if (method_exists($node,'getNodePath'))
			return '/'.str_replace('/text()','',$node->getNodePath());
		
		// Let's go...
	    $q     = new DOMXPath($node->ownerDocument);
	    $xpath = '';
	    do
	    {
	    	$prevSibling = $q->query('preceding-sibling::*[name()="' . $node->nodeName . '"]', $node)->length;
	    	$nextSibling = $q->query('following-sibling::*[name()="' . $node->nodeName . '"]', $node)->length;
	        $position = 1 + $prevSibling;
	        if (!SLS_String::startsWith($node->nodeName,"#"))
	        {
	        	$xpathS    = '/' . $node->nodeName;
	        	if ($prevSibling > 0 || $nextSibling > 0)
	        		$xpathS .= '[' . $position . ']';
	        	$xpath = $xpathS.$xpath;
	        }
	        $node     = $node->parentNode;
	    }
	    while (!$node instanceof DOMDocument);
	    return '/'.$xpath;
	}
	/**
	 * Log execution time
	 * 
	 * @access public
	 * @param float $time execution time
	 * @param string $message message to log
	 * @param string $detail detail
	 * @param string $type type of process
	 * @since 1.0.5
	 */
	public function logTime($time,$message,$detail="",$type="unknown")
	{
		#echo "[".$type."] || ".date("Y-m-d H:i:s")." || ".$time." || ".$message." || "."Detail: ".$detail."<br />";
		
		// Developer monitoring
		if ($this->getSide() == "user" && $this->getBo() != $this->getGenericControllerName())
		{
			$types = array("statics" 		=> array("time" => "0", "logs" => array()),
						   "components" 	=> array("time" => "0", "logs" => array()),
						   "routing" 		=> array("time" => "0", "msg"  => ""),
						   "init" 			=> array("time" => "0", "msg"  => ""),
						   "action" 		=> array("time" => "0", "msg"  => ""),
						   "sql" 			=> array("time" => "0", "logs" => array()),
						   "parsing_html" 	=> array("time" => "0", "msg"  => ""),
						   "parsing_xsl" 	=> array("time" => "0", "msg"  => ""),
						   "flush_cache" 	=> array("time" => "0", "logs" => array()));
			$logSession = $this->_session->getParam("sls_dev_logs");
			$devLogs = (empty($logSession)) ? $types : $logSession;
			switch($type)
	    	{
	    		case "Controller Static":
	    			$devLogs["statics"]["time"] += $time;
	    			$devLogs["statics"]["logs"][] = array("time" => $time, "msg" => trim(SLS_String::substrAfterFirstDelimiter($detail,"Controller:")));
	    			break;
	    		case "Controller Component":
	    			$devLogs["components"]["time"] += $time;
	    			$devLogs["components"]["logs"][] = array("time" => $time, "msg" => trim(SLS_String::substrAfterFirstDelimiter($detail,"Controller:")));
	    			break;
	    		case "Controller Front":
	    			$mapping = trim(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($message,"Resolve Mapping ("),")"));
	    			$mappingController = SLS_String::substrBeforeFirstDelimiter($mapping,"/");
	    			$mappingAction = SLS_String::substrAfterFirstDelimiter($mapping,"/");
	    			$devLogs["routing"]["time"] += $time;
	    			$devLogs["routing"]["msg"] = SLS_String::printArray(array("mode" => $mappingController, "smode" => $mappingAction));
	    			break;
	    		case "Controller Init":
	    			$devLogs["init"]["time"] += $time;
	    			break;
	    		case "Controller Action":
	    			$devLogs["action"]["time"] += $time;
	    			break;
	    		case "MySQL Query":
					$message = trim((!SLS_String::startsWith($detail,"Query:")) ? $message : SLS_String::substrAfterFirstDelimiter($detail,"Query:"));
					if ($message == "MySQL Connecting")
						$message = "Connection"." |n|".$detail;
					$message = str_replace(array("|n|"),array("\n"),$message);
	    			$devLogs["sql"]["time"] += $time;
	    			$devLogs["sql"]["logs"][] = array("time" => $time, "msg" => $message);
	    			break;
	    		case "HTML Parsing":
	    			$devLogs["parsing_html"]["time"] += $time;
	    			break;
	    		case "XML/XSL Parsing":
	    			$devLogs["parsing_xsl"]["time"] += $time;
	    			break;
	    		case "Flush Cache":
	    			$devLogs["flush_cache"]["time"] += $time;
	    			$devLogs["flush_cache"]["logs"][] = array("time" => $time, "msg" => $detail);
	    			break;
	    	}
	    	$this->_session->setParam("sls_dev_logs",$devLogs);
		}
		
		if (!$this->isMonitoring())
			return;
		
		// Objects
		$nbOccurencesFiles = 0;
		$nbMaxLines = 5000;
		$directory = "monitoring/".date("Y-m");
		$fileName = date("Y-m-d");
		$filePath = "";
		
		// Check if monitoring directory exists
		if (!file_exists($this->getPathConfig("logs")."monitoring"))
			mkdir($this->getPathConfig("logs")."monitoring",0777);	
		
		// If month directory doesn't exists, create it			
		if (!file_exists($this->getPathConfig("logs").$directory))			
			mkdir($this->getPathConfig("logs").$directory,0777);
			
		// Count the number of hits of log file			
		$handle = opendir($this->getPathConfig("logs").$directory);
		while (false !== ($file = readdir($handle)))
			if (SLS_String::startsWith($file,$fileName))
				$nbOccurencesFiles++;
    	closedir($handle);
    	
    	// If the current file log doesn't exists, create it		    
	    if ($nbOccurencesFiles == 0)
	    {
	    	touch($this->getPathConfig("logs").$directory."/".$fileName."_0.log");
	    	$filePath = $this->getPathConfig("logs").$directory."/".$fileName."_0.log";
	    }
	    // Else, locate it
	    else	    
	    	$filePath = $this->getPathConfig("logs").$directory."/".$fileName."_".($nbOccurencesFiles-1).".log";
	    
	    // Then, if and only if the file log has been located, increased or created : write into the logs		    
	    if (is_file($filePath) && $this->getSide() == "user")
	    {
	    	$oldContentLog = file_get_contents($filePath);
	    	$newContentLog = "".$type." || ".date("Y-m-d H:i:s")." || ".$time." || ".$message." || ".$detail;
	    	if (SLS_String::endsWith($newContentLog,"\n"))
	    		$newContentLog = SLS_String::substrBeforeLastDelimiter($newContentLog,"\n");
	    	$newContentLog = str_replace("\n","|n|",$newContentLog);
	    	    	
	    	file_put_contents($filePath,$newContentLog."\n".$oldContentLog,LOCK_EX);
	    		    	
	    	if ($type == "Render")
	    	{
	    		$oldContentLog = file_get_contents($filePath);
	    		$newContentLog = "#|end|#";
	    		file_put_contents($filePath,$newContentLog."\n".$oldContentLog,LOCK_EX);
	    		
		    	// If the max number of lines has been reach, increase the file log version		    
			    if (SLS_String::countLines(file_get_contents($filePath)) >= $nbMaxLines)
			    {
			    	touch($this->getPathConfig("logs").$directory."/".$fileName."_".$nbOccurencesFiles.".log");
			    	$filePath = $this->getPathConfig("logs").$directory."/".$fileName."_".$nbOccurencesFiles.".log";
			    }
	    	}
	    }
	}