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 (#329)
by Sebastian
03:28
created

Basket::printDocument()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 60
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 44
nc 12
nop 0
dl 0
loc 60
rs 8.2826
c 0
b 0
f 0

How to fix   Long Method   

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
namespace Kitodo\Dlf\Plugins;
3
4
/**
5
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
6
 *
7
 * This file is part of the Kitodo and TYPO3 projects.
8
 *
9
 * @license GNU General Public License version 3 or later.
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 */
13
14
use Kitodo\Dlf\Common\Document;
15
use Kitodo\Dlf\Common\Helper;
16
17
/**
18
 * Plugin 'Basket' for the 'dlf' extension
19
 *
20
 * @author Christopher Timm <[email protected]>
21
 * @package TYPO3
22
 * @subpackage dlf
23
 * @access public
24
 */
25
class Basket extends \Kitodo\Dlf\Common\AbstractPlugin {
26
    public $scriptRelPath = 'Classes/Plugins/Basket.php';
27
28
    /**
29
     * The main method of the PlugIn
30
     *
31
     * @access public
32
     *
33
     * @param string $content: The PlugIn content
34
     * @param array $conf: The PlugIn configuration
35
     *
36
     * @return string The content that is displayed on the website
37
     */
38
    public function main($content, $conf) {
39
        $this->init($conf);
40
        // Don't cache the output.
41
        $this->setCache(FALSE);
42
        // Load template file.
43
        $this->getTemplate();
44
        $subpartArray['entry'] = $this->cObj->getSubpart($this->template, '###ENTRY###');
1 ignored issue
show
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Conte...tRenderer::getSubpart() has been deprecated: since TYPO3 v8, will be removed in TYPO3 v9, please use the MarkerBasedTemplateService instead. ( Ignorable by Annotation )

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

44
        $subpartArray['entry'] = /** @scrutinizer ignore-deprecated */ $this->cObj->getSubpart($this->template, '###ENTRY###');

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
Comprehensibility Best Practice introduced by
$subpartArray was never initialized. Although not strictly required by PHP, it is generally a good practice to add $subpartArray = array(); before regardless.
Loading history...
45
        $markerArray['###JS###'] = '';
1 ignored issue
show
Comprehensibility Best Practice introduced by
$markerArray was never initialized. Although not strictly required by PHP, it is generally a good practice to add $markerArray = array(); before regardless.
Loading history...
46
        // get user session
47
        $sessionId = $GLOBALS['TSFE']->fe_user->id;
48
        if ($GLOBALS['TSFE']->loginUser) {
49
            $insertArray['fe_user_id'] = $GLOBALS['TSFE']->fe_user->user['uid'];
1 ignored issue
show
Comprehensibility Best Practice introduced by
$insertArray was never initialized. Although not strictly required by PHP, it is generally a good practice to add $insertArray = array(); before regardless.
Loading history...
50
            $query = $GLOBALS['TYPO3_DB']->SELECTquery(
51
                '*',
52
                'tx_dlf_basket',
53
                'tx_dlf_basket.fe_user_id='.intval($insertArray['fe_user_id'])
54
                    .Helper::whereClause('tx_dlf_basket'),
55
                '',
56
                '',
57
                '1'
58
            );
59
        } else {
60
            $GLOBALS['TSFE']->fe_user->setKey('ses', 'tx_dlf_basket', '');
61
            $GLOBALS['TSFE']->fe_user->sesData_change = TRUE;
62
            $GLOBALS['TSFE']->fe_user->storeSessionData();
63
            $query = $GLOBALS['TYPO3_DB']->SELECTquery(
64
                '*',
65
                'tx_dlf_basket',
66
                'tx_dlf_basket.session_id='.$GLOBALS['TYPO3_DB']->fullQuoteStr($sessionId, 'tx_dlf_basket')
67
                    .Helper::whereClause('tx_dlf_basket'),
68
                '',
69
                '',
70
                '1'
71
            );
72
        }
73
        $result = $GLOBALS['TYPO3_DB']->sql_query($query);
74
        // session already exists
75
        if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) == 0) {
76
            // create new basket in db
77
            $insertArray['session_id'] = $sessionId;
78
            $insertArray['doc_ids'] = '';
79
            $insertArray['label'] = '';
80
            $insertArray['l18n_diffsource'] = '';
81
            $GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_dlf_basket', $insertArray);
82
            $result = $GLOBALS['TYPO3_DB']->sql_query($query);
83
        }
84
        $basketData = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
85
        $piVars = $this->piVars;
86
        // action add to basket
87
        if (!empty($this->piVars['id'])
88
            && $this->piVars['addToBasket']) {
89
            $returnData = $this->addToBasket($this->piVars, $basketData);
90
            $basketData = $returnData['basketData'];
91
            $markerArray['###JS###'] = $returnData['jsOutput'];
92
        } else {
93
            $basketData['doc_ids'] = json_decode($basketData['doc_ids']);
94
        }
95
        // action remove from basket
96
        if ($this->piVars['basket_action'] == 'remove') {
97
            // remove entry from list
98
            unset($piVars['basket_action']);
99
            if (isset($this->piVars['selected'])) {
100
                $basketData = $this->removeFromBasket($piVars, $basketData);
101
            }
102
        }
103
        // action remove from basket
104
        if ($this->piVars['basket_action'] == 'open') {
105
            // open selected documents
106
            unset($piVars['basket_action']);
107
            if (isset($this->piVars['selected'])) {
108
                $basketData = $this->openFromBasket($piVars, $basketData);
109
            }
110
        }
111
        // action print from basket
112
        if ($this->piVars['print_action']) {
113
            // open selected documents
114
            unset($piVars['print_action']);
115
            if (isset($this->piVars['selected'])) {
116
                $basketData = $this->printDocument($piVars, $basketData);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $basketData is correct as $this->printDocument($piVars, $basketData) targeting Kitodo\Dlf\Plugins\Basket::printDocument() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Unused Code introduced by
The call to Kitodo\Dlf\Plugins\Basket::printDocument() has too many arguments starting with $piVars. ( Ignorable by Annotation )

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

116
                /** @scrutinizer ignore-call */ 
117
                $basketData = $this->printDocument($piVars, $basketData);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
117
            }
118
        }
119
        // action send mail
120
        if ($this->piVars['mail_action']) {
121
            if (isset($this->piVars['selected'])) {
122
                $this->sendMail($this->piVars);
0 ignored issues
show
Unused Code introduced by
The call to Kitodo\Dlf\Plugins\Basket::sendMail() has too many arguments starting with $this->piVars. ( Ignorable by Annotation )

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

122
                $this->/** @scrutinizer ignore-call */ 
123
                       sendMail($this->piVars);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
123
            }
124
        }
125
        // set marker
126
        $markerArray['###ACTION###'] = $this->pi_getPageLink($GLOBALS['TSFE']->id);
127
        $markerArray['###LISTTITLE###'] = $this->pi_getLL('basket', '', TRUE);
128
        if ($basketData['doc_ids']) {
129
            if (is_object($basketData['doc_ids'])) {
130
                $basketData['doc_ids'] = get_object_vars($basketData['doc_ids']);
131
            }
132
            $markerArray['###COUNT###'] = sprintf($this->pi_getLL('count'), count($basketData['doc_ids']));
133
        } else {
134
            $markerArray['###COUNT###'] = sprintf($this->pi_getLL('count'), 0);
135
        }
136
        // get mail addresses
137
        $resultMail = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
138
            '*',
139
            'tx_dlf_mail',
140
            '1=1'
141
                .Helper::whereClause('tx_dlf_mail'),
142
            '',
143
            'tx_dlf_mail.sorting',
144
            ''
145
        );
