<?php
/**
 * Define a docx.
 * @author Valentin MORREEL
 * @category Plugin
 * @license MIT
 */
class WordExport {
	public $mime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
	public $extension = 'docx';
	public $description = 'Fichier de traitement de texte Word';
	public $destination;
	public $zip,$body,$header,$footer,$relationships;

	public  function sample($dataset,$level = 0,$parent=''){
		$rows = array();
		$rows[] = array(
			'content' => 'Macros disponibles :',
			'style' => array(
				'bold' => true,
				'font-size' => 16
			)
		);
		$rows = array_merge($rows, $this->recursive_sample($dataset,$level,$parent));
		$temp_file = tempnam(sys_get_temp_dir(), mt_rand(0,10000));

		self::write($temp_file, $rows);
		$stream = file_get_contents($temp_file);
		unlink($temp_file);
		return $stream;
	}

	public function recursive_sample($dataset,$level = 0,$parent=''){
		$stream = array();
		$parent = ($parent!=''?$parent.'.':'');
		$indentation = str_repeat("\t", $level);
		$titleSize = 18-($level*2);
		$titleSize = $titleSize < 12 ? $titleSize:12;
		foreach($dataset as $macro => $infos){

			$infos['type'] = isset($infos['type']) ? $infos['type'] : '';
			switch($infos['type']){
				case 'list':
					$stream[]= array(
						'content'=>  $indentation.$parent.$macro.' '.(isset($infos['label'])?': '.$infos['label']:'').' (liste)',
						'style' => array(
							'bold' => true,
							'font-size' => $titleSize
						)
					);
					$stream[]= array('content'=>  $indentation.'{{#'.$parent.$macro.'}}');
					if(is_array($infos['value']) && isset($infos['value'][0])) $stream=  array_merge($stream,self::recursive_sample($infos['value'][0],$level+1));
					$stream[]= array('content'=> $indentation.'{{/'.$parent.$macro.'}}');
				break;
				case 'object':
					$stream[]= array(
						'content'=> $indentation.$parent.$macro.' '.(!empty($infos['label'])?': '.$infos['label']:''),
						'style' => array(
							'bold' => true,
							'font-size' => $titleSize
						)
					);
					$stream= array_merge( $stream,self::recursive_sample($infos['value'],$level+1,$parent.$macro));
				break;
				case 'image' :
					$stream[]= array('content'=> $indentation.'{{'.$parent.$macro.'::image}} : '.( !isset($infos['label']) ? '': $infos['label']));
				break;
				default :
					$stream[]= array('content'=> $indentation.'{{'.$parent.$macro.'}} : '.( !isset($infos['label']) ? '': $infos['label']));
				break;
			}
		}
		return $stream;
	}

	/** ROOT **/
	//Fichier [Content_Types].xml
	public static function content_types(){
		return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/><Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/><Override PartName="/word/webSettings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"/><Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"/><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/><Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/></Types>';
	}

	/** DOCPROPS **/
	//Fichier docProps/app.xml
	public static function app(){
		return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><Template>Normal.dotm</Template><TotalTime>0</TotalTime><Pages>1</Pages><Words>0</Words><Characters>0</Characters><Application>Microsoft Office Word</Application><DocSecurity>0</DocSecurity><Lines>1</Lines><Paragraphs>1</Paragraphs><ScaleCrop>false</ScaleCrop><HeadingPairs><vt:vector size="2" baseType="variant"><vt:variant><vt:lpstr>Titre</vt:lpstr></vt:variant><vt:variant><vt:i4>1</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size="1" baseType="lpstr"><vt:lpstr></vt:lpstr></vt:vector></TitlesOfParts><Company></Company><LinksUpToDate>false</LinksUpToDate><CharactersWithSpaces>0</CharactersWithSpaces><SharedDoc>false</SharedDoc><HyperlinksChanged>false</HyperlinksChanged><AppVersion>16.0000</AppVersion></Properties>';
	}
	//Fichier docProps/core.xml
	public static function core(){
		global $myUser;
		return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:title></dc:title><dc:subject></dc:subject><dc:creator>'.$myUser->fullName().'</dc:creator><cp:keywords></cp:keywords><cp:lastModifiedBy>'.$myUser->fullName().'</cp:lastModifiedBy><cp:revision>1</cp:revision><dcterms:created xsi:type="dcterms:W3CDTF">'.date('Y-m-d').'T'.date('H:i:s').'Z'.'</dcterms:created><dcterms:modified xsi:type="dcterms:W3CDTF">'.date('Y-m-d').'T'.date('H:i:s').'Z'.'</dcterms:modified></cp:coreProperties>';
	}


