Gitlab CSE Unil

pdf.php 29.5 KB
Newer Older
M. Chardon's avatar
init  
M. Chardon committed
1
<?php
M. Chardon's avatar
M. Chardon committed
2

M. Chardon's avatar
init  
M. Chardon committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Library code for manipulating PDFs
 *
 * @package assignfeedback_editpdfplus
M. Chardon's avatar
GPL3    
M. Chardon committed
22
 * @copyright  2016 Université de Lausanne
23
 * The code is based on mod/assign/feedback/editpdf/classes/pdf.php by Davo Smith.
M. Chardon's avatar
init  
M. Chardon committed
24
25
26
27
28
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace assignfeedback_editpdfplus;

M. Chardon's avatar
M. Chardon committed
29
30
31
use \assignfeedback_editpdfplus\utils_color;
use \assignfeedback_editpdfplus\utils_stamp;

M. Chardon's avatar
init  
M. Chardon committed
32
33
34
defined('MOODLE_INTERNAL') || die();

global $CFG;
M. Chardon's avatar
M. Chardon committed
35
require_once($CFG->libdir . '/pdflib.php');
36
require_once($CFG->dirroot . '/mod/assign/feedback/editpdfplus/fpdi/autoload.php');
M. Chardon's avatar
init  
M. Chardon committed
37

38
39
40
use \setasign\Fpdi\Tcpdf\Fpdi;

class pdf extends Fpdi {
M. Chardon's avatar
init  
M. Chardon committed
41
42
43

    /** @var int the number of the current page in the PDF being processed */
    protected $currentpage = 0;
M. Chardon's avatar
M. Chardon committed
44

M. Chardon's avatar
init  
M. Chardon committed
45
46
    /** @var int the total number of pages in the PDF being processed */
    protected $pagecount = 0;
M. Chardon's avatar
M. Chardon committed
47

M. Chardon's avatar
init  
M. Chardon committed
48
49
    /** @var float used to scale the pixel position of annotations (in the database) to the position in the final PDF */
    protected $scale = 0.0;
M. Chardon's avatar
M. Chardon committed
50

M. Chardon's avatar
init  
M. Chardon committed
51
52
    /** @var string the path to the PDF currently being processed */
    protected $filename = null;
53
54
    public $arrayLinks = array();
    public $arrayLinksOrigi = array();
M. Chardon's avatar
init  
M. Chardon committed
55
56
57

    /** No errors */
    const GSPATH_OK = 'ok';
M. Chardon's avatar
M. Chardon committed
58

M. Chardon's avatar
init  
M. Chardon committed
59
60
    /** Not set */
    const GSPATH_EMPTY = 'empty';
M. Chardon's avatar
M. Chardon committed
61

M. Chardon's avatar
init  
M. Chardon committed
62
63
    /** Does not exist */
    const GSPATH_DOESNOTEXIST = 'doesnotexist';
M. Chardon's avatar
M. Chardon committed
64

M. Chardon's avatar
init  
M. Chardon committed
65
66
    /** Is a dir */
    const GSPATH_ISDIR = 'isdir';
M. Chardon's avatar
M. Chardon committed
67

M. Chardon's avatar
init  
M. Chardon committed
68
69
    /** Not executable */
    const GSPATH_NOTEXECUTABLE = 'notexecutable';
M. Chardon's avatar
M. Chardon committed
70

M. Chardon's avatar
init  
M. Chardon committed
71
72
    /** Test file missing */
    const GSPATH_NOTESTFILE = 'notestfile';
M. Chardon's avatar
M. Chardon committed
73

M. Chardon's avatar
init  
M. Chardon committed
74
75
    /** Any other error */
    const GSPATH_ERROR = 'error';
M. Chardon's avatar
M. Chardon committed
76

M. Chardon's avatar
init  
M. Chardon committed
77
78
    /** Min. width an annotation should have */
    const MIN_ANNOTATION_WIDTH = 5;
M. Chardon's avatar
M. Chardon committed
79

M. Chardon's avatar
init  
M. Chardon committed
80
81
82
    /** Min. height an annotation should have */
    const MIN_ANNOTATION_HEIGHT = 5;

83
    /** Blank PDF file used during error. */
84
    const BLANK_PDF = '/mod/assign/feedback/editpdfplus/fixtures/blank.pdf';
85

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
    /** Page image file name prefix */
    const IMAGE_PAGE = 'image_page';

