ExtensionController.php 27.1 KB
Newer Older
speedprogs_de's avatar
speedprogs_de committed
1
<?php
2
3
namespace T3o\TerFe2\Controller;

4
5
/*
 * This file is part of the TYPO3 CMS project.
6
 *
7
8
9
 * 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.
10
 *
11
12
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
15
 * The TYPO3 project - inspiring people to share!
 */
16

17
use T3o\Ter\Api\ApiUser;
18
use T3o\Ter\Api\ExtensionKey;
19
use T3o\Ter\Api\ExtensionVersion;
20
use T3o\TerFe2\Domain\Model\Extension;
21
use T3o\TerFe2\Domain\Repository\DownloadRepository;
22
use T3o\TerFe2\Provider\FileProvider;
23
use T3o\TerFe2\Utility\ExtensionUtility;
24
use T3o\TerFe2\Utility\VersionUtility;
25
use T3o\TerFe2\Validation\Validator\ComposerNameValidator;
26
use TYPO3\CMS\Core\Page\PageRenderer;
27
use TYPO3\CMS\Core\Utility\GeneralUtility;
Stefan Froemken's avatar
Stefan Froemken committed
28

29
30
31
/**
 * Controller for the extension object
 */
32
class ExtensionController extends \T3o\TerFe2\Controller\AbstractController
33
34
{
    /**
35
     * @var \T3o\TerFe2\Domain\Repository\ExtensionRepository
36
37
38
39
     */
    protected $extensionRepository;

    /**
40
     * @var \T3o\TerFe2\Domain\Repository\TagRepository
41
42
43
44
     */
    protected $tagRepository;

    /**
45
     * @var \T3o\TerFe2\Domain\Repository\VersionRepository
46
47
48
     */
    protected $versionRepository;

Stefan Froemken's avatar
Stefan Froemken committed
49
    /**
Thomas Löffler's avatar
Thomas Löffler committed
50
     * @var \T3o\TerFe2\Domain\Repository\FrontendUserRepository
Stefan Froemken's avatar
Stefan Froemken committed
51
52
53
     */
    protected $ownerRepository;

54
55
56
57
58
    /**
     * @var \T3o\TerFe2\Domain\Repository\DomainRepository
     */
    protected $downloadRepository;

59
    /**
60
     * @var \T3o\TerFe2\Persistence\Session
61
62
63
64
     */
    protected $session;

    /**
65
     * @var \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager
66
67
68
69
     */
    protected $persistenceManager;

    /**
Stefan Froemken's avatar
Stefan Froemken committed
70
     * @var array
71
     */
Stefan Froemken's avatar
Stefan Froemken committed
72
    protected $frontendUser;
73
74

    /**
Stefan Froemken's avatar
Stefan Froemken committed
75
76
77
     * inject extensionRepository
     *
     * @param \T3o\TerFe2\Domain\Repository\ExtensionRepository $extensionRepository
78
     */
Stefan Froemken's avatar
Stefan Froemken committed
79
80
81
82
    public function injectExtensionRepository(\T3o\TerFe2\Domain\Repository\ExtensionRepository $extensionRepository)
    {
        $this->extensionRepository = $extensionRepository;
    }
83
84

    /**
Stefan Froemken's avatar
Stefan Froemken committed
85
     * inject tagRepository
86
     *
Stefan Froemken's avatar
Stefan Froemken committed
87
     * @param \T3o\TerFe2\Domain\Repository\TagRepository $tagRepository
88
     */
Stefan Froemken's avatar
Stefan Froemken committed
89
    public function injectTagRepository(\T3o\TerFe2\Domain\Repository\TagRepository $tagRepository)
90
    {
Stefan Froemken's avatar
Stefan Froemken committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
        $this->tagRepository = $tagRepository;
    }

    /**
     * inject versionRepository
     *
     * @param \T3o\TerFe2\Domain\Repository\VersionRepository $versionRepository
     */
    public function injectVersionRepository(\T3o\TerFe2\Domain\Repository\VersionRepository $versionRepository)
    {
        $this->versionRepository = $versionRepository;
    }

    /**
     * inject ownerRepository
     *
Thomas Löffler's avatar
Thomas Löffler committed
107
     * @param \T3o\TerFe2\Domain\Repository\FrontendUserRepository $ownerRepository
Stefan Froemken's avatar
Stefan Froemken committed
108
     */
Thomas Löffler's avatar
Thomas Löffler committed
109
    public function injectOwnerRepository(\T3o\TerFe2\Domain\Repository\FrontendUserRepository $ownerRepository)
Stefan Froemken's avatar
Stefan Froemken committed
110
111
112
    {
        $this->ownerRepository = $ownerRepository;
    }
113

114
115
116
117
118
    public function injectDownloadRepository(\T3o\TerFe2\Domain\Repository\DownloadRepository $downloadRepository)
    {
        $this->downloadRepository = $downloadRepository;
    }

Stefan Froemken's avatar
Stefan Froemken committed
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    /**
     * inject session
     *
     * @param \T3o\TerFe2\Persistence\Session $session
     */
    public function injectSession(\T3o\TerFe2\Persistence\Session $session)
    {
        $this->session = $session;
    }

    /**
     * inject persistenceManager
     *
     * @param \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager $persistenceManager
     */
    public function injectPersistenceManager(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager $persistenceManager)
    {
        $this->persistenceManager = $persistenceManager;
    }

    /**
     * Initializes this object after all injects were done
     */
    protected function initializeObject()
    {
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
        // Show insecure extensions only for reviewers
        $this->extensionRepository->setShowInsecure($this->securityRole->isReviewer());
        $this->versionRepository->setShowInsecure($this->securityRole->isReviewer());
    }

    /**
     * List latest action, displays new and updated extensions
     *
     * Note: Required for RSS / JSON output
     */
    public function listLatestAction()
    {
        $latestCount = (!empty($this->settings['latestCount']) ? $this->settings['latestCount'] : 20);
        $extensions = $this->extensionRepository->findLatest($latestCount);
        if ($extensions->count() > 0) {
            $this->updateSysLastChanged($extensions[0]->getLastVersion()->getUploadDate());
        }
        $this->view->assign('extensions', $extensions);
    }

    /**
     * Action that displays a single extension
     *
167
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension to display
168
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("extension")
169
     */
170
    public function showAction(\T3o\TerFe2\Domain\Model\Extension $extension = null)
171
    {
172
173
        if ($extension === null || !$extension instanceof \T3o\TerFe2\Domain\Model\Extension) {
            $GLOBALS['TSFE']->pageNotFoundAndExit('Extension not found!');
174
        }
175
        $owner = [];
176
        if ($extension instanceof \T3o\TerFe2\Domain\Model\Extension and $extension->getFrontendUser()) {
177
178
179
            $querySettings = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings::class);
            $querySettings->setRespectStoragePage(false);
            $this->ownerRepository->setDefaultQuerySettings($querySettings);
180
181
182
            $owner = $this->ownerRepository->findOneByUsername($extension->getFrontendUser());
        }
        $versionHistoryCount = (!empty($this->settings['versionHistoryCount']) ? $this->settings['versionHistoryCount'] : 5);
Markus Sommer's avatar
Markus Sommer committed
183
        $skipLatestVersion = (isset($this->settings['skipLatestVersion']) ? $this->settings['skipLatestVersion'] : true);
184

185
186
187
188
        if ($extension !== null
            && $extension instanceof \T3o\TerFe2\Domain\Model\Extension
            && $extension->getLastVersion() instanceof \T3o\TerFe2\Domain\Model\Version
        ) {
189
190
191
192
            $versionHistory = $this->versionRepository->getVersionHistory($extension, $versionHistoryCount, $skipLatestVersion);
            $this->view->assign('owner', $owner);
            $this->view->assign('extension', $extension);
            $this->view->assign('versionHistory', $versionHistory);
193
            $this->view->assign('extensionDownloads', $this->downloadRepository->findDownloadsByExtensionkey($extension->getExtKey()));
194

195
196
            /** @var \T3o\TerFe2\Service\DocumentationService $documentationService */
            $documentationService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\T3o\TerFe2\Service\DocumentationService::class);
197
            $documentationLink = $documentationService->getDocumentationLink($extension->getExtKey(), $extension->getLastVersion()->getVersionString(), true);
198
199
            $this->view->assign('documentationLink', $documentationLink);

200
201
202
            /** @var PageRenderer $pageRenderer */
            $pageRenderer = $this->objectManager->get(PageRenderer::class);
            $pageRenderer->setMetaTag('name', 'description', htmlspecialchars($extension->getLastVersion()->getDescription()));
203
            if ($extension->getTags()->count() > 0) {
204
                $pageRenderer->setMetaTag('name', 'keywords', htmlspecialchars(implode(',', $extension->getTags()->toArray())));
205
206
207
208
            }

            // gets all other extensions from the owner
            $this->extensionRepository->setDefaultOrderings(
209
                [
210
                    'lastVersion.uploadDate' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING
211
                ]
212
213
214
            );
            $otherExtensionsByUser = $this->extensionRepository->findAllOtherFromFrontendUser($extension, $extension->getFrontendUser());
            $this->view->assign('extensionsByUser', $otherExtensionsByUser);
Thomas Löffler's avatar
Thomas Löffler committed
215
216
217
218
219

            if ($GLOBALS['TSFE'] && $GLOBALS['TSFE']->loginUser) {
                $currentUser = $this->ownerRepository->findByUid((int)$GLOBALS['TSFE']->fe_user->user['uid']);
                if ($currentUser instanceof \T3o\TerFe2\Domain\Model\FrontendUser) {
                    $this->view->assign('hasLiked', $currentUser->getLikedExtensions()->contains($extension));
220
                    $this->view->assign('notification', $currentUser->getNotifiedExtensions()->contains($extension));
Thomas Löffler's avatar
Thomas Löffler committed
221
222
                }
            }
223
224
225
226
227

            $metaTagManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\MetaTag\MetaTagManagerRegistry::class)->getManagerForProperty('og:title');
            $metaTagManager->addProperty('og:title', $extension->getLastVersion()->getTitle() . ' (' . $extension->getExtKey() . ')');
            $metaTagManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\MetaTag\MetaTagManagerRegistry::class)->getManagerForProperty('og:description');
            $metaTagManager->addProperty('og:description', $extension->getLastVersion()->getDescription());
