Download.php 7.75 KB
Newer Older
Carsten  Rose's avatar
Carsten Rose committed
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
109
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
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 4/17/17
 * Time: 11:32 AM
 */

namespace qfq;

use TYPO3\CMS\Core\Resource\Exception\FileDoesNotExistException;

require_once(__DIR__ . '/../Constants.php');
require_once(__DIR__ . '/../store/Session.php');
require_once(__DIR__ . '/../store/Store.php');
require_once(__DIR__ . '/../helper/OnArray.php');
require_once(__DIR__ . '/../report/Html2Pdf.php');
//require_once(__DIR__ . '/Link.php');
//require_once(__DIR__ . '/Sendmail.php');
require_once(__DIR__ . '/../exceptions/DownloadException.php');
//require_once(__DIR__ . '/../Evaluate.php');
//require_once(__DIR__ . '/../helper/KeyValueStringParser.php');
//

/**
 * Class Download
 *
 * 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;

    /**
     * @param bool|false $phpUnit
     */
    public function __construct($phpUnit = false) {

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

    /**
     * Collect all elements, separated per element.
     * Skip parameter which do not start with '<i>_' (i=integer).
     * Create a numbered and sorted (by key) array, with all parameter belonging to one element in one subarray.
     *
     * E.g.: exportFilename=final.pdf&mode=pdf&1_id=exportP1&2_id=123&3_file=fileadmin/pdf/test.pdf&1_grId=78
     * result [
     *          [1] => [ 'id' => 'exportP1', 'grId' = '78' ],
     *          [2] => [ 'id' => '123' ],
     *          [3] => [ 'file' => 'fileadmin/pdf/test.pdf' ],
     *          [mode] => 'pdf|file|excel',
     *          [exportFilename] => '....'
     *        ]
     *
     * @param array $vars
     * @return array
     */
    private function collectElement(array $vars) {
        $final = array();

        foreach ($vars as $key => $value) {
            $splitArr = explode(DOWNLOAD_PARAMETER_DELIMITER, $key, 2);
            $idx = $splitArr[0];
            if ((count($splitArr) == 2) && is_numeric($idx) && !isset($final[$idx])) {
                $arr = OnArray::getArrayItemKeyNameStartWith($vars, $idx . DOWNLOAD_PARAMETER_DELIMITER);
                if (count($arr) > 0) {
                    $final[$idx] = $arr;
                }

            }
        }

        // sort array
        ksort($final, SORT_NATURAL);

        return $final;
    }

    /**
     * Concatenate all named files to one PDF file. Return name of new full PDF.
     *
     * @param array $files
     * @return string  - fileName of concatenated file
     * @throws DownloadException
     */
    private function concatPdfFiles(array $files) {

        $concatFile = tempnam(sys_get_temp_dir(), DOWNLOAD_FILE_PREFIX);
        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') {
                throw new downloadException("Error concat file $filename. Mimetype 'application/pdf' expected, got: $mimetype", ERROR_DOWNLOAD_UNEXPECTED_MIMETYPE);
            }
        }

        $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";

        exec($cmd, $output, $rc);

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

        return $concatFile;
    }

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

        $mimetype = mime_content_type($filename);
        $length = filesize($filename);

        header("Content-type: $mimetype");
        header("Content-Length: $length");
        header("Content-Disposition: inline; filename=$outputFilename");

        print file_get_contents($filename);
    }

    /**
     * Iterate over array $files. Delete all named files which exist in DOWNLOAD_TMP_DIR.
     *
     * @param array $files
     */
    private function cleanTempFiles(array $files) {
        $prefix = sys_get_temp_dir() . '/' . DOWNLOAD_FILE_PREFIX;
        $len = strlen($prefix);

        foreach ($files as $file) {
            if (substr($file, 0, $len) == $prefix) {
                unlink($file);
            }
        }
    }

    /**
     * @param $element
     * @return mixed
     * @throws DownloadException
     * @throws \exception
     */
    private function getFile($element) {
//        $first = each($element);
//        $key = $first['key'];
//        $arr = explode(DOWNLOAD_PARAMETER_DELIMITER, $key, 2);
//        $idx = $arr[0];

        if (isset($element[DOWNLOAD_FILE])) {

            $filename = $element[DOWNLOAD_FILE];

        } elseif (isset($element[DOWNLOAD_PAGE_ID])) {

            $filename = $this->html2pdf->page2pdf($element);

        } else {
            throw new DownloadException('Neither found: ' . DOWNLOAD_FILE . ', ' . DOWNLOAD_PAGE_ID, ERROR_MISSING_REQUIRED_PARAMETER);
        }

        return $filename;
    }

    /**
     * exportFilename=<new filename>
     * mode=file | pdf | excel - default is 'file' in case of only one or 'pdf' in case of multiple sources.
     * HTML to PDF | Excel
     *   <i>_id=<Typo3 pageId>
     *   <i>_<key>=<value i>
     * Direct
     * <i>_file=<filename>
     *
     * @param array $elements
     * @throws DownloadException
     */
    private function doElements(array $elements, array $vars) {

        $tmpFiles = array();

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

        $exportFilename = isset($vars[DOWNLOAD_EXPORT_FILENAME]) ? $vars[DOWNLOAD_EXPORT_FILENAME] : '';

        foreach ($elements as $element) {
            $tmpFiles[] = $this->getFile($element);
        }

        switch (count($tmpFiles)) {
            case 0:
                throw new DownloadException('Nothing to do.', ERROR_DOWNLOAD_NOTHING_TO_DO);
                break;

            case 1:
                $filename = $tmpFiles[0];
                if ($exportFilename == '') {
                    $exportFilename = strrchr($filename, '/');
                    if ($exportFilename == false) {
                        $exportFilename = DOWNLOAD_OUTPUT_PDF;
                    }
                }
                break;
            default:
                $filename = $this->concatPdfFiles($tmpFiles);
                if ($exportFilename == '') {
                    $exportFilename = DOWNLOAD_OUTPUT_PDF;
                }
                break;
        }

        $this->outputFile($filename, $exportFilename);

        $tmpFiles[] = $filename;
        $this->cleanTempFiles($tmpFiles);
    }

    /**
     * @return string
     * @throws CodeException
     * @throws UserFormException
     */
    public function process() {

        $vars = $this->store->getStore(STORE_SIP);
        $elements = $this->collectElement($vars);
        $this->doElements($elements, $vars);
    }
}