Completed
Push — backend-compatibility ( c3c5b5...b6bc18 )
by Romain
02:26
created

Core::getEnvironmentService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
/*
3
 * 2017 Romain CANON <[email protected]>
4
 *
5
 * This file is part of the TYPO3 Formz project.
6
 * It is free software; you can redistribute it and/or modify it
7
 * under the terms of the GNU General Public License, either
8
 * version 3 of the License, or any later version.
9
 *
10
 * For the full copyright and license information, see:
11
 * http://www.gnu.org/licenses/gpl-3.0.html
12
 */
13
14
namespace Romm\Formz\Core;
15
16
use Romm\Formz\Configuration\ConfigurationFactory;
17
use Romm\Formz\Form\FormObjectFactory;
18
use Romm\Formz\Utility\TypoScriptUtility;
19
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
20
use TYPO3\CMS\Core\Cache\Backend\AbstractBackend;
21
use TYPO3\CMS\Core\Cache\CacheManager;
22
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
23
use TYPO3\CMS\Core\SingletonInterface;
24
use TYPO3\CMS\Core\Utility\ArrayUtility;
25
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
26
use TYPO3\CMS\Core\Utility\GeneralUtility;
27
use TYPO3\CMS\Core\Utility\MathUtility;
28
use TYPO3\CMS\Core\Utility\PathUtility;
29
use TYPO3\CMS\Extbase\Object\ObjectManager;
30
use TYPO3\CMS\Extbase\Object\ObjectManagerInterface;
31
use TYPO3\CMS\Extbase\Service\EnvironmentService;
32
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
33
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
34
35
/**
36
 * Class containing general functions.
37
 */
