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