146
        if ($GLOBALS['TYPO3_DB']->sql_num_rows($resultMail) > 0) {
147
            $mailForm = '<select name="tx_dlf[mail_action]">';
148
            $mailForm .= '<option value="">'.$this->pi_getLL('chooseMail', '', TRUE).'</option>';
149
            while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($resultMail)) {
150
                $mailForm .= '<option value="'.$row['uid'].'">'.$row['name'].' ('.$row['mail'].')</option>';
151
            }
152
            $mailForm .= '</select><input type="submit">';
153
        }
154
        // mail action form
155
        $markerArray['###MAILACTION###'] = $mailForm;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $mailForm does not seem to be defined for all execution paths leading up to this point.
Loading history...
156
        // remove action form
157
        $markerArray['###REMOVEACTION###'] = '
158
   <select name="tx_dlf[basket_action]">
159
    <option value="">'.$this->pi_getLL('chooseAction', '', TRUE).'</option>
160
    <option value="open">'.$this->pi_getLL('download', '', TRUE).'</option>
161
    <option value="remove">'.$this->pi_getLL('remove', '', TRUE).'</option>
162
   </select>
163
   <input type="submit">
164
  ';
165
        // get mail addresses
166
        $resultPrinter = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
167
            '*',
168
            'tx_dlf_printer',
