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

4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*******************************************************************
 *  Copyright notice
 *
 *  (c) 2011 Kai Vogel <kai.vogel@speedprogs.de>, Speedprogs.de
 *
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as
 *  published by the Free Software Foundation; either version 2 of
 *  the License, or (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ******************************************************************/

/**
 * Controller for the extension object
 */
31
class ExtensionController extends \T3o\TerFe2\Controller\AbstractController
32
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\AuthorRepository
46
47
48
49
     */
    protected $authorRepository;

    /**
50
     * @var \T3o\TerFe2\Domain\Repository\VersionRepository
51
52
53
54
     */
    protected $versionRepository;

    /**
55
     * @var \T3o\TerFe2\Provider\ProviderManager
56
57
58
59
     */
    protected $providerManager;

    /**
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;

    /**
70
     * @var \TYPO3\CMS\Extbase\Domain\Repository\FrontendUserRepository
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
     */
    protected $ownerRepository;

    /**
     * @var array
     */
    protected $frontendUser;

    /**
     * Initializes the controller
     *
     * @return void
     */
    protected function initializeController()
    {
86
87
88
89
        $this->extensionRepository = $this->objectManager->get(\T3o\TerFe2\Domain\Repository\ExtensionRepository::class);
        $this->tagRepository = $this->objectManager->get(\T3o\TerFe2\Domain\Repository\TagRepository::class);
        $this->versionRepository = $this->objectManager->get(\T3o\TerFe2\Domain\Repository\VersionRepository::class);
        $this->authorRepository = $this->objectManager->get(\T3o\TerFe2\Domain\Repository\AuthorRepository::class);
90
        $this->ownerRepository = $this->objectManager->get(\TYPO3\CMS\Extbase\Domain\Repository\FrontendUserRepository::class);
91
92
93
        $querySettings = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface::class);
        $querySettings->setRespectStoragePage(false);
        $this->ownerRepository->setDefaultQuerySettings($querySettings);
94
95
        $this->providerManager = $this->objectManager->get(\T3o\TerFe2\Provider\ProviderManager::class);
        $this->session = $this->objectManager->get(\T3o\TerFe2\Persistence\Session::class);
96
        $this->persistenceManager = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class);
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181

        // Show insecure extensions only for reviewers
        $this->extensionRepository->setShowInsecure($this->securityRole->isReviewer());
        $this->versionRepository->setShowInsecure($this->securityRole->isReviewer());

        $this->frontendUser = (!empty($GLOBALS['TSFE']->fe_user->user) ? $GLOBALS['TSFE']->fe_user->user : array());
    }

    /**
     * Index action, displays extension list (USER)
     *
     * @return void
     * @dontvalidate $search
     */
    public function indexAction()
    {
        $this->searchAction();
    }


    /**
     * search action (USER_INT)
     *
     * @param array $search Search params for extension list
     * @param array $restoreSearch Restore last search from session
     * @return void
     * @dontvalidate $search
     */
    public function searchAction(array $search = array(), $restoreSearch = FALSE)
    {
        // Get extension list
        if (!empty($this->settings['show']['extensionSearch'])) {
            $this->view->assign('extensions', $this->getExtensions($search, $restoreSearch));
            $this->view->assign('search', $search);
        } else {
            $this->view->assign('extensions', $this->extensionRepository->findAll());
        }

        // Get all tags
        if (!empty($this->settings['show']['tagOverview'])) {
            $tags = $this->tagRepository->findAll();
            $this->view->assign('tags', $tags);
        }

        // Get authors
        if (!empty($this->settings['show']['authorOverview'])) {
            $authors = $this->authorRepository->findByLatestExtensionVersion();
            $this->view->assign('authors', $authors);
        }
    }


    /**
     * List action, displays all extensions
     *
     * Note: Required for RSS / JSON output
     *
     * @return void
     */
    public function listAction()
    {
        $this->view->assign('extensions', $this->extensionRepository->findAll());
    }


    /**
     * List latest action, displays new and updated extensions
     *
     * Note: Required for RSS / JSON output
     *
     * @return void
     */
    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
     *