    /**
     * Get the name of the font to use in generated PDF files.
     * If $CFG->pdfexportfont is set - use it, otherwise use "freesans" as this
     * open licensed font has wide support for different language charsets.
     *
     * @return string
     */
    private function get_export_font_name() {
        global $CFG;

        $fontname = 'freesans';
        if (!empty($CFG->pdfexportfont)) {
            $fontname = $CFG->pdfexportfont;
        }
        return $fontname;
    }

M. Chardon's avatar
init  
M. Chardon committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
    /**
     * Combine the given PDF files into a single PDF. Optionally add a coversheet and coversheet fields.
     * @param string[] $pdflist  the filenames of the files to combine
     * @param string $outfilename the filename to write to
     * @return int the number of pages in the combined PDF
     */
    public function combine_pdfs($pdflist, $outfilename) {

        raise_memory_limit(MEMORY_EXTRA);
        $olddebug = error_reporting(0);

        $this->setPageUnit('pt');
        $this->setPrintHeader(false);
        $this->setPrintFooter(false);
        $this->scale = 72.0 / 100.0;
121
122
        // Use font supporting the widest range of characters.
        $this->SetFont($this->get_export_font_name(), '', 16.0 * $this->scale, '', true);
M. Chardon's avatar
init  
M. Chardon committed
123
124
125
126
127
128
129
        $this->SetTextColor(0, 0, 0);

        $totalpagecount = 0;

        foreach ($pdflist as $file) {
            $pagecount = $this->setSourceFile($file);
            $totalpagecount += $pagecount;
M. Chardon's avatar
M. Chardon committed
130
            for ($i = 1; $i <= $pagecount; $i++) {
M. Chardon's avatar
init  
M. Chardon committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
                $this->create_page_from_source($i);
            }
        }

        $this->save_pdf($outfilename);
        error_reporting($olddebug);

        return $totalpagecount;
    }

    /**
     * The number of the current page in the PDF being processed
     * @return int
     */
    public function current_page() {
        return $this->currentpage;
    }

    /**
     * The total number of pages in the PDF being processed
     * @return int
     */
    public function page_count() {
        return $this->pagecount;
    }

    /**
     * Load the specified PDF and set the initial output configuration
     * Used when processing comments and outputting a new PDF
     * @param string $filename the path to the PDF to load
     * @return int the number of pages in the PDF
     */
    public function load_pdf($filename) {
        raise_memory_limit(MEMORY_EXTRA);
        $olddebug = error_reporting(0);

        $this->setPageUnit('pt');
        $this->scale = 72.0 / 100.0;
169
        $this->SetFont($this->get_export_font_name(), '', 16.0 * $this->scale, '', true);
M. Chardon's avatar
init  
M. Chardon committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
        $this->SetFillColor(255, 255, 176);
        $this->SetDrawColor(0, 0, 0);
        $this->SetLineWidth(1.0 * $this->scale);
        $this->SetTextColor(0, 0, 0);
        $this->setPrintHeader(false);
        $this->setPrintFooter(false);
        $this->pagecount = $this->setSourceFile($filename);
        $this->filename = $filename;

        error_reporting($olddebug);
        return $this->pagecount;
    }

    /**
     * Sets the name of the PDF to process, but only loads the file if the
     * pagecount is zero (in order to count the number of pages)
     * Used when generating page images (but not a new PDF)
     * @param string $filename the path to the PDF to process
     * @param int $pagecount optional the number of pages in the PDF, if known
     * @return int the number of pages in the PDF
     */
    public function set_pdf($filename, $pagecount = 0) {
        if ($pagecount == 0) {
            return $this->load_pdf($filename);
        } else {
            $this->filename = $filename;
            $this->pagecount = $pagecount;
            return $pagecount;
        }
    }

    /**
     * Copy the next page from the source file and set it as the current page
     * @return bool true if successful
     */
    public function copy_page() {
        if (!$this->filename) {
            return false;
        }
M. Chardon's avatar
M. Chardon committed
209
        if ($this->currentpage >= $this->pagecount) {
M. Chardon's avatar
init  
M. Chardon committed
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
            return false;
        }
        $this->currentpage++;
        $this->create_page_from_source($this->currentpage);
        return true;
    }

    /**
     * Create a page from a source PDF.
     *
     * @param int $pageno
     */
    protected function create_page_from_source($pageno) {
        // Get the size (and deduce the orientation) of the next page.
        $template = $this->importPage($pageno);
        $size = $this->getTemplateSize($template);
        $orientation = 'P';
        if ($size['w'] > $size['h']) {
            $orientation = 'L';
        }
        // Create a page of the required size / orientation.
        $this->AddPage($orientation, array($size['w'], $size['h']));
        // Prevent new page creation when comments are at the bottom of a page.
        $this->setPageOrientation($orientation, false, 0);
        // Fill in the page with the original contents from the student.
        $this->useTemplate($template);
    }

