ImportExtensionsFromQueueTask.php 21.9 KB
Newer Older
1
<?php
2

3
namespace T3o\TerFe2\Task;
4

5
/*
6
 * This file is part of the TYPO3 CMS project.
7
 *
8
9
10
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
11
 *
12
13
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
14
 *
15
16
17
 * The TYPO3 project - inspiring people to share!
 */

18
use ApacheSolrForTypo3\Solr\IndexQueue\Queue;
19
use Psr\Log\LoggerInterface;
20
use T3o\Ter\Api\UploadQueue;
21
use TYPO3\CMS\Core\Database\ConnectionPool;
22
use TYPO3\CMS\Core\Log\LogManager;
23
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
24
use TYPO3\CMS\Core\Utility\GeneralUtility;
25
use TYPO3\CMS\Core\Utility\VersionNumberUtility;
26
use TYPO3\CMS\Extbase\Scheduler\Task;
27
use TYPO3\CMS\Extensionmanager\Domain\Model\Extension;
28
29
30
31
32

/**
 * Class ImportExtensionsFromQueueTask
 */
class ImportExtensionsFromQueueTask extends Task
33
34
35
36
37
38
39
{

    /**
     * PID for all extension related records
     *
     * @var int $pid
     */
40
    protected $pidExtensions = 2;
41

42
43
44
45
46
    /**
     * @var LoggerInterface
     */
    protected $logger;

47
48
49
50
51
52
53
    /**
     * executes the importer
     *
     * @return bool
     */
    public function execute()
    {
54
55
        $this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);

56
57
        $this->logger->info('Task ImportExtensionsFromQueueTask started');

58
59
60
61
        $queue = GeneralUtility::makeInstance(UploadQueue::class);

        // Get extensions from queue which are not imported yet in ter_fe2
        $extensionsFromQueue = $queue->getItemsInQueue();
62
63
64

        // finish task if no extensions in queue
        if (empty($extensionsFromQueue)) {
65
            $this->logger->info('No new extensions in queue table');
66
67

            return true;
68
69
70
71
72
73
74
        }

        foreach ($extensionsFromQueue as $ext) {
            $extensionData = $this->getExtensionData($ext['extensionuid']);
            if (!$this->versionExists($extensionData)) {
                $extUid = $this->extensionExists($extensionData);
                $this->saveExtension($extUid, $extensionData, $ext['crdate']);
75
76
                $this->logger->info(sprintf(
                    'Extension "%s" version %s saved in ter_fe2',
77
78
                    $extensionData['extensionkey'],
                    $extensionData['version']
79
                ));
80
81

                // update the EXT:solr Index Queue
82
                if (ExtensionManagementUtility::isLoaded('solr')) {
83
                    $indexQueue = GeneralUtility::makeInstance(Queue::class);
84
85
                    $indexQueue->updateItem('tx_terfe2_domain_model_extension', $extUid);
                }
86
                $this->sendNotifications($extUid, $extensionData);
87
            }
88
89
            $this->logger->info(sprintf(
                'Extension "%s" still exists in ter_fe2 with version %s',
90
91
                $extensionData['extensionkey'],
                $extensionData['version']
92
            ));
93
            $queue->markAsProcessed((int)$ext['extensionuid'], $ext['extensionkey']);
94
95
        }

96
97
98
99
100
        if (count($extensionsFromQueue) > 0) {
            $cacheManager = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class);
            $cacheManager->flushCaches();
        }

101
102
        $this->logger->info('Task ImportExtensionsFromQueueTask finished');

103
        return true;