228
            $metaTagManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\MetaTag\MetaTagManagerRegistry::class)->getManagerForProperty('og:image');
229
            $metaTagManager->addProperty('og:image', $this->getOGImageUrl($extension));
230

231
            $GLOBALS['TSFE']->page['title'] = 'TYPO3 Extension \'' . $extension->getLastVersion()->getTitle() . '\' (' . $extension->getExtKey() . ')';
232
233
234
235
236
237
        }
    }

    /**
     * Displays a form to edit an existing extension
     *
238
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension to display
239
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("extension")
240
     */
241
    public function editAction(\T3o\TerFe2\Domain\Model\Extension $extension)
242
243
244
245
246
247
248
249
250
251
    {
        $extensionOwner = $this->ownerRepository->findByUid($GLOBALS['TSFE']->fe_user->user['uid']);
        if ($this->securityRole->isAdmin()
            || $extension->getFrontendUser() == $extensionOwner->getUsername()
        ) {
            $this->view->assign('isLoggedIn', 1);
            $this->view->assign('extension', $extension);
        }
    }

252
253
254
255
256
257
258
259
260
261
262
263
    public function initializeUpdateAction()
    {
        if (!$this->request->hasArgument('packagistConfirm')) {
            return;
        }
        ComposerNameValidator::$composerNameIsConfirmed = (bool)$this->request->getArgument('packagistConfirm');
        if (!ComposerNameValidator::$composerNameIsConfirmed) {
            $extensionProperties = $this->request->getArgument('extension');
            $extensionProperties['composerName'] = '';
            $this->request->setArgument('extension', $extensionProperties);
        }
    }
