WordExport.class.php 22 KB

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