class.tx_ter_helper.php 24.4 KB
Newer Older
1
<?php
2
/*
3 4 5 6 7 8 9 10 11 12 13
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */
14

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/**
 * Helper functions used in the TER API
 *
 * $Id$
 *
 * @author    Robert Lemke <robert@typo3.org>
 */
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 *
 *
 *  103: class tx_ter_helper
 *  114:     public function __construct($pluginObj)
 *  127:     public function getValidUser ($accountData)
 *  162:     public function extensionKeyIsAvailable($extensionKey)
 *  188:     public function getExtensionKeyRecord ($extKey)
 *  215:     public function getLatestVersionNumberOfExtension ($extensionKey)
 *  245:     public function requestUpdateOfExtensionIndexFile()
 *  260:     public function writeExtensionIndexfile()
 *  358:     public function xmlentities ($string)
 *
 * TOTAL FUNCTIONS: 8
 * (This index is automatically created/updated by the extension "extdeveval")
 */
use TYPO3\CMS\Core\Utility\GeneralUtility;

// Make sure that we are executed only in TYPO3 context
if (!defined('TYPO3_MODE')) {
Markus Sommer's avatar
Markus Sommer committed
44
    die('Access denied.');
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
}

// Error codes:
define('TX_TER_ERROR_GENERAL_EXTREPDIRDOESNTEXIST', '100');
define('TX_TER_ERROR_GENERAL_NOUSERORPASSWORD', '101');
define('TX_TER_ERROR_GENERAL_USERNOTFOUND', '102');
define('TX_TER_ERROR_GENERAL_WRONGPASSWORD', '103');
define('TX_TER_ERROR_GENERAL_DATABASEERROR', '104');
define('TX_TER_ERROR_GENERAL_EXTENSIONCONTAINSNOFILES', '105');

define('TX_TER_ERROR_UPLOADEXTENSION_EXTENSIONDOESNTEXIST', '202');
define('TX_TER_ERROR_UPLOADEXTENSION_EXTENSIONCONTAINSNOFILES', '203');
define('TX_TER_ERROR_UPLOADEXTENSION_WRITEERRORWHILEWRITINGFILES', '204');
define('TX_TER_ERROR_UPLOADEXTENSION_EXTENSIONTOOBIG', '205');
define('TX_TER_ERROR_UPLOADEXTENSION_EXISTINGEXTENSIONRECORDNOTFOUND', '206');
define('TX_TER_ERROR_UPLOADEXTENSION_FILEMD5DOESNOTMATCH', '207');
define('TX_TER_ERROR_UPLOADEXTENSION_ACCESSDENIED', '208');
define('TX_TER_ERROR_UPLOADEXTENSION_TYPO3DEPENDENCYINCORRECT', '209');
define('TX_TER_ERROR_UPLOADEXTENSION_TYPO3DEPENDENCYCHECKFAILED', '210');
define('TX_TER_ERROR_UPLOADEXTENSION_EXTENSIONVERSIONEXISTS', '211');
65
define('TX_TER_ERROR_UPLOADEXTENSION_NOUPLOADCOMMENT', '212');
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

define('TX_TER_ERROR_REGISTEREXTENSIONKEY_DBERRORWHILEINSERTINGKEY', '300');

define('TX_TER_ERROR_DELETEEXTENSIONKEY_ACCESSDENIED', '500');
define('TX_TER_ERROR_DELETEEXTENSIONKEY_KEYDOESNOTEXIST', '501');
define('TX_TER_ERROR_DELETEEXTENSIONKEY_CANTDELETEBECAUSEVERSIONSEXIST', '502');

define('TX_TER_ERROR_MODIFYEXTENSIONKEY_ACCESSDENIED', '600');
define('TX_TER_ERROR_MODIFYEXTENSIONKEY_SETTINGTOTHISOWNERISNOTPOSSIBLE', '601');
define('TX_TER_ERROR_MODIFYEXTENSIONKEY_KEYDOESNOTEXIST', '602');