264
265
266
267

    /**
     * Updates an existing extension
     *
268
     * @param \T3o\TerFe2\Domain\Model\Extension $extension extension to update
269
270
     * @param string $tag
     * @param string $save
271
     *
272
     * @TYPO3\CMS\Extbase\Annotation\Validate("\T3o\TerFe2\Validation\Validator\ExtensionArgumentValidator", param="extension")
273
     */
274
    public function updateAction(\T3o\TerFe2\Domain\Model\Extension $extension, $tag = '', $save = '')
275
    {
276
        /** @var \TYPO3\CMS\Extbase\Domain\Model\FrontendUser $currentUser */
277
278
279
280
281
282
283
284
285
        $currentUser = $this->ownerRepository->findByUid($GLOBALS['TSFE']->fe_user->user['uid']);
        if ($extension->getFrontendUser() !== $currentUser->getUsername()) {
            $this->redirectWithError(
                'You are not the owner of the extension you wanted to update.',
                'index',
                'Registerkey'
            );
        }
        if (!empty($tag)) {
286
            $tags = [];
Markus Sommer's avatar
Markus Sommer committed
287
            $intermediateTags = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(' ', $tag, true);
288
289
290
291
292
293
294
295
            foreach ($intermediateTags as $tag) {
                $tag = trim($tag, ',');
                if (!empty($tag)) {
                    $tags[] = $tag;
                }
            }
            $tags = array_unique($tags);
            foreach ($tags as $tag) {
296
                /** @var \T3o\TerFe2\Domain\Model\Tag $newTag */
297
                $newTag = $this->tagRepository->findByTitle($tag)->getFirst();
Markus Sommer's avatar
Markus Sommer committed
298
                if ($newTag !== null) {
299
300
301
302
303
304
                    if (!$extension->getTags()->contains($newTag)) {
                        $extension->addTag($newTag);
                    } else {
                        continue;
                    }
                } else {
305
                    $newTag = $this->objectManager->get(\T3o\TerFe2\Domain\Model\Tag::class);
306
307
308
                    $newTag->setTitle($tag);
                    $extension->addTag($newTag);
                }
309
                $this->addFlashMessage('Tag "' . htmlspecialchars($tag) . '" added to extension');
310
311
312
313
314
315
316
317
            }
        }
        $this->extensionRepository->update($extension);
        if (!empty($save)) {
            $this->redirectWithMessage(
                $this->translate('msg.extension_updated'),
                'edit',
                '',
318
                \TYPO3\CMS\Core\Messaging\FlashMessage::OK,
319
                'Extension',
Markus Sommer's avatar
Markus Sommer committed
320
                null,
321
                ['extension' => $extension]
322
323
324
325
326
327
            );
        } else {
            $this->redirectWithMessage(
                $this->translate('msg.extension_updated'),
                'index',
                '',
328
                \TYPO3\CMS\Core\Messaging\FlashMessage::OK,
329
330
331
332
333
334
                'Registerkey'
            );
        }
    }

    /**
335
336
     * @param \T3o\TerFe2\Domain\Model\Extension $extension
     * @param \T3o\TerFe2\Domain\Model\Tag $tag
337
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("extension")
338
     */
