tx_dlf_helper::loadFromSession()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 38
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 14
nc 6
nop 1
dl 0
loc 38
rs 8.439
c 0
b 0
f 0
1
<?php
2
/**
3
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
4
 *
5
 * This file is part of the Kitodo and TYPO3 projects.
6
 *
7
 * @license GNU General Public License version 3 or later.
8
 * For the full copyright and license information, please read the
9
 * LICENSE.txt file that was distributed with this source code.
10
 */
11
12
/**
13
 * Helper class 'tx_dlf_helper' for the 'dlf' extension.
14
 *
15
 * @author	Sebastian Meyer <[email protected]>
16
 * @author	Henrik Lochmann <[email protected]>
17
 * @package	TYPO3
18
 * @subpackage	tx_dlf
19
 * @access	public
20
 */
21
class tx_dlf_helper {
22
23
    /**
24
     * The extension key
25
     *
26
     * @var	string
27
     * @access public
28
     */
29
    public static $extKey = 'dlf';
30
31
    /**
32
     * The locallang array for common use
33
     *
34
     * @var	array
35
     * @access protected
36
     */
37
    protected static $locallang = array ();
38
39
    /**
40
     * Adds a message to the message queue.
41
     *
42
     * @access	public
43
     *
44
     * @param	\TYPO3\CMS\Core\Messaging\FlashMessage		$message: Instance of \TYPO3\CMS\Core\Messaging\FlashMessage
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Core\Messaging\FlashMessage was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
45
     *
46
     * @return	void
47
     */
48
    public static function addMessage($message) {
49
50
        $flashMessageService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessageService');
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Core\Utility\GeneralUtility was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
51
52
        $flashMessageService->getMessageQueueByIdentifier()->enqueue($message);
53
54
    }
55
56
    /**
57
     * Implements array_merge_recursive_overrule() in a cross-version way
58
     * This code is a copy from realurl, written by Dmitry Dulepov <[email protected]>.
59
     *
60
     * @access	public
61
     *
62
     * @param	array		$array1: First array
63
     * @param	array		$array2: Second array
64
     *
65
     * @return	array		Merged array with second array overruling first one
66
     */
67
    static public function array_merge_recursive_overrule($array1, $array2) {
68
69
        if (class_exists('\\TYPO3\\CMS\\Core\\Utility\\ArrayUtility')) {
70
71
            \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($array1, $array2);
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Core\Utility\ArrayUtility was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
72
73
        } else {
74
75
            $array1 = \TYPO3\CMS\Core\Utility\GeneralUtility::array_merge_recursive_overrule($array1, $array2);
76
77
        }
78
79
        return $array1;
80
81
    }
82
83
    /**
84
     * Searches the array recursively for a given value and returns the corresponding key if successful
85
     * @see http://php.net/array_search
86
     *
87
     * @access	public
88
     *
89
     * @param	mixed		$needle: The searched value
90
     * @param	array		$haystack: The array to search in
91
     * @param	boolean		$strict: Check needle's type, too?
92
     *
93
     * @return	mixed		Returns the needle's key if found and FALSE otherwise
94
     *
95
     * @deprecated because of its inefficiency
96
     */
97
    public static function array_search_recursive($needle, $haystack, $strict = FALSE) {
98
99
        foreach ($haystack as $key => $value) {
100
101
            if (($strict && $value === $needle) || (!$strict && $value == $needle) || (is_array($value) && self::array_search_recursive($needle, $value, $strict) !== FALSE)) {
0 ignored issues
show
Deprecated Code introduced by
The function tx_dlf_helper::array_search_recursive() has been deprecated: because of its inefficiency ( Ignorable by Annotation )

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

101
            if (($strict && $value === $needle) || (!$strict && $value == $needle) || (is_array($value) && /** @scrutinizer ignore-deprecated */ self::array_search_recursive($needle, $value, $strict) !== FALSE)) {

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...
102
103
                return $key;
104
105
            }
106
107
        }
108
109
        return FALSE;
110
111
    }
112
113
    /**
114
     * Check if given identifier is a valid identifier of the German National Library
115
     * @see	http://support.d-nb.de/iltis/onlineRoutinen/Pruefziffernberechnung.htm
116
     *
117
     * @access	public
118
     *
119
     * @param	string		$id: The identifier to check
120
     * @param	string		$type: What type is the identifier supposed to be?
121
     * 						Possible values: PPN, IDN, PND, ZDB, SWD, GKD
122
     *
123
     * @return	boolean		Is $id a valid GNL identifier of the given $type?
124
     */
125
    public static function checkIdentifier($id, $type) {
126
127
        $digits = substr($id, 0, 8);
128
129
        $checksum = 0;
130
131
        for ($i = 0, $j = strlen($digits); $i < $j; $i++) {
132
133
            $checksum += (9 - $i) * intval(substr($digits, $i, 1));
134
135
        }
136
137
        $checksum = (11 - ($checksum % 11)) % 11;
138
139
        switch (strtoupper($type)) {
140
141
            case 'PPN':
142
            case 'IDN':
143
            case 'PND':
144
145
                if ($checksum == 10) {
146
147
                    $checksum = 'X';
148
149
                }
150
151
                if (!preg_match('/[0-9]{8}[0-9X]{1}/i', $id)) {
152
153
                    return FALSE;
154
155
                } elseif (strtoupper(substr($id, -1, 1)) != $checksum) {
156
157
                    return FALSE;
158
159
                }
160
161
                break;
162
163
            case 'ZDB':
164
165
                if ($checksum == 10) {
166
167
                    $checksum = 'X';
168
169
                }
170
171
                if (!preg_match('/[0-9]{8}-[0-9X]{1}/i', $id)) {
172
173
                    return FALSE;
174
175
                } elseif (strtoupper(substr($id, -1, 1)) != $checksum) {
176
177
                    return FALSE;
178
179
                }
180
181
                break;
182
183
            case 'SWD':
184
185
                $checksum = 11 - $checksum;
186
187
                if (!preg_match('/[0-9]{8}-[0-9]{1}/i', $id)) {
188
189
                    return FALSE;
190
191
                } elseif ($checksum == 10) {
192
193
                    return self::checkIdentifier(($digits + 1).substr($id, -2, 2), 'SWD');
194
195
                } elseif (substr($id, -1, 1) != $checksum) {
196
197
                    return FALSE;
198
199
                }
200
201
                break;
202
203
            case 'GKD':
204
205
                $checksum = 11 - $checksum;
206
207
                if ($checksum == 10) {
208
209
                    $checksum = 'X';
210
211
                }
212
213
                if (!preg_match('/[0-9]{8}-[0-9X]{1}/i', $id)) {
214
215
                    return FALSE;
216
217
                } elseif (strtoupper(substr($id, -1, 1)) != $checksum) {
218
219
                    return FALSE;
220
221
                }
222
223
                break;
224
225
        }
226
227
        return TRUE;
228
229
    }
230
231
    /**
232
     * Decrypt encrypted value with given control hash
233
     * @see http://yavkata.co.uk/weblog/php/securing-html-hidden-input-fields-using-encryption-and-hashing/
234
     *
235
     * @access	public
236
     *
237
     * @param	string		$encrypted: The encrypted value to decrypt
238
     * @param	string		$hash: The control hash for decrypting
239
     *
240
     * @return	mixed		The decrypted value or NULL on error
241
     */
242
    public static function decrypt($encrypted, $hash) {
243
244
        $decrypted = NULL;
0 ignored issues
show
Unused Code introduced by
The assignment to $decrypted is dead and can be removed.
Loading history...
245
246
        // Check for PHP extension "mcrypt".
247
        if (!extension_loaded('mcrypt')) {
248
249
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
250
251
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->decrypt('.$encrypted.', '.$hash.')] PHP extension "mcrypt" not available', self::$extKey, SYSLOG_SEVERITY_WARNING);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_WARNING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
252
253
            }
254
255
            return;
256
257
        }
258
259
        if (empty($encrypted) || empty($hash)) {
260
261
            if (TYPO3_DLOG) {
262
263
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->decrypt('.$encrypted.', '.$hash.')] Invalid parameters given for decryption', self::$extKey, SYSLOG_SEVERITY_ERROR);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_ERROR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
264
265
            }
266
267
            return;
268
269
        }
