ExtensionController.php 28.4 KB
Newer Older
speedprogs_de's avatar
speedprogs_de committed
1
<?php
2
3
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*******************************************************************
 *  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
 */
class Tx_TerFe2_Controller_ExtensionController extends Tx_TerFe2_Controller_AbstractController
{

    /**
     * @var Tx_TerFe2_Domain_Repository_ExtensionRepository
     */
    protected $extensionRepository;

    /**
     * @var Tx_TerFe2_Domain_Repository_TagRepository
     */
    protected $tagRepository;

    /**
     * @var Tx_TerFe2_Domain_Repository_AuthorRepository
     */
    protected $authorRepository;

    /**
     * @var Tx_TerFe2_Domain_Repository_VersionRepository
     */
    protected $versionRepository;

    /**
     * @var Tx_TerFe2_Provider_ProviderManager
     */
    protected $providerManager;

    /**
     * @var Tx_TerFe2_Persistence_Session
     */
    protected $session;

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

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

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

    /**
     * Initializes the controller
     *
     * @return void
     */
    protected function initializeController()
    {
        $this->extensionRepository = $this->objectManager->get('Tx_TerFe2_Domain_Repository_ExtensionRepository');
        $this->tagRepository = $this->objectManager->get('Tx_TerFe2_Domain_Repository_TagRepository');
        $this->versionRepository = $this->objectManager->get('Tx_TerFe2_Domain_Repository_VersionRepository');
        $this->authorRepository = $this->objectManager->get('Tx_TerFe2_Domain_Repository_AuthorRepository');
88
        $this->ownerRepository = $this->objectManager->get(\TYPO3\CMS\Extbase\Domain\Repository\FrontendUserRepository::class);
89
90
        $this->providerManager = $this->objectManager->get('Tx_TerFe2_Provider_ProviderManager');
        $this->session = $this->objectManager->get('Tx_TerFe2_Persistence_Session');
91
        $this->persistenceManager = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class);
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198