182
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension to display
183
184
     * @param string $extensionKey Extension key
     * @return void
185
186
     *
     * @ignorevalidation $extension
187
     */
188
    public function showAction(\T3o\TerFe2\Domain\Model\Extension $extension = NULL, $extensionKey = NULL)
189
190
191
    {
        if (!empty($extensionKey)) {
            if (!is_string($extensionKey)) {
192
                throw new \Exception('No valid extension key given');
193
194
195
196
            }
            $extension = $this->extensionRepository->findOneByExtKey($extensionKey);
        }
        $owner = array();
197
        if ($extension instanceof \T3o\TerFe2\Domain\Model\Extension and $extension->getFrontendUser()) {
198
199
200
201
202
            $owner = $this->ownerRepository->findOneByUsername($extension->getFrontendUser());
        }
        $versionHistoryCount = (!empty($this->settings['versionHistoryCount']) ? $this->settings['versionHistoryCount'] : 5);
        $skipLatestVersion = (isset($this->settings['skipLatestVersion']) ? $this->settings['skipLatestVersion'] : TRUE);

203
        if ($extension !== NULL && $extension instanceof \T3o\TerFe2\Domain\Model\Extension) {
204
205
206
207
208
            $versionHistory = $this->versionRepository->getVersionHistory($extension, $versionHistoryCount, $skipLatestVersion);
            $this->view->assign('owner', $owner);
            $this->view->assign('extension', $extension);
            $this->view->assign('versionHistory', $versionHistory);

209
            /** @var \T3o\TerFe2\Service\Documentation $documentationService */
Thomas Löffler's avatar
Thomas Löffler committed
210
211
            $documentationService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\T3o\TerFe2\Service\Documentation::class);
            $documentationLink = $documentationService->getDocumentationLink($extension->getExtKey(), $extension->getLastVersion()->getVersionString());
212
213
            $this->view->assign('documentationLink', $documentationLink);

214
215
            $pageRenderer = $this->objectManager->get(\TYPO3\CMS\Core\Page\PageRenderer::class);
            $pageRenderer->addMetaTag('<meta name="description" content="' . htmlspecialchars($extension->getLastVersion()->getDescription()) . '" />');
216
            if ($extension->getTags()->count() > 0) {
217
                $pageRenderer->addMetaTag('<meta name="keywords" content="' . htmlspecialchars(implode(',', $extension->getTags()->toArray())) . '" />');
218
219
220
221
222
            }

            // gets all other extensions from the owner
            $this->extensionRepository->setDefaultOrderings(
                array(
223
                    'lastVersion.uploadDate' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING
224
225
226
227
228
229
230
231
232
233
234
235
                )
            );
            $otherExtensionsByUser = $this->extensionRepository->findAllOtherFromFrontendUser($extension, $extension->getFrontendUser());
            $this->view->assign('extensionsByUser', $otherExtensionsByUser);

            // flattr check
            if ($extension->getFlattrUsername() !== '') {
                // build flattr url with "auto-submit"
                $url = 'https://flattr.com/submit/auto?';
                // adds username
                $url .= '&user_id=' . urlencode($extension->getFlattrUsername());
                // adds current url
236
                /** @var \TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder $uriBuilder */
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
                $uriBuilder = $this->controllerContext->getUriBuilder();
                $uriBuilder->setArguments(
                    array(
                        'tx_terfe2_pi1' => array(
                            'action' => 'show',
                            'extension' => $extension->getUid()
                        )
                    )
                );
                $uriBuilder->setCreateAbsoluteUri(TRUE);
                $url .= '&url=' . urlencode($uriBuilder->buildFrontendUri());
                // adds title
                $url .= '&title=' . urlencode($extension->getLastVersion()->getTitle());
                // adds description
                $url .= '&description=' . urlencode($extension->getLastVersion()->getDescription());
                // adds language
                $url .= '&language=en_GB';
                // adds tags
                // @todo maybe add extension tags from user?
                $url .= '&tags=';
                // adds hidden tag
                $url .= '&hidden=0';

                $this->view->assign('flattrUrl', $url);
            }
        }


    }


    /**
     * Displays a form for creating a new extension
     *
271
     * @param \T3o\TerFe2\Domain\Model\Extension $newExtension New extension object
272
273
274
     * @return void
     * @dontvalidate $newExtension
     */