104
105
106
107
108
109
110
111
112
113
114
    }

    /**
     * Gets the extension data out of ter tables
     *
     * @param int $extensionUid
     *
     * @return array $extData
     */
    public function getExtensionData($extensionUid)
    {
115
116
117
118
119
120
        $tableName = 'tx_ter_extensions';
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable($tableName);
        $queryBuilder->getRestrictions()->removeAll();

        $statement = $queryBuilder
121
122
            ->select('*')
            ->from($tableName)
123
            ->where(
124
                $queryBuilder->expr()->eq('uid', (int)$extensionUid)
125
126
127
            )
            ->execute();
        return $statement->fetch(\PDO::FETCH_ASSOC);
128
129
130
131
132
133
134
135
    }

    /**
     * checks if a version with a specific version
     * string exists
     *
     * @param array $extData
     *
136
     * @return bool
137
138
139
     */
    public function versionExists($extData)
    {
140
141
142
143
144
145
146
147
        $tableName = 'tx_terfe2_domain_model_version';
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable($tableName);
        $queryBuilder->getRestrictions()->removeAll();

        $statement = $queryBuilder
            ->count('ver.uid')
            ->from($tableName, 'ver')
148
149
150
151
            ->leftJoin(
                'ver',
                'tx_terfe2_domain_model_extension',
                'ext',
152
153
154
155
156
157
158
159
160
161
                $queryBuilder->expr()->eq('ext.uid', $queryBuilder->quoteIdentifier('ver.extension'))
            )
            ->where(
                $queryBuilder->expr()->eq('ver.deleted', 0),
                $queryBuilder->expr()->eq('ver.version_string', $queryBuilder->createNamedParameter($extData['version'])),
                $queryBuilder->expr()->eq('ext.ext_key', $queryBuilder->createNamedParameter($extData['extensionkey']))
            )
            ->execute();
        $statement->execute();

162
        return $statement->fetchColumn(0) > 0;
163
164
165
166
167
168
169
170
171
    }

    /**
     * @param array $extData
     *
     * @return int $uid extension uid
     */
    public function extensionExists($extData)
    {
172
173
174
175
176
177
178
179
180
181
182
183
184
185
        $tableName = 'tx_terfe2_domain_model_extension';
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($tableName);
        $queryBuilder->getRestrictions()->removeAll();

        $statement = $queryBuilder
            ->select('uid')
            ->from($tableName)
            ->where(
                $queryBuilder->expr()->eq('deleted', 0),
                $queryBuilder->expr()->eq('ext_key', $queryBuilder->createNamedParameter($extData['extensionkey']))
            )
            ->execute();
        $statement->execute();
        $extRec = $statement->fetch(\PDO::FETCH_ASSOC);
186
187
188
        if ($extRec) {
            return $extRec['uid'];
        }
189

190
191
192
193
194
195
196
197
198
199
        return $this->createExtension($extData);
    }

    /**
     * @param array $extData
     *
     * @return int $uid extension uid of new record
     */
    public function createExtension($extData)
    {
200
        $insertExtension = [
201
            'pid' => $this->pidExtensions,
202
203
204
205
206
207
208
209
            'ext_key' => $extData['extensionkey'],
            'last_upload' => time(),
            'last_maintained' => time(),
            'versions' => 0,
            'last_version' => 0,
            'frontend_user' => $extData['lastuploadbyusername'],
            'crdate' => time(),
            'tstamp' => time()
210
211
        ];

212
213
214
        $tableName = 'tx_terfe2_domain_model_extension';
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
        $queryBuilder = $connectionPool->getQueryBuilderForTable($tableName);
215

216
        $queryBuilder->insert($tableName)->values($insertExtension)->execute();
217
218

        return $connectionPool->getConnectionForTable($tableName)->lastInsertId($tableName);
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
    }

    /**
     * @param int $extUid
     * @param array $extData
     * @param int $crdate
     */
    public function saveExtension($extUid, $extData, $crdate)
    {
        $versionUid = $this->createVersion($extUid, $extData, $crdate);
        if ($versionUid) {
            $this->addRelations($versionUid, $extData['dependencies']);
            $this->updateExtension($versionUid, $extUid);
        }
    }

    /**
     * @param int $extUid
     * @param array $extData
     * @param int $crdate
     *
     * @return int $versionUid
     */
    public function createVersion($extUid, $extData, $crdate)
    {
244
        $extensionModel = GeneralUtility::makeInstance(Extension::class);
245
        $states = $extensionModel->getDefaultState(null);
246
        $categories = \T3o\TerFe2\Utility\CategoryUtility::getDefaultCategories();
247
248
249
250
251

        $folder1 = substr($extData['extensionkey'], 0, 1);
        $folder2 = substr($extData['extensionkey'], 1, 1);
        $t3xFile = PATH_site . 'fileadmin/ter/' . $folder1 . '/' . $folder2 . '/' . $extData['extensionkey'] . '_' . $extData['version'] . '.t3x';

252
        $insertVersion = [
253
254
            'pid' => $this->pidExtensions,
            'crdate' => (int)$crdate,
255
256
257
258
259
            'tstamp' => time(),
            'extension' => $extUid,
            'title' => $extData['title'],
            'description' => $extData['description'],
            'author' => $this->createAuthor($extData),
260
            'version_number' => VersionNumberUtility::convertVersionNumberToInteger($extData['version']),
261
262
263
264
265
266
            'version_string' => $extData['version'],
            'upload_date' => $crdate,
            'upload_comment' => $extData['uploadcomment'],
            'file_hash' => $extData['t3xfilemd5'],
            'download_counter' => 0,
            'frontend_download_counter' => 0,
267
268
            'state' => in_array((string)$extData['state'], $states) ? (string)$extData['state'] : 'n/a',
            'em_category' => array_key_exists((string)$extData['category'], $categories) ? (string)$extData['category'] : '',
269
            'uploadfolder' => $extData['uploadfolder'] ? 1 : 0,
270
            'create_dirs' => $extData['createdirs'] ? $extData['createdirs'] : '',
271
            'clear_cache_on_load' => (int)(boolean)$extData['clearcacheonload'],
272
273
            'review_state' => 0,
            'manual' => '',
274
            'has_manual' => (int)(boolean)$extData['ismanualincluded'],
275
276
277
278
            'software_relations' => 0,
            'has_zip_file' => 0,
            'has_images' => 0,
            't3x_file_size' => @filesize($t3xFile),
279
280
            'zip_file_size' => 0,
            'composer_info' => $extData['composerinfo']
281
282
        ];

283
284
285
        if ($extData['composerinfo']) {
            $this->ensureValidComposerNameInExtension($extUid, $extData['composerinfo']);
        }
286

287
288
289
290
        $tableName = 'tx_terfe2_domain_model_version';
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
        $queryBuilder = $connectionPool->getQueryBuilderForTable($tableName);

291
        $queryBuilder->insert($tableName)->values($insertVersion)->execute();
292

293
        return $connectionPool->getConnectionForTable($tableName)->lastInsertId($tableName);
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
    private function ensureValidComposerNameInExtension(int $extUid, string $composerInfoJson)
    {
        $composerInfo = @\json_decode($composerInfoJson, true);
        if (empty($composerInfo['name'])) {
            return;
        }

        $tableName = 'tx_terfe2_domain_model_extension';
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
        $queryBuilder = $connectionPool->getQueryBuilderForTable($tableName);
        $persistedComposerName = $queryBuilder->select('composer_name')
            ->from($tableName)
            ->where(
                $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($extUid, \PDO::PARAM_INT))
            )
            ->execute()
            ->fetchColumn();

        if (empty($persistedComposerName) || $persistedComposerName === $composerInfo['name']) {
            return;
        }

        $queryBuilder = $connectionPool->getQueryBuilderForTable($tableName);
        $queryBuilder->update($tableName)
            ->set('composer_name', '')
            ->where(
                $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($extUid, \PDO::PARAM_INT))
            )
            ->execute();
    }