270
271
        if (empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])) {
272
273
            if (TYPO3_DLOG) {
274
275
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->decrypt('.$encrypted.', '.$hash.')] No encryption key set in TYPO3 configuration', self::$extKey, SYSLOG_SEVERITY_ERROR);
276
277
            }
278
279
            return;
280
281
        }
282
283
        $iv = substr(md5($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']), 0, mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CFB));
0 ignored issues
show
Deprecated Code introduced by
The function mcrypt_get_iv_size() has been deprecated: 7.1 ( Ignorable by Annotation )

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

283
        $iv = substr(md5($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']), 0, /** @scrutinizer ignore-deprecated */ mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CFB));

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...
284
285
        $decrypted = mcrypt_decrypt(MCRYPT_BLOWFISH, substr($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'], 0, 56), base64_decode($encrypted), MCRYPT_MODE_CFB, $iv);
0 ignored issues
show
Deprecated Code introduced by
The function mcrypt_decrypt() has been deprecated: 7.1 ( Ignorable by Annotation )

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

285
        $decrypted = /** @scrutinizer ignore-deprecated */ mcrypt_decrypt(MCRYPT_BLOWFISH, substr($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'], 0, 56), base64_decode($encrypted), MCRYPT_MODE_CFB, $iv);

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...
286
287
        $salt = substr($hash, 0, 10);
288
289
        $hashed = $salt.substr(sha1($salt.$decrypted), -10);
290
291
        if ($hashed !== $hash) {
292
293
            if (TYPO3_DLOG) {
294
295
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->decrypt('.$encrypted.', '.$hash.')] Invalid hash "'.$hash.'" given for decryption', self::$extKey, SYSLOG_SEVERITY_WARNING);
296
297
            }
298
299
            return;
300
301
        }
302
303
        return $decrypted;
304
305
    }
306
307
    /**
308
     * Encrypt the given string
309
     * @see http://yavkata.co.uk/weblog/php/securing-html-hidden-input-fields-using-encryption-and-hashing/
310
     *
311
     * @access	public
312
     *
313
     * @param	string		$string: The string to encrypt
314
     *
315
     * @return	array		Array with encrypted string and control hash
316
     */
317
    public static function encrypt($string) {
318
319
        // Check for PHP extension "mcrypt".
320
        if (!extension_loaded('mcrypt')) {
321
322
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
323
324
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->encrypt('.$string.')] PHP extension "mcrypt" not available', self::$extKey, SYSLOG_SEVERITY_WARNING);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_WARNING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
325
326
            }
327
328
            return;
329
330
        }
331
332
        if (empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])) {
333
334
            if (TYPO3_DLOG) {
335
336
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->encrypt('.$string.')] No encryption key set in TYPO3 configuration', self::$extKey, SYSLOG_SEVERITY_ERROR);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_ERROR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
337
338
            }
339
340
            return;
341
342
        }
343
344
        $iv = substr(md5($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']), 0, mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CFB));
0 ignored issues
show
Deprecated Code introduced by
The function mcrypt_get_iv_size() has been deprecated: 7.1 ( Ignorable by Annotation )

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

344
        $iv = substr(md5($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']), 0, /** @scrutinizer ignore-deprecated */ mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CFB));

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...
345
346
        $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_BLOWFISH, substr($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'], 0, 56), $string, MCRYPT_MODE_CFB, $iv));
0 ignored issues
show
Deprecated Code introduced by
The function mcrypt_encrypt() has been deprecated: 7.1 ( Ignorable by Annotation )

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

346
        $encrypted = base64_encode(/** @scrutinizer ignore-deprecated */ mcrypt_encrypt(MCRYPT_BLOWFISH, substr($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'], 0, 56), $string, MCRYPT_MODE_CFB, $iv));

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...
347
348
        $salt = substr(md5(uniqid(rand(), TRUE)), 0, 10);
0 ignored issues
show
Bug introduced by
The call to rand() has too few arguments starting with min. ( Ignorable by Annotation )

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

348
        $salt = substr(md5(uniqid(/** @scrutinizer ignore-call */ rand(), TRUE)), 0, 10);

This check compares calls to functions or methods with their respective definitions. If the call has less 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...
349
350
        $hash = $salt.substr(sha1($salt.$string), -10);
351
352
        return array ('encrypted' => $encrypted, 'hash' => $hash);
353
354
    }
355
356
    /**
357
     * Get a backend user object (even in frontend mode)
358
     *
359
     * @access	public
360
     *
361
     * @return	\TYPO3\CMS\Core\Authentication\BackendUserAuthentication		Instance of \TYPO3\CMS\Core\Authentication\BackendUserAuthentication or NULL on failure
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Core\Authentic...ckendUserAuthentication was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
362
     */
363
    public static function getBeUser() {
364
365
        if (TYPO3_MODE === 'FE' || TYPO3_MODE === 'BE') {
0 ignored issues
show
Bug introduced by
The constant TYPO3_MODE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
366
367
            // Initialize backend session with CLI user's rights.
368
            $userObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Authentication\\BackendUserAuthentication');
369
370
            $userObj->dontSetCookie = TRUE;
371
372
            $userObj->start();
373
374
            $userObj->setBeUserByName('_cli_dlf');
375
376
            $userObj->backendCheckLogin();
377
378
            return $userObj;
379
380
        } else {
381
382
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
383
384
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->getBeUser()] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_ERROR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
385
386
            }
387
388
            return;
389
390
        }
391
392
    }
393
394
    /**
395
     * Get the current frontend user object
396
     *
397
     * @access	public
398
     *
399
     * @return	\TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication		Instance of \TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication or NULL on failure
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Frontend\Authe...ntendUserAuthentication was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
400
     */
401
    public static function getFeUser() {
402
403
        if (TYPO3_MODE === 'FE') {
0 ignored issues
show
Bug introduced by
The constant TYPO3_MODE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
404
405
            // Check if a user is currently logged in.
406
            if (!empty($GLOBALS['TSFE']->loginUser)) {
407
408
                return $GLOBALS['TSFE']->fe_user;
409
410
            } elseif (\TYPO3\CMS\Core\Utility\GeneralUtility::_GP('eID') !== NULL) {
411
412
                return \TYPO3\CMS\Frontend\Utility\EidUtility::initFeUser();
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Frontend\Utility\EidUtility was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
413
414
            }
415
416
        } else {
417
418
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
419
420
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->getFeUser()] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_ERROR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
421
422
            }
423
424
        }
425
426
        return;
427
428
    }
429
430
    /**
431
     * Get the registered hook objects for a class
432
     *
433
     * @access	public
434
     *
435
     * @param	string		$scriptRelPath: The path to the class file
436
     *
437
     * @return	array		Array of hook objects for the class
438
     */
439
    public static function getHookObjects($scriptRelPath) {
440
441
        $hookObjects = array ();
442
443
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::$extKey.'/'.$scriptRelPath]['hookClass'])) {
444
445
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::$extKey.'/'.$scriptRelPath]['hookClass'] as $classRef) {
446
447
                $hookObjects[] = &\TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($classRef);
448
449
            }
450
451
        }
452
453
        return $hookObjects;
454
455
    }
