Gitlab CSE Unil

combined_document.php 11.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
// 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.
 *
 * @package   assignfeedback_editpdfplus
 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace assignfeedback_editpdfplus;

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

/**
 * The combined_document class for the assignfeedback_editpdfplus plugin.
 *
 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
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;

    /**
     * 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.
     *
     * @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;
        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;
109
                        break;
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
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
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
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
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405

                    case \core_files\conversion::STATUS_FAILED:
                        return self::STATUS_FAILED;
                }
            }
        }
        if ($pending) {
            return self::STATUS_PENDING_INPUT;
        } else {
            return self::STATUS_READY;
        }
    }
    /**
     * 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:
                        continue;
                    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();
        if ($currentstatus === self::STATUS_FAILED) {
            $this->store_empty_document($contextid, $itemid);

            return $this;
        } else if ($currentstatus !== self::STATUS_READY) {
            // 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)) {
                $compatiblepdf = pdf::ensure_pdf_compatible($file->get_destfile());
            } 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.
        $this->store_combined_file($tmpfile, $contextid, $itemid);

        // 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
     * @return  $this
     */
    protected function store_combined_file($tmpfile, $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);

        // 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;
        }

        if ($this->get_status() === self::STATUS_FAILED) {
            // The empty document will be returned.
            return 1;
        }

        if ($this->get_status() !== self::STATUS_COMPLETE) {
            // 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
     * @return  stdClass
     */
    protected function get_stored_file_record($contextid, $itemid) {
        return (object) [
            'contextid' => $contextid,
            'component' => 'assignfeedback_editpdfplus',
            'filearea' => document_services::COMBINED_PDF_FILEAREA,
            'itemid' => $itemid,
            'filepath' => '/',
            'filename' => document_services::COMBINED_PDF_FILENAME,
        ];
    }
}