Пример #1
0
	/**
	 * 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();
		$nbDelete = 0;
		# /Objects
				
		# Params
		$ids = $this->_http->getParam("id");
		$ids = (SLS_String::contains($ids,"|")) ? explode("|",$ids) : array($ids);
		# /Params
		
		# Perform delete
		foreach($ids as $id)
			if ($this->_object->getModel($id) === true)
				$nbDelete += $this->_object->delete(true);
		if ($this->_object->isMultilanguage() && is_numeric($nbDelete) && $nbDelete > 0)
			$nbDelete = floor($nbDelete / count($this->_lang->getSiteLangs()));
		# Perform delete
		
		if ($this->_async)
		{
			if ($nbDelete !== false && is_numeric($nbDelete) && $nbDelete > 0)
			{
				$this->_render["status"] = "OK";
				$this->_render["result"]["message"] = ($nbDelete==1) ? $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_GENERIC_SUBMIT_SUCCESS_DELETE'] : sprintf($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_GENERIC_SUBMIT_SUCCESS_DELETES'],$nbDelete);
			}
			echo json_encode($this->_render);
			die();
		}
		else
		{
			# Notif
			if ($nbDelete !== false && is_numeric($nbDelete) && $nbDelete > 0)
				$this->pushNotif("success",($nbDelete==1) ? $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_GENERIC_SUBMIT_SUCCESS_DELETE'] : sprintf($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_GENERIC_SUBMIT_SUCCESS_DELETES'],$nbDelete));
			# /Notif
			
			# 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
	}
	public function action() 
	{		
		// Objects
		$xml = $this->getXML();
		$user = $this->hasAuthorative();
		$xml = $this->makeMenu($xml);
		$this->_generic->registerLink('Add', 'SLS_Bo', 'AddRight');
		$xml->addFullTag("delete",$this->_generic->getFullPath("SLS_Bo","DeleteRight",array(),false));
		$xml->addFullTag("edit",$this->_generic->getFullPath("SLS_Bo","EditRight",array(),false));
		
		$pathsHandle = file_get_contents($this->_generic->getPathConfig("configSls")."/rights.xml");		
		$xmlRights = new SLS_XMLToolbox($pathsHandle);
		$result = $xmlRights->getTagsAttributes("//sls_configs/entry",array("login","password","name","firstname","enabled"));
				
		$xml->startTag("accounts");
		for($i=0 ; $i<$count=count($result) ; $i++)
		{
			$xml->startTag("account");
			for($j=0 ; $j<$count2=count($result[$i]["attributes"]) ; $j++)
			{				
				if ($result[$i]["attributes"][$j]["key"] == "password")
					$xml->addFullTag($result[$i]["attributes"][$j]["key"],"******",true);
				else if (SLS_String::contains($result[$i]["attributes"][$j]["key"],"name"))
					$xml->addFullTag($result[$i]["attributes"][$j]["key"],ucwords(strtolower($result[$i]["attributes"][$j]["value"])),true);
				else
					$xml->addFullTag($result[$i]["attributes"][$j]["key"],$result[$i]["attributes"][$j]["value"],true);
			}
			$xml->addFullTag("color",$xmlRights->getTag("//sls_configs/entry[@login='******']/settings/setting[@key='color']"),true);
			$xml->endTag("account");
		}
		$xml->endTag("accounts");
		
		$xml->addFullTag("url_status",$this->_generic->getFullPath("SLS_Bo","ManageRightsStatus",array(),false));
		
		$this->saveXML($xml);
	}
Пример #3
0
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$langs = $this->_generic->getObjectLang()->getSiteLangs();
		$listing = true;
		$errors = array();
		$protocol = $this->_generic->getProtocol();
		$siteXML = $this->_generic->getSiteXML();
		$aliasesSelected = array();
		$componentsSelected = array();
		
		$plugin = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configPlugins")."/plugins.xml"));
		$pluginMobile = $plugin->getTag("//plugins/plugin[@code='mobile']");
		$pluginMobile = (!empty($pluginMobile)) ? true : false;
				
		$controllersXML = $this->_generic->getControllersXML();
		
		$controller = SLS_String::trimSlashesFromString($this->_http->getParam("Controller"));
		$controllers = $controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']");
		if (count($controllers) == 1)
		{
			$controllerID = array_shift($controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']/@id"));
			$protocol = $this->_generic->getControllerProtocol($controllerID);
			$listing = false;
			$xml->addFullTag('request', 'AddAction', true);
			
			if ($this->_http->getParam('reload') == 'true')
			{
				// Get the form informations
				$newAction 				= SLS_String::stringToUrl(ucwords(SLS_String::trimSlashesFromString($this->_http->getParam("actionName"))), "", false);
				$needDynamic 			= SLS_String::trimSlashesFromString($this->_http->getParam("dynamic"));
				$needOffline 			= SLS_String::trimSlashesFromString($this->_http->getParam("offline"));
				$needDefault 			= SLS_String::trimSlashesFromString($this->_http->getParam("default"));
				$searchEngine			= SLS_String::trimSlashesFromString($this->_http->getParam("indexes"));
				$postProtocol			= SLS_String::trimSlashesFromString($this->_http->getParam("protocol"));
				$tpl 					= SLS_String::trimSlashesFromString($this->_http->getParam('template'));
				$aliases				= SLS_String::trimSlashesFromString($this->_http->getParam('domains'));
				$components				= SLS_String::trimSlashesFromString($this->_http->getParam('components'));
				$cache_visibility 		= SLS_String::trimSlashesFromString($this->_http->getParam('cache_visibility'));
				$cache_scope 			= SLS_String::trimSlashesFromString($this->_http->getParam('cache_scope'));
				$cache_expiration 		= SLS_String::trimSlashesFromString($this->_http->getParam('cache_expiration'));
				$cache_responsive 		= SLS_String::trimSlashesFromString($this->_http->getParam('cache_responsive'));
				if (empty($postProtocol))
					$postProtocol = "http";
				$postActionsLang		= array();
				$postTitlesLang			= array();
				$postDescriptionsLang	= array();
				$postKeywordsLang		= array();	
				$toCache			 	= (in_array($cache_visibility,array("public","private"))) ? true : false;
				
				// If responsive wanted
				if ($cache_responsive == "true" && !$pluginMobile)
				{
					// Force Mobile plugin download
					file_get_contents($this->_generic->getFullPath("SLS_Bo",
																  "SearchPlugin",
																  array("Action" => "Download",
																  		"Server" => "4",
																  		"Plugin" => "20",
																  		"token"	 => sha1(substr($this->_generic->getSiteConfig("privateKey"), 0, 3).substr($this->_generic->getSiteConfig("privateKey"), strlen($this->_generic->getSiteConfig("privateKey"))-3))),
																  true));
				}
				
				if (empty($newAction))
					array_push($errors, "Action name can't be empty");
								
				$actionExist 		= $controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller[@name='".$newAction."']");
				if (count($actionExist) == 0)
				{
					if (empty($postProtocol) || ($postProtocol != 'http' && $postProtocol != 'https'))
						array_push($errors, "Protocol must be http or https");
					else 
						$protocol = $postProtocol;
										
					if (!empty($aliases) && is_array($aliases))
						foreach($aliases as $alias)
							array_push($aliasesSelected,$alias);
							
					if (!empty($components) && is_array($components))
						foreach($components as $component)
							array_push($componentsSelected,$component);
						
					$siteLangs = $this->_generic->getObjectLang()->getSiteLangs();
					
					foreach ($siteLangs as $lang)
					{
						// Check Url
						$postLang = trim(SLS_String::stringToUrl(SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-action")), "", false));
						$translationExist = $controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller/scontrollerLangs[scontrollerLang = '".$postLang."']");
						if (empty($postLang))
							array_push($errors, "You need to fill the ".$lang." url translations");
						elseif(count($translationExist) != 0)
							array_push($errors, "You URL translation in ".$lang." is already in use on another action in the same controller");
						else
							$postActionsLang[$lang] =  $postLang;
						
						// Get Titles	
						$postTitlesLang[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-title"));
						// Get Description
						$postDescriptionsLang[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-description"));
						// Get Keywords
						$postKeywordsLang[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-keywords"));
					}
					
					if ($toCache && (!is_numeric($cache_expiration) || $cache_expiration < 0))
						array_push($errors, "Your expiration cache must be a positive time or 0");
					if ($toCache && (!in_array($cache_scope,array("full","partial"))))
						array_push($errors, "Your must describe your cache scope");
					
					if (count($errors) == 0)
					{
						// If an error existing and the controller directory wasn't created
						if (!is_dir($this->_generic->getPathConfig("actionsControllers").$controller))
							mkdir($this->_generic->getPathConfig("actionsControllers").$controller);
						if (!is_file($this->_generic->getPathConfig("actionsControllers").$controller."/__".$controller.".protected.php"))
						{
							$strControllerProtected = '<?php'."\n".
							   '/**'."\n".
							   '* Class generic for the controller '.$newControllerName.''."\n".
							   '* Write here all your generic functions you need in your '.$newControllerName.' Actions'."\n".
							   '* @author SillySmart'."\n".
							   '* @copyright SillySmart'."\n".
							   '* @package Mvc.Controllers.'.$newControllerName.''."\n".
							   '* @see Mvc.Controllers.SiteProtected'."\n".
							   '* @see Sls.Controllers.Core.SLS_GenericController'."\n".
							   '* @since 1.0'."\n".
							   '*/'."\n".
							   'class '.$newControllerName.'ControllerProtected extends SiteProtected'."\n".
							   '{'."\n".
							   t(1).'public function init()'."\n".
							   t(1).'{'."\n".
							   		t(2).'parent::init();'."\n".
							   t(1).'}'."\n".
							   '}'."\n".
							   '?>';
						
							file_put_contents($this->_generic->getPathConfig("actionsControllers").$controller."/__".$controller.".protected.php", $strControllerProtected);
						}
						
						// Create Controller File
						$strControllerAction = '<?php'."\n".
												'/**'."\n".
												'* Class '.$newAction.' into '.$controller.' Controller'."\n".
												'* @author SillySmart'."\n".
												'* @copyright SillySmart'."\n".
												'* @package Mvc.Controllers.'.$controller."\n".
												'* @see Mvc.Controllers.'.$controller.'.ControllerProtected'."\n".
												'* @see Mvc.Controllers.SiteProtected'."\n".
												'* @see Sls.Controllers.Core.SLS_GenericController'."\n".
												'* @since 1.0'."\n".
												'*'."\n".
												'*/'."\n".
												'class '.$controller.$newAction.' extends '.$controller.'ControllerProtected'."\n".
												'{'."\n".
												t(1).'public function init()'."\n".
											   	t(1).'{'."\n".
											   		t(2).'parent::init();'."\n".
											   	t(1).'}'."\n\n".
												t(1).'public function action()'."\n".
												t(1).'{'."\n".
													t(2)."\n".
												t(1).'}'."\n".
												"}\n".
												'?>';
						file_put_contents($this->_generic->getPathConfig("actionsControllers").$controller."/".$newAction.".controller.php", $strControllerAction);
						
						// Create Lang Files
						if (!is_dir($this->_generic->getPathConfig("langs")."Actions/".$controller))
							mkdir($this->_generic->getPathConfig("langs")."Actions/".$controller);
						$langsFiles = array();
						
						foreach ($siteLangs as $lang)
						{
							$strLang = '<?php'."\n".
												'/**'."\n".
												'* '.strtoupper($lang).' File for the action '.$newAction.' into '.$controller.' Controller'."\n".
												'* You can create all your sentences variables here. To create it, follow the exemple :'."\n".
												'* '."\t".'Access it with JS and XSL variable : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'JS\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
												'* '."\t".'Access it with XSL variable only   : $GLOBALS[$GLOBALS[\'PROJECT_NAME\']][\'XSL\'][\'KEY_OF_YOUR_VARIABLE\'] = "value of your sentence in '.strtoupper($lang).'";'."\n".
												'*'."\n".
												'* '."\t".'You can customise the value \'KEY_OF_YOUR_VARIABLE\' and "value of your sentence in '.strtoupper($lang).'" '."\n".
												'* @author SillySmart'."\n".
												'* @copyright SillySmart'."\n".
												'* @package Langs.Actions.'.$controller."\n".
												'* @since 1.0'."\n".
												'*'."\n".
												'*/'."\n".
												'?>';
							file_put_contents($this->_generic->getPathConfig("langs")."Actions/".$controller."/".$newAction.".".strtolower($lang).".lang.php", $strLang);
						}
						
						// Create Views File
						if (!is_dir($this->_generic->getPathConfig("viewsBody").$controller))
							mkdir($this->_generic->getPathConfig("viewsBody").$controller);
						if (!is_dir($this->_generic->getPathConfig("viewsHeaders").$controller))
							mkdir($this->_generic->getPathConfig("viewsHeaders").$controller);
						
						$strBody = '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" xmlns="http://www.w3.org/1999/xhtml">'."\n".
									t(1).'<xsl:template name="'.$newAction.'">'."\n".
										t(2).'<h1>Customize the body of this page in <i>'.$this->_generic->getPathConfig('viewsBody').$controller.'/'.$newAction.'.xsl</i></h1>'."\n".
										t(2).'<h2>And your headers in <i>'.$this->_generic->getPathConfig('viewsHeaders').$controller.'/'.$newAction.'.xsl</i></h2>'."\n".
									t(1).'</xsl:template>'."\n".
									'</xsl:stylesheet>';
						$strHeader = 	'<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" xmlns="http://www.w3.org/1999/xhtml">'."\n".
										t(1).'<xsl:template name="Header'.$newAction.'">'."\n".
										t(1).'</xsl:template>'."\n".
										'</xsl:stylesheet>';
						file_put_contents($this->_generic->getPathConfig("viewsBody").$controller.'/'.$newAction.'.xsl', $strBody);
						file_put_contents($this->_generic->getPathConfig("viewsHeaders").$controller.'/'.$newAction.'.xsl', $strHeader);
						// End of files creation
						
						// XML Modifications
						$metasXML = $this->_generic->getCoreXML('metas');
						// Get the titles
						
						// If default, reset other in current controller
						if (!empty($needDefault))
						{
							$actions = $controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller/@id");
							foreach($actions as $curActionId)
								$controllersXML->setTagAttributes("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller[@id='".$curActionId."']", array('default' => '0'));
						}
												
						$actionId = $this->_generic->generateActionId();
						$xmlAction = "<scontroller name=\"".$newAction."\" needParam=\"";
						$xmlAction .= ($this->_http->getParam("dynamic") == "on") ? "1" : "0";
						$xmlAction .= "\" id=\"".$actionId."\" protocol=\"".$protocol."\"";
						if ($tpl != -1)
							$xmlAction .= " tpl=\"".$tpl."\"";
						if (!empty($aliases))
							$xmlAction .= " domains=\"".implode(",",$aliases)."\"";
						if (!empty($components))
							$xmlAction .= " components=\"".implode(",",$components)."\"";
						if (!empty($needOffline))
							$xmlAction .= " disable=\"1\"";
						if (!empty($needDefault))
							$xmlAction .= " default=\"1\"";
						if ($toCache)
							$xmlAction .= " cache=\"".$cache_visibility."|".$cache_scope."|".(($cache_responsive == "true") ? "responsive" : "no_responsive")."|".$cache_expiration."\"";
						$xmlAction .= "><scontrollerLangs>";
						$strMetas = "<action id=\"".$actionId."\" />";
						$metasXML->appendXMLNode("//sls_configs", $strMetas);
						foreach ($siteLangs as $lang)
						{
							$xmlAction .= "<scontrollerLang lang=\"".$lang."\"><![CDATA[".$postActionsLang[$lang]."]]></scontrollerLang>";
							// Metas
							$metas = "<title lang=\"".$lang."\"><![CDATA[".$postTitlesLang[$lang]."]]></title>";
							$metas .= "<description lang=\"".$lang."\"><![CDATA[".$postDescriptionsLang[$lang]."]]></description>";
							$metas .= "<keywords lang=\"".$lang."\"><![CDATA[".$postKeywordsLang[$lang]."]]></keywords>";
							$metasXML->appendXMLNode("//sls_configs/action[@id=\"".$actionId."\"]", $metas);							
						}
						$xmlAction .= "</scontrollerLangs></scontroller>";
						if (!SLS_String::contains($searchEngine,", "))
							$searchEngine = str_replace(",",", ",$searchEngine);
						if ($searchEngine != "index, follow" && $searchEngine != "noindex, follow" && $searchEngine != "noindex, nofollow" && $searchEngine != "index, nofollow")
							$searchEngine = "index, follow";
						$metasXML->appendXMLNode("//sls_configs/action[@id='".$actionId."']", "<robots><![CDATA[".$searchEngine."]]></robots>");
						$controllersXML->appendXMLNode("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers", $xmlAction);
						file_put_contents($this->_generic->getPathConfig("configSecure")."controllers.xml", $controllersXML->getXML());
						file_put_contents($this->_generic->getPathConfig("configSls")."metas.xml", $metasXML->getXML());
						$controllers = $this->_generic->getTranslatedController("SLS_Bo", "Controllers");
						$this->_generic->redirect($controllers['controller']."/".$controllers['scontroller'].".sls");
					}				
				}
				else 
					array_push($errors, "This generic name is already in use for this controller");
								
				if (!empty($errors))
				{
					$xml->startTag("errors");
						foreach ($errors as $error)
							$xml->addFullTag("error", $error, true);
					$xml->endTag("errors");
					$xml->startTag('form');
					$xml->addFullTag("controllerName", $postControllerName);					
					foreach ($postActionsLang as $key=>$value)
						$xml->addFullTag($key."-action", $value, true);					
					$xml->endTag('form');
					$xml->addFullTag("default",(empty($needDefault)) ? "false" : "true",true);
					$xml->addFullTag("dynamic",(empty($needDynamic)) ? "false" : "true",true);
					$xml->addFullTag("offline",(empty($needOffline)) ? "false" : "true",true);
					$xml->startTag("cache");			
						$xml->addFullTag("cache_visibility", $cache_visibility,true);
						$xml->addFullTag("cache_scope", $cache_scope,true);
						$xml->addFullTag("cache_responsive", $cache_responsive,true);
						$xml->addFullTag("cache_expiration", $cache_expiration,true);
					$xml->endTag("cache");
				}
			}
			else
			{
				$defaultExists = $controllersXML->getTag("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@default='1']/@name");
				$xml->addFullTag("default",(empty($defaultExists)) ? "true" : "false",true);
				$xml->startTag("cache");					
					$xml->addFullTag("cache_visibility", "",true);
					$xml->addFullTag("cache_scope", "",true);
					$xml->addFullTag("cache_responsive","",true);
					$xml->addFullTag("cache_expiration", 0,true);
				$xml->endTag("cache");
			}
			
			// Build all tpls
			$tpls = $this->getAppTpls();
			$xml->startTag("tpls");
			foreach($tpls as $template)
				$xml->addFullTag("tpl",$template,true);
			$xml->endTag("tpls");
			
			$xml->startTag('controller');
			$xml->addFullTag("name", $controller, true);
				$xml->startTag('translations');
				foreach ($langs as $lang)
				{
					$xml->startTag('translation');
						$xml->addFullTag("lang", $lang, true);
						$xml->addFullTag("name", $controllersXML->getTag("//controllers/controller[@name='".$controller."' and @side='user']/controllerLangs/controllerLang[@lang='".$lang."']"), true);
					$xml->endTag('translation');
				}
				$xml->endTag('translations');
			$xml->endTag('controller');
			$xml->addFullTag('request', 'addAction', true);
		}
		else {
			$this->_generic->dispatch('SLS_Bo', 'Controllers');
		}
		
		if (empty($tpl))
			$tpl = $controllersXML->getTag("//controllers/controller[@name='".$controller."' and @side='user']/@tpl");
		
		$xml->addFullTag('protocol', $protocol, true);
		$xml->addFullTag('template', $tpl, true);
		
		$aliases = $siteXML->getTagsAttributes("//configs/domainName/domain",array("alias"));
		$xml->startTag("aliases");
		for($i=0 ; $i<$count=count($aliases) ; $i++)
		{
			$xml->startTag("alias");
				$xml->addFullTag("name",$aliases[$i]["attributes"][0]["value"],true);
				$xml->addFullTag("selected",(in_array($aliases[$i]["attributes"][0]["value"],$aliasesSelected)) ? "true" : "false",true);
			$xml->endTag("alias");
		}
		$xml->endTag("aliases");
		
		$components = $this->_generic->recursiveReadDir($this->_generic->getPathConfig("componentsControllers"), array(), array(0=>"php"));
		$xml->startTag("components");				
		foreach ($components as $component)
		{
			$xml->startTag("component");
				$xml->addFullTag("name", SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($component, "/"), ".controller.php"),true);
				$xml->addFullTag("selected",(in_array(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($component, "/"), ".controller.php"),$componentsSelected)) ? "true" : "false",true);
			$xml->endTag("component");
		}
		$xml->endTag("components");
		
		$this->saveXML($xml);
	}
	/**
	 * 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);
	}
Пример #5
0
	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);
	}
Пример #6
0
	/**
	 * Format XML for a given recordsets collection
	 * 
	 * @access public
	 * @param SLS_XMLToolbox $xml current controller's XML
	 * @param array $recordsets array of PDO recordsets
	 * @param array $options transformations on some columns - delimited by ":". each function can be methods of SLS' classes or php standard function
	 * <code>
     * // Complete example
	 * $newss = $news->searchModels("news",array("user","article_category"));
	 * $xml = $news->pdoToXML($xml,$newss,array("news_excerpt" => array("php:strip_tags","SLS_String:trimStringToLength:100"),
	 *											"news_date" => array("SLS_Date:getDate:FULL_LITTERAL_TIME","php:ucwords"),
	 *											"news_photo" => "SLS_String:getUrlFileImg:_0",
	 *											"news_pdf" => "SLS_String:getUrlFile",
	 *											"news_title" => "php:trim")
	 *						, "all_news/news");
	 * </code>
	 * @param string $nodeName the root node of your model, by default it's your classname in lowercase
	 * @return SLS_XMLToolbox $xml current controller's XML updated
	 * @see SLS_FrontModel::getParams
	 * @see SLS_FrontModel::toXML
	 * @since 1.0.8	 
	 */
	public function pdoToXML($xml,$recordsets,$options=array(),$nodeNames="")
	{
		$nodeName 	= (SLS_String::contains($nodeNames,"/")) ? SLS_String::substrAfterLastDelimiter($nodeNames,"/") : "";
		$nodeNames 	= (SLS_String::contains($nodeNames,"/")) ? SLS_String::substrBeforeFirstDelimiter($nodeNames,"/") : strtolower($this->getTable())."s";
		
		$xml->startTag($nodeNames);
		for($i=0 ; $i<$count=count($recordsets) ; $i++)		
			$xml = $this->toXML($xml,$options,array(),$nodeName,SLS_String::objectToArray($recordsets[$i]));		
		$xml->endTag($nodeNames);
		
		return $xml;
	}