    /**
     * Copy all the remaining pages in the file
     */
    public function copy_remaining_pages() {
        $morepages = true;
        while ($morepages) {
            $morepages = $this->copy_page();
        }
    }

248
249
    /**
     * Add an annotation to the current page
M. Chardon's avatar
M. Chardon committed
250
     * 
M. Chardon's avatar
M. Chardon committed
251
     * @param \assignfeedback_editpdfplus\bdd\annotation $annotation
252
253
     * @param int[]|string $path optional for 'pen' annotations this is an array of x and y coordinates for
     *              the line, for 'stamp' annotations it is the name of the stamp file (without the path)
M. Chardon's avatar
M. Chardon committed
254
     * @param type $annotation_index
255
256
     * @return bool true if successful (always)
     */
M. Chardon's avatar
M. Chardon committed
257
    public function add_annotation(bdd\annotation $annotation, $path, $annotation_index) {
258
259
260
        if (!$this->filename) {
            return false;
        }
261

262
263
264
265
266
        //check tcpdf cache directory, needed for image transformation
        if (!file_exists(K_PATH_CACHE)) {
            //try to create the directory
            mkdir(K_PATH_CACHE, 0777, true);
        }
M. Chardon's avatar
M. Chardon committed
267

268
        $colour = $annotation->colour;
M. Chardon's avatar
M. Chardon committed
269
        $colourarray = utils_color::getColorRGB($colour); //$this->get_colour_for_pdf($colour);
M. Chardon's avatar
init  
M. Chardon committed
270
271
        $this->SetDrawColorArray($colourarray);

M. Chardon's avatar
M. Chardon committed
272
273
274
275
        $sx = $this->scale * $annotation->x;
        $sy = $this->scale * $annotation->y;
        $ex = $this->scale * $annotation->endx;
        $ey = $this->scale * $annotation->endy;
M. Chardon's avatar
init  
M. Chardon committed
276

277
        $this->SetLineWidth(2.0 * $this->scale);
M. Chardon's avatar
M. Chardon committed
278
279
280
        //$type = 'line';
        $toolid = $annotation->toolid;
        $toolObject = page_editor::get_tool($toolid);
M. Chardon's avatar
M. Chardon committed
281
        $typetool = $toolObject->typeObject;
M. Chardon's avatar
M. Chardon committed
282
        $type = $typetool->label;
283
284
285
286
        $colourcartridge = $toolObject->cartridge_color;
        if (!$colourcartridge) {
            $colourcartridge = $typetool->cartridge_color;
        }
M. Chardon's avatar
M. Chardon committed
287
        $colourcartridgearray = utils_color::getColorRGB($colourcartridge); //$this->get_colour_for_pdf($colourcartridge);
288
289
290
        $this->SetTextColorArray($colourcartridgearray);
        $this->SetFontSize(10);

M. Chardon's avatar
init  
M. Chardon committed
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
        switch ($type) {
            case 'oval':
                $rx = abs($sx - $ex) / 2;
                $ry = abs($sy - $ey) / 2;
                $sx = min($sx, $ex) + $rx;
                $sy = min($sy, $ey) + $ry;

                // $rx and $ry should be >= min width and height
                if ($rx < self::MIN_ANNOTATION_WIDTH) {
                    $rx = self::MIN_ANNOTATION_WIDTH;
                }
                if ($ry < self::MIN_ANNOTATION_HEIGHT) {
                    $ry = self::MIN_ANNOTATION_HEIGHT;
                }

                $this->Ellipse($sx, $sy, $rx, $ry);
                break;
            case 'rectangle':
                $w = abs($sx - $ex);
                $h = abs($sy - $ey);
                $sx = min($sx, $ex);
                $sy = min($sy, $ey);

                // Width or height should be >= min width and height
                if ($w < self::MIN_ANNOTATION_WIDTH) {
                    $w = self::MIN_ANNOTATION_WIDTH;
                }
                if ($h < self::MIN_ANNOTATION_HEIGHT) {
                    $h = self::MIN_ANNOTATION_HEIGHT;
                }
                $this->Rect($sx, $sy, $w, $h);
                break;
            case 'highlight':
                $w = abs($sx - $ex);
                $h = 8.0 * $this->scale;
                $sx = min($sx, $ex);
                $sy = min($sy, $ey) + ($h * 0.5);
                $this->SetAlpha(0.5, 'Normal', 0.5, 'Normal');
                $this->SetLineWidth(8.0 * $this->scale);

                // width should be >= min width
                if ($w < self::MIN_ANNOTATION_WIDTH) {
                    $w = self::MIN_ANNOTATION_WIDTH;
                }

                $this->Rect($sx, $sy, $w, $h);
                $this->SetAlpha(1.0, 'Normal', 1.0, 'Normal');
                break;
            case 'pen':
                if ($path) {
                    $scalepath = array();
                    $points = preg_split('/[,:]/', $path);
                    foreach ($points as $point) {
                        $scalepath[] = intval($point) * $this->scale;
                    }

                    if (!empty($scalepath)) {
                        $this->PolyLine($scalepath, 'S');
                    }
                }
                break;
M. Chardon's avatar
M. Chardon committed
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
            case 'highlightplus':
                $w = abs($sx - $ex);
                $h = 8.0 * $this->scale;
                $sx = min($sx, $ex);
                $sy = min($sy, $ey) + ($h * 0.5);
                $this->SetAlpha(0.5, 'Normal', 0.5, 'Normal');
                $this->SetLineWidth(8.0 * $this->scale);

                // width should be >= min width
                if ($w < self::MIN_ANNOTATION_WIDTH) {
                    $w = self::MIN_ANNOTATION_WIDTH;
                }

                $this->Rect($sx, $sy, $w, $h);
                $this->SetAlpha(1.0, 'Normal', 1.0, 'Normal');
367
368
369
370

                $scartx = ($annotation->cartridgex + $annotation->x) * $this->scale;
                $scarty = ($annotation->cartridgey + $annotation->y) * $this->scale;
                $this->SetXY($scartx, $scarty);
M. Chardon's avatar
M. Chardon committed
371
372
373
                break;
            case 'verticalline':
                $this->Line($sx, $sy, $sx, $ey);
374
375
376
377

                $scartx = ($annotation->cartridgex + $annotation->x) * $this->scale;
                $scarty = ($annotation->cartridgey + $annotation->y) * $this->scale;
                $this->SetXY($scartx, $scarty);
M. Chardon's avatar
M. Chardon committed
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
                break;
            case 'frame':
                $w = abs($sx - $ex);
                $h = abs($sy - $ey);
                $sx = min($sx, $ex);
                $sy = min($sy, $ey);

                // Width or height should be >= min width and height
                if ($w < self::MIN_ANNOTATION_WIDTH) {
                    $w = self::MIN_ANNOTATION_WIDTH;
                }
                if ($h < self::MIN_ANNOTATION_HEIGHT) {
                    $h = self::MIN_ANNOTATION_HEIGHT;
                }
                $this->Rect($sx, $sy, $w, $h);
393
394

                if (!$annotation->parent_annot) {
395
                    $scartx = max(($annotation->cartridgex) * $this->scale, 0);
396
397
398
                    $scarty = ($annotation->cartridgey + $annotation->y) * $this->scale;
                    $this->SetXY($scartx, $scarty);
                    $this->SetTextColorArray($colourarray);
399
                    //ne pas effacer, pour afficher du dash dans les encadrements
400
401
402
403
404
405
406
                    /* $this->writeHTMLCell(20, 20, $scartx, $scarty, "test", array(
                      'LRTB' => array(
                      'width' => 1, // careful, this is not px but the unit you declared
                      'dash' => 1,
                      'color' => array(0, 0, 0)
                      )
                      ), false, false, false, 'L', false); */
407
                }
M. Chardon's avatar
M. Chardon committed
408
409
                break;
            case 'stampcomment':
410
                if ($annotation->displayrotation == 1) {
411
                    $imgFileFromFA = utils_stamp::getPngFromFont("arrows-v", $colourcartridge);
M. Chardon's avatar
M. Chardon committed
412
413
414
415
                    //$imgfile = $CFG->dirroot . '/mod/assign/feedback/editpdfplus/pix/twoway_v_pdf.png';
                    //$h = 20; //abs($sy - $ey);
                    //$w = $h * 37 / 96;
                    $sx = min($sx, $ex) - 6;
416
                } else {
417
                    $imgFileFromFA = utils_stamp::getPngFromFont("arrows-h", $colourcartridge);
M. Chardon's avatar
M. Chardon committed
418
419
420
421
422
423
424
425
426
427
                    //$imgfile = $CFG->dirroot . '/mod/assign/feedback/editpdfplus/pix/twoway_h_pdf.png';
                    //$w = 20; //abs($sx - $ex);
                    //$h = $w * 37 / 96;
                    $sx = min($sx, $ex) - 1;
                }
                $sy = min($sy, $ey);
                $w = 30 * $this->scale;
                $h = 30 * $this->scale;
                if ($imgFileFromFA) {
                    $this->Image($imgFileFromFA, $sx, $sy, $w, $h);
428
429
430
431
432
                }

                $scartx = ($annotation->cartridgex + $annotation->x) * $this->scale;
                $scarty = ($annotation->cartridgey + $annotation->y) * $this->scale;
                $this->SetXY($scartx, $scarty);
M. Chardon's avatar
M. Chardon committed
433
434
                break;
            case 'commentplus':
435
                $imgFileFromFA = utils_stamp::getPngFromFont("commenting", $colourcartridge);
M. Chardon's avatar
M. Chardon committed
436
                //$imgfile = $CFG->dirroot . '/mod/assign/feedback/editpdfplus/pix/comment.png';
437
438
                $w = 16 * $this->scale;
                $h = 16 * $this->scale;
M. Chardon's avatar
M. Chardon committed
439
440
                $sx = min($sx, $ex);
                $sy = min($sy, $ey);
441
                $this->SetXY($sx + $w + 2, $sy);
M. Chardon's avatar
M. Chardon committed
442
443
444
                if ($imgFileFromFA) {
                    $this->Image($imgFileFromFA, $sx, $sy, $w, $h);
                }
M. Chardon's avatar
M. Chardon committed
445
446
447
448
449
450
451
452
453
454
455
456
457
458
                break;
            case 'stampplus':
                $w = abs($sx - $ex);
                $h = abs($sy - $ey);
                $sx = min($sx, $ex);
                $sy = min($sy, $ey);

                // Width or height should be >= min width and height
                if ($w < self::MIN_ANNOTATION_WIDTH) {
                    $w = self::MIN_ANNOTATION_WIDTH;
                }
                if ($h < self::MIN_ANNOTATION_HEIGHT) {
                    $h = self::MIN_ANNOTATION_HEIGHT;
                }
459
                $this->SetXY($sx, $sy);
460
461
462
463
464

                $colourcartridge = $toolObject->colors;
                if (!$colourcartridge) {
                    $colourcartridge = $typetool->color;
                }
M. Chardon's avatar
M. Chardon committed
465
                $colourcartridgearray = utils_color::getColorRGB($colourcartridge); //$this->get_colour_for_pdf($colourcartridge);
466
467
468
                $this->SetTextColorArray($colourcartridgearray);

                $cartouche = $toolObject->label;
469

470
                //Texte centré dans une cellule 20*10 mm encadrée et retour à la ligne
471
                $this->SetFont('freeserif', '', 10);
M. Chardon's avatar
M. Chardon committed
472
                $this->Cell(strlen($cartouche) * 6 + 4, 10, $cartouche, 1, 1, 'C');
473
                $this->SetFont($this->get_export_font_name());
474

M. Chardon's avatar
M. Chardon committed
475
                break;
M. Chardon's avatar
init  
M. Chardon committed
476
477
478
479
            default: // Line.
                $this->Line($sx, $sy, $ex, $ey);
                break;
        }
480
        if ($type == 'commentplus' || $type == 'stampcomment' || ($type == 'frame' && !$annotation->parent_annot) || $type == 'verticalline' || $type == 'highlightplus') {
481
482
            $cartouche = $toolObject->cartridge;
            if ($annotation->textannot) {
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
                if ($annotation->pdfdisplay === "inline") {
                    $cartouche .= ' | ' . $annotation->textannot;
                }
                $this->Write(5, $cartouche . ' [');

                //create link source for annotation's text
                $link = $this->addLink();
                $this->SetTextColor(0, 0, 255);
                $this->SetFont('', 'U');
                $this->Write(5, $annotation_index, $link);
                $this->SetTextColorArray($colourcartridgearray);
                $this->SetFont('', '');
                $this->arrayLinks[$annotation_index] = $link;

                $this->Write(5, ']');

                //create link target to go back to the annotation display
                $linkorigi = $this->addLink();
                $this->setLink($linkorigi, -1);
                $this->arrayLinksOrigi[$annotation_index] = $linkorigi;

504
                //$this->Annotation($sx + 50, $sy, 30, 30, $annotation->textannot, array('Subtype' => 'Text', 'Name' => 'Comment', 'T' => $toolObject->label, 'Subj' => 'example', 'C' => $colourarray));
505
            }
506
507
508

            //$html = '&nbsp;<a href="#annot' . $annotation_index . '" style="color:red;">' . '[#annot' . $annotation_index . ']' . '</a>';
            //$this->writeHTML($html);
509
510
        }

M. Chardon's avatar
init  
M. Chardon committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
        $this->SetDrawColor(0, 0, 0);
        $this->SetLineWidth(1.0 * $this->scale);

        return true;
    }