456
457
    /**
458
     * Get the "index_name" for an UID
459
     *
460
     * @access	public
461
     *
462
     * @param	integer		$uid: The UID of the record
463
     * @param	string		$table: Get the "index_name" from this table
464
     * @param	integer		$pid: Get the "index_name" from this page
465
     *
466
     * @return	string		"index_name" for the given UID
467
     */
468
    public static function getIndexName($uid, $table, $pid = -1) {
469
470
        // Save parameters for logging purposes.
471
        $_uid = $uid;
472
473
        $_pid = $pid;
474
475
        // Sanitize input.
476
        $uid = max(intval($uid), 0);
477
478
        if (!$uid || !in_array($table, array ('tx_dlf_collections', 'tx_dlf_libraries', 'tx_dlf_metadata', 'tx_dlf_structures', 'tx_dlf_solrcores'))) {
479
480
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
481
482
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->getIndexName('.$_uid.', '.$table.', '.$_pid.')] Invalid UID "'.$uid.'" or table "'.$table.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_ERROR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
483
484
            }
485
486
            return '';
487
488
        }
489
490
        $where = '';
491
492
        // Should we check for a specific PID, too?
493
        if ($pid !== -1) {
494
495
            $pid = max(intval($pid), 0);
496
497
            $where = ' AND '.$table.'.pid='.$pid;
498
499
        }