Пример #7
0
	/**
	 * Protect a sql column
	 * 
	 * @param string $col the column to protect
	 * @return string column protected
	 * @since 1.0.7
	 * @example
     * protectColumn("news_id")
     * // will produce "`news_id`"
     * protectColumn("news.news_id")
     * // will produce "`news`.`news_id`"
	 */
	public function protectColumn($col)
	{
		return ((SLS_String::contains($col,'.'))
				? self::ESC.SLS_String::substrBeforeFirstDelimiter($col,'.').self::ESC.'.'.self::ESC.SLS_String::substrAfterFirstDelimiter($col,'.').self::ESC
				: self::ESC.$col.self::ESC);
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$langs = $this->_generic->getObjectLang()->getSiteLangs();
		$errors = array();
		$siteXML = $this->_generic->getSiteXML();		
		$aliasesSelected = array();
		$componentsSelected = array();
		
		$plugin = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configPlugins")."/plugins.xml"));
		$pluginMobile = $plugin->getTag("//plugins/plugin[@code='mobile']");
		$pluginMobile = (!empty($pluginMobile)) ? true : false;
		
		$controllersXML = $this->_generic->getControllersXML();
		$metasXML = $this->_generic->getCoreXML('metas');
		$controller = $this->_http->getParam('Controller');
		$action = $this->_http->getParam('Action');
				
		$actionExist = $controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']");
		$actionId = array_shift($controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']/@id"));
		$protocol = $this->_generic->getActionProtocol($actionId);
		if (count($actionExist) == 1)
		{
			$aliasesChecked = array_shift($controllersXML->getTagsAttributes("//controllers/controller/scontrollers/scontroller[@id='".$actionId."']",array("domains")));
			if (!empty($aliasesChecked))
			{				
				$alias = explode(",",$aliasesChecked["attributes"][0]["value"]);
				foreach($alias as $cur_alias)
					array_push($aliasesSelected,$cur_alias);
			}
			$componentsChecked = array_shift($controllersXML->getTagsAttributes("//controllers/controller/scontrollers/scontroller[@id='".$actionId."']",array("components")));
			if (!empty($componentsChecked))
			{				
				$component = explode(",",$componentsChecked["attributes"][0]["value"]);
				foreach($component as $cur_component)
					array_push($componentsSelected,$cur_component);
			}
			
			$reload = $this->_http->getParam("reload");
			if ($reload == 'true')
			{
				$oldAction  		= SLS_String::trimSlashesFromString($this->_http->getParam("genericName"));
				$newAction 			= SLS_String::stringToUrl(ucwords(SLS_String::trimSlashesFromString($this->_http->getParam("actionName"))), "", false);
				$needDynamic 		= SLS_String::trimSlashesFromString($this->_http->getParam("dynamic"));
				$needOffline 		= SLS_String::trimSlashesFromString($this->_http->getParam("offline"));
				$needDefault 		= SLS_String::trimSlashesFromString($this->_http->getParam("default"));
				$searchEngine 		= SLS_String::trimSlashesFromString($this->_http->getParam("indexes"));
				$postProtocol		= SLS_String::trimSlashesFromString($this->_http->getParam("protocol"));
				$tpl 				= SLS_String::trimSlashesFromString($this->_http->getParam('template'));
				$aliases			= SLS_String::trimSlashesFromString($this->_http->getParam('domains'));
				$components			= SLS_String::trimSlashesFromString($this->_http->getParam('components'));
				$cache_visibility 	= SLS_String::trimSlashesFromString($this->_http->getParam('cache_visibility'));
				$cache_scope 		= SLS_String::trimSlashesFromString($this->_http->getParam('cache_scope'));
				$cache_expiration 	= SLS_String::trimSlashesFromString($this->_http->getParam('cache_expiration'));
				$cache_responsive 	= SLS_String::trimSlashesFromString($this->_http->getParam('cache_responsive'));
				$toCache			 = (in_array($cache_visibility,array("public","private"))) ? true : false;
				
				if ($controller == "Home" && $action == "Index")
				{
					$needDefault = "true";
					$newAction = $oldAction;
				}
				
				// If responsive wanted
				if ($cache_responsive == "true" && !$pluginMobile)
				{
					// Force Mobile plugin download
					file_get_contents($this->_generic->getFullPath("SLS_Bo",
																  "SearchPlugin",
																  array("Action" => "Download",
																  		"Server" => "4",
																  		"Plugin" => "20",
																  		"token"	 => sha1(substr($this->_generic->getSiteConfig("privateKey"), 0, 3).substr($this->_generic->getSiteConfig("privateKey"), strlen($this->_generic->getSiteConfig("privateKey"))-3))),
																  true));
				}
				
				$postActionsLang	= array();
				$postTitlesLang		= array();
				$postDescriptionsLang = array();
				$postKeywordsLang	= array();
				
				// Save Form informations
				$xml->startTag("form");
					$xml->addFullTag("actionName", $newAction, true);
					foreach ($langs as $lang)
					{
						$postLang = trim(SLS_String::stringToUrl(SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-action")), "", false));
						$postOldLang = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-oldAction"));
						if ($postLang != $oldAction)
						{
							$translationExist = $controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller[@name != '".$oldAction."']/scontrollerLangs[scontrollerLang = '".$postLang."']");
						
							if (empty($postLang)) 
								array_push($errors, "You need to fill the ".$lang." url translations");
							elseif(count($translationExist) != 0)
								array_push($errors, "You URL translation in ".$lang." is already in use on another action in the same controller");
							else
								$postActionsLang[$lang] =  $postLang;
						}
						
						// Get Titles	
						$postTitlesLang[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-title"));
						$postDescriptionsLang[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-description"));
						$postKeywordsLang[$lang] = SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-keywords"));
						$xml->addFullTag($lang."-action", $postLang, true);
						$xml->addFullTag($lang."-title", $postTitlesLang[$lang], true);
						$xml->addFullTag($lang."-description", $postDescriptionsLang[$lang], true);
						$xml->addFullTag($lang."-keywords", $postKeywordsLang[$lang], true);
					}
				$xml->endTag("form");
				
				if (empty($postProtocol) || ($postProtocol != 'http' && $postProtocol != 'https'))
						array_push($errors, "Protocol must be http or https");
					else 
						$protocol = $postProtocol;
								
				if (!empty($aliases) && is_array($aliases))
				{
					$aliasesSelected = array();
					foreach($aliases as $alias)
						array_push($aliasesSelected,$alias);
				}
				else
				{
					$aliasesSelected = array();
					$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']", array('domains' => ''));
				}
				
				if ($toCache && (!is_numeric($cache_expiration) || $cache_expiration < 0))
					array_push($errors, "Your expiration cache must be a positive time or 0");
				if ($toCache && (!in_array($cache_scope,array("full","partial"))))
					array_push($errors, "Your must describe your cache scope");
				
				if ($toCache && is_numeric($cache_expiration) && $cache_expiration >= 0 && in_array($cache_scope,array("full","partial")))
					$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']", array('cache' => $cache_visibility.'|'.$cache_scope.'|'.(($cache_responsive == 'true') ? 'responsive' : 'no_responsive').'|'.$cache_expiration));
				if (!$toCache)
					$controllersXML->deleteTagAttribute("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']","cache");
				
				if (!empty($components) && is_array($components))
				{
					$componentsSelected = array();
					foreach($components as $component)
						array_push($componentsSelected,$component);
				}
				else
				{
					$componentsSelected = array();
					$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']", array('components' => ''));
				}
				
				if ((($controller != 'Home' && $controller != 'Default') || (($controller == 'Home' && $action != 'Index') || ($controller == 'Default' && ($action != 'UrlError' && $action != 'BadRequestError' && $action != 'AuthorizationError' && $action != 'ForbiddenError' && $action != 'InternalServerError' && $action != 'TemporaryRedirectError' && $action != 'MaintenanceError')))) && ($oldAction != $newAction)) 
				{
					$newNameExist = $controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$newAction."']");
					if (count($newNameExist) != 0)
						array_push($errors, "The generic action name is already in use in this controller");						
				}
				else 
					$newAction = $oldAction;
				
				if (empty($newAction))
					array_push($errors, "Action name can't be empty.");
					
				if (!empty($aliases))									
					$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']", array('domains' => implode(",",$aliasesSelected)));					
					
				if (!empty($components))									
					$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']", array('components' => implode(",",$componentsSelected)));
								
				$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@name='".$action."' and @id='".$actionId."']", array('disable' => (empty($needOffline)) ? '0' : '1'));					
									
				if ($tpl == -1)
					$controllersXML->deleteTagAttribute("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']", "tpl");
				else
					$controllersXML->setTagAttributes("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']", array('tpl' => $tpl));
				file_put_contents($this->_generic->getPathConfig('configSecure')."controllers.xml", $controllersXML->getXML());

				$dynamic = (($controller != 'Home' && $controller != 'Default') || (($controller == 'Home' && $action != 'Index') || ($controller == 'Default' && ($action != 'UrlError' && $action != 'BadRequestError' && $action != 'AuthorizationError' && $action != 'ForbiddenError' && $action != 'InternalServerError' && $action != 'TemporaryRedirectError' && $action != 'MaintenanceError')))) ? ($needDynamic == 'on') ? "1" : "0" : array_shift($controllersXML->getTags("//controllers/controller[@name='".$controller."' and side='user']/scontrollers/scontroller[@name='".$oldAction."']/@needParam"));
				// If no errors
				if (empty($errors))
				{
					// If default, reset other in current controller
					if (!empty($needDefault))
					{
						$actions = $controllersXML->getTags("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller/@id");
						foreach($actions as $curActionId)
							$controllersXML->setTagAttributes("//controllers/controller[@side='user' and @name='".$controller."']/scontrollers/scontroller[@id='".$curActionId."']", array('default' => '0'));
					}
					
					$controllersXML->setTagAttributes("//controllers/controller/scontrollers/scontroller[@id='".$actionId."']", array("name"=>$newAction,"needParam"=>$dynamic,'protocol'=>$protocol,"default"=>(empty($needDefault) ? '0' : '1')));
					
					foreach ($langs as $lang)
					{
						if (array_key_exists($lang, $postActionsLang))
							$controllersXML->setTag("//controllers/controller/scontrollers/scontroller[@id='".$actionId."']/scontrollerLangs/scontrollerLang[@lang='".$lang."']", $postActionsLang[$lang], true);
						else 
							$controllersXML->setTag("//controllers/controller/scontrollers/scontroller[@id='".$actionId."']/scontrollerLangs/scontrollerLang[@lang='".$lang."']", SLS_String::trimSlashesFromString($this->_http->getParam(strtolower($lang)."-oldAction")), true);
					}
					
					// If generic name is not the same, we modify all files
					if ($oldAction != $newAction)
					{
						// Controller
						$contentController = file_get_contents($this->_generic->getPathConfig('actionsControllers').$controller."/".$oldAction.".controller.php");
						$contentController = str_replace(array(0=>" ".$controller.$oldAction." ", 1=>" ".$oldAction." "), array(0=>" ".$controller.$newAction." ", 1=>" ".$newAction." "), $contentController);
						file_put_contents($this->_generic->getPathConfig('actionsControllers').$controller."/".$newAction.".controller.php", $contentController);
						unlink($this->_generic->getPathConfig('actionsControllers').$controller."/".$oldAction.".controller.php");
						
						//Langs
						foreach ($langs as $lang)
						{
							$contentLang = file_get_contents($this->_generic->getPathConfig('actionLangs').$controller."/".$oldAction.".".$lang.".lang.php");
							$contentLang = str_replace(array(0=>" ".$controller.$oldAction." ", 1=>" ".$oldAction." "), array(0=>" ".$controller.$newAction." ", 1=>" ".$newAction." "), $contentLang);
							file_put_contents($this->_generic->getPathConfig('actionLangs').$controller."/".$newAction.".".$lang.".lang.php", $contentLang);
							unlink($this->_generic->getPathConfig('actionLangs').$controller."/".$oldAction.".".$lang.".lang.php");
						}
						
						// Views
						// Body
						$contentBody = file_get_contents($this->_generic->getPathConfig('viewsBody').$controller."/".$oldAction.".xsl");
						$contentBody = str_replace(array(0=>"name=\"".$oldAction."\">", 1=>$oldAction.".xsl"), array(0=>"name=\"".$newAction."\">", 1=>$newAction.".xsl"), $contentBody);
						file_put_contents($this->_generic->getPathConfig('viewsBody').$controller."/".$newAction.".xsl", $contentBody);
						unlink($this->_generic->getPathConfig('viewsBody').$controller."/".$oldAction.".xsl");
						
						// Headers
						$contentHeader = file_get_contents($this->_generic->getPathConfig('viewsHeaders').$controller."/".$oldAction.".xsl");
						$contentHeader = str_replace(array(0=>"name=\"Header".$oldAction."\">"), array(0=>"name=\"Header".$newAction."\">"), $contentHeader);
						file_put_contents($this->_generic->getPathConfig('viewsHeaders').$controller."/".$newAction.".xsl", $contentHeader);
						unlink($this->_generic->getPathConfig('viewsHeaders').$controller."/".$oldAction.".xsl");
					}
					
					// We now update the XML
					
					foreach ($langs as $lang)
					{
						// Metas
						$metasXML->setTag("//sls_configs/action[@id='".$actionId."']/title[@lang='".$lang."']", $postTitlesLang[$lang], true);
						$metasXML->setTag("//sls_configs/action[@id='".$actionId."']/description[@lang='".$lang."']", $postDescriptionsLang[$lang], true);
						$metasXML->setTag("//sls_configs/action[@id='".$actionId."']/keywords[@lang='".$lang."']", $postKeywordsLang[$lang], true);
					}
					if (!SLS_String::contains($searchEngine,", "))
						$searchEngine = str_replace(",",", ",$searchEngine);
					if ($searchEngine != "index, follow" && $searchEngine != "noindex, follow" && $searchEngine != "noindex, nofollow" && $searchEngine != "index, nofollow")
						$searchEngine = "index, follow";
					$metasXML->setTag("//sls_configs/action[@id='".$actionId."']/robots", $searchEngine, true);
							
					file_put_contents($this->_generic->getPathConfig("configSecure")."controllers.xml", $controllersXML->getXML());
					file_put_contents($this->_generic->getPathConfig("configSls")."metas.xml", $metasXML->getXML());					
				}
				
				if (count($errors) != 0)
				{
					$xml->startTag("errors");
					foreach ($errors as $error)
						$xml->addFullTag("error", $error, true);
					$xml->endTag("errors");
				}
				
				$xml->startTag("cache");					
					$xml->addFullTag("cache_visibility", $cache_visibility,true);
					$xml->addFullTag("cache_scope", $cache_scope,true);
					$xml->addFullTag("cache_expiration", $cache_expiration,true);
					$xml->addFullTag("cache_responsive", $cache_responsive,true);
				$xml->endTag("cache");
			}
			else
			{
				$actionCache = $this->_cache->getAction($actionId);				
				$xml->startTag("cache");					
					$xml->addFullTag("cache_visibility", (is_array($actionCache)) ? $actionCache[0] : "",true);
					$xml->addFullTag("cache_scope", (is_array($actionCache)) ? $actionCache[1] : "",true);
					$xml->addFullTag("cache_expiration", (is_array($actionCache)) ? $actionCache[3] : "",true);
					$xml->addFullTag("cache_responsive", (is_array($actionCache)) ? (($actionCache[2]=="responsive") ? "true" : "") : "",true);
				$xml->endTag("cache");
			}
			$tpl = $controllersXML->getTag("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']/@tpl");
			if (empty($tpl))
				$tpl = $controllersXML->getTag("//controllers/controller[@name='".$controller."' and @side='user']/@tpl");
			
			$controllersXML = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSecure")."controllers.xml"));
			
			$xml->startTag("action");
				$xml->addFullTag("name", $action, true);
				$xml->addFullTag("dynamic", (array_shift($controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']/@needParam")) == '1') ? 'true' : 'false', true);
				$xml->addFullTag("offline", (array_shift($controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']/@disable")) == '1') ? 'true' : 'false', true);
				$xml->addFullTag("default", (array_shift($controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']/@default")) == '1') ? 'true' : 'false', true);
				$xml->addFullTag("indexes", array_shift($metasXML->getTags("//sls_configs/action[@id='".$actionId."']/robots")), true);
				$xml->addFullTag("canBeModified", (($controller != 'Home' && $controller != 'Default') || (($controller == 'Home' && $action != 'Index') || ($controller == 'Default' && ($action != 'UrlError' && $action != 'BadRequestError' && $action != 'AuthorizationError' && $action != 'ForbiddenError' && $action != 'InternalServerError' && $action != 'TemporaryRedirectError' && $action != 'MaintenanceError')))) ? 'true' : 'false', true);
				$xml->startTag("translations");
				foreach ($langs as $lang)
				{
					$xml->startTag("translation");
					$xml->addFullTag("lang", $lang, true);
					$xml->addFullTag("name", array_shift($controllersXML->getTags("//controllers/controller[@name='".$controller."' and @side='user']/scontrollers/scontroller[@name='".$action."']/scontrollerLangs/scontrollerLang[@lang='".$lang."']")) ,true);
					$xml->addFullTag("title", array_shift($metasXML->getTags("//sls_configs/action[@id='".$actionId."']/title[@lang='".$lang."']")),true);
					$xml->addFullTag("description", array_shift($metasXML->getTags("//sls_configs/action[@id='".$actionId."']/description[@lang='".$lang."']")),true);
					$xml->addFullTag("keywords", array_shift($metasXML->getTags("//sls_configs/action[@id='".$actionId."']/keywords[@lang='".$lang."']")),true);
					$xml->endTag("translation");
				}
				$xml->endTag("translations");
			$xml->endTag("action");
			$xml->startTag('controller');
				$xml->addFullTag("name", $controller, true);
				$xml->startTag('translations');
				foreach ($langs as $lang)
				{
					$xml->startTag('translation');
						$xml->addFullTag("lang", $lang, true);	
						$xml->addFullTag("name", $controllersXML->getTag("//controllers/controller[@name='".$controller."' and @side='user']/controllerLangs/controllerLang[@lang='".$lang."']"), true);	
					$xml->endTag('translation');
				}
				$xml->endTag('translations');
			$xml->endTag('controller');
			
			// Build all tpls
			$tpls = $this->getAppTpls();
			$xml->startTag("tpls");
			foreach($tpls as $template)
				$xml->addFullTag("tpl",$template,true);
			$xml->endTag("tpls");
			
			$xml->addFullTag('request', 'modifyAction', true);			
			
			$aliases = $siteXML->getTagsAttributes("//configs/domainName/domain",array("alias"));
			$xml->startTag("aliases");
			for($i=0 ; $i<$count=count($aliases) ; $i++)
			{				
				$xml->startTag("alias");
					$xml->addFullTag("name",$aliases[$i]["attributes"][0]["value"],true);
					$xml->addFullTag("selected",(in_array($aliases[$i]["attributes"][0]["value"],$aliasesSelected)) ? "true" : "false",true);
				$xml->endTag("alias");
			}
			$xml->endTag("aliases");
			
			$components = $this->_generic->recursiveReadDir($this->_generic->getPathConfig("componentsControllers"), array(), array(0=>"php"));
			$xml->startTag("components");				
			foreach ($components as $component)
			{
				$xml->startTag("component");
					$xml->addFullTag("name", SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($component, "/"), ".controller.php"),true);
					$xml->addFullTag("selected",(in_array(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($component, "/"), ".controller.php"),$componentsSelected)) ? "true" : "false",true);
				$xml->endTag("component");
			}
			$xml->endTag("components");
		}
		else 
		{
			$this->_generic->dispatch('SLS_Bo', 'Controllers');
		}
		$xml->addFullTag('protocol', $protocol, true);
		$xml->addFullTag('template', $tpl, true);
		$this->saveXML($xml);
	}
Пример #9
0
	/**
	 * Check if the current admin is authorized to access on this back-office action
	 *
	 * @access public static
	 * @param string $type the type of action ('List'|'Add'|'Modify'|'Delete')
	 * @return int $authorized -1 if not logged, 0 is not authorized, 1 if ok
	 * @since 1.0
	 */
	public static function isAuthorized($role="read",$entity="",$aid="")
	{		
		$generic = SLS_Generic::getInstance();
		$session = $generic->getObjectSession();
		
		$sessionToken = substr(substr(sha1($generic->getSiteConfig("privateKey")),12,31).substr(sha1($generic->getSiteConfig("privateKey")),4,11),6);
		$xmlRights = new SLS_XMLToolbox(file_get_contents($generic->getPathConfig("configSls")."/rights.xml"));
		$authorized = 0;
				
		if (self::isLogged())
		{	
			if ($session->getParam("SLS_SESSION_VALID_".$sessionToken) == "true")
				return 1;
			
			if ($role == "dashboard" && SLS_String::contains($aid,"sls_graph"))
			{
				$result = array_shift($xmlRights->getTags("//sls_configs/entry[@login='******']/action[@id='".$aid."']/@id"));
				$authorized = (!empty($result)) ? 1 : 0;
			}
			else if ($generic->actionIdExists($aid))
			{				
				$result = array_shift($xmlRights->getTags("//sls_configs/entry[@login='******']/action[@id='".$aid."']/@id"));
				$authorized = (!empty($result)) ? 1 : 0;
			}
			else
			{
				$result = array_shift($xmlRights->getTags("//sls_configs/entry[@login='******']/action[@role='".$role."' and @entity='".$entity."']/@id"));				
				$authorized = (!empty($result)) ? 1 : 0;
			}
			
			return $authorized;
		}
		else
			return -1;
	}
Пример #10
0
	/**
	 * 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;
	}
Пример #11
0
	/**
	 * Delete n objects of models
	 * 
	 * @param string $table the current table to delete (default: empty => current model)
	 * @param array $joins the table(s) to join with current table (default: empty => no join)
	 * If you want to natural join: 
	 * <code>array("table_2","table_3","...","table_n")</code> will give 'DELETE FROM table_1 NATURAL JOIN table_2 NATURAL JOIN table_3 ... NATURAL JOIN table_n'
	 * If you want to join with a specific column: 
	 * <code>array(0=>array("table"=>"table_2","column"=>"column_2"),1=>array("table"=>"table_3","column"=>"column_3"))</code>
	 * If you want to inner/left/right join:
	 * <code>array(0=>array("table"=>"table_2","column"=>"column_2","mode"=>"natural"),1=>array("table"=>"table_3","column"=>"column_3","mode"=>"left"))</code>
	 * @param array $clause the clause wanted (default: empty => no clause)
	 * <code>
	 * array
	 * (
	 *		[0] => array
	 *				(
	 *					["column"] = "column_1",
	 *					["value"] = "value_1",
	 *					["mode"] = "like" or "notlike" or "beginwith" or "endwith" or "equal" or "notequal" or "lt" or "le" or "ge" or "gt" or "null" or "notnull"
	 *				)
	 *		[1] => array
	 *				(
	 *					["column"] = "user_department",
	 *					["value"] = "75",
	 *					["mode"] = "like" or "notlike" or "beginwith" or "endwith" or "equal" or "notequal" or "lt" or "le" or "ge" or "gt" or "null" or "notnull"
	 *				)
	 * )
	 * </code>
	 * @return int $count the number of lines deleted
	 * @see SLS_FrontModel::searchModels
	 * @since 1.0.6
	 */
	public function deleteModels($table,$joins,$clause)
	{
		$allowToJoin = false;
		$modeJoin = "inner";
		$modesJoin = array("inner","left","right");
		$columns = array();
		
		/**
		 * TABLE NAME
		 */
		// If table name haven't been filled, try to recover table name from the current model
		if (empty($table))
		{
			$table = (empty($this->_table)) ? substr(get_class($this),0,strlen(get_class($this))-3) : $this->_table;
		}
		// If table name is again empty, throw a Sls Exception
		if (empty($table))
		{
			SLS_Tracing::addTrace(new Exception("Error: Table's name has been omitted"),true);
			return false;
		}
		// If model doesn't exists
		if ($this->_generic->useModel(SLS_String::tableToClass($table),$this->_db->getCurrentDb(),"user") || $this->_generic->useModel(SLS_String::tableToClass($table),$this->_db->getCurrentDb(),"sls"))
		{
			$className = ucfirst(strtolower($this->_db->getCurrentDb()))."_".SLS_String::tableToClass($table);
			$object = new $className();
			foreach($object->getParams() as $key => $value)
				array_push($columns,$key);
		}
		else
		{
			SLS_Tracing::addTrace(new Exception("Error: Table `".$table."` doesn't exist in database `".($this->_db->getCurrentDb())."`"),true);
			return false;
		}
		/**
		 * /TABLE NAME
		 */

		
		/**
		 * JOINS
		 */
		// Get all the columns of the current table
		$columnsMain = $columns;
		$joinMain = $table;
		
		// If we want to join tables
		if (is_array($joins) && !empty($joins))
		{
			// Foreach tables to join
			foreach ($joins as $currentJoin)
			{
				// If we want joins with the clause "using"
				if (is_array($currentJoin))
				{
					// Override join mode ?
					if (array_key_exists("mode",$currentJoin))					
						$modeJoin = (in_array(strtolower($currentJoin["mode"]),$modesJoin)) ? strtolower($currentJoin["mode"]) : array_shift($modesJoin);
					
					$currentJoin = $currentJoin["table"];
				}
				
				// If the table to join doesn't exists in MySQL, throw a Sls Exception
				if (!$this->_generic->useModel(SLS_String::tableToClass($currentJoin),$this->_db->getCurrentDb(),"user") && !$this->_generic->useModel(SLS_String::tableToClass($currentJoin),$this->_db->getCurrentDb(),"sls"))
					SLS_Tracing::addTrace(new Exception("Warning: Table `".$currentJoin."` to join with `".$joinMain."` doesn't exist in database `".(SLS_Generic::getInstance()->getDbConfig("base"))."`"),true);			
				// Else check if we can join
				else 
				{
					$className = ucfirst(strtolower($this->_db->getCurrentDb()))."_".SLS_String::tableToClass($currentJoin);
					$objectJoin = new $className();
					$columnsJoin = array();
					
					// Get all the columns of the table to join
					foreach($objectJoin->getParams() as $key => $value)
						array_push($columnsJoin,$key);
					
					// If we want joins with the clause "using", allow to join and merge the columns of the table to join with all the columns already listed
					if (is_array($currentJoin))
					{
						$allowToJoin = true;
						$columnsMain = array_merge($columnsMain,$columnsJoin);	
					}
					// Else if we want a "NATURAL JOIN", check if we have a common key
					else
					{
						// Foreach columns of the current table
						foreach($columnsMain as $tMain)
						{
							// Foreach columns of the table to join
							foreach($columnsJoin as $tJoin)
							{
								// If we have a common column, allow to join and merge the columns of the table to join with all the columns already listed
								if ($tJoin == $tMain)
								{
									$allowToJoin = true;
									$columnsMain = array_merge($columnsMain,$columnsJoin);
								}
							}
						}
					}
					
					// If we can't join, throw a Sls Exception
					if (!$allowToJoin)
					{
						SLS_Tracing::addTrace(new Exception("Warning: Table `".$currentJoin."` to join with `".$joinMain."` doesn't have a common key"),true);
						$joins = array();
						break;
					}
					
					// Move the reference table
					$joinMain = $currentJoin;
				}
			}
		}
		
		// Build the start of the query
		$sql = "DELETE `".$table."` FROM `".$table."` ";
		
		// If we can join, build the join
		if ($allowToJoin && is_array($joins) && !empty($joins))
		{
			foreach ($joins as $currentJoin)
			{
				if (is_array($currentJoin))
					$sql .= strtoupper($modeJoin)." JOIN "."\n".
					"    `".$currentJoin["table"]."` USING(".$currentJoin["column"].") ";
				else
					$sql .= "NATURAL JOIN "."\n".
					"    `".$currentJoin."` ";
			}
		}
		/**
		 * /JOINS
		 */
				
		
		/**
		 * CLAUSE
		 */
		// If we want a clause where
		if (!empty($clause))
		{			
			$lastSucceeded = false;
			// Foreach items to restrict
			for($i=0 ; $i<count($clause) ; $i++)
			{
				// If column on which you want to apply a restrict clause is in the list of columns collected on the tables
				$columnName = (SLS_String::contains($clause[$i]["column"],".")) ? SLS_String::substrAfterLastDelimiter($clause[$i]["column"],".") : $clause[$i]["column"];				
				if (in_array($columnName,$columnsMain))
				{
					$sql .= ($lastSucceeded) ? " AND " : " WHERE ";
					
					// Build the correct statement
					$clause[$i]["column"] = "`".$clause[$i]["column"]."`";
					switch($clause[$i]["mode"])
					{
						case "like":
							$sql .= ("LOWER(".$clause[$i]["column"].") LIKE ".$this->_db->quote("%".strtolower($clause[$i]["value"])."%"));
							break;
						case "notlike":
							$sql .= ("LOWER(".$clause[$i]["column"].") NOT LIKE ".$this->_db->quote("%".strtolower($clause[$i]["value"])."%"));
							break;							
						case "beginwith":
							$sql .= ("LOWER(".$clause[$i]["column"].") LIKE ".$this->_db->quote(strtolower($clause[$i]["value"])."%"));
							break;
						case "endwith":
							$sql .= ("LOWER(".$clause[$i]["column"].") LIKE ".$this->_db->quote("%".strtolower($clause[$i]["value"])));
							break;
						case "equal":
							$sql .= ("".$clause[$i]["column"]." = ".$this->_db->quote($clause[$i]["value"]));	
							break;
						case "notequal":
							$sql .= ("".$clause[$i]["column"]." != ".$this->_db->quote($clause[$i]["value"]));	
							break;
						case "lt":
							$sql .= ("".$clause[$i]["column"]." < ".$this->_db->quote($clause[$i]["value"]));
							break;
						case "le":
							$sql .= ("".$clause[$i]["column"]." <= ".$this->_db->quote($clause[$i]["value"]));
							break;
						case "ge":
							$sql .= ("".$clause[$i]["column"]." >= ".$this->_db->quote($clause[$i]["value"]));
							break;
						case "gt":
							$sql .= ("".$clause[$i]["column"]." > ".$this->_db->quote($clause[$i]["value"]));
							break;
						case "null":
							$sql .= ("".$clause[$i]["column"]." IS NULL ");
							break;
						case "notnull":
							$sql .= ("".$clause[$i]["column"]." IS NOT NULL ");
							break;
						case "in":
							$clause[$i]["value"] = (is_array($clause[$i]["value"])) ? array_map(array($this->_db, 'quote'),$clause[$i]["value"]) : $clause[$i]["value"];
							$sql .= ("".$clause[$i]["column"]." IN (".((is_array($clause[$i]["value"]) ? implode(",",$clause[$i]["value"]) : $this->_db->quote($clause[$i]["value"]))).") ");
							break;
						case "notin":
							$clause[$i]["value"] = (is_array($clause[$i]["value"])) ? array_map(array($this->_db, 'quote'),$clause[$i]["value"]) : $clause[$i]["value"];
							$sql .= ("    ".$clause[$i]["column"]." NOT IN (".((is_array($clause[$i]["value"]) ? implode(",",$clause[$i]["value"]) : $this->_db->quote($clause[$i]["value"]))).") ");
							break;
						default:
							$sql .= ("LOWER(".$clause[$i]["column"].") LIKE ".$this->_db->quote("%".strtolower($clause[$i]["value"])."%"));
							break;
					}						
					$lastSucceeded = true;
				}
				// Else, throw a Sls Exception
				else
					SLS_Tracing::addTrace(new Exception("Warning: Column ".$clause[$i]["column"]." in clause where doesn't exist in table `".$table."` (and collected tables to join)"),true);
			}
		}
		/**
		 * /CLAUSE
		 */
				
		
		// Try to execute the built query
		try
		{
			return $this->_db->delete($sql);		
		}
		catch (Exception $e)
		{			
			SLS_Tracing::addTrace($e,true);
			return false;
		}
	}
Пример #12
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->_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;
	}
Пример #13
0
	public function getXML()
	{
		# Objects
		$className = ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table);
		$this->_generic->useModel(SLS_String::tableToClass($this->_table),ucfirst(strtolower($this->_db_alias)),"user");
		$this->_object = new $className();
		$this->_table = $this->_object->getTable();
		$this->_langsValues = array();
		if ($this->_object->isMultilanguage())
		{
			$this->_object->setModelLanguage($this->_lang->getLang());
			foreach($this->_langs as $lang)
				$this->_langsValues[$lang] = array();
		}
		else
			$this->_langsValues[$this->_defaultLang] = array();
		$this->_boPath = "//sls_configs/entry[@type='table' and @name='".strtolower($className)."']";
		$boExists = $this->_xmlBo->getTag($this->_boPath);
		if (empty($boExists))		
			$this->_boPath = "//sls_configs/entry/entry[@type='table' and @name='".strtolower($className)."']";
		$this->_db->changeDb($this->_db_alias);
		$redirects = array("list","add","edit");
		# /Objects
		
		# Model comment
		$this->_tableComment = $this->_object->getTableComment($this->_table,$this->_db_alias);		
		if (SLS_String::startsWith($this->_tableComment,"sls:lang:"))
		{
			$key = strtoupper(SLS_String::substrAfterFirstDelimiter($this->_tableComment,"sls:lang:"));
			$this->_tableComment = (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$key])) ? (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$key]) ? $this->_table : $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$key]) : $GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$key];
		}
		if (empty($this->_tableComment))
			$this->_tableComment = $this->_table;
		# /Model comment
		
		# Params
		$this->_object_id = $this->_http->getParam("id");
		# /Params
		
		# Columns definitions
		$this->_columns = array();
		$this->_bearers = array();
		$this->_children = array();

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

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

		# Reload
		$this->_error = false;
		$this->_recordsets = array();
		if ($this->_http->getParam("reload-edit") == "true")
		{	
			$modelParams 		= (is_array($this->_http->getParam($this->_table))) ? $this->_http->getParam($this->_table) : array();
			$properties 		= (is_array($modelParams["properties"])) ? $modelParams["properties"] : array();
			$bearers 			= (is_array($modelParams["bearers"])) ? $modelParams["bearers"] : array();
			$children 			= (is_array($modelParams["children"])) ? $modelParams["children"] : array();
			$childrenToDelete	= (is_array($modelParams["children-to-delete"])) ? $modelParams["children-to-delete"] : array();
			$redirect 			= (in_array(strtolower($this->_http->getParam("redirect")),$redirects)) ? strtolower($this->_http->getParam("redirect")) : array_shift($redirects);
			
			# MAIN MODEL
			uksort($properties,array($this, 'unshiftDefaultLang'));
			foreach($properties as $lang => $columns)
			{
				$this->_object->setModelLanguage($lang);
				
				if (!empty($columns))
				{
					foreach(((is_array($columns)) ? $columns : array($columns)) as $column => $value)
					{
						// Reset old value
						$this->_columns[$column]["values"][$lang] = array();
						
						$functionName = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$column)," ",false)),"");
						
						// Remember values
						if (is_array($value) && array_key_exists("file",$value))
						{
							$value = $value["file"];
							
							if (!is_array($value))
								$value = SLS_String::substrAfterFirstDelimiter($value,$this->_generic->getPathConfig("files"));
						}
						else if (is_array($value))
						{
							$this->_columns[$column]["values"][$lang] = $value;
							
							// MySQL Type Set
							if ($this->_columns[$column]["specific_type"] != 'file')
								$value = implode(",",$value);
						}
						else
						{	
							// Check FK
							if (!empty($value) && $this->_columns[$column]["html_type"] == 'input_ac')
							{
								$fkAlias = ucfirst(strtolower(SLS_String::substrBeforeFirstDelimiter($this->_columns[$column]["ac_fk"],"_")));
								$fkModel = SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($this->_columns[$column]["ac_fk"],"_"));
								$fkClass = $fkAlias."_".$fkModel;
								$this->_generic->useModel($fkModel,$fkAlias,"user");
								$fkObject = new $fkClass();
								
								if ($fkObject->getModel($value) == true)
								{
									$replacements = $fkObject->getParams();
									$fkLabel = $this->_columns[$column]["ac_pattern"];
									foreach($replacements as $keyFk => $valueFk)
										$fkLabel = str_replace($keyFk, $valueFk, $fkLabel);
										
									$this->_columns[$column]["values"][$lang][] = array("label" => $fkLabel, "value" => $value);
								}
								else
									$this->_columns[$column]["values"][$lang][] = "";
							}
							else
								$this->_columns[$column]["values"][$lang][] = $value;
						}
						
						// Setter
						if (!$this->_object->$functionName($value))
						{
							$this->_error = true;
							$this->_columns[$column]["errors"][$lang] = $this->_object->getError($column);
							if ($this->_async)
								$this->_render["errors"][$column] = $this->_columns[$column]["label"]." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_'.strtoupper($this->_columns[$column]["errors"][$lang])];
						}
						
						// Remember value type file
						if ($this->_columns[$column]["html_type"] == 'input_file')
						{
							// No error, take model value
							if (empty($this->_columns[$column]["errors"][$lang]))
							{
								$fileValue = $this->_object->__get($column);
								$this->_columns[$column]["values"][$lang][] = (!empty($fileValue)) ? SLS_String::getUrlFile($fileValue) : "";
							}
							// Else, take uploaded file
							else
							{
								// Modern browsers
								if (array_key_exists("data",$value))
									$value = $value["data"];
								
								if (is_array($value) && array_key_exists("tmp_name",$value))
									$this->_columns[$column]["values"][$lang][] = $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$value["tmp_name"];
							}
						}
					}
				}
				
				$this->_object->save();
			}
			# /MAIN MODEL
			
			# CHILDREN
			foreach($children as $childTable => $childValues)
			{
				$this->_generic->useModel(SLS_String::tableToClass($childTable),$this->_db_alias,"user");
				$childClassName = $this->_db_alias."_".SLS_String::tableToClass($childTable);
				$childObject = new $childClassName();
				$this->_recordsets[$childTable]["pk"] = $childObject->getPrimaryKey();
				$this->_children[$childTable]["model"]["nbChildren"] = (is_array($childValues)) ? count($childValues) : 1;
				
				foreach(((is_array($childValues)) ? $childValues : array($childValues)) as $childItem => $infos)
				{	
					// Child
					$properties = (is_array($infos["properties"])) ? $infos["properties"] : array($infos["properties"]);
					uksort($properties,array($this, 'unshiftDefaultLang'));
					
					$childId = $properties[$this->_defaultLang][$childObject->getPrimaryKey()];
					$needToCreate = (empty($childId)) ? true : false;
					if ($needToCreate)
						$this->_recordsets[$childTable]["ids"][] = $childId = $childObject->giveNextId();
					
					foreach($properties as $lang => $columns)
					{		
						$childObject->setModelLanguage($lang);
						if (!$needToCreate)
							$childObject->getModel($childId);
						
						foreach(((is_array($columns)) ? $columns : array($columns)) as $column => $value)
						{
							// Exclude pk if existed (update)
							if ($column == $this->_recordsets[$childTable]["pk"])
								continue;
							
							$functionName = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$column)," ",false)),"");
							
							// Remember values
							if (is_array($value) && array_key_exists("file",$value))
							{
								$value = $value["file"];
								
								if (!is_array($value))
									$value = SLS_String::substrAfterFirstDelimiter($value,$this->_generic->getPathConfig("files"));
							}
							else if (is_array($value))
							{
								$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang] = $value;
								
								// MySQL Type Set
								if ($this->_children[$childTable]["columns"][$column]["specific_type"] != 'file')
									$value = implode(",",$value);
							}
							else
							{
								// Check FK
								if (!empty($value) && $this->_children[$childTable]["columns"][$column]["html_type"] == 'input_ac')
								{
									$fkAlias = ucfirst(strtolower(SLS_String::substrBeforeFirstDelimiter($this->_children[$childTable]["columns"][$column]["ac_fk"],"_")));
									$fkModel = SLS_String::tableToClass(SLS_String::substrAfterFirstDelimiter($this->_children[$childTable]["columns"][$column]["ac_fk"],"_"));
									$fkClass = $fkAlias."_".$fkModel;
									$this->_generic->useModel($fkModel,$fkAlias,"user");
									$fkObject = new $fkClass();
									
									if ($fkObject->getModel($value) == true)
									{
										$replacements = $fkObject->getParams();
										$fkLabel = $this->_children[$childTable]["columns"][$column]["ac_pattern"];
										foreach($replacements as $keyFk => $valueFk)
											$fkLabel = str_replace($keyFk, $valueFk, $fkLabel);
											
										$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang][] = array("label" => $fkLabel, "value" => $value);
									}
									else
										$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang][] = "";
								}
								else
									$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang][] = $value;
							}
							
							// Setter
							if (!$childObject->$functionName($value))
							{
								$this->_error = true;
								$this->_children[$childTable]["columns"][$column]["errors"][$childItem][$lang] = $childObject->getError($column);
							}
							else
								$this->_children[$childTable]["columns"][$column]["errors"][$childItem][$lang] = "";
							
							// Remember value type file
							if ($this->_children[$childTable]["columns"][$column]["html_type"] == 'input_file')
							{
								// No error, take model value
								if (empty($this->_children[$childTable]["columns"][$column]["errors"][$childItem][$lang]))
								{
									$fileValue = $childObject->__get($column);
									$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang][] = (!empty($fileValue)) ? SLS_String::getUrlFile($fileValue) : "";
								}
								// Else, take uploaded file
								else
								{
									// Modern browsers
									if (is_array($value) && array_key_exists("data",$value))
										$value = $value["data"];
									
									if (is_array($value) && array_key_exists("tmp_name",$value))
										$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang][] = $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$value["tmp_name"];
									else
										$this->_children[$childTable]["columns"][$column]["values"][$childItem][$lang][] = "";
								}
							}
						}
						
						// Force fk setter
						$fkColumn = $this->_xmlFk->getTag("//sls_configs/entry[@tableFk='".strtolower($childClassName)."' and @tablePk='".$this->_db_alias."_".SLS_String::tableToClass($this->_table)."']/@columnFk");
						if (!empty($fkColumn))
						{
							$functionName = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$fkColumn)," ",false)),"");
							$childObject->$functionName($this->_object_id);
						}
						// Create or save
						if ($needToCreate)
							$childObject->create();
						else
							$childObject->save();
					}
					
					$childObject->clear();
					
					// Bearers
					$childBearers = (!empty($infos["bearers"])) ? ((is_array($infos["bearers"])) ? $infos["bearers"] : array($infos["bearers"])) : array();
					foreach($childBearers as $bearerTable => $bearerValues)
					{
						// Bearer object
						$bearerClass = ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($bearerTable);
						$bearerAttributes = array_shift($this->_xmlBearer->getTagsAttributes("//sls_configs/entry[@tableBearer='".$bearerClass."']",array("table1","table2")));
						$this->_generic->useModel(SLS_String::tableToClass($bearerTable),$this->_db_alias,"user");
						$this->_generic->useModel(SLS_String::substrAfterFirstDelimiter($bearerAttributes["attributes"][0]["value"],"_"),SLS_String::substrBeforeFirstDelimiter($bearerAttributes["attributes"][0]["value"],"_"));
						$this->_generic->useModel(SLS_String::substrAfterFirstDelimiter($bearerAttributes["attributes"][1]["value"],"_"),SLS_String::substrBeforeFirstDelimiter($bearerAttributes["attributes"][1]["value"],"_"));
						$bearerObject = new $bearerClass();
						$this->_recordsets[$bearerObject->getTable()]["pk"] = $bearerObject->getPrimaryKey();
						$objectBearerTarget1 = new $bearerAttributes["attributes"][0]["value"]();
						$objectBearerTarget2 = new $bearerAttributes["attributes"][1]["value"]();				
						$setterBearerTarget1 = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$objectBearerTarget1->getPrimaryKey())," ",false)),"");
						$setterBearerTarget2 = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$objectBearerTarget2->getPrimaryKey())," ",false)),"");
						$fkColumn = $this->_xmlFk->getTag("//sls_configs/entry[@tableFk='".strtolower($bearerObject->getDatabase())."_".$bearerObject->getTable()."' and @tablePk='".strtolower($bearerObject->getDatabase())."_".SLS_String::substrAfterFirstDelimiter($bearerAttributes["attributes"][0]["value"],"_")."']/@columnFk");
						
						// Delete old bearers
						$bearerObject->deleteModels($bearerObject->getTable(),array(),array(0=>array("column"=>$fkColumn,"value"=>$childId,"mode"=>"equal")));
						
						// Save new bearers
						foreach($bearerValues as $bearerValue)
						{	
							if ($objectBearerTarget2->getModel($bearerValue) === true)
							{
								$replacements = $objectBearerTarget2->getParams();
								$bearerLabel = $this->_children[$childTable]["bearers"][$bearerObject->getTable()]["ac_pattern"];
								foreach($replacements as $keyBearer => $valueBearer)
									$bearerLabel = str_replace($keyBearer, $valueBearer, $bearerLabel);
								
								$this->_children[$childTable]["bearers"][$bearerObject->getTable()]["values"][$childItem][] = array("label" => $bearerLabel, "value" => $bearerValue);
								
								if (!$this->_error)
								{
									$bearerObject->$setterBearerTarget1($childId);
									$bearerObject->$setterBearerTarget2($bearerValue);
									$bearerObjectId = $bearerObject->create();
									$this->_recordsets[$bearerObject->getTable()]["ids"][] = $bearerObjectId;
									$bearerObject->clear();
								}
							}
						}
					}
				}
			}
			# /CHILDREN
			
			# BEARERS
			foreach($bearers as $bearerTable => $bearerValues)
			{
				// Bearer object
				$bearerClass = ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($bearerTable);
				$bearerAttributes = array_shift($this->_xmlBearer->getTagsAttributes("//sls_configs/entry[@tableBearer='".$bearerClass."']",array("table1","table2")));
				$this->_generic->useModel(SLS_String::tableToClass($bearerTable),$this->_db_alias,"user");
				$this->_generic->useModel(SLS_String::substrAfterFirstDelimiter($bearerAttributes["attributes"][0]["value"],"_"),SLS_String::substrBeforeFirstDelimiter($bearerAttributes["attributes"][0]["value"],"_"));
				$this->_generic->useModel(SLS_String::substrAfterFirstDelimiter($bearerAttributes["attributes"][1]["value"],"_"),SLS_String::substrBeforeFirstDelimiter($bearerAttributes["attributes"][1]["value"],"_"));
				$bearerObject = new $bearerClass();
				$this->_recordsets[$bearerObject->getTable()]["pk"] = $bearerObject->getPrimaryKey();
				$objectBearerTarget1 = new $bearerAttributes["attributes"][0]["value"]();
				$objectBearerTarget2 = new $bearerAttributes["attributes"][1]["value"]();				
				$setterBearerTarget1 = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$objectBearerTarget1->getPrimaryKey())," ",false)),"");
				$setterBearerTarget2 = "set".SLS_String::fullTrim(ucwords(SLS_String::stringToUrl(str_replace("_"," ",$objectBearerTarget2->getPrimaryKey())," ",false)),"");
				$fkColumn = $this->_xmlFk->getTag("//sls_configs/entry[@tableFk='".strtolower($bearerObject->getDatabase())."_".$bearerObject->getTable()."' and @tablePk='".strtolower($bearerObject->getDatabase())."_".SLS_String::substrAfterFirstDelimiter($bearerAttributes["attributes"][0]["value"],"_")."']/@columnFk");
				
				// Delete old bearers
				$bearerObject->deleteModels($bearerObject->getTable(),array(),array(0=>array("column"=>$fkColumn,"value"=>$this->_object_id,"mode"=>"equal")));
				
				// Save new bearers
				foreach($bearerValues as $bearerValue)
				{	
					if ($objectBearerTarget2->getModel($bearerValue) === true)
					{
						$replacements = $objectBearerTarget2->getParams();
						$bearerLabel = $this->_bearers[$bearerObject->getTable()]["ac_pattern"];
						foreach($replacements as $keyBearer => $valueBearer)
							$bearerLabel = str_replace($keyBearer, $valueBearer, $bearerLabel);
						
						$this->_bearers[$bearerObject->getTable()]["values"][] = array("label" => $bearerLabel, "value" => $bearerValue);
						
						if (!$this->_error)
						{
							$bearerObject->$setterBearerTarget1($this->_object_id);
							$bearerObject->$setterBearerTarget2($bearerValue);
							$bearerObjectId = $bearerObject->create();
							$this->_recordsets[$bearerObject->getTable()]["ids"][] = $bearerObjectId;
							$bearerObject->clear();
						}
					}
				}
			}
			# /BEARERS
			
			# CHILDREN-TO-DELETE
			foreach($childrenToDelete as $childTable => $childValues)
			{
				$this->_generic->useModel(SLS_String::tableToClass($childTable),$this->_db_alias,"user");
				$childClassName = $this->_db_alias."_".SLS_String::tableToClass($childTable);
				$childObject = new $childClassName();
				
				foreach(((is_array($childValues)) ? $childValues : array($childValues)) as $childToDelete)
				{
					if ($childObject->getModel($childToDelete) === true)
						$childObject->delete(true);
				}
			}
			# /CHILDREN-TO-DELETE
			
			# If error, delete model & linked recordsets
			if ($this->_error && $this->_object->getModel($this->_object_id))
			{
				if ($this->_async)
				{
					$this->_render["message"] = sprintf($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_ERROR'],$this->_lang->getLang()); 
					// Render
					echo json_encode($this->_render);
					die();
				}
			}
			# /Errors
			
			# All good dude !
			if (!$this->_error)
			{
				if ($this->_async)
				{
					$this->_render["status"] = "OK";
					$this->_render["message"] = $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_GENERIC_SUBMIT_SUCCESS_EDIT'];
				}
				
				else
				{
					$this->pushNotif("success",$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_GENERIC_SUBMIT_SUCCESS_EDIT']);
					
					if ($this->_forward)
					{
						switch ($redirect)
						{
							case "edit":
								# Remember admin settings
								$nodeExists = $this->_xmlRight->getTag("//sls_configs/entry[@login='******']/@login");
								if (!empty($nodeExists))
								{
									$this->_xmlRight->setTag("//sls_configs/entry[@login='******']/settings/setting[@key='edit_callback']","edit");
									$this->_xmlRight->saveXML($this->_generic->getPathConfig("configSls")."/rights.xml");
									$this->_xmlRight->refresh();
								}
								# /Remember admin settings
								$this->_generic->forward($this->_boController,"Modify".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table),array("id"=>$this->_object_id));
								break;
							case "list":
								# Remember admin settings
								$nodeExists = $this->_xmlRight->getTag("//sls_configs/entry[@login='******']/@login");
								if (!empty($nodeExists))
								{
									$this->_xmlRight->setTag("//sls_configs/entry[@login='******']/settings/setting[@key='edit_callback']","list");
									$this->_xmlRight->saveXML($this->_generic->getPathConfig("configSls")."/rights.xml");
									$this->_xmlRight->refresh();
								}
								# /Remember admin settings
								$rememberList = (is_array($this->_session->getParam("SLS_BO_LIST"))) ? $this->_session->getParam("SLS_BO_LIST") : array();
								if (array_key_exists($this->_db_alias."_".$this->_table,$rememberList) && !empty($rememberList[$this->_db_alias."_".$this->_table]))
									$this->_generic->redirect($rememberList[$this->_db_alias."_".$this->_table]);
								else
									$this->_generic->forward($this->_boController,"List".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table));
								break;
						}
					}
				}
			}
			# /All good dude !
		}
		# /Reload
		
		# Page infos
		$langsError = array();
		$columnValues = array();
		$this->_xml->startTag("page");	
			$this->_xml->startTag("model");
				$this->_xml->addFullTag("db",$this->_db_alias,true);
				$this->_xml->addFullTag("table",$this->_table,true);				
				$this->_xml->addFullTag("label",$this->_tableComment,true);
				$this->_xml->addFullTag("multilanguage",($this->_object->isMultilanguage()) ? "true" : "false",true);
				$this->_xml->addFullTag("pk",$this->_object->getPrimaryKey(),true);
			$this->_xml->endTag("model");
			$this->_xml->startTag("urls");
				$this->_xml->addFullTag("list",($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController,"List".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)))) ? $this->_generic->getFullPath($this->_boController,"List".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)) : "",true,array("authorized" => (SLS_BoRights::isAuthorized("read",ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table))) ? "true" : "false"));
				$this->_xml->addFullTag("add",($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController,"Add".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)))) ? $this->_generic->getFullPath($this->_boController,"Add".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)) : "",true,array("authorized" => (SLS_BoRights::isAuthorized("add",ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table))) ? "true" : "false"));
				$this->_xml->addFullTag("populate",$this->_generic->getFullPath($this->_boController,"BoPopulate",array("Db" => ucfirst(strtolower($this->_db_alias)), "Table" => $this->_table)),true,array("authorized" => (SLS_BoRights::getAdminType() == "developer") ? "true" : "false"));
				$this->_xml->addFullTag("edit",($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController,"Modify".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)))) ? $this->_generic->getFullPath($this->_boController,"Modify".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table),array("id" => ""),false) : "",true,array("authorized" => (SLS_BoRights::isAuthorized("edit",ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table))) ? "true" : "false"));
				$this->_xml->addFullTag("clone",($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController,"Clone".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)))) ? $this->_generic->getFullPath($this->_boController,"Clone".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table),array("id" => ""),false) : "",true,array("authorized" => (SLS_BoRights::isAuthorized("clone",ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table))) ? "true" : "false"));
				$this->_xml->addFullTag("delete",($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController,"Delete".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table)))) ? $this->_generic->getFullPath($this->_boController,"Delete".ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table),array("id" => ""),false) : "",true,array("authorized" => (SLS_BoRights::isAuthorized("delete",ucfirst(strtolower($this->_db_alias))."_".SLS_String::tableToClass($this->_table))) ? "true" : "false"));
			$this->_xml->endTag("urls");
			$this->_xml->startTag("columns");
			foreach($this->_columns as $columnName => $infosColumn)
			{
				$this->_xml->startTag("column");
				foreach($infosColumn as $key => $value)
				{
					if (is_array($value) && !in_array($key,array("choices","values","errors")))
						continue;
						
					if ($key == "choices")
					{
						$this->_xml->startTag("choices");
						foreach($value as $currentValue)
							$this->_xml->addFullTag("choice",$currentValue,true);
						$this->_xml->endTag("choices");
					}
					else if ($key == "values")
					{
						$this->_xml->startTag("values");
						foreach($value as $currentLang => $values)
						{	
							if ($this->_async)
							{	
								if (empty($columnValues[$columnName]))
								{
									if ($this->_object->isMultilanguage() && $this->_columns[$columnName]["multilanguage"] == "true" && $currentLang == $this->_lang->getLang())
									{
										$columnValues[$columnName] = ($columnName == "pk_lang") ? $this->_lang->getLang() : $values;
									}
									else if ($currentLang == $this->_defaultLang)
									{
										$columnValues[$columnName] = ($columnName == "pk_lang") ? $this->_lang->getLang() : $values;
									}
								}
							}
								
							foreach($values as $currentValue)
							{
								if (is_array($currentValue))
									$this->_xml->addFullTag("value",$currentValue["value"],true,array("lang"=>$currentLang,"label"=>$currentValue["label"]));
								else
								{
									if ($this->_columns[$columnName]["specific_type"] == 'file' && $this->_columns[$columnName]["specific_type_extended"] == 'all')
									{
										$img = "false";
										if (file_exists($this->_generic->getPathConfig("coreImg")."BO-2014/Mime-Types/".strtolower(str_replace("/","-",SLS_String::getExtensionMimeType(SLS_String::substrAfterLastDelimiter($currentValue,"."))).".png")))
										{
											$mime = $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$this->_generic->getPathConfig("coreImg")."BO-2014/Mime-Types/".strtolower(str_replace("/","-",SLS_String::getExtensionMimeType(SLS_String::substrAfterLastDelimiter($currentValue,"."))).".png");
											if (SLS_String::startsWith(SLS_String::getExtensionMimeType(SLS_String::substrAfterLastDelimiter($currentValue,".")),"image/"))
												$img = "true";
										}
										else
											$mime = $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$this->_generic->getPathConfig("coreImg")."BO-2014/Mime-Types/application-octet-stream.png";
										$this->_xml->addFullTag("value",$currentValue,true,array("lang"=>$currentLang,"img"=>$img,"mime"=>$mime));
									}
									else if ($this->_columns[$columnName]["specific_type"] == 'file' && $this->_columns[$columnName]["specific_type_extended"] == 'img')
									{
										$image = $currentValue;
										if (SLS_String::contains($image,$this->_generic->getSiteConfig("domainName")."/"))
											$image = SLS_String::substrAfterFirstDelimiter($image,$this->_generic->getSiteConfig("domainName")."/");
										$this->_xml->addFullTag("value",$currentValue,true,array("lang"=>$currentLang,"size"=>(file_exists($image)) ? filesize($image) : 0));
									}
									else
										$this->_xml->addFullTag("value",$currentValue,true,array("lang"=>$currentLang));
								}
							}
						}
						$this->_xml->endTag("values");
					}
					else if ($key == "errors")
					{
						$this->_xml->startTag("errors");
						foreach($value as $currentLang => $currentValue)
						{
							$this->_xml->addFullTag("error",$infosColumn["label"]." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_'.strtoupper($currentValue)],true,array("lang"=>$currentLang));
							if (!in_array($currentLang,$langsError))
							{
								$this->pushNotif("error",sprintf($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_ERROR'],$currentLang));
								$langsError[] = $currentLang;
							}
						}
						$this->_xml->endTag("errors");
					}
					else
						$this->_xml->addFullTag($key,$value,true);
				}
				$this->_xml->endTag("column");
			}
			$this->_xml->endTag("columns");
			
			// If quick-edit view
			if ($this->_async)
			{
				// Render
				$this->_render["status"] = "OK";
				$this->_render["result"] = $columnValues;
				echo json_encode($this->_render);
				die();
			}
			
			$this->_xml->startTag("bearers");
			foreach($this->_bearers as $bearerTable => $infosColumn)
			{
				$this->_xml->startTag("column");
				foreach($infosColumn as $key => $value)
				{
					if (is_array($value) && !in_array($key,array("choices","values")))
						continue;
						
					if ($key == "choices")
					{
						$this->_xml->startTag("choices");
						foreach($value as $currentValue)
							$this->_xml->addFullTag("choice",$currentValue,true);
						$this->_xml->endTag("choices");
					}
					else if ($key == "values")
					{
						$this->_xml->startTag("values");
						foreach($value as $currentValue => $currentValues)
							$this->_xml->addFullTag("value",$currentValues["value"],true,array("lang"=>$this->_defaultLang,"label"=>$currentValues["label"]));
						$this->_xml->endTag("values");
					}
					else
						$this->_xml->addFullTag($key,$value,true);
				}
				$this->_xml->endTag("column");
			}
			$this->_xml->endTag("bearers");
			$this->_xml->startTag("children");
			foreach($this->_children as $childTable => $childInfos)
			{
				$this->_xml->startTag("child");
					$this->_xml->startTag("model");
					foreach($childInfos["model"] as $key => $value)
						$this->_xml->addFullTag($key,$value,true);
					$this->_xml->endTag("model");
					$this->_xml->startTag("urls");
					foreach($childInfos["urls"] as $key => $value)
						$this->_xml->addFullTag($key,$value["url"],true,array("authorized" => $value["authorized"]));
					$this->_xml->endTag("urls");
					$this->_xml->startTag("columns");
					foreach($childInfos["columns"] as $columnName => $infosColumn)
					{
						$this->_xml->startTag("column");
						foreach($infosColumn as $key => $value)
						{
							if (is_array($value) && !in_array($key,array("choices","values","errors")))
								continue;
								
							if ($key == "choices")
							{
								$this->_xml->startTag("choices");
								foreach($value as $currentValue)
									$this->_xml->addFullTag("choice",$currentValue,true);
								$this->_xml->endTag("choices");
							}
							else if ($key == "values")
							{
								$this->_xml->startTag("values");
								foreach($value as $offset => $valuesChildren)
								{
									$this->_xml->startTag("record");
									foreach($valuesChildren as $currentLang => $values)
									{
										foreach($values as $currentValue)
										{
											if (is_array($currentValue))
												$this->_xml->addFullTag("value",$currentValue["value"],true,array("lang"=>$currentLang,"label"=>$currentValue["label"]));
											else
											{
												if ($this->_children[$childTable]["columns"][$columnName]["specific_type"] == 'file' && $this->_children[$childTable]["columns"][$columnName]["specific_type_extended"] == 'all')
												{
													$img = "false";
													if (file_exists($this->_generic->getPathConfig("coreImg")."BO-2014/Mime-Types/".strtolower(str_replace("/","-",SLS_String::getExtensionMimeType(SLS_String::substrAfterLastDelimiter($currentValue,"."))).".png")))
													{
														$mime = $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$this->_generic->getPathConfig("coreImg")."BO-2014/Mime-Types/".strtolower(str_replace("/","-",SLS_String::getExtensionMimeType(SLS_String::substrAfterLastDelimiter($currentValue,"."))).".png");
														if (SLS_String::startsWith(SLS_String::getExtensionMimeType(SLS_String::substrAfterLastDelimiter($currentValue,".")),"image/"))
															$img = "true";
													}
													else
														$mime = $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$this->_generic->getPathConfig("coreImg")."BO-2014/Mime-Types/application-octet-stream.png";
													$this->_xml->addFullTag("value",$currentValue,true,array("lang"=>$currentLang,"img"=>$img,"mime"=>$mime));
												}
												else if ($this->_children[$childTable]["columns"][$columnName]["specific_type"] == 'file' && $this->_children[$childTable]["columns"][$columnName]["specific_type_extended"] == 'img')
												{
													$image = $currentValue;
													if (SLS_String::contains($image,$this->_generic->getSiteConfig("domainName")."/"))
														$image = SLS_String::substrAfterFirstDelimiter($image,$this->_generic->getSiteConfig("domainName")."/");
													$this->_xml->addFullTag("value",$currentValue,true,array("lang"=>$currentLang,"size"=>(file_exists($image)) ? filesize($image) : 0));
												}
												else
													$this->_xml->addFullTag("value",$currentValue,true,array("lang"=>$currentLang));
											}
										}
									}
									$this->_xml->endTag("record");
								}
								$this->_xml->endTag("values");
							}
							else if ($key == "errors")
							{
								$this->_xml->startTag("errors");
								foreach($value as $currentLang => $currentValues)
								{
									$this->_xml->startTag("record");
									foreach($currentValues as $currentLang => $currentValue)
									{
										if (!empty($currentValue))
										{
											$this->_xml->addFullTag("error",$infosColumn["label"]." ".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_'.strtoupper($currentValue)],true,array("lang"=>$currentLang));
											if (!in_array($currentLang,$langsError))
											{
												$this->pushNotif("error",sprintf($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_ERROR'],$currentLang));
												$langsError[] = $currentLang;
											}
										}
										else
											$this->_xml->addFullTag("error","",true,array("lang"=>$currentLang));
									}
									$this->_xml->endTag("record");
								}
								$this->_xml->endTag("errors");
							}
							else
								$this->_xml->addFullTag($key,$value,true);
						}
						$this->_xml->endTag("column");
					}
					$this->_xml->endTag("columns");
					$this->_xml->startTag("bearers");
					foreach($this->_children[$childTable]["bearers"] as $bearerTable => $infosColumn)
					{
						$this->_xml->startTag("column");
						foreach($infosColumn as $key => $value)
						{
							if (is_array($value) && !in_array($key,array("choices","values")))
								continue;
								
							if ($key == "choices")
							{
								$this->_xml->startTag("choices");
								foreach($value as $currentValue)
									$this->_xml->addFullTag("choice",$currentValue,true);
								$this->_xml->endTag("choices");
							}
							else if ($key == "values")
							{
								$this->_xml->startTag("values");
								foreach($value as $childItem => $values)
								{
									$this->_xml->startTag("record");
									foreach($values as $currentValue => $currentValues)
										$this->_xml->addFullTag("value",$currentValues["value"],true,array("lang"=>$this->_defaultLang,"label"=>$currentValues["label"]));
									$this->_xml->endTag("record");
								}
								$this->_xml->endTag("values");
							}
							else
								$this->_xml->addFullTag($key,$value,true);
						}
						$this->_xml->endTag("column");
					}
					$this->_xml->endTag("bearers");
				$this->_xml->endTag("child");
			}
			$this->_xml->endTag("children");
		$this->_xml->endTag("page");
		# /Page infos
		
		return $this->_xml;
	}
	/**
	 * Read recursively path & sub-paths of js file
	 *
	 * @access private
	 * @param string $path the root path
	 * @param array &$arrayPath reference array, it will contains paths
	 * @param array &$arrayFilename reference array, it will contains filenames
	 * @param array $pathExclu array of ignore paths
	 * @since 1.0
	 */
	private function recursiveRead($path,&$arrayPath, &$arrayFilename, $pathExclu=array())
	{ 
		if (substr($path, strlen($path)-1, 1) != "/")
			$path .= "/";
				
		if (@is_dir($path))
		{
			$handle = opendir($path);			
			while (false !== ($object = readdir($handle))) 
			{
				if (is_dir($path.$object) && substr($object, 0, 1) != ".") 
					$this->recursiveRead($path.$object,$arrayPath, $arrayFilename,$pathExclu);				
				if (substr($object, 0, 1) != "." && is_file($path.$object) && SLS_String::getFileExtension($object) == "js" && !in_array($path, $pathExclu)) 
				{
					array_push($arrayPath, $path.$object.((!SLS_String::contains($object,"?")) ? "?".$this->_generic->getSiteConfig("versionName") : ""));
					array_push($arrayFilename, $object);
				}		
			}
			closedir($handle);
		}
	}	
Пример #15
0
	/**
	 * Clean cache params (internal method)
	 * 
	 * @access private
	 * @param string $key key to check
	 * @param string $value value to check
	 * @return string value cleaned
	 * @since 1.0.9
	 */
	private function getCacheParam($key,$value="")
	{
		switch ($key)
		{
			case "type":
				return (!in_array(strtolower($value),array("static","component","action"))) ? "action" : strtolower($value);
				break;
			case "visibility":
				return (!in_array(strtolower($value),array("private","public"))) ? "private" : strtolower($value);
				break;
			case "responsive":
				return (!in_array(strtolower($value),array("responsive","no_responsive"))) ? "no_responsive" : strtolower($value);
				break;
			case "controller":
				return (empty($value)) ? "controller_".SLS_String::substrAfterFirstDelimiter(strtolower($this->_generic->getControllerId()),"c_") : strtolower($value);
				break;
			case "action":
				return (empty($value)) ? "action_".SLS_String::substrAfterFirstDelimiter(strtolower($this->_generic->getActionId()),"a_") : strtolower($value);
				break;
			case "component":
				return "component_".$value;
				break;
			case "static":
				return "static_".$value;
				break;
			case "uri":
				if (empty($value))
				{
					$bind = $this->_generic->getTranslatedController($this->_generic->getGenericControllerName(),$this->_generic->getGenericScontrollerName());
					$value = "/".$bind["controller"]."/".$bind["scontroller"];
					$params = $this->_generic->getObjectHttpRequest()->getParams();
					uksort($params,"strcasecmp");	
					foreach($params as $key => $val)
					{
						if (!in_array($key,array("mode","smode")))
						{
							if (is_array($val))
							{
								foreach($val as $arr_key => $arr_value)
									$value .= "/".$key."[".$arr_key."]/".$arr_value; 
							}
							else
								$value .= "/".$key."/".$val;
						}
					}
							
					if (empty($value))
						$value = "/";
				}
				
				if (SLS_String::contains($value,"#")) // Remove before anchor
					$value = SLS_String::substrBeforeFirstDelimiter($value,"#");		
				if ($this->_generic->urlRewriteEnabled()) // If rewrite, remove after ?
					$value = SLS_String::substrBeforeFirstDelimiter($value,"?");
					
				$value = SLS_String::stringToUrl($value,"#"); // Remove forbidden chars and join querystring parameters with # glue
				$value = mb_substr($value,0,250,"UTF-8"); // Cut file name at 255 chars for rubbish OS (250 + 5 reserved for extension .xml|.html)
				return $value;
				break;
			default:
				return $value;
		}
	}
	public function action()
	{
		$user 	= $this->hasAuthorative();
		$xml 	= $this->getXML();
		$xml	= $this->makeMenu($xml);
		$siteXML = $this->_generic->getSiteXML();
		
		$googleSettings = array();
		
		if ($this->_http->getParam("reload") == "true")
		{
			$googleSettings = $this->_http->getParam("ga");
			
			$siteXML->setTag("//configs/google/setting[@name='ua']",trim($googleSettings["ua"]));
			$siteXML->setTag("//configs/google/setting[@name='apiKey']",trim($googleSettings["apiKey"]));
			$siteXML->setTag("//configs/google/setting[@name='clientId']",trim($googleSettings["clientId"]));
			$siteXML->setTag("//configs/google/setting[@name='accountId']",trim($googleSettings["accountId"]));
			$siteXML->saveXML($this->_generic->getPathConfig("configSecure")."site.xml");
			$siteXML->refresh();
			
			if (!empty($googleSettings["ua"]))
			{
				$googleSettings["ua"] = (SLS_String::startsWith(trim(strtolower($googleSettings["ua"])),"ua-")) ? $googleSettings["ua"] : "UA-".$googleSettings["ua"];
				$templates = scandir($this->_generic->getPathConfig("viewsTemplates"));
				foreach($templates as $template)
				{
					if (!SLS_String::startsWith($template,"."))
					{
						$templateContent = file_get_contents($this->_generic->getPathConfig("viewsTemplates").$template);
						
						if (SLS_String::contains($templateContent,"<!-- GA loading -->") && SLS_String::contains($templateContent,"_gaq.push(['_setAccount'"))
						{
							$oldUa = trim(str_replace("'","",SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($templateContent,"_gaq.push(['_setAccount',"),"]")));
							if ($oldUa != $googleSettings["ua"])
							{
								$templateContent = str_replace("_gaq.push(['_setAccount', '".$oldUa."']);","_gaq.push(['_setAccount', '".$googleSettings["ua"]."']);",$templateContent);
								file_put_contents($this->_generic->getPathConfig("viewsTemplates").$template,$templateContent);
							}
						}
						else
						{
							$newContent = "";
							$templateLines = explode("\n",$templateContent);
							
							for($i=0 ; $i<$count=count($templateLines) ; $i++)
							{
								$line = $templateLines[$i];
								
								if (SLS_String::contains($line,"</body>"))
								{
									$newContent .= t(4)."<!-- GA loading -->"."\n".
													t(4)."<xsl:if test=\"//Statics/Sls/Configs/site/isProd = '1'\">"."\n".
														t(5)."<script type=\"text/javascript\">"."\n".
															t(6)."var _gaq = _gaq || [];"."\n".
															t(6)."_gaq.push(['_setAccount', '".$googleSettings["ua"]."']);"."\n".
															t(6)."_gaq.push(['_trackPageview']);"."\n".
															t(6)."(function() {"."\n".
																t(7)."var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;"."\n".
																t(7)."ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';"."\n".
																t(7)."var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);"."\n".
															t(6)."})();"."\n".
														t(5)."</script>"."\n".
													t(4)."</xsl:if>"."\n".
													t(4)."<!-- /GA loading -->"."\n\n";
								}
								
								$newContent .= $line."\n";
							}
							
							file_put_contents($this->_generic->getPathConfig("viewsTemplates").$template,$newContent);
						}
					}
				}
			}
			
			$xml->addFullTag("success","Your settings have been saved.",true);
		}
		else
		{
			$googleSettings["ua"] = $siteXML->getTag("//configs/google/setting[@name='ua']");
			$googleSettings["apiKey"] = $siteXML->getTag("//configs/google/setting[@name='apiKey']");
			$googleSettings["clientId"] = $siteXML->getTag("//configs/google/setting[@name='clientId']");
			$googleSettings["accountId"] = $siteXML->getTag("//configs/google/setting[@name='accountId']");
		}
		
		$xml->startTag("google");
		foreach($googleSettings as $key => $value)
			$xml->addFullTag($key,$value,true);
		$xml->endTag("google");
		
		$this->saveXML($xml);		
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);
		$langs = $this->_generic->getObjectLang()->getSiteLangs();
		$listing = true;
		$errors = array();
		
		// Get user controllers listing
		$controllersXML = $this->_generic->getControllersXML();
		$controllers = $controllersXML->getTags("//controllers/controller[@side='user']/@id");		
		$xml->startTag("controllers");
		foreach($controllers as $controller)
		{
			$controller_id = $controller;
			$controller_tpl = $controllersXML->getTag("//controllers/controller[@id='".$controller_id."']/@tpl");
			$controller = $controllersXML->getTag("//controllers/controller[@id='".$controller_id."']/@name");
			$xml->startTag("controller");
			$xml->addFullTag("name",$controller,"true");
			$xml->addFullTag("id",$controller_id,"true");
			$xml->addFullTag("tpl",(!empty($controller_tpl)) ? $controller_tpl : $controller_tpl = "default","true");
			$xml->addFullTag("canBeDeleted",($controller == 'Home' || $controller == 'Default') ? 'false' : 'true', true);
			$scontrollers = $controllersXML->getTags("//controllers/controller[@name='".$controller."']/scontrollers/scontroller/@id");			
			$xml->startTag("scontrollers");
			foreach($scontrollers as $scontroller)
			{
				$scontroller_id = $scontroller;
				$scontroller_tpl = $controllersXML->getTag("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@id='".$scontroller_id."']/@tpl");
				$scontroller_cache = $controllersXML->getTag("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@id='".$scontroller_id."']/@cache");
				if (!SLS_String::contains($scontroller_cache,"|"))
					$scontroller_cache = "false";
				 
				$scontroller = $controllersXML->getTag("//controllers/controller[@name='".$controller."']/scontrollers/scontroller[@id='".$scontroller_id."']/@name");				
				$xml->startTag("scontroller");
					$xml->addFullTag("name",$scontroller,true);
					$xml->addFullTag("id",$scontroller_id,true);
					$xml->addFullTag("cache",$scontroller_cache,true);
					$xml->addFullTag("tpl",(!empty($scontroller_tpl)) ? $scontroller_tpl : $controller_tpl,true);
					if (($controller == 'Home' && ($scontroller == 'Index')) || ($controller == 'Default' && ($scontroller == 'UrlError' || $scontroller == 'BadRequestError' || $scontroller == 'TemporaryRedirectError' || $scontroller == 'MaintenanceError' || $scontroller == 'AuthorizationError' || $scontroller == 'ForbiddenError' || $scontroller == 'InternalServerError')))
						$xml->addFullTag("canBeDeleted",'false',true);
					else 
						$xml->addFullTag("canBeDeleted",'true',true);
				$xml->endTag("scontroller");
			}
			$xml->endTag("scontrollers");	
			$xml->endTag("controller");
		}
		$xml->endTag("controllers");
		$xml->startTag("statics");
		$statics = $this->_generic->recursiveReadDir($this->_generic->getPathConfig("staticsControllers"), array(), array(0=>"php"));
		foreach ($statics as $static)
		{			
			$static = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($static, "/"), ".controller.php");
			$cache = $this->_cache->getObject(strtolower($static),"statics","visibility")."|".$this->_cache->getObject(strtolower($static),"statics","scope")."|".$this->_cache->getObject(strtolower($static),"statics","responsive")."|".$this->_cache->getObject(strtolower($static),"statics","expire");
			if ($cache == "|||")
				$cache = "false";
			$xml->startTag("static");
				$xml->addFullTag("id", strtolower($static),true);
				$xml->addFullTag("name", $static,true);
				$xml->addFullTag("cache",$cache,true);
			$xml->endTag("static");
		}
		$xml->endTag("statics");
		$xml->startTag("components");
		$components = $this->_generic->recursiveReadDir($this->_generic->getPathConfig("componentsControllers"), array(), array(0=>"php"));
		foreach ($components as $component)
		{
			$component = SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterLastDelimiter($component, "/"), ".controller.php");
			$cache = $this->_cache->getObject(strtolower($component),"components","visibility")."|".$this->_cache->getObject(strtolower($component),"components","scope")."|".$this->_cache->getObject(strtolower($static),"statics","responsive")."|".$this->_cache->getObject(strtolower($component),"components","expire");
			if ($cache == "|||")
				$cache = "false";
			$xml->startTag("component");
				$xml->addFullTag("id", strtolower($component),true);
				$xml->addFullTag("name", $component,true);
				$xml->addFullTag("cache",$cache,true);
			$xml->endTag("component");
		}
		$xml->endTag("components");
		$xml->addFullTag('request', 'listing', true);
		$this->registerLink('ADDACTION', 'SLS_Bo', 'AddAction', false);
		$this->registerLink('ADDSTATICCONTROLLER', 'SLS_Bo', 'AddStaticController', false);
		$this->registerLink('EDITSTATICCONTROLLER', 'SLS_Bo', 'EditStaticController', false);
		$this->registerLink('DELSTATICCONTROLLER', 'SLS_Bo', 'DeleteStaticController', false);
		$this->registerLink('ADDCOMPONENTCONTROLLER', 'SLS_Bo', 'AddComponentController', false);
		$this->registerLink('EDITCOMPONENTCONTROLLER', 'SLS_Bo', 'EditComponentController', false);
		$this->registerLink('DELCOMPONENTCONTROLLER', 'SLS_Bo', 'DeleteComponentController', false);
		$this->registerLink('EDITACTION', 'SLS_Bo', 'EditAction', false);
		$this->registerLink('DELACTION', 'SLS_Bo', 'DeleteAction', false);
		$this->registerLink('ADDCONTROLLER', 'SLS_Bo', 'AddController', false);
		$this->registerLink('EDITCONTROLLER', 'SLS_Bo', 'EditController', false);
		$this->registerLink('FLUSHCACHE', 'SLS_Bo', 'FlushCache', false);
		$this->registerLink('DELCONTROLLER', 'SLS_Bo', 'DeleteController', false);
		$this->saveXML($xml);		
	}
Пример #18
0
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);

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

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

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

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

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

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

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

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

			$xmlNew = '';

			# columns

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

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

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

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

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

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


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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		$this->saveXML($xml);
	}