    /**
     * Save the completed PDF to the given file
     * @param string $filename the filename for the PDF (including the full path)
     */
    public function save_pdf($filename) {
        $olddebug = error_reporting(0);
        $this->Output($filename, 'F');
        error_reporting($olddebug);
    }

    /**
     * Set the path to the folder in which to generate page image files
     * @param string $folder
     */
    public function set_image_folder($folder) {
        $this->imagefolder = $folder;
    }

    /**
     * Generate an image of the specified page in the PDF
     * @param int $pageno the page to generate the image of
538
539
     * @throws \moodle_exception
     * @throws \coding_exception
M. Chardon's avatar
init  
M. Chardon committed
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
     * @return string the filename of the generated image
     */
    public function get_image($pageno) {
        global $CFG;

        if (!$this->filename) {
            throw new \coding_exception('Attempting to generate a page image without first setting the PDF filename');
        }

        if (!$this->imagefolder) {
            throw new \coding_exception('Attempting to generate a page image without first specifying the image output folder');
        }

        if (!is_dir($this->imagefolder)) {
            throw new \coding_exception('The specified image output folder is not a valid folder');
        }

557
        $imagefile = $this->imagefolder . '/' . self::IMAGE_PAGE . $pageno . '.png';
M. Chardon's avatar
init  
M. Chardon committed
558
559
        $generate = true;
        if (file_exists($imagefile)) {
M. Chardon's avatar
M. Chardon committed
560
            if (filemtime($imagefile) > filemtime($this->filename)) {
M. Chardon's avatar
init  
M. Chardon committed
561
562
563
564
565
566
567
568
569
570
571
572
                // Make sure the image is newer than the PDF file.
                $generate = false;
            }
        }

        if ($generate) {
            // Use ghostscript to generate an image of the specified page.
            $gsexec = \escapeshellarg($CFG->pathtogs);
            $imageres = \escapeshellarg(100);
            $imagefilearg = \escapeshellarg($imagefile);
            $filename = \escapeshellarg($this->filename);
            $pagenoinc = \escapeshellarg($pageno + 1);
M. Chardon's avatar
M. Chardon committed
573
574
            $command = "$gsexec -q -sDEVICE=png16m -dSAFER -dBATCH -dNOPAUSE -r$imageres -dFirstPage=$pagenoinc -dLastPage=$pagenoinc " .
                    "-dDOINTERPOLATE -dGraphicsAlphaBits=4 -dTextAlphaBits=4 -sOutputFile=$imagefilearg $filename";
M. Chardon's avatar
init  
M. Chardon committed
575
576
577
578

            $output = null;
            $result = exec($command, $output);
            if (!file_exists($imagefile)) {
M. Chardon's avatar
M. Chardon committed
579
                $fullerror = '<pre>' . get_string('command', 'assignfeedback_editpdfplus') . "\n";
M. Chardon's avatar
init  
M. Chardon committed
580
                $fullerror .= $command . "\n\n";
M. Chardon's avatar
M. Chardon committed
581
                $fullerror .= get_string('result', 'assignfeedback_editpdfplus') . "\n";
M. Chardon's avatar
init  
M. Chardon committed
582
                $fullerror .= htmlspecialchars($result) . "\n\n";
M. Chardon's avatar
M. Chardon committed
583
584
                $fullerror .= get_string('output', 'assignfeedback_editpdfplus') . "\n";
                $fullerror .= htmlspecialchars(implode("\n", $output)) . '</pre>';
M. Chardon's avatar
init  
M. Chardon committed
585
586
587
588
                throw new \moodle_exception('errorgenerateimage', 'assignfeedback_editpdfplus', '', $fullerror);
            }
        }

589
        return self::IMAGE_PAGE . $pageno . '.png';
M. Chardon's avatar
init  
M. Chardon committed
590
591
592
593
    }

