Passed
Push — master ( 5cd161...fce549 )
by Tobias
03:57
created

DocxMustache::SaveOpenXmlObjectToFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 5
nc 2
nop 3
1
<?php
2
3
namespace WrkLst\DocxMustache;
4
5
use Exception;
6
use Illuminate\Support\Facades\Log;
7
8
//Custom DOCX template class to change content based on mustache templating engine.
9
class DocxMustache
10
{
11
    public $items;
12
    public $word_doc;
13
    public $template_file_name;
14
    public $template_file;
15
    public $local_path;
16
    public $storageDisk;
17
    public $storagePathPrefix;
18
    public $zipper;
19
    public $imageManipulation;
20
    public $verbose;
21
22
    public function __construct($items, $local_template_file)
23
    {
24
        $this->items = $items;
25
        $this->template_file_name = basename($local_template_file);
26
        $this->template_file = $local_template_file;
27
        $this->word_doc = false;
28
        $this->zipper = new \Chumper\Zipper\Zipper();
29
30
        //name of disk for storage
31
        $this->storageDisk = 'local';
32
33
        //prefix within your storage path
34
        $this->storagePathPrefix = 'app/';
35
36
        //if you use img urls that support manipulation via parameter
37
        $this->imageManipulation = ''; //'&w=1800';
38
39
        $this->verbose = false;
40
    }
41
42
    public function Execute()
43
    {
44
        $this->CopyTmplate();
45
        $this->ReadTeamplate();
46
    }
47
48
    /**
49
     * @param string $file
50
     */
51
    public function StoragePath($file)
52
    {
53
        return storage_path($file);
54
    }
55
56
    /**
57
     * @param string $msg
58
     */
59
    protected function Log($msg)
60
    {
61
        //introduce logging method here to keep track of process
62
        // can be overwritten in extended class to log with custom preocess logger
63
        if ($this->verbose) {
64
            Log::error($msg);
65
        }
66
    }
67
68
    public function CleanUpTmpDirs()
69
    {
70
        $now = time();
71
        $isExpired = ($now - (60 * 240));
72
        $disk = \Storage::disk($this->storageDisk);
73
        $all_dirs = $disk->directories($this->storagePathPrefix.'DocxMustache');
74
        foreach ($all_dirs as $dir) {
75
            //delete dirs older than 20min
76
            if ($disk->lastModified($dir) < $isExpired) {
77
                $disk->deleteDirectory($dir);
78
            }
79
        }
80
    }
81
82
    public function GetTmpDir()
83
    {
84
        $this->CleanUpTmpDirs();
85
        $path = $this->storagePathPrefix.'DocxMustache/'.uniqid($this->template_file).'/';
86
        \File::makeDirectory($this->StoragePath($path), 0775, true);
87
88
        return $path;
89
    }
90
91
    public function CopyTmplate()
92
    {
93
        $this->Log('Get Copy of Template');
94
        $this->local_path = $this->GetTmpDir();
95
        \Storage::disk($this->storageDisk)->copy($this->storagePathPrefix.$this->template_file, $this->local_path.$this->template_file_name);
96
    }
97
98
    protected function exctractOpenXmlFile($file)
99
    {
100
        $this->zipper->make($this->StoragePath($this->local_path.$this->template_file_name))
101
            ->extractTo($this->StoragePath($this->local_path), [$file], \Chumper\Zipper\Zipper::WHITELIST);
102
    }
103
104
    protected function ReadOpenXmlFile($file, $type = 'file')
105
    {
106
        $this->exctractOpenXmlFile($file);
107
108
        if ($type == 'file') {
109
            if ($file_contents = \Storage::disk($this->storageDisk)->get($this->local_path.$file)) {
110
                return $file_contents;
111
            } else {
112
                throw new Exception('Cannot not read file '.$file);
113
            }
114
        } else {
115
            if ($xml_object = simplexml_load_file($this->StoragePath($this->local_path.$file))) {
116
                return $xml_object;
117
            } else {
118
                throw new Exception('Cannot load XML Object from file '.$file);
119
            }
120
        }
121
    }
122
123
    protected function SaveOpenXmlFile($file, $folder, $content)
124
    {
125
        \Storage::disk($this->storageDisk)
126
            ->put($this->local_path.$file, $content);
127
        //add new content to word doc
128
        if ($folder) {
129
            $this->zipper->folder($folder)
130
                ->add($this->StoragePath($this->local_path.$file));
131
        } else {
132
            $this->zipper
133
                ->add($this->StoragePath($this->local_path.$file));
134
        }
135
    }
136
137
    protected function SaveOpenXmlObjectToFile($xmlObject, $file, $folder)
138
    {
139
        if ($xmlString = $xmlObject->asXML()) {
140
            $this->SaveOpenXmlFile($file, $folder, $xmlString);
141
        } else {
142
            throw new Exception('Cannot generate xml for '.$file);
143
        }
144
    }
145
146
    public function ReadTeamplate()
147
    {
148
        $this->Log('Analyze Template');
149
        //get the main document out of the docx archive
150
        $this->word_doc = $this->ReadOpenXmlFile('word/document.xml', 'file');
151
152
        $this->Log('Merge Data into Template');
153
154
        $this->word_doc = MustacheRender::render($this->items, $this->word_doc);
155
156
        $this->word_doc = HtmlConversion::convert($this->word_doc);
157
158
        $this->ImageReplacer();
159
160
        $this->Log('Compact Template with Data');
161
162
        $this->SaveOpenXmlFile('word/document.xml', 'word', $this->word_doc);
163
        $this->zipper->close();
164
    }
165
166
    protected function AddContentType($imageCt = 'jpeg')
167
    {
168
        $ct_file = $this->ReadOpenXmlFile('[Content_Types].xml', 'object');
169
170
        if (! ($ct_file instanceof \Traversable)) {
171
            throw new Exception('Cannot traverse through [Content_Types].xml.');
172
        }
173
174
        //check if content type for jpg has been set
175
        $i = 0;
176
        $ct_already_set = false;
177
        foreach ($ct_file as $ct) {
178
            if ((string) $ct_file->Default[$i]['Extension'] == $imageCt) {
179
                $ct_already_set = true;
180
            }
181
            $i++;
182
        }
183
184
        //if content type for jpg has not been set, add it to xml
185
        // and save xml to file and add it to the archive
186
        if (! $ct_already_set) {
187
            $sxe = $ct_file->addChild('Default');
188
            $sxe->addAttribute('Extension', $imageCt);
189
            $sxe->addAttribute('ContentType', 'image/'.$imageCt);
190
            $this->SaveOpenXmlObjectToFile($ct_file, '[Content_Types].xml', false);
191
        }
192
    }
193
194
    protected function FetchReplaceableImages(&$main_file, $ns)
195
    {
196
        //set up basic arrays to keep track of imgs
197
        $imgs = [];
198
        $imgs_replaced = []; // so they can later be removed from media and relation file.
199
        $newIdCounter = 1;
200
201
        //iterate through all drawing containers of the xml document
202
        foreach ($main_file->xpath('//w:drawing') as $k=>$drawing) {
203
            //figure out if there is a URL saved in the description field of the img
204
            $img_url = $this->AnalyseImgUrlString($drawing->children($ns['wp'])->xpath('wp:docPr')[0]->attributes()['descr']);
205
            $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->xpath('wp:docPr')[0]->attributes()['descr'] = $img_url['rest'];
206
207
            //if there is a url, save this img as a img to be replaced
208
            if ($img_url['valid']) {
209
                $ueid = 'wrklstId'.$newIdCounter;
210
                $wasId = (string) $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a'])->graphic->graphicData->children($ns['pic'])->pic->blipFill->children($ns['a'])->blip->attributes($ns['r'])['embed'];
211
212
                //get dimensions
213
                $cx = (int) $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a'])->graphic->graphicData->children($ns['pic'])->pic->spPr->children($ns['a'])->xfrm->ext->attributes()['cx'];
214
                $cy = (int) $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a'])->graphic->graphicData->children($ns['pic'])->pic->spPr->children($ns['a'])->xfrm->ext->attributes()['cy'];
215
216
                //remember img as being replaced
217
                $imgs_replaced[$wasId] = $wasId;
218
219
                //set new img id
220
                $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a'])->graphic->graphicData->children($ns['pic'])->pic->blipFill->children($ns['a'])->blip->attributes($ns['r'])['embed'] = $ueid;
221
222
                $imgs[] = [
223
                    'cx'     => (int) $cx,
224
                    'cy'     => (int) $cy,
225
                    'wasId'  => $wasId,
226
                    'id'     => $ueid,
227
                    'url'    => $img_url['url'],
228
                    'path'    => $img_url['path'],
229
                    'mode'    => $img_url['mode'],
230
                ];
231
232
                $newIdCounter++;
233
            }
234
        }
235
236
        return [
237
            'imgs'          => $imgs,
238
            'imgs_replaced' => $imgs_replaced,
239
        ];
240
    }
241
242
    protected function RemoveReplaceImages($imgs_replaced, &$rels_file)
243
    {
244
        //TODO: check if the same img is used at a different position int he file as well, as otherwise broken images are produced.
245
        //iterate through replaced images and clean rels files from them
246
        foreach ($imgs_replaced as $img_replaced) {
247
            $i = 0;
248
            foreach ($rels_file as $rel) {
249
                if ((string) $rel->attributes()['Id'] == $img_replaced) {
250
                    $this->zipper->remove('word/'.(string) $rel->attributes()['Target']);
251
                    unset($rels_file->Relationship[$i]);
252
                }
253
                $i++;
254
            }
255
        }
256
    }
257
258
    protected function InsertImages($ns, &$imgs, &$rels_file, &$main_file)
259
    {
260
        $docimage = new DocImage();
261
        $allowed_imgs = $docimage->AllowedContentTypeImages();
262
263
264
        $image_i = 1;
265
        //iterate through replacable images
266
        foreach ($imgs as $k=>$img) {
267
            $this->Log('Merge Images into Template - '.round($image_i/count($imgs)*100).'%';
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected ';', expecting ',' or ')'
Loading history...
268
            //get file type of img and test it against supported imgs
269
            if ($imgageData = $docimage->GetImageFromUrl($img['mode'] == 'url' ? $img['url'] : $img['path'], $img['mode'] == 'url' ? $this->imageManipulation : '')) {
270
                $imgs[$k]['img_file_src'] = str_replace('wrklstId', 'wrklst_image', $img['id']).$allowed_imgs[$imgageData['mime']];
271
                $imgs[$k]['img_file_dest'] = str_replace('wrklstId', 'wrklst_image', $img['id']).'.jpeg';
272
273
                $resampled_img = $docimage->ResampleImage($this, $imgs, $k, $imgageData['data']);
274
275
                $sxe = $rels_file->addChild('Relationship');
276
                $sxe->addAttribute('Id', $img['id']);
277
                $sxe->addAttribute('Type', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image');
278
                $sxe->addAttribute('Target', 'media/'.$imgs[$k]['img_file_dest']);
279
280
                foreach ($main_file->xpath('//w:drawing') as $k=>$drawing) {
281
                    if ($img['id'] == $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a'])
282
                        ->graphic->graphicData->children($ns['pic'])->pic->blipFill->children($ns['a'])
283
                        ->blip->attributes($ns['r'])['embed']) {
284
                        $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a'])
285
                            ->graphic->graphicData->children($ns['pic'])->pic->spPr->children($ns['a'])
286
                            ->xfrm->ext->attributes()['cx'] = $resampled_img['width_emus'];
287
                        $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a'])
288
                            ->graphic->graphicData->children($ns['pic'])->pic->spPr->children($ns['a'])
289
                            ->xfrm->ext->attributes()['cy'] = $resampled_img['height_emus'];
290
                        //anchor images
291
                        if (isset($main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->anchor)) {
292
                            $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->anchor->extent->attributes()['cx'] = $resampled_img['width_emus'];
293
                            $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->anchor->extent->attributes()['cy'] = $resampled_img['height_emus'];
294
                        }
295
                        //inline images
296
                        elseif (isset($main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->inline)) {
297
                            $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->inline->extent->attributes()['cx'] = $resampled_img['width_emus'];
298
                            $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->inline->extent->attributes()['cy'] = $resampled_img['height_emus'];
299
                        }
300
301
                        break;
302
                    }
303
                }
304
            }
305
            $image_i++;
306
        }
307
    }
308
309
    protected function ImageReplacer()
310
    {
311
        $this->Log('Merge Images into Template');
312
313
        //load main doc xml
314
        $main_file = simplexml_load_string($this->word_doc);
315
316
        //get all namespaces of the document
317
        $ns = $main_file->getNamespaces(true);
318
319
        $replaceableImage = $this->FetchReplaceableImages($main_file, $ns);
320
        $imgs = $replaceableImage['imgs'];
321
        $imgs_replaced = $replaceableImage['imgs_replaced'];
322
323
        $rels_file = $this->ReadOpenXmlFile('word/_rels/document.xml.rels', 'object');
324
325
        //do not remove until it is checked if the same img is used at a different position int he file as well, as otherwise broken images are produced.
326
        //$this->RemoveReplaceImages($imgs_replaced, $rels_file);
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
327
328
        //add jpg content type if not set
329
        $this->AddContentType('jpeg');
330
331
        $this->InsertImages($ns, $imgs, $rels_file, $main_file);
332
333
        $this->SaveOpenXmlObjectToFile($rels_file, 'word/_rels/document.xml.rels', 'word/_rels');
334
335
        if ($main_file_xml = $main_file->asXML()) {
336
            $this->word_doc = $main_file_xml;
337
        } else {
338
            throw new Exception('Cannot generate xml for word/document.xml.');
339
        }
340
    }
341
342
    /**
343
     * @param string $string
344
     */
345
    protected function AnalyseImgUrlString($string)
346
    {
347
        $string = (string) $string;
348
        $start = '[IMG-REPLACE]';
349
        $end = '[/IMG-REPLACE]';
350
        $start_local = '[LOCAL_IMG_REPLACE]';
351
        $end_local = '[/LOCAL_IMG_REPLACE]';
352
        $valid = false;
353
        $url = '';
354
        $path = '';
355
356
        if ($string != str_replace($start, '', $string) && $string == str_replace($start.$end, '', $string)) {
357
            $string = ' '.$string;
358
            $ini = strpos($string, $start);
359
            if ($ini == 0) {
360
                $url = '';
361
                $rest = $string;
362
            } else {
363
                $ini += strlen($start);
364
                $len = ((strpos($string, $end, $ini)) - $ini);
365
                $url = substr($string, $ini, $len);
366
367
                $ini = strpos($string, $start);
368
                $len = strpos($string, $end, $ini + strlen($start)) + strlen($end);
369
                $rest = substr($string, 0, $ini).substr($string, $len);
370
            }
371
372
            $valid = true;
373
374
            //TODO: create a better url validity check
375
            if (! trim(str_replace(['http', 'https', ':', ' '], '', $url)) || $url == str_replace('http', '', $url)) {
376
                $valid = false;
377
            }
378
            $mode = 'url';
379
        } elseif ($string != str_replace($start_local, '', $string) && $string == str_replace($start_local.$end_local, '', $string)) {
380
            $string = ' '.$string;
381
            $ini = strpos($string, $start_local);
382
            if ($ini == 0) {
383
                $path = '';
384
                $rest = $string;
385
            } else {
386
                $ini += strlen($start_local);
387
                $len = ((strpos($string, $end_local, $ini)) - $ini);
388
                $path = str_replace('..', '', substr($string, $ini, $len));
389
390
                $ini = strpos($string, $start_local);
391
                $len = strpos($string, $end_local, $ini + strlen($start)) + strlen($end_local);
392
                $rest = substr($string, 0, $ini).substr($string, $len);
393
            }
394
395
            $valid = true;
396
397
            //check if path starts with storage path
398
            if (! starts_with($path, storage_path())) {
399
                $valid = false;
400
            }
401
            $mode = 'path';
402
        } else {
403
            $mode = 'nothing';
404
            $url = '';
405
            $path = '';
406
            $rest = str_replace([$start, $end, $start_local, $end_local], '', $string);
407
        }
408
409
        return [
410
            'mode' => $mode,
411
            'url'  => trim($url),
412
            'path' => trim($path),
413
            'rest' => trim($rest),
414
            'valid' => $valid,
415
        ];
416
    }
417
418
    public function SaveAsPdf()
419
    {
420
        $this->Log('Converting DOCX to PDF');
421
        //convert to pdf with libre office
422
        $command = 'soffice --headless --convert-to pdf '.$this->StoragePath($this->local_path.$this->template_file_name).' --outdir '.$this->StoragePath($this->local_path);
423
        $process = new \Symfony\Component\Process\Process($command);
424
        $process->start();
425
        while ($process->isRunning()) {
426
            //wait until process is ready
427
        }
428
        // executes after the command finishes
429
        if (! $process->isSuccessful()) {
430
            throw new \Symfony\Component\Process\Exception\ProcessFailedException($process);
431
        } else {
432
            $path_parts = pathinfo($this->StoragePath($this->local_path.$this->template_file_name));
433
434
            return $this->StoragePath($this->local_path.$path_parts['filename'].'pdf');
435
        }
436
    }
437
}
438