Gitlab CSE Unil

combined_document.php 13.6 KB
Newer Older
1
<?php
2

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 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/>.

/**
 * This file contains the combined document class for the assignfeedback_editpdfplus plugin.
20
21
 * 
 * The combined_document class for the assignfeedback_editpdfplus plugin.
22
23
 *
 * @package   assignfeedback_editpdfplus
24
25
 * @copyright  2017 Université de Lausanne
 * The code is based on mod/assign/feedback/editpdf/classes/combined_document.php by Andrew Nicols <andrew@nicols.co.uk>.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace assignfeedback_editpdfplus;

defined('MOODLE_INTERNAL') || die();

class combined_document {

    /**
     * Status value representing a conversion waiting to start.
     */
    const STATUS_PENDING_INPUT = 0;

    /**
     * Status value representing all documents ready to be combined.
     */
    const STATUS_READY = 1;

    /**
     * Status value representing a successful conversion.
     */
    const STATUS_COMPLETE = 2;

50
51
52
53
54
    /**
     * Status value representing all documents are ready to be combined as are supported.
     */
    const STATUS_READY_PARTIAL = 3;

55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    /**
     * Status value representing a permanent error.
     */
    const STATUS_FAILED = -1;

    /**
     * The list of files which make this document.
     */
    protected $sourcefiles = [];

    /**
     * The resultant combined file.
     */
    protected $combinedfile;

    /**
     * The combination status.
     */
    protected $combinationstatus = null;

    /**
     * The number of pages in the combined PDF.
     */
    protected $pagecount = 0;

    /**
     * Check the current status of the document combination.
82
83
84
     * Note that the combined document may not contain all the source files if some of the
     * source files were not able to be converted. An example is an audio file with a pdf cover sheet. Only
     * the cover sheet will be included in the combined document.
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
     *
     * @return  int
     */
    public function get_status() {
        if ($this->combinedfile) {
            // The combined file exists. Report success.
            return self::STATUS_COMPLETE;
        }

        if (empty($this->sourcefiles)) {
            // There are no source files to combine.
            return self::STATUS_FAILED;
        }

        if (!empty($this->combinationstatus)) {
            // The combination is in progress and has set a status.
            // Return it instead.
            return $this->combinationstatus;
        }

        $pending = false;
106
        $partial = false;
107
108
109
110
111
112
113
114
115
        foreach ($this->sourcefiles as $file) {
            // The combined file has not yet been generated.
            // Check the status of each source file.
            if (is_a($file, \core_files\conversion::class)) {
                $status = $file->get('status');
                switch ($status) {
                    case \core_files\conversion::STATUS_IN_PROGRESS:
                    case \core_files\conversion::STATUS_PENDING:
                        $pending = true;
116
                        break;
117
118

                    case \core_files\conversion::STATUS_FAILED:
119
120
121
                        $partial = true;
                        break;

122
123
                    default :
                        break;
124
125
126
127
128
129
                }
            }
        }
        if ($pending) {
            return self::STATUS_PENDING_INPUT;
        } else {
130
131
132
            if ($partial) {
                return self::STATUS_READY_PARTIAL;
            }
133
134
135
            return self::STATUS_READY;
        }
    }
136

137
138
139
140
141
142
143
144
145
146
147
148
149
150
    /**
     * Return true of the combined file contained only some of the submission files.
     *
     * @return  boolean
     */
    public function is_partial_conversion() {
        $combinedfile = $this->get_combined_file();
        if (empty($combinedfile)) {
            return false;
        }
        $filearea = $combinedfile->get_filearea();
        return $filearea == document_services::PARTIAL_PDF_FILEAREA;
    }

