Passed
Pull Request — master (#29)
by
unknown
01:44
created

DocxMustache::SaveOpenXmlObjectToFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
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 \Wrklst\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($dpi = 72)
43
    {
44
        $this->CopyTmplate();
45
        $this->zipper->make($this->StoragePath($this->local_path.$this->template_file_name));
46
        $this->ReadTeamplate($dpi);
47
    }
48
49
    /**
50
     * @param string $file
51
     */
52
    public function StoragePath($file)
53
    {
54
        return storage_path($file);
55
    }
56
57
    /**
58
     * @param string $msg
59
     */
60
    protected function Log($msg)
61
    {
62
        //introduce logging method here to keep track of process
63
        // can be overwritten in extended class to log with custom preocess logger
64
        if ($this->verbose) {
65
            Log::error($msg);
66
        }
67
    }
68
69
    public function CleanUpTmpDirs()
70
    {
71
        $now = time();
72
        $isExpired = ($now - (60 * 240));
73
        $disk = \Storage::disk($this->storageDisk);
74
        $all_dirs = $disk->directories($this->storagePathPrefix.'DocxMustache');
75
        foreach ($all_dirs as $dir) {
76
            //delete dirs older than 20min
77
            if ($disk->lastModified($dir) < $isExpired) {
78
                $disk->deleteDirectory($dir);
79
            }
80
        }
81
    }
82
83
    public function GetTmpDir()
84
    {
85
        $this->CleanUpTmpDirs();
86
        $path = $this->storagePathPrefix.'DocxMustache/'.uniqid($this->template_file).'/';
87
        \File::makeDirectory($this->StoragePath($path), 0775, true);
88
89
        return $path;
90
    }
91
92
    public function CopyTmplate()
93
    {
94
        $this->Log('Get Copy of Template');
95
        $this->local_path = $this->GetTmpDir();
96
        \Storage::disk($this->storageDisk)->copy($this->storagePathPrefix.$this->template_file, $this->local_path.$this->template_file_name);
97
    }
98
99
    protected function exctractOpenXmlFile($file)
100
    {
101
        $this->zipper
102
            ->make($this->StoragePath($this->local_path.$this->template_file_name))
103
            ->extractTo($this->StoragePath($this->local_path), [$file], \Wrklst\Zipper\Zipper::WHITELIST);
104
    }
105
106
    protected function ReadOpenXmlFile($file, $type = '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($dpi)
147
    {
148
        $this->Log('Analyze Template');
149
150
        $this->relevant_files = [];
0 ignored issues
show
Bug introduced by
The property relevant_files does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
151
        //get every File in docx-Archive
152
        $this->zipper
153
            ->getRepository()->each([$this, 'retrieveFilesList']);
154
        foreach ($this->relevant_files as $file) {
155
            $this->SubstituteOpenXmlFile($file, $dpi);
156
        }
157
158
        $this->zipper->close();
159
    }
160
161
    public function retrieveFilesList($file, $stats)
0 ignored issues
show
Unused Code introduced by
The parameter $stats is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
162
    {
163
        $this->exctractOpenXmlFile($file);
164
        if (substr($file, -3) === 'xml' && substr($file, 0, 4) === 'word') {
165
            $this->relevant_files[] = $file;
166
        }
167
    }
168
169
    public function SubstituteOpenXmlFile($file, $dpi)
170
    {
171
        $this->word_doc = $this->ReadOpenXmlFile($file, 'file');
172
        // $this->Log('Merge Data into Template');
173
        $this->word_doc = MustacheRender::render($this->items, $this->word_doc);
174
175
        $this->word_doc = HtmlConversion::convert($this->word_doc);
176
        if ($file == 'word/document.xml') {
177
            $this->ImageReplacer($dpi);
178
        }
179
        $this->SaveOpenXmlFile($file, 'word', $this->word_doc);
180
    }
181
182
    protected function AddContentType($imageCt = 'jpeg')
183
    {
184
        $ct_file = $this->ReadOpenXmlFile('[Content_Types].xml', 'object');
185
186
        if (! ($ct_file instanceof \Traversable)) {
187
            throw new Exception('Cannot traverse through [Content_Types].xml.');
188
        }
189
190
        //check if content type for jpg has been set
191
        $i = 0;
192
        $ct_already_set = false;
193
        foreach ($ct_file as $ct) {
194
            if ((string) $ct_file->Default[$i]['Extension'] == $imageCt) {
0 ignored issues
show
Bug introduced by
Accessing Default on the interface Traversable suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
195
                $ct_already_set = true;
196
            }
197
            $i++;
198
        }
199
200
        //if content type for jpg has not been set, add it to xml
201
        // and save xml to file and add it to the archive
202
        if (! $ct_already_set) {
203
            $sxe = $ct_file->addChild('Default');
204
            $sxe->addAttribute('Extension', $imageCt);
205
            $sxe->addAttribute('ContentType', 'image/'.$imageCt);
206
            $this->SaveOpenXmlObjectToFile($ct_file, '[Content_Types].xml', false);
207
        }
208
    }
209
210
    protected function FetchReplaceableImages(&$main_file, $ns)
211
    {
212
        //set up basic arrays to keep track of imgs
213
        $imgs = [];
214
        $imgs_replaced = []; // so they can later be removed from media and relation file.
215
        $newIdCounter = 1;
216
217
        //iterate through all drawing containers of the xml document
218
        foreach ($main_file->xpath('//w:drawing') as $k=>$drawing) {
219
            //figure out if there is a URL saved in the description field of the img
220
            $img_url = $this->AnalyseImgUrlString($drawing->children($ns['wp'])->xpath('wp:docPr')[0]->attributes()['descr']);
221
            $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->xpath('wp:docPr')[0]->attributes()['descr'] = $img_url['rest'];
222
223
            //if there is a url, save this img as a img to be replaced
224
            if ($img_url['valid']) {
225
                $ueid = 'wrklstId'.$newIdCounter;
226
                $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'];
227
228
                //get dimensions
229
                $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'];
230
                $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'];
231
232
                //remember img as being replaced
233
                $imgs_replaced[$wasId] = $wasId;
234
235
                //set new img id
236
                $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;
237
238
                $imgs[] = [
239
                    'cx'     => (int) $cx,
240
                    'cy'     => (int) $cy,
241
                    'wasId'  => $wasId,
242
                    'id'     => $ueid,
243
                    'url'    => $img_url['url'],
244
                    'path'    => $img_url['path'],
245
                    'mode'    => $img_url['mode'],
246
                ];
247
248
                $newIdCounter++;
249
            }
250
        }
251
252
        return [
253
            'imgs'          => $imgs,
254
            'imgs_replaced' => $imgs_replaced,
255
        ];
256
    }
257
258
    protected function RemoveReplaceImages($imgs_replaced, &$rels_file)
259
    {
260
        //TODO: check if the same img is used at a different position int he file as well, as otherwise broken images are produced.
261
        //iterate through replaced images and clean rels files from them
262
        foreach ($imgs_replaced as $img_replaced) {
263
            $i = 0;
264
            foreach ($rels_file as $rel) {
265
                if ((string) $rel->attributes()['Id'] == $img_replaced) {
266
                    $this->zipper->remove('word/'.(string) $rel->attributes()['Target']);
267
                    unset($rels_file->Relationship[$i]);
268
                }
269
                $i++;
270
            }
271
        }
272
    }
273
274
    protected function InsertImages($ns, &$imgs, &$rels_file, &$main_file, $dpi)
275
    {
276
        $docimage = new DocImage();
277
        $allowed_imgs = $docimage->AllowedContentTypeImages();
278
        $image_i = 1;
279
        //iterate through replacable images
280
        foreach ($imgs as $k=>$img) {
281
            $this->Log('Merge Images into Template - '.round($image_i / count($imgs) * 100).'%');
282
            //get file type of img and test it against supported imgs
283
            if ($imgageData = $docimage->GetImageFromUrl($img['mode'] == 'url' ? $img['url'] : $img['path'], $img['mode'] == 'url' ? $this->imageManipulation : '')) {
284
                $imgs[$k]['img_file_src'] = str_replace('wrklstId', 'wrklst_image', $img['id']).$allowed_imgs[$imgageData['mime']];
285
                $imgs[$k]['img_file_dest'] = str_replace('wrklstId', 'wrklst_image', $img['id']).'.jpeg';
286
287
                $resampled_img = $docimage->ResampleImage($this, $imgs, $k, $imgageData['data'], $dpi);
288
289
                $sxe = $rels_file->addChild('Relationship');
290
                $sxe->addAttribute('Id', $img['id']);
291
                $sxe->addAttribute('Type', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image');
292
                $sxe->addAttribute('Target', 'media/'.$imgs[$k]['img_file_dest']);
293
294
                foreach ($main_file->xpath('//w:drawing') as $k=>$drawing) {
295
                    if (null !== $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a'])
296
                        ->graphic->graphicData->children($ns['pic'])->pic->blipFill &&
297
                        $img['id'] == $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a'])
298
                        ->graphic->graphicData->children($ns['pic'])->pic->blipFill->children($ns['a'])
299
                        ->blip->attributes($ns['r'])['embed']) {
300
                        $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a'])
301
                            ->graphic->graphicData->children($ns['pic'])->pic->spPr->children($ns['a'])
302
                            ->xfrm->ext->attributes()['cx'] = $resampled_img['width_emus'];
303
                        $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->children($ns['a'])
304
                            ->graphic->graphicData->children($ns['pic'])->pic->spPr->children($ns['a'])
305
                            ->xfrm->ext->attributes()['cy'] = $resampled_img['height_emus'];
306
                        //anchor images
307
                        if (isset($main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->anchor)) {
308
                            $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->anchor->extent->attributes()['cx'] = $resampled_img['width_emus'];
309
                            $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->anchor->extent->attributes()['cy'] = $resampled_img['height_emus'];
310
                        }
311
                        //inline images
312
                        elseif (isset($main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->inline)) {
313
                            $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->inline->extent->attributes()['cx'] = $resampled_img['width_emus'];
314
                            $main_file->xpath('//w:drawing')[$k]->children($ns['wp'])->inline->extent->attributes()['cy'] = $resampled_img['height_emus'];
315
                        }
316
317
                        break;
318
                    }
319
                }
320
            }
321
            $image_i++;
322
        }
323
    }
324
325
    protected function ImageReplacer($dpi)
326
    {
327
        $this->Log('Load XML Document to Merge Images');
328
329
        //load main doc xml
330
        libxml_use_internal_errors(true);
331
        $main_file = simplexml_load_string($this->word_doc);
332
333
        if (gettype($main_file) == 'object') {
334
            $this->Log('Merge Images into Template');
335
336
            //get all namespaces of the document
337
            $ns = $main_file->getNamespaces(true);
338
339
            $replaceableImage = $this->FetchReplaceableImages($main_file, $ns);
340
            $imgs = $replaceableImage['imgs'];
341
            $imgs_replaced = $replaceableImage['imgs_replaced'];
0 ignored issues
show
Unused Code introduced by
$imgs_replaced is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
342
343
            $rels_file = $this->ReadOpenXmlFile('word/_rels/document.xml.rels', 'object');
344
345
            //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.
346
            //$this->RemoveReplaceImages($imgs_replaced, $rels_file);
347
348
            //add jpg content type if not set
349
            $this->AddContentType('jpeg');
350
351
            $this->InsertImages($ns, $imgs, $rels_file, $main_file, $dpi);
352
353
            $this->SaveOpenXmlObjectToFile($rels_file, 'word/_rels/document.xml.rels', 'word/_rels');
354
355
            if ($main_file_xml = $main_file->asXML()) {
356
                $this->word_doc = $main_file_xml;
357
            } else {
358
                throw new Exception('Cannot generate xml for word/document.xml.');
359
            }
360
        } else {
361
            $xmlerror = '';
362
            $errors = libxml_get_errors();
363
            foreach ($errors as $error) {
364
                // handle errors here
365
                $xmlerror .= $this->display_xml_error($error, explode("\n", $this->word_doc));
366
            }
367
            libxml_clear_errors();
368
            $this->Log('Error: Could not load XML file. '.$xmlerror);
369
            libxml_clear_errors();
370
        }
371
    }
372
373
    /*
374
    example for extracting xml errors from
375
    http://php.net/manual/en/function.libxml-get-errors.php
376
    */
377
    protected function display_xml_error($error, $xml)
378
    {
379
        $return = $xml[$error->line - 1]."\n";
380
        $return .= str_repeat('-', $error->column)."^\n";
381
382
        switch ($error->level) {
383
            case LIBXML_ERR_WARNING:
384
                $return .= "Warning $error->code: ";
385
                break;
386
                case LIBXML_ERR_ERROR:
387
                $return .= "Error $error->code: ";
388
                break;
389
            case LIBXML_ERR_FATAL:
390
                $return .= "Fatal Error $error->code: ";
391
                break;
392
        }
393
394
        $return .= trim($error->message).
395
                    "\n  Line: $error->line".
396
                    "\n  Column: $error->column";
397
398
        if ($error->file) {
399
            $return .= "\n  File: $error->file";
400
        }
401
402
        return "$return\n\n--------------------------------------------\n\n";
403
    }
404
405
    /**
406
     * @param string $string
407
     */
408
    protected function AnalyseImgUrlString($string)
409
    {
410
        $string = (string) $string;
411
        $start = '[IMG-REPLACE]';
412
        $end = '[/IMG-REPLACE]';
413
        $start_local = '[LOCAL_IMG_REPLACE]';
414
        $end_local = '[/LOCAL_IMG_REPLACE]';
415
        $valid = false;
416
        $url = '';
417
        $path = '';
418
419
        if ($string != str_replace($start, '', $string) && $string == str_replace($start.$end, '', $string)) {
420
            $string = ' '.$string;
421
            $ini = strpos($string, $start);
422 View Code Duplication
            if ($ini == 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
423
                $url = '';
424
                $rest = $string;
425
            } else {
426
                $ini += strlen($start);
427
                $len = ((strpos($string, $end, $ini)) - $ini);
428
                $url = substr($string, $ini, $len);
429
430
                $ini = strpos($string, $start);
431
                $len = strpos($string, $end, $ini + strlen($start)) + strlen($end);
432
                $rest = substr($string, 0, $ini).substr($string, $len);
433
            }
434
435
            $valid = true;
436
437
            //TODO: create a better url validity check
438
            if (! trim(str_replace(['http', 'https', ':', ' '], '', $url)) || $url == str_replace('http', '', $url)) {
439
                $valid = false;
440
            }
441
            $mode = 'url';
442
        } elseif ($string != str_replace($start_local, '', $string) && $string == str_replace($start_local.$end_local, '', $string)) {
443
            $string = ' '.$string;
444
            $ini = strpos($string, $start_local);
445 View Code Duplication
            if ($ini == 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
446
                $path = '';
447
                $rest = $string;
448
            } else {
449
                $ini += strlen($start_local);
450
                $len = ((strpos($string, $end_local, $ini)) - $ini);
451
                $path = str_replace('..', '', substr($string, $ini, $len));
452
453
                $ini = strpos($string, $start_local);
454
                $len = strpos($string, $end_local, $ini + strlen($start)) + strlen($end_local);
455
                $rest = substr($string, 0, $ini).substr($string, $len);
456
            }
457
458
            $valid = true;
459
460
            //check if path starts with storage path
461
            if (! starts_with($path, storage_path())) {
462
                $valid = false;
463
            }
464
            $mode = 'path';
465
        } else {
466
            $mode = 'nothing';
467
            $url = '';
468
            $path = '';
469
            $rest = str_replace([$start, $end, $start_local, $end_local], '', $string);
470
        }
471
472
        return [
473
            'mode' => $mode,
474
            'url'  => trim($url),
475
            'path' => trim($path),
476
            'rest' => trim($rest),
477
            'valid' => $valid,
478
        ];
479
    }
480
481
    public function SaveAsPdf()
482
    {
483
        $this->Log('Converting DOCX to PDF');
484
        //convert to pdf with libre office
485
        $process = new \Symfony\Component\Process\Process([
486
            'soffice',
487
            '--headless',
488
            '--convert-to',
489
            'pdf',
490
            $this->StoragePath($this->local_path.$this->template_file_name),
491
            '--outdir',
492
            $this->StoragePath($this->local_path),
493
        ]);
494
        $process->start();
495
        while ($process->isRunning()) {
496
            //wait until process is ready
497
        }
498
        // executes after the command finishes
499
        if (! $process->isSuccessful()) {
500
            throw new \Symfony\Component\Process\Exception\ProcessFailedException($process);
501
        } else {
502
            $path_parts = pathinfo($this->StoragePath($this->local_path.$this->template_file_name));
503
504
            return $this->StoragePath($this->local_path.$path_parts['filename'].'.pdf');
505
        }
506
    }
507
}
508