Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — dev-extbase-fluid (#720)
by Alexander
03:12
created

BasketController::basketAction()   B

Complexity

Conditions 11
Paths 81

Size

Total Lines 43
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 21
c 2
b 0
f 0
dl 0
loc 43
rs 7.3166
cc 11
nc 81
nop 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
5
 *
6
 * This file is part of the Kitodo and TYPO3 projects.
7
 *
8
 * @license GNU General Public License version 3 or later.
9
 * For the full copyright and license information, please read the
10
 * LICENSE.txt file that was distributed with this source code.
11
 */
12
13
namespace Kitodo\Dlf\Controller;
14
15
use Kitodo\Dlf\Common\Document;
16
use Kitodo\Dlf\Common\Helper;
17
use TYPO3\CMS\Core\Database\Connection;
18
use TYPO3\CMS\Core\Database\ConnectionPool;
19
use TYPO3\CMS\Core\Utility\GeneralUtility;
20
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
21
22
class BasketController extends AbstractController
23
{
24
    /**
25
     * Different actions which depends on the choosen action (form)
26
     *
27
     * @return void
28
     */
29
    public function basketAction()
30
    {
31
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
32
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
33
34
        $basketData = $this->getBasketData();
35
36
        // action remove from basket
37
        if ($requestData['basket_action'] === 'remove') {
38
            // remove entry from list
39
            if (isset($requestData['selected'])) {
40
                $basketData = $this->removeFromBasket($requestData, $basketData);
41
            }
42
        }
43
        // action remove from basket
44
        if ($requestData['basket_action'] == 'download') {
45
            // open selected documents
46
            if (isset($requestData['selected'])) {
47
                $pdfUrl = $this->settings['pdfgenerate'];
48
                foreach ($requestData['selected'] as $docValue) {
49
                    if ($docValue['id']) {
50
                        $docData = $this->getDocumentData($docValue['id'], $docValue);
51
                        $pdfUrl .= $docData['urlParams'] . $this->settings['pdfparamseparator'];
52
                        $this->redirectToUri($pdfUrl);
53
                    }
54
                }
55
            }
56
        }
57
        // action print from basket
58
        if ($requestData['print_action']) {
59
            // open selected documents
60
            if (isset($requestData['selected'])) {
61
                $this->printDocument($requestData, $basketData);
62
            }
63
        }
64
        // action send mail
65
        if ($requestData['mail_action']) {
66
            if (isset($requestData['selected'])) {
67
                $this->sendMail($requestData);
68
            }
69
        }
70
71
        $this->redirect('main');
72
    }
73
74
    /**
75
     * Add documents to the basket
76
     *
77
     * @return void
78
     */
79
    public function addAction()
80
    {
81
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
82
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
83
84
        $basketData = $this->getBasketData();
85
86
        if (
87
            !empty($requestData['id'])
88
            && $requestData['addToBasket']
89
        ) {
90
            $returnData = $this->addToBasket($requestData, $basketData);
91
            $this->view->assign('pregenerateJs', $returnData['jsOutput']);
92
        }
93
94
        $this->redirect('main');
95
    }
96
97
    /**
98
     * The main method of the plugin
99
     *
100
     * @return void
101
     */
102
    public function mainAction()
103
    {
104
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
105
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
106
107
        $basketData = $this->getBasketData();
108
109
        if ($basketData['doc_ids']) {
110
            if (is_object($basketData['doc_ids'])) {
111
                $basketData['doc_ids'] = get_object_vars($basketData['doc_ids']);
112
            }
113
            $count = sprintf(LocalizationUtility::translate('basket.count', 'dlf'), count($basketData['doc_ids']));
0 ignored issues
show
Bug introduced by
It seems like TYPO3\CMS\Extbase\Utilit...('basket.count', 'dlf') can also be of type null; however, parameter $format of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

113
            $count = sprintf(/** @scrutinizer ignore-type */ LocalizationUtility::translate('basket.count', 'dlf'), count($basketData['doc_ids']));
Loading history...
114
        } else {
115
            $count = sprintf(LocalizationUtility::translate('basket.count', 'dlf'), 0);
116
        }
117
        $this->view->assign('count', $count);
118
119
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
120
            ->getQueryBuilderForTable('tx_dlf_mail');
121
122
        // get mail addresses
123
        $resultMail = $queryBuilder
124
            ->select('*')
125
            ->from('tx_dlf_mail')
126
            ->where(
127
                '1=1',
128
                Helper::whereExpression('tx_dlf_mail')
129
            )
130
            ->orderBy('tx_dlf_mail.sorting')
131
            ->execute();
132
133
        $mailSelect = [];
134
        if ($resultMail->rowCount() > 0) {
135
            $mailSelect[0] = htmlspecialchars(LocalizationUtility::translate('basket.chooseMail', 'dlf'));
0 ignored issues
show
Bug introduced by
It seems like TYPO3\CMS\Extbase\Utilit...ket.chooseMail', 'dlf') can also be of type null; however, parameter $string of htmlspecialchars() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

135
            $mailSelect[0] = htmlspecialchars(/** @scrutinizer ignore-type */ LocalizationUtility::translate('basket.chooseMail', 'dlf'));
Loading history...
136
            while ($row = $resultMail->fetch()) {
137
                $mailSelect[$row['uid']] = htmlspecialchars($row['name']) . ' (' . htmlspecialchars($row['mail']) . ')';
138
            }
139
            $this->view->assign('mailSelect', $mailSelect);
140
        }
141
142
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
143
            ->getQueryBuilderForTable('tx_dlf_printer');
144
145
        // get mail addresses
146
        $resultPrinter = $queryBuilder
147
            ->select('*')
148
            ->from('tx_dlf_printer')
149
            ->where(
150
                '1=1',
151
                Helper::whereExpression('tx_dlf_printer')
152
            )
153
            ->execute();
154
155
        $printSelect = [];
156
        if ($resultPrinter->rowCount() > 0) {
157
            $printSelect[0] = htmlspecialchars(LocalizationUtility::translate('basket.choosePrinter', 'dlf'));
158
            while ($row = $resultPrinter->fetch()) {
159
                $printSelect[$row['uid']] = htmlspecialchars($row['label']);
160
            }
161
            $this->view->assign('printSelect', $printSelect);
162
        }
163
164
        $entries = [];
165
        if (isset($basketData['doc_ids'])) {
166
            // get each entry
167
            foreach ($basketData['doc_ids'] as $value) {
168
                $entries[] = $this->getEntry($value);
169
            }
170
            $this->view->assign('entries', $entries);
171
        }
172
    }
173
174
    /**
175
     * The basket data from user session.
176
     *
177
     * @return array The found data from user session.
178
     */
179
    protected function getBasketData() {
180
        // get user session
181
        $sessionId = $GLOBALS['TSFE']->fe_user->id;
182
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
183
            ->getQueryBuilderForTable('tx_dlf_basket');
184
185
        if ($GLOBALS['TSFE']->loginUser) {
186
            $result = $queryBuilder
187
                ->select('*')
188
                ->from('tx_dlf_basket')
189
                ->where(
190
                    $queryBuilder->expr()->eq('tx_dlf_basket.fe_user_id', (int) $GLOBALS['TSFE']->fe_user->user['uid']),
191
                    Helper::whereExpression('tx_dlf_basket')
192
                )
193
                ->setMaxResults(1)
194
                ->execute();
195
        } else {
196
            $GLOBALS['TSFE']->fe_user->setKey('ses', 'tx_dlf_basket', '');
197
            $GLOBALS['TSFE']->fe_user->sesData_change = true;
198
            $GLOBALS['TSFE']->fe_user->storeSessionData();
199
            $result = $queryBuilder
200
                ->select('*')
201
                ->from('tx_dlf_basket')
202
                ->where(
203
                    $queryBuilder->expr()->eq('tx_dlf_basket.session_id', $queryBuilder->createNamedParameter($sessionId)),
204
                    Helper::whereExpression('tx_dlf_basket')
205
                )
206
                ->setMaxResults(1)
207
                ->execute();
208
        }
209
        // session already exists
210
        if ($result->rowCount() === 0) {
211
            // create new basket in db
212
            $insertArray['fe_user_id'] = $GLOBALS['TSFE']->loginUser ? $GLOBALS['TSFE']->fe_user->user['uid'] : 0;
213
            $insertArray['session_id'] = $sessionId;
214
            $insertArray['doc_ids'] = '';
215
            $insertArray['label'] = '';
216
            $insertArray['l18n_diffsource'] = '';
217
            GeneralUtility::makeInstance(ConnectionPool::class)
218
                ->getConnectionForTable('tx_dlf_basket')
219
                ->insert(
220
                    'tx_dlf_basket',
221
                    $insertArray
222
                );
223
        }
224
        $basketData = $result->fetchAll()[0];
225
        $basketData['doc_ids'] = json_decode($basketData['doc_ids']);
226
        return $basketData;
227
    }
228
229
    /**
230
     * Return one basket entry
231
     *
232
     * @access protected
233
     *
234
     * @param array $data: DocumentData
235
     * @param array $template: Template information
236
     *
237
     * @return string One basket entry
238
     */
239
    protected function getEntry($data)
240
    {
241
        if (is_object($data)) {
242
            $data = get_object_vars($data);
243
        }
244
        $id = $data['id'];
245
        $startpage = $data['startpage'];
246
        $endpage = $data['endpage'];
247
        $startX = $data['startX'];
248
        $startY = $data['startY'];
249
        $endX = $data['endX'];
250
        $endY = $data['endY'];
251
        $rotation = $data['rotation'];
252
253
        $docData = $this->getDocumentData($id, $data);
254
255
        $entryArray['BASKETDATA'] = $docData;
256
257
        $entryKey = $id . '_' . $startpage;
258
        if (!empty($startX)) {
259
            $entryKey .= '_' . $startX;
260
        }
261
        if (!empty($endX)) {
262
            $entryKey .= '_' . $endX;
263
        }
264
265
        $entryArray['id'] = $id;
266
        $entryArray['CONTROLS'] = [
267
            'startpage' => $startpage,
268
            'endpage' => $endpage,
269
            'startX' => $startX,
270
            'startY' => $startY,
271
            'endX' => $endX,
272
            'endY' => $endY,
273
            'rotation' => $rotation,
274
        ];
275
276
        $entryArray['NUMBER'] = $docData['record_id'];
277
        $entryArray['key'] = $entryKey;
278
279
        // return one entry
280
        return $entryArray;
281
    }
282
283
    /**
284
     * Returns the downloadurl configured in the basket
285
     *
286
     * @access protected
287
     *
288
     * @param int $id: Document id
289
     *
290
     * @return mixed download url or false
291
     */
292
    protected function getDocumentData($id, $data)
293
    {
294
        // get document instance to load further information
295
        $document = Document::getInstance($id, 0);
296
        if ($document) {
0 ignored issues
show
introduced by
$document is of type Kitodo\Dlf\Common\Document, thus it always evaluated to true.
Loading history...
297
            // replace url param placeholder
298
            $urlParams = str_replace("##page##", (int) $data['page'], $this->settings['pdfparams']);
299
            $urlParams = str_replace("##docId##", $document->recordId, $urlParams);
300
            $urlParams = str_replace("##startpage##", (int) $data['startpage'], $urlParams);
301
            if ($data['startpage'] != $data['endpage']) {
302
                $urlParams = str_replace("##endpage##", $data['endpage'] === "" ? "" : (int) $data['endpage'], $urlParams);
303
            } else {
304
                // remove parameter endpage
305
                $urlParams = str_replace(",##endpage##", '', $urlParams);
306
            }
307
            $urlParams = str_replace("##startx##", $data['startX'] === "" ? "" : (int) $data['startX'], $urlParams);
308
            $urlParams = str_replace("##starty##", $data['startY'] === "" ? "" : (int) $data['startY'], $urlParams);
309
            $urlParams = str_replace("##endx##", $data['endX'] === "" ? "" : (int) $data['endX'], $urlParams);
310
            $urlParams = str_replace("##endy##", $data['endY'] === "" ? "" : (int) $data['endY'], $urlParams);
311
            $urlParams = str_replace("##rotation##", $data['rotation'] === "" ? "" : (int) $data['rotation'], $urlParams);
312
313
            $downloadUrl = $this->settings['pdfgenerate'] . $urlParams;
314
315
            $title = $document->getTitle($id, true);
316
            if (empty($title)) {
317
                $title = LocalizationUtility::translate('basket.noTitle', 'dlf');
318
            }
319
320
            // Set page and cutout information
321
            $info = '';
322
            if ($data['startX'] != '' && $data['endX'] != '') {
323
                // cutout
324
                $info .= htmlspecialchars(LocalizationUtility::translate('basket.cutout', 'dlf')) . ' ';
0 ignored issues
show
Bug introduced by
It seems like TYPO3\CMS\Extbase\Utilit...'basket.cutout', 'dlf') can also be of type null; however, parameter $string of htmlspecialchars() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

324
                $info .= htmlspecialchars(/** @scrutinizer ignore-type */ LocalizationUtility::translate('basket.cutout', 'dlf')) . ' ';
Loading history...
325
            }
326
            if ($data['startpage'] == $data['endpage']) {
327
                // One page
328
                $info .= htmlspecialchars(LocalizationUtility::translate('page', 'dlf')) . ' ' . $data['startpage'];
329
            } else {
330
                $info .= htmlspecialchars(LocalizationUtility::translate('page', 'dlf')) . ' ' . $data['startpage'] . '-' . $data['endpage'];
331
            }
332
            $downloadLink = '<a href="' . $downloadUrl . '" target="_blank">' . htmlspecialchars($title) . '</a> (' . $info . ')';
333
            if ($data['startpage'] == $data['endpage']) {
334
                $pageNums = 1;
335
            } else {
336
                $pageNums = $data['endpage'] - $data['startpage'];
337
            }
338
            return [
339
                'downloadUrl' => $downloadUrl,
340
                'title' => $title,
341
                'info' => $info,
342
                'downloadLink' => $downloadLink,
343
                'pageNums' => $pageNums,
344
                'urlParams' => $urlParams,
345
                'record_id' => $document->recordId,
346
            ];
347
        }
348
        return false;
349
    }
350
351
    /**
352
     * Adds documents to the basket
353
     *
354
     * @access protected
355
     *
356
     * @param array $_piVars: piVars
357
     * @param array $basketData: basket data
358
     *
359
     * @return array Basket data and Javascript output
360
     */
361
    protected function addToBasket($_piVars, $basketData)
362
    {
363
        $output = '';
364
        if (!$_piVars['startpage']) {
365
            $page = 0;
366
        } else {
367
            $page = (int) $_piVars['startpage'];
368
        }
369
        if ($page != null || $_piVars['addToBasket'] == 'list') {
370
            $documentItem = [
371
                'id' => (int) $_piVars['id'],
372
                'startpage' => (int) $_piVars['startpage'],
373
                'endpage' => !isset($_piVars['endpage']) || $_piVars['endpage'] === "" ? "" : (int) $_piVars['endpage'],
374
                'startX' => !isset($_piVars['startX']) || $_piVars['startX'] === "" ? "" : (int) $_piVars['startX'],
375
                'startY' => !isset($_piVars['startY']) || $_piVars['startY'] === "" ? "" : (int) $_piVars['startY'],
376
                'endX' => !isset($_piVars['endX']) || $_piVars['endX'] === "" ? "" : (int) $_piVars['endX'],
377
                'endY' => !isset($_piVars['endY']) || $_piVars['endY'] === "" ? "" : (int) $_piVars['endY'],
378
                'rotation' => !isset($_piVars['rotation']) || $_piVars['rotation'] === "" ? "" : (int) $_piVars['rotation']
379
            ];
380
            // update basket
381
            if (!empty($basketData['doc_ids'])) {
382
                $items = $basketData['doc_ids'];
383
                $items = get_object_vars($items);
384
            } else {
385
                $items = [];
386
            }
387
            // get document instance to load further information
388
            $document = Document::getInstance($documentItem['id'], 0);
389
            // set endpage for toc and subentry based on logid
390
            if (($_piVars['addToBasket'] == 'subentry') or ($_piVars['addToBasket'] == 'toc')) {
391
                $smLinks = $document->smLinks;
392
                $pageCounter = sizeof($smLinks['l2p'][$_piVars['logId']]);
393
                $documentItem['endpage'] = ($documentItem['startpage'] + $pageCounter) - 1;
394
            }
395
            // add whole document
396
            if ($_piVars['addToBasket'] == 'list') {
397
                $documentItem['endpage'] = $document->numPages;
398
            }
399
            $arrayKey = $documentItem['id'] . '_' . $page;
400
            if (!empty($documentItem['startX'])) {
401
                $arrayKey .= '_' . $documentItem['startX'];
402
            }
403
            if (!empty($documentItem['endX'])) {
404
                $arrayKey .= '_' . $documentItem['endX'];
405
            }
406
            // do not add more than one identical object
407
            if (!in_array($arrayKey, $items)) {
408
                $items[$arrayKey] = $documentItem;
409
                // replace url param placeholder
410
                $pdfParams = str_replace("##startpage##", $documentItem['startpage'], $this->settings['pdfparams']);
411
                $pdfParams = str_replace("##docId##", $document->recordId, $pdfParams);
412
                $pdfParams = str_replace("##startx##", $documentItem['startX'], $pdfParams);
413
                $pdfParams = str_replace("##starty##", $documentItem['startY'], $pdfParams);
414
                $pdfParams = str_replace("##endx##", $documentItem['endX'], $pdfParams);
415
                $pdfParams = str_replace("##endy##", $documentItem['endY'], $pdfParams);
416
                $pdfParams = str_replace("##rotation##", $documentItem['rotation'], $pdfParams);
417
                if ($documentItem['startpage'] != $documentItem['endpage']) {
418
                    $pdfParams = str_replace("##endpage##", $documentItem['endpage'], $pdfParams);
419
                } else {
420
                    // remove parameter endpage
421
                    $pdfParams = str_replace(",##endpage##", '', $pdfParams);
422
                }
423
                $pdfGenerateUrl = $this->settings['pdfgenerate'] . $pdfParams;
424
                if ($this->settings['pregeneration']) {
425
                    // send ajax request to webapp
426
                    $output .= '
427
     <script>
428
      $(document).ready(function(){
429
       $.ajax({
430
         url: "' . $pdfGenerateUrl . '",
431
       }).done(function() {
432
       });
433
      });
434
     </script>';
435
                }
436
            }
437
            $update = ['doc_ids' => json_encode($items)];
438
            GeneralUtility::makeInstance(ConnectionPool::class)
439
                ->getConnectionForTable('tx_dlf_basket')
440
                ->update(
441
                    'tx_dlf_basket',
442
                    $update,
443
                    ['uid' => (int) $basketData['uid']]
444
                );
445
            $basketData['doc_ids'] = $items;
446
        }
447
        return ['basketData' => $basketData, 'jsOutput' => $output];
448
    }
449
450
    /**
451
     * Removes selected documents from basket
452
     *
453
     * @access protected
454
     *
455
     * @param array $_piVars: plugin variables
456
     * @param array $basketData: array with document information
457
     *
458
     * @return array basket data
459
     */
460
    protected function removeFromBasket($_piVars, $basketData)
461
    {
462
        if (!empty($basketData['doc_ids'])) {
463
            $items = $basketData['doc_ids'];
464
            $items = get_object_vars($items);
465
        }
466
        foreach ($_piVars['selected'] as $value) {
467
            if (isset($value['id'])) {
468
                $arrayKey = $value['id'] . '_' . $value['startpage'];
469
                if (!empty($value['startX'])) {
470
                    $arrayKey .= '_' . $value['startX'];
471
                }
472
                if (!empty($value['endX'])) {
473
                    $arrayKey .= '_' . $value['endX'];
474
                }
475
                if (isset($items[$arrayKey])) {
476
                    unset($items[$arrayKey]);
477
                }
478
            }
479
        }
480
        if (empty($items)) {
481
            $update = ['doc_ids' => ''];
482
        } else {
483
            $update = ['doc_ids' => json_encode($items)];
484
        }
485
486
        GeneralUtility::makeInstance(ConnectionPool::class)
487
            ->getConnectionForTable('tx_dlf_basket')
488
            ->update(
489
                'tx_dlf_basket',
490
                 $update,
491
                ['uid' => (int) $basketData['uid']]
492
            );
493
        $basketData['doc_ids'] = $items;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $items does not seem to be defined for all execution paths leading up to this point.
Loading history...
494
        return $basketData;
495
    }
496
497
    /**
498
     * Send mail with pdf download url
499
     *
500
     * @access protected
501
     *
502
     * @return void
503
     */
504
    protected function sendMail($requestData)
505
    {
506
        // send mail
507
        $mailId = $requestData['mail_action'];
508
509
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
510
            ->getQueryBuilderForTable('tx_dlf_mail');
511
512
        // get id from db and send selected doc download link
513
        $resultMail = $queryBuilder
514
            ->select('*')
515
            ->from('tx_dlf_mail')
516
            ->where(
517
                $queryBuilder->expr()->eq('tx_dlf_mail.uid', intval($mailId)),
518
                Helper::whereExpression('tx_dlf_mail')
519
            )
520
            ->setMaxResults(1)
521
            ->execute();
522
523
        $allResults = $resultMail->fetchAll();
524
        $mailData = $allResults[0];
525
        $mailText = htmlspecialchars(LocalizationUtility::translate('basket.mailBody', 'dlf')) . "\n";
0 ignored issues
show
Bug introduced by
It seems like TYPO3\CMS\Extbase\Utilit...asket.mailBody', 'dlf') can also be of type null; however, parameter $string of htmlspecialchars() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

525
        $mailText = htmlspecialchars(/** @scrutinizer ignore-type */ LocalizationUtility::translate('basket.mailBody', 'dlf')) . "\n";
Loading history...
526
        $numberOfPages = 0;
527
        $pdfUrl = $this->settings['pdfdownload'];
528
        // prepare links
529
        foreach ($requestData['selected'] as $docValue) {
530
            if ($docValue['id']) {
531
                $explodeId = explode("_", $docValue['id']);
532
                $docData = $this->getDocumentData($explodeId[0], $docValue);
533
                $pdfUrl .= $docData['urlParams'] . $this->settings['pdfparamseparator'];
534
                $pages = (abs(intval($docValue['startpage']) - intval($docValue['endpage'])));
535
                if ($pages === 0) {
536
                    $numberOfPages = $numberOfPages + 1;
537
                } else {
538
                    $numberOfPages = $numberOfPages + $pages;
539
                }
540
            }
541
        }
542
        // Remove leading/tailing pdfparamseperator
543
        $pdfUrl = trim($pdfUrl, $this->settings['pdfparamseparator']);
544
        $mailBody = $mailText . $pdfUrl;
545
        // Get hook objects.
546
        $hookObjects = Helper::getHookObjects($this->scriptRelPath);
0 ignored issues
show
Bug Best Practice introduced by
The property scriptRelPath does not exist on Kitodo\Dlf\Controller\BasketController. Did you maybe forget to declare it?
Loading history...
547
        // Hook for getting a customized mail body.
548
        foreach ($hookObjects as $hookObj) {
549
            if (method_exists($hookObj, 'customizeMailBody')) {
550
                $mailBody = $hookObj->customizeMailBody($mailText, $pdfUrl);
551
            }
552
        }
553
        $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
554
        // send mail
555
        $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
556
        // Prepare and send the message
557
        $mail
558
            // subject
559
            ->setSubject(LocalizationUtility::translate('basket.mailSubject', 'dlf'))
560
            // Set the From address with an associative array
561
            ->setFrom($from)
562
            // Set the To addresses with an associative array
563
            ->setTo([$mailData['mail'] => $mailData['name']])
564
            ->setBody($mailBody, 'text/html')
565
            ->send();
566
        // protocol
567
        $insertArray = [
568
            'pid' => $this->settings['pages'],
569
            'file_name' => $pdfUrl,
570
            'count_pages' => $numberOfPages,
571
            'crdate' => time(),
572
        ];
573
        if ($GLOBALS["TSFE"]->loginUser) {
574
            // internal user
575
            $insertArray['user_id'] = $GLOBALS["TSFE"]->fe_user->user['uid'];
576
            $insertArray['name'] = $GLOBALS["TSFE"]->fe_user->user['username'];
577
            $insertArray['label'] = 'Mail: ' . $mailData['mail'];
578
        } else {
579
            // external user
580
            $insertArray['user_id'] = 0;
581
            $insertArray['name'] = 'n/a';
582
            $insertArray['label'] = 'Mail: ' . $mailData['mail'];
583
        }
584
        // add action to protocol
585
        GeneralUtility::makeInstance(ConnectionPool::class)
586
            ->getConnectionForTable('tx_dlf_actionlog')
587
            ->insert(
588
                'tx_dlf_actionlog',
589
                $insertArray
590
            );
591
        $this->redirect('main');
592
    }
593
594
    /**
595
     * Sends document information to an external printer (url)
596
     *
597
     * @access protected
598
     *
599
     * @return void
600
     */
601
    protected function printDocument($requestData, $basketData)
0 ignored issues
show
Unused Code introduced by
The parameter $basketData is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

601
    protected function printDocument($requestData, /** @scrutinizer ignore-unused */ $basketData)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
602
    {
603
        $pdfUrl = $this->settings['pdfprint'];
604
        $numberOfPages = 0;
605
        foreach ($requestData['selected'] as $docId => $docValue) {
606
            if ($docValue['id']) {
607
                $docData = $this->getDocumentData($docValue['id'], $docValue);
608
                $pdfUrl .= $docData['urlParams'] . $this->settings['pdfparamseparator'];
609
                $numberOfPages += $docData['pageNums'];
610
            }
611
        }
612
        // get printer data
613
        $printerId = $requestData['print_action'];
614
615
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
616
            ->getQueryBuilderForTable('tx_dlf_printer');
617
618
        // get id from db and send selected doc download link
619
        $resultPrinter = $queryBuilder
620
            ->select('*')
621
            ->from('tx_dlf_printer')
622
            ->where(
623
                $queryBuilder->expr()->eq('tx_dlf_printer.uid', intval($printerId)),
624
                Helper::whereExpression('tx_dlf_printer')
625
            )
626
            ->setMaxResults(1)
627
            ->execute();
628
629
        $allResults = $resultPrinter->fetchAll();
630
        $printerData = $allResults[0];
631
        // printer is selected
632
        if ($printerData) {
633
            $pdfUrl = $printerData['print'];
634
            $numberOfPages = 0;
635
            foreach ($requestData['selected'] as $docId => $docValue) {
636
                if ($docValue['id']) {
637
                    $explodeId = explode("_", $docId);
638
                    $docData = $this->getDocumentData($explodeId[0], $docValue);
639
                    $pdfUrl .= $docData['urlParams'] . $this->settings['pdfparamseparator'];
640
                    $numberOfPages += $docData['pageNums'];
641
                }
642
            }
643
            $pdfUrl = trim($pdfUrl, $this->settings['pdfparamseparator']);
644
        }
645
        // protocol
646
        $insertArray = [
647
            'pid' => $this->settings['pages'],
648
            'file_name' => $pdfUrl,
649
            'count_pages' => $numberOfPages,
650
            'crdate' => time(),
651
        ];
652
        if ($GLOBALS["TSFE"]->loginUser) {
653
            // internal user
654
            $insertArray['user_id'] = $GLOBALS["TSFE"]->fe_user->user['uid'];
655
            $insertArray['name'] = $GLOBALS["TSFE"]->fe_user->user['username'];
656
            $insertArray['label'] = 'Print: ' . $printerData['label'];
657
        } else {
658
            // external user
659
            $insertArray['user_id'] = 0;
660
            $insertArray['name'] = 'n/a';
661
            $insertArray['label'] = 'Print: ' . $printerData['label'];
662
        }
663
        // add action to protocol
664
        GeneralUtility::makeInstance(ConnectionPool::class)
665
            ->getConnectionForTable('tx_dlf_actionlog')
666
            ->insert(
667
                'tx_dlf_actionlog',
668
                $insertArray
669
            );
670
671
        $this->redirectToUri($pdfUrl);
672
    }
673
674
}
675