ExtensionController.php 28.6 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
        $this->providerManager = $this->objectManager->get(\T3o\TerFe2\Provider\ProviderManager::class);
        $this->session = $this->objectManager->get(\T3o\TerFe2\Persistence\Session::class);
93
        $this->persistenceManager = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class);
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
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

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

201
        //$loggedInUser = $this->ownerRepository->findCurrent();
202
203

        if ($extension !== NULL &&
204
            $extension instanceof \T3o\TerFe2\Domain\Model\Extension &&
205
206
207
208
209
210
211
212
213
214
215
            (
                $this->securityRole->isReviewer() ||
                ($extension->getLastVersion() && $extension->getLastVersion()->getReviewState() != -1)
            )
        ) {
            $versionHistory = $this->versionRepository->getVersionHistory($extension, $versionHistoryCount, $skipLatestVersion);
            $this->view->assign('owner', $owner);
            $this->view->assign('extension', $extension);
            $this->view->assign('versionHistory', $versionHistory);
            $this->view->assign('loggedInUser', $loggedInUser);

216
217
            /** @var \T3o\TerFe2\Service\Documentation $documentationService */
            //$documentationService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('\T3o\TerFe2\Service\Documentation');
218
            //$documentationLink = $documentationService->getDocumentationLink($extension->getExtKey(), $extension->getLastVersion()->getVersionString());
219
220
            $this->view->assign('documentationLink', $documentationLink);

221
222
            $pageRenderer = $this->objectManager->get(\TYPO3\CMS\Core\Page\PageRenderer::class);
            $pageRenderer->addMetaTag('<meta name="description" content="' . htmlspecialchars($extension->getLastVersion()->getDescription()) . '" />');
223
            if ($extension->getTags()->count() > 0) {
224
                $pageRenderer->addMetaTag('<meta name="keywords" content="' . htmlspecialchars(implode(',', $extension->getTags()->toArray())) . '" />');
225
226
227
228
229
            }

            // gets all other extensions from the owner
            $this->extensionRepository->setDefaultOrderings(
                array(
230
                    'lastVersion.uploadDate' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING
231
232
233
234
235
236
237
238
239
240
241
242
                )
            );
            $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
243
                /** @var \TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder $uriBuilder */
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
271
272
273
274
275
276
277
                $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
     *
278
     * @param \T3o\TerFe2\Domain\Model\Extension $newExtension New extension object
279
280
281
     * @return void
     * @dontvalidate $newExtension
     */
282
    public function newAction(\T3o\TerFe2\Domain\Model\Extension $newExtension = NULL)
283
284
285
286
287
288
289
290
291
    {
        $this->view->assign('newExtension', $newExtension);
        $this->view->assign('tags', $this->tagRepository->findAll());
    }


    /**
     * Creates a new extension
     *
292
     * @param \T3o\TerFe2\Domain\Model\Extension $newExtension New extension object
293
294
     * @return void
     */
295
    public function createAction(\T3o\TerFe2\Domain\Model\Extension $newExtension)
296
297
298
299
300
301
302
303
304
    {
        $this->extensionRepository->add($newExtension);
        $this->redirectWithMessage($this->translate('msg.extension_created'), 'index');
    }


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

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


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


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

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

        // 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);
456
457
458
                \T3o\TerFe2\Utility\Archive::convertT3xToZip(
                    \T3o\TerFe2\Utility\File::getAbsolutePathFromUrl($t3xFileUrl),
                    \T3o\TerFe2\Utility\File::getAbsolutePathFromUrl($zipFileUrl)
459
460
461
                );

                // update ZIP filesize
462
                $version->setZipFileSize(filesize(\T3o\TerFe2\Utility\File::getAbsolutePathFromUrl($zipFileUrl)));
463
464
465
466
467
468
469
470
                $this->versionRepository->update($version);
                $this->persistenceManager->persistAll();

                $fileUrl = $zipFileUrl;
            }
        }

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

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

        // 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
499
        if (!\T3o\TerFe2\Utility\File::transferFile($fileUrl)) {
500
            $this->redirectWithMessage($this->translate('msg.could_not_transfer_file'), 'show', '', \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, NULL, NULL, array('extension' => $extension));
501
502
503
504
505
506
507
508
509
510
        }

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


    /**
     * Show upload form for a new extension version
     *
511
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension object
512
513
514
515
516
     * @param array $form Form information for the new version
     * @return void
     * @dontvalidate $extension
     * @dontvalidate $form
     */
517
    public function uploadVersionAction(\T3o\TerFe2\Domain\Model\Extension $extension, array $form = array())
518
    {
519
        if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('ter')) {
520
            $this->addFlashMessage($this->translate('msq.createVersionTerNotLoaded'));
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
        }
        $this->view->assign('extension', $extension);
        $this->view->assign('form', $form);
    }


    /**
     * Disable HMAC validation for createVersionAction to prevent validation
     * errors with modified form fields
     *
     * @return void
     */
    public function initializeCreateVersionAction()
    {
        $this->request->setHmacVerified(TRUE);
    }


    /**
     * Create new version of an extension
     *
542
     * @param \T3o\TerFe2\Domain\Model\Extension $extension The extension object
543
544
545
546
547
     * @param array $form Form information for the new version
     * @return void
     * @dontvalidate $extension
     * @dontvalidate $form
     */
548
    public function createVersionAction(\T3o\TerFe2\Domain\Model\Extension $extension, array $form)
549
550
551
552
553
    {
        if (!$form['gplCompliant']) {
            $this->forwardWithError($this->translate('msg.acceptGPL'), 'uploadVersion');
        }

554
        if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('ter')) {
555
556
557
558
559
560
561
562
            $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');
        }
563
//        $fileInfo = \T3o\TerFe2\Utility\File::getFileInfo('tx_terfe2_pi1.form.file');
564
565
566
567
568
569
570
571
        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 {
572
            $extensionInfo = \T3o\TerFe2\Utility\Archive::getExtensionDetailsFromZipArchive($fileInfo['tmp_name'], $files);
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
        } catch (Exception $exception) {
            $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 {
            $result = tx_ter_api::uploadExtensionWithoutSoap($this->frontendUser['username'], $extensionInfo, $filesData);
            if ($result) {
                $this->redirect('index', 'Registerkey', NULL, array('uploaded' => TRUE), $this->settings['pages']['manageKeysPID']);
            }
        } catch (Exception $exception) {
            $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
610
     * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage Objects
611
612
613
614
     */
    protected function getExtensions(array &$options, $restoreSearch = FALSE)
    {
        // Get last search
615
        $session = $this->objectManager->get(\T3o\TerFe2\Persistence\Session::class);
616
617
618
619
620
621
622
623
        $lastSearch = $session->get('lastSearch');

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

        // Direction
624
625
        $desc = \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING;
        $asc = \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING;
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
        $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') . '"
711
				AND extensionkey LIKE "' . $GLOBALS['TYPO3_DB']->quoteStr($extensionKey, 'foo') . '"'
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
        );
        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') . '"
735
				AND version LIKE "' . $GLOBALS['TYPO3_DB']->quoteStr($versionString, 'foo') . '"'
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
        );
        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;
        }
    }
}