275
    public function newAction(\T3o\TerFe2\Domain\Model\Extension $newExtension = NULL)
276
277
278
279
280
281
282
283
284
    {
        $this->view->assign('newExtension', $newExtension);
        $this->view->assign('tags', $this->tagRepository->findAll());
    }


    /**
     * Creates a new extension
     *
285
     * @param \T3o\TerFe2\Domain\Model\Extension $newExtension New extension object
286
287
     * @return void
     */
288
    public function createAction(\T3o\TerFe2\Domain\Model\Extension $newExtension)
289
290
291
292
293
294
295
296
297
    {
        $this->extensionRepository->add($newExtension);
        $this->redirectWithMessage($this->translate('msg.extension_created'), 'index');
    }


    /**
     * Displays a form to edit an existing extension
     *
298
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension to display
299
300
301
     * @dontvalidate $extension
     * @return void
     */
302
    public function editAction(\T3o\TerFe2\Domain\Model\Extension $extension)
303
304
305
306
307
308
309
310
311
312
313
314
315
316
    {
        $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);
        }
    }


    /**
     * Updates an existing extension
     *
317
     * @param \T3o\TerFe2\Domain\Model\Extension $extension extension to update
318
319
320
321
     * @param string $tag
     * @param string $save
     * @return void
     */
322
    public function updateAction(\T3o\TerFe2\Domain\Model\Extension $extension, $tag = '', $save = '')
323
    {
324
        /** @var \TYPO3\CMS\Extbase\Domain\Model\FrontendUser $currentUser */
325
326
327
328
329
330
331
332
333
334
        $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)) {
            $tags = array();
335
            $intermediateTags = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(' ', $tag, TRUE);
336
337
338
339
340
341
342
343
            foreach ($intermediateTags as $tag) {
                $tag = trim($tag, ',');
                if (!empty($tag)) {
                    $tags[] = $tag;
                }
            }
            $tags = array_unique($tags);
            foreach ($tags as $tag) {
344
                /** @var \T3o\TerFe2\Domain\Model\Tag $newTag */
345
346
347
348
349
350
351
352
                $newTag = $this->tagRepository->findByTitle($tag)->getFirst();
                if ($newTag !== NULL) {
                    if (!$extension->getTags()->contains($newTag)) {
                        $extension->addTag($newTag);
                    } else {
                        continue;
                    }
                } else {
353
                    $newTag = $this->objectManager->get(\T3o\TerFe2\Domain\Model\Tag::class);
354
355
356
                    $newTag->setTitle($tag);
                    $extension->addTag($newTag);
                }
357
                $this->addFlashMessage('Tag "' . htmlspecialchars($tag) . '" added to extension');
358
359
360
361
362
363
364
365
            }
        }
        $this->extensionRepository->update($extension);
        if (!empty($save)) {
            $this->redirectWithMessage(
                $this->translate('msg.extension_updated'),
                'edit',
                '',
366
                \TYPO3\CMS\Core\Messaging\FlashMessage::OK,
367
368
369
370
371
372
373
374
375
                'Extension',
                NULL,
                array('extension' => $extension)
            );
        } else {
            $this->redirectWithMessage(
                $this->translate('msg.extension_updated'),
                'index',
                '',
376
                \TYPO3\CMS\Core\Messaging\FlashMessage::OK,
377
378
379
380
381
382
                'Registerkey'
            );
        }
    }

    /**
383
384
     * @param \T3o\TerFe2\Domain\Model\Extension $extension
     * @param \T3o\TerFe2\Domain\Model\Tag $tag
385
386
387
     *
     * @return void
     */
