WordExport.class.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. <?php
  2. /**
  3. * Define a docx.
  4. * @author Valentin MORREEL
  5. * @category Plugin
  6. * @license MIT
  7. */
  8. class WordExport {
  9. public $mime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
  10. public $extension = 'docx';
  11. public $description = 'Fichier de traitement de texte Word';
  12. public $destination;
  13. public $zip,$body,$header,$footer,$relationships;
  14. public function sample($dataset,$level = 0,$parent=''){
  15. $rows = array();
  16. $rows[] = array(
  17. 'content' => 'Macros disponibles :',
  18. 'style' => array(
  19. 'bold' => true,
  20. 'font-size' => 16
  21. )
  22. );
  23. $rows = array_merge($rows, $this->recursive_sample($dataset,$level,$parent));
  24. $temp_file = tempnam(sys_get_temp_dir(), mt_rand(0,10000));
  25. self::write($temp_file, $rows);
  26. $stream = file_get_contents($temp_file);
  27. unlink($temp_file);
  28. return $stream;
  29. }
  30. public function recursive_sample($dataset,$level = 0,$parent=''){
  31. $stream = array();
  32. $parent = ($parent!=''?$parent.'.':'');
  33. $indentation = str_repeat("\t", $level);
  34. $titleSize = 18-($level*2);
  35. $titleSize = $titleSize < 12 ? $titleSize:12;
  36. foreach($dataset as $macro => $infos){
  37. $infos['type'] = isset($infos['type']) ? $infos['type'] : '';
  38. switch($infos['type']){
  39. case 'list':
  40. $stream[]= array(
  41. 'content'=> $indentation.$parent.$macro.' '.(isset($infos['label'])?': '.$infos['label']:'').' (liste)',
  42. 'style' => array(
  43. 'bold' => true,
  44. 'font-size' => $titleSize
  45. )
  46. );
  47. $stream[]= array('content'=> $indentation.'{{#'.$parent.$macro.'}}');
  48. if(is_array($infos['value']) && isset($infos['value'][0])) $stream= array_merge($stream,self::recursive_sample($infos['value'][0],$level+1));
  49. $stream[]= array('content'=> $indentation.'{{/'.$parent.$macro.'}}');
  50. break;
  51. case 'object':
  52. $stream[]= array(
  53. 'content'=> $indentation.$parent.$macro.' '.(!empty($infos['label'])?': '.$infos['label']:''),
  54. 'style' => array(
  55. 'bold' => true,
  56. 'font-size' => $titleSize
  57. )
  58. );
  59. $stream= array_merge( $stream,self::recursive_sample($infos['value'],$level+1,$parent.$macro));
  60. break;
  61. case 'image' :
  62. $stream[]= array('content'=> $indentation.'{{'.$parent.$macro.'::image}} : '.( !isset($infos['label']) ? '': $infos['label']));
  63. break;
  64. default :
  65. $stream[]= array('content'=> $indentation.'{{'.$parent.$macro.'}} : '.( !isset($infos['label']) ? '': $infos['label']));
  66. break;
  67. }
  68. }
  69. return $stream;
  70. }
  71. /** ROOT **/
  72. //Fichier [Content_Types].xml
  73. public static function content_types(){
  74. return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  75. <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>';
  76. }
  77. /** DOCPROPS **/
  78. //Fichier docProps/app.xml
  79. public static function app(){
  80. return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  81. <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>';
  82. }
  83. //Fichier docProps/core.xml
  84. public static function core(){
  85. global $myUser;
  86. return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  87. <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>';
  88. }
  89. /** _RELS **/
  90. //Fichier _rels/.rels
  91. public static function single_rels(){
  92. return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  93. <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>';
  94. }
  95. /** WORD **/
  96. //Fichier word/_rels/document.xml.rels
  97. public static function word_rels(){
  98. return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  99. <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>';
  100. }
  101. //Fichier word/webSettings.xml
  102. public static function web_settings(){
  103. return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  104. <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>';
  105. }
  106. //Fichier word/settings.xml
  107. public static function settings(){
  108. return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  109. <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>';
  110. }
  111. //Fichier word/fontTable.xml
  112. public static function font_table(){
  113. return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  114. <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>';
  115. }
  116. //créée le document d'exemple
  117. public static function document($rows){
  118. $stream = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  119. <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>';
  120. foreach($rows as $row){
  121. $stream .= '<w:p><w:r>';
  122. if(isset($row['style'])) {
  123. $stream .= '<w:rPr>';
  124. foreach ($row['style'] as $property => $value) {
  125. $stream .= self::custom_style_map($property, $value);
  126. }
  127. $stream .= '</w:rPr>';
  128. }
  129. if(isset($row['content'])) $stream .= '<w:t xml:space="preserve">'. htmlspecialchars($row['content'], ENT_COMPAT).'</w:t>';
  130. $stream .= '</w:r></w:p>';
  131. }
  132. $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>';
  133. return $stream;
  134. }
  135. //Retourne les différentes balises de style
  136. public static function custom_style_map($property=null, $value=null){
  137. $stdColor = '000000';
  138. $stdHighlight = 'none';
  139. $stdHighlightColors= array('black','blue','cyan','green','magenta','red','yellow','white','darkBlue','darkCyan','darkGreen','darkMagenta','darkRed','darkYellow','darkGray','lightGray');
  140. $basic = array(
  141. 'bold' => array('tag'=>'<w:b/>'),
  142. 'italic' => array('tag'=>'<w:i/>'),
  143. 'underline' => array('tag'=>'<w:u w:val="single"/>'),
  144. 'strike' => array('tag'=>'<w:strike/>'),
  145. 'caps' => array('tag'=>'<w:caps/>'),
  146. );
  147. if(isset($value)){
  148. $advanced = array(
  149. 'font-size' => array('tag'=>'<w:sz w:val="'.(is_numeric($value)?$value*2:22).'"/>'),
  150. 'color' => array('tag'=>'<w:color w:val="'.(ctype_xdigit($value) && strlen($value)==6)?ltrim($value,'#'):$stdColor.'"/>'),
  151. 'highlight' => array('tag'=>'<w:highlight w:val="'.(in_array($value,$stdHighlightColors))?$value:$stdHighlight.'"/>')
  152. );
  153. }
  154. $styles = array_merge($basic, $advanced);
  155. return isset($property) && isset($styles[$property]) ? $styles[$property]['tag'] : '';
  156. }
  157. //Crée un fichier Word (format .docx) au chemin
  158. //$path indiqué avec les données $rows fournies
  159. //en paramètres
  160. /** Tableau de données attendu :
  161. * $rows = array(
  162. * 0 => array(
  163. * 'content' => 'Macros disponibles :',
  164. * 'style' => array(
  165. * 'bold' => true,
  166. * 'font-size' => 16
  167. * )
  168. * ),
  169. * 1 => array(
  170. * 'content' => '[programme.date]'
  171. * ),
  172. * 2 => array(
  173. * 'content' => '[programme.heure]'
  174. * )
  175. * );
  176. *
  177. * Chaque entrée dans $rows correspond à une ligne (paragraphe) sur le fichier
  178. **/
  179. public static function write($path, $rows){
  180. $docx = new ZipArchive();
  181. if(file_exists($path)) unlink($path);
  182. $docx->open($path, ZipArchive::CREATE);
  183. //root
  184. $docx->addFromString('[Content_Types].xml', self::content_types());
  185. //_rels folder
  186. $docx->addFromString('_rels/.rels', self::single_rels());
  187. //docProps folder
  188. $docx->addFromString('docProps/app.xml', self::app());
  189. $docx->addFromString('docProps/core.xml', self::core());
  190. //word folder
  191. $docx->addFromString('word/_rels/document.xml.rels', self::word_rels());
  192. $docx->addFromString('word/document.xml', self::document($rows));
  193. $docx->addFromString('word/fontTable.xml', self::font_table());
  194. $docx->addFromString('word/settings.xml', self::settings());
  195. $docx->addFromString('word/webSettings.xml', self::web_settings());
  196. $docx->close();
  197. }
  198. public function parse($filePath){
  199. $this->zip = new ZipArchive();
  200. $res = $this->zip->open($filePath);
  201. if($res !== TRUE) throw new Exception('Impossible d\'ouvrir le ZIP, code:' . $res);
  202. $this->body = self::strip($this->zip->getFromName('word/document.xml'));
  203. $this->footer = self::strip($this->zip->getFromName('word/footer1.xml'));
  204. $this->header = self::strip($this->zip->getFromName('word/header1.xml'));
  205. $this->relationships = $this->zip->getFromName('word/_rels/document.xml.rels');
  206. }
  207. public function add_image($img){
  208. //Unité utilisé en OOXML, 1px = 9525 EMU
  209. $emu = 9525;
  210. $finfo = new finfo(FILEINFO_MIME);
  211. $mime = $finfo->buffer($img);
  212. $ext = 'jpg';
  213. switch($mime){
  214. case 'image/jpeg': $ext = 'jpeg'; break;
  215. case 'image/png': $ext = 'png'; break;
  216. case 'image/gif': $ext = 'gif'; break;
  217. }
  218. if($mime == 'image/jpg') $mime = 'image/jpeg';
  219. list($width, $height) = getimagesizefromstring($img);
  220. $mimeTypes = $this->zip->getFromName('[Content_Types].xml', 0, ZipArchive::OVERWRITE);
  221. if(strrpos($mimeTypes, '<Default Extension="'.$ext.'" ContentType="'.$mime.'"/>') === false) {
  222. $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);
  223. $this->zip->addFromString('[Content_Types].xml', $mimeTypes);
  224. }
  225. $i = 100;
  226. $uid = 'img'.$i;
  227. while(strpos($this->relationships, 'Id="'.$uid.'"') !== false){
  228. $i++;
  229. $uid = 'img'.$i;
  230. }
  231. $this->zip->addFromString( 'word/media/'.$uid.'.'.$ext,$img);
  232. $rel = '<Relationship Id="'.$uid.'" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/'.$uid.'.'.$ext.'"/>';
  233. $this->relationships = str_replace('</Relationships>',$rel.'</Relationships>',$this->relationships);
  234. $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>';
  235. return $xmlPic;
  236. }
  237. public function start(&$modelStream, $data){
  238. $this->destination = File::dir().'tmp'.SLASH.'template.'.time().'-'.rand(0,100).'.docx';
  239. file_put_contents($this->destination, utf8_decode($modelStream) );
  240. $this->parse($this->destination);
  241. $modelStream = $this->body;
  242. }
  243. public function from_template($stream, $datas){
  244. //if / loop
  245. $loopIfRegex = '/\{\{\#([^\/\#}]*)\}\}(.*?)\{\{\/\1\}\}/is';
  246. $stream = preg_replace_callback($loopIfRegex,function($matches) use ($datas) {
  247. $key = $matches[1];
  248. $streamTpl = $matches[2];
  249. $keyInfos = explode('::',$key);
  250. $key = $keyInfos[0];
  251. $type = isset($keyInfos[1]) ? $keyInfos[1] : 'string';
  252. $value = $this->decomposeKey($datas,$key);
  253. //gestion des boucles
  254. if(is_array($value)){
  255. $stream = '';
  256. foreach($value as $line){
  257. $localData = is_array($line) ? array_merge($datas,$line) : $datas;
  258. $stream .= $this->from_template($streamTpl,$localData);
  259. }
  260. return $stream;
  261. //gestion des if
  262. }else{
  263. return !isset($value) || (!is_array($value) && empty($value)) || (is_array($value) && count($value)==0) ? '' : $this->from_template($streamTpl,$datas);
  264. }
  265. },$stream);
  266. //gestion des elses
  267. $elseRegex = '/\{\{\^([^\/\#}]*)\}\}(.*?)\{\{\/\1\}\}/is';
  268. $stream = preg_replace_callback($elseRegex,function($matches) use ($datas) {
  269. $key = $matches[1];
  270. $streamTpl = $matches[2];
  271. $keyInfos = explode('::',$key);
  272. $key = $keyInfos[0];
  273. $type = isset($keyInfos[1]) ? $keyInfos[1] : 'string';
  274. $value = $this->decomposeKey($datas,$key);
  275. if(is_array($value)){
  276. $stream = '';
  277. foreach($value as $line){
  278. $localData = is_array($line) ? array_merge($datas,$line) : $datas;
  279. $stream .= $this->from_template($streamTpl,$localData);
  280. }
  281. return $stream;
  282. //gestion des else
  283. }else{
  284. return !isset($value) || (!is_array($value) && empty($value)) || (is_array($value) && count($value)==0) ? $this->from_template($streamTpl,$datas) : '';
  285. }
  286. },$stream);
  287. //gestion des simples variables
  288. $stream = preg_replace_callback('/{{([^#\/}]*)}}/',function($matches) use ($datas) {
  289. $key = $matches[1];
  290. $keyInfos = explode('::',$key);
  291. $key = $keyInfos[0];
  292. $type = isset($keyInfos[1]) ? $keyInfos[1] : 'string';
  293. $value = $this->decomposeKey($datas,$key);
  294. if(!isset($value)) return $this->formatValue($type,$matches[0]);
  295. if(is_array($value)) return 'Array';
  296. return $this->formatValue($type,$value);
  297. },$stream);
  298. return $stream;
  299. }
  300. public function formatValue($type,$value){
  301. if($type == 'image') $value = $this->add_image($value);
  302. if($type == 'html') $value = self::convert_text_format($value);
  303. if($type == 'string'){
  304. //Remplace les & par des &amp;
  305. $value = str_replace(array('&'), array('&amp;'), $value);
  306. //remplace les balises non word (ne commencant pas par <w: ou </w: )
  307. $value = preg_replace('|<(?!/?w:)([^>]*)>|is', '&lt;$1&gt;', $value);
  308. }
  309. return $value;
  310. }
  311. public function end($stream,$data){
  312. $this->body = $stream;
  313. $this->footer = $this->from_template($this->footer, $data);
  314. $this->header = $this->from_template($this->header, $data);
  315. $this->zip->addFromString('word/document.xml', $this->body);
  316. if(!empty($this->header)) $this->zip->addFromString('word/header1.xml', $this->header);
  317. if(!empty($this->footer)) $this->zip->addFromString('word/footer1.xml', $this->footer);
  318. $this->zip->addFromString('word/_rels/document.xml.rels', $this->relationships);
  319. $this->zip->close();
  320. $stream = file_get_contents($this->destination);
  321. unlink($this->destination);
  322. return $stream;
  323. }
  324. public function decomposeKey($datas,$key){
  325. if(array_key_exists($key, $datas)) return isset($datas[$key]) ? $datas[$key] : '' ;
  326. $attributes = explode('.',$key);
  327. $current = $datas;
  328. $value = null;
  329. foreach ($attributes as $attribute) {
  330. if(!array_key_exists($attribute, $current)) break;
  331. $current = $current[$attribute];
  332. $value = isset($current) ? $current : '';
  333. }
  334. return $value;
  335. }
  336. // Converti les data wysiwyg en wysiwyg word
  337. public static function convert_text_format($value){
  338. //Remplace les <p> et les <br> par les w:br word
  339. $value = str_replace(array('<br>','<p>','</p>','<ul>'),'<w:br/>',$value);
  340. //todo ameliorable
  341. $value = str_replace(array('<li>'),' - ',$value);
  342. $value = str_replace(array('</li>'),'<w:br/>',$value);
  343. $value = str_replace('</ul>','',$value);
  344. return $value;
  345. }
  346. public static function strip($content){
  347. $content = preg_replace_callback(
  348. '#\{\{([^\]]+)\}\}#U',
  349. function ($match) {
  350. return strip_tags($match[0]);
  351. },
  352. $content
  353. );
  354. return $content;
  355. }
  356. }
  357. ?>