    /**
     * Check to see if PDF is version 1.4 (or below); if not: use ghostscript to convert it
594
     * 
M. Chardon's avatar
init  
M. Chardon committed
595
596
597
598
599
600
     * @param stored_file $file
     * @return string path to copy or converted pdf (false == fail)
     */
    public static function ensure_pdf_compatible(\stored_file $file) {
        global $CFG;

601
        // Copy the stored_file to local disk for checking.
M. Chardon's avatar
M. Chardon committed
602
        $temparea = make_request_directory();
603
        $tempsrc = $temparea . "/source.pdf";
604
        $file->copy_content_to($tempsrc);
M. Chardon's avatar
init  
M. Chardon committed
605

606
607
608
609
610
611
612
613
614
615
616
617
        return self::ensure_pdf_file_compatible($tempsrc);
    }

    /**
     * Check to see if PDF is version 1.4 (or below); if not: use ghostscript to convert it
     *
     * @param   string $tempsrc The path to the file on disk.
     * @return  string path to copy or converted pdf (false == fail)
     */
    public static function ensure_pdf_file_compatible($tempsrc) {
        global $CFG;

M. Chardon's avatar
init  
M. Chardon committed
618
619
620
621
622
623
624
625
626
627
628
        $pdf = new pdf();
        $pagecount = 0;
        try {
            $pagecount = $pdf->load_pdf($tempsrc);
        } catch (\Exception $e) {
            // PDF was not valid - try running it through ghostscript to clean it up.
            $pagecount = 0;
        }
        $pdf->Close(); // PDF loaded and never saved/outputted needs to be closed.

        if ($pagecount > 0) {
629
            // PDF is already valid and can be read by tcpdf.
M. Chardon's avatar
init  
M. Chardon committed
630
631
632
            return $tempsrc;
        }

633
634
635
        $temparea = make_request_directory();
        $tempdst = $temparea . "/target.pdf";

M. Chardon's avatar
init  
M. Chardon committed
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
        $gsexec = \escapeshellarg($CFG->pathtogs);
        $tempdstarg = \escapeshellarg($tempdst);
        $tempsrcarg = \escapeshellarg($tempsrc);
        $command = "$gsexec -q -sDEVICE=pdfwrite -dBATCH -dNOPAUSE -sOutputFile=$tempdstarg $tempsrcarg";
        exec($command);
        if (!file_exists($tempdst)) {
            // Something has gone wrong in the conversion.
            return false;
        }

        $pdf = new pdf();
        $pagecount = 0;
        try {
            $pagecount = $pdf->load_pdf($tempdst);
        } catch (\Exception $e) {
            // PDF was not valid - try running it through ghostscript to clean it up.
            $pagecount = 0;
        }
        $pdf->Close(); // PDF loaded and never saved/outputted needs to be closed.

        if ($pagecount <= 0) {
            // Could not parse the converted pdf.
            return false;
        }

        return $tempdst;
    }

664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
    /**
     * Generate an localised error image for the given pagenumber.
     *
     * @param string $errorimagefolder path of the folder where error image needs to be created.
     * @param int $pageno page number for which error image needs to be created.
     *
     * @return string File name
     * @throws \coding_exception
     */
    public static function get_error_image($errorimagefolder, $pageno) {
        global $CFG;

        $errorfile = $CFG->dirroot . self::BLANK_PDF;
        if (!file_exists($errorfile)) {
            throw new \coding_exception("Blank PDF not found", "File path" . $errorfile);
        }

        $tmperrorimagefolder = make_request_directory();

        $pdf = new pdf();
        $pdf->set_pdf($errorfile);
        $pdf->copy_page();
686
        $pdf->add_comment(get_string('errorpdfpage', 'assignfeedback_editpdfplus'), 250, 300, 200, "red");
687
688
689
690
691
692
693
694
        $generatedpdf = $tmperrorimagefolder . '/' . 'error.pdf';
        $pdf->save_pdf($generatedpdf);

        $pdf = new pdf();
        $pdf->set_pdf($generatedpdf);
        $pdf->set_image_folder($tmperrorimagefolder);
        $image = $pdf->get_image(0);
        $pdf->Close(); // PDF loaded and never saved/outputted needs to be closed.
695
        $newimg = self::IMAGE_PAGE . $pageno . '.png';
696
697
698
699
700

        copy($tmperrorimagefolder . '/' . $image, $errorimagefolder . '/' . $newimg);
        return $newimg;
    }

M. Chardon's avatar
init  
M. Chardon committed
701
702
703
    /**
     * Test that the configured path to ghostscript is correct and working.
     * @param bool $generateimage - If true - a test image will be generated to verify the install.
704
     * @return \stdClass
M. Chardon's avatar
init  
M. Chardon committed
705
706
707
708
     */
    public static function test_gs_path($generateimage = true) {
        global $CFG;

M. Chardon's avatar
M. Chardon committed
709
710
711
        $ret = (object) array(
                    'status' => self::GSPATH_OK,
                    'message' => null,
M. Chardon's avatar
init  
M. Chardon committed
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
        );
        $gspath = $CFG->pathtogs;
        if (empty($gspath)) {
            $ret->status = self::GSPATH_EMPTY;
            return $ret;
        }
        if (!file_exists($gspath)) {
            $ret->status = self::GSPATH_DOESNOTEXIST;
            return $ret;
        }
        if (is_dir($gspath)) {
            $ret->status = self::GSPATH_ISDIR;
            return $ret;
        }
        if (!is_executable($gspath)) {
            $ret->status = self::GSPATH_NOTEXECUTABLE;
            return $ret;
        }

        if (!$generateimage) {
            return $ret;
        }

M. Chardon's avatar
M. Chardon committed
735
        $testfile = $CFG->dirroot . '/mod/assign/feedback/editpdfplus/tests/fixtures/testgs.pdf';
M. Chardon's avatar
init  
M. Chardon committed
736
737
738
739
740
741
        if (!file_exists($testfile)) {
            $ret->status = self::GSPATH_NOTESTFILE;
            return $ret;
        }

        $testimagefolder = \make_temp_directory('assignfeedback_editpdfplus_test');
742
743
744
745
746
        $filepath = $testimagefolder . '/' . self::IMAGE_PAGE . '0.png';
        // Delete any previous test images, if they exist.
        if (file_exists($filepath)) {
            unlink($filepath);
        }
M. Chardon's avatar
init  
M. Chardon committed
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767

        $pdf = new pdf();
        $pdf->set_pdf($testfile);
        $pdf->set_image_folder($testimagefolder);
        try {
            $pdf->get_image(0);
        } catch (\moodle_exception $e) {
            $ret->status = self::GSPATH_ERROR;
            $ret->message = $e->getMessage();
        }
        $pdf->Close(); // PDF loaded and never saved/outputted needs to be closed.

        return $ret;
    }

