ExtensionIndexService.php 10.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

declare(strict_types = 1);

/*
 * This file is part of TYPO3 CMS-extension "ter_fe2", created by Benni Mack.
 *
 * 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.
 */

namespace T3o\TerFe2\Service;

use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
17
use T3o\Ter\Api\Configuration;
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
use T3o\Ter\Exception\InternalServerErrorException;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * TYPO3 installations usually fetch a extensions.xml.gzip file, and this file is responsible for generating this
 * file if the data is provided properly.
 *
 * This is currently the XML logic (based on ext-dom) but this could be modified to be used for JSON as well.
 */
class ExtensionIndexService implements LoggerAwareInterface
{
    use LoggerAwareTrait;

    /**
     * @var string
     */
    protected $basePath;

    public function __construct(string $basePath = null)
    {
        if ($basePath === null) {
39
40
41
            $this->basePath = $this->getRepositoryBasePath();
        } else {
            $this->basePath = rtrim($basePath, '/') . '/';
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
128
129
130
131
132
133
134
135
136
137
        }
    }

    /**
     * Creates the extensions.xml.gz file in a safe manner
     *
     * @param \DOMDocument $dom
     * @return string the newly created filename
     * @throws InternalServerErrorException
     */
    public function writeXmlToFile(\DOMDocument $dom): string
    {
        // Write XML data to disk:
        $fh = fopen($this->basePath . 'new-extensions.xml.gz', 'wb');
        if (!$fh) {
            throw new InternalServerErrorException(
                'Write error while writing extensions index file: ' . $this->basePath . 'extensions.xml'
            );
        }
        fwrite($fh, gzencode($dom->saveXML(), 9));
        fclose($fh);

        if (!@filesize($this->basePath . 'new-extensions.xml.gz') > 0) {
            $this->logger->error('Newly created extension index is zero bytes!');
            throw new InternalServerErrorException(
                'Write error while writing extensions index file (zero bytes): ' . $this->basePath . 'extensions.xml'
            );
        }

        @unlink($this->basePath . 'extensions.xml.gz');
        rename($this->basePath . 'new-extensions.xml.gz', $this->basePath . 'extensions.xml.gz');
        GeneralUtility::writeFile($this->basePath . 'extensions.md5', md5_file($this->basePath . 'extensions.xml.gz'));
        return $this->basePath . 'extensions.xml.gz';
    }

