Download.php 13.8 KB
Newer Older
Carsten  Rose's avatar
Carsten Rose committed
1
2
3
4
5
6
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 4/17/17
 * Time: 11:32 AM
Carsten  Rose's avatar
Carsten Rose committed
7
8
 *
 * Check: CODING.md > Download
Carsten  Rose's avatar
Carsten Rose committed
9
10
11
12
 */

namespace qfq;

13
//use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;
Carsten  Rose's avatar
Carsten Rose committed
14
15
16
17
18

require_once(__DIR__ . '/../Constants.php');
require_once(__DIR__ . '/../store/Session.php');
require_once(__DIR__ . '/../store/Store.php');
require_once(__DIR__ . '/../helper/OnArray.php');
19
require_once(__DIR__ . '/../helper/Logger.php');
20
require_once(__DIR__ . '/../helper/Sanitize.php');
21
require_once(__DIR__ . '/../helper/HelperFile.php');
Carsten  Rose's avatar
Carsten Rose committed
22
require_once(__DIR__ . '/../report/Html2Pdf.php');
23
require_once(__DIR__ . '/Thumbnail.php');
Carsten  Rose's avatar
Carsten Rose committed
24
require_once(__DIR__ . '/Monitor.php');
Carsten  Rose's avatar
Carsten Rose committed
25
26
27
28
29
30
31
32
require_once(__DIR__ . '/../exceptions/DownloadException.php');
//require_once(__DIR__ . '/../Evaluate.php');
//require_once(__DIR__ . '/../helper/KeyValueStringParser.php');
//

/**
 * Class Download
 *
33
34
 * Documentation: PROTOCOL.md >> Download
 *
Carsten  Rose's avatar
Carsten Rose committed
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
 * Param: i=1..n
 *   <i>_mode=direct | html2pdf
 *   <i>_id=<pageId>
 *   <i>_<key i>=<value i>
 *
 * @package qfq
 */
class Download {

    /**
     * @var Store
     */
    private $store = null;

    /**
     * @var Session
     */
    private $session = null;

    /**
     * @var Database
     */
    private $db = null;

    /**
     * @var Html2Pdf
     */
    private $html2pdf = null;

64
65
66
67
68
    /**
     * @var string Filename where to write download Information
     */
    private $downloadDebugLog = '';

69
70
71
72
73
    /**
     * @var string DOWNLOAD_OUTPUT_FORMAT_RAW | DOWNLOAD_OUTPUT_FORMAT_JSON
     */
    private $outputFormat = DOWNLOAD_OUTPUT_FORMAT_RAW;

Carsten  Rose's avatar
Carsten Rose committed
74
75
    /**
     * @param bool|false $phpUnit
76
     * @throws CodeException
77
     * @throws DbException
78
     * @throws UserFormException
Carsten  Rose's avatar
Carsten Rose committed
79
     * @throws UserReportException
Carsten  Rose's avatar
Carsten Rose committed
80
81
82
83
84
85
     */
    public function __construct($phpUnit = false) {

        $this->session = Session::getInstance($phpUnit);
        $this->store = Store::getInstance('', $phpUnit);
        $this->db = new Database();
86
        $this->html2pdf = new Html2Pdf($this->store->getStore(STORE_SYSTEM), $phpUnit);
87

88
        if (Support::findInSet(SYSTEM_SHOW_DEBUG_INFO_DOWNLOAD, $this->store->getVar(SYSTEM_SHOW_DEBUG_INFO, STORE_SYSTEM))) {
89
90
            $this->downloadDebugLog = $this->store->getVar(SYSTEM_SQL_LOG, STORE_SYSTEM);
        }
Carsten  Rose's avatar
Carsten Rose committed
91
92
93
94
95
96
    }