169
            '1=1'
170
                .Helper::whereClause('tx_dlf_printer'),
171
            '',
172
            '',
173
            ''
174
        );
175
        $printForm = '';
176
        if ($GLOBALS['TYPO3_DB']->sql_num_rows($resultPrinter) > 0) {
177
            $printForm = '<select name="tx_dlf[print_action]">';
178
            $printForm .= '<option value="">'.$this->pi_getLL('choosePrinter', '', TRUE).'</option>';
179
            while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($resultPrinter)) {
180
                $printForm .= '<option value="'.$row['uid'].'">'.$row['label'].'</option>';
181
            }
182
            $printForm .= '</select><input type="submit" />';
183
        }
184
        // print action form
185
        $markerArray['###PRINTACTION###'] = $printForm;
186
        $entries = '';
187
        if (isset($basketData['doc_ids'])) {
188
            // get each entry
189
            foreach ($basketData['doc_ids'] as $value) {
190
                $entries .= $this->getEntry($value, $subpartArray);
191
            }
192
        } else {
193
            $entries = '';
194
        }
195
        // basket go to
196
        if ($this->conf['targetBasket'] && $this->conf['basketGoToButton'] && $this->piVars['id']) {
197
            $label = $this->pi_getLL('goBasket', '', TRUE);
198
            $basketConf = [
199
                'parameter' => $this->conf['targetBasket'],
200
                'title' => $label
201
            ];
202
            $markerArray['###BASKET###'] = $this->cObj->typoLink($label, $basketConf);
203
        } else {
204
            $markerArray['###BASKET###'] = '';
205
        }
206
        $content = $this->cObj->substituteMarkerArray($this->cObj->substituteSubpart($this->template, '###ENTRY###', $entries, TRUE), $markerArray);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Conte...substituteMarkerArray() has been deprecated: since TYPO3 v8, will be removed in TYPO3 v9, please use the MarkerBasedTemplateService instead. ( Ignorable by Annotation )

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

206
        $content = /** @scrutinizer ignore-deprecated */ $this->cObj->substituteMarkerArray($this->cObj->substituteSubpart($this->template, '###ENTRY###', $entries, TRUE), $markerArray);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Conte...er::substituteSubpart() has been deprecated: since TYPO3 v8, will be removed in TYPO3 v9, please use the MarkerBasedTemplateService instead. ( Ignorable by Annotation )

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

206
        $content = $this->cObj->substituteMarkerArray(/** @scrutinizer ignore-deprecated */ $this->cObj->substituteSubpart($this->template, '###ENTRY###', $entries, TRUE), $markerArray);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
207
        return $this->pi_wrapInBaseClass($content);
208
    }
209
210
    /**
211
     * Return one basket entry
212
     *
213
     * @access protected
214
     *
215
     * @param array $data: DocumentData
216
     * @param array $template: Template information
217
     *
218
     * @return string One basket entry
219
     */