        // 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
     *
     * @param Tx_TerFe2_Domain_Model_Extension $extension The extension to display
     * @param string $extensionKey Extension key
     * @return void
     * @dontvalidate $extension
     * @dontvalidate $extensionKey
     */
    public function showAction(Tx_TerFe2_Domain_Model_Extension $extension = NULL, $extensionKey = NULL)
    {
        if (!empty($extensionKey)) {
            if (!is_string($extensionKey)) {
                throw new Exception('No valid extension key given');
            }
            $extension = $this->extensionRepository->findOneByExtKey($extensionKey);
        }
        $owner = array();
        if ($extension instanceof Tx_TerFe2_Domain_Model_Extension and $extension->getFrontendUser()) {
            $owner = $this->ownerRepository->findOneByUsername($extension->getFrontendUser());
        }
        $versionHistoryCount = (!empty($this->settings['versionHistoryCount']) ? $this->settings['versionHistoryCount'] : 5);
        $skipLatestVersion = (isset($this->settings['skipLatestVersion']) ? $this->settings['skipLatestVersion'] : TRUE);

199
        //$loggedInUser = $this->ownerRepository->findCurrent();
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214

        if ($extension !== NULL &&
            $extension instanceof Tx_TerFe2_Domain_Model_Extension &&
            (
                $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);

            /** @var Tx_TerFe2_Service_Documentation $documentationService */
215
216
            //$documentationService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('Tx_TerFe2_Service_Documentation');
            //$documentationLink = $documentationService->getDocumentationLink($extension->getExtKey(), $extension->getLastVersion()->getVersionString());
217
218
219
220
221
222
223
224
225
226
            $this->view->assign('documentationLink', $documentationLink);

            $GLOBALS['TSFE']->getPageRenderer()->addMetaTag('<meta name="description" content="' . htmlspecialchars($extension->getLastVersion()->getDescription()) . '" />');
            if ($extension->getTags()->count() > 0) {
                $GLOBALS['TSFE']->getPageRenderer()->addMetaTag('<meta name="keywords" content="' . htmlspecialchars(implode(',', $extension->getTags()->toArray())) . '" />');
            }

            // gets all other extensions from the owner
            $this->extensionRepository->setDefaultOrderings(
                array(
227
                    'lastVersion.uploadDate' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING
228
229
230
231
232
233
234
235
236
237
238
239
                )
            );
            $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
240
                /** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
                $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
     *
     * @param Tx_TerFe2_Domain_Model_Extension $newExtension New extension object
     * @return void
     * @dontvalidate $newExtension
     */
    public function newAction(Tx_TerFe2_Domain_Model_Extension $newExtension = NULL)
    {
        $this->view->assign('newExtension', $newExtension);
        $this->view->assign('tags', $this->tagRepository->findAll());
    }


    /**
     * Creates a new extension
     *
     * @param Tx_TerFe2_Domain_Model_Extension $newExtension New extension object
     * @return void
     */
    public function createAction(Tx_TerFe2_Domain_Model_Extension $newExtension)
    {
        $this->extensionRepository->add($newExtension);
        $this->redirectWithMessage($this->translate('msg.extension_created'), 'index');
    }


    /**
     * Displays a form to edit an existing extension
     *
     * @param Tx_TerFe2_Domain_Model_Extension $extension The extension to display
     * @dontvalidate $extension
     * @return void
     */
    public function editAction(Tx_TerFe2_Domain_Model_Extension $extension)
    {
        $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
     *
     * @param Tx_TerFe2_Domain_Model_Extension $extension extension to update
     * @param string $tag
     * @param string $save
     * @return void
     */
    public function updateAction(Tx_TerFe2_Domain_Model_Extension $extension, $tag = '', $save = '')
    {
        /** @var Tx_T3oAjaxlogin_Domain_Model_User $currentUser */
        $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();
339
            $intermediateTags = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(' ', $tag, TRUE);
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
            foreach ($intermediateTags as $tag) {
                $tag = trim($tag, ',');
                if (!empty($tag)) {
                    $tags[] = $tag;
                }
            }
            $tags = array_unique($tags);
            foreach ($tags as $tag) {
                /** @var Tx_TerFe2_Domain_Model_Tag $newTag */
                $newTag = $this->tagRepository->findByTitle($tag)->getFirst();
                if ($newTag !== NULL) {
                    if (!$extension->getTags()->contains($newTag)) {
                        $extension->addTag($newTag);
                    } else {
                        continue;
                    }
                } else {
                    $newTag = $this->objectManager->get('Tx_TerFe2_Domain_Model_Tag');
                    $newTag->setTitle($tag);
                    $extension->addTag($newTag);
                }
361
                $this->addFlashMessage('Tag "' . htmlspecialchars($tag) . '" added to extension');
362
363
364
365
366
367
368
369
            }
        }
        $this->extensionRepository->update($extension);
        if (!empty($save)) {
            $this->redirectWithMessage(
                $this->translate('msg.extension_updated'),
                'edit',
                '',
370
                \TYPO3\CMS\Core\Messaging\FlashMessage::OK,
371
372
373
374
375
376
377
378
379
                'Extension',
                NULL,
                array('extension' => $extension)
            );
        } else {
            $this->redirectWithMessage(
                $this->translate('msg.extension_updated'),
                'index',
                '',
380
                \TYPO3\CMS\Core\Messaging\FlashMessage::OK,
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
                'Registerkey'
            );
        }
    }

    /**
     * @param Tx_TerFe2_Domain_Model_Extension $extension
     * @param Tx_TerFe2_Domain_Model_Tag $tag
     *
     * @return void
     */
    public function removeTagAction(Tx_TerFe2_Domain_Model_Extension $extension, Tx_TerFe2_Domain_Model_Tag $tag)
    {
        if ($extension->getTags()->contains($tag)) {
            $extension->removeTag($tag);
        }
        $this->redirectWithMessage(
            'Tag "' . htmlspecialchars($tag->getTitle()) . '" was removed',
            'edit',
            '',
401
            \TYPO3\CMS\Core\Messaging\FlashMessage::OK,
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
            'Extension',
            NULL,
            array('extension' => $extension)
        );
    }


    /**
     * Deletes an existing extension and all versions
     *
     * @param Tx_TerFe2_Domain_Model_Extension $extension The extension to delete
     * @return void
     */
    public function deleteAction(Tx_TerFe2_Domain_Model_Extension $extension)
    {
        $this->extensionRepository->remove($extension);
        $this->redirectWithMessage($this->translate('msg.extension_deleted'), 'index');
    }


    /**
     * Check file hash, increment download counter and send file to client browser
     *
     * @param Tx_TerFe2_Domain_Model_Extension $extension The extension object
     * @param string $versionString An existing version string
     * @param string $format Format of the file output
     * @return void
     */
    public function downloadAction(Tx_TerFe2_Domain_Model_Extension $extension, $versionString, $format)
    {
        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) {
441
            $this->redirectWithMessage($this->translate('msg.version_not_found'), 'show', '', \TYPO3\CMS\Core\Messaging\FlashMessage::ERROR, NULL, NULL, array('extension' => $extension));
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
        }

        // 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);
                Tx_TerFe2_Utility_Archive::convertT3xToZip(
                    Tx_TerFe2_Utility_File::getAbsolutePathFromUrl($t3xFileUrl),
                    Tx_TerFe2_Utility_File::getAbsolutePathFromUrl($zipFileUrl)
                );

                // update ZIP filesize
                $version->setZipFileSize(filesize(Tx_TerFe2_Utility_File::getAbsolutePathFromUrl($zipFileUrl)));
                $this->versionRepository->update($version);
                $this->persistenceManager->persistAll();

                $fileUrl = $zipFileUrl;
            }
        }

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

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

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

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


    /**
     * Show upload form for a new extension version
     *
     * @param Tx_TerFe2_Domain_Model_Extension $extension The extension object
     * @param array $form Form information for the new version
     * @return void
     * @dontvalidate $extension
     * @dontvalidate $form
     */
    public function uploadVersionAction(Tx_TerFe2_Domain_Model_Extension $extension, array $form = array())
    {
516
        if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('ter')) {
517
            $this->addFlashMessage($this->translate('msq.createVersionTerNotLoaded'));
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
        }
        $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
     *
     * @param Tx_TerFe2_Domain_Model_Extension $extension The extension object
     * @param array $form Form information for the new version
     * @return void
     * @dontvalidate $extension
     * @dontvalidate $form
     */
    public function createVersionAction(Tx_TerFe2_Domain_Model_Extension $extension, array $form)
    {
        if (!$form['gplCompliant']) {
            $this->forwardWithError($this->translate('msg.acceptGPL'), 'uploadVersion');
        }

551
        if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('ter')) {
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
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
            $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');
        }
        $fileInfo = Tx_TerFe2_Utility_File::getFileInfo('tx_terfe2_pi1.form.file');
        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 {
            $extensionInfo = Tx_TerFe2_Utility_Archive::getExtensionDetailsFromZipArchive($fileInfo['tmp_name'], $files);
        } 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
607
     * @return \TYPO3\CMS\Extbase\Persistence\ObjectStorage Objects
608
609
610
611
612
613
614
615
616
617
618
619
620
     */
    protected function getExtensions(array &$options, $restoreSearch = FALSE)
    {
        // Get last search
        $session = $this->objectManager->get('Tx_TerFe2_Persistence_Session');
        $lastSearch = $session->get('lastSearch');

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

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