339
    public function removeTagAction(\T3o\TerFe2\Domain\Model\Extension $extension, \T3o\TerFe2\Domain\Model\Tag $tag)
340
341
342
    {
        if ($extension->getTags()->contains($tag)) {
            $extension->removeTag($tag);
343
            $this->extensionRepository->update($extension);
344
345
346
347
348
        }
        $this->redirectWithMessage(
            'Tag "' . htmlspecialchars($tag->getTitle()) . '" was removed',
            'edit',
            '',
349
            \TYPO3\CMS\Core\Messaging\FlashMessage::OK,
350
            'Extension',
Markus Sommer's avatar
Markus Sommer committed
351
            null,
352
            ['extension' => $extension]
353
354
355
356
357
358
        );
    }

    /**
     * Deletes an existing extension and all versions
     *
359
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension to delete
360
     */
361
    public function deleteAction(\T3o\TerFe2\Domain\Model\Extension $extension)
362
363
364
365
366
367
368
369
    {
        $this->extensionRepository->remove($extension);
        $this->redirectWithMessage($this->translate('msg.extension_deleted'), 'index');
    }

    /**
     * Check file hash, increment download counter and send file to client browser
     *
370
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension object
371
372
     * @param string $versionString An existing version string
     * @param string $format Format of the file output
373
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("extension")
374
     * @throws \Exception
375
     */
376
    public function downloadAction(\T3o\TerFe2\Domain\Model\Extension $extension, $versionString = '', $format = '')