    /**
     * Concatenate all named files to one PDF file. Return name of new full PDF.
     *
     * @param array $files
Carsten  Rose's avatar
Carsten Rose committed
97
     *
Carsten  Rose's avatar
Carsten Rose committed
98
     * @return string  - fileName of concatenated file
99
100
     * @throws UserFormException
     * @throws downloadException
Carsten  Rose's avatar
Carsten Rose committed
101
102
103
     */
    private function concatPdfFiles(array $files) {

104
105
106
        // Remove empty entries. Might happen if there was no upload
        $files = OnArray::removeEmptyElementsFromArray($files);

107
108
        // Check that all files exist and readable
        foreach ($files AS $filename) {
109
            if (!is_readable($filename)) {
110
111
112
113
                throw new downloadException("Error reading file $filename. Not found or no permission", ERROR_DOWNLOAD_FILE_NOT_READABLE);
            }
        }

114
115
116
117
118
119
120
121
122
        switch (count($files)) {
            case 0:
                return '';
            case 1:
                return $files[0];
            default:
                break;
        }

123
124

        $concatFile = tempnam(sys_get_temp_dir(), TMP_FILE_PREFIX);
Carsten  Rose's avatar
Carsten Rose committed
125
126
127
128
129
130
131
132
        if (false === $concatFile) {
            throw new DownloadException('Error creating output file.', ERROR_DOWNLOAD_CREATE_NEW_FILE);
        }

        // Check that all files are of type 'application/pdf'
        foreach ($files AS $filename) {
            $mimetype = mime_content_type($filename);
            if ($mimetype != 'application/pdf') {
133
                throw new downloadException("Error concat file $filename. Mimetype 'application/pdf' expected, got: $mimetype", ERROR_DOWNLOAD_UNEXPECTED_MIME_TYPE);
Carsten  Rose's avatar
Carsten Rose committed
134
135
136
137
138
139
140
141
142
143
144
145
            }
        }

        $files = OnArray::arrayEscapeshellarg($files);

        $inputFiles = implode(' ', $files);
        if (trim($inputFiles) == '') {
            throw new DownloadException('No files to concatenate.', ERROR_DOWNLOAD_NO_FILES);
        }

        $cmd = "pdftk $inputFiles cat output $concatFile";

146
147
148
149
        if ($this->downloadDebugLog != '') {
            Logger::logMessage("Download: $cmd", $this->downloadDebugLog);
        }

Carsten  Rose's avatar
Carsten Rose committed
150
151
152
153
154
155
156
157
158
159
        exec($cmd, $output, $rc);

        if ($rc != 0) {
            throw new DownloadException ("<p>Failed: RC=$rc   $cmd</p>" . implode("<br>", $output));
        }

        return $concatFile;
    }

    /**
160
161
     * Get the mimetype of $filename and store them in $rcMimetype.
     * Checks if the extension of $outputFilename fit's to the mimetype. If not, append the mimetype extension.
Carsten  Rose's avatar
Carsten Rose committed
162
     *
163
164
165
     * @param string $filename
     * @param string $outputFilename
     * @param string $rcMimetype
Carsten  Rose's avatar
Carsten Rose committed
166
     *
167
     * @return string possible updated $outputFilename, according the mimetype.
Carsten  Rose's avatar
Carsten Rose committed
168
     */
169
    private function targetFilenameExtension($filename, $outputFilename, &$rcMimetype) {
Carsten  Rose's avatar
Carsten Rose committed
170

171
        $rcMimetype = mime_content_type($filename);
172

173
174
175
176
177
178
        return $outputFilename;
    }

    /**
     * Set header type and output $filename. Be careful not to send any additional characters.
     *
179
     * @param $file
180
181
     * @param $outputFilename
     */
182
    private function outputFile($file, $outputFilename) {
183

184
        $length = filesize($file);
185

186
187
        $outputFilename = $this->targetFilenameExtension($file, $outputFilename, $mimetype);
        $outputFilename = Sanitize::safeFilename($outputFilename); // be sure that there are no problematic chars in the filename. E.g. MacOS X don't like spaces for downloads.
188

Carsten  Rose's avatar
Carsten Rose committed
189
190
        header("Content-type: $mimetype");
        header("Content-Length: $length");
191
192
        // If defined as 'attachment': PDFs are not shown inside the browser (if user configured that). Instead, always a 'save as'-dialog appears (Chrome, FF)
        // header("Content-Disposition: attachment; filename=$outputFilename");
193
        header("Content-Disposition: inline; filename=\"$outputFilename\"; name=\"$outputFilename\"");
Carsten  Rose's avatar
Carsten Rose committed
194
195
        header("Pragma: no-cache");
        header("Expires: 0");
Carsten  Rose's avatar
Carsten Rose committed
196

197
        print file_get_contents($file);
Carsten  Rose's avatar
Carsten Rose committed
198
199
200
    }