define('TX_TER_ERROR_SETREVIEWSTATE_NOUSERGROUPDEFINED', '700');
define('TX_TER_ERROR_SETREVIEWSTATE_ACCESSDENIED', '701');
define('TX_TER_ERROR_SETREVIEWSTATE_EXTENSIONVERSIONDOESNOTEXIST', '702');

define('TX_TER_ERROR_INCREASEEXTENSIONDOWNLOADCOUNTER_NOUSERGROUPDEFINED', '800');
define('TX_TER_ERROR_INCREASEEXTENSIONDOWNLOADCOUNTER_ACCESSDENIED', '801');
define('TX_TER_ERROR_INCREASEEXTENSIONDOWNLOADCOUNTER_EXTENSIONVERSIONDOESNOTEXIST', '802');
define('TX_TER_ERROR_INCREASEEXTENSIONDOWNLOADCOUNTER_INCREMENTORNOTPOSITIVEINTEGER', '803');
define('TX_TER_ERROR_INCREASEEXTENSIONDOWNLOADCOUNTER_EXTENSIONKEYDOESNOTEXIST', '804');

define('TX_TER_ERROR_DELETEEXTENSION_ACCESS_DENIED', '900');
define('TX_TER_ERROR_DELETEEXTENSION_EXTENSIONDOESNTEXIST', '901');

// Result codes:
define('TX_TER_RESULT_GENERAL_OK', '10000');
define('TX_TER_RESULT_ERRORS_OCCURRED', '10001');

define('TX_TER_RESULT_EXTENSIONKEYALREADYEXISTS', '10500');
define('TX_TER_RESULT_EXTENSIONKEYDOESNOTEXIST', '10501');
define('TX_TER_RESULT_EXTENSIONKEYNOTVALID', '10502');
define('TX_TER_RESULT_EXTENSIONKEYSUCCESSFULLYREGISTERED', '10503');
define('TX_TER_RESULT_EXTENSIONSUCCESSFULLYUPLOADED', '10504');
define('TX_TER_RESULT_EXTENSIONSUCCESSFULLYDELETED', '10505');

/**
 * TYPO3 Extension Repository, helper functions
 *
 * @author    Robert Lemke <robert@typo3.org>
 */
class tx_ter_helper
{
    protected $pluginObj;

    /**
     * Constructor
     *
     * @param    object $pluginObj : Reference to parent object
     * @access    public
     */
    public function __construct($pluginObj)
    {
        $this->pluginObj = $pluginObj;
    }

    /**
     * This verifies the given fe_users username/password.
     * Either the fe_user row is returned or an exception is thrown.
     *
     * @param    object $accountData : Account data information with username, password and upload password
     * @return    mixed        If success, returns array of fe_users, otherwise error string.
     * @access    public
128
     * @throws \T3o\Ter\Exception\UnauthorizedException
129 130 131 132
     */
    public function getValidUser($accountData)
    {
        if (!strlen($accountData->username) || (!strlen($accountData->password))) {
133
            throw new \T3o\Ter\Exception\UnauthorizedException('No user or no password submitted.', TX_TER_ERROR_GENERAL_NOUSERORPASSWORD);
134 135
        }

136
        $res = $this->getDatabaseConnection()->exec_SELECTquery(
Markus Sommer's avatar
Markus Sommer committed
137 138
            '*',
            'fe_users',
139
            'username=' . $this->getDatabaseConnection()->fullQuoteStr($accountData->username, 'fe_users') . $this->getTyposcriptFrontendObject()->sys_page->enableFields('fe_users')
140 141
        );

142
        if ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
143 144
            if (!$this->userIsAlreadyLoggedIn(
                $accountData
Markus Sommer's avatar
Markus Sommer committed
145 146
                ) && !$this->ldapValidationSucceeded($accountData)
            ) {
147
                throw new \T3o\Ter\Exception\UnauthorizedException('Wrong password.', TX_TER_ERROR_GENERAL_WRONGPASSWORD);
148 149
            }
        } else {
150
            throw new \T3o\Ter\Exception\UnauthorizedException('The specified user does not exist. You need to login first on extensions.typo3.org.', TX_TER_ERROR_GENERAL_USERNOTFOUND);
151 152
        }

153
        $row['admin'] = $this->userIsAdmin($row['usergroup']) || $this->userIsSecurityTeamMember($row['usergroup']);
154 155 156 157