	/** _RELS **/
	//Fichier _rels/.rels
	public static function single_rels(){
		return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>';
	}


	/** WORD **/
	//Fichier word/_rels/document.xml.rels
	public static function word_rels(){
		return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings" Target="webSettings.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/><Relationship Id="rId4" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable" Target="fontTable.xml"/></Relationships>';
	}

	//Fichier word/webSettings.xml
	public static function web_settings(){
		return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:webSettings xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" mc:Ignorable="w14 w15 w16se w16cid"><w:optimizeForBrowser/><w:allowPNG/></w:webSettings>';
	}

	//Fichier word/settings.xml
	public static function settings(){
		return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:settings xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" xmlns:sl="http://schemas.openxmlformats.org/schemaLibrary/2006/main" mc:Ignorable="w14 w15 w16se w16cid"><w:zoom w:percent="100"/><w:proofState w:spelling="clean" w:grammar="clean"/><w:defaultTabStop w:val="708"/><w:hyphenationZone w:val="425"/><w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/><w:compatSetting w:name="overrideTableStyleFontSizeAndJustification" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="enableOpenTypeFeatures" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="doNotFlipMirrorIndents" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="differentiateMultirowTableHeaders" w:uri="http://schemas.microsoft.com/office/word" w:val="1"/><w:compatSetting w:name="useWord2013TrackBottomHyphenation" w:uri="http://schemas.microsoft.com/office/word" w:val="0"/></w:compat><m:mathPr><m:mathFont m:val="Cambria Math"/><m:brkBin m:val="before"/><m:brkBinSub m:val="--"/><m:smallFrac m:val="0"/><m:dispDef/><m:lMargin m:val="0"/><m:rMargin m:val="0"/><m:defJc m:val="centerGroup"/><m:wrapIndent m:val="1440"/><m:intLim m:val="subSup"/><m:naryLim m:val="undOvr"/></m:mathPr><w:themeFontLang w:val="fr-FR"/><w:clrSchemeMapping w:bg1="light1" w:t1="dark1" w:bg2="light2" w:t2="dark2" w:accent1="accent1" w:accent2="accent2" w:accent3="accent3" w:accent4="accent4" w:accent5="accent5" w:accent6="accent6" w:hyperlink="hyperlink" w:followedHyperlink="followedHyperlink"/><w:shapeDefaults><o:shapedefaults v:ext="edit" spidmax="1026"/><o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1"/></o:shapelayout></w:shapeDefaults><w:decimalSymbol w:val=","/><w:listSeparator w:val=";"/><w15:chartTrackingRefBased/><w15:docId w15:val="{E4CFD658-C7F9-47A9-A972-9FA0C777DED5}"/></w:settings>';
	}

	//Fichier word/fontTable.xml
	public static function font_table(){
		return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:fonts xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" mc:Ignorable="w14 w15 w16se w16cid"><w:font w:name="Calibri"><w:panose1 w:val="020F0502020204030204"/><w:charset w:val="00"/><w:family w:val="swiss"/><w:pitch w:val="variable"/><w:sig w:usb0="E0002AFF" w:usb1="4000ACFF" w:usb2="00000001" w:usb3="00000000" w:csb0="000001FF" w:csb1="00000000"/></w:font></w:fonts>';
	}

