c42c408fba6e6690614d8886f11d9e1323afb661
[Packages/TYPO3.CMS.git] / typo3 / sysext / extensionmanager / Classes / Utility / InstallUtility.php
1 <?php
2 namespace TYPO3\CMS\Extensionmanager\Utility;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Impexp\Utility\ImportExportUtility;
18
19 /**
20 * Extension Manager Install Utility
21 *
22 * @author Susanne Moog <susanne.moog@typo3.org>
23 */
24 class InstallUtility implements \TYPO3\CMS\Core\SingletonInterface {
25
26 /**
27 * @var \TYPO3\CMS\Extbase\Object\ObjectManager
28 * @inject
29 */
30 public $objectManager;
31
32 /**
33 * @var \TYPO3\CMS\Install\Service\SqlSchemaMigrationService
34 * @inject
35 */
36 public $installToolSqlParser;
37
38 /**
39 * @var \TYPO3\CMS\Extensionmanager\Utility\DependencyUtility
40 * @inject
41 */
42 protected $dependencyUtility;
43
44 /**
45 * @var \TYPO3\CMS\Extensionmanager\Utility\FileHandlingUtility
46 * @inject
47 */
48 protected $fileHandlingUtility;
49
50 /**
51 * @var \TYPO3\CMS\Extensionmanager\Utility\ListUtility
52 * @inject
53 */
54 protected $listUtility;
55
56 /**
57 * @var \TYPO3\CMS\Extensionmanager\Utility\DatabaseUtility
58 * @inject
59 */
60 protected $databaseUtility;
61
62 /**
63 * @var \TYPO3\CMS\Extensionmanager\Domain\Repository\ExtensionRepository
64 * @inject
65 */
66 public $extensionRepository;
67
68 /**
69 * @var \TYPO3\CMS\Core\Package\PackageManager
70 * @inject
71 */
72 protected $packageManager;
73
74 /**
75 * @var \TYPO3\CMS\Core\Cache\CacheManager
76 * @inject
77 */
78 protected $cacheManager;
79
80 /**
81 * @var \TYPO3\CMS\Extbase\SignalSlot\Dispatcher
82 * @inject
83 */
84 protected $signalSlotDispatcher;
85
86 /**
87 * @var \TYPO3\CMS\Core\Registry
88 * @inject
89 */
90 protected $registry;
91
92 /**
93 * Helper function to install an extension
94 * also processes db updates and clears the cache if the extension asks for it
95 *
96 * @param string $extensionKey
97 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
98 * @return void
99 */
100 public function install($extensionKey) {
101 $extension = $this->enrichExtensionWithDetails($extensionKey);
102 $this->ensureConfiguredDirectoriesExist($extension);
103 if (!$this->isLoaded($extensionKey)) {
104 $this->loadExtension($extensionKey);
105 }
106 if (!empty($extension['clearcacheonload']) || !empty($extension['clearCacheOnLoad'])) {
107 $this->cacheManager->flushCaches();
108 } else {
109 $this->cacheManager->flushCachesInGroup('system');
110 }
111 $this->reloadCaches();
112
113 $this->importInitialFiles($extension['siteRelPath'], $extensionKey);
114 $this->processDatabaseUpdates($extension);
115 $this->processRuntimeDatabaseUpdates($extensionKey);
116 $this->saveDefaultConfiguration($extension['key']);
117
118 $this->emitAfterExtensionInstallSignal($extensionKey);
119 }
120
121 /**
122 * Helper function to uninstall an extension
123 *
124 * @param string $extensionKey
125 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
126 * @return void
127 */
128 public function uninstall($extensionKey) {
129 $dependentExtensions = $this->dependencyUtility->findInstalledExtensionsThatDependOnMe($extensionKey);
130 if (is_array($dependentExtensions) && count($dependentExtensions) > 0) {
131 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException(
132 \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate(
133 'extensionList.uninstall.dependencyError',
134 'extensionmanager',
135 array($extensionKey, implode(',', $dependentExtensions))
136 ),
137 1342554622
138 );
139 } else {
140 $this->unloadExtension($extensionKey);
141 }
142 }
143
144 /**
145 * Wrapper function to check for loaded extensions
146 *
147 * @param string $extensionKey
148 * @return bool TRUE if extension is loaded
149 */
150 public function isLoaded($extensionKey) {
151 return $this->packageManager->isPackageActive($extensionKey);
152 }
153
154 /**
155 * Wrapper function for loading extensions
156 *
157 * @param string $extensionKey
158 * @return void
159 */
160 protected function loadExtension($extensionKey) {
161 $this->packageManager->activatePackage($extensionKey);
162 }
163
164 /**
165 * Wrapper function for unloading extensions
166 *
167 * @param string $extensionKey
168 * @return void
169 */
170 protected function unloadExtension($extensionKey) {
171 $this->packageManager->deactivatePackage($extensionKey);
172 $this->emitAfterExtensionUninstallSignal($extensionKey);
173 $this->cacheManager->flushCachesInGroup('system');
174 }
175
176 /**
177 * Emits a signal after an extension has been installed
178 *
179 * @param string $extensionKey
180 */
181 protected function emitAfterExtensionInstallSignal($extensionKey) {
182 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterExtensionInstall', array($extensionKey, $this));
183 }
184
185 /**
186 * Emits a signal after an extension has been uninstalled
187 *
188 * @param string $extensionKey
189 */
190 protected function emitAfterExtensionUninstallSignal($extensionKey) {
191 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterExtensionUninstall', array($extensionKey, $this));
192 }
193
194 /**
195 * Checks if an extension is available in the system
196 *
197 * @param string $extensionKey
198 * @return bool
199 */
200 public function isAvailable($extensionKey) {
201 return $this->packageManager->isPackageAvailable($extensionKey);
202 }
203
204 /**
205 * Fetch additional information for an extension key
206 *
207 * @param string $extensionKey
208 * @access private
209 * @return array
210 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
211 */
212 public function enrichExtensionWithDetails($extensionKey) {
213 $availableExtensions = $this->listUtility->getAvailableExtensions();
214 if (isset($availableExtensions[$extensionKey])) {
215 $extension = $availableExtensions[$extensionKey];
216 } else {
217 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException('Extension ' . $extensionKey . ' is not available', 1342864081);
218 }
219 $availableAndInstalledExtensions = $this->listUtility->enrichExtensionsWithEmConfAndTerInformation(array($extensionKey => $extension));
220
221 if (!isset($availableAndInstalledExtensions[$extensionKey])) {
222 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException(
223 'Please check your uploaded extension "' . $extensionKey . '". The configuration file "ext_emconf.php" seems to be invalid.',
224 1391432222
225 );
226 }
227
228 return $availableAndInstalledExtensions[$extensionKey];
229 }
230
231 /**
232 * Creates directories as requested in ext_emconf.php
233 *
234 * @param array $extension
235 */
236 protected function ensureConfiguredDirectoriesExist(array $extension) {
237 $this->fileHandlingUtility->ensureConfiguredDirectoriesExist($extension);
238 }
239
240 /**
241 * Gets the content of the ext_tables.sql and ext_tables_static+adt.sql files
242 * Additionally adds the table definitions for the cache tables
243 *
244 * @param array $extension
245 */
246 public function processDatabaseUpdates(array $extension) {
247 $extTablesSqlFile = PATH_site . $extension['siteRelPath'] . 'ext_tables.sql';
248 $extTablesSqlContent = '';
249 if (file_exists($extTablesSqlFile)) {
250 $extTablesSqlContent .= \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($extTablesSqlFile);
251 }
252 if ($extTablesSqlContent !== '') {
253 $this->updateDbWithExtTablesSql($extTablesSqlContent);
254 }
255
256 $this->importStaticSqlFile($extension['siteRelPath']);
257 $this->importT3DFile($extension['siteRelPath']);
258 }
259
260 /**
261 * Gets all database updates due to runtime configuration, like caching framework or
262 * category api for example
263 *
264 * @param string $extensionKey
265 */
266 protected function processRuntimeDatabaseUpdates($extensionKey) {
267 $sqlString = $this->emitTablesDefinitionIsBeingBuiltSignal($extensionKey);
268 if (!empty($sqlString)) {
269 $this->updateDbWithExtTablesSql(implode(LF . LF . LF . LF, $sqlString));
270 }
271 }
272
273 /**
274 * Emits a signal to manipulate the tables definitions
275 *
276 * @param string $extensionKey
277 * @return mixed
278 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
279 */
280 protected function emitTablesDefinitionIsBeingBuiltSignal($extensionKey) {
281 $signalReturn = $this->signalSlotDispatcher->dispatch(__CLASS__, 'tablesDefinitionIsBeingBuilt', array(array(), $extensionKey));
282 // This is important to support old associated returns
283 $signalReturn = array_values($signalReturn);
284 $sqlString = $signalReturn[0];
285 if (!is_array($sqlString)) {
286 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException(
287 sprintf(
288 'The signal %s of class %s returned a value of type %s, but array was expected.',
289 'tablesDefinitionIsBeingBuilt',
290 __CLASS__,
291 gettype($sqlString)
292 ),
293 1382360258
294 );
295 }
296 return $sqlString;
297 }
298
299 /**
300 * Reload Cache files and Typo3LoadedExtensions
301 *
302 * @return void
303 */
304 public function reloadCaches() {
305 // Reload class aliases defined in Migrations/Code/ClassAliasMap.php
306 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->getEarlyInstance(\TYPO3\CMS\Core\Core\ClassLoader::class)
307 ->setPackages($this->packageManager->getActivePackages());
308 \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::loadExtLocalconf(FALSE);
309 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->loadExtensionTables(FALSE);
310 }
311
312 /**
313 * Save default configuration of an extension
314 *
315 * @param string $extensionKey
316 * @return void
317 */
318 protected function saveDefaultConfiguration($extensionKey) {
319 /** @var $configUtility \TYPO3\CMS\Extensionmanager\Utility\ConfigurationUtility */
320 $configUtility = $this->objectManager->get(\TYPO3\CMS\Extensionmanager\Utility\ConfigurationUtility::class);
321 $configUtility->saveDefaultConfiguration($extensionKey);
322 }
323
324 /**
325 * Update database / process db updates from ext_tables
326 *
327 * @param string $rawDefinitions The raw SQL statements from ext_tables.sql
328 * @return void
329 */
330 public function updateDbWithExtTablesSql($rawDefinitions) {
331 $fieldDefinitionsFromFile = $this->installToolSqlParser->getFieldDefinitions_fileContent($rawDefinitions);
332 if (count($fieldDefinitionsFromFile)) {
333 $fieldDefinitionsFromCurrentDatabase = $this->installToolSqlParser->getFieldDefinitions_database();
334 $diff = $this->installToolSqlParser->getDatabaseExtra($fieldDefinitionsFromFile, $fieldDefinitionsFromCurrentDatabase);
335 $updateStatements = $this->installToolSqlParser->getUpdateSuggestions($diff);
336 $db = $this->getDatabaseConnection();
337 foreach ((array)$updateStatements['add'] as $string) {
338 $db->admin_query($string);
339 }
340 foreach ((array)$updateStatements['change'] as $string) {
341 $db->admin_query($string);
342 }
343 foreach ((array)$updateStatements['create_table'] as $string) {
344 $db->admin_query($string);
345 }
346 }
347 }
348
349 /**
350 * Import static SQL data (normally used for ext_tables_static+adt.sql)
351 *
352 * @param string $rawDefinitions
353 * @return void
354 */
355 public function importStaticSql($rawDefinitions) {
356 $statements = $this->installToolSqlParser->getStatementarray($rawDefinitions, 1);
357 list($statementsPerTable, $insertCount) = $this->installToolSqlParser->getCreateTables($statements, 1);
358 $db = $this->getDatabaseConnection();
359 // Traverse the tables
360 foreach ($statementsPerTable as $table => $query) {
361 $db->admin_query('DROP TABLE IF EXISTS ' . $table);
362 $db->admin_query($query);
363 if ($insertCount[$table]) {
364 $insertStatements = $this->installToolSqlParser->getTableInsertStatements($statements, $table);
365 foreach ($insertStatements as $statement) {
366 $db->admin_query($statement);
367 }
368 }
369 }
370 }
371
372 /**
373 * Remove an extension (delete the directory)
374 *
375 * @param string $extension
376 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
377 * @return void
378 */
379 public function removeExtension($extension) {
380 $absolutePath = $this->fileHandlingUtility->getAbsoluteExtensionPath($extension);
381 if ($this->fileHandlingUtility->isValidExtensionPath($absolutePath)) {
382 if ($this->packageManager->isPackageAvailable($extension)) {
383 // Package manager deletes the extension and removes the entry from PackageStates.php
384 $this->packageManager->deletePackage($extension);
385 } else {
386 // The extension is not listed in PackageStates.php, we can safely remove it
387 $this->fileHandlingUtility->removeDirectory($absolutePath);
388 }
389 } else {
390 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException('No valid extension path given.', 1342875724);
391 }
392 }
393
394 /**
395 * Get the data dump for an extension
396 *
397 * @param string $extension
398 * @return array
399 */
400 public function getExtensionSqlDataDump($extension) {
401 $extension = $this->enrichExtensionWithDetails($extension);
402 $filePrefix = PATH_site . $extension['siteRelPath'];
403 $sqlData['extTables'] = $this->getSqlDataDumpForFile($filePrefix . 'ext_tables.sql');
404 $sqlData['staticSql'] = $this->getSqlDataDumpForFile($filePrefix . 'ext_tables_static+adt.sql');
405 return $sqlData;
406 }
407
408 /**
409 * Gets the sql data dump for a specific sql file (for example ext_tables.sql)
410 *
411 * @param string $sqlFile
412 * @return string
413 */
414 protected function getSqlDataDumpForFile($sqlFile) {
415 $sqlData = '';
416 if (file_exists($sqlFile)) {
417 $sqlContent = \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($sqlFile);
418 $fieldDefinitions = $this->installToolSqlParser->getFieldDefinitions_fileContent($sqlContent);
419 $sqlData = $this->databaseUtility->dumpStaticTables($fieldDefinitions);
420 }
421 return $sqlData;
422 }
423
424
425 /**
426 * Checks if an update for an extension is available which also resolves dependencies.
427 *
428 * @internal
429 * @param \TYPO3\CMS\Extensionmanager\Domain\Model\Extension $extensionData
430 * @return bool
431 */
432 public function isUpdateAvailable(\TYPO3\CMS\Extensionmanager\Domain\Model\Extension $extensionData) {
433 return (bool)$this->getUpdateableVersion($extensionData);
434 }
435
436 /**
437 * Returns the updateable version for an extension which also resolves dependencies.
438 *
439 * @internal
440 * @param \TYPO3\CMS\Extensionmanager\Domain\Model\Extension $extensionData
441 * @return bool|\TYPO3\CMS\Extensionmanager\Domain\Model\Extension FALSE if no update available otherwise latest
442 * possible update
443 */
444 public function getUpdateableVersion(\TYPO3\CMS\Extensionmanager\Domain\Model\Extension $extensionData) {
445 // Only check for update for TER extensions
446 $version = $extensionData->getIntegerVersion();
447
448 /** @var $extensionUpdates[] \TYPO3\CMS\Extensionmanager\Domain\Model\Extension */
449 $extensionUpdates = $this->extensionRepository->findByVersionRangeAndExtensionKeyOrderedByVersion(
450 $extensionData->getExtensionKey(),
451 $version + 1
452 );
453 if ($extensionUpdates->count() > 0) {
454 foreach ($extensionUpdates as $extensionUpdate) {
455 $this->dependencyUtility->checkDependencies($extensionUpdate);
456 if (!$this->dependencyUtility->hasDependencyErrors()) {
457 return $extensionUpdate;
458 }
459 }
460 }
461 return FALSE;
462 }
463
464 /**
465 * Uses the export import extension to import a T3D or XML file to PID 0
466 * Execution state is saved in the this->registry, so it only happens once
467 *
468 * @param string $extensionSiteRelPath
469 * @return void
470 */
471 protected function importT3DFile($extensionSiteRelPath) {
472 $registryKeysToCheck = array(
473 $extensionSiteRelPath . 'Initialisation/data.t3d',
474 $extensionSiteRelPath . 'Initialisation/dataImported',
475 );
476 foreach ($registryKeysToCheck as $registryKeyToCheck) {
477 if ($this->registry->get('extensionDataImport', $registryKeyToCheck)) {
478 // Data was imported before => early return
479 return;
480 }
481 }
482 $importFileToUse = NULL;
483 $possibleImportFiles = array(
484 $extensionSiteRelPath . 'Initialisation/data.t3d',
485 $extensionSiteRelPath . 'Initialisation/data.xml'
486 );
487 foreach ($possibleImportFiles as $possibleImportFile) {
488 if (!file_exists(PATH_site . $possibleImportFile)) {
489 continue;
490 }
491 $importFileToUse = $possibleImportFile;
492 }
493 if ($importFileToUse !== NULL) {
494 /** @var ImportExportUtility $importExportUtility */
495 $importExportUtility = $this->objectManager->get(\TYPO3\CMS\Impexp\Utility\ImportExportUtility::class);
496 try {
497 $importResult = $importExportUtility->importT3DFile(PATH_site . $importFileToUse, 0);
498 $this->registry->set('extensionDataImport', $extensionSiteRelPath . 'Initialisation/dataImported', 1);
499 $this->emitAfterExtensionT3DImportSignal($importFileToUse, $importResult);
500 } catch (\ErrorException $e) {
501 /** @var \TYPO3\CMS\Core\Log\Logger $logger */
502 $logger = $this->objectManager->get(\TYPO3\CMS\Core\Log\LogManager::class)->getLogger(__CLASS__);
503 $logger->log(\TYPO3\CMS\Core\Log\LogLevel::WARNING, $e->getMessage());
504 }
505 }
506 }
507
508 /**
509 * Emits a signal after an t3d file was imported
510 *
511 * @param string $importFileToUse
512 * @param int $importResult
513 */
514 protected function emitAfterExtensionT3DImportSignal($importFileToUse, $importResult) {
515 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterExtensionT3DImport', array($importFileToUse, $importResult, $this));
516 }
517
518 /**
519 * Imports a static tables SQL File (ext_tables_static+adt)
520 * Execution state is saved in the this->registry, so it only happens once
521 *
522 * @param string $extensionSiteRelPath
523 * @return void
524 */
525 protected function importStaticSqlFile($extensionSiteRelPath) {
526 $extTablesStaticSqlRelFile = $extensionSiteRelPath . 'ext_tables_static+adt.sql';
527 if (!$this->registry->get('extensionDataImport', $extTablesStaticSqlRelFile)) {
528 $extTablesStaticSqlFile = PATH_site . $extTablesStaticSqlRelFile;
529 if (file_exists($extTablesStaticSqlFile)) {
530 $extTablesStaticSqlContent = \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($extTablesStaticSqlFile);
531 $this->importStaticSql($extTablesStaticSqlContent);
532 }
533 $this->registry->set('extensionDataImport', $extTablesStaticSqlRelFile, 1);
534 $this->emitAfterExtensionStaticSqlImportSignal($extTablesStaticSqlRelFile);
535 }
536 }
537
538 /**
539 * Emits a signal after a static sql file was imported
540 *
541 * @param string $extTablesStaticSqlRelFile
542 */
543 protected function emitAfterExtensionStaticSqlImportSignal($extTablesStaticSqlRelFile) {
544 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterExtensionStaticSqlImport', array($extTablesStaticSqlRelFile, $this));
545 }
546
547 /**
548 * Imports files from Initialisation/Files to fileadmin
549 * via lowlevel copy directory method
550 *
551 * @param string $extensionSiteRelPath relative path to extension dir
552 * @param string $extensionKey
553 */
554 protected function importInitialFiles($extensionSiteRelPath, $extensionKey) {
555 $importRelFolder = $extensionSiteRelPath . 'Initialisation/Files';
556 if (!$this->registry->get('extensionDataImport', $importRelFolder)) {
557 $importFolder = PATH_site . $importRelFolder;
558 if (file_exists($importFolder)) {
559 $destinationRelPath = $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'] . $extensionKey;
560 $destinationAbsolutePath = PATH_site . $destinationRelPath;
561 if (!file_exists($destinationAbsolutePath) &&
562 \TYPO3\CMS\Core\Utility\GeneralUtility::isAllowedAbsPath($destinationAbsolutePath)
563 ) {
564 \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir($destinationAbsolutePath);
565 }
566 \TYPO3\CMS\Core\Utility\GeneralUtility::copyDirectory($importRelFolder, $destinationRelPath);
567 $this->registry->set('extensionDataImport', $importRelFolder, 1);
568 $this->emitAfterExtensionFileImportSignal($destinationAbsolutePath);
569 }
570 }
571 }
572
573 /**
574 * Emits a signal after extension files were imported
575 *
576 * @param string $destinationAbsolutePath
577 */
578 protected function emitAfterExtensionFileImportSignal($destinationAbsolutePath) {
579 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterExtensionFileImport', array($destinationAbsolutePath, $this));
580 }
581
582 /**
583 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
584 */
585 protected function getDatabaseConnection() {
586 return $GLOBALS['TYPO3_DB'];
587 }
588
589 }