Пример #19
0
	/**
	 * Contains recursive
	 * 
	 * @param string $hay the string in which you search
	 * @param mixed $needles the string or the array of occurences searched
	 * @return mixed false if not contain, else occurence found
	 */
	public function containsRecursive($hay,$needles)
	{
		if (is_array($needles))
		{
			foreach($needles as $needle)
			{				
				if (SLS_String::contains($hay,$needle))				
					return $needle;
			}
		}
		else
			return SLS_String::contains($hay,$needles);
			
		return false;
	}
	public function action()
	{
		set_time_limit(0);
		
		$user = $this->hasAuthorative();
		$errors = array();
		$sql = SLS_Sql::getInstance();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);

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

		if($slsGraphQuery->getModel($slsGraphQueryId) === false)
			return null;

		$this->_generic->useModel("Sls_graph_query_column",$this->defaultDb,"sls");
		$className = ucfirst($this->defaultDb)."_Sls_graph_query_column";
		$slsGraphQueryColumn = new $className();
		
		$this->_generic->useModel("Sls_graph_query_join",$this->defaultDb,"sls");
		$className = ucfirst($this->defaultDb)."_Sls_graph_query_join";
		$slsGraphQueryJoin = new $className();
		
		$this->_generic->useModel("Sls_graph_query_where",$this->defaultDb,"sls");
		$className = ucfirst($this->defaultDb)."_Sls_graph_query_where";
		$slsGraphQueryWhere = new $className();
		
		$this->_generic->useModel("Sls_graph_query_group",$this->defaultDb,"sls");
		$className = ucfirst($this->defaultDb)."_Sls_graph_query_group";
		$slsGraphQueryGroup = new $className();
		
		$this->_generic->useModel("Sls_graph_query_order",$this->defaultDb,"sls");
		$className = ucfirst($this->defaultDb)."_Sls_graph_query_order";
		$slsGraphQueryOrder = new $className();
		
		$this->_generic->useModel("Sls_graph_query_limit",$this->defaultDb,"sls");
		$className = ucfirst($this->defaultDb)."_Sls_graph_query_limit";
		$slsGraphQueryLimit = new $className();
		$db = SLS_Sql::getInstance();
		$render = "";

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

		if (!empty($joins))
		{
			for($j=0 ; $j<$countJ=count($joins) ; $j++)
			{
				$tables[$joins[$j]->sls_graph_query_join_table] = $joins[$j]->sls_graph_query_join_table_alias;
			}
		}

		$whereRoot = null;
		if(!empty($wheres))
			$whereRoot = $wheres[0];

		$groups = $slsGraphQueryGroup->searchModels("sls_graph_query_group",array(),array(0=>array("column"=>"sls_graph_query_id","value"=>$slsGraphQueryId,"mode"=>"equal")),array(),array(array("column"=>"sls_graph_query_group_id","order"=>"asc")));
		$orders = $slsGraphQueryOrder->searchModels("sls_graph_query_order",array(),array(0=>array("column"=>"sls_graph_query_id","value"=>$slsGraphQueryId,"mode"=>"equal")),array(),array(array("column"=>"sls_graph_query_order_id","order"=>"asc")));
		$limit = array_shift($slsGraphQueryLimit->searchModels("sls_graph_query_limit",array(),array(0=>array("column"=>"sls_graph_query_id","value"=>$slsGraphQueryId,"mode"=>"equal")),array(),array(array("column"=>"sls_graph_query_limit_id","order"=>"asc"))));

		$render = '';

		// SELECT
		$sql = "SELECT "."\n";
		$nbColumns = count($columns);

		$columnsAggregation = array_filter($columns, array($this,'filterAggregate'));

		if (!empty($columns))
		{
			if($nbColumns == 1 && !empty($columnsAggregation))
				$sql .= "\t"."*, ";

			for($j=0 ; $j<$countJ=count($columns) ; $j++)
			{
				if(!empty($columns[$j]->sls_graph_query_column_aggregation))
					$sql .= "\t".strtoupper($columns[$j]->sls_graph_query_column_aggregation)."(".(empty($columns[$j]->sls_graph_query_column_name) ? '*' : ($columns[$j]->sls_graph_query_column_table_alias).".`".$columns[$j]->sls_graph_query_column_name."`").")";
				else if(!SLS_String::contains($columns[$j]->sls_graph_query_column_name, 'CONCAT('))
				{
					$columnDateFormat = false;
					if ($columns[$j]->sls_graph_query_column_alias == "legend_group")
					{
						$columnInfos = $this->sql->showColumns($columns[$j]->sls_graph_query_column_table);
						for($i=0 ; $i<$count=count($columnInfos) ; $i++)
						{
							if ($columnInfos[$i]->Field == $columns[$j]->sls_graph_query_column_name)
							{
								if (SLS_String::contains($columnInfos[$i]->Type,"date") || SLS_String::contains($columnInfos[$i]->Type,"timestamp"))
									$columnDateFormat = true;
									
								break;
							}
						}
					}
					$sql .= "\t".(($columnDateFormat) ? "DATE_FORMAT(".($columns[$j]->sls_graph_query_column_table_alias).".`".$columns[$j]->sls_graph_query_column_name."`".",'%Y-%m')" : ($columns[$j]->sls_graph_query_column_table_alias).".`".$columns[$j]->sls_graph_query_column_name."`");
				}
				else
					$sql .= "\t".$columns[$j]->sls_graph_query_column_name;

				if (!empty($columns[$j]->sls_graph_query_column_alias))
					$sql .= " AS `".$columns[$j]->sls_graph_query_column_alias."`";
				$sql .= (($j < ($countJ-1)) ? ", " : " ")."\n";
			}

		}
		else
			$sql .= "\t"."* ";

		// FROM
		$sql .= "FROM "."\n";
		$sql .= "\t"."`".$slsGraphQuery->sls_graph_query_table."`"." ".$slsGraphQuery->sls_graph_query_table_alias." "."\n";

		// JOIN
		if (!empty($joins))
		{
			for($j=0 ; $j<$countJ=count($joins) ; $j++)
			{
				$sql .= "\t".strtoupper($joins[$j]->sls_graph_query_join_mode)." JOIN "."`".$joins[$j]->sls_graph_query_join_table_source."`"." ".$joins[$j]->sls_graph_query_join_table_alias_source." ON ".$joins[$j]->sls_graph_query_join_table_alias_target."."."`".$joins[$j]->sls_graph_query_join_column_target."`"." = ".$joins[$j]->sls_graph_query_join_table_alias_source."."."`".$joins[$j]->sls_graph_query_join_column_source."`";
				$sql .= (($j < ($countJ-1)) ? " " : " ")."\n";
			}
		}

		// WHERE
		if (!empty($whereRoot) && count($wheres) > 1)
		{
			$tab = 0;
			$sql .= "WHERE "."\n";
			$sql .= str_repeat("\t",$tab)."( "."\n";
			$sql .= $this->getSlsGraphQueryWheres($whereRoot->sls_graph_query_where_id,$tab+1,$tables,$slsGraphQueryId);
			$sql .= str_repeat("\t",$tab).") "."\n";
		}

		// GROUP
		if (!empty($groups))
		{
			$sql .= "GROUP BY "."\n";
			for($j=0 ; $j<$countJ=count($groups) ; $j++)
			{
				$join = $this->array_pdo_multiple_search($joins, array(
					'sls_graph_query_join_column_target' => $groups[$j]->sls_graph_query_group_column,
					'sls_graph_query_join_table_alias_target' => $groups[$j]->sls_graph_query_group_table_alias)
				);

				$groupAlias = "";
				$groupColumn = "";
				$groupTable = "";	
				$groupDateFormat = false;			
				if(empty($join))
				{
					$groupAlias = $groups[$j]->sls_graph_query_group_table_alias;
					$groupColumn = $groups[$j]->sls_graph_query_group_column;
					$groupTable = $groups[$j]->sls_graph_query_group_table;
				}
				else
				{
					$groupAlias = $join->sls_graph_query_join_table_alias_source;
					$groupColumn = $join->sls_graph_query_join_column_source;
					$groupTable = $join->sls_graph_query_join_table_source;
				}
				$columnGroupInfos = $this->sql->showColumns($groupTable);
				for($i=0 ; $i<$count=count($columnGroupInfos) ; $i++)
				{
					if ($columnGroupInfos[$i]->Field == $groupColumn)
					{
						if (SLS_String::contains($columnGroupInfos[$i]->Type,"date") || SLS_String::contains($columnGroupInfos[$i]->Type,"timestamp"))
							$groupDateFormat = true;
							
						break;
					}
				}
				$sql .= (($groupDateFormat) ? "\t"."DATE_FORMAT(".$groupAlias."."."`".$groupColumn."`, '%Y-%m')" : "\t".$groupAlias."."."`".$groupColumn."`");

				$sql .= (($j < ($countJ-1)) ? ", " : " ")."\n";
			}
		}

		// ORDER
		if (!empty($orders))
		{
			$sql .= "ORDER BY "."\n";
			for($j=0 ; $j<$countJ=count($orders) ; $j++)
			{
				$sql .= "\t".$orders[$j]->sls_graph_query_order_table_alias."."."`".$orders[$j]->sls_graph_query_order_column."`"." ".strtoupper($orders[$j]->sls_graph_query_order_way);
				$sql .= (($j < ($countJ-1)) ? ", " : " ")."\n";
			}
		}

		// LIMIT
		if (!empty($limit) && $limit->sls_graph_query_limit_start >= 0 && $limit->sls_graph_query_limit_length > 0)
		{
			$sql .= "LIMIT "."\n";
			$sql .= "\t".$limit->sls_graph_query_limit_start.", ".$limit->sls_graph_query_limit_length." "."\n";
		}
		return $sql;
	}