500
501
        // Get index_name from database.
502
        $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
503
            $table.'.index_name AS index_name',
504
            $table,
505
            $table.'.uid='.$uid.$where.self::whereClause($table),
506
            '',
507
            '',
508
            '1'
509
        );
510
511
        if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
512
513
            $resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
514
515
            return $resArray['index_name'];
516
517
        } else {
518
519
            if (TYPO3_DLOG) {
520
521
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->getIndexName('.$_uid.', '.$table.', '.$_pid.')] No "index_name" with UID "'.$uid.'" and PID "'.$pid.'" found in table "'.$table.'"', self::$extKey, SYSLOG_SEVERITY_WARNING);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_WARNING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
522
523
            }
524
525
            return '';
526
527
        }
528
529
    }
530
531
    /**
532
     * Get the UID for a given "index_name"
533
     *
534
     * @access	public
535
     *
536
     * @param	integer		$index_name: The index_name of the record
537
     * @param	string		$table: Get the "index_name" from this table
538
     * @param	integer		$pid: Get the "index_name" from this page
539
     *
540
     * @return	string		"uid" for the given index_name
541
     */
542
    public static function getIdFromIndexName($index_name, $table, $pid = -1) {
543
544
        // Save parameters for logging purposes.
545
        $_index_name = $index_name;
546
547
        $_pid = $pid;
548
549
        if (!$index_name || !in_array($table, array ('tx_dlf_collections', 'tx_dlf_libraries', 'tx_dlf_metadata', 'tx_dlf_structures', 'tx_dlf_solrcores'))) {
550
551
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
552
553
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->getIdFromIndexName('.$_index_name.', '.$table.', '.$_pid.')] Invalid UID "'.$index_name.'" or table "'.$table.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_ERROR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
554
555
            }
556
557
            return '';
558
559
        }
560
561
        $where = '';
562
563
        // Should we check for a specific PID, too?
564
        if ($pid !== -1) {
565
566
            $pid = max(intval($pid), 0);
567
568
            $where = ' AND '.$table.'.pid='.$pid;
569
570
        }
571
572
        // Get index_name from database.
573
        $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
574
            $table.'.uid AS uid',
575
            $table,
576
            $table.'.index_name="'.$index_name.'"'.$where.self::whereClause($table),
577
            '',
578
            '',
579
            '1'
580
        );
581
582
        if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
583
584
            $resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
585
586
            return $resArray['uid'];
587
588
        } else {
589
590
            if (TYPO3_DLOG) {
591
592
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->getIdFromIndexName('.$_index_name.', '.$table.', '.$_pid.')] No UID for given "index_name" "'.$index_name.'" and PID "'.$pid.'" found in table "'.$table.'"', self::$extKey, SYSLOG_SEVERITY_WARNING);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_WARNING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
593
594
            }
595
596
            return '';
597
598
        }
599
600
    }
601
602
    /**
603
     * Get language name from ISO code
604
     *
605
     * @access	public
606
     *
607
     * @param	string		$code: ISO 639-1 or ISO 639-2/B language code
608
     *
609
     * @return	string		Localized full name of language or unchanged input
610
     */
611
    public static function getLanguageName($code) {
612
613
        // Analyze code and set appropriate ISO table.
614
        $isoCode = strtolower(trim($code));
615
616
        if (preg_match('/^[a-z]{3}$/', $isoCode)) {
617
618
            $file = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath(self::$extKey).'lib/ISO-639/iso-639-2b.xml';
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Core\Utility\ExtensionManagementUtility was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
619
620
        } elseif (preg_match('/^[a-z]{2}$/', $isoCode)) {
621
622
            $file = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath(self::$extKey).'lib/ISO-639/iso-639-1.xml';
623
624
        } else {
625
626
            // No ISO code, return unchanged.
627
            return $code;
628
629
        }
630
631
        // Load ISO table and get localized full name of language.
632
        if (TYPO3_MODE === 'FE') {
0 ignored issues
show
Bug introduced by
The constant TYPO3_MODE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
633
634
            $iso639 = $GLOBALS['TSFE']->readLLfile($file);
635
636
            if (!empty($iso639['default'][$isoCode])) {
637
638
                $lang = $GLOBALS['TSFE']->getLLL($isoCode, $iso639);
639
640
            }
641
642
        } elseif (TYPO3_MODE === 'BE') {
643
644
            $iso639 = $GLOBALS['LANG']->includeLLFile($file, FALSE, TRUE);
645
646
            if (!empty($iso639['default'][$isoCode])) {
647
648
                $lang = $GLOBALS['LANG']->getLLL($isoCode, $iso639, FALSE);
649
650
            }
651
652
        } else {
653
654
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
655
656
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->getLanguageName('.$code.')] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_ERROR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
657
658
            }
659
660
            return $code;
661
662
        }