	//créée le document d'exemple
	public static function document($rows){
		$stream = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex" xmlns:cx1="http://schemas.microsoft.com/office/drawing/2015/9/8/chartex" xmlns:cx2="http://schemas.microsoft.com/office/drawing/2015/10/21/chartex" xmlns:cx3="http://schemas.microsoft.com/office/drawing/2016/5/9/chartex" xmlns:cx4="http://schemas.microsoft.com/office/drawing/2016/5/10/chartex" xmlns:cx5="http://schemas.microsoft.com/office/drawing/2016/5/11/chartex" xmlns:cx6="http://schemas.microsoft.com/office/drawing/2016/5/12/chartex" xmlns:cx7="http://schemas.microsoft.com/office/drawing/2016/5/13/chartex" xmlns:cx8="http://schemas.microsoft.com/office/drawing/2016/5/14/chartex" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:aink="http://schemas.microsoft.com/office/drawing/2016/ink" xmlns:am3d="http://schemas.microsoft.com/office/drawing/2017/model3d" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" mc:Ignorable="w14 w15 w16se w16cid wp14"><w:body>';

		foreach($rows as $row){
			$stream .= '<w:p><w:r>';
			if(isset($row['style'])) {
				$stream .= '<w:rPr>';
				foreach ($row['style'] as $property => $value) {
					$stream .= self::custom_style_map($property, $value);
				}
				$stream .= '</w:rPr>';
			}
			if(isset($row['content'])) $stream .= '<w:t xml:space="preserve">'. htmlspecialchars($row['content'], ENT_COMPAT).'</w:t>';
			$stream .= '</w:r></w:p>';
		}

		$stream .= '<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="720" w:header="708" w:footer="708" w:gutter="0"/><w:cols w:space="708"/><w:docGrid w:linePitch="360"/></w:sectPr></w:body></w:document>';

		return $stream;
	}

	//Retourne les différentes balises de style
	public static function custom_style_map($property=null, $value=null){

		$stdColor = '000000';
		$stdHighlight = 'none';
		$stdHighlightColors= array('black','blue','cyan','green','magenta','red','yellow','white','darkBlue','darkCyan','darkGreen','darkMagenta','darkRed','darkYellow','darkGray','lightGray');

		$basic = array(
			'bold' => array('tag'=>'<w:b/>'),
			'italic' => array('tag'=>'<w:i/>'),
			'underline' => array('tag'=>'<w:u w:val="single"/>'),
			'strike' => array('tag'=>'<w:strike/>'),
			'caps' => array('tag'=>'<w:caps/>'),
		);

		if(isset($value)){
			$advanced =	array(
				'font-size' => array('tag'=>'<w:sz w:val="'.(is_numeric($value)?$value*2:22).'"/>'),
				'color' => array('tag'=>'<w:color w:val="'.(ctype_xdigit($value) && strlen($value)==6)?ltrim($value,'#'):$stdColor.'"/>'),
				'highlight' => array('tag'=>'<w:highlight w:val="'.(in_array($value,$stdHighlightColors))?$value:$stdHighlight.'"/>')
			);
		}
		$styles = array_merge($basic, $advanced);
		return isset($property) && isset($styles[$property]) ? $styles[$property]['tag'] : '';
	}

	//Crée un fichier Word (format .docx) au chemin
	//$path indiqué avec les données $rows fournies
	//en paramètres
	/** Tableau de données attendu :
	 *	$rows = array(
	 *		0 => array(
	 *			'content' => 'Macros disponibles :',
	 *			'style' => array(
	 *				'bold' => true,
	 *				'font-size' => 16
	 *			)
	 *		),
	 *		1 => array(
	 *			'content' => '[programme.date]'
	 *		),
	 *		2 => array(
	 *			'content' => '[programme.heure]'
	 *		)
	 *	);
	 *
	 * Chaque entrée dans $rows correspond à une ligne (paragraphe) sur le fichier
	 **/
	public static function write($path, $rows){
		$docx = new ZipArchive();

		if(file_exists($path)) unlink($path);
		$docx->open($path, ZipArchive::CREATE);

		//root
		$docx->addFromString('[Content_Types].xml', self::content_types());
		//_rels folder
		$docx->addFromString('_rels/.rels', self::single_rels());
		//docProps folder
		$docx->addFromString('docProps/app.xml', self::app());
		$docx->addFromString('docProps/core.xml', self::core());
		//word folder
		$docx->addFromString('word/_rels/document.xml.rels', self::word_rels());
		$docx->addFromString('word/document.xml', self::document($rows));
		$docx->addFromString('word/fontTable.xml', self::font_table());
		$docx->addFromString('word/settings.xml', self::settings());
		$docx->addFromString('word/webSettings.xml', self::web_settings());

		$docx->close();
	}