377
    {
378
379
        $downloadSource = VersionUtility::DOWNLOAD_SOURCE_TER;

380
381
        if ($format === '') {
            $format = 'zip';
382
383
        }
        if ($format !== 't3x' && $format !== 'zip') {
384
            throw new \Exception('A download action for the format "' . $format . '" is not implemented');
385
        }
386
387
388
        if ($versionString === '') {
            $versionString = $extension->getLastVersion()->getVersionString();
        }
389
390
391

        $version = $this->versionRepository->findOneByExtensionAndVersionString($extension, $versionString);
        if (!$version) {
392
            $this->redirectWithMessage($this->translate('msg.version_not_found'), 'show', '', \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, null, null, ['extension' => $extension]);
393
394
395
        }

        // Get file path
396
        $provider = GeneralUtility::makeInstance(FileProvider::class);
397
398
399
400
401
402
403
        $fileUrl = $provider->getFileUrl($version, $format);

        if ($format === 'zip') {
            // If ZIP does not exist, create it
            if ($fileUrl === '') {
                $t3xFileUrl = $provider->getFileUrl($version, 't3x');
                $zipFileUrl = str_replace('.t3x', '.zip', $t3xFileUrl);
404
405
406
                \T3o\TerFe2\Utility\ArchiveUtility::convertT3xToZip(
                    \T3o\TerFe2\Utility\FileUtility::getAbsolutePathFromUrl($t3xFileUrl),
                    \T3o\TerFe2\Utility\FileUtility::getAbsolutePathFromUrl($zipFileUrl)
407
408
409
                );

                // update ZIP filesize
410
                $version->setZipFileSize(filesize(\T3o\TerFe2\Utility\FileUtility::getAbsolutePathFromUrl($zipFileUrl)));
411
412
413
414
415
416
417
418
                $this->versionRepository->update($version);
                $this->persistenceManager->persistAll();

                $fileUrl = $zipFileUrl;
            }
        }

        // Check if file exists
419
        if (empty($fileUrl) || !\T3o\TerFe2\Utility\FileUtility::fileExists($fileUrl)) {
420
            $this->redirectWithMessage($this->translate('msg.file_not_found') . ': ' . basename($fileUrl), 'show', '', \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, null, null, ['extension' => $extension]);
421
422
423
424
        }

        // Check file hash of t3x packages
        if ($format === 't3x') {
425
            $downloadSource = VersionUtility::DOWNLOAD_SOURCE_EM;
426
            $fileHash = \T3o\TerFe2\Utility\FileUtility::getFileHash($fileUrl);
427
            if ($fileHash != $version->getFileHash()) {
428
                $this->redirectWithMessage($this->translate('msg.file_hash_not_equal'), 'show', '', \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, null, null, ['extension' => $extension]);
429
430
431
432
433
434
435
436
            }
        }

        // Check session if user has already downloaded this file today
        if (!empty($this->settings['countDownloads'])) {
            $extensionKey = $extension->getExtKey();
            $downloads = $this->session->get('downloads');
            if (empty($downloads) || !in_array($extensionKey, $downloads)) {
437
                VersionUtility::updateVersionCounter($extensionKey, $version->getUid(), $downloadSource);
438
439
440
441
442
443
444
445

                // Add extension key to session
                $downloads[] = $extensionKey;
                $this->session->add('downloads', $downloads);
            }
        }

        // Send file to browser
446
        if (!\T3o\TerFe2\Utility\FileUtility::transferFile($fileUrl)) {
447
            $this->redirectWithMessage($this->translate('msg.could_not_transfer_file'), 'show', '', \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, null, null, ['extension' => $extension]);
448
449
450
        }

        // Fallback
451
        $this->redirect('show', null, null, ['extension' => $extension]);
452
453
454
455
456
    }

    /**
     * Show upload form for a new extension version
     *
457
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension object
458
     * @param array $form Form information for the new version
459
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("extension")
460
     */
461
    public function uploadVersionAction(\T3o\TerFe2\Domain\Model\Extension $extension, array $form = [])
462
    {
463
        if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('ter')) {
464
            $this->addFlashMessage($this->translate('msq.createVersionTerNotLoaded'));
465
466
467
468
469
470
471
472
        }
        $this->view->assign('extension', $extension);
        $this->view->assign('form', $form);
    }

    /**
     * Create new version of an extension
     *
473
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension object
474
     * @param array $form Form information for the new version
475
     * @TYPO3\CMS\Extbase\Annotation\IgnoreValidation("extension")
476
     */
477
    public function createVersionAction(\T3o\TerFe2\Domain\Model\Extension $extension, array $form)
478
    {
479
        $this->frontendUser = (!empty($GLOBALS['TSFE']->fe_user->user) ? $GLOBALS['TSFE']->fe_user->user : []);
480
481
482
483
        if (!$form['gplCompliant']) {
            $this->forwardWithError($this->translate('msg.acceptGPL'), 'uploadVersion');
        }

484
        if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('ter')) {
485
486
487
488
489
490
491
492
            $this->forwardWithError($this->translate('msg.createVersionTerNotLoaded'), 'uploadVersion');
        }
        if (empty($this->frontendUser['username'])) {
            $this->forwardWithError($this->translate('msg.createVersionNotLoggedIn'), 'uploadVersion');
        }
        if (empty($form['comment'])) {
            $this->forwardWithError($this->translate('msg.createVersionCommentEmpty'), 'uploadVersion');
        }