220
    protected function getEntry($data, $template) {
221
        if (is_object($data)) {
222
            $data = get_object_vars($data);
223
        }
224
        $id = $data['id'];
225
        $startpage = $data['startpage'];
226
        $endpage = $data['endpage'];
227
        $startX = $data['startX'];
228
        $startY = $data['startY'];
229
        $endX = $data['endX'];
230
        $endY = $data['endY'];
231
        $rotation = $data['rotation'];
232
        $docData = $this->getDocumentData($id, $data);
233
        $markerArray['###BASKETDATA###'] = $docData['downloadLink'];
1 ignored issue
show
Comprehensibility Best Practice introduced by
$markerArray was never initialized. Although not strictly required by PHP, it is generally a good practice to add $markerArray = array(); before regardless.
Loading history...
234
        $arrayKey = $id.'_'.$startpage;
235
        if (isset($startX)) {
236
            $arrayKey .= '_'.$startX;
237
        }
238
        if (isset($endX)) {
239
            $arrayKey .= '_'.$endX;
240
        }
241
        $controlMark = '<input value="'.$id.'" name="tx_dlf[selected]['.$arrayKey.'][id]" type="checkbox">';
242
        $controlMark .= '<input value="'.$startpage.'" name="tx_dlf[selected]['.$arrayKey.'][startpage]" type="hidden">';
243
        $controlMark .= '<input value="'.$endpage.'" name="tx_dlf[selected]['.$arrayKey.'][endpage]" type="hidden">';
244
        // add hidden fields for detail information
245
        if ($startX) {
246
            $controlMark .= '<input type="hidden" name="tx_dlf[selected]['.$arrayKey.'][startX]" value="'.$startX.'">';
247
            $controlMark .= '<input type="hidden" name="tx_dlf[selected]['.$arrayKey.'][startY]"  value="'.$startY.'">';
248
            $controlMark .= '<input type="hidden" name="tx_dlf[selected]['.$arrayKey.'][endX]"  value="'.$endX.'">';
249
            $controlMark .= '<input type="hidden" name="tx_dlf[selected]['.$arrayKey.'][endY]"  value="'.$endY.'">';
250
            $controlMark .= '<input type="hidden" name="tx_dlf[selected]['.$arrayKey.'][rotation]"  value="'.$rotation.'">';
251
        }
252
        // return one entry
253
        $markerArray['###CONTROLS###'] = $controlMark;
254
        $markerArray['###NUMBER###'] = $docData['record_id'];
255
        return $this->cObj->substituteMarkerArray($this->cObj->substituteSubpart($template['entry'], '###ENTRY###', '', TRUE), $markerArray);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Conte...er::substituteSubpart() has been deprecated: since TYPO3 v8, will be removed in TYPO3 v9, please use the MarkerBasedTemplateService instead. ( Ignorable by Annotation )

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

255
        return $this->cObj->substituteMarkerArray(/** @scrutinizer ignore-deprecated */ $this->cObj->substituteSubpart($template['entry'], '###ENTRY###', '', TRUE), $markerArray);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Conte...substituteMarkerArray() has been deprecated: since TYPO3 v8, will be removed in TYPO3 v9, please use the MarkerBasedTemplateService instead. ( Ignorable by Annotation )

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

255
        return /** @scrutinizer ignore-deprecated */ $this->cObj->substituteMarkerArray($this->cObj->substituteSubpart($template['entry'], '###ENTRY###', '', TRUE), $markerArray);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
256
    }
257
258
    /**
259
     * Adds documents to the basket
260
     *
261
     * @access protected
262
     *
263
     * @param array $_piVars: piVars
264
     * @param array $basketData: basket data
265
     *
266
     * @return array Basket data and Javascript output
267
     */