38
class Core implements SingletonInterface
39
{
40
    const EXTENSION_KEY = 'formz';
41
    const CACHE_IDENTIFIER = 'cache_formz';
42
    const GENERATED_FILES_PATH = 'typo3temp/Formz/';
43
44
    /**
45
     * @var Core
46
     */
47
    protected static $instance;
48
49
    /**
50
     * @var int|null
51
     */
52
    private $currentPageUid = -1;
53
54
    /**
55
     * @var ObjectManagerInterface
56
     */
57
    private $objectManager;
58
59
    /**
60
     * @var TypoScriptUtility
61
     */
62
    private $typoScriptUtility;
63
64
    /**
65
     * @var ConfigurationFactory
66
     */
67
    private $configurationFactory;
68
69
    /**
70
     * @var FormObjectFactory
71
     */
72
    private $formObjectFactory;
73
74
    /**
75
     * @var EnvironmentService
76
     */
77
    private $environmentService;
78
79
    /**
80
     * Contains the actual language key.
81
     *
82
     * @var string
83
     */
84
    private $languageKey;
85
86
    /**
87
     * @var array
88
     */
89
    private $extensionConfiguration;
90
91
    /**
92
     * @var FrontendInterface
93
     */
94
    protected $cacheInstance;
95
96
    /**
97
     * @return Core
98
     */
99
    public static function get()
100
    {
101
        if (null === self::$instance) {
102
            /** @var ObjectManager $objectManager */
103
            $objectManager = GeneralUtility::makeInstance(ObjectManager::class);
104
105
            self::$instance = $objectManager->get(self::class);
106
        }
107
108
        return self::$instance;
109
    }
110
111
    /**
112
     * Translation handler. Does the same job as Extbase translation tools,
113
     * expect that if the index to the LLL reference is not found, the index is
114
     * returned (Extbase would have returned an empty string).
115
     *
116
     * @param    string $index        The index to the LLL reference.
117
     * @param    string $extensionKey Key of the extension containing the LLL reference.
118
     * @param    array  $arguments    Arguments passed over to vsprintf.
119
     * @return   string               The translated string.
120
     */
121
    public function translate($index, $extensionKey = null, $arguments = null)
122
    {
123
        $extensionKey = ($extensionKey) ?: self::EXTENSION_KEY;
124
        $result = LocalizationUtility::translate($index, $extensionKey, $arguments);
125
        if ($result === '' && $index !== '') {
126
            $result = $index;
127
        }
128
129
        return $result;
130
    }
131
132
    /**
133
     * Converts an array to a clean JSON string which can be used by JavaScript.
134
     *
135
     * @param array $array
136
     * @return string
137
     */
138
    public function arrayToJavaScriptJson(array $array)
139
    {
140
        return json_encode($array, JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_TAG);
141
    }
142
143
    /**
144
     * Returns the type of backend cache defined in TypoScript at the path:
145
     * `settings.defaultBackendCache`.
146
     *
147
     * @return string
148
     * @throws \Exception
149
     */
150
    public function getBackendCache()
151
    {
152
        $backendCache = $this->getTypoScriptUtility()
153
            ->getExtensionConfigurationFromPath('settings.defaultBackendCache');
154
155
        if (false === class_exists($backendCache)
156
            && false === in_array(AbstractBackend::class, class_parents($backendCache))
157
        ) {
158
            throw new \Exception(
159
                'The cache class name given in configuration "config.tx_formz.settings.defaultBackendCache" must inherit "' . AbstractBackend::class . '" (current value: "' . (string)$backendCache . '")',
160
                1459251263
161
            );
162
        }
163
164
        return $backendCache;
165
    }
166
167
    /**
168
     * Returns the current page uid, in a frontend or backend context.
169
     *
170
     * Returns null if the uid can't be found (backend module, ajax call, etc.).
171
     *
172
     * @return int|null
173
     */
174
    public function getCurrentPageUid()
175
    {
176
        if (-1 === $this->currentPageUid) {
177
            $id = ($this->environmentService->isEnvironmentInFrontendMode())
178
                ? $this->getPageController()->id
179
                : GeneralUtility::_GP('id');
180
181
            if (false === MathUtility::canBeInterpretedAsInteger($id)
182
                || intval($id) < 0
183
            ) {
184
                $id = null;
185
            }
186
187
            $this->currentPageUid = $id;
188
        }
189
190
        return $this->currentPageUid;
191
    }
192
193
    /**
194
     * Allows you to set manually the current page uid. Useful when editing a
195
     * record, for example.
196
     *
197
     * @param int $uid The uid of the page.
198
     */
199
    public function setCurrentPageUid($uid)
200
    {
201
        $this->currentPageUid = intval($uid);
202
    }
203
204
    /**
205
     * Returns the cache instance for this extension.
206
     *
207
     * @return FrontendInterface
208
     */
209
    public function getCacheInstance()
210
    {
211
        if (null === $this->cacheInstance) {
212
            /** @var $cacheManager CacheManager */
213
            $cacheManager = $this->getObjectManager()->get(CacheManager::class);
214
215
            if ($cacheManager->hasCache(self::CACHE_IDENTIFIER)) {
216
                $this->cacheInstance = $cacheManager->getCache(self::CACHE_IDENTIFIER);
217
            }
218
        }
219
220
        return $this->cacheInstance;
221
    }
222
223
    /**
224
     * @param FrontendInterface $cacheInstance
225
     */
226
    public function setCacheInstance(FrontendInterface $cacheInstance)
227
    {
228
        $this->cacheInstance = $cacheInstance;
229
    }
230
231
    /**
232
     * Generic cache identifier creation for usages in the extension.
233
     *
234
     * @param string $string
235
     * @param string $formClassName
236
     * @param int    $maxLength
237
     * @return string
238
     */
239
    public function getCacheIdentifier($string, $formClassName, $maxLength = 55)
240
    {
241
        $explodedClassName = explode('\\', $formClassName);
242
243
        $identifier = strtolower(
244
            $string .
245
            end($explodedClassName) .
246
            '-' .
247
            sha1($formClassName)
248
        );
249
250
        return substr($identifier, 0, $maxLength);
251
    }
252
253
    /**
254
     * Return the wanted extension configuration.
255
     *
256
     * @param string $configurationName
257
     * @return mixed
258
     */
259
    public function getExtensionConfiguration($configurationName)
260
    {
261
        $result = null;
262
        $extensionConfiguration = $this->getFullExtensionConfiguration();
263
264
        if (null === $configurationName) {
265
            $result = $extensionConfiguration;
266
        } elseif (ArrayUtility::isValidPath($extensionConfiguration, $configurationName, '.')) {
267
            $result = ArrayUtility::getValueByPath($extensionConfiguration, $configurationName, '.');
268
        }
269
270
        return $result;
271
    }
272
273
    /**
274
     * @return array
275
     */
276
    protected function getFullExtensionConfiguration()
277
    {
278
        if (null === $this->extensionConfiguration) {
279
            $this->extensionConfiguration = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][self::EXTENSION_KEY]);
280
281
            if (false === $this->extensionConfiguration) {
282
                $this->extensionConfiguration = [];
283
            }
284
        }
285
286
        return $this->extensionConfiguration;
287
    }
288
289
    /**
290
     * Function called when clearing TYPO3 caches. It will remove the temporary
291
     * asset files created by Formz.
292
     *
293
     * @param array $parameters
294
     */
295
    public function clearCacheCommand($parameters)
296
    {
297
        if (false === in_array($parameters['cacheCmd'], ['all', 'system'])) {
298
            return;
299
        }
300
301
        $files = glob(GeneralUtility::getFileAbsFileName(self::GENERATED_FILES_PATH . '*'));
302
303
        if (false === $files) {
304
            return;
305
        }
306
307
        foreach ($files as $assetCacheFile) {
308
            unlink($assetCacheFile);
309
        }
310
    }
311
312
    /**
313
     * Returns the current language key.
314
     *
315
     * @return string
316
     */
317
    public function getLanguageKey()