493
        $fileInfo = \T3o\TerFe2\Utility\FileUtility::getFileInfo('tx_terfe2_pi1.form.file');
494
495
496
497
498
499
        if (empty($fileInfo) || empty($fileInfo['tmp_name']) || $fileInfo['error'] != UPLOAD_ERR_OK) {
            $this->forwardWithError($this->translate('msg.createVersionFileEmpty'), 'uploadVersion');
        }
        if (empty($fileInfo['name']) || substr($fileInfo['name'], -3) !== 'zip') {
            $this->forwardWithError($this->translate('msg.createVersionFileNoZip'), 'uploadVersion');
        }
500
        $files = [];
501
        try {
502
            $extensionInfo = \T3o\TerFe2\Utility\ArchiveUtility::getExtensionDetailsFromZipArchive($fileInfo['tmp_name'], $files);
503
        } catch (\Exception $exception) {
504
            $this->forwardWithError('Error ' . $exception->getCode() . ': ' . $exception->getMessage(), 'uploadVersion');
505
506
507
508
509
510
511
512
513
514
515
516
        }
        unlink($fileInfo['tmp_name']);
        if (empty($extensionInfo->version)) {
            $this->forwardWithError($this->translate('msg.createVersionVersionEmpty'), 'uploadVersion');
        }
        $extensionKey = preg_replace('/_(\d+)(\.|\-)(\d+)(\.|\-)(\d+).*/i', '', strtolower($fileInfo['name']));
        if ($extensionKey !== $extension->getExtKey()) {
            $this->forwardWithError($this->translate('msg.createVersionFilenameNotValid'), 'uploadVersion');
        }
        if (!$this->userIsAllowedToUploadExtension($extensionKey)) {
            $this->forwardWithError($this->translate('msg.createVersionUploadNotAllowed'), 'uploadVersion');
        }
517
518
519
520
        $extensionKeyObject = new ExtensionKey($extensionKey);
        $extensionVersion = new ExtensionVersion($extensionKeyObject, $extensionInfo->version);

        if ($extensionVersion->doesExtensionVersionExist()) {
521
522
523
524
525
            $this->forwardWithError($this->translate('msg.createVersionVersionExists'), 'uploadVersion');
        }
        $extensionInfo->extensionKey = $extensionKey;
        $extensionInfo->infoData->uploadComment = $form['comment'];
        try {
526
527
528
529
530
            // Use the API to upload the file as t3x file
            // This code will be reworked into a full-blown API
            $uploader = new ApiUser($this->frontendUser['username']);
            $uploader->authenticate();
            $extensionVersion->upload($uploader, $extensionInfo, $files);
531
            $this->redirect('index', 'Registerkey', null, ['uploaded' => true], $this->settings['pages']['manageKeysPID']);
532
        } catch (\Exception $exception) {
533
            $this->forwardWithError('Error ' . $exception->getCode() . ': ' . $exception->getMessage(), 'uploadVersion');
534
535
536
537
        }
        $this->forwardWithError($this->translate('msg.createVersionUploadFailed'), 'uploadVersion');
    }

Thomas Löffler's avatar
Thomas Löffler committed
538
539
540
541
542
543
544
    /**
     * @param \T3o\TerFe2\Domain\Model\Extension $extension
     * @return bool
     */
    public function likeAction(\T3o\TerFe2\Domain\Model\Extension $extension)
    {
        $liked = false;
545
546
547
548
549
550
        $currentUser = $this->getLoggedInUser();
        if ($currentUser instanceof \T3o\TerFe2\Domain\Model\FrontendUser) {
            $currentUser->addLikedExtension($extension);
            $this->ownerRepository->update($currentUser);
            $this->extensionRepository->update($extension);
            $liked = true;
Thomas Löffler's avatar
Thomas Löffler committed
551
552
553
554
555
556
557
558
        }

        return json_encode($liked);
    }

    public function disLikeAction(\T3o\TerFe2\Domain\Model\Extension $extension)
    {
        $disliked = false;
559
560
561
562
563
564
        $currentUser = $this->getLoggedInUser();
        if ($currentUser instanceof \T3o\TerFe2\Domain\Model\FrontendUser) {
            $currentUser->removeLikedExtension($extension);
            $this->ownerRepository->update($currentUser);
            $this->extensionRepository->update($extension);
            $disliked = true;
Thomas Löffler's avatar
Thomas Löffler committed
565
566
567
568
569
        }

        return json_encode($disliked);
    }