Пример #22
0
	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);
	}
	public function action()
	{
		$user = $this->hasAuthorative();
		$xml = $this->getXML();
		$xml = $this->makeMenu($xml);

		$sql = SLS_Sql::getInstance();

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

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

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

		$slsGraphQueryCurrent = $slsGraphQuery;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

					$columnTable = $objectFk->getTable();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

					$columnTable = $objectFk->getTable();

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

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

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

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

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

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

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

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

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

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

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

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

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

						$columnTable = $objectFk->getTable();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

					$columnTable = $objectFk->getTable();

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

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

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

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

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

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

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

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

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

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

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

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

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

					$columnTable = $objectFk->getTable();

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

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

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

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

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

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

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

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

				# /query columns

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

						$joinBefore = $join;
					}
					# /joins

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

					$tableComment = $join['sls_graph_query_join_table_comment_target'];

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

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

				# /columns
			}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		$xml->addFullTag("url_reporting_getfields",$this->_generic->getFullPath("SLS_Bo","ReportingBoGetFields"),true);
		$xml->addFullTag("url_reporting_getfieldsfrommutipletables",$this->_generic->getFullPath("SLS_Bo","ReportingBoGetFieldsFromMultipleTables"),true);
		$xml->addFullTag("url_report",$this->_generic->getFullPath("SLS_Bo","ReportingBo"),true);
		$xml->addFullTag("url_delete",$this->_generic->getFullPath("SLS_Bo","ReportingBoDelete",array("id" => $slsGraphId)),true);
		$xml->addFullTag("url_status",$this->_generic->getFullPath("SLS_Bo","ReportingBoStatus",array("id" => $slsGraphId)),true);
		
		$this->saveXML($xml);
	}