318
    {
319
        if (null === $this->languageKey) {
320
            $this->languageKey = 'default';
321
322
            if ($this->environmentService->isEnvironmentInFrontendMode()) {
323
                $pageController = $this->getPageController();
324
325
                if (isset($pageController->config['config']['language'])) {
326
                    $this->languageKey = $pageController->config['config']['language'];
327
                }
328
            } else {
329
                $backendUser = $this->getBackendUser();
330
331
                if (strlen($backendUser->uc['lang']) > 0) {
332
                    $this->languageKey = $backendUser->uc['lang'];
333
                }
334
            }
335
        }
336
337
        return $this->languageKey;
338
    }
339
340
    /**
341
     * Will check if the TypoScript was indeed included, as it contains required
342
     * configuration to make the forms work properly.
343
     *
344
     * @return bool
345
     */
346
    public function isTypoScriptIncluded()
347
    {
348
        return null !== $this->getTypoScriptUtility()->getExtensionConfigurationFromPath('settings.typoScriptIncluded');
349
    }
350
351
    /**
352
     * @return bool
353
     */
354
    public function isInDebugMode()
355
    {
356
        return (bool)$this->getExtensionConfiguration('debugMode');
357
    }
358
359
    /**
360
     * @param string|null $path If a string is given, it will be precessed by the extension relative path and returned.
361
     * @return string
362
     */
363
    public function getExtensionRelativePath($path = null)
364
    {
365
        $relativePath = ExtensionManagementUtility::siteRelPath('formz');
366
367
        return (null !== $path)
368
            ? $relativePath . $path
369
            : $relativePath;
370
    }
371
372
    /**
373
     * @param string $path
374
     * @return string
375
     */
376
    public function getResourceRelativePath($path)
377
    {
378
        return rtrim(
379
            PathUtility::getRelativePath(
380
                GeneralUtility::getIndpEnv('TYPO3_DOCUMENT_ROOT'),
381
                GeneralUtility::getFileAbsFileName($path)
382
            ),
383
            '/'
384
        );
385
    }
386
387
    /**
388
     * Sanitizes a string: lower case with dash separation.
389
     *
390
     * @param string $string
391
     * @return string
392
     */
393
    public function sanitizeString($string)
394
    {
395
        $string = str_replace('_', '-', GeneralUtility::camelCaseToLowerCaseUnderscored($string));
396
397
        while (strpos($string, '--')) {
398
            $string = str_replace('--', '-', $string);
399
        }
400
401
        return $string;
402
    }
403
404
    /**
405
     * @return ObjectManagerInterface
406
     */
407
    public function getObjectManager()
408
    {
409
        return $this->objectManager;
410
    }
411
412
    /**
413
     * @param ObjectManagerInterface $objectManager
414
     */
415
    public function injectObjectManager(ObjectManagerInterface $objectManager)
416
    {
417
        $this->objectManager = $objectManager;
418
    }
419
420
    /**
421
     * @return TypoScriptUtility
422
     */
423
    public function getTypoScriptUtility()
424
    {
425
        return $this->typoScriptUtility;
426
    }
427
428
    /**
429
     * @param TypoScriptUtility $typoScriptUtility
430
     */
431
    public function injectTypoScriptUtility(TypoScriptUtility $typoScriptUtility)
432
    {
433
        $this->typoScriptUtility = $typoScriptUtility;
434
    }
435
436
    /**
437
     * @return ConfigurationFactory
438
     */
439
    public function getConfigurationFactory()
440
    {
441
        return $this->configurationFactory;
442
    }
443
444
    /**
445
     * @param ConfigurationFactory $configurationFactory
446
     */
447
    public function injectConfigurationFactory(ConfigurationFactory $configurationFactory)
448
    {
449
        $this->configurationFactory = $configurationFactory;
450
    }
451
452
    /**
453
     * @return FormObjectFactory
454
     */
455
    public function getFormObjectFactory()
456
    {
457
        return $this->formObjectFactory;
458
    }
459
460
    /**
461
     * @param FormObjectFactory $formObjectFactory
462
     */
463
    public function injectFormObjectFactory(FormObjectFactory $formObjectFactory)
464
    {
465
        $this->formObjectFactory = $formObjectFactory;
466
    }
467
468
    /**
469
     * @return EnvironmentService
470
     */
471
    public function getEnvironmentService()
472
    {
473
        return $this->environmentService;
474
    }
475
476
    /**
477
     * @param EnvironmentService $environmentService
478
     */
479
    public function injectEnvironmentService(EnvironmentService $environmentService)
480
    {
481
        $this->environmentService = $environmentService;
482
    }
483
484
    /**
485
     * Returns the extension key.
486
     *
487
     * @return string
488
     */
489
    public function getExtensionKey()
490
    {
491
        return self::EXTENSION_KEY;
492
    }
493
494
    /**
495
     * @return TypoScriptFrontendController
496
     */
497
    public function getPageController()
498
    {
499
        return $GLOBALS['TSFE'];
500
    }
501
502
    /**
503
     * @return BackendUserAuthentication
504
     */
505
    public function getBackendUser()
506
    {
507
        return $GLOBALS['BE_USER'];
508
    }
509
}
510