    /**
     * Write serialized array file to disk. Question is: WHY should we do this?
     *
     * @param array $extensionsAndVersionsArr
     * @return string the absolute file that was created.
     * @throws InternalServerErrorException
     */
    public function writeSerializedExtensionInformationToFile(array $extensionsAndVersionsArr): string
    {
        $fh = fopen($this->basePath . 'new-extensions.bin', 'wb');
        if (!$fh) {
            throw new InternalServerErrorException(
                'Write error while writing extensions index file: ' . $this->basePath . 'extensions.bin'
            );
        }
        fwrite($fh, serialize($extensionsAndVersionsArr));
        fclose($fh);

        if (!@filesize($this->basePath . 'new-extensions.bin') > 0) {
            $this->logger->debug('Newly created extension index is zero bytes!');
            throw new InternalServerErrorException(
                'Write error while writing extensions index file (zero bytes): ' . $this->basePath . 'extensions.bin'
            );
        }

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

    /**
     * Build DOM structure for the XML to output.
     *
     * @param array $extensionsAndVersionsArr
     * @param string $processStarted
     * @return \DOMDocument
     */
    public function compileXmlStructure(array $extensionsAndVersionsArr, string $processStarted): \DOMDocument
    {
        // Prepare the DOM object:
        $dom = new \DOMDocument('1.0', 'utf-8');
        $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'));
            $extensionObj->appendChild(new \DOMAttr('extensionkey', $extensionKey));
            $extensionObj->appendChild(
                new \DOMElement(
                    'downloadcounter',
                    $this->xmlentities((string)($extensionVersionsArr['downloads'] ?? '0'))
                )
            );

            foreach ($extensionVersionsArr['versions'] as $versionNumber => $extensionVersionArr) {
                $versionObj = $extensionObj->appendChild(new \DOMElement('version'));
                $versionObj->appendChild(new \DOMAttr('version', (string)$versionNumber));
                $versionObj->appendChild(new \DOMElement('title', $this->xmlentities((string)$extensionVersionArr['title'])));
                $versionObj->appendChild(new \DOMElement('description', $this->xmlentities((string)$extensionVersionArr['description'])));
                $versionObj->appendChild(new \DOMElement('state', $this->xmlentities((string)$extensionVersionArr['state'])));
138
139
                $versionObj->appendChild(new \DOMElement('reviewstate', (string)$extensionVersionArr['review_state']));
                $versionObj->appendChild(new \DOMElement('category', $this->xmlentities((string)$extensionVersionArr['em_category'])));
140
141
142
143
144
145
146
147
148
149
150
151
152
153
                if ($extensionVersionArr['category'] === 'distribution') {
                    $prefixDistributionFilePath = $extensionKey[0] . '/' . $extensionKey[1] . '/' . $extensionKey . '_' . $versionNumber . '_';
                    $distributionImage = $prefixDistributionFilePath . 'Distribution.png';
                    $distributionWelcomeImage = $prefixDistributionFilePath . 'DistributionWelcome.png';
                    if (is_file($this->basePath . $distributionImage)) {
                        $versionObj->appendChild(new \DOMElement('distributionImage', $this->xmlentities($distributionImage)));
                    }
                    if (is_file($this->basePath . $distributionWelcomeImage)) {
                        $versionObj->appendChild(new \DOMElement('distributionImageWelcome', $this->xmlentities($distributionWelcomeImage)));
                    }
                }
                $versionObj->appendChild(
                    new \DOMElement(
                        'downloadcounter',
154
                        $this->xmlentities((string)$extensionVersionArr['download_counter'])
155
156
                    )
                );
157
                $versionObj->appendChild(new \DOMElement('lastuploaddate', (string)$extensionVersionArr['upload_date']));
158
159
160
                $versionObj->appendChild(
                    new \DOMElement(
                        'uploadcomment',
161
                        $this->xmlentities((string)$extensionVersionArr['upload_comment'])
162
163
                    )
                );
164
                $versionObj->appendChild(new \DOMElement('dependencies', $this->serializeDependencies($extensionVersionArr['dependencies'])));
165
                $versionObj->appendChild(new \DOMElement('composerinfo', (string)$extensionVersionArr['composer_info']));
166
167
168
169
170
171
172
173
174
175
176
                $versionObj->appendChild(new \DOMElement('authorname', $this->xmlentities((string)$extensionVersionArr['authorname'])));
                $versionObj->appendChild(new \DOMElement('authoremail', $this->xmlentities((string)$extensionVersionArr['authoremail'])));
                $versionObj->appendChild(
                    new \DOMElement(
                        'authorcompany',
                        $this->xmlentities((string)$extensionVersionArr['authorcompany'])
                    )
                );
                $versionObj->appendChild(
                    new \DOMElement(
                        'ownerusername',
177
                        $this->xmlentities((string)$extensionVersionsArr['frontend_user'])
178
179
                    )
                );
180
                $versionObj->appendChild(new \DOMElement('t3xfilemd5', (string)$extensionVersionArr['file_hash']));
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
                $versionObj->appendChild(new \DOMElement('documentation_link', (string)$extensionVersionArr['external_manual'] ?: ''));
            }
        }

        $extensionsObj->appendChild(new \DOMComment('Index created at ' . date('D M j G:i:s T Y')));
        $extensionsObj->appendChild(new \DOMComment('Index created in ' . (microtime() - $processStarted) . ' ms'));
        return $dom;
    }

    /**
     * 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.
     */
    public function requestUpdate()
    {
        GeneralUtility::writeFile(
            $this->basePath . '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'
        );
    }

    public function isOldUpdateRequested(): bool
    {
        // Check if update of files requested
        $updateRequestedFile = $this->basePath . 'extensions.xml.gz.needsupdate';
        if (file_exists($updateRequestedFile) && @filemtime($updateRequestedFile) <= @filemtime($this->basePath . 'extensions.xml.gz')) {
            return true;
        }
        return false;
    }

    /**
     * Equivalent to htmlentities but for XML content
     *
     * @param    string $string : String to encode
     * @return    string        &,",',< and > replaced by entities
     */
    protected function xmlentities(string $string): string
    {
        // Until I have found a better solution for guaranteeing valid characters, I use this regex:
        $string = (preg_replace('/[^\w\s"%&\[\]\(\)\.\,\;\:\/\?\{\}!\$\-\/\@]/u', '', $string));
        return str_replace(['&', '"', "'", '<', '>'], ['&amp;', '&quot;', '&apos;', '&lt;', '&gt;'], $string);
    }

    protected function getRepositoryBasePath(): string
    {
231
        return GeneralUtility::makeInstance(Configuration::class)->getRepositoryBasePath();
232
    }
233

Oliver Bartsch's avatar
Oliver Bartsch committed
234
    protected function serializeDependencies(?string $dependencies): string
235
236
237
238
239
    {
        return $dependencies !== null
            ? (string)serialize(json_decode($dependencies, true))
            : '';
    }
240
}