Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Issues (210)

Classes/Updates/FileLocationUpdater.php (1 issue)

1
<?php
2
3
/**
4
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
5
 *
6
 * This file is part of the Kitodo and TYPO3 projects.
7
 *
8
 * @license GNU General Public License version 3 or later.
9
 * For the full copyright and license information, please read the
10
 * LICENSE.txt file that was distributed with this source code.
11
 */
12
13
namespace Kitodo\Dlf\Updates;
14
15
use Doctrine\DBAL\Exception;
16
use Psr\Log\LoggerAwareInterface;
17
use Psr\Log\LoggerAwareTrait;
18
use Symfony\Component\Console\Output\OutputInterface;
19
use TYPO3\CMS\Core\Core\Environment;
20
use TYPO3\CMS\Core\Database\ConnectionPool;
21
use TYPO3\CMS\Core\Database\Query\Expression\ExpressionBuilder;
22
use TYPO3\CMS\Core\Resource\ResourceStorage;
23
use TYPO3\CMS\Core\Resource\StorageRepository;
24
use TYPO3\CMS\Core\Utility\GeneralUtility;
25
use TYPO3\CMS\Install\Updates\DatabaseUpdatedPrerequisite;
26
use TYPO3\CMS\Install\Updates\UpgradeWizardInterface;
27
use TYPO3\CMS\Install\Updates\ChattyInterface;
28
29
/**
30
 * Migrate reference of thumbnail image in collections record.
31
 *
32
 * @package TYPO3
33
 * @subpackage dlf
34
 *
35
 * @access public
36
 */