Пример #24
0
	/**
	 * Bind dependencies between mysql table and static|component|controller|action into controller_bind.json.
	 * This file is used to know if we need to flush cached files when we insert/update/delete datas into tables.
	 * 
	 * @access private
	 * @param string $query the sql select query you have to analyze
	 * @since 1.0.9
	 */
	private function logDependencies($query)
	{
		// If cache enabled, don't log dependencies
		if ($this->_generic->isCache())
			return true;
		
		// Objects
		$log = false;
		$query = strtolower($query);
		$tables = array();
				
		// Force explain on the query to grep tables
		$explains = $this->select("EXPLAIN ".$query);		
		for($i=0 ; $i<$count=count($explains) ; $i++)
			$tables[] = $explains[$i]->table;
		
		// Check all tables > real table name or f****n alias ?
		for($i=0 ; $i<$count=count($tables) ; $i++)
		{		
			if (!in_array($tables[$i],$this->_tables))
			{				
				if (SLS_String::endsWith($query," ".$tables[$i]))				
					$tables[$i] = str_replace('`','',SLS_String::substrAfterLastDelimiter(trim(SLS_String::substrBeforeLastDelimiter($query," ".$tables[$i]))," "));				
				else	
					$tables[$i] = str_replace('`','',SLS_String::substrAfterLastDelimiter(trim(SLS_String::substrBeforeFirstDelimiter($query," ".$tables[$i]." "))," "));
				
					
				if (!in_array($tables[$i],$this->_tables))
					unset($tables[$i]);
			}
		}
		
		if (!empty($tables))
		{			
			$traces = debug_backtrace();		
			for($i=0 ; $i<$count=count($traces) ; $i++)
			{
				$file = $traces[$i]["file"];
				if (SLS_String::contains($file,$this->_generic->getPathConfig("staticsControllers")))
				{
					$log = true;
					$name = strtolower(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($file,$this->_generic->getPathConfig("staticsControllers")),".controller.php"));
					foreach($tables as $table)
						$this->_cache->addBind($table,"statics",$name);
					break;
				}
				if (SLS_String::contains($file,$this->_generic->getPathConfig("componentsControllers")))
				{
					$log = true;					 
					$name = strtolower(SLS_String::substrBeforeFirstDelimiter(SLS_String::substrAfterFirstDelimiter($file,$this->_generic->getPathConfig("componentsControllers")),".controller.php"));
					foreach($tables as $table)
						$this->_cache->addBind($table,"components",$name);
					break;
				}
				if (SLS_String::contains($file,$this->_generic->getPathConfig("actionsControllers")))
				{
					$log = true;
					if (SLS_String::contains($file,"/__") && SLS_String::contains($file,".protected.php"))
					{
						$name = strtolower(SLS_String::substrAfterFirstDelimiter($this->_generic->getControllerId(),"_"));
						foreach($tables as $table)
							$this->_cache->addBind($table,"controllers",$name);
						break;
					}
					else
					{
						$name = strtolower(SLS_String::substrAfterFirstDelimiter($this->_generic->getActionId(),"_"));
						foreach($tables as $table)
							$this->_cache->addBind($table,"actions",$name);
						break;
					}
				}
			}
			if ($log)			
				$this->_cache->saveBind();				
		}
	}