    /**
     * If the test image has been generated correctly - send it direct to the browser.
     */
    public static function send_test_image() {
        global $CFG;
        header('Content-type: image/png');
M. Chardon's avatar
M. Chardon committed
768
        require_once($CFG->libdir . '/filelib.php');
M. Chardon's avatar
init  
M. Chardon committed
769
770

        $testimagefolder = \make_temp_directory('assignfeedback_editpdfplus_test');
771
        $testimage = $testimagefolder . '/' . self::IMAGE_PAGE . '0.png';
M. Chardon's avatar
init  
M. Chardon committed
772
773
774
775
        send_file($testimage, basename($testimage), 0);
        die();
    }

776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
    /**
     * This function add an image file to PDF page.
     * @param \stored_file $imagestoredfile Image file to be added
     */
    public function add_image_page($imagestoredfile) {
        $imageinfo = $imagestoredfile->get_imageinfo();
        $imagecontent = $imagestoredfile->get_content();
        $this->currentpage++;
        $template = $this->importPage($this->currentpage);
        $size = $this->getTemplateSize($template);

        if ($imageinfo["width"] > $imageinfo["height"]) {
            if ($size['w'] < $size['h']) {
                $temp = $size['w'];
                $size['w'] = $size['h'];
                $size['h'] = $temp;
            }
            $orientation = 'L';
        } else if ($imageinfo["width"] < $imageinfo["height"]) {
            if ($size['w'] > $size['h']) {
                $temp = $size['w'];
                $size['w'] = $size['h'];
                $size['h'] = $temp;
            }
            $orientation = 'P';
        } else {
            $orientation = 'P';
        }
        $this->SetHeaderMargin(0);
        $this->SetFooterMargin(0);
        $this->SetMargins(0, 0, 0, true);
        $this->setPrintFooter(false);
        $this->setPrintHeader(false);

        $this->AddPage($orientation, $size);
        $this->SetAutoPageBreak(false, 0);
        $this->Image('@' . $imagecontent, 0, 0, $size['w'], $size['h'],
                '', '', '', false, null, '', false, false, 0);
    }

M. Chardon's avatar
init  
M. Chardon committed
816
}