        return $row;
    }

158 159 160 161 162 163
    /**
     * @param string $userGroupList
     * @return bool
     */
    private function userIsAdmin(string $userGroupList): bool
    {
Thomas Löffler's avatar
Thomas Löffler committed
164
        return $this->pluginObj->conf['adminFrontendUsergroupUid'] > 0 && GeneralUtility::inList($userGroupList, (int)$this->pluginObj->conf['adminFrontendUsergroupUid']);
165 166 167 168 169 170 171 172
    }

    /**
     * @param string $userGroupList
     * @return bool
     */
    private function userIsSecurityTeamMember(string $userGroupList): bool
    {
Thomas Löffler's avatar
Thomas Löffler committed
173
        return $this->pluginObj->conf['securityTeamFrontendUsergroupUid'] > 0 && GeneralUtility::inList($userGroupList, (int)$this->pluginObj->conf['securityTeamFrontendUsergroupUid']);
174 175
    }

176 177 178 179 180 181 182 183 184 185
    /**
     * We check whether a user is logged in by TYPO3
     * because of a sent session cookie
     *
     * @param $accountData
     * @return bool
     */
    private function userIsAlreadyLoggedIn($accountData)
    {
        /** @var \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController $tsfe */
Thomas Löffler's avatar
Thomas Löffler committed
186
        $tsfe = $GLOBALS['TSFE'];
187 188 189 190 191 192 193
        if (!empty($tsfe->fe_user->user['username']) && $accountData->username === $tsfe->fe_user->user['username']) {
            return true;
        }

        return false;
    }

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    /**
     * Check if LDAP authenticates the credentials
     *
     * @param stdClass $accountData
     * @return bool
     */
    private function ldapValidationSucceeded(stdClass $accountData): bool
    {
        if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('ig_ldap_sso_auth')) {
            return false;
        }

        /** @var \Causal\IgLdapSsoAuth\Domain\Repository\ConfigurationRepository $configurationRepository */
        $configurationRepository = GeneralUtility::makeInstance(\Causal\IgLdapSsoAuth\Domain\Repository\ConfigurationRepository::class);
        $configurationRecords = $configurationRepository->findAll();

        \Causal\IgLdapSsoAuth\Library\Configuration::initialize('fe', $configurationRecords[0]);

        return (bool)\Causal\IgLdapSsoAuth\Library\Authentication::ldapAuthenticate($accountData->username, $accountData->password);
    }