268
    protected function addToBasket($_piVars, $basketData) {
269
        $output = '';
270
        if (!$_piVars['startpage']) {
271
            $page = 0;
272
        } else {
273
            $page = intval($_piVars['startpage']);
274
        }
275
        if ($page != NULL || $_piVars['addToBasket'] == 'list') {
276
            $documentItem = [
277
                'id' => intval($_piVars['id']),
278
                'startpage' => intval($_piVars['startpage']),
279
                'endpage' => !isset($_piVars['endpage']) || $_piVars['endpage'] === "" ? "" : intval($_piVars['endpage']),
280
                'startX' => !isset($_piVars['startX']) || $_piVars['startX'] === "" ? "" : intval($_piVars['startX']),
281
                'startY' => !isset($_piVars['startY']) || $_piVars['startY'] === "" ? "" : intval($_piVars['startY']),
282
                'endX' => !isset($_piVars['endX']) || $_piVars['endX'] === "" ? "" : intval($_piVars['endX']),
283
                'endY' => !isset($_piVars['endY']) || $_piVars['endY'] === "" ? "" : intval($_piVars['endY']),
284
                'rotation' => !isset($_piVars['rotation']) || $_piVars['rotation'] === "" ? "" : intval($_piVars['rotation'])
285
            ];
286
            // update basket
287
            if (!empty($basketData['doc_ids'])) {
288
                $items = json_decode($basketData['doc_ids']);
289
                $items = get_object_vars($items);
290
            } else {
291
                $items = [];
292
            }
293
            // get document instance to load further information
294
            $document = Document::getInstance($documentItem['id'], 0);
295
            // set endpage for toc and subentry based on logid
296
            if (($_piVars['addToBasket'] == 'subentry') or ($_piVars['addToBasket'] == 'toc')) {
297
                $smLinks = $document->smLinks;
0 ignored issues
show
Bug Best Practice introduced by
The property $smLinks is declared protected in Kitodo\Dlf\Common\Document. Since you implement __get, consider adding a @property or @property-read.
Loading history...
298
                $pageCounter = sizeof($smLinks['l2p'][$_piVars['logId']]);
299
                $documentItem['endpage'] = ($documentItem['startpage'] + $pageCounter) - 1;
300
            }
301
            // add whole document
302
            if ($_piVars['addToBasket'] == 'list') {
303
                $documentItem['endpage'] = $document->numPages;
0 ignored issues
show
Bug Best Practice introduced by
The property $numPages is declared protected in Kitodo\Dlf\Common\Document. Since you implement __get, consider adding a @property or @property-read.
Loading history...
304
            }
305
            $arrayKey = $documentItem['id'].'_'.$page;
306
            if (!empty($documentItem['startX'])) {
307
                $arrayKey .= '_'.$documentItem['startX'];
308
            }
309
            if (!empty($documentItem['endX'])) {
310
                $arrayKey .= '_'.$documentItem['endX'];
311
            }
312
            // do not add more than one identical object
313
            if (!in_array($arrayKey, $items)) {
314
                $items[$arrayKey] = $documentItem;
315
                // replace url param placeholder
316
                $pdfParams = str_replace("##startpage##", $documentItem['startpage'], $this->conf['pdfparams']);
317
                $pdfParams = str_replace("##docId##", $document->recordId, $pdfParams);
0 ignored issues
show
Bug Best Practice introduced by
The property $recordId is declared protected in Kitodo\Dlf\Common\Document. Since you implement __get, consider adding a @property or @property-read.
Loading history...
318
                $pdfParams = str_replace("##startx##", $documentItem['startX'], $pdfParams);
319
                $pdfParams = str_replace("##starty##", $documentItem['startY'], $pdfParams);
320
                $pdfParams = str_replace("##endx##", $documentItem['endX'], $pdfParams);
321
                $pdfParams = str_replace("##endy##", $documentItem['endY'], $pdfParams);
322
                $pdfParams = str_replace("##rotation##", $documentItem['rotation'], $pdfParams);
323
                if ($documentItem['startpage'] != $documentItem['endpage']) {
324
                    $pdfParams = str_replace("##endpage##", $documentItem['endpage'], $pdfParams);
325
                } else {
326
                    // remove parameter endpage
327
                    $pdfParams = str_replace(",##endpage##", '', $pdfParams);
328
                }
329
                $pdfGenerateUrl = $this->conf['pdfgenerate'].$pdfParams;
330
                if ($this->conf['pregeneration']) {
331
                    // send ajax request to webapp
332
                    $output .= '
333
     <script>
334
      $(document).ready(function(){
335
       $.ajax({
336
         url: "'.$pdfGenerateUrl.'",
337
       }).done(function() {
338
       });
339
      });
340
     </script>';
341
                }
342
            }
343
            $update = ['doc_ids' => json_encode($items)];
344
            $GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_dlf_basket', 'uid='.intval($basketData['uid']), $update);
345
            $basketData['doc_ids'] = $items;
346
        }
347
        return ['basketData' => $basketData, 'jsOutput' => $output];
348
    }