327
328
329
330
331
332
    /**
     * @param int $versionUid
     * @param int $extUid
     */
    public function updateExtension($versionUid, $extUid)
    {
333
334
        $highestVersionUid = $this->calculatedHighestVersion($versionUid, $extUid);

335
336
337
338
339
340
341
342
343
344
345
346
347
348
        $tableName = 'tx_terfe2_domain_model_extension';
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
        $queryBuilder = $connectionPool->getQueryBuilderForTable($tableName);
        $queryBuilder->getRestrictions()->removeAll();

        $queryBuilder
            ->update($tableName)
            ->set('tstamp', time())
            ->set('versions', $this->getNumberOfVersions($extUid))
            ->set('last_version', $highestVersionUid)
            ->where(
                $queryBuilder->expr()->eq('uid', $extUid)
            )
            ->execute();
349
350
351
352
353
354
355
356
357
    }

    /**
     * @param int $extUid
     *
     * @return int $numberOfVersions
     */
    public function getNumberOfVersions($extUid)
    {
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
        $tableName = 'tx_terfe2_domain_model_version';
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
        $queryBuilder = $connectionPool->getQueryBuilderForTable($tableName);
        $queryBuilder->getRestrictions()->removeAll();

        $statement = $queryBuilder
            ->count('uid')
            ->from($tableName)
            ->where(
                $queryBuilder->expr()->eq('extension', $extUid),
                $queryBuilder->expr()->eq('deleted', 0)
            )
            ->execute();
        $statement->execute();

        return $statement->fetchColumn(0);
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
    }

    /**
     * @param int $versionUid
     * @param string $dependencies
     */
    public function addRelations($versionUid, $dependencies)
    {
        $countRelations = 0;
        $dependencies = unserialize($dependencies);
        foreach ($dependencies as $relation) {
            $relationType = $relation['kind'];
            $relationKey = $relation['extensionKey'];
            $version = $this->getVersionByRange($relation['versionRange']);
            if ($relationKey) {
389
                $insertRelation = [
390
391
392
393
394
395
                    'relation_type' => $relationType,
                    'relation_key' => $relationKey,
                    'minimum_version' => $version[0],
                    'maximum_version' => $version[1],
                    'version' => $versionUid,
                    'related_extension' => $this->getUidOfRelatedExtension($relationKey)
396
                ];
397
                $countRelations++;
398
399
400
401

                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
                    ->getQueryBuilderForTable('tx_terfe2_domain_model_relation');

402
                $queryBuilder->insert('tx_terfe2_domain_model_relation')->values($insertRelation)->execute();
403
404
405
            }
        }

406
407
408
409
410
411
412
413
414
415
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable('tx_terfe2_domain_model_relation');

        $queryBuilder
            ->update('tx_terfe2_domain_model_version')
            ->set('software_relations', $countRelations)
            ->where(
                $queryBuilder->expr()->eq('uid', $versionUid)
            )
            ->execute();
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
441
442
443
444
445
446
    protected function sendNotifications(int $extensionUid, array $extensionData)
    {
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable('fe_users');

        $notifications = $queryBuilder
            ->select(...['u.email', 'u.name', 'e.ext_key', 'e.composer_name'])
            ->from('tx_terfe2_extension_feuser_notification_mm', 'notify')
            ->join(
                'notify',
                'fe_users',
                'u',
                'u.uid = notify.uid_foreign'
            )
            ->join(
                'notify',
                'tx_terfe2_domain_model_extension',
                'e',
                'e.uid = notify.uid_local'
            )
            ->where(
                $queryBuilder->expr()->eq('notify.uid_local', (int)$extensionUid)
            )
            ->execute()
            ->fetchAll();

        if (!empty($notifications)) {
            foreach ($notifications as $notification) {
                $mail = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Mail\MailMessage::class);
Thomas Löffler's avatar
Fix CGL    
Thomas Löffler committed
447
                $mail->setTo($notification['email'], $notification['name']);
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
                $mail->setSubject('Release of extension "' . $notification['ext_key'] . '", version ' . $extensionData['version']);
                $standalone = GeneralUtility::makeInstance(\TYPO3\CMS\Fluid\View\StandaloneView::class);
                $standalone->setTemplatePathAndFilename('EXT:ter_fe2/Resources/Private/Templates/Mail/NewVersionNotify.html');
                $standalone->assignMultiple(
                    [
                        'notify' => $notification,
                        'extData' => $extensionData
                    ]
                );
                $mail->setBody($standalone->render());

                $mail->send();
            }
        }
    }