388
    public function removeTagAction(\T3o\TerFe2\Domain\Model\Extension $extension, \T3o\TerFe2\Domain\Model\Tag $tag)
389
390
391
    {
        if ($extension->getTags()->contains($tag)) {
            $extension->removeTag($tag);
392
            $this->extensionRepository->update($extension);
393
394
395
396
397
        }
        $this->redirectWithMessage(
            'Tag "' . htmlspecialchars($tag->getTitle()) . '" was removed',
            'edit',
            '',
398
            \TYPO3\CMS\Core\Messaging\FlashMessage::OK,
399
400
401
402
403
404
405
406
407
408
            'Extension',
            NULL,
            array('extension' => $extension)
        );
    }


    /**
     * Deletes an existing extension and all versions
     *
409
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension to delete
410
411
     * @return void
     */
412
    public function deleteAction(\T3o\TerFe2\Domain\Model\Extension $extension)
413
414
415
416
417
418
419
420
421
    {
        $this->extensionRepository->remove($extension);
        $this->redirectWithMessage($this->translate('msg.extension_deleted'), 'index');
    }


    /**
     * Check file hash, increment download counter and send file to client browser
     *
422
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension object
423
424
     * @param string $versionString An existing version string
     * @param string $format Format of the file output
425
     * @ignorevalidation $extension
426
427
     * @return void
     */
428
    public function downloadAction(\T3o\TerFe2\Domain\Model\Extension $extension, $versionString, $format)
429
430
431
432
433
    {
        if (!$format) {
            $format = 't3x';
        }
        if ($format !== 't3x' && $format !== 'zip') {
434
            throw new \Exception('A download action for the format "' . $format . '" is not implemented');
435
436
437
438
        }

        $version = $this->versionRepository->findOneByExtensionAndVersionString($extension, $versionString);
        if (!$version) {
439
            $this->redirectWithMessage($this->translate('msg.version_not_found'), 'show', '', \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, NULL, NULL, array('extension' => $extension));
440
441
442
443
444
445
446
447
448
449
450
        }

        // Get file path
        $provider = $this->providerManager->getProvider($version->getExtensionProvider());
        $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);
451
452
453
                \T3o\TerFe2\Utility\Archive::convertT3xToZip(
                    \T3o\TerFe2\Utility\File::getAbsolutePathFromUrl($t3xFileUrl),
                    \T3o\TerFe2\Utility\File::getAbsolutePathFromUrl($zipFileUrl)
454
455
456
                );

                // update ZIP filesize
457
                $version->setZipFileSize(filesize(\T3o\TerFe2\Utility\File::getAbsolutePathFromUrl($zipFileUrl)));
458
459
460
461
462
463
464
465
                $this->versionRepository->update($version);
                $this->persistenceManager->persistAll();

                $fileUrl = $zipFileUrl;
            }
        }

        // Check if file exists
466
        if (empty($fileUrl) || !\T3o\TerFe2\Utility\File::fileExists($fileUrl)) {
467
            $this->redirectWithMessage($this->translate('msg.file_not_found') . ': ' . basename($fileUrl), 'show', '', \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, NULL, NULL, array('extension' => $extension));
468
469
470
471
        }

        // Check file hash of t3x packages
        if ($format === 't3x') {
472
            $fileHash = \T3o\TerFe2\Utility\File::getFileHash($fileUrl);
473
            if ($fileHash != $version->getFileHash()) {
474
                $this->redirectWithMessage($this->translate('msg.file_hash_not_equal'), 'show', '', \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, NULL, NULL, array('extension' => $extension));
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
            }
        }

        // 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)) {
                // Add +1 to download counter and save immediately
                $version->incrementDownloadCounter();
                $this->persistenceManager->persistAll();

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

        // Send file to browser