151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
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
209
210
211
212
213
214
215
216
217
218
    /**
     * Set the completed combined file.
     *
     * @param   stored_file $file The completed document for all files to be combined.
     * @return  $this
     */
    public function set_combined_file($file) {
        $this->combinedfile = $file;

        return $this;
    }

    /**
     * Retrieve the completed combined file.
     *
     * @return  stored_file
     */
    public function get_combined_file() {
        return $this->combinedfile;
    }

    /**
     * Set all source files which are to be combined.
     *
     * @param   stored_file|conversion[] $files The complete list of all source files to be combined.
     * @return  $this
     */
    public function set_source_files($files) {
        $this->sourcefiles = $files;

        return $this;
    }

    /**
     * Add an additional source file to the end of the existing list.
     *
     * @param   stored_file|conversion $file The file to add to the end of the list.
     * @return  $this
     */
    public function add_source_file($file) {
        $this->sourcefiles[] = $file;

        return $this;
    }

    /**
     * Retrieve the complete list of source files.
     *
     * @return  stored_file|conversion[]
     */
    public function get_source_files() {
        return $this->sourcefiles;
    }

    /**
     * Refresh the files.
     *
     * This includes polling any pending conversions to see if they are complete.
     *
     * @return  $this
     */
    public function refresh_files() {
        $converter = new \core_files\converter();
        foreach ($this->sourcefiles as $file) {
            if (is_a($file, \core_files\conversion::class)) {
                $status = $file->get('status');
                switch ($status) {
                    case \core_files\conversion::STATUS_COMPLETE:
219
                        continue 2;
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
                    default:
                        $converter->poll_conversion($conversion);
                }
            }
        }

        return $this;
    }

    /**
     * Combine all source files into a single PDF and store it in the
     * file_storage API using the supplied contextid and itemid.
     *
     * @param   int $contextid The contextid for the file to be stored under
     * @param   int $itemid The itemid for the file to be stored under
     * @return  $this
     */
    public function combine_files($contextid, $itemid) {
        global $CFG;

        $currentstatus = $this->get_status();
241
        $readystatuslist = [self::STATUS_READY, self::STATUS_READY_PARTIAL];
242
243
244
245
        if ($currentstatus === self::STATUS_FAILED) {
            $this->store_empty_document($contextid, $itemid);

            return $this;
246
        } else if (!in_array($currentstatus, $readystatuslist)) {
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
            // The document is either:
            // * already combined; or
            // * pending input being fully converted; or
            // * unable to continue due to an issue with the input documents.
            //
            // Exit early as we cannot continue.
            return $this;
        }

        require_once($CFG->libdir . '/pdflib.php');

        $pdf = new pdf();
        $files = $this->get_source_files();
        $compatiblepdfs = [];

        foreach ($files as $file) {
            // Check that each file is compatible and add it to the list.
            // Note: We drop non-compatible files.
            $compatiblepdf = false;
            if (is_a($file, \core_files\conversion::class)) {
267
268
269
270
                $status = $file->get('status');
                if ($status == \core_files\conversion::STATUS_COMPLETE) {
                    $compatiblepdf = pdf::ensure_pdf_compatible($file->get_destfile());
                }
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
            } else {
                $compatiblepdf = pdf::ensure_pdf_compatible($file);
            }

            if ($compatiblepdf) {
                $compatiblepdfs[] = $compatiblepdf;
            }
        }

        $tmpdir = make_request_directory();
        $tmpfile = $tmpdir . '/' . document_services::COMBINED_PDF_FILENAME;

        try {
            $pagecount = $pdf->combine_pdfs($compatiblepdfs, $tmpfile);
            $pdf->Close();
        } catch (\Exception $e) {
            // Unable to combine the PDF.
            debugging('TCPDF could not process the pdf files:' . $e->getMessage(), DEBUG_DEVELOPER);

            $pdf->Close();
            return $this->mark_combination_failed();
        }

        // Verify the PDF.
        $verifypdf = new pdf();
        $verifypagecount = $verifypdf->load_pdf($tmpfile);
        $verifypdf->Close();

        if ($verifypagecount <= 0) {
            // No pages were found in the combined PDF.
            return $this->mark_combination_failed();
        }

        // Store the newly created file as a stored_file.
305
        $this->store_combined_file($tmpfile, $contextid, $itemid, ($currentstatus == self::STATUS_READY_PARTIAL));
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329

        // Note the verified page count.
        $this->pagecount = $verifypagecount;

        return $this;
    }

    /**
     * Mark the combination attempt as having encountered a permanent failure.
     *
     * @return  $this
     */
    protected function mark_combination_failed() {
        $this->combinationstatus = self::STATUS_FAILED;

        return $this;
    }

    /**
     * Store the combined file in the file_storage API.
     *
     * @param   string $tmpfile The path to the file on disk to be stored.
     * @param   int $contextid The contextid for the file to be stored under
     * @param   int $itemid The itemid for the file to be stored under
330
     * @param   boolean $partial The combined pdf contains only some of the source files.
331
332
     * @return  $this
     */