464
465
466
467
468
469
470
    /**
     * @param string $extKey
     *
     * @return int $uidOfRelatedExtension
     */
    public function getUidOfRelatedExtension($extKey)
    {
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
        $tableName = 'tx_terfe2_domain_model_extension';
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable($tableName);
        $queryBuilder->getRestrictions()->removeAll();

        $statement = $queryBuilder
            ->select('uid')
            ->from($tableName)
            ->where(
                $queryBuilder->expr()->eq('ext_key', $queryBuilder->createNamedParameter($extKey)),
                $queryBuilder->expr()->eq('deleted', 0)
            )
            ->execute();
        $statement->execute();

        $extRec = $statement->fetch(\PDO::FETCH_ASSOC);
487
488
489
        if ($extRec['uid']) {
            return $extRec['uid'];
        }
490

491
492
493
494
495
496
497
498
499
500
        return 0;
    }

    /**
     * @param array $extData
     *
     * @return int $authorUid
     */
    public function createAuthor($extData)
    {
501
        $insertAuthor = [
502
503
504
505
506
            'name' => $extData['authorname'],
            'email' => $extData['authoremail'],
            'company' => $extData['authorcompany'],
            'username' => $extData['lastuploadbyusername'],
            'frontend_user' => $this->getFeUserUidFromUsername($extData['lastuploadbyusername'])
507
508
        ];

509
510
511
512
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
        $tableName = 'tx_terfe2_domain_model_author';
        $queryBuilder = $connectionPool->getQueryBuilderForTable($tableName);

513
        $queryBuilder->insert($tableName)->values($insertAuthor)->execute();
514

515
        return $connectionPool->getConnectionForTable($tableName)->lastInsertId($tableName);
516
517
518
519
520
521
522
523
524
    }

    /**
     * @param string $username
     *
     * @return int $feUserUid
     */
    public function getFeUserUidFromUsername($username)
    {
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
        $tableName = 'fe_users';
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable($tableName);
        $queryBuilder->getRestrictions()->removeAll();

        $statement = $queryBuilder
            ->select('uid')
            ->from($tableName)
            ->where(
                $queryBuilder->expr()->eq('username', $queryBuilder->createNamedParameter($username))
            )
            ->execute();
        $statement->execute();

        $userRec = $statement->fetch(\PDO::FETCH_ASSOC);
540
541
542
        if ($userRec['uid']) {
            return $userRec['uid'];
        }
543
544

        return false;
545
546
547
548
549
550
551
552
553
554
    }

    /**
     * Returns an array with minimum and maximum version number from range
     *
     * @param string $version Range of versions
     * @return array Minumum and maximum version number
     */
    protected function getVersionByRange($version)
    {
555
556
557
        $version = GeneralUtility::trimExplode('-', $version);
        $minimum = (!empty($version[0]) ? VersionNumberUtility::convertVersionNumberToInteger($version[0]) : 0);
        $maximum = (!empty($version[1]) ? VersionNumberUtility::convertVersionNumberToInteger($version[1]) : 0);
558

559
        return [$minimum, $maximum];
560
561
    }