    /**
Carsten  Rose's avatar
Carsten Rose committed
201
202
203
     * Interprets $element and fetches corresponding content as file.
     *
     * @param string $element - U:id=myExport&r=12, u:http://www.nzz.ch/issue?nr=21, f:fileadmin/sample.pdf
Carsten  Rose's avatar
Carsten Rose committed
204
     *
Carsten  Rose's avatar
Carsten Rose committed
205
     * @return string filename - already ready or fresh exported. Fresh exported needs to be deleted later.
Carsten  Rose's avatar
Carsten Rose committed
206
207
208
     * @throws DownloadException
     * @throws \exception
     */
Carsten  Rose's avatar
Carsten Rose committed
209
    private function getElement($element) {
Carsten  Rose's avatar
Carsten Rose committed
210

Carsten  Rose's avatar
Carsten Rose committed
211
212
213
214
        $arr = explode(':', $element, 2);
        if (count($arr) != 2) {
            throw new DownloadException('Missing parameter for "' . $element . '"', ERROR_MISSING_REQUIRED_PARAMETER);
        }
Carsten  Rose's avatar
Carsten Rose committed
215

Carsten  Rose's avatar
Carsten Rose committed
216
217
        $token = $arr[0];
        $value = $arr[1];
Carsten  Rose's avatar
Carsten Rose committed
218

Carsten  Rose's avatar
Carsten Rose committed
219
220
221
        switch ($token) {
            case TOKEN_URL:
            case TOKEN_URL_PARAM:
222
            case TOKEN_PAGE:
Carsten  Rose's avatar
Carsten Rose committed
223
224
                $filename = $this->html2pdf->page2pdf($token, $value);
                break;
Carsten  Rose's avatar
Carsten Rose committed
225

Carsten  Rose's avatar
Carsten Rose committed
226
            case TOKEN_FILE:
227
            case TOKEN_FILE_DEPRECATED:
Carsten  Rose's avatar
Carsten Rose committed
228
229
230
231
232
                $filename = $value;
                break;
            default:
                throw new DownloadException('Unknown token: "' . $token . '"', ERROR_UNKNOWN_TOKEN);
                break;
Carsten  Rose's avatar
Carsten Rose committed
233
234
235
236
237
        }

        return $filename;
    }

Carsten  Rose's avatar
Carsten Rose committed
238
239
240
241
242