333
    protected function store_combined_file($tmpfile, $contextid, $itemid, $partial = false) {
334
        // Store the file.
335
        $record = $this->get_stored_file_record($contextid, $itemid, $partial);
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
        $fs = get_file_storage();

        // Delete existing files first.
        $fs->delete_area_files($record->contextid, $record->component, $record->filearea, $record->itemid);

        // This was a combined pdf.
        $file = $fs->create_file_from_pathname($record, $tmpfile);

        $this->set_combined_file($file);

        return $this;
    }

    /**
     * Store the empty document file in the file_storage API.
     *
     * @param   int $contextid The contextid for the file to be stored under
     * @param   int $itemid The itemid for the file to be stored under
     * @return  $this
     */
    protected function store_empty_document($contextid, $itemid) {
        // Store the file.
        $record = $this->get_stored_file_record($contextid, $itemid);
        $fs = get_file_storage();

        // Delete existing files first.
        $fs->delete_area_files($record->contextid, $record->component, $record->filearea, $record->itemid);

        $file = $fs->create_file_from_string($record, base64_decode(document_services::BLANK_PDF_BASE64));
        $this->pagecount = 1;

        $this->set_combined_file($file);

        return $this;
    }

    /**
     * Get the total number of pages in the combined document.
     *
     * If there are no pages, or it is not yet possible to count them a
     * value of 0 is returned.
     *
     * @return  int
     */
    public function get_page_count() {
        if ($this->pagecount) {
            return $this->pagecount;
        }

385
386
387
        $status = $this->get_status();

        if ($status === self::STATUS_FAILED) {
388
389
390
391
            // The empty document will be returned.
            return 1;
        }

392
        if ($status !== self::STATUS_COMPLETE) {
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
            // No pages yet.
            return 0;
        }

        // Load the PDF to determine the page count.
        $temparea = make_request_directory();
        $tempsrc = $temparea . "/source.pdf";
        $this->get_combined_file()->copy_content_to($tempsrc);

        $pdf = new pdf();
        $pagecount = $pdf->load_pdf($tempsrc);
        $pdf->Close();

        if ($pagecount <= 0) {
            // Something went wrong. Return an empty page count again.
            return 0;
        }

        $this->pagecount = $pagecount;
        return $this->pagecount;
    }

    /**
     * Get the total number of documents to be combined.
     *
     * @return  int
     */
    public function get_document_count() {
        return count($this->sourcefiles);
    }

    /**
     * Helper to fetch the stored_file record.
     *
     * @param   int $contextid The contextid for the file to be stored under
     * @param   int $itemid The itemid for the file to be stored under
429
     * @param   boolean $partial The combined file contains only some of the source files.
430
431
     * @return  stdClass
     */
432
433
434
435
436
    protected function get_stored_file_record($contextid, $itemid, $partial = false) {
        $filearea = document_services::COMBINED_PDF_FILEAREA;
        if ($partial) {
            $filearea = document_services::PARTIAL_PDF_FILEAREA;
        }
437
        return (object) [
438
439
                    'contextid' => $contextid,
                    'component' => 'assignfeedback_editpdfplus',
440
                    'filearea' => $filearea,
441
442
443
                    'itemid' => $itemid,
                    'filepath' => '/',
                    'filename' => document_services::COMBINED_PDF_FILENAME,
444
445
        ];
    }
446

447
}