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