[TASK] Deprecate usage of $GLOBALS['typo3CacheManager']
[Packages/TYPO3.CMS.git] / typo3 / sysext / extensionmanager / Classes / Utility / InstallUtility.php
1 <?php
2 namespace TYPO3\CMS\Extensionmanager\Utility;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 2012-2013 Susanne Moog <susanne.moog@typo3.org>
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the text file GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29
30 /**
31 * Extension Manager Install Utility
32 *
33 * @author Susanne Moog <susanne.moog@typo3.org>
34 */
35 class InstallUtility implements \TYPO3\CMS\Core\SingletonInterface {
36
37 /**
38 * @var \TYPO3\CMS\Extbase\Object\ObjectManager
39 * @inject
40 */
41 public $objectManager;
42
43 /**
44 * @var \TYPO3\CMS\Install\Service\SqlSchemaMigrationService
45 * @inject
46 */
47 public $installToolSqlParser;
48
49 /**
50 * @var \TYPO3\CMS\Extensionmanager\Utility\DependencyUtility
51 * @inject
52 */
53 protected $dependencyUtility;
54
55 /**
56 * @var \TYPO3\CMS\Extensionmanager\Utility\FileHandlingUtility
57 * @inject
58 */
59 protected $fileHandlingUtility;
60
61 /**
62 * @var \TYPO3\CMS\Extensionmanager\Utility\ListUtility
63 * @inject
64 */
65 protected $listUtility;
66
67 /**
68 * @var \TYPO3\CMS\Extensionmanager\Utility\DatabaseUtility
69 * @inject
70 */
71 protected $databaseUtility;
72
73 /**
74 * @var \TYPO3\CMS\Extensionmanager\Domain\Repository\ExtensionRepository
75 * @inject
76 */
77 public $extensionRepository;
78
79 /**
80 * @var \TYPO3\CMS\Core\Package\PackageManager
81 * @inject
82 */
83 protected $packageManager;
84
85 /**
86 * @var \TYPO3\CMS\Core\Cache\CacheManager
87 * @inject
88 */
89 protected $cacheManager;
90
91 /**
92 * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
93 * @inject
94 */
95 protected $signalSlotDispatcher;
96
97 /**
98 * @var \TYPO3\CMS\Core\Registry
99 * @inject
100 */
101 protected $registry;
102
103 /**
104 * __construct
105 */
106 public function __construct() {
107 $this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
108 /** @var $installToolSqlParser \TYPO3\CMS\Install\Service\SqlSchemaMigrationService */
109 $this->installToolSqlParser = $this->objectManager->get('TYPO3\\CMS\\Install\\Service\\SqlSchemaMigrationService');
110 $this->dependencyUtility = $this->objectManager->get('TYPO3\\CMS\\Extensionmanager\\Utility\\DependencyUtility');
111 }
112
113 /**
114 * Helper function to install an extension
115 * also processes db updates and clears the cache if the extension asks for it
116 *
117 * @param string $extensionKey
118 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
119 * @return void
120 */
121 public function install($extensionKey) {
122 $extension = $this->enrichExtensionWithDetails($extensionKey);
123 $this->processDatabaseUpdates($extension);
124 $this->ensureConfiguredDirectoriesExist($extension);
125 $this->importInitialFiles($extension['siteRelPath'], $extensionKey);
126 if (!$this->isLoaded($extensionKey)) {
127 $this->loadExtension($extensionKey);
128 }
129 $this->reloadCaches();
130 $this->processRuntimeDatabaseUpdates($extensionKey);
131 $this->saveDefaultConfiguration($extension['key']);
132 if ($extension['clearcacheonload']) {
133 $this->cacheManager->flushCaches();
134 }
135 }
136
137 /**
138 * Helper function to uninstall an extension
139 *
140 * @param string $extensionKey
141 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
142 * @return void
143 */
144 public function uninstall($extensionKey) {
145 $dependentExtensions = $this->dependencyUtility->findInstalledExtensionsThatDependOnMe($extensionKey);
146 if (is_array($dependentExtensions) && count($dependentExtensions) > 0) {
147 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException(
148 \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate(
149 'extensionList.uninstall.dependencyError',
150 'extensionmanager',
151 array($extensionKey, implode(',', $dependentExtensions))
152 ),
153 1342554622
154 );
155 } else {
156 $this->unloadExtension($extensionKey);
157 }
158 }
159
160 /**
161 * Wrapper function to check for loaded extensions
162 *
163 * @param string $extensionKey
164 * @return boolean TRUE if extension is loaded
165 */
166 public function isLoaded($extensionKey) {
167 return $this->packageManager->isPackageActive($extensionKey);
168 }
169
170 /**
171 * Wrapper function for loading extensions
172 *
173 * @param string $extensionKey
174 * @return void
175 */
176 protected function loadExtension($extensionKey) {
177 $this->packageManager->activatePackage($extensionKey);
178 }
179
180 /**
181 * Wrapper function for unloading extensions
182 *
183 * @param string $extensionKey
184 * @return void
185 */
186 protected function unloadExtension($extensionKey) {
187 $this->packageManager->deactivatePackage($extensionKey);
188 $this->reloadCaches();
189 }
190
191 /**
192 * Checks if an extension is available in the system
193 *
194 * @param $extensionKey
195 * @return boolean
196 */
197 public function isAvailable($extensionKey) {
198 return $this->packageManager->isPackageAvailable($extensionKey);
199 }
200
201 /**
202 * Fetch additional information for an extension key
203 *
204 * @param string $extensionKey
205 * @access private
206 * @return array
207 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
208 */
209 public function enrichExtensionWithDetails($extensionKey) {
210 $availableExtensions = $this->listUtility->getAvailableExtensions();
211 if (isset($availableExtensions[$extensionKey])) {
212 $extension = $availableExtensions[$extensionKey];
213 } else {
214 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException('Extension ' . $extensionKey . ' is not available', 1342864081);
215 }
216 $availableAndInstalledExtensions = $this->listUtility->enrichExtensionsWithEmConfAndTerInformation(array($extensionKey => $extension));
217
218 if (!isset($availableAndInstalledExtensions[$extensionKey])) {
219 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException(
220 'Please check your uploaded extension "' . $extensionKey . '". The configuration file "ext_emconf.php" seems to be invalid.',
221 1391432222
222 );
223 }
224
225 return $availableAndInstalledExtensions[$extensionKey];
226 }
227
228 /**
229 * Creates directories as requested in ext_emconf.php
230 *
231 * @param array $extension
232 */
233 protected function ensureConfiguredDirectoriesExist(array $extension) {
234 $this->fileHandlingUtility->ensureConfiguredDirectoriesExist($extension);
235 }
236
237 /**
238 * Gets the content of the ext_tables.sql and ext_tables_static+adt.sql files
239 * Additionally adds the table definitions for the cache tables
240 *
241 * @param array $extension
242 */
243 public function processDatabaseUpdates(array $extension) {
244 $extTablesSqlFile = PATH_site . $extension['siteRelPath'] . '/ext_tables.sql';
245 $extTablesSqlContent = '';
246 if (file_exists($extTablesSqlFile)) {
247 $extTablesSqlContent .= \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($extTablesSqlFile);
248 }
249 if ($extTablesSqlContent !== '') {
250 $this->updateDbWithExtTablesSql($extTablesSqlContent);
251 }
252
253 $this->importStaticSqlFile($extension['siteRelPath']);
254 $this->importT3DFile($extension['siteRelPath']);
255 }
256
257 /**
258 * Gets all database updates due to runtime configuration, like caching framework or
259 * category api for example
260 *
261 * @param string $extensionKey
262 */
263 protected function processRuntimeDatabaseUpdates($extensionKey) {
264 $sqlString = $this->emitTablesDefinitionIsBeingBuiltSignal($extensionKey);
265 if (!empty($sqlString)) {
266 $this->updateDbWithExtTablesSql(implode(LF . LF . LF . LF, $sqlString));
267 }
268 }
269
270 /**
271 * Emits a signal to manipulate the tables definitions
272 *
273 * @param string $extensionKey
274 * @return mixed
275 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
276 */
277 protected function emitTablesDefinitionIsBeingBuiltSignal($extensionKey) {
278 $signalReturn = $this->signalSlotDispatcher->dispatch(__CLASS__, 'tablesDefinitionIsBeingBuilt', array('sqlString' => array(), 'extensionKey' => $extensionKey));
279 $sqlString = $signalReturn['sqlString'];
280 if (!is_array($sqlString)) {
281 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException(
282 sprintf(
283 'The signal %s of class %s returned a value of type %s, but array was expected.',
284 'tablesDefinitionIsBeingBuilt',
285 __CLASS__,
286 gettype($sqlString)
287 ),
288 1382360258
289 );
290 }
291 return $sqlString;
292 }
293
294 /**
295 * Reload Cache files and Typo3LoadedExtensions
296 *
297 * @return void
298 */
299 public function reloadCaches() {
300 $this->cacheManager->flushCachesInGroup('system');
301 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->reloadTypo3LoadedExtAndClassLoaderAndExtLocalconf()->loadExtensionTables();
302 }
303
304 /**
305 * Save default configuration of an extension
306 *
307 * @param string $extensionKey
308 * @return void
309 */
310 protected function saveDefaultConfiguration($extensionKey) {
311 /** @var $configUtility \TYPO3\CMS\Extensionmanager\Utility\ConfigurationUtility */
312 $configUtility = $this->objectManager->get('TYPO3\\CMS\\Extensionmanager\\Utility\\ConfigurationUtility');
313 $configUtility->saveDefaultConfiguration($extensionKey);
314 }
315
316 /**
317 * Update database / process db updates from ext_tables
318 *
319 * @param string $rawDefinitions The raw SQL statements from ext_tables.sql
320 * @return void
321 */
322 public function updateDbWithExtTablesSql($rawDefinitions) {
323 $fieldDefinitionsFromFile = $this->installToolSqlParser->getFieldDefinitions_fileContent($rawDefinitions);
324 if (count($fieldDefinitionsFromFile)) {
325 $fieldDefinitionsFromCurrentDatabase = $this->installToolSqlParser->getFieldDefinitions_database();
326 $diff = $this->installToolSqlParser->getDatabaseExtra($fieldDefinitionsFromFile, $fieldDefinitionsFromCurrentDatabase);
327 $updateStatements = $this->installToolSqlParser->getUpdateSuggestions($diff);
328 foreach ((array) $updateStatements['add'] as $string) {
329 $GLOBALS['TYPO3_DB']->admin_query($string);
330 }
331 foreach ((array) $updateStatements['change'] as $string) {
332 $GLOBALS['TYPO3_DB']->admin_query($string);
333 }
334 foreach ((array) $updateStatements['create_table'] as $string) {
335 $GLOBALS['TYPO3_DB']->admin_query($string);
336 }
337 }
338 }
339
340 /**
341 * Import static SQL data (normally used for ext_tables_static+adt.sql)
342 *
343 * @param string $rawDefinitions
344 * @return void
345 */
346 public function importStaticSql($rawDefinitions) {
347 $statements = $this->installToolSqlParser->getStatementarray($rawDefinitions, 1);
348 list($statementsPerTable, $insertCount) = $this->installToolSqlParser->getCreateTables($statements, 1);
349 // Traverse the tables
350 foreach ($statementsPerTable as $table => $query) {
351 $GLOBALS['TYPO3_DB']->admin_query('DROP TABLE IF EXISTS ' . $table);
352 $GLOBALS['TYPO3_DB']->admin_query($query);
353 if ($insertCount[$table]) {
354 $insertStatements = $this->installToolSqlParser->getTableInsertStatements($statements, $table);
355 foreach ($insertStatements as $statement) {
356 $GLOBALS['TYPO3_DB']->admin_query($statement);
357 }
358 }
359 }
360 }
361
362 /**
363 * Remove an extension (delete the directory)
364 *
365 * @param string $extension
366 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
367 * @return void
368 */
369 public function removeExtension($extension) {
370 $absolutePath = $this->fileHandlingUtility->getAbsoluteExtensionPath($extension);
371 if ($this->fileHandlingUtility->isValidExtensionPath($absolutePath)) {
372 $this->fileHandlingUtility->removeDirectory($absolutePath);
373 } else {
374 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException('No valid extension path given.', 1342875724);
375 }
376 }
377
378 /**
379 * Get the data dump for an extension
380 *
381 * @param string $extension
382 * @return array
383 */
384 public function getExtensionSqlDataDump($extension) {
385 $extension = $this->enrichExtensionWithDetails($extension);
386 $filePrefix = PATH_site . $extension['siteRelPath'];
387 $sqlData['extTables'] = $this->getSqlDataDumpForFile($filePrefix . '/ext_tables.sql');
388 $sqlData['staticSql'] = $this->getSqlDataDumpForFile($filePrefix . '/ext_tables_static+adt.sql');
389 return $sqlData;
390 }
391
392 /**
393 * Gets the sql data dump for a specific sql file (for example ext_tables.sql)
394 *
395 * @param string $sqlFile
396 * @return string
397 */
398 protected function getSqlDataDumpForFile($sqlFile) {
399 $sqlData = '';
400 if (file_exists($sqlFile)) {
401 $sqlContent = \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($sqlFile);
402 $fieldDefinitions = $this->installToolSqlParser->getFieldDefinitions_fileContent($sqlContent);
403 $sqlData = $this->databaseUtility->dumpStaticTables($fieldDefinitions);
404 }
405 return $sqlData;
406 }
407
408 /**
409 * Checks if an update for an extension is available
410 *
411 * @internal
412 * @param \TYPO3\CMS\Extensionmanager\Domain\Model\Extension $extensionData
413 * @return boolean
414 */
415 public function isUpdateAvailable(\TYPO3\CMS\Extensionmanager\Domain\Model\Extension $extensionData) {
416 $isUpdateAvailable = FALSE;
417 // Only check for update for TER extensions
418 $version = $extensionData->getIntegerVersion();
419 /** @var $highestTerVersionExtension \TYPO3\CMS\Extensionmanager\Domain\Model\Extension */
420 $highestTerVersionExtension = $this->extensionRepository->findHighestAvailableVersion($extensionData->getExtensionKey());
421 if ($highestTerVersionExtension instanceof \TYPO3\CMS\Extensionmanager\Domain\Model\Extension) {
422 $highestVersion = $highestTerVersionExtension->getIntegerVersion();
423 if ($highestVersion > $version) {
424 try {
425 $this->dependencyUtility->buildExtensionDependenciesTree($highestTerVersionExtension);
426 $isUpdateAvailable = TRUE;
427 } catch (\TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException $e) {
428 }
429 }
430 }
431 return $isUpdateAvailable;
432 }
433
434 /**
435 * Uses the export import extension to import a T3DFile to PID 0
436 * Execution state is saved in the this->registry, so it only happens once
437 *
438 * @param string $extensionSiteRelPath
439 * @return void
440 */
441 protected function importT3DFile($extensionSiteRelPath) {
442 $t3dImportRelFile = $extensionSiteRelPath . '/Initialisation/data.t3d';
443 if (!$this->registry->get('extensionDataImport', $t3dImportRelFile)) {
444 $t3dImportFile = PATH_site . $t3dImportRelFile;
445 if (file_exists($t3dImportFile)) {
446 $importExportUtility = $this->objectManager->get('TYPO3\\CMS\\Impexp\\Utility\\ImportExportUtility');
447 try {
448 $importResult = $importExportUtility->importT3DFile($t3dImportFile, 0);
449 $this->registry->set('extensionDataImport', $t3dImportRelFile, 1);
450 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterExtensionT3DImport', array($t3dImportRelFile, $importResult, $this));
451 } catch (\ErrorException $e) {
452 /** @var \TYPO3\CMS\Core\Log\Logger $logger */
453 $logger = $this->objectManager->get('TYPO3\\CMS\\Core\\Log\\LogManager')->getLogger(__CLASS__);
454 $logger->log(\TYPO3\CMS\Core\Log\LogLevel::WARNING, $e->getMessage());
455 }
456 }
457 }
458 }
459
460 /**
461 * Imports a static tables SQL File (ext_tables_static+adt)
462 * Execution state is saved in the this->registry, so it only happens once
463 *
464 * @param string $extensionSiteRelPath
465 * @return void
466 */
467 protected function importStaticSqlFile($extensionSiteRelPath) {
468 $extTablesStaticSqlRelFile = $extensionSiteRelPath . '/ext_tables_static+adt.sql';
469 if (!$this->registry->get('extensionDataImport', $extTablesStaticSqlRelFile)) {
470 $extTablesStaticSqlFile = PATH_site . $extTablesStaticSqlRelFile;
471 if (file_exists($extTablesStaticSqlFile)) {
472 $extTablesStaticSqlContent = \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($extTablesStaticSqlFile);
473 $this->importStaticSql($extTablesStaticSqlContent);
474 }
475 $this->registry->set('extensionDataImport', $extTablesStaticSqlRelFile, 1);
476 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterExtensionStaticSqlImport', array($extTablesStaticSqlRelFile, $this));
477 }
478 }
479
480 /**
481 * Imports files from Initialisation/Files to fileadmin
482 * via lowlevel copy directory method
483 *
484 * @param string $extensionSiteRelPath relative path to extension dir
485 * @param string $extensionKey
486 */
487 protected function importInitialFiles($extensionSiteRelPath, $extensionKey) {
488 $importRelFolder = $extensionSiteRelPath . '/Initialisation/Files';
489 if (!$this->registry->get('extensionDataImport', $importRelFolder)) {
490 $importFolder = PATH_site . $importRelFolder;
491 if (file_exists($importFolder)) {
492 $destinationRelPath = $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'] . $extensionKey;
493 $destinationAbsolutePath = PATH_site . $destinationRelPath;
494 if (!file_exists($destinationAbsolutePath) &&
495 \TYPO3\CMS\Core\Utility\GeneralUtility::isAllowedAbsPath($destinationAbsolutePath)
496 ) {
497 \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir($destinationAbsolutePath);
498 }
499 \TYPO3\CMS\Core\Utility\GeneralUtility::copyDirectory($importRelFolder, $destinationRelPath);
500 $this->registry->set('extensionDataImport', $importRelFolder, 1);
501 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterExtensionFileImport', array($destinationAbsolutePath, $this));
502 }
503 }
504 }
505 }