37
class FileLocationUpdater implements UpgradeWizardInterface, ChattyInterface, LoggerAwareInterface
38
{
39
    use LoggerAwareTrait;
40
41
    /**
42
     * @access protected
43
     * @var OutputInterface
44
     */
45
    protected OutputInterface $output;
46
47
    /**
48
     * @access protected
49
     * @var ResourceStorage
50
     */
51
    protected ResourceStorage $storage;
52
53
    /**
54
     * @access protected
55
     * @var array Array with table and fields to migrate
56
     */
57
    protected array $fieldsToMigrate = [
58
        'tx_dlf_collections' => 'thumbnail'
59
    ];
60
61
    /**
62
     * @access public
63
     *
64
     * @return string Unique identifier of this updater
65
     */
66
    public function getIdentifier(): string
67
    {
68
        return self::class;
69
    }
70
71
    /**
72
     * Return the speaking name of this wizard
73
     *
74
     * @access public
75
     *
76
     * @return string
77
     */
78
    public function getTitle(): string
79
    {
80
        return 'Migrate Kitodo.Presentation file references';
81
    }
82
83
    /**
84
     * Get description
85
     *
86
     * @access public
87
     *
88
     * @return string Longer description of this updater
89
     */
90
    public function getDescription(): string
91
    {
92
        return 'Convert file reference of thumbnail images in collection records.';
93
    }
94
95
    /**
96
     * Is an update necessary?
97
     *
98
     * Is used to determine whether a wizard needs to be run.
99
     * Check if data for migration exists.
100
     *
101
     * @access public
102
     *
103
     * @return bool
104
     */
105
    public function updateNecessary(): bool
106
    {
107
        /** @var int */
108
        $numRecords = $this->getRecordsFromTable(true);
109
        if ($numRecords > 0) {
110
            return true;
111
        }
112
        return false;
113
    }
114
115
    /**
116
     * @access public
117
     *
118
     * @return string[] All new fields and tables must exist
119
     */
120
    public function getPrerequisites(): array
121
    {
122
        return [
123
            DatabaseUpdatedPrerequisite::class
124
        ];
125
    }
126
127
    /**
128
     * @access public
129
     *
130
     * @param OutputInterface $output
131
     */
132
    public function setOutput(OutputInterface $output): void
133
    {
134
        $this->output = $output;
135
    }
136
137
    /**
138
     * Execute the update
139
     *
140
     * Called when a wizard reports that an update is necessary
141
     *
142
     * @access public
143
     *
144
     * @return bool
145
     */
146
    public function executeUpdate(): bool
147
    {
148
        $result = true;
149
        try {
150
            /** @var int */
151
            $numRecords = $this->getRecordsFromTable(true);
152
            if ($numRecords > 0) {
153
                $this->performUpdate();
154
            }
155
        } catch (\Exception $e) {
156
            // If something goes wrong, migrateField() logs an error
157
            $result = false;
158
        }
159
        return $result;
160
    }
161
162
    /**
163
     * Get records from table where the field to migrate is not empty (NOT NULL and != '')
164
     * and also not numeric (which means that it is migrated)
165
     *
166
     * Work based on BackendLayoutIconUpdateWizard::class
167
     *
168
     * @access public
169
     *
170
     * @return array|int
171
     *
172
     * @throws \RuntimeException
173
     */
174
    protected function getRecordsFromTable(bool $countOnly = false)
175
    {
176
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
177
        $allResults = [];
178
        $numResults = 0;
179
        foreach (array_keys($this->fieldsToMigrate) as $table) {
180
            $queryBuilder = $connectionPool->getQueryBuilderForTable($table);
181
            $queryBuilder->getRestrictions()->removeAll();
182
            try {
183
                $result = $queryBuilder
184
                    ->select('uid', 'pid', $this->fieldsToMigrate[$table])
185
                    ->from($table)
186
                    ->where(
187
                        $queryBuilder->expr()->isNotNull($this->fieldsToMigrate[$table]),
188
                        $queryBuilder->expr()->neq(
189
                            $this->fieldsToMigrate[$table],
190
                            $queryBuilder->createNamedParameter('', \PDO::PARAM_STR)
191
                        ),
192
                        $queryBuilder->expr()->comparison(
193
                            'CAST(CAST(' . $queryBuilder->quoteIdentifier($this->fieldsToMigrate[$table]) . ' AS DECIMAL) AS CHAR)',
194
                            ExpressionBuilder::NEQ,
195
                            'CAST(' . $queryBuilder->quoteIdentifier($this->fieldsToMigrate[$table]) . ' AS CHAR)'
196
                        )
197
                    )
198
                    ->orderBy('uid')
199
                    ->execute()
200
                    ->fetchAllAssociative();
201
                if ($countOnly === true) {
202
                    $numResults += count($result);
203
                } else {
204
                    $allResults[$table] = $result;
205
                }
206
            } catch (Exception $e) {
207
                throw new \RuntimeException(
208
                    'Database query failed. Error was: ' . $e->getPrevious()->getMessage(),
209
                    1511950673
210
                );
211
            }
212
        }
213
214
        if ($countOnly === true) {
215
            return $numResults;
216
        } else {
217
            return $allResults;
218
        }
219
    }
220
221
222
    /**
223
     * Performs the database update.
224
     *
225
     * @access public
226
     *
227
     * @return bool TRUE on success, FALSE on error
228
     */
229
    protected function performUpdate(): bool
230
    {
231
        $result = true;
232
233
        try {
234
            $storages = GeneralUtility::makeInstance(StorageRepository::class)->findAll();
235
            $this->storage = $storages[0];
236
237
            $records = $this->getRecordsFromTable();
238
            foreach ($records as $table => $recordsInTable) {
239
                foreach ($recordsInTable as $record) {
240
                    $this->migrateField($table, $record);
241
                }
242
            }
243
        } catch (\Exception $e) {
244
            $result = false;
245
        }
246
247
        return $result;
248
    }
249
250
    /**
251
     * Migrates a single field.
252
     *
253
     * @access public
254
     *
255
     * @param string $table
256
     * @param array $row
257
     *
258
     * @return void
259
     *
260
     * @throws \Exception
261
     */
262
    protected function migrateField(string $table, array $row): void
263
    {
264
        $fieldItem = trim($row[$this->fieldsToMigrate[$table]]);
265
266
        if (empty($fieldItem) || is_numeric($fieldItem)) {
267
            return;
268
        }
269
270
        $storageUid = (int) $this->storage->getUid();
271
        $connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
272
273
        $fileUid = null;
274
        $sourcePath = Environment::getPublicPath() . '/' . $fieldItem;
275
276
        // maybe the file was already moved, so check if the original file still exists
277
        if (file_exists($sourcePath)) {
278
279
            // see if the file already exists in the storage
280
            $fileSha1 = sha1_file($sourcePath);
281
282
            $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file');
283
            $existingFileRecord = $queryBuilder->select('uid')->from('sys_file')->where(
284
                $queryBuilder->expr()->eq(
285
                    'missing',
286
                    $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
287
                ),
288
                $queryBuilder->expr()->eq(
289
                    'sha1',
290
                    $queryBuilder->createNamedParameter($fileSha1, \PDO::PARAM_STR)
291
                ),
292
                $queryBuilder->expr()->eq(
293
                    'storage',
294
                    $queryBuilder->createNamedParameter($storageUid, \PDO::PARAM_INT)
295
                )
296
            )->execute()->fetchAssociative();
297
298
            // the file exists
299
            if (is_array($existingFileRecord)) {
300
                $fileUid = $existingFileRecord['uid'];
301
            }
302
        }
303
304
        if ($fileUid > 0) {
305
            $fields = [
306
                'fieldname' => $this->fieldsToMigrate[$table],
307
                'pid' => ($table === 'pages' ? $row['uid'] : $row['pid']),
308
                'uid_foreign' => $row['uid'],
309
                'uid_local' => $fileUid,
310
                'tablenames' => $table,
311
                'crdate' => time(),
312
                'tstamp' => time(),
313
            ];
314
315
            $queryBuilder = $connectionPool->getQueryBuilderForTable('sys_file_reference');
316
317
            $result = $queryBuilder
0 ignored issues
show
The assignment to $result is dead and can be removed.
Loading history...
318
                ->insert('sys_file_reference')
319
                ->values($fields)
320
                ->execute();
321
322
            // Update referencing table's original field to now contain the count of references,
323
            // which is "1" in our case.
324
            $queryBuilder = $connectionPool->getQueryBuilderForTable($table);
325
            $queryBuilder->update($table)->where(
326
                $queryBuilder->expr()->eq(
327
                    'uid',
328
                    $queryBuilder->createNamedParameter($row['uid'], \PDO::PARAM_INT)
329
                )
330
            )->set($this->fieldsToMigrate[$table], 1)->execute();
331
        }
332
    }
333
}
334