[CLEANUP] Extension Manager code
[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 * Helper function to install an extension
105 * also processes db updates and clears the cache if the extension asks for it
106 *
107 * @param string $extensionKey
108 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
109 * @return void
110 */
111 public function install($extensionKey) {
112 $extension = $this->enrichExtensionWithDetails($extensionKey);
113 $this->processDatabaseUpdates($extension);
114 $this->ensureConfiguredDirectoriesExist($extension);
115 $this->importInitialFiles($extension['siteRelPath'], $extensionKey);
116 if (!$this->isLoaded($extensionKey)) {
117 $this->loadExtension($extensionKey);
118 }
119 $this->reloadCaches();
120 $this->processRuntimeDatabaseUpdates($extensionKey);
121 $this->saveDefaultConfiguration($extension['key']);
122 if ($extension['clearcacheonload']) {
123 $this->cacheManager->flushCaches();
124 } else {
125 $this->cacheManager->flushCachesInGroup('system');
126 }
127 }
128
129 /**
130 * Helper function to uninstall an extension
131 *
132 * @param string $extensionKey
133 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
134 * @return void
135 */
136 public function uninstall($extensionKey) {
137 $dependentExtensions = $this->dependencyUtility->findInstalledExtensionsThatDependOnMe($extensionKey);
138 if (is_array($dependentExtensions) && count($dependentExtensions) > 0) {
139 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException(
140 \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate(
141 'extensionList.uninstall.dependencyError',
142 'extensionmanager',
143 array($extensionKey, implode(',', $dependentExtensions))
144 ),
145 1342554622
146 );
147 } else {
148 $this->unloadExtension($extensionKey);
149 }
150 }
151
152 /**
153 * Wrapper function to check for loaded extensions
154 *
155 * @param string $extensionKey
156 * @return boolean TRUE if extension is loaded
157 */
158 public function isLoaded($extensionKey) {
159 return $this->packageManager->isPackageActive($extensionKey);
160 }
161
162 /**
163 * Wrapper function for loading extensions
164 *
165 * @param string $extensionKey
166 * @return void
167 */
168 protected function loadExtension($extensionKey) {
169 $this->packageManager->activatePackage($extensionKey);
170 }
171
172 /**
173 * Wrapper function for unloading extensions
174 *
175 * @param string $extensionKey
176 * @return void
177 */
178 protected function unloadExtension($extensionKey) {
179 $this->packageManager->deactivatePackage($extensionKey);
180 $this->cacheManager->flushCachesInGroup('system');
181 }
182
183 /**
184 * Checks if an extension is available in the system
185 *
186 * @param $extensionKey
187 * @return boolean
188 */
189 public function isAvailable($extensionKey) {
190 return $this->packageManager->isPackageAvailable($extensionKey);
191 }
192
193 /**
194 * Fetch additional information for an extension key
195 *
196 * @param string $extensionKey
197 * @access private
198 * @return array
199 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
200 */
201 public function enrichExtensionWithDetails($extensionKey) {
202 $availableExtensions = $this->listUtility->getAvailableExtensions();
203 if (isset($availableExtensions[$extensionKey])) {
204 $extension = $availableExtensions[$extensionKey];
205 } else {
206 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException('Extension ' . $extensionKey . ' is not available', 1342864081);
207 }
208 $availableAndInstalledExtensions = $this->listUtility->enrichExtensionsWithEmConfAndTerInformation(array($extensionKey => $extension));
209
210 if (!isset($availableAndInstalledExtensions[$extensionKey])) {
211 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException(
212 'Please check your uploaded extension "' . $extensionKey . '". The configuration file "ext_emconf.php" seems to be invalid.',
213 1391432222
214 );
215 }
216
217 return $availableAndInstalledExtensions[$extensionKey];
218 }
219
220 /**
221 * Creates directories as requested in ext_emconf.php
222 *
223 * @param array $extension
224 */
225 protected function ensureConfiguredDirectoriesExist(array $extension) {
226 $this->fileHandlingUtility->ensureConfiguredDirectoriesExist($extension);
227 }
228
229 /**
230 * Gets the content of the ext_tables.sql and ext_tables_static+adt.sql files
231 * Additionally adds the table definitions for the cache tables
232 *
233 * @param array $extension
234 */
235 public function processDatabaseUpdates(array $extension) {
236 $extTablesSqlFile = PATH_site . $extension['siteRelPath'] . 'ext_tables.sql';
237 $extTablesSqlContent = '';
238 if (file_exists($extTablesSqlFile)) {
239 $extTablesSqlContent .= \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($extTablesSqlFile);
240 }
241 if ($extTablesSqlContent !== '') {
242 $this->updateDbWithExtTablesSql($extTablesSqlContent);
243 }
244
245 $this->importStaticSqlFile($extension['siteRelPath']);
246 $this->importT3DFile($extension['siteRelPath']);
247 }
248
249 /**
250 * Gets all database updates due to runtime configuration, like caching framework or
251 * category api for example
252 *
253 * @param string $extensionKey
254 */
255 protected function processRuntimeDatabaseUpdates($extensionKey) {
256 $sqlString = $this->emitTablesDefinitionIsBeingBuiltSignal($extensionKey);
257 if (!empty($sqlString)) {
258 $this->updateDbWithExtTablesSql(implode(LF . LF . LF . LF, $sqlString));
259 }
260 }
261
262 /**
263 * Emits a signal to manipulate the tables definitions
264 *
265 * @param string $extensionKey
266 * @return mixed
267 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
268 */
269 protected function emitTablesDefinitionIsBeingBuiltSignal($extensionKey) {
270 $signalReturn = $this->signalSlotDispatcher->dispatch(__CLASS__, 'tablesDefinitionIsBeingBuilt', array('sqlString' => array(), 'extensionKey' => $extensionKey));
271 $sqlString = $signalReturn['sqlString'];
272 if (!is_array($sqlString)) {
273 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException(
274 sprintf(
275 'The signal %s of class %s returned a value of type %s, but array was expected.',
276 'tablesDefinitionIsBeingBuilt',
277 __CLASS__,
278 gettype($sqlString)
279 ),
280 1382360258
281 );
282 }
283 return $sqlString;
284 }
285
286 /**
287 * Reload Cache files and Typo3LoadedExtensions
288 *
289 * @return void
290 */
291 public function reloadCaches() {
292 \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::loadExtLocalconf(FALSE);
293 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->loadExtensionTables(FALSE);
294 }
295
296 /**
297 * Save default configuration of an extension
298 *
299 * @param string $extensionKey
300 * @return void
301 */
302 protected function saveDefaultConfiguration($extensionKey) {
303 /** @var $configUtility \TYPO3\CMS\Extensionmanager\Utility\ConfigurationUtility */
304 $configUtility = $this->objectManager->get('TYPO3\\CMS\\Extensionmanager\\Utility\\ConfigurationUtility');
305 $configUtility->saveDefaultConfiguration($extensionKey);
306 }
307
308 /**
309 * Update database / process db updates from ext_tables
310 *
311 * @param string $rawDefinitions The raw SQL statements from ext_tables.sql
312 * @return void
313 */
314 public function updateDbWithExtTablesSql($rawDefinitions) {
315 $fieldDefinitionsFromFile = $this->installToolSqlParser->getFieldDefinitions_fileContent($rawDefinitions);
316 if (count($fieldDefinitionsFromFile)) {
317 $fieldDefinitionsFromCurrentDatabase = $this->installToolSqlParser->getFieldDefinitions_database();
318 $diff = $this->installToolSqlParser->getDatabaseExtra($fieldDefinitionsFromFile, $fieldDefinitionsFromCurrentDatabase);
319 $updateStatements = $this->installToolSqlParser->getUpdateSuggestions($diff);
320 $db = $this->getDatabaseConnection();
321 foreach ((array) $updateStatements['add'] as $string) {
322 $db->admin_query($string);
323 }
324 foreach ((array) $updateStatements['change'] as $string) {
325 $db->admin_query($string);
326 }
327 foreach ((array) $updateStatements['create_table'] as $string) {
328 $db->admin_query($string);
329 }
330 }
331 }
332
333 /**
334 * Import static SQL data (normally used for ext_tables_static+adt.sql)
335 *
336 * @param string $rawDefinitions
337 * @return void
338 */
339 public function importStaticSql($rawDefinitions) {
340 $statements = $this->installToolSqlParser->getStatementarray($rawDefinitions, 1);
341 list($statementsPerTable, $insertCount) = $this->installToolSqlParser->getCreateTables($statements, 1);
342 $db = $this->getDatabaseConnection();
343 // Traverse the tables
344 foreach ($statementsPerTable as $table => $query) {
345 $db->admin_query('DROP TABLE IF EXISTS ' . $table);
346 $db->admin_query($query);
347 if ($insertCount[$table]) {
348 $insertStatements = $this->installToolSqlParser->getTableInsertStatements($statements, $table);
349 foreach ($insertStatements as $statement) {
350 $db->admin_query($statement);
351 }
352 }
353 }
354 }
355
356 /**
357 * Remove an extension (delete the directory)
358 *
359 * @param string $extension
360 * @throws \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException
361 * @return void
362 */
363 public function removeExtension($extension) {
364 $absolutePath = $this->fileHandlingUtility->getAbsoluteExtensionPath($extension);
365 if ($this->fileHandlingUtility->isValidExtensionPath($absolutePath)) {
366 $this->fileHandlingUtility->removeDirectory($absolutePath);
367 } else {
368 throw new \TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException('No valid extension path given.', 1342875724);
369 }
370 }
371
372 /**
373 * Get the data dump for an extension
374 *
375 * @param string $extension
376 * @return array
377 */
378 public function getExtensionSqlDataDump($extension) {
379 $extension = $this->enrichExtensionWithDetails($extension);
380 $filePrefix = PATH_site . $extension['siteRelPath'];
381 $sqlData['extTables'] = $this->getSqlDataDumpForFile($filePrefix . 'ext_tables.sql');
382 $sqlData['staticSql'] = $this->getSqlDataDumpForFile($filePrefix . 'ext_tables_static+adt.sql');
383 return $sqlData;
384 }
385
386 /**
387 * Gets the sql data dump for a specific sql file (for example ext_tables.sql)
388 *
389 * @param string $sqlFile
390 * @return string
391 */
392 protected function getSqlDataDumpForFile($sqlFile) {
393 $sqlData = '';
394 if (file_exists($sqlFile)) {
395 $sqlContent = \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($sqlFile);
396 $fieldDefinitions = $this->installToolSqlParser->getFieldDefinitions_fileContent($sqlContent);
397 $sqlData = $this->databaseUtility->dumpStaticTables($fieldDefinitions);
398 }
399 return $sqlData;
400 }
401
402 /**
403 * Checks if an update for an extension is available
404 *
405 * @internal
406 * @param \TYPO3\CMS\Extensionmanager\Domain\Model\Extension $extensionData
407 * @return boolean
408 */
409 public function isUpdateAvailable(\TYPO3\CMS\Extensionmanager\Domain\Model\Extension $extensionData) {
410 $isUpdateAvailable = FALSE;
411 // Only check for update for TER extensions
412 $version = $extensionData->getIntegerVersion();
413 /** @var $highestTerVersionExtension \TYPO3\CMS\Extensionmanager\Domain\Model\Extension */
414 $highestTerVersionExtension = $this->extensionRepository->findHighestAvailableVersion($extensionData->getExtensionKey());
415 if ($highestTerVersionExtension instanceof \TYPO3\CMS\Extensionmanager\Domain\Model\Extension) {
416 $highestVersion = $highestTerVersionExtension->getIntegerVersion();
417 if ($highestVersion > $version) {
418 try {
419 $this->dependencyUtility->buildExtensionDependenciesTree($highestTerVersionExtension);
420 $isUpdateAvailable = TRUE;
421 } catch (\TYPO3\CMS\Extensionmanager\Exception\ExtensionManagerException $e) {
422 }
423 }
424 }
425 return $isUpdateAvailable;
426 }
427
428 /**
429 * Uses the export import extension to import a T3DFile to PID 0
430 * Execution state is saved in the this->registry, so it only happens once
431 *
432 * @param string $extensionSiteRelPath
433 * @return void
434 */
435 protected function importT3DFile($extensionSiteRelPath) {
436 $t3dImportRelFile = $extensionSiteRelPath . 'Initialisation/data.t3d';
437 if (!$this->registry->get('extensionDataImport', $t3dImportRelFile)) {
438 $t3dImportFile = PATH_site . $t3dImportRelFile;
439 if (file_exists($t3dImportFile)) {
440 $importExportUtility = $this->objectManager->get('TYPO3\\CMS\\Impexp\\Utility\\ImportExportUtility');
441 try {
442 $importResult = $importExportUtility->importT3DFile($t3dImportFile, 0);
443 $this->registry->set('extensionDataImport', $t3dImportRelFile, 1);
444 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterExtensionT3DImport', array($t3dImportRelFile, $importResult, $this));
445 } catch (\ErrorException $e) {
446 /** @var \TYPO3\CMS\Core\Log\Logger $logger */
447 $logger = $this->objectManager->get('TYPO3\\CMS\\Core\\Log\\LogManager')->getLogger(__CLASS__);
448 $logger->log(\TYPO3\CMS\Core\Log\LogLevel::WARNING, $e->getMessage());
449 }
450 }
451 }
452 }
453
454 /**
455 * Imports a static tables SQL File (ext_tables_static+adt)
456 * Execution state is saved in the this->registry, so it only happens once
457 *
458 * @param string $extensionSiteRelPath
459 * @return void
460 */
461 protected function importStaticSqlFile($extensionSiteRelPath) {
462 $extTablesStaticSqlRelFile = $extensionSiteRelPath . 'ext_tables_static+adt.sql';
463 if (!$this->registry->get('extensionDataImport', $extTablesStaticSqlRelFile)) {
464 $extTablesStaticSqlFile = PATH_site . $extTablesStaticSqlRelFile;
465 if (file_exists($extTablesStaticSqlFile)) {
466 $extTablesStaticSqlContent = \TYPO3\CMS\Core\Utility\GeneralUtility::getUrl($extTablesStaticSqlFile);
467 $this->importStaticSql($extTablesStaticSqlContent);
468 }
469 $this->registry->set('extensionDataImport', $extTablesStaticSqlRelFile, 1);
470 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterExtensionStaticSqlImport', array($extTablesStaticSqlRelFile, $this));
471 }
472 }
473
474 /**
475 * Imports files from Initialisation/Files to fileadmin
476 * via lowlevel copy directory method
477 *
478 * @param string $extensionSiteRelPath relative path to extension dir
479 * @param string $extensionKey
480 */
481 protected function importInitialFiles($extensionSiteRelPath, $extensionKey) {
482 $importRelFolder = $extensionSiteRelPath . 'Initialisation/Files';
483 if (!$this->registry->get('extensionDataImport', $importRelFolder)) {
484 $importFolder = PATH_site . $importRelFolder;
485 if (file_exists($importFolder)) {
486 $destinationRelPath = $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'] . $extensionKey;
487 $destinationAbsolutePath = PATH_site . $destinationRelPath;
488 if (!file_exists($destinationAbsolutePath) &&
489 \TYPO3\CMS\Core\Utility\GeneralUtility::isAllowedAbsPath($destinationAbsolutePath)
490 ) {
491 \TYPO3\CMS\Core\Utility\GeneralUtility::mkdir($destinationAbsolutePath);
492 }
493 \TYPO3\CMS\Core\Utility\GeneralUtility::copyDirectory($importRelFolder, $destinationRelPath);
494 $this->registry->set('extensionDataImport', $importRelFolder, 1);
495 $this->signalSlotDispatcher->dispatch(__CLASS__, 'afterExtensionFileImport', array($destinationAbsolutePath, $this));
496 }
497 }
498 }
499
500
501 /**
502 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
503 */
504 protected function getDatabaseConnection() {
505 return $GLOBALS['TYPO3_DB'];
506 }
507 }