494
        if (!\T3o\TerFe2\Utility\File::transferFile($fileUrl)) {
495
            $this->redirectWithMessage($this->translate('msg.could_not_transfer_file'), 'show', '', \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, NULL, NULL, array('extension' => $extension));
496
497
498
499
500
501
502
503
504
505
        }

        // Fallback
        $this->redirect('index');
    }


    /**
     * Show upload form for a new extension version
     *
506
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension object
507
508
     * @param array $form Form information for the new version
     * @return void
509
     * @ignorevalidation $extension
510
     */
511
    public function uploadVersionAction(\T3o\TerFe2\Domain\Model\Extension $extension, array $form = array())
512
    {
513
        if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('ter')) {
514
            $this->addFlashMessage($this->translate('msq.createVersionTerNotLoaded'));
515
516
517
518
519
520
521
522
        }
        $this->view->assign('extension', $extension);
        $this->view->assign('form', $form);
    }

    /**
     * Create new version of an extension
     *
523
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension object
524
525
     * @param array $form Form information for the new version
     * @return void
526
     * @ignorevalidation $extension
527
     */
528
    public function createVersionAction(\T3o\TerFe2\Domain\Model\Extension $extension, array $form)
529
530
531
532
533
    {
        if (!$form['gplCompliant']) {
            $this->forwardWithError($this->translate('msg.acceptGPL'), 'uploadVersion');
        }

534
        if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('ter')) {
535
536
537
538
539
540
541
542
            $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');
        }
543
        $fileInfo = \T3o\TerFe2\Utility\File::getFileInfo('tx_terfe2_pi1.form.file');