663
664
        if (!empty($lang)) {
665
666
            return $lang;
667
668
        } else {
669
670
            if (TYPO3_DLOG) {
671
672
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->getLanguageName('.$code.')] Language code "'.$code.'" not found in ISO-639 table', self::$extKey, SYSLOG_SEVERITY_NOTICE);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_NOTICE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
673
674
            }
675
676
            return $code;
677
678
        }
679
680
    }
681
682
    /**
683
     * Wrapper function for getting localizations in frontend and backend
684
     *
685
     * @param	string		$key: The locallang key to translate
686
     * @param	boolean		$hsc: Should the result be htmlspecialchar()'ed?
687
     * @param	string		$default: Default return value if no translation is available
688
     *
689
     * @return	string		The translated string or the given key on failure
690
     */
691
    public static function getLL($key, $hsc = FALSE, $default = '') {
692
693
        // Set initial output to default value.
694
        $translated = (string) $default;
695
696
        // Load common locallang file.
697
        if (empty(self::$locallang)) {
698
699
            $file = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath(self::$extKey, 'common/locallang.xml');
700
701
            if (TYPO3_MODE === 'FE') {
0 ignored issues
show
Bug introduced by
The constant TYPO3_MODE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
702
703
                self::$locallang = $GLOBALS['TSFE']->readLLfile($file);
704
705
            } elseif (TYPO3_MODE === 'BE') {
706
707
                self::$locallang = $GLOBALS['LANG']->includeLLFile($file, FALSE, TRUE);
708
709
            } elseif (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
710
711
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->getLL('.$key.', '.$default.', ['.($hsc ? 'TRUE' : 'FALSE').'])] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_ERROR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
712
713
            }
714
715
        }
716
717
        // Get translation.
718
        if (!empty(self::$locallang['default'][$key])) {
719
720
            if (TYPO3_MODE === 'FE') {
721
722
                $translated = $GLOBALS['TSFE']->getLLL($key, self::$locallang);
723
724
            } elseif (TYPO3_MODE === 'BE') {
725
726
                $translated = $GLOBALS['LANG']->getLLL($key, self::$locallang, FALSE);
727
728
            } elseif (TYPO3_DLOG) {
729
730
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->getLL('.$key.', '.$default.', ['.($hsc ? 'TRUE' : 'FALSE').'])] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
731
732
            }
733
734
        }
735
736
        // Escape HTML characters if applicable.
737
        if ($hsc) {
738
739
            $translated = htmlspecialchars($translated);
740
741
        }
742
743
        return $translated;
744
745
    }
746
747
    /**
748
     * Get the URN of an object
749
     * @see	http://www.persistent-identifier.de/?link=316
750
     *
751
     * @access	public
752
     *
753
     * @param	string		$base: The namespace and base URN
754
     * @param	string		$id: The object's identifier
755
     *
756
     * @return	string		Uniform Resource Name as string
757
     */
758
    public static function getURN($base, $id) {
759
760
        $concordance = array (
761
            '0' => 1,
762
            '1' => 2,
763
            '2' => 3,
764
            '3' => 4,
765
            '4' => 5,
766
            '5' => 6,
767
            '6' => 7,
768
            '7' => 8,
769
            '8' => 9,
770
            '9' => 41,
771
            'a' => 18,
772
            'b' => 14,
773
            'c' => 19,
774
            'd' => 15,
775
            'e' => 16,
776
            'f' => 21,
777
            'g' => 22,
778
            'h' => 23,
779
            'i' => 24,
780
            'j' => 25,
781
            'k' => 42,
782
            'l' => 26,
783
            'm' => 27,
784
            'n' => 13,
785
            'o' => 28,
786
            'p' => 29,
787
            'q' => 31,
788
            'r' => 12,
789
            's' => 32,
790
            't' => 33,
791
            'u' => 11,
792
            'v' => 34,
793
            'w' => 35,
794
            'x' => 36,
795
            'y' => 37,
796
            'z' => 38,
797
            '-' => 39,
798
            ':' => 17,
799
        );
800
801
        $urn = strtolower($base.$id);
802
803
        if (preg_match('/[^a-z0-9:-]/', $urn)) {
804
805
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
806
807
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->getURN('.$base.', '.$id.')] Invalid chars in given parameters', self::$extKey, SYSLOG_SEVERITY_WARNING);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_WARNING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
808
809
            }
810
811
            return '';
812
813
        }
814
815
        $digits = '';
816
817
        for ($i = 0, $j = strlen($urn); $i < $j; $i++) {
818
819
            $digits .= $concordance[substr($urn, $i, 1)];
820
821
        }
822
823
        $checksum = 0;
824
825
        for ($i = 0, $j = strlen($digits); $i < $j; $i++) {
826
827
            $checksum += ($i + 1) * intval(substr($digits, $i, 1));
828
829
        }
830
831
        $checksum = substr(intval($checksum / intval(substr($digits, -1, 1))), -1, 1);
832
833
        return $base.$id.$checksum;
834
835
    }
836
837
    /**
838
     * Check if given ID is a valid Pica Production Number (PPN)
839
     *
840
     * @access	public
841
     *
842
     * @param	string		$ppn: The identifier to check
843
     *
844
     * @return	boolean		Is $id a valid PPN?
845
     */
846
    public static function isPPN($id) {
847
848
        return self::checkIdentifier($id, 'PPN');
849
850
    }
851
852
    /**
853
     * Load value from user's session.
854
     *
855
     * @access	public
856
     *
857
     * @param	string		$key: Session data key for retrieval
858
     *
859
     * @return	mixed		Session value for given key or NULL on failure
860
     */
