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 — master (#715)
by Alexander
03:35
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 Kitodo\Dlf\Domain\Repository\MailRepository;
18
use Kitodo\Dlf\Domain\Repository\BasketRepository;
19
use Kitodo\Dlf\Domain\Repository\PrinterRepository;
20
use TYPO3\CMS\Core\Database\Connection;
21
use TYPO3\CMS\Core\Database\ConnectionPool;
22
use TYPO3\CMS\Core\Utility\GeneralUtility;
23
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
24
25
class BasketController extends AbstractController
26
{
27
28
    /**
29
     * @var BasketRepository
30
     */
31
    protected $basketRepository;
32
33
    /**
34
     * @var MailRepository
35
     */
36
    protected $mailRepository;
37
38
    /**
39
     * @var PrinterRepository
40
     */
41
    protected $printerRepository;
42
43
    /**
44
     * @param BasketRepository $basketRepository
45
     */
46
    public function injectBasketRepository(BasketRepository $basketRepository)
47
    {
48
        $this->basketRepository = $basketRepository;
49
    }
50
51
    /**
52
     * @param MailRepository $mailRepository
53
     */
54
    public function injectMailRepository(MailRepository $mailRepository)
55
    {
56
        $this->mailRepository = $mailRepository;
57
    }
58
59
    /**
60
     * @param PrinterRepository $printerRepository
61
     */
62
    public function injectPrinterRepository(PrinterRepository $printerRepository)
63
    {
64
        $this->printerRepository = $printerRepository;
65
    }
66
67
    /**
68
     * Different actions which depends on the choosen action (form)
69
     *
70
     * @return void
71
     */
72
    public function basketAction()
73
    {
74
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
75
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
76
77
        $basketData = $this->getBasketData();
78
79
        // action remove from basket
80
        if ($requestData['basket_action'] === 'remove') {
81
            // remove entry from list
82
            if (isset($requestData['selected'])) {
83
                $basketData = $this->removeFromBasket($requestData, $basketData);
84
            }
85
        }
86
        // action remove from basket
87
        if ($requestData['basket_action'] == 'download') {
88
            // open selected documents
89
            if (isset($requestData['selected'])) {
90
                $pdfUrl = $this->settings['pdfgenerate'];
91
                foreach ($requestData['selected'] as $docValue) {
92
                    if ($docValue['id']) {
93
                        $docData = $this->getDocumentData($docValue['id'], $docValue);
94
                        $pdfUrl .= $docData['urlParams'] . $this->settings['pdfparamseparator'];
95
                        $this->redirectToUri($pdfUrl);
96
                    }
97
                }
98
            }
99
        }
100
        // action print from basket
101
        if ($requestData['print_action']) {
102
            // open selected documents
103
            if (isset($requestData['selected'])) {
104
                $this->printDocument($requestData, $basketData);
105
            }
106
        }
107
        // action send mail
108
        if ($requestData['mail_action']) {
109
            if (isset($requestData['selected'])) {
110
                $this->sendMail($requestData);
111
            }
112
        }
113
114
        $this->redirect('main');
115
    }
116
117
    /**
118
     * Add documents to the basket
119
     *
120
     * @return void
121
     */
122
    public function addAction()
123
    {
124
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
125
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
126
127
        $basketData = $this->getBasketData();
128
129
        if (
130
            !empty($requestData['id'])
131
            && $requestData['addToBasket']
132
        ) {
133
            $returnData = $this->addToBasket($requestData, $basketData);
134
            $this->view->assign('pregenerateJs', $returnData['jsOutput']);
135
        }
136
137
        $this->redirect('main');
138
    }
139
140
    /**
141
     * The main method of the plugin
142
     *
143
     * @return void
144
     */
145
    public function mainAction()
146
    {
147
        $requestData = GeneralUtility::_GPmerged('tx_dlf');
148
        unset($requestData['__referrer'], $requestData['__trustedProperties']);
149
150
        $basketData = $this->getBasketData();
151
152
        if ($basketData['doc_ids']) {
153
            if (is_object($basketData['doc_ids'])) {
154
                $basketData['doc_ids'] = get_object_vars($basketData['doc_ids']);
155
            }
156
            $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

156
            $count = sprintf(/** @scrutinizer ignore-type */ LocalizationUtility::translate('basket.count', 'dlf'), count($basketData['doc_ids']));
Loading history...
157
        } else {
158
            $count = sprintf(LocalizationUtility::translate('basket.count', 'dlf'), 0);
159
        }
160
        $this->view->assign('count', $count);
161
162
        $allMails = $this->mailRepository->findAllWithPid($this->settings['pages']);
163
164
        $mailSelect = [];
165
        if ($allMails->count() > 0) {
166
            $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

166
            $mailSelect[0] = htmlspecialchars(/** @scrutinizer ignore-type */ LocalizationUtility::translate('basket.chooseMail', 'dlf'));
Loading history...
167
            foreach ($allMails as $mail) {
168
                $mailSelect[$mail->getUid()] = htmlspecialchars($mail->getName()) . ' (' . htmlspecialchars($mail->getMail()) . ')';
169
            }
170
            $this->view->assign('mailSelect', $mailSelect);
171
        }
172
173
        $allPrinter = $this->printerRepository->findAllWithPid($this->settings['pages']);
174
175
        $printSelect = [];
176
        if ($allPrinter->count() > 0) {
177
            $printSelect[0] = htmlspecialchars(LocalizationUtility::translate('basket.choosePrinter', 'dlf'));
178
            foreach ($allPrinter as $printer) {
179
                $printSelect[$printer->getUid()] = htmlspecialchars($printer->getLabel());
180
            }
181
            $this->view->assign('printSelect', $printSelect);
182
        }
183
184
        $entries = [];
185
        if (isset($basketData['doc_ids'])) {
186
            // get each entry
187
            foreach ($basketData['doc_ids'] as $value) {
188
                $entries[] = $this->getEntry($value);
189
            }
190
            $this->view->assign('entries', $entries);
191
        }
192
    }
193
194
    /**
195
     * The basket data from user session.
196
     *
197
     * @return array The found data from user session.
198
     */
199
    protected function getBasketData()
200
    {
201
        // get user session
202
        $sessionId = $GLOBALS['TSFE']->fe_user->id;
203
204
        if ($GLOBALS['TSFE']->loginUser) {
205
            $basket = $this->basketRepository->findOneByFeUserId((int) $GLOBALS['TSFE']->fe_user->user['uid']);
0 ignored issues
show
Bug introduced by
The method findOneByFeUserId() does not exist on Kitodo\Dlf\Domain\Repository\BasketRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

205
            /** @scrutinizer ignore-call */ 
206
            $basket = $this->basketRepository->findOneByFeUserId((int) $GLOBALS['TSFE']->fe_user->user['uid']);
Loading history...
206
        } else {
207
            $GLOBALS['TSFE']->fe_user->setKey('ses', 'tx_dlf_basket', '');
208
            $GLOBALS['TSFE']->fe_user->sesData_change = true;
209
            $GLOBALS['TSFE']->fe_user->storeSessionData();
210
211
            $basket = $this->basketRepository->findOneBySessionId($sessionId);
0 ignored issues
show
Bug introduced by
The method findOneBySessionId() does not exist on Kitodo\Dlf\Domain\Repository\BasketRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

211
            /** @scrutinizer ignore-call */ 
212
            $basket = $this->basketRepository->findOneBySessionId($sessionId);
Loading history...
212
        }
213
        // session already exists
214
        if ($basket === null) {
215
            // create new basket in db
216
            $insertArray['fe_user_id'] = $GLOBALS['TSFE']->loginUser ? $GLOBALS['TSFE']->fe_user->user['uid'] : 0;
217
            $insertArray['session_id'] = $sessionId;
218
            $insertArray['doc_ids'] = '';
219
            $insertArray['label'] = '';
220
            $insertArray['l18n_diffsource'] = '';
221
            GeneralUtility::makeInstance(ConnectionPool::class)
222
                ->getConnectionForTable('tx_dlf_basket')
223
                ->insert(
224
                    'tx_dlf_basket',
225
                    $insertArray
226
                );
227
228
            return '';
0 ignored issues
show
Bug Best Practice introduced by
The expression return '' returns the type string which is incompatible with the documented return type array.
Loading history...
229
        }
230
231
        $basketData['uid'] = $basket->getUid();
0 ignored issues
show
Bug introduced by
The method getUid() does not exist on TYPO3\CMS\Extbase\Persistence\QueryResultInterface. ( Ignorable by Annotation )

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

231
        /** @scrutinizer ignore-call */ 
232
        $basketData['uid'] = $basket->getUid();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
232
        $basketData['doc_ids'] = json_decode($basket->getDocIds());
0 ignored issues
show
Bug introduced by
The method getDocIds() does not exist on TYPO3\CMS\Extbase\Persistence\QueryResultInterface. ( Ignorable by Annotation )

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

232
        $basketData['doc_ids'] = json_decode($basket->/** @scrutinizer ignore-call */ getDocIds());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
233
        return $basketData;
234
    }
235
236
    /**
237
     * Return one basket entry
238
     *
239
     * @access protected
240
     *
241
     * @param array $data: DocumentData
242
     * @param array $template: Template information
243
     *
244
     * @return string One basket entry
245
     */
246
    protected function getEntry($data)
247
    {
248
        if (is_object($data)) {
249
            $data = get_object_vars($data);
250
        }
251
        $id = $data['id'];
252
        $startpage = $data['startpage'];
253
        $endpage = $data['endpage'];
254
        $startX = $data['startX'];
255
        $startY = $data['startY'];
256
        $endX = $data['endX'];
257
        $endY = $data['endY'];
258
        $rotation = $data['rotation'];
259
260
        $docData = $this->getDocumentData($id, $data);
261
262
        $entryArray['BASKETDATA'] = $docData;
263
264
        $entryKey = $id . '_' . $startpage;
265
        if (!empty($startX)) {
266
            $entryKey .= '_' . $startX;
267
        }
268
        if (!empty($endX)) {
269
            $entryKey .= '_' . $endX;
270
        }
271
272
        $entryArray['id'] = $id;
273
        $entryArray['CONTROLS'] = [
274
            'startpage' => $startpage,
275
            'endpage' => $endpage,
276
            'startX' => $startX,
277
            'startY' => $startY,
278
            'endX' => $endX,
279
            'endY' => $endY,
280
            'rotation' => $rotation,
281
        ];
282
283
        $entryArray['NUMBER'] = $docData['record_id'];
284
        $entryArray['key'] = $entryKey;
285
286
        // return one entry
287
        return $entryArray;
288
    }
289
290
    /**
291
     * Returns the downloadurl configured in the basket
292
     *
293
     * @access protected
294
     *
295
     * @param int $id: Document id
296
     *
297
     * @return mixed download url or false
298
     */
299
    protected function getDocumentData($id, $data)
300
    {
301
        // get document instance to load further information
302
        $document = Document::getInstance($id, 0);
303
        if ($document) {
0 ignored issues
show
introduced by
$document is of type Kitodo\Dlf\Common\Document, thus it always evaluated to true.
Loading history...
304
            // replace url param placeholder
305
            $urlParams = str_replace("##page##", (int) $data['page'], $this->settings['pdfparams']);
306
            $urlParams = str_replace("##docId##", $document->recordId, $urlParams);
307
            $urlParams = str_replace("##startpage##", (int) $data['startpage'], $urlParams);
308
            if ($data['startpage'] != $data['endpage']) {
309
                $urlParams = str_replace("##endpage##", $data['endpage'] === "" ? "" : (int) $data['endpage'], $urlParams);
310
            } else {
311
                // remove parameter endpage
312
                $urlParams = str_replace(",##endpage##", '', $urlParams);
313
            }
314
            $urlParams = str_replace("##startx##", $data['startX'] === "" ? "" : (int) $data['startX'], $urlParams);
315
            $urlParams = str_replace("##starty##", $data['startY'] === "" ? "" : (int) $data['startY'], $urlParams);
316
            $urlParams = str_replace("##endx##", $data['endX'] === "" ? "" : (int) $data['endX'], $urlParams);
317
            $urlParams = str_replace("##endy##", $data['endY'] === "" ? "" : (int) $data['endY'], $urlParams);
318
            $urlParams = str_replace("##rotation##", $data['rotation'] === "" ? "" : (int) $data['rotation'], $urlParams);
319
320
            $downloadUrl = $this->settings['pdfgenerate'] . $urlParams;
321
322
            $title = $document->getTitle($id, true);
323
            if (empty($title)) {
324
                $title = LocalizationUtility::translate('basket.noTitle', 'dlf');
325
            }
326
327
            // Set page and cutout information
328
            $info = '';
329
            if ($data['startX'] != '' && $data['endX'] != '') {
330
                // cutout
331
                $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

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

518
        $mailText = htmlspecialchars(/** @scrutinizer ignore-type */ LocalizationUtility::translate('basket.mailBody', 'dlf')) . "\n";
Loading history...
519
        $numberOfPages = 0;
520
        $pdfUrl = $this->settings['pdfdownload'];
521
        // prepare links
522
        foreach ($requestData['selected'] as $docValue) {
523
            if ($docValue['id']) {
524
                $explodeId = explode("_", $docValue['id']);
525
                $docData = $this->getDocumentData($explodeId[0], $docValue);
526
                $pdfUrl .= $docData['urlParams'] . $this->settings['pdfparamseparator'];
527
                $pages = (abs(intval($docValue['startpage']) - intval($docValue['endpage'])));
528
                if ($pages === 0) {
529
                    $numberOfPages = $numberOfPages + 1;
530
                } else {
531
                    $numberOfPages = $numberOfPages + $pages;
532
                }
533
            }
534
        }
535
        // Remove leading/tailing pdfparamseperator
536
        $pdfUrl = trim($pdfUrl, $this->settings['pdfparamseparator']);
537
        $mailBody = $mailText . $pdfUrl;
538
        // Get hook objects.
539
        $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...
540
        // Hook for getting a customized mail body.
541
        foreach ($hookObjects as $hookObj) {
542
            if (method_exists($hookObj, 'customizeMailBody')) {
543
                $mailBody = $hookObj->customizeMailBody($mailText, $pdfUrl);
544
            }
545
        }
546
        $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
547
        // send mail
548
        $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
549
        // Prepare and send the message
550
        $mail
551
            // subject
552
            ->setSubject(LocalizationUtility::translate('basket.mailSubject', 'dlf'))
553
            // Set the From address with an associative array
554
            ->setFrom($from)
555
            // Set the To addresses with an associative array
556
            ->setTo([$mailObject->getMail() => $mailObject->getName()])
557
            ->setBody($mailBody, 'text/html')
558
            ->send();
559
        // protocol
560
        $insertArray = [
561
            'pid' => $this->settings['pages'],
562
            'file_name' => $pdfUrl,
563
            'count_pages' => $numberOfPages,
564
            'crdate' => time(),
565
        ];
566
        if ($GLOBALS["TSFE"]->loginUser) {
567
            // internal user
568
            $insertArray['user_id'] = $GLOBALS["TSFE"]->fe_user->user['uid'];
569
            $insertArray['name'] = $GLOBALS["TSFE"]->fe_user->user['username'];
570
            $insertArray['label'] = 'Mail: ' . $mailObject->getMail();
571
        } else {
572
            // external user
573
            $insertArray['user_id'] = 0;
574
            $insertArray['name'] = 'n/a';
575
            $insertArray['label'] = 'Mail: ' . $mailObject->getMail();
576
        }
577
        // add action to protocol
578
        GeneralUtility::makeInstance(ConnectionPool::class)
579
            ->getConnectionForTable('tx_dlf_actionlog')
580
            ->insert(
581
                'tx_dlf_actionlog',
582
                $insertArray
583
            );
584
        $this->redirect('main');
585
    }
586
587
    /**
588
     * Sends document information to an external printer (url)
589
     *
590
     * @access protected
591
     *
592
     * @return void
593
     */
594
    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

594
    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...
595
    {
596
        $pdfUrl = $this->settings['pdfprint'];
597
        $numberOfPages = 0;
598
        foreach ($requestData['selected'] as $docId => $docValue) {
599
            if ($docValue['id']) {
600
                $docData = $this->getDocumentData($docValue['id'], $docValue);
601
                $pdfUrl .= $docData['urlParams'] . $this->settings['pdfparamseparator'];
602
                $numberOfPages += $docData['pageNums'];
603
            }
604
        }
605
        // get printer data
606
        $printerId = $requestData['print_action'];
607
608
        // get id from db and send selected doc download link
609
        $printer = $this->printerRepository->findByUid($printerId)->getFirst();
610
611
        // printer is selected
612
        if ($printer) {
613
            $pdfUrl = $printer->getPrint();
614
            $numberOfPages = 0;
615
            foreach ($requestData['selected'] as $docId => $docValue) {
616
                if ($docValue['id']) {
617
                    $explodeId = explode("_", $docId);
618
                    $docData = $this->getDocumentData($explodeId[0], $docValue);
619
                    $pdfUrl .= $docData['urlParams'] . $this->settings['pdfparamseparator'];
620
                    $numberOfPages += $docData['pageNums'];
621
                }
622
            }
623
            $pdfUrl = trim($pdfUrl, $this->settings['pdfparamseparator']);
624
        }
625
        // protocol
626
        $insertArray = [
627
            'pid' => $this->settings['pages'],
628
            'file_name' => $pdfUrl,
629
            'count_pages' => $numberOfPages,
630
            'crdate' => time(),
631
        ];
632
        if ($GLOBALS["TSFE"]->loginUser) {
633
            // internal user
634
            $insertArray['user_id'] = $GLOBALS["TSFE"]->fe_user->user['uid'];
635
            $insertArray['name'] = $GLOBALS["TSFE"]->fe_user->user['username'];
636
            $insertArray['label'] = 'Print: ' . $printer->getLabel();
637
        } else {
638
            // external user
639
            $insertArray['user_id'] = 0;
640
            $insertArray['name'] = 'n/a';
641
            $insertArray['label'] = 'Print: ' . $printer->getLabel();
642
        }
643
        // add action to protocol
644
        GeneralUtility::makeInstance(ConnectionPool::class)
645
            ->getConnectionForTable('tx_dlf_actionlog')
646
            ->insert(
647
                'tx_dlf_actionlog',
648
                $insertArray
649
            );
650
651
        $this->redirectToUri($pdfUrl);
652
    }
653
654
}
655