544
545
546
547
548
549
550
551
        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');
        }
        $files = array();
        try {
552
            $extensionInfo = \T3o\TerFe2\Utility\Archive::getExtensionDetailsFromZipArchive($fileInfo['tmp_name'], $files);
553
        } catch (\Exception $exception) {
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
            $this->forwardWithError($exception->getMessage(), 'uploadVersion');
        }
        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');
        }
        if (!$this->versionIsPossibleForExtension($extensionKey, $extensionInfo->version)) {
            $this->forwardWithError($this->translate('msg.createVersionVersionExists'), 'uploadVersion');
        }
        $extensionInfo->extensionKey = $extensionKey;
        $extensionInfo->infoData->uploadComment = $form['comment'];
        $filesData = (object)array('fileData' => $files);
        try {
574
            $result = \tx_ter_api::uploadExtensionWithoutSoap($this->frontendUser['username'], $extensionInfo, $filesData);
575
576
577
            if ($result) {
                $this->redirect('index', 'Registerkey', NULL, array('uploaded' => TRUE), $this->settings['pages']['manageKeysPID']);
            }
578
        } catch (\Exception $exception) {
579
580
581
582
583
584
585
586
587
588
589
            $this->forwardWithError($exception->getMessage(), 'uploadVersion');
        }
        $this->forwardWithError($this->translate('msg.createVersionUploadFailed'), 'uploadVersion');
    }


    /**
     * Returns all / filtered extensions
     *
     * @param array $options Options for extension list
     * @param array $restoreSearch Restore last search from session
590
     * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage Objects
591
592
593
594
     */
    protected function getExtensions(array &$options, $restoreSearch = FALSE)
    {
        // Get last search
595
        $session = $this->objectManager->get(\T3o\TerFe2\Persistence\Session::class);
596
597
598
599
600
601
602
603
        $lastSearch = $session->get('lastSearch');

        // Revert last search if set
        if (!empty($restoreSearch) && !empty($lastSearch)) {
            $options = $lastSearch;
        }

        // Direction
604
605
        $desc = \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING;
        $asc = \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING;
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
        $direction = $desc;
        if (!empty($options['direction'])) {
            $direction = ($options['direction'] === 'asc' ? $asc : $desc);
        }

        // Sorting
        $sortings = array(
            'updated' => 'lastVersion.uploadDate',
            'downloads' => 'downloads',
            'title' => 'lastVersion.title',
        );
        $sorting = $sortings['updated'];
        if (!empty($options['sorting'])) {
            // Set direction to ASC when sorting by title
            if (!empty($sortings[$options['sorting']])) {
                $sorting = $sortings[$options['sorting']];
                if (empty($options['direction'])) {
                    $direction = $desc;
                    if ($options['sorting'] === 'title') {
                        $direction = $asc;
                        $options['direction'] = 'asc';
                    }
                }
            }
            // Sort by downloads when searching
            if (!empty($options['needle']) && (empty($lastSearch['needle']) || $lastSearch['needle'] !== $options['needle'])) {
                $sorting = $sortings['downloads'];
                $options['sorting'] = 'downloads';
                $direction = $desc;
            }
        }

        // Set new search params
        $searchParams = array();
        if (!empty($options['needle'])) {
            $searchParams = array(
                'needle' => $options['needle'],
                'sorting' => $sorting,
                'direction' => $direction,
            );
        }
        $session->set('lastSearch', $searchParams);

        // Ordering
        $ordering = array($sorting => $direction);

        // Return sorted list of all extensions
        if (empty($options['needle'])) {
            return $this->extensionRepository->findAll(0, 0, $ordering);
        }

        // Return search result
        return $this->extensionRepository->findBySearchWordsAndFilters($options['needle'], array(), $ordering);
    }


    /**
     * gets the number of extensions in TER (for ajax call)
     *
     * @return int $number of extensions
     */
    public function getExtensionNumberAction()
    {
        $number = $this->extensionRepository->findAll()->count();
        return (int)$number;
    }


    /**
     * Check if current frontend user can upload given extension
     *
     * There is no better (and faster) way to do this at the momement.
     *
     * @param string $extensionKey The extension key
     * @return boolean TRUE if upload is allowed
     */
    protected function userIsAllowedToUploadExtension($extensionKey)
    {
        if (empty($this->frontendUser['username'])) {
            return FALSE;
        }
        $isAllowedToUploadKey = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
            'uid',
            'tx_ter_extensionkeys',
            'ownerusername LIKE "' . $GLOBALS['TYPO3_DB']->quoteStr($this->frontendUser['username'], 'foo') . '"
691
				AND extensionkey LIKE "' . $GLOBALS['TYPO3_DB']->quoteStr($extensionKey, 'foo') . '"'
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
        );
        return !empty($isAllowedToUploadKey);
    }


    /**
     * Check if an version does not exist for extension
     *
     * There is no better (and faster) way to do this at the momement.
     *
     * @param string $extensionKey The extension key
     * @param string $versionString The extension version
     * @return boolean TRUE if version already exists
     */
    protected function versionIsPossibleForExtension($extensionKey, $versionString)
    {
        if (empty($extensionKey) || empty($versionString)) {
            return FALSE;
        }
        $versionExistsForExtension = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows(
            'uid',
            'tx_ter_extensions',
            'extensionkey = "' . $GLOBALS['TYPO3_DB']->quoteStr($extensionKey, 'foo') . '"
715
				AND version LIKE "' . $GLOBALS['TYPO3_DB']->quoteStr($versionString, 'foo') . '"'
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
        );
        return empty($versionExistsForExtension);
    }

    /**
     * sets SYS_LASTCHANGED to this date if it is newer than the currently set
     * @param integer $dateTime
     */
    protected function updateSysLastChanged($dateTime)
    {
        if ($dateTime instanceof \DateTime) {
            $dateTime = $dateTime->getTimestamp();
        }
        if ($GLOBALS['TSFE']->register['SYS_LASTCHANGED'] < $dateTime) {
            $GLOBALS['TSFE']->register['SYS_LASTCHANGED'] = $dateTime;
        }
    }
}