861
    public static function loadFromSession($key) {
862
863
        // Save parameter for logging purposes.
864
        $_key = $key;
865
866
        // Cast to string for security reasons.
867
        $key = (string) $key;
868
869
        if (!$key) {
870
871
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
872
873
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->loadFromSession('.$_key.')] Invalid key "'.$key.'" for session data retrieval', self::$extKey, SYSLOG_SEVERITY_WARNING);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_WARNING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
874
875
            }
876
877
            return;
878
879
        }
880
881
        // Get the session data.
882
        if (TYPO3_MODE === 'FE') {
0 ignored issues
show
Bug introduced by
The constant TYPO3_MODE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
883
884
            return $GLOBALS['TSFE']->fe_user->getKey('ses', $key);
885
886
        } elseif (TYPO3_MODE === 'BE') {
887
888
            return $GLOBALS['BE_USER']->getSessionData($key);
889
890
        } else {
891
892
            if (TYPO3_DLOG) {
893
894
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->loadFromSession('.$_key.')] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_ERROR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
895
896
            }
897
898
            return;
899
900
        }
901
902
    }
903
904
    /**
905
     * Process a data and/or command map with TYPO3 core engine.
906
     *
907
     * @access	public
908
     *
909
     * @param	array		$data: Data map
910
     * @param	array		$cmd: Command map
911
     * @param	boolean		$reverseOrder: Should the command map be processed first?
912
     * @param	boolean		$be_user: Use current backend user's rights for processing?
913
     *
914
     * @return	array		Array of substituted "NEW..." identifiers and their actual UIDs.
915
     */
916
    public static function processDB(array $data = array (), array $cmd = array (), $reverseOrder = FALSE, $be_user = FALSE) {
917
918
        // Instantiate TYPO3 core engine.
919
        $tce = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\DataHandling\\DataHandler');
920
921
        // Set some configuration variables.
922
        $tce->stripslashes_values = FALSE;
923
924
        // Get backend user for processing.
925
        if ($be_user && isset($GLOBALS['BE_USER'])) {
926
927
            $user = $GLOBALS['BE_USER'];
928
929
        } else {
930
931
            $user = self::getBeUser();
932
933
        }
934
935
        // Load data and command arrays.
936
        $tce->start($data, $cmd, $user);
937
938
        // Process command map first if default order is reversed.
939
        if ($cmd && $reverseOrder) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $cmd of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
940
941
            $tce->process_cmdmap();
942
943
        }
944
945
        // Process data map.
946
        if ($data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
947
948
            $tce->process_datamap();
949
950
        }
951
952
        // Process command map if processing order is not reversed.
953
        if ($cmd && !$reverseOrder) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $cmd of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
954
955
            $tce->process_cmdmap();
956
957
        }
958
959
        return $tce->substNEWwithIDs;
960
961
    }
962
963
    /**
964
     * Process a data and/or command map with TYPO3 core engine as admin.
965
     *
966
     * @access	public
967
     *
968
     * @param	array		$data: Data map
969
     * @param	array		$cmd: Command map
970
     * @param	boolean		$reverseOrder: Should the command map be processed first?
971
     *
972
     * @return	array		Array of substituted "NEW..." identifiers and their actual UIDs.
973
     */
974
    public static function processDBasAdmin(array $data = array (), array $cmd = array (), $reverseOrder = FALSE) {
975
976
        if (TYPO3_MODE === 'BE' && $GLOBALS['BE_USER']->isAdmin()) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_MODE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
977
978
            return self::processDB($data, $cmd, $reverseOrder, TRUE);
979
980
        } else {
981
982
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
983
984
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->processDBasAdmin([data->data], [data->cmd], ['.($reverseOrder ? 'TRUE' : 'FALSE').'])] Current backend user has no admin privileges', self::$extKey, SYSLOG_SEVERITY_ERROR, array ('data' => $data, 'cmd' => $cmd));
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_ERROR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
985
986
            }
987
988
            return array ();
989
990
        }
991
992
    }
993
994
    /**
995
     * Fetches and renders all available flash messages from the queue.
996
     *
997
     * @return	string		All flash messages in the queue rendered as HTML.
998
     */
999
    public static function renderFlashMessages() {
1000
1001
        $flashMessageService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessageService');
1002
1003
        $content = '';
1004
1005
        if (version_compare(TYPO3_branch, '7.4', '<')) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_branch was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1006
1007
            // For TYPO3 6.2 - 7.3, we can use the existing method.
1008
            $content .= $flashMessageService->getMessageQueueByIdentifier()->renderFlashMessages();
1009
1010
        } else {
1011
1012
            // Since TYPO3 7.4.0, \TYPO3\CMS\Core\Messaging\FlashMessageQueue::renderFlashMessages
1013
            // uses htmlspecialchars on all texts, but we have message text with HTML tags.
1014
            // Therefore we copy the implementation from 7.4.0, but remove the htmlspecialchars call.
1015
            $flashMessages = $flashMessageService->getMessageQueueByIdentifier()->getAllMessagesAndFlush();
1016
1017
            if (!empty($flashMessages)) {
1018
1019
                $content .= '<ul class="typo3-messages">';
1020
1021
                foreach ($flashMessages as $flashMessage) {
1022
1023
                    $severityClass = sprintf('alert %s', $flashMessage->getClass());
1024
1025
                    //~ $messageContent = htmlspecialchars($flashMessage->getMessage());
1026
1027
                    $messageContent = $flashMessage->getMessage();
1028
1029
                    if ($flashMessage->getTitle() !== '') {
1030
1031
                        $messageContent = sprintf('<h4>%s</h4>', htmlspecialchars($flashMessage->getTitle())).$messageContent;
1032
1033
                    }
1034
1035
                    $content .= sprintf('<li class="%s">%s</li>', htmlspecialchars($severityClass), $messageContent);
1036
1037
                }
1038
1039
                $content .= '</ul>';
1040
1041
            }
1042
1043
        }