349
350
    /**
351
     * Removes selected documents from basket
352
     *
353
     * @access protected
354
     *
355
     * @param array $_piVars: plugin variables
356
     * @param array $basketData: array with document information
357
     *
358
     * @return array basket data
359
     */
360
    protected function removeFromBasket($_piVars, $basketData) {
361
        if (!empty($basketData['doc_ids'])) {
362
            $items = $basketData['doc_ids'];
363
            $items = get_object_vars($items);
364
        }
365
        foreach ($_piVars['selected'] as $value) {
366
            if (isset($value['id'])) {
367
                $arrayKey = $value['id'].'_'.$value['startpage'];
368
                if (isset($value['startX'])) {
369
                    $arrayKey .= '_'.$value['startX'];
370
                }
371
                if (isset($value['endX'])) {
372
                    $arrayKey .= '_'.$value['endX'];
373
                }
374
                if (isset($items[$arrayKey])) {
375
                    unset($items[$arrayKey]);
376
                }
377
            }
378
        }
379
        if (empty($items)) {
380
            $update = ['doc_ids' => ''];
381
        } else {
382
            $update = ['doc_ids' => json_encode($items)];
383
        }
384
        $GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_dlf_basket', 'uid='.intval($basketData['uid']), $update);
385
        $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...
386
        return $basketData;
387
    }
388
389
    /**
390
     * Open selected documents from basket
391
     *
392
     * @access protected
393
     *
394
     * @param array $_piVars: plugin variables
395
     * @param array $basketData: array with document information
396
     *
397
     * @return array basket data
398
     */