	public function parse($filePath){
		$this->zip = new ZipArchive();

		$res = $this->zip->open($filePath);
		if($res !== TRUE)  throw new Exception('Impossible d\'ouvrir le ZIP, code:' . $res);
		$this->body = self::strip($this->zip->getFromName('word/document.xml'));
		$this->footer = self::strip($this->zip->getFromName('word/footer1.xml'));
		$this->header = self::strip($this->zip->getFromName('word/header1.xml'));
		$this->relationships = $this->zip->getFromName('word/_rels/document.xml.rels');
	}

	public function add_image($img){
		//Unité utilisé en OOXML, 1px = 9525 EMU
		$emu = 9525;

		$finfo = new finfo(FILEINFO_MIME);
		$mime = $finfo->buffer($img);

		$ext = 'jpg';
		switch($mime){
			case 'image/jpeg': $ext = 'jpeg'; break;
			case 'image/png': $ext = 'png'; break;
			case 'image/gif': $ext = 'gif'; break;
		}
		if($mime == 'image/jpg') $mime = 'image/jpeg';

		list($width, $height) = getimagesizefromstring($img);

		$mimeTypes = $this->zip->getFromName('[Content_Types].xml', 0, ZipArchive::OVERWRITE);
		if(strrpos($mimeTypes, '<Default Extension="'.$ext.'" ContentType="'.$mime.'"/>') === false) {
			$mimeTypes = str_replace('</Types>', '<Default Extension="gif" ContentType="image/gif"/><Default Extension="png" ContentType="image/png"/><Default Extension="jpeg" ContentType="image/jpeg"/><Default Extension="jpg" ContentType="image/jpeg"/></Types>', $mimeTypes);
			$this->zip->addFromString('[Content_Types].xml', $mimeTypes);
		}

		$i = 100;
		$uid = 'img'.$i;
		while(strpos($this->relationships, 'Id="'.$uid.'"') !== false){
			$i++;
			$uid = 'img'.$i;
		}
		$this->zip->addFromString( 'word/media/'.$uid.'.'.$ext,$img);

		$rel = '<Relationship Id="'.$uid.'" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/'.$uid.'.'.$ext.'"/>';
		$this->relationships = str_replace('</Relationships>',$rel.'</Relationships>',$this->relationships);

		$xmlPic = '<w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0" ><wp:extent cx="'.$width*$emu.'" cy="'.$height*$emu.'"/><wp:effectExtent l="1" t="1" r="1" b="1"/><wp:docPr id="'.rand(100,200).'" name="'.$uid.'" descr=""/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="0" name=""/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="'.$uid.'"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="'.$width*$emu.'" cy="'.$height*$emu.'"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing>';

		return $xmlPic;
	}

	public function start(&$modelStream, $data){
		$this->destination = File::dir().'tmp'.SLASH.'template.'.time().'-'.rand(0,100).'.docx';
		file_put_contents($this->destination, utf8_decode($modelStream) );
		$this->parse($this->destination);
		$modelStream = $this->body;
	}