Пример #25
0
	/**
	 * 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
		}
	}
Пример #26
0
	public function constructXML()
	{
		$this->_boController = $this->_generic->getBo();
		
		if ($this->_generic->getGenericControllerName() == $this->_boController)
		{
			@include_once($this->_generic->getPathConfig("actionLangs").$this->_boController."/__".$this->_boController.".".$this->_lang->getLang().".lang.php");
			
			$db = SLS_Sql::getInstance();
			$dbsAlias = $db->getDbs();
			$comments = array();
			foreach($dbsAlias as $dbAlias)
			{
				$db->changeDb($dbAlias);
				$tables = $db->showTables();			
				for($i=0 ; $i<$count=count($tables) ; $i++)
				{
					$table = $tables[$i]->Name;
					$key = ucfirst(strtolower($dbAlias))."_".SLS_String::tableToClass($table);
					if (!array_key_exists($key,$comments))
					{
						$comment = $tables[$i]->Comment;
						if (SLS_String::startsWith($comment,"sls:lang:"))
						{
							$globalKey = strtoupper(SLS_String::substrAfterFirstDelimiter($comment,"sls:lang:"));
							$comment = (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$globalKey])) ? (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$globalKey]) ? $table : $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$globalKey]) : $GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$globalKey];
						}
						$comments[$key] = (empty($comment)) ? $table : $comment;
					}
				}
			}
			$db->changeDb($db->connectToDefaultDb());
			
			# Nav
			if (SLS_BoRights::isLogged())
			{
				$xmlBo = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/bo.xml"));
				$entries = $xmlBo->getTagsAttributes("//sls_configs/entry",array("type","name"));		
				$this->_xmlToolBox->startTag("nav");
					if (!empty($entries))
					{
						# BOs
						$this->_xmlToolBox->startTag("section");
							$this->_xmlToolBox->addFullTag("title",$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_MENU_SITE'],"true");
							$this->_xmlToolBox->addFullTag("href","#","true");
							$this->_xmlToolBox->startTag("categories");
							for($i=0 ; $i<$count=count($entries) ; $i++)
							{
								$position = ($i+1);
								$type = $entries[$i]["attributes"][0]["value"];
								$name = $entries[$i]["attributes"][1]["value"];
								
								if ($type == "category")
								{
									$childs = $xmlBo->getTagsAttributes("//sls_configs/entry[".$position."]/entry",array("type","name"));
									$comment = $name;
									if (SLS_String::startsWith($comment,"sls:lang:"))
									{
										$globalKey = strtoupper(SLS_String::substrAfterFirstDelimiter($comment,"sls:lang:"));
										$comment = (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$globalKey])) ? (empty($GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$globalKey]) ? $name : $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$globalKey]) : $GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$globalKey];
									}
									$this->_xmlToolBox->startTag("category",array("type"=>"category"));
										$this->_xmlToolBox->addFullTag("title",$comment,"true");
										$this->_xmlToolBox->addFullTag("href","#","true");
										if (!empty($childs))
										{
											$this->_xmlToolBox->startTag("items");
											for($j=0 ; $j<$count=count($childs) ; $j++)
											{
												$type = $childs[$j]["attributes"][0]["value"];
												$name = $childs[$j]["attributes"][1]["value"];
												$dbAlias = ucfirst(strtolower(SLS_String::substrBeforeFirstDelimiter($name,"_")));
												$table = SLS_String::substrAfterFirstDelimiter($name,"_");							
												$right = SLS_BoRights::isAuthorized("read",$dbAlias."_".SLS_String::tableToClass($table));
												if ($right == 1)
												{
													$comment = $comments[$dbAlias."_".SLS_String::tableToClass($table)];
													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]) ? $table : $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$key]) : $GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$key];
													}
													$actionIdsModel = array($this->_generic->getActionId($this->_boController,"List".$dbAlias."_".SLS_String::tableToClass($table)),
																			$this->_generic->getActionId($this->_boController,"Add".$dbAlias."_".SLS_String::tableToClass($table)),
																			$this->_generic->getActionId($this->_boController,"Modify".$dbAlias."_".SLS_String::tableToClass($table)),
																			$this->_generic->getActionId($this->_boController,"Clone".$dbAlias."_".SLS_String::tableToClass($table)),
																			$this->_generic->getActionId($this->_boController,"Delete".$dbAlias."_".SLS_String::tableToClass($table)));
													if ($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController,"List".$dbAlias."_".SLS_String::tableToClass($table))))
													{
														$this->_xmlToolBox->startTag("item");
															$this->_xmlToolBox->addFullTag("db",$dbAlias,true);
															$this->_xmlToolBox->addFullTag("model",SLS_String::tableToClass($table),true);
															$this->_xmlToolBox->addFullTag("title",$comment,"true");
															$this->_xmlToolBox->addFullTag("like",(SLS_BoRights::isLike("read",$dbAlias."_".SLS_String::tableToClass($table))) ? "true" : "false","true");												
															$this->_xmlToolBox->addFullTag("selected",(in_array($this->_generic->getActionId(),$actionIdsModel)) ? "true" : "false","true");
															$this->_xmlToolBox->addFullTag("href",$this->_generic->getFullPath($this->_boController,"List".$dbAlias."_".SLS_String::tableToClass($table)),"true");
														$this->_xmlToolBox->endTag("item");
													}
												}
											}
											$this->_xmlToolBox->endTag("items");
										}
									$this->_xmlToolBox->endTag("category");
								}
								else
								{
									$dbAlias = ucfirst(strtolower(SLS_String::substrBeforeFirstDelimiter($name,"_")));
									$table = SLS_String::substrAfterFirstDelimiter($name,"_");							
									$right = SLS_BoRights::isAuthorized("read",$dbAlias."_".SLS_String::tableToClass($table));
									if ($right == 1)
									{
										$comment = $comments[$dbAlias."_".SLS_String::tableToClass($table)];
										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]) ? $table : $GLOBALS[$GLOBALS['PROJECT_NAME']]['JS'][$key]) : $GLOBALS[$GLOBALS['PROJECT_NAME']]['XSL'][$key];
										}
										$actionIdsModel = array($this->_generic->getActionId($this->_boController,"List".$dbAlias."_".SLS_String::tableToClass($table)),
																$this->_generic->getActionId($this->_boController,"Add".$dbAlias."_".SLS_String::tableToClass($table)),
																$this->_generic->getActionId($this->_boController,"Modify".$dbAlias."_".SLS_String::tableToClass($table)),
																$this->_generic->getActionId($this->_boController,"Clone".$dbAlias."_".SLS_String::tableToClass($table)),
																$this->_generic->getActionId($this->_boController,"Delete".$dbAlias."_".SLS_String::tableToClass($table)));
										if ($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController,"List".$dbAlias."_".SLS_String::tableToClass($table))))
										{
											$this->_xmlToolBox->startTag("category",array("type"=>"table"));
												$this->_xmlToolBox->addFullTag("db",$dbAlias,true);
												$this->_xmlToolBox->addFullTag("model",SLS_String::tableToClass($table),true);
												$this->_xmlToolBox->addFullTag("title",$comment,"true");
												$this->_xmlToolBox->addFullTag("like",(SLS_BoRights::isLike("read",$dbAlias."_".SLS_String::tableToClass($table))) ? "true" : "false","true");
												$this->_xmlToolBox->addFullTag("selected",(in_array($this->_generic->getActionId(),$actionIdsModel)) ? "true" : "false","true");
												$this->_xmlToolBox->addFullTag("href",$this->_generic->getFullPath($this->_boController,"List".$dbAlias."_".SLS_String::tableToClass($table)),"true");
											$this->_xmlToolBox->endTag("category");
										}
									}
								}
							}
							$this->_xmlToolBox->endTag("categories");
							
						$this->_xmlToolBox->endTag("section");
						# /BOs
					}
					
					# i18n
					if ($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController, "Boi18n")) && SLS_BoRights::isAuthorized("","",$this->_generic->getActionId($this->_boController, "Boi18n")))
					{
						$file = $this->_http->getParam("File");
						$this->_xmlToolBox->startTag("section");
							$this->_xmlToolBox->addFullTag("title",$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_MENU_I18N'],"true");
							$this->_xmlToolBox->addFullTag("selected",($this->_generic->getActionId() == $this->_generic->getActionId($this->_boController, "Boi18n")) ? "true" : "false","true");
							$this->_xmlToolBox->addFullTag("href","#","true");
							$this->_xmlToolBox->startTag("categories");
								$controllers = $this->_generic->getControllersXML()->getTags("//controllers/controller[@side='user']/@name");
								sort($controllers,SORT_STRING);
								for($i=0 ; $i<$count=count($controllers) ; $i++)
								{
									$actions = $this->_generic->getControllersXML()->getTags("//controllers/controller[@name='".$controllers[$i]."' and @side='user']/scontrollers/scontroller/@name");
									sort($actions,SORT_STRING);
									$this->_xmlToolBox->startTag("category",array("type"=>"category"));
										$this->_xmlToolBox->addFullTag("title",$controllers[$i],"true");
										$this->_xmlToolBox->addFullTag("selected",($this->_generic->getActionId() == $this->_generic->getActionId($this->_boController, "Boi18n") && SLS_String::startsWith($file, "Actions|".$controllers[$i]."|")) ? "true" : "false","true");
										$this->_xmlToolBox->addFullTag("href","#","true");
										$this->_xmlToolBox->startTag("items");
										if (file_exists($this->_generic->getPathConfig("actionLangs").$controllers[$i]."/__".$controllers[$i].".".$this->_lang->getLang().".lang.php") && ($translations = file_get_contents($this->_generic->getPathConfig("actionLangs").$controllers[$i]."/__".$controllers[$i].".".$this->_lang->getLang().".lang.php")) && SLS_String::contains(str_replace("","",$translations),'*/'."\n".'$GLOBALS') || (!SLS_String::contains($translations,"/**") && SLS_String::contains($translations,'$GLOBALS')))
										{
											$this->_xmlToolBox->startTag("item");
												$this->_xmlToolBox->addFullTag("title","__".$controllers[$i],"true");
												$this->_xmlToolBox->addFullTag("selected",($this->_generic->getActionId() == $this->_generic->getActionId($this->_boController, "Boi18n") && $file == "Actions|".$controllers[$i]."|__".$controllers[$i]) ? "true" : "false","true");
												$this->_xmlToolBox->addFullTag("href",$this->_generic->getFullPath($this->_boController, "Boi18n", array("File" => "Actions|".$controllers[$i]."|__".$controllers[$i])),"true");
											$this->_xmlToolBox->endTag("item");
										}
										for($j=0 ; $j<$countJ=count($actions) ; $j++)
										{
											if (file_exists($this->_generic->getPathConfig("actionLangs").$controllers[$i]."/".$actions[$j].".".$this->_lang->getLang().".lang.php") && ($translations = file_get_contents($this->_generic->getPathConfig("actionLangs").$controllers[$i]."/".$actions[$j].".".$this->_lang->getLang().".lang.php")) && SLS_String::contains(str_replace("","",$translations),'*/'."\n".'$GLOBALS') || (!SLS_String::contains($translations,"/**") && SLS_String::contains($translations,'$GLOBALS')))
											{
												$this->_xmlToolBox->startTag("item");
													$this->_xmlToolBox->addFullTag("title",$actions[$j],"true");
													$this->_xmlToolBox->addFullTag("selected",($this->_generic->getActionId() == $this->_generic->getActionId($this->_boController, "Boi18n") && $file == "Actions|".$controllers[$i]."|".$actions[$j]) ? "true" : "false","true");
													$this->_xmlToolBox->addFullTag("href",$this->_generic->getFullPath($this->_boController, "Boi18n", array("File" => "Actions|".$controllers[$i]."|".$actions[$j])),"true");
												$this->_xmlToolBox->endTag("item");
											}
										}
										$this->_xmlToolBox->endTag("items");
									$this->_xmlToolBox->endTag("category");
								}
								if (file_exists($this->_generic->getPathConfig("genericLangs")."site.".$this->_lang->getLang().".lang.php") && ($translations = file_get_contents($this->_generic->getPathConfig("genericLangs")."site.".$this->_lang->getLang().".lang.php")) && SLS_String::contains(str_replace("","",$translations),'*/'."\n".'$GLOBALS') || (!SLS_String::contains($translations,"/**") && SLS_String::contains($translations,'$GLOBALS')))
								{
									$this->_xmlToolBox->startTag("category",array("type"=>"table"));
										$this->_xmlToolBox->addFullTag("title","__".$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_MENU_I18N_SITE'],"true");
										$this->_xmlToolBox->addFullTag("selected",($this->_generic->getActionId() == $this->_generic->getActionId($this->_boController, "Boi18n") && $file == "Generics|site") ? "true" : "false","true");
										$this->_xmlToolBox->addFullTag("href",$this->_generic->getFullPath($this->_boController, "Boi18n", array("File" => "Generics|site")),"true");
									$this->_xmlToolBox->endTag("category");
								}
							$this->_xmlToolBox->endTag("categories");
						$this->_xmlToolBox->endTag("section");
					}
					# /i18n
					
					# CkFinder
					if ($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController, "BoFileUpload")) && SLS_BoRights::isAuthorized("","",$this->_generic->getActionId($this->_boController, "BoFileUpload")))
					{
						$this->_xmlToolBox->startTag("section");
							$this->_xmlToolBox->addFullTag("title",$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_MENU_FILE_MANAGER'],"true");
							$this->_xmlToolBox->addFullTag("selected",($this->_generic->getActionId() == $this->_generic->getActionId($this->_boController,"BoFileUpload")) ? "true" : "false","true");
							$this->_xmlToolBox->addFullTag("href",$this->_generic->getFullPath($this->_boController,"BoFileUpload"),"true");
						$this->_xmlToolBox->endTag("section");
					}
					# /CkFinder
					
					# ProjectSettings
					if ($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController, "BoProjectSettings")) && SLS_BoRights::isAuthorized("","",$this->_generic->getActionId($this->_boController, "BoProjectSettings")))
					{
						$this->_xmlToolBox->startTag("section");
							$this->_xmlToolBox->addFullTag("title",$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_MENU_PROJECT_SETTINGS'],"true");
							$this->_xmlToolBox->addFullTag("selected",($this->_generic->getActionId() == $this->_generic->getActionId($this->_boController,"BoProjectSettings")) ? "true" : "false","true");
							$this->_xmlToolBox->addFullTag("href",$this->_generic->getFullPath($this->_boController,"BoProjectSettings"),"true");
						$this->_xmlToolBox->endTag("section");
					}
					# /ProjectSettings
					
					# Users
					if ($this->_generic->actionIdExists($this->_generic->getActionId($this->_boController, "BoUserList")) && SLS_BoRights::isAuthorized("","",$this->_generic->getActionId($this->_boController, "BoUserList")))
					{
						$actionsUser = array($this->_generic->getActionId($this->_boController, "BoUserList"),
											 $this->_generic->getActionId($this->_boController, "BoUserAdd"),
											 $this->_generic->getActionId($this->_boController, "BoUserModify"),
											 $this->_generic->getActionId($this->_boController, "BoUserDelete"),
											 $this->_generic->getActionId($this->_boController, "BoUserStatus"));
						$this->_xmlToolBox->startTag("section");
							$this->_xmlToolBox->addFullTag("title",$GLOBALS[$GLOBALS['PROJECT_NAME']]['JS']['SLS_BO_MENU_USERS'],"true");
							$this->_xmlToolBox->addFullTag("selected",(in_array($this->_generic->getActionId(),$actionsUser)) ? "true" : "false","true");
							$this->_xmlToolBox->addFullTag("href",$this->_generic->getFullPath($this->_boController,"BoUserList"),"true");
						$this->_xmlToolBox->endTag("section");
					}
					# /Users
					
					# Developer actions
					$boActions = $this->_generic->getControllersXML()->getTags("//controllers/controller[@isBo='true']/scontrollers/scontroller/@name");
					for($i=0 ; $i<$count=count($boActions) ; $i++)
					{
						// If dev action & admin authorized
						if (!SLS_String::startsWith($boActions[$i],"Bo") && 	// Sls generated actions
							!SLS_String::startsWith($boActions[$i],"List") && 	// User action ListDb_Model
							!SLS_String::startsWith($boActions[$i],"Add") && 	// User action AddDb_Model
							!SLS_String::startsWith($boActions[$i],"Modify") && // User action ModifyDb_Model
							!SLS_String::startsWith($boActions[$i],"Delete") && // User action DeleteDb_Model
							!SLS_String::startsWith($boActions[$i],"Clone") && 	// User action CloneDb_Model
							!SLS_String::startsWith($boActions[$i],"Email") &&	// User action EmailDb_Model
							SLS_BoRights::isAuthorized("","",$this->_generic->getActionId($this->_boController, $boActions[$i])))
						{
							$this->_xmlToolBox->startTag("section");
								$this->_xmlToolBox->addFullTag("title",$this->_generic->getControllersXML()->getTag("//controllers/controller[@isBo='true']/scontrollers/scontroller[@name='".$boActions[$i]."']/scontrollerLangs/scontrollerLang[@lang='".$this->_lang->getLang()."']"),"true");
								$this->_xmlToolBox->addFullTag("selected",($this->_generic->getActionId() == $this->_generic->getActionId($this->_boController, $boActions[$i])) ? "true" : "false", "true");
								$this->_xmlToolBox->addFullTag("href",$this->_generic->getFullPath($this->_boController,$boActions[$i]),"true");
							$this->_xmlToolBox->endTag("section");
						}
					}
					# /Developer actions
					
				$this->_xmlToolBox->endTag("nav");
			}
			# /Nav
			
			# Admin
			$xmlRight = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/rights.xml"));
			$adminName = $this->_session->getParam("SLS_BO_USER_NAME");
			$adminFirstname = $this->_session->getParam("SLS_BO_USER_FIRSTNAME");
			if (!empty($adminName) && !empty($adminFirstname))
				$imgPath = $this->_generic->getPathConfig("files")."__Uploads/images/bo/".SLS_String::stringToUrl($adminName."_".$adminFirstname,"_").".jpg";
			else
				$imgPath = $this->_generic->getPathConfig("coreImg")."BO-2014/Pictos/default_dev_account_small.jpg";
			$this->_xmlToolBox->startTag("admin");
				$this->_xmlToolBox->addFullTag("img",(file_exists($imgPath) && !is_dir($imgPath)) ? $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$imgPath : $this->_generic->getSiteConfig("protocol")."://".$this->_generic->getSiteConfig("domainName")."/".$this->_generic->getPathConfig("files")."__Uploads/images/bo/default_account.jpg",true);
				$this->_xmlToolBox->addFullTag("login",$this->_session->getParam("SLS_BO_USER"),true);
				$this->_xmlToolBox->addFullTag("name",ucwords(strtolower((!empty($adminName)) ? $adminName : "Developer")),true);
				$this->_xmlToolBox->addFullTag("firstname",((!empty($adminFirstname)) ? ucwords(strtolower($adminFirstname)) : "SillySmart"),true);
				$this->_xmlToolBox->addFullTag("type",SLS_BoRights::getAdminType(),true);			
				$nodeExists = $xmlRight->getTag("//sls_configs/entry[@login='******']/@login");
				if (!empty($nodeExists))
				{
					$settings = array_combine($xmlRight->getTags("//sls_configs/entry[@login='******']/settings/setting/@key"),$xmlRight->getTags("//sls_configs/entry[@login='******']/settings/setting"));
					$this->_xmlToolBox->startTag("settings");
					foreach($settings as $key => $value)
						$this->_xmlToolBox->addFullTag("setting",$value,true,array("key"=>$key));
					$this->_xmlToolBox->endTag("settings");
				}
				$xmlBoColors = new SLS_XMLToolbox(file_get_contents($this->_generic->getPathConfig("configSls")."/bo_colors.xml"));
				$boColors = $xmlBoColors->getTagsAttributes("//sls_configs/template",array("name","hexa"));
				$this->_xmlToolBox->startTag("colors");
				for($i=0 ; $i<$count=count($boColors) ; $i++)
					$this->_xmlToolBox->addFullTag("color",$boColors[$i]["attributes"][0]["value"],true,array("hexa" => $boColors[$i]["attributes"][1]["value"]));
				$this->_xmlToolBox->endTag("colors");
			$this->_xmlToolBox->endTag("admin");
			# /Admin
			
			# URLs
			$this->_xmlToolBox->startTag("various");
				$this->_xmlToolBox->addFullTag("dashboard",$this->_generic->getFullPath($this->_boController,"BoDashBoard"),true,array("selected" => ($this->_generic->getActionId() == $this->_generic->getActionId($this->_boController,"BoDashBoard")) ? "true" : "false"));
				$this->_xmlToolBox->addFullTag("export",$this->_generic->getFullPath($this->_boController,"BoExport"),true);
				$this->_xmlToolBox->addFullTag("ac",$this->_generic->getFullPath($this->_boController,"BoFkAc"),true);
				$this->_xmlToolBox->addFullTag("like",$this->_generic->getFullPath($this->_boController,"BoLike"),true);
				$this->_xmlToolBox->addFullTag("setting",$this->_generic->getFullPath($this->_boController,"BoSetting"),true);
				$this->_xmlToolBox->addFullTag("unique",$this->_generic->getFullPath($this->_boController,"BoUnique"),true);
				$this->_xmlToolBox->addFullTag("upload",$this->_generic->getFullPath($this->_boController,"BoUpload"),true);
				$this->_xmlToolBox->addFullTag("upload_progress",$this->_generic->getFullPath($this->_boController,"BoUploadProgress"),true);
				$this->_xmlToolBox->addFullTag("delete_file",$this->_generic->getFullPath($this->_boController,"BoDeleteFile"),true);
				$this->_xmlToolBox->addFullTag("login",$this->_generic->getFullPath($this->_boController,"BoLogin"),true);
				$this->_xmlToolBox->addFullTag("logout",(SLS_BoRights::getAdminType() == "developer") ? $this->_generic->getFullPath("SLS_Bo","Logout",array("Redirect" => $this->_generic->getActionId($this->_boController,"BoLogin"), "Lang" => $this->_lang->getLang()),true,"en") : $this->_generic->getFullPath($this->_boController,"BoLogout"),true);
				$this->_xmlToolBox->addFullTag("forgotten_pwd",$this->_generic->getFullPath($this->_boController,"BoForgottenPwd"),true);
				$this->_xmlToolBox->addFullTag("renew_pwd",$this->_generic->getFullPath($this->_boController,"BoRenewPwd",array("Login"=>$this->_session->getParam("SLS_BO_USER"))),true);
				$this->_xmlToolBox->addFullTag("is_logged",$this->_generic->getFullPath($this->_boController,"BoIsLogged"),true);
				$this->_xmlToolBox->addFullTag("switch_lang",$this->_generic->getFullPath($this->_boController,"BoSwitchLang",array("Lang"=>""),false),true);
				$this->_xmlToolBox->addFullTag("user_add",$this->_generic->getFullPath($this->_boController,"BoUserAdd"),true,array("authorized" => (SLS_BoRights::isAuthorized("","",$this->_generic->getActionId($this->_boController,"BoUserAdd"))) ? "true" : "false"));
				$this->_xmlToolBox->addFullTag("user_modify",$this->_generic->getFullPath($this->_boController,"BoUserModify",array("id" => ''),false),true,array("authorized" => (SLS_BoRights::isAuthorized("","",$this->_generic->getActionId($this->_boController,"BoUserModify"))) ? "true" : "false"));
				$this->_xmlToolBox->addFullTag("user_delete",$this->_generic->getFullPath($this->_boController,"BoUserDelete",array("id" => ''),false),true,array("authorized" => (SLS_BoRights::isAuthorized("","",$this->_generic->getActionId($this->_boController,"BoUserDelete"))) ? "true" : "false"));
				$this->_xmlToolBox->addFullTag("user_status",$this->_generic->getFullPath($this->_boController,"BoUserStatus",array("id" => ''),false),true,array("authorized" => (SLS_BoRights::isAuthorized("","",$this->_generic->getActionId($this->_boController,"BoUserStatus"))) ? "true" : "false"));
			$this->_xmlToolBox->endTag("various");
			# /URLs
			
			# Server
			$apcUpload = (in_array(ini_get("apc.rfc1867"),array(1,"1","On","on",true,"true"))) ? "true" : "false";
			$apcUploadKey = ini_get("apc.rfc1867_name");
			$uploadMaxFilesize = ini_get("upload_max_filesize");
			$unite = strtolower(substr(trim($uploadMaxFilesize), -1));
			switch ($unite)
		    {   
				case 'k': $uploadMaxFilesize = (int)$uploadMaxFilesize * 1024;					break;
		    	case 'm': $uploadMaxFilesize = (int)$uploadMaxFilesize * 1024 * 1024; 			break;
				case 'g': $uploadMaxFilesize = (int)$uploadMaxFilesize * 1024 * 1024 * 1024;	break;
				default: $uploadMaxFilesize = $uploadMaxFilesize;								break;
		    }
			$this->_xmlToolBox->startTag("server");
				$this->_xmlToolBox->addFullTag("apc_upload",$apcUpload,true);
				$this->_xmlToolBox->addFullTag("apc_upload_key",$apcUploadKey,true);
				$this->_xmlToolBox->addFullTag("upload_max_size",$uploadMaxFilesize,true);
			$this->_xmlToolBox->endTag("server");
			# /Server
		}
	}