    /**
     * Creates a ZIP Files of all given $files
     *
     * @param array $files
Carsten  Rose's avatar
Carsten Rose committed
243
     *
Carsten  Rose's avatar
Carsten Rose committed
244
245
246
247
248
     * @return string ZIP filename - has to be deleted later.
     * @throws DownloadException
     */
    private function zipFiles(array $files) {

249
        $zipFile = tempnam(sys_get_temp_dir(), TMP_FILE_PREFIX);
Carsten  Rose's avatar
Carsten Rose committed
250
251
252
253
254
255
        if (false === $zipFile) {
            throw new DownloadException("Error creating output file.", ERROR_DOWNLOAD_CREATE_NEW_FILE);
        }

        $zip = new \ZipArchive();

Carsten  Rose's avatar
Carsten Rose committed
256
        if ($zip->open($zipFile, \ZipArchive::CREATE) !== true) {
Carsten  Rose's avatar
Carsten Rose committed
257
258
259
            throw new DownloadException("Error creating/opening new empty zip file: $zipFile", ERROR_IO_OPEN);
        }

260
        $len = strlen(TMP_FILE_PREFIX);
261
        $ii = 1;
Carsten  Rose's avatar
Carsten Rose committed
262
        foreach ($files AS $filename) {
263
264
            $localname = substr($filename, strrpos($filename, '/') + 1);

265
            if (substr($localname, 0, $len) == TMP_FILE_PREFIX) {
266
267
268
                $localname = 'file-' . $ii;
                $ii++;
            }
269
//            $localname = $this->targetFilenameExtension($filename, $localname, $mimetype);
270

Carsten  Rose's avatar
Carsten Rose committed
271
272
273
274
275
276
277
            $zip->addFile($filename, $localname);
        }
        $zip->close();

        return $zipFile;
    }

Carsten  Rose's avatar
Carsten Rose committed
278
279
    /**
     * exportFilename=<new filename>
280
     * mode=file | pdf | excel | thumbnail | monitor - default is 'file' in case of only one or 'pdf' in case of multiple sources.
Carsten  Rose's avatar
Carsten Rose committed
281
282
283
284
     * HTML to PDF | Excel
     *   <i>_id=<Typo3 pageId>
     *   <i>_<key>=<value i>
     * Direct
285
     *   <i>_file=<filename>
Carsten  Rose's avatar
Carsten Rose committed
286
     *
Carsten  Rose's avatar
Carsten Rose committed
287
     * @param array $vars [ DOWNLOAD_EXPORT_FILENAME, DOWNLOAD_MODE, SIP_DOWNLOAD_PARAMETER ]
Carsten  Rose's avatar
Carsten Rose committed
288
     *
289
290
291
     * @param string $outputMode OUTPUT_MODE_DIRECT | OUTPUT_MODE_FILE
     * @return string            Filename of the generated file. The filename only points to a real existing filename with  $outputMode=OUTPUT_MODE_FILE
     * @throws CodeException
Carsten  Rose's avatar
Carsten Rose committed
292
     * @throws DownloadException
293
294
     * @throws UserFormException
     * @throws UserReportException
Carsten  Rose's avatar
Carsten Rose committed
295
     */
296
    private function doElements(array $vars, $outputMode) {
Carsten  Rose's avatar
Carsten Rose committed
297
298
299
300
301
302
303
304

        $tmpFiles = array();

        $workDir = $this->store->getVar(SYSTEM_SITE_PATH, STORE_SYSTEM);
        if (!chdir($workDir)) {
            throw new DownloadException ("Error chdir($workDir)", ERROR_IO_CHDIR);
        }

Carsten  Rose's avatar
Carsten Rose committed
305
        $downloadMode = $vars[DOWNLOAD_MODE];
306

307
        if ($downloadMode == DOWNLOAD_MODE_MONITOR) {
308
            $monitor = new Monitor();
Carsten  Rose's avatar
Carsten Rose committed
309
310

            return $monitor->dump($vars[TOKEN_L_FILE], $vars[TOKEN_L_TAIL], $vars[TOKEN_L_APPEND]);
311
312
        }

313
314
315
316
317
318
319
        if ($downloadMode == DOWNLOAD_MODE_THUMBNAIL) {
            // Fake $vars control array.
            $pathFilenameThumbnail = $this->doThumbnail($vars[SIP_DOWNLOAD_PARAMETER]);
            $downloadMode = DOWNLOAD_MODE_FILE;
            $vars[SIP_DOWNLOAD_PARAMETER] = TOKEN_FILE . ':' . $pathFilenameThumbnail;
        }

Carsten  Rose's avatar
Carsten Rose committed
320
        $elements = explode(PARAM_DELIMITER, $vars[SIP_DOWNLOAD_PARAMETER]);
Carsten  Rose's avatar
Carsten Rose committed
321

Carsten  Rose's avatar
Carsten Rose committed
322
        // Get all files
Carsten  Rose's avatar
Carsten Rose committed
323
        foreach ($elements as $element) {
Carsten  Rose's avatar
Carsten Rose committed
324
            $tmpFiles[] = $this->getElement($element);
Carsten  Rose's avatar
Carsten Rose committed
325
326
        }

Carsten  Rose's avatar
Carsten Rose committed
327
328
329
330
        // Export, Concat File(s)
        switch ($downloadMode) {
            case DOWNLOAD_MODE_ZIP:
                $filename = $this->zipFiles($tmpFiles);
331
332
333
                if (empty($vars[DOWNLOAD_EXPORT_FILENAME])) {
                    $vars[DOWNLOAD_EXPORT_FILENAME] = basename($filename);
                }
Carsten  Rose's avatar
Carsten Rose committed
334
335
336
337
                break;

            case DOWNLOAD_MODE_EXCEL:
                throw new DownloadException("Not implemented: $downloadMode", ERROR_NOT_IMPLEMENTED);
Carsten  Rose's avatar
Carsten Rose committed
338
339
                break;

Carsten  Rose's avatar
Carsten Rose committed
340
            case DOWNLOAD_MODE_FILE:
Carsten  Rose's avatar
Carsten Rose committed
341
                $filename = $tmpFiles[0];
342
                if (empty($vars[DOWNLOAD_EXPORT_FILENAME])) {
343
                    $vars[DOWNLOAD_EXPORT_FILENAME] = basename($filename);
344
                }
Carsten  Rose's avatar
Carsten Rose committed
345
                break;
Carsten  Rose's avatar
Carsten Rose committed
346
347

            case DOWNLOAD_MODE_PDF:
Carsten  Rose's avatar
Carsten Rose committed
348
                $filename = $this->concatPdfFiles($tmpFiles);
349
350
351
352
353
354
355
356
357
358
359
360
                // try to find a meaningful filename
                if (empty($vars[DOWNLOAD_EXPORT_FILENAME])) {
                    if (count($tmpFiles) > 1) {
                        $vars[DOWNLOAD_EXPORT_FILENAME] = DOWNLOAD_OUTPUT_FILENAME . ".pdf";
                    } else {
                        if (HelperFile::isQfqTemp($filename)) {
                            $vars[DOWNLOAD_EXPORT_FILENAME] = DOWNLOAD_OUTPUT_FILENAME . ".pdf";
                        } else {
                            $vars[DOWNLOAD_EXPORT_FILENAME] = basename($filename);
                        }
                    }
                }
Carsten  Rose's avatar
Carsten Rose committed
361
362
363
364
                break;

            default:
                throw new DownloadException("Unknown downloadMode: $downloadMode", ERROR_UNKNOWN_MODE);
Carsten  Rose's avatar
Carsten Rose committed
365
366
367
                break;
        }

368
369
370
371
372
373
        switch ($outputMode) {

            case OUTPUT_MODE_FILE:
                break;

            case OUTPUT_MODE_DIRECT:
374
                $this->outputFile($filename, $vars[DOWNLOAD_EXPORT_FILENAME]);
375
376
                HelperFile::cleanTempFiles([$filename]);
                break;
Carsten  Rose's avatar
Carsten Rose committed
377

378
379
380
381
382
            default:
                throw new CodeException('Unkown mode: ' . $outputMode, ERROR_UNKNOWN_MODE);
        }

        return $filename;
Carsten  Rose's avatar
Carsten Rose committed
383
384
    }

385
386
387
    /**
     * @param string $urlParam
     * @return string
Carsten  Rose's avatar
Carsten Rose committed
388
     * @throws CodeException
389
     * @throws UserFormException
390
391
392
393
394
395
396
397
398
399
     * @throws UserReportException
     */
    private function doThumbnail($urlParam) {

        $thumbnail = new Thumbnail();
        $pathFilenameThumbnail = $thumbnail->process($urlParam, THUMBNAIL_VIA_DOWNLOAD);

        return $pathFilenameThumbnail;
    }

Carsten  Rose's avatar
Carsten Rose committed
400
    /**
401
402
403
404
405
     * Process download as requested in $vars. Output is either directly send to the browser, or a file which has to be deleted later.
     *
     * @param string|array $vars If $config is not an array, get values from STORE_SIP. If $config is an array, take it.
     * @param string $outputMode OUTPUT_MODE_DIRECT | OUTPUT_MODE_FILE
     *
Carsten  Rose's avatar
Carsten Rose committed
406
407
     * @return string
     * @throws CodeException
408
     * @throws DownloadException
Carsten  Rose's avatar
Carsten Rose committed
409
     * @throws UserFormException
Carsten  Rose's avatar
Carsten Rose committed
410
     * @throws UserReportException
Carsten  Rose's avatar
Carsten Rose committed
411
     */
412
    public function process($vars, $outputMode = OUTPUT_MODE_DIRECT) {
Carsten  Rose's avatar
Carsten Rose committed
413

414
415
416
        if (!is_array($vars)) {
            $vars = $this->store->getStore(STORE_SIP);
        }
417

418
419
        $this->setOutputFormat(empty($vars[DOWNLOAD_OUTPUT_FORMAT]) ? DOWNLOAD_OUTPUT_FORMAT_RAW : $vars[DOWNLOAD_OUTPUT_FORMAT]);

420
        return $this->doElements($vars, $outputMode);
Carsten  Rose's avatar
Carsten Rose committed
421
422
    }

423
424
425
426
427
428
429
430
431
432
433
434
435
    /**
     * @param $outputFormat
     */
    private function setOutputFormat($outputFormat) {
        $this->outputFormat = $outputFormat;
    }

    /**
     * @return string - DOWNLOAD_OUTPUT_FORMAT_RAW | DOWNLOAD_OUTPUT_FORMAT_JSON
     */
    public function getOutputFormat() {
        return $this->outputFormat;
    }
436
}
Carsten  Rose's avatar
Carsten Rose committed
437