	public function from_template($stream, $datas){
		//if / loop
		$loopIfRegex = '/\{\{\#([^\/\#}]*)\}\}(.*?)\{\{\/\1\}\}/is';
		$stream =  preg_replace_callback($loopIfRegex,function($matches) use ($datas) {
			$key = $matches[1];
			$streamTpl = $matches[2];
			$keyInfos = explode('::',$key);
			$key = $keyInfos[0];
			$type = isset($keyInfos[1]) ? $keyInfos[1] : 'string';

			$value = $this->decomposeKey($datas,$key);

			//gestion des boucles
			if(is_array($value)){
				$stream = '';
				foreach($value as $line){
					$localData = is_array($line) ? array_merge($datas,$line) : $datas;
					$stream .= $this->from_template($streamTpl,$localData);
				}
				return $stream;
			//gestion des if
			}else{
				return !isset($value) || (!is_array($value) && empty($value)) || (is_array($value) && count($value)==0) ? '' : $this->from_template($streamTpl,$datas);
			}
		},$stream);

		//gestion des elses
		$elseRegex = '/\{\{\^([^\/\#}]*)\}\}(.*?)\{\{\/\1\}\}/is';
		$stream =  preg_replace_callback($elseRegex,function($matches) use ($datas) {
			$key = $matches[1];
			$streamTpl = $matches[2];

			$keyInfos = explode('::',$key);
			$key = $keyInfos[0];
			$type = isset($keyInfos[1]) ? $keyInfos[1] : 'string';

			$value = $this->decomposeKey($datas,$key);

			if(is_array($value)){
				$stream = '';
				foreach($value as $line){
					$localData = is_array($line) ? array_merge($datas,$line) : $datas;
					$stream .= $this->from_template($streamTpl,$localData);
				}
				return $stream;
			//gestion des else
			}else{
				return !isset($value) || (!is_array($value) && empty($value)) || (is_array($value) && count($value)==0) ? $this->from_template($streamTpl,$datas) : '';
			}
		},$stream);

		//gestion des simples variables
	    $stream = preg_replace_callback('/{{([^#\/}]*)}}/',function($matches) use ($datas) {
	        $key = $matches[1];

	        $keyInfos = explode('::',$key);
			$key = $keyInfos[0];
			$type = isset($keyInfos[1]) ? $keyInfos[1] : 'string';

	        $value = $this->decomposeKey($datas,$key);
	        if(!isset($value)) return $this->formatValue($type,$matches[0]);
	        if(is_array($value)) return 'Array';
	        return $this->formatValue($type,$value);
	    },$stream);

		return $stream;
	}

	public  function formatValue($type,$value){
		if($type == 'image') $value = $this->add_image($value);
		if($type == 'html') $value = self::convert_text_format($value);

		if($type == 'string'){
			//Remplace les & par des &amp;
			$value = str_replace(array('&'), array('&amp;'), $value);
			//remplace les balises non word (ne commencant pas par <w: ou </w: )
			$value = preg_replace('|<(?!/?w:)([^>]*)>|is', '&lt;$1&gt;', $value);
		}
		return $value;
	}

	public function end($stream,$data){
		$this->body = $stream;

		$this->footer = $this->from_template($this->footer, $data);
		$this->header = $this->from_template($this->header, $data);

		$this->zip->addFromString('word/document.xml', $this->body);
		if(!empty($this->header)) $this->zip->addFromString('word/header1.xml', $this->header);
		if(!empty($this->footer)) $this->zip->addFromString('word/footer1.xml', $this->footer);
		$this->zip->addFromString('word/_rels/document.xml.rels', $this->relationships);
		$this->zip->close();

		$stream = file_get_contents($this->destination);
		unlink($this->destination);
		return $stream;
	}

	public function decomposeKey($datas,$key){
		if(array_key_exists($key, $datas)) return isset($datas[$key]) ? $datas[$key] : '' ;

		$attributes = explode('.',$key);
		$current = $datas;
		$value = null;

        foreach ($attributes as $attribute) {
        	if(!array_key_exists($attribute, $current))  break;
        	$current = $current[$attribute];
        	$value = isset($current) ?  $current :  '';
        }
        return $value;
	}

	// Converti les data wysiwyg en wysiwyg word
	public static function convert_text_format($value){
		//Remplace les <p> et les <br> par les w:br word
		$value = str_replace(array('<br>','<p>','</p>','<ul>'),'<w:br/>',$value);
		//todo ameliorable
		$value = str_replace(array('<li>'),' - ',$value);
		$value = str_replace(array('</li>'),'<w:br/>',$value);
		$value = str_replace('</ul>','',$value);


		return $value;
	}

	public static function strip($content){
		$content = preg_replace_callback(
			'#\{\{([^\]]+)\}\}#U',
			function ($match) {
				return strip_tags($match[0]);
			},
			$content
		);
		return $content;
	}
}
?>