399
    protected function openFromBasket($_piVars, $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

399
    protected function openFromBasket($_piVars, /** @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...
Unused Code introduced by
The parameter $_piVars 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

399
    protected function openFromBasket(/** @scrutinizer ignore-unused */ $_piVars, $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...
400
        $pdfUrl = $this->conf['pdfgenerate'];
401
        foreach ($this->piVars['selected'] as $docValue) {
402
            if ($docValue['id']) {
403
                $docData = $this->getDocumentData($docValue['id'], $docValue);
404
                $pdfUrl .= $docData['urlParams'].$this->conf['pdfparamseparator'];
405
            }
406
        }
407
        header('Location: '.$pdfUrl);
408
        ob_end_flush();
409
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
410
    }
411
412
    /**
413
     * Returns the downloadurl configured in the basket
414
     *
415
     * @access protected
416
     *
417
     * @param integer $id: Document id
418
     *
419
     * @return mixed download url or false
420
     */
421
    protected function getDocumentData($id, $data) {
422
        // get document instance to load further information
423
        $document = Document::getInstance($id, 0);
424
        if ($document) {
0 ignored issues
show
introduced by
$document is of type Kitodo\Dlf\Common\Document, thus it always evaluated to true.
Loading history...
425
            // replace url param placeholder
426
            $urlParams = str_replace("##page##", intval($data['page']), $this->conf['pdfparams']);
427
            $urlParams = str_replace("##docId##", $document->recordId, $urlParams);
0 ignored issues
show
Bug Best Practice introduced by
The property $recordId is declared protected in Kitodo\Dlf\Common\Document. Since you implement __get, consider adding a @property or @property-read.
Loading history...
428
            $urlParams = str_replace("##startpage##", intval($data['startpage']), $urlParams);
429
            if ($data['startpage'] != $data['endpage']) {
430
                $urlParams = str_replace("##endpage##", $data['endpage'] === "" ? "" : intval($data['endpage']), $urlParams);
431
            } else {
432
                // remove parameter endpage
433
                $urlParams = str_replace(",##endpage##", '', $urlParams);
434
            }
435
            $urlParams = str_replace("##startx##", $data['startX'] === "" ? "" : intval($data['startX']), $urlParams);
436
            $urlParams = str_replace("##starty##", $data['startY'] === "" ? "" : intval($data['startY']), $urlParams);
437
            $urlParams = str_replace("##endx##", $data['endX'] === "" ? "" : intval($data['endX']), $urlParams);
438
            $urlParams = str_replace("##endy##", $data['endY'] === "" ? "" : intval($data['endY']), $urlParams);
439
            $urlParams = str_replace("##rotation##", $data['rotation'] === "" ? "" : intval($data['rotation']), $urlParams);
440
            $downloadUrl = $this->conf['pdfgenerate'].$urlParams;
441
            $title = $document->getTitle($id, TRUE);
442
            if (empty($title)) {
443
                $title = $this->pi_getLL('noTitle', '', TRUE);
444
            }
445
            // Set page and cutout information
446
            $info = '';
447
            if ($data['startX'] != '' && $data['endX'] != '') {
448
                // cutout
449
                $info .= $this->pi_getLL('cutout', '', TRUE).' ';
450
            }
451
            if ($data['startpage'] == $data['endpage']) {
452
                // One page
453
                $info .= $this->pi_getLL('page', '', TRUE).' '.$data['startpage'];
454
            } else {
455
                $info .= $this->pi_getLL('page', '', TRUE).' '.$data['startpage'].'-'.$data['endpage'];
456
            }
457
            $downloadLink = '<a href="'.$downloadUrl.'" target="_blank">'.$title.'</a> ('.$info.')';
458
            if ($data['startpage'] == $data['endpage']) {
459
                $pageNums = 1;
460
            } else {
461
                $pageNums = $data['endpage'] - $data['startpage'];
462
            }
463
            return [
464
                'downloadUrl' => $downloadUrl,
465
                'downloadLink' => $downloadLink,
466
                'pageNums' => $pageNums,
467
                'urlParams' => $urlParams,
468
                'record_id' => $document->recordId,
469
            ];
470
        }
471
        return FALSE;
472
    }
473
474
    /**
475
     * Send mail with pdf download url
476
     *
477
     * @access protected
478
     *
479
     * @return void
480
     */
481
    protected function sendMail() {
482
        // send mail
483
        $mailId = $this->piVars['mail_action'];
484
        // get id from db and send selected doc downloadlink
485
        $resultMail = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
486
            '*',
487
            'tx_dlf_mail',
488
            'tx_dlf_mail.uid='.intval($mailId)
489
                .Helper::whereClause('tx_dlf_mail'),
490
            '',
491
            '',
492
            '1'
493
        );
494
        $mailData = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($resultMail);
495
        $mailText = $this->pi_getLL('mailBody', '', TRUE)."\n";
496
        $numberOfPages = 0;
497
        $pdfUrl = $this->conf['pdfdownload'];
498
        // prepare links
499
        foreach ($this->piVars['selected'] as $docValue) {
500
            if ($docValue['id']) {
501
                $explodeId = explode("_", $docValue['id']);
502
                $docData = $this->getDocumentData($explodeId[0], $docValue);
503
                $pdfUrl .= $docData['urlParams'].$this->conf['pdfparamseparator'];
504
                $pages = (abs(intval($docValue['startpage']) - intval($docValue['endpage'])));
505
                if ($pages === 0) {
506
                    $numberOfPages = $numberOfPages + 1;
507
                } else {
508
                    $numberOfPages = $numberOfPages + $pages;
509
                }
510
            }
511
        }
512
        // Remove leading/tailing pdfparamseperator
513
        $pdfUrl = trim($pdfUrl, $this->conf['pdfparamseparator']);
514
        $mailBody = $mailText.$pdfUrl;
515
        // Get hook objects.
516
        $hookObjects = Helper::getHookObjects($this->scriptRelPath);
517
        // Hook for getting a customized mail body.
518
        foreach ($hookObjects as $hookObj) {
519
            if (method_exists($hookObj, 'customizeMailBody')) {
520
                $mailBody = $hookObj->customizeMailBody($mailText, $pdfUrl);
521
            }
522
        }
523
        $from = \TYPO3\CMS\Core\Utility\MailUtility::getSystemFrom();
524
        // send mail
525
        $mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
526
        // Prepare and send the message
527
        $mail
528
            // subject
529
            ->setSubject($this->pi_getLL('mailSubject', '', TRUE))
530
            // Set the From address with an associative array
531
            ->setFrom($from)
532
            // Set the To addresses with an associative array
533
            ->setTo([$mailData['mail'] => $mailData['name']])
534
            ->setBody($mailBody, 'text/html')
535
            ->send();
536
        // protocol
537
        $insertArray = [
538
            'pid' => $this->conf['pages'],
539
            'file_name' => $pdfUrl,
540
            'count_pages' => $numberOfPages,
541
            'crdate' => time(),
542
        ];
543
        if ($GLOBALS["TSFE"]->loginUser) {
544
            // internal user
545
            $insertArray['user_id'] = $GLOBALS["TSFE"]->fe_user->user['uid'];
546
            $insertArray['name'] = $GLOBALS["TSFE"]->fe_user->user['username'];
547
            $insertArray['label'] = 'Mail: '.$mailData['mail'];
548
        } else {
549
            // external user
550
            $insertArray['user_id'] = 0;
551
            $insertArray['name'] = 'n/a';
552
            $insertArray['label'] = 'Mail: '.$mailData['mail'];
553
        }
554
        // add action to protocol
555
        $GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_dlf_actionlog', $insertArray);
556
    }
