<?php
/*
Officity - Web application platform - Version 6.0 - 2011-07-05

François Dispaux, Boris Verdeyen, Thomas Hermant,
Jérémie Roy, Grégory Meurice, Abdelila Harbi, 
Marc Mignonsin, Jonathan Sanchez, Julien Gonzalez, Pierre Fouchez

Sushee and Officity is © Copyright 2011 Nectil SA.

`/var/www/installer/public_html/officity-source/apps/system/class/XSLFlattener.class.php` is part of Officity.

Sushee is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Officity and Sushee are distributed in the hope that they will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Sushee. If not, see <http://www.gnu.org/licenses/>.
*/
	require_once(dirname(__FILE__).'/../system.config.php');
	require_once(dirname(__FILE__).'/../system.url.php');
	require_once(KERNEL_PATH.'common/xslt.class.php');
	require_once(dirname(__FILE__).'/SVNClient.class.php');

	/* *** */

    class Officity_LibXSLTProcessor extends LibXSLTProcessor
    {
    	// directly on the XML file
   		public function execute($target_file)
   		{
   			$html_on_error = $this->output_error;
   			$more_params = $this->params;   			

   			$xsltproc = "xsltproc";
   			if(getServerOS()=='windows' && file_exists(KERNEL_PATH.'/common/xsltproc/xsltproc.exe'))
   			$xsltproc='"'.realpath(KERNEL_PATH.'/common/xsltproc/xsltproc.exe').'"';
   			if(isset($GLOBALS["xsltproc"]))
   			$xsltproc = $GLOBALS["xsltproc"];
   			$xsltproc_params = '';

   			if(is_array($more_params) && sizeof($more_params)>0){
   				foreach($more_params as $param_name=>$param_value){
   					if($param_name && $param_value && !is_object($param_value)){
   						$xsltproc_params.='--stringparam "'.encodeQuote($param_name).'" "'.encodeQuote($param_value).'" ';
   					}
   				}
   					
   			}

   			$command = "$xsltproc ".$xsltproc_params." \"".$this->template."\" \"".$target_file."\"  2>&1";
   			/*$cmdCaller = new commandLine($command);
   			 $cmdCaller->enableLogging(false);
   			 $html = $cmdCaller->execute();*/
   			
   			var_dump($command);

   			$command = batchFile($command);
   			$html_array = array();
   			session_write_close();
   			exec($command,$html_array,$res);
   			session_start();
   			$result_xsl = implode("\n",$html_array);
   			// if there was an error display it
   			if($res>0){
   				$line = false;
   				$xsl_str = file_in_string($template);
   				$xsl_str = str_replace("\r\n","\n",$xsl_str);
   				$xsl_lines = explode("\n",$xsl_str);
   				$line_pos = strpos($result_xsl,'line ');
   				if($line_pos){
   					$space_pos = strpos($result_xsl,' ',$line_pos+6);
   					if(!$space_pos)
   					$space_pos = strpos($result_xsl,"\n",$line_pos+6);
   					if($space_pos)
   					$line = substr($result_xsl,$line_pos+5,$space_pos-$line_pos-5);
   				}
   				if($line)
   				$line_msg = ' on line '.$line;
   				$html = '<html><body><h1>Error '.$line_msg.':</h1><p style="font-size:110%;line-height:1.3;">';
   			}
   			if($res>0)
   			$html.= str_replace('^','<br/>',encode_to_XML($result_xsl));
   			else
   			$html.= str_replace('<br></br>','<br/>',$result_xsl);
   			if($res>0 && $line){
   				$html.= "</p><p style='line-height:18px;padding:5px;margin-left:20px;background-color:lightgrey;'>";
   				$html.= "<code>".encode_to_XML($xsl_lines[$line-2])."<br/><span style='color:red;'>".encode_to_XML($xsl_lines[$line-1])."</span><br/>".encode_to_XML($xsl_lines[$line])."<br/>".encode_to_XML($xsl_lines[$line+1])."</code></p>";
   				$html.='</body></html>';
   					
   			}
   			unlink($tmp_xml_file);

   			if($html_on_error===false && $res>0){
   				return false;
   			}else{
   				return $html;
   			}
   		}
    }

	/* *** */
	
	/*
	 * Application Class
	 * 
	 * @since	2010-11-05
	 *
	*/
	
	class XSLFlattener
	{
		private static $xslt_proc = null;
		private static $flattener_URI = '../tools/xsl/flattener.xsl';
		private static $suffix = 'flat';
		
		function __construct()
		{
			self::$xslt_proc = new Officity_LibXSLTProcessor();
		}
		
		function __destruct()
		{
		
		}
		
		public static function setFlattenerURI($new_uri)
		{
			self::$flattener_URI = $new_uri;
		}
		
		public static function setSuffix($new_suffix)
		{
			self::$suffix = $new_suffix;
		}
		
		public static function distinctFlatten($in_path, &$out_path)
		{
			if (self::$xslt_proc == null) self::$xslt_proc = new Officity_LibXSLTProcessor();
			
			// 1st pass
		    self::setFlattenerURI('../tools/xsl/v2/concatenator.xsl');
		    self::setSuffix('concat');
		    
		    $target_path_parts = pathinfo($in_path);
		    $initial_path = dirname($in_path).'/';
		    
		    self::$xslt_proc->setParams(array(
		    	'initial-path' => $initial_path
		    ));
		    		    
		    $concat_file = '';
		    $result = self::flatten($in_path, $concat_file);
		    if ($result !== true)
		    {
		    	return $result;
		    }
		    
		    // 2nd pass
		    self::setFlattenerURI('../tools/xsl/v2/flattener.xsl');
		    self::setSuffix('flat');
		    return self::flatten($concat_file, $out_path);
		}
		
		public static function flatten($in_path, &$out_path)
		{
			if (self::$xslt_proc == null) self::$xslt_proc = new Officity_LibXSLTProcessor();
			
			$flattener_path = dirname(__FILE__).'/'.self::$flattener_URI;
		    if (!file_exists($flattener_path))
		    {
		    	return 'Error: system template '.$flattener_path.' does not exist!';
		    }
		    if (!file_exists($in_path))
		    {
		    	return 'Error: input template '.$in_path.' does not exist!';
		    }
	    	
	    	self::$xslt_proc->setTemplate($flattener_path);    	
	    	$flat_xsl = self::$xslt_proc->execute($in_path);
	    	
	    	$target_path_parts = pathinfo($in_path);
	    	$out_path = $target_path_parts['dirname'].'/'.$target_path_parts['filename'].'-'.self::$suffix.'.xsl';
	    		    	
	    	$update = file_exists($out_path);
	    	saveInFile($flat_xsl, $out_path);
	    	
		    if (!file_exists($out_path))
		    {
		    	return 'Error: output template '.$out_path.' has not been created!';
		    }
		    
	      	$svn_client = new SVNClient();
	      	if ($update == true) 
	      	{
	      		$svn_client->update($out_path);
	      	}
	      	else
	      	{
	      		$svn_client->create($out_path);
	      	}
	    	
	    	return true;
		}
	}
?>