1044
1045
        return $content;
1046
1047
    }
1048
1049
    /**
1050
     * Save given value to user's session.
1051
     *
1052
     * @access	public
1053
     *
1054
     * @param	mixed		$value: Value to save
1055
     * @param	string		$key: Session data key for saving
1056
     *
1057
     * @return	boolean		TRUE on success, FALSE on failure
1058
     */
1059
    public static function saveToSession($value, $key) {
1060
1061
        // Save parameter for logging purposes.
1062
        $_key = $key;
1063
1064
        // Cast to string for security reasons.
1065
        $key = (string) $key;
1066
1067
        if (!$key) {
1068
1069
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1070
1071
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->saveToSession([data], '.$_key.')] Invalid key "'.$key.'" for session data saving', self::$extKey, SYSLOG_SEVERITY_WARNING, $value);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_WARNING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1072
1073
            }
1074
1075
            return FALSE;
1076
1077
        }
1078
1079
        // Save value in session data.
1080
        if (TYPO3_MODE === 'FE') {
0 ignored issues
show
Bug introduced by
The constant TYPO3_MODE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1081
1082
            $GLOBALS['TSFE']->fe_user->setKey('ses', $key, $value);
1083
1084
            $GLOBALS['TSFE']->fe_user->storeSessionData();
1085
1086
            return TRUE;
1087
1088
        } elseif (TYPO3_MODE === 'BE') {
1089
1090
            $GLOBALS['BE_USER']->setAndSaveSessionData($key, $value);
1091
1092
            return TRUE;
1093
1094
        } else {
1095
1096
            if (TYPO3_DLOG) {
1097
1098
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->saveToSession([data], '.$_key.')] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR, $data);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $data seems to be never defined.
Loading history...
Bug introduced by
The constant SYSLOG_SEVERITY_ERROR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1099
1100
            }
1101
1102
            return FALSE;
1103
1104
        }
1105
1106
    }
1107
1108
    /**
1109
     * This translates an internal "index_name"
1110
     *
1111
     * @access	public
1112
     *
1113
     * @param	string		$index_name: The internal "index_name" to translate
1114
     * @param	string		$table: Get the translation from this table
1115
     * @param	string		$pid: Get the translation from this page
1116
     *
1117
     * @return	string		Localized label for $index_name
1118
     */
1119
    public static function translate($index_name, $table, $pid) {
1120
1121
        // Save parameters for logging purposes.
1122
        $_index_name = $index_name;
1123
1124
        $_pid = $pid;
1125
1126
        // Load labels into static variable for future use.
1127
        static $labels = array ();
1128
1129
        // Sanitize input.
1130
        $pid = max(intval($pid), 0);
1131
1132
        if (!$pid) {
1133
1134
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1135
1136
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->translate('.$_index_name.', '.$table.', '.$_pid.')] Invalid PID "'.$pid.'" for translation', self::$extKey, SYSLOG_SEVERITY_WARNING);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_WARNING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1137
1138
            }
1139
1140
            return $index_name;
1141
1142
        }
1143
1144
        // Check if "index_name" is an UID.
1145
        if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($index_name)) {
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Core\Utility\MathUtility was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1146
1147
            $index_name = self::getIndexName($index_name, $table, $pid);
1148
1149
        }
1150
1151
        /* $labels already contains the translated content element, but with the index_name of the translated content element itself
1152
		 * and not with the $index_name of the original that we receive here. So we have to determine the index_name of the
1153
		 * associated translated content element. E.g. $labels['title0'] != $index_name = title. */
1154
1155
        // First fetch the uid of the received index_name
1156
        $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1157
                'uid, l18n_parent',
1158
                $table,
1159
                'pid='.$pid.' AND index_name="'.$index_name.'"'.self::whereClause($table, TRUE),
1160
                '',
1161
                '',
1162
                ''
1163
        );
1164
1165
        if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
1166
1167
            // Now we use the uid of the l18_parent to fetch the index_name of the translated content element.
1168
            $resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
1169
1170
            $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1171
                    'index_name',
1172
                    $table,
1173
                    'pid='.$pid.' AND uid='.$resArray['l18n_parent'].' AND sys_language_uid='.intval($GLOBALS['TSFE']->sys_language_content).self::whereClause($table, TRUE),
1174
                    '',
1175
                    '',
1176
                    ''
1177
            );
1178
1179
            if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
1180
1181
                // If there is an translated content element, overwrite the received $index_name.
1182
                $resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result);
1183
1184
                $index_name = $resArray['index_name'];
1185
1186
            }
1187
1188
        }
1189
1190
        // Check if we already got a translation.