215 216 217 218 219
    /**
     * Checks for correct account data without throwing an exception.
     * It just returns TRUE / FALSE
     *
     * @param  object $accountData
220
     * @return bool
221 222 223 224 225 226 227
     */
    public function checkValidUser($accountData)
    {
        if (!strlen($accountData->username) || (!strlen($accountData->password))) {
            $success = false;
        } else {
            $success = false;
228
            $res = $this->getDatabaseConnection()->exec_SELECTquery(
Markus Sommer's avatar
Markus Sommer committed
229 230 231 232 233
                '*',
                'fe_users',
                'username=' . $this->getDatabaseConnection()->fullQuoteStr(
                    $accountData->username,
                    'fe_users'
234 235 236
                ) . $GLOBALS['TSFE']->sys_page->enableFields('fe_users')
            );

237
            if ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
238
                if ($this->ldapValidationSucceeded($accountData)
Markus Sommer's avatar
Markus Sommer committed
239
                ) {
240 241 242
                    $success = true;
                }
            }
243
            $this->getDatabaseConnection()->sql_free_result($res);
244 245 246 247 248 249 250 251 252 253 254
        }

        return $success;
    }

    /**
     * Checks if the given extension key is unique and not registered yet.
     * Takes underscores into account, so the key "ter_ter" can't be registered
     * if "te_rt_er" or "terter" already exist.
     *
     * @param    string $extensionKey : The extension key to check
255
     * @return    bool        Returns TRUE if the extension key is unique and not used yet, otherwise FALSE
256 257 258 259 260 261 262 263
     * @access    public
     * @author  Elmar Hinz
     */
    public function extensionKeyIsAvailable($extensionKey)
    {
        $cleanedExtensionKey = str_replace('_', '', $extensionKey);
        $isAvailable = true;

264
        $res = $this->getDatabaseConnection()->exec_SELECTquery(
Markus Sommer's avatar
Markus Sommer committed
265 266 267
            'extensionkey',
            'tx_ter_extensionkeys',
            'pid=' . intval($this->pluginObj->extensionsPID)
268
        );
269
        while ($row = $this->getDatabaseConnection()->sql_fetch_row($res)) {
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
            if ($cleanedExtensionKey === str_replace('_', '', $row[0])) {
                $isAvailable = false;
            }
        }

        return $isAvailable;
    }

    /**
     * Based on $extKey this returns the extension-key record.
     *
     * @param    string $extKey : Extension key
     * @return    mixed        The extension key row or FALSE
     * @access    public
     */
    public function getExtensionKeyRecord($extKey)
    {
287 288 289 290 291 292
        $row = $this->getDatabaseConnection()->exec_SELECTgetSingleRow(
            '*',
            'tx_ter_extensionkeys',
            'extensionkey=' . $this->getDatabaseConnection()->fullQuoteStr($extKey, 'tx_ter_extensionkeys') .
            'AND pid=' . intval($this->pluginObj->extensionsPID) .
            $this->getTyposcriptFrontendObject()->sys_page->enableFields('tx_ter_extensionkeys')
293 294
        );

295
        return $row;
296 297 298 299 300 301 302 303 304 305 306 307 308 309
    }

    /**
     * Searches the repository for the highest version number of an upload of the
     * extension specified by $extensionKey. If no upload was found at all, FALSE
     * will be returned. If at least one upload was found, the highest version number
     * following the format major.minor.dev (eg. 4.2.1) will be returned.
     *
     * @param    string $extKey : Extension key
     * @return    mixed        The version number as a string or FALSE
     * @access    public
     */
    public function getLatestVersionNumberOfExtension($extensionKey)
    {
310
        $res = $this->getDatabaseConnection()->exec_SELECTquery(
Markus Sommer's avatar
Markus Sommer committed
311 312 313
            'version',
            'tx_ter_extensions',
            'extensionkey=' . $this->getDatabaseConnection()->fullQuoteStr($extensionKey, 'tx_ter_extensions') . '
314 315 316
				AND pid=' . intval($this->pluginObj->extensionsPID)
        );
        $latestVersion = false;
317
        while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
            if (version_compare($row['version'], $latestVersion, '>')) {
                $latestVersion = $row['version'];
            }
        }

        return $latestVersion;
    }

    /**
     * Sets a flag so the cron job knows that the extensions.xml.gz file has to be
     * regenerated. Call this whenever data has changed which also exists in
     * extensions.xml.gz
     *
     * Note: Depending on the cron job it might take a while until the index file really
     *       has been updated. See "cli/build-extension-index.php" for more information
     *
     * @access    public
     */
    public function requestUpdateOfExtensionIndexFile()
    {
        GeneralUtility::writeFile(
            $this->pluginObj->repositoryDir . 'extensions.xml.gz.needsupdate',
            'Dear cron-job. The extensions.xml.gz file needs to be regenerated, please do so as soon as you find the time for it.' . chr(
                10
            ) . 'Thanks, your TER helper class'
        );
    }

    /**
     * Updates the "extensions.xml" file which contains an index of all uploaded
     * extensions in the TER.
     *
     * @access    public
351
     * @throws \T3o\Ter\Exception\InternalServerErrorException
352 353 354 355 356
     */
    public function writeExtensionIndexfile()
    {
        GeneralUtility::devLog('writing extension index!', 'tx_ter_helper', 0);
        if (!@is_dir($this->pluginObj->repositoryDir)) {
357
            throw new \T3o\Ter\Exception\InternalServerErrorException(
Markus Sommer's avatar
Markus Sommer committed
358 359
                'Extension repository directory does not exist.',
                TX_TER_ERROR_GENERAL_EXTREPDIRDOESNTEXIST
360 361 362
            );
        }

363 364 365 366 367 368
        // Check if update of files requested
        $updateRequestedFile = $this->pluginObj->repositoryDir . 'extensions.xml.gz.needsupdate';
        if (@filemtime($updateRequestedFile) <= @filemtime($this->pluginObj->repositoryDir . 'extensions.xml.gz')) {
            return;
        }

369 370
        $trackTime = microtime();

371
        $res = $this->getDatabaseConnection()->exec_SELECTquery(
372
            'uid,tstamp,extensionkey,version,title,description,state,reviewstate,category,downloadcounter,t3xfilemd5',
Markus Sommer's avatar
Markus Sommer committed
373 374
            'tx_ter_extensions',
            '1'
375 376 377 378
        );
        // Read the extension records from the DB:
        $extensionsAndVersionsArr = [];
        $extensionsTotalDownloadsArr = [];
379 380
        while ($row = $this->getDatabaseConnection()->sql_fetch_assoc($res)) {
            $res2 = $this->getDatabaseConnection()->exec_SELECTquery(
Markus Sommer's avatar
Markus Sommer committed
381 382
                'ownerusername,downloadcounter',
                'tx_ter_extensionkeys',
383
                'extensionkey=' . $this->getDatabaseConnection()->fullQuoteStr($row['extensionkey'], 'tx_ter_extensionkeys')
384
            );
385
            $extensionKeyRow = $this->getDatabaseConnection()->sql_fetch_assoc($res2);
386 387 388
            $row['ownerusername'] = $extensionKeyRow['ownerusername'];
            $extensionsTotalDownloadsArr[$row['extensionkey']] = $extensionKeyRow['downloadcounter'];

389
            $res2 = $this->getDatabaseConnection()->exec_SELECTquery(
390
                'lastuploaddate,uploadcomment,dependencies,composerinfo,authorname,authoremail,authorcompany',
Markus Sommer's avatar
Markus Sommer committed
391 392
                'tx_ter_extensiondetails',
                'extensionuid=' . (int)$row['uid']
393
            );
394
            $detailsRow = $this->getDatabaseConnection()->sql_fetch_assoc($res2);
395 396 397 398 399 400
            if (is_array($detailsRow)) {
                $row = $row + $detailsRow;
            }
            $extensionsAndVersionsArr [$row['extensionkey']]['versions'][$row['version']] = $row;
        }
        // Prepare the DOM object:
Markus Sommer's avatar
Markus Sommer committed
401
        $dom = new DOMDocument('1.0', 'utf-8');
402 403 404 405 406 407
        $dom->formatOutput = true;
        $extensionsObj = $dom->appendChild(new DOMElement('extensions'));

        // Create the nested XML structure:
        foreach ($extensionsAndVersionsArr as $extensionKey => $extensionVersionsArr) {
            $extensionObj = $extensionsObj->appendChild(new DOMElement('extension'));
Markus Sommer's avatar
Markus Sommer committed
408
            $extensionObj->appendChild(new DOMAttr('extensionkey', $extensionKey));
409
            $extensionObj->appendChild(
Markus Sommer's avatar
Markus Sommer committed
410 411 412
                new DOMElement(
                    'downloadcounter',
                    $this->xmlentities($extensionsTotalDownloadsArr[$extensionKey])
413 414 415 416 417
                )
            );

            foreach ($extensionVersionsArr['versions'] as $versionNumber => $extensionVersionArr) {
                $versionObj = $extensionObj->appendChild(new DOMElement('version'));
Markus Sommer's avatar
Markus Sommer committed
418
                $versionObj->appendChild(new DOMAttr('version', $versionNumber));
419 420 421 422 423
                $versionObj->appendChild(new DOMElement('title', $this->xmlentities($extensionVersionArr['title'])));
                $versionObj->appendChild(new DOMElement('description', $this->xmlentities($extensionVersionArr['description'])));
                $versionObj->appendChild(new DOMElement('state', $this->xmlentities($extensionVersionArr['state'])));
                $versionObj->appendChild(new DOMElement('reviewstate', intval($extensionVersionArr['reviewstate'])));
                $versionObj->appendChild(new DOMElement('category', $this->xmlentities($extensionVersionArr['category'])));
424
                if ($extensionVersionArr['category'] === 'distribution') {
425 426 427 428 429 430 431 432 433 434
                    $prefixPathOnServer = PATH_site . 'fileadmin/ter/';
                    $prefixDistributionFilePath = $extensionKey[0] . '/' . $extensionKey[1] . '/' . $extensionKey . '_' . $versionNumber . '_';
                    $distributionImage = $prefixDistributionFilePath . 'Distribution.png';
                    $distributionWelcomeImage = $prefixDistributionFilePath . 'DistributionWelcome.png';
                    if (is_file($prefixPathOnServer . $distributionImage)) {
                        $versionObj->appendChild(new DOMElement('distributionImage', $this->xmlentities($distributionImage)));
                    }
                    if (is_file($prefixPathOnServer . $distributionWelcomeImage)) {
                        $versionObj->appendChild(new DOMElement('distributionImageWelcome', $this->xmlentities($distributionWelcomeImage)));
                    }
435
                }
436 437
                $versionObj->appendChild(
                    new DOMElement(
Markus Sommer's avatar
Markus Sommer committed
438 439
                        'downloadcounter',
                        $this->xmlentities($extensionVersionArr['downloadcounter'])
440 441 442 443 444
                    )
                );
                $versionObj->appendChild(new DOMElement('lastuploaddate', $extensionVersionArr['lastuploaddate']));
                $versionObj->appendChild(
                    new DOMElement(
Markus Sommer's avatar
Markus Sommer committed
445 446
                        'uploadcomment',
                        $this->xmlentities($extensionVersionArr['uploadcomment'])
447 448 449 450 451 452 453 454
                    )
                );
                $versionObj->appendChild(new DOMElement('dependencies', $extensionVersionArr['dependencies']));
                $versionObj->appendChild(new DOMElement('composerinfo', $extensionVersionArr['composerinfo']));
                $versionObj->appendChild(new DOMElement('authorname', $this->xmlentities($extensionVersionArr['authorname'])));
                $versionObj->appendChild(new DOMElement('authoremail', $this->xmlentities($extensionVersionArr['authoremail'])));
                $versionObj->appendChild(
                    new DOMElement(
Markus Sommer's avatar
Markus Sommer committed
455 456
                        'authorcompany',
                        $this->xmlentities($extensionVersionArr['authorcompany'])
457 458 459 460
                    )
                );
                $versionObj->appendChild(
                    new DOMElement(
Markus Sommer's avatar
Markus Sommer committed
461 462
                        'ownerusername',
                        $this->xmlentities($extensionVersionArr['ownerusername'])
463 464 465 466 467 468
                    )
                );
                $versionObj->appendChild(new DOMElement('t3xfilemd5', $extensionVersionArr['t3xfilemd5']));
            }
        }

469
        $extensionsObj->appendChild(new DOMComment('Index created at ' . date('D M j G:i:s T Y')));
470 471 472 473 474
        $extensionsObj->appendChild(new DOMComment('Index created in ' . (microtime() - $trackTime) . ' ms'));

        // Write XML data to disk:
        $fh = fopen($this->pluginObj->repositoryDir . 'new-extensions.xml.gz', 'wb');
        if (!$fh) {
475
            throw new \T3o\Ter\Exception\InternalServerErrorException(
476 477 478 479 480 481 482 483 484
                'Write error while writing extensions index file: ' . $this->pluginObj->repositoryDir . 'extensions.xml',
                TX_TER_ERROR_UPLOADEXTENSION_WRITEERRORWHILEWRITINGEXTENSIONSINDEX
            );
        }
        fwrite($fh, gzencode($dom->saveXML(), 9));
        fclose($fh);

        if (!@filesize($this->pluginObj->repositoryDir . 'new-extensions.xml.gz') > 0) {
            GeneralUtility::devLog('Newly created extension index is zero bytes!', 'tx_ter_helper', 0);
485
            throw new \T3o\Ter\Exception\InternalServerErrorException(
486 487 488 489 490 491 492 493
                'Write error while writing extensions index file (zero bytes): ' . $this->pluginObj->repositoryDir . 'extensions.xml',
                TX_TER_ERROR_UPLOADEXTENSION_WRITEERRORWHILEWRITINGEXTENSIONSINDEX
            );
        }

        @unlink($this->pluginObj->repositoryDir . 'extensions.xml.gz');
        rename($this->pluginObj->repositoryDir . 'new-extensions.xml.gz', $this->pluginObj->repositoryDir . 'extensions.xml.gz');
        GeneralUtility::writeFile(
Markus Sommer's avatar
Markus Sommer committed
494 495
            $this->pluginObj->repositoryDir . 'extensions.md5',
            md5_file($this->pluginObj->repositoryDir . 'extensions.xml.gz')
496 497 498 499 500
        );

        // Write serialized array file to disk:
        $fh = fopen($this->pluginObj->repositoryDir . 'new-extensions.bin', 'wb');
        if (!$fh) {
501
            throw new \T3o\Ter\Exception\InternalServerErrorException(
502 503 504 505 506 507 508 509 510
                'Write error while writing extensions index file: ' . $this->pluginObj->repositoryDir . 'extensions.bin',
                TX_TER_ERROR_UPLOADEXTENSION_WRITEERRORWHILEWRITINGEXTENSIONSINDEX
            );
        }
        fwrite($fh, serialize($extensionsAndVersionsArr));
        fclose($fh);

        if (!@filesize($this->pluginObj->repositoryDir . 'new-extensions.bin') > 0) {
            GeneralUtility::devLog('Newly created extension index is zero bytes!', 'tx_ter_helper', 0);
511
            throw new \T3o\Ter\Exception\InternalServerErrorException(
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
                'Write error while writing extensions index file (zero bytes): ' . $this->pluginObj->repositoryDir . 'extensions.bin',
                TX_TER_ERROR_UPLOADEXTENSION_WRITEERRORWHILEWRITINGEXTENSIONSINDEX
            );
        }

        @unlink($this->pluginObj->repositoryDir . 'extensions.bin');
        rename($this->pluginObj->repositoryDir . 'new-extensions.bin', $this->pluginObj->repositoryDir . 'extensions.bin');
    }

    /**
     * Equivalent to htmlentities but for XML content
     *
     * @param    string $string : String to encode
     * @return    string        &,",',< and > replaced by entities
     * @access    public
     */
    public function xmlentities($string)
    {
        // Until I have found a better solution for guaranteeing valid characters, I use this regex:
531
        $string = (preg_replace('/[^\w\s"%&\[\]\(\)\.\,\;\:\/\?\{\}!\$\-\/\@]/u', '', $string));
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551

        return str_replace(['&', '"', "'", '<', '>'], ['&amp;', '&quot;', '&apos;', '&lt;', '&gt;'], $string);
    }

    /***
     * Load an instance of the BE_USER to use with TCEFORM
     *
     * @param integer $uid UID of the virtual user
     * @param string $username Username
     * @param boolean $isAdmin Set admin rights
     * @return void
     */
    public function loadBackendUser($uid, $username, $isAdmin = false)
    {
        if (!empty($GLOBALS['BE_USER'])) {
            return;
        }

        $GLOBALS['BE_USER'] = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\FrontendBackendUserAuthentication::class);
        $GLOBALS['BE_USER']->user = [
552
            'uid' => 0,
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
            'username' => $username,
            'admin' => (int)$isAdmin,
        ];
    }

    /**
     * Load an instance of the LANG object
     *
     * @param string $language Used language ident
     */
    public function loadLang($lang = 'default')
    {
        if (!empty($GLOBALS['LANG'])) {
            return;
        }

569
        $GLOBALS['LANG'] = GeneralUtility::makeInstance(\TYPO3\CMS\Lang\LanguageService::class);
570 571
        $GLOBALS['LANG']->init($lang);
    }
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587

    /**
     * @return \TYPO3\CMS\Core\Database\DatabaseConnection
     */
    private function getDatabaseConnection()
    {
        return $GLOBALS['TYPO3_DB'];
    }

    /**
     * @return \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
     */
    private function getTyposcriptFrontendObject()
    {
        return $GLOBALS['TSFE'];
    }
588
}