557
558
    /**
559
     * Sends document information to an external printer (url)
560
     *
561
     * @access protected
562
     *
563
     * @return void
564
     */
565
    protected function printDocument() {
566
        $pdfUrl = $this->conf['pdfprint'];
567
        $numberOfPages = 0;
568
        foreach ($this->piVars['selected'] as $docId => $docValue) {
569
            if ($docValue['id']) {
570
                $docData = $this->getDocumentData($docValue['id'], $docValue);
571
                $pdfUrl .= $docData['urlParams'].$this->conf['pdfparamseparator'];
572
                $numberOfPages += $docData['pageNums'];
573
            }
574
        }
575
        // get printer data
576
        $printerId = $this->piVars['print_action'];
577
        // get id from db and send selected doc downloadlink
578
        $resultPrinter = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
579
            '*',
580
            'tx_dlf_printer',
581
            'tx_dlf_printer.uid='.intval($printerId)
582
                .Helper::whereClause('tx_dlf_basket'),
583
            '',
584
            '',
585
            '1'
586
        );
587
        $printerData = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($resultPrinter);
588
        // printer is selected
589
        if ($printerData) {
590
            $pdfUrl = $printerData['print'];
591
            $numberOfPages = 0;
592
            foreach ($this->piVars['selected'] as $docId => $docValue) {
593
                if ($docValue['id']) {
594
                    $explodeId = explode("_", $docId);
595
                    $docData = $this->getDocumentData($explodeId[0], $docValue);
596
                    $pdfUrl .= $docData['urlParams'].$this->conf['pdfparamseparator'];
597
                    $numberOfPages += $docData['pageNums'];
598
                }
599
            }
600
            $pdfUrl = trim($pdfUrl, $this->conf['pdfparamseparator']);
601
        }
602
        // protocol
603
        $insertArray = [
604
            'pid' => $this->conf['pages'],
605
            'file_name' => $pdfUrl,
606
            'count_pages' => $numberOfPages,
607
            'crdate' => time(),
608
        ];
609
        if ($GLOBALS["TSFE"]->loginUser) {
610
            // internal user
611
            $insertArray['user_id'] = $GLOBALS["TSFE"]->fe_user->user['uid'];
612
            $insertArray['name'] = $GLOBALS["TSFE"]->fe_user->user['username'];
613
            $insertArray['label'] = 'Print: '.$printerData['label'];
614
        } else {
615
            // external user
616
            $insertArray['user_id'] = 0;
617
            $insertArray['name'] = 'n/a';
618
            $insertArray['label'] = 'Print: '.$printerData['label'];
619
        }
620
        // add action to protocol
621
        $GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_dlf_actionlog', $insertArray);
622
        header('Location: '.$pdfUrl);
623
        ob_end_flush();
624
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
625
    }
626
}
627