1191
        if (empty($labels[$table][$pid][$GLOBALS['TSFE']->sys_language_content][$index_name])) {
1192
1193
            // Check if this table is allowed for translation.
1194
            if (in_array($table, array ('tx_dlf_collections', 'tx_dlf_libraries', 'tx_dlf_metadata', 'tx_dlf_structures'))) {
1195
1196
                $additionalWhere = ' AND sys_language_uid IN (-1,0)';
1197
1198
                if ($GLOBALS['TSFE']->sys_language_content > 0) {
1199
1200
                    $additionalWhere = ' AND (sys_language_uid IN (-1,0) OR (sys_language_uid='.intval($GLOBALS['TSFE']->sys_language_content).' AND l18n_parent=0))';
1201
1202
                }
1203
1204
                // Get labels from database.
1205
                $result = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1206
                    '*',
1207
                    $table,
1208
                    'pid='.$pid.$additionalWhere.self::whereClause($table, TRUE),
1209
                    '',
1210
                    '',
1211
                    ''
1212
                );
1213
1214
                if ($GLOBALS['TYPO3_DB']->sql_num_rows($result) > 0) {
1215
1216
                    while ($resArray = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($result)) {
1217
1218
                        // Overlay localized labels if available.
1219
                        if ($GLOBALS['TSFE']->sys_language_content > 0) {
1220
1221
                            $resArray = $GLOBALS['TSFE']->sys_page->getRecordOverlay($table, $resArray, $GLOBALS['TSFE']->sys_language_content, $GLOBALS['TSFE']->sys_language_contentOL);
1222
1223
                        }
1224
1225
                        if ($resArray) {
1226
1227
                            $labels[$table][$pid][$GLOBALS['TSFE']->sys_language_content][$resArray['index_name']] = $resArray['label'];
1228
1229
                        }
1230
1231
                    }
1232
1233
                } else {
1234
1235
                    if (TYPO3_DLOG) {
1236
1237
                        \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->translate('.$_index_name.', '.$table.', '.$_pid.')] No translation with PID "'.$pid.'" available in table "'.$table.'" or translation not accessible', self::extKey, SYSLOG_SEVERITY_NOTICE);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_NOTICE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant tx_dlf_helper::extKey was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1238
1239
                    }
1240
1241
                }
1242
1243
            } else {
1244
1245
                if (TYPO3_DLOG) {
1246
1247
                    \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->translate('.$_index_name.', '.$table.', '.$_pid.')] No translations available for table "'.$table.'"', self::$extKey, SYSLOG_SEVERITY_WARNING);
1248
1249
                }
1250
1251
            }
1252
1253
        }
1254
1255
        if (!empty($labels[$table][$pid][$GLOBALS['TSFE']->sys_language_content][$index_name])) {
1256
1257
            return $labels[$table][$pid][$GLOBALS['TSFE']->sys_language_content][$index_name];
1258
1259
        } else {
1260
1261
            return $index_name;
1262
1263
        }
1264
1265
    }
1266
1267
    /**
1268
     * This returns the additional WHERE clause of a table based on its TCA configuration
1269
     *
1270
     * @access	public
1271
     *
1272
     * @param	string		$table: Table name as defined in TCA
1273
     * @param	boolean		$showHidden: Ignore the hidden flag?
1274
     *
1275
     * @return	string		Additional WHERE clause
1276
     */
1277
    public static function whereClause($table, $showHidden = FALSE) {
1278
1279
        if (TYPO3_MODE === 'FE') {
0 ignored issues
show
Bug introduced by
The constant TYPO3_MODE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1280
1281
            // Table "tx_dlf_formats" always has PID 0.
1282
            if ($table == 'tx_dlf_formats') {
1283
1284
                return \TYPO3\CMS\Backend\Utility\BackendUtility::deleteClause($table);
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Backend\Utility\BackendUtility was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1285
1286
            }
1287
1288
            // Should we ignore the record's hidden flag?
1289
            $ignoreHide = -1;
1290
1291
            if ($showHidden) {
1292
1293
                $ignoreHide = 1;
1294
1295
            }
1296
1297
            // $GLOBALS['TSFE']->sys_page is not always available in frontend.
1298
            if (is_object($GLOBALS['TSFE']->sys_page)) {
1299
1300
                return $GLOBALS['TSFE']->sys_page->enableFields($table, $ignoreHide);
1301
1302
            } else {
1303
1304
                $pageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
1305
1306
                $GLOBALS['TSFE']->includeTCA();
1307
1308
                return $pageRepository->enableFields($table, $ignoreHide);
1309
1310
            }
1311
1312
        } elseif (TYPO3_MODE === 'BE') {
1313
1314
            return \TYPO3\CMS\Backend\Utility\BackendUtility::deleteClause($table);
1315
1316
        } else {
1317
1318
            if (TYPO3_DLOG) {
0 ignored issues
show
Bug introduced by
The constant TYPO3_DLOG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1319
1320
                \TYPO3\CMS\Core\Utility\GeneralUtility::devLog('[tx_dlf_helper->whereClause('.$table.', ['.($showHidden ? 'TRUE' : 'FALSE').'])] Unexpected TYPO3_MODE "'.TYPO3_MODE.'"', self::$extKey, SYSLOG_SEVERITY_ERROR);
0 ignored issues
show
Bug introduced by
The constant SYSLOG_SEVERITY_ERROR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1321
1322
            }
1323
1324
            return ' AND 1=-1';
1325
1326
        }
1327
1328
    }
1329
1330
    /**
1331
     * This is a static class, thus no instances should be created
1332
     *
1333
     * @access private
1334
     */
1335
    private function __construct() {}
1336
1337
}
1338