562
563
564
565
566
    /**
     * Check which version is higher, so that we can se the right version in latest_version
     *
     * @param $versionUid
     * @param $extUid
567
     * @return int
568
     */
569
    private function calculatedHighestVersion($versionUid, $extUid): int
570
571
572
573
574
575
576
577
    {
        $currentHighestVersion = $this->getHighestVersion($extUid);
        if (empty($currentHighestVersion)) {
            return $versionUid;
        }

        $newVersionNumber = $this->getVersionNumber($versionUid);

578
        if ($newVersionNumber < $currentHighestVersion['version_number']) {
579
580
581
582
583
584
585
586
587
588
589
590
591
            $versionUid = $currentHighestVersion['uid'];
        }
        return $versionUid;
    }

    /**
     * Get the version number of the current version
     *
     * @param $versionUid
     * @return int
     */
    private function getVersionNumber($versionUid)
    {
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
        $tableName = 'tx_terfe2_domain_model_version';
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable($tableName);
        $queryBuilder->getRestrictions()->removeAll();

        $statement = $queryBuilder
            ->select('version_number')
            ->from($tableName)
            ->where(
                $queryBuilder->expr()->eq('deleted', 0),
                $queryBuilder->expr()->eq('uid', $versionUid)
            )
            ->execute();
        $statement->execute();

        $res = $statement->fetch(\PDO::FETCH_ASSOC);
608
609
610
611
612
613
614
615
616
617
618
619
620

        if ($res['version_number']) {
            return $res['version_number'];
        }

        return 0;
    }

    /**
     * Gets the highest version number
     *
     * @param $extUid
     *
621
     * @return array|false|null
622
     */
623
624
    private function getHighestVersion($extUid)
    {
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
        $tableName = 'tx_terfe2_domain_model_version';
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable($tableName);
        $queryBuilder->getRestrictions()->removeAll();

        $statement = $queryBuilder
            ->select('uid', 'version_number')
            ->from($tableName)
            ->where(
                $queryBuilder->expr()->eq('deleted', 0),
                $queryBuilder->expr()->eq('extension', $extUid)
            )
            ->orderBy('version_number', 'DESC')
            ->execute();
        $statement->execute();

        $res = $statement->fetch(\PDO::FETCH_ASSOC);
642
643
644
645
646
647
        if (!empty($res)) {
            return $res;
        }

        return [];
    }
648
}