570
571
572
    public function activateNotificationAction(\T3o\TerFe2\Domain\Model\Extension $extension): string
    {
        $notified = false;
573
574
575
576
577
578
        $currentUser = $this->getLoggedInUser();
        if ($currentUser instanceof \T3o\TerFe2\Domain\Model\FrontendUser) {
            $currentUser->addNotifiedExtension($extension);
            $this->ownerRepository->update($currentUser);
            $this->extensionRepository->update($extension);
            $notified = true;
579
580
581
582
583
584
585
586
        }

        return json_encode($notified);
    }

    public function deactivateNotificationAction(\T3o\TerFe2\Domain\Model\Extension $extension): string
    {
        $unnotified = false;
587
588
589
590
591
592
        $currentUser = $this->getLoggedInUser();
        if ($currentUser instanceof \T3o\TerFe2\Domain\Model\FrontendUser) {
            $currentUser->removeNotifiedExtension($extension);
            $this->ownerRepository->update($currentUser);
            $this->extensionRepository->update($extension);
            $unnotified = true;
593
594
595
596
597
        }

        return json_encode($unnotified);
    }

598
599
600
    /**
     * Check if current frontend user can upload given extension
     *
601
     * There is no better (and faster) way to do this at the moment.
602
603
     *
     * @param string $extensionKey The extension key
604
     * @return bool TRUE if upload is allowed
605
     */
606
    protected function userIsAllowedToUploadExtension($extensionKey): bool
607
    {
608
        $this->frontendUser = (!empty($GLOBALS['TSFE']->fe_user->user) ? $GLOBALS['TSFE']->fe_user->user : []);
609
        if (empty($this->frontendUser['username'])) {
Markus Sommer's avatar
Markus Sommer committed
610
            return false;
611
        }
612

613
614
615
616
617
618
        // Let's use a proper API in the future here.
        $extensionKeyObject = GeneralUtility::makeInstance(ExtensionKey::class, $extensionKey);
        if (strtolower($extensionKeyObject->getOwner()) === strtolower($this->frontendUser['username'])) {
            return true;
        }
        return false;
619
620
    }

621
622
623
624
625
626
627
628
629
630
631
632
    /**
     * @return \T3o\TerFe2\Domain\Model\FrontendUser|null
     */
    protected function getLoggedInUser(): ?\T3o\TerFe2\Domain\Model\FrontendUser
    {
        if ($GLOBALS['TSFE'] && $GLOBALS['TSFE']->fe_user && $GLOBALS['TSFE']->fe_user->user) {
            return $this->ownerRepository->findByUid((int)$GLOBALS['TSFE']->fe_user->user['uid']);
        }

        return null;
    }

633
634
    /**
     * sets SYS_LASTCHANGED to this date if it is newer than the currently set
635
     * @param int $dateTime
636
637
638
639
640
641
642
643
644
645
     */
    protected function updateSysLastChanged($dateTime)
    {
        if ($dateTime instanceof \DateTime) {
            $dateTime = $dateTime->getTimestamp();
        }
        if ($GLOBALS['TSFE']->register['SYS_LASTCHANGED'] < $dateTime) {
            $GLOBALS['TSFE']->register['SYS_LASTCHANGED'] = $dateTime;
        }
    }
646
647
648
649
650
651

    /**
     * @return \Psr\Http\Message\UriInterface|string
     */
    private function getBaseUrl()
    {
652
653
654
655
656
657
658
659
660
        return (string)GeneralUtility::makeInstance(\TYPO3\CMS\Core\Site\SiteFinder::class)->getSiteByPageId($GLOBALS['TSFE']->id)->getBase();
    }

    /**
     * @return string
     */
    private function getOGImageUrl(Extension $extension): string
    {
        return $this->getBaseUrl() . '/' . ExtensionUtility::getExtensionIcon($extension->getExtKey(), $extension->getLastVersion()->getVersionString());
661
    }
662
}