Completed
Push — in-memory-cache2 ( de4787 )
by André
21:05
created

DoctrineDatabase::updateContent()   C

Complexity

Conditions 10
Paths 256

Size

Total Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
nc 256
nop 3
dl 0
loc 65
rs 5.6703
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * File containing the DoctrineDatabase Content Gateway class.
5
 *
6
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
7
 * @license For full copyright and license information view LICENSE file distributed with this source code.
8
 */
9
namespace eZ\Publish\Core\Persistence\Legacy\Content\Gateway;
10
11
use Doctrine\DBAL\Connection;
12
use Doctrine\DBAL\DBALException;
13
use Doctrine\DBAL\FetchMode;
14
use Doctrine\DBAL\ParameterType;
15
use Doctrine\DBAL\Query\QueryBuilder as DoctrineQueryBuilder;
16
use eZ\Publish\Core\Base\Exceptions\BadStateException;
17
use eZ\Publish\Core\Persistence\Legacy\Content\Gateway;
18
use eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase\QueryBuilder;
19
use eZ\Publish\Core\Persistence\Database\DatabaseHandler;
20
use eZ\Publish\Core\Persistence\Database\UpdateQuery;
21
use eZ\Publish\Core\Persistence\Database\InsertQuery;
22
use eZ\Publish\Core\Persistence\Database\SelectQuery;
23
use eZ\Publish\Core\Persistence\Legacy\Content\StorageFieldValue;
24
use eZ\Publish\Core\Persistence\Legacy\Content\Language\MaskGenerator as LanguageMaskGenerator;
25
use eZ\Publish\SPI\Persistence\Content;
26
use eZ\Publish\SPI\Persistence\Content\CreateStruct;
27
use eZ\Publish\SPI\Persistence\Content\UpdateStruct;
28
use eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct;
29
use eZ\Publish\SPI\Persistence\Content\ContentInfo;
30
use eZ\Publish\SPI\Persistence\Content\VersionInfo;
31
use eZ\Publish\SPI\Persistence\Content\Field;
32
use eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct as RelationCreateStruct;
33
use eZ\Publish\SPI\Persistence\Content\Language\Handler as LanguageHandler;
34
use eZ\Publish\Core\Base\Exceptions\NotFoundException as NotFound;
35
use eZ\Publish\API\Repository\Values\Content\VersionInfo as APIVersionInfo;
36
use DOMXPath;
37
use DOMDocument;
38
use PDO;
39
40
/**
41
 * Doctrine database based content gateway.
42
 */
43
class DoctrineDatabase extends Gateway
44
{
45
    /**
46
     * eZ Doctrine database handler.
47
     *
48
     * @var \eZ\Publish\Core\Persistence\Database\DatabaseHandler
49
     * @deprecated Start to use DBAL $connection instead.
50
     */
51
    protected $dbHandler;
52
53
    /**
54
     * The native Doctrine connection.
55
     *
56
     * Meant to be used to transition from eZ/Zeta interface to Doctrine.
57
     *
58
     * @var \Doctrine\DBAL\Connection
59
     */
60
    protected $connection;
61
62
    /**
63
     * Query builder.
64
     *
65
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase\QueryBuilder
66
     */
67
    protected $queryBuilder;
68
69
    /**
70
     * Caching language handler.
71
     *
72
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\Language\CachingHandler
73
     */
74
    protected $languageHandler;
75
76
    /**
77
     * Language mask generator.
78
     *
79
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\Language\MaskGenerator
80
     */
81
    protected $languageMaskGenerator;
82
83
    /**
84
     * Creates a new gateway based on $db.
85
     *
86
     * @param \eZ\Publish\Core\Persistence\Database\DatabaseHandler $db
87
     * @param \Doctrine\DBAL\Connection $connection
88
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase\QueryBuilder $queryBuilder
89
     * @param \eZ\Publish\SPI\Persistence\Content\Language\Handler $languageHandler
90
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\Language\MaskGenerator $languageMaskGenerator
91
     */
92
    public function __construct(
93
        DatabaseHandler $db,
94
        Connection $connection,
95
        QueryBuilder $queryBuilder,
96
        LanguageHandler $languageHandler,
97
        LanguageMaskGenerator $languageMaskGenerator
98
    ) {
99
        $this->dbHandler = $db;
100
        $this->connection = $connection;
101
        $this->queryBuilder = $queryBuilder;
102
        $this->languageHandler = $languageHandler;
0 ignored issues
show
Documentation Bug introduced by
It seems like $languageHandler of type object<eZ\Publish\SPI\Pe...ntent\Language\Handler> is incompatible with the declared type object<eZ\Publish\Core\P...anguage\CachingHandler> of property $languageHandler.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
103
        $this->languageMaskGenerator = $languageMaskGenerator;
104
    }
105
106
    /**
107
     * Get context definition for external storage layers.
108
     *
109
     * @return array
110
     */
111
    public function getContext()
112
    {
113
        return array(
114
            'identifier' => 'LegacyStorage',
115
            'connection' => $this->dbHandler,
116
        );
117
    }
118
119
    /**
120
     * Inserts a new content object.
121
     *
122
     * @param \eZ\Publish\SPI\Persistence\Content\CreateStruct $struct
123
     * @param mixed $currentVersionNo
124
     *
125
     * @return int ID
126
     */
127
    public function insertContentObject(CreateStruct $struct, $currentVersionNo = 1)
128
    {
129
        $initialLanguageId = !empty($struct->mainLanguageId) ? $struct->mainLanguageId : $struct->initialLanguageId;
130
        $initialLanguageCode = $this->languageHandler->load($initialLanguageId)->languageCode;
131
132
        if (isset($struct->name[$initialLanguageCode])) {
133
            $name = $struct->name[$initialLanguageCode];
134
        } else {
135
            $name = '';
136
        }
137
138
        $q = $this->dbHandler->createInsertQuery();
139
        $q->insertInto(
140
            $this->dbHandler->quoteTable('ezcontentobject')
141
        )->set(
142
            $this->dbHandler->quoteColumn('id'),
143
            $this->dbHandler->getAutoIncrementValue('ezcontentobject', 'id')
144
        )->set(
145
            $this->dbHandler->quoteColumn('current_version'),
146
            $q->bindValue($currentVersionNo, null, \PDO::PARAM_INT)
147
        )->set(
148
            $this->dbHandler->quoteColumn('name'),
149
            $q->bindValue($name, null, \PDO::PARAM_STR)
150
        )->set(
151
            $this->dbHandler->quoteColumn('contentclass_id'),
152
            $q->bindValue($struct->typeId, null, \PDO::PARAM_INT)
153
        )->set(
154
            $this->dbHandler->quoteColumn('section_id'),
155
            $q->bindValue($struct->sectionId, null, \PDO::PARAM_INT)
156
        )->set(
157
            $this->dbHandler->quoteColumn('owner_id'),
158
            $q->bindValue($struct->ownerId, null, \PDO::PARAM_INT)
159
        )->set(
160
            $this->dbHandler->quoteColumn('initial_language_id'),
161
            $q->bindValue($initialLanguageId, null, \PDO::PARAM_INT)
162
        )->set(
163
            $this->dbHandler->quoteColumn('remote_id'),
164
            $q->bindValue($struct->remoteId, null, \PDO::PARAM_STR)
165
        )->set(
166
            $this->dbHandler->quoteColumn('modified'),
167
            $q->bindValue(0, null, \PDO::PARAM_INT)
168
        )->set(
169
            $this->dbHandler->quoteColumn('published'),
170
            $q->bindValue(0, null, \PDO::PARAM_INT)
171
        )->set(
172
            $this->dbHandler->quoteColumn('status'),
173
            $q->bindValue(ContentInfo::STATUS_DRAFT, null, \PDO::PARAM_INT)
174
        )->set(
175
            $this->dbHandler->quoteColumn('language_mask'),
176
            $q->bindValue(
177
                $this->generateLanguageMask(
178
                    $struct->fields,
179
                    $initialLanguageCode,
180
                    $struct->alwaysAvailable
181
                ),
182
                null,
183
                \PDO::PARAM_INT
184
            )
185
        );
186
187
        $q->prepare()->execute();
188
189
        return $this->dbHandler->lastInsertId(
190
            $this->dbHandler->getSequenceName('ezcontentobject', 'id')
191
        );
192
    }
193
194
    /**
195
     * Generates a language mask for $fields.
196
     *
197
     * @param \eZ\Publish\SPI\Persistence\Content\Field[] $fields
198
     * @param string $initialLanguageCode
199
     * @param bool $isAlwaysAvailable
200
     *
201
     * @return int
202
     */
203
    protected function generateLanguageMask(array $fields, string $initialLanguageCode, bool $isAlwaysAvailable): int
204
    {
205
        $languages = array($initialLanguageCode => true);
206
        foreach ($fields as $field) {
207
            if (isset($languages[$field->languageCode])) {
208
                continue;
209
            }
210
211
            $languages[$field->languageCode] = true;
212
        }
213
214
        return $this->languageMaskGenerator->generateLanguageMaskFromLanguageCodes(array_keys($languages), $isAlwaysAvailable);
215
    }
216
217
    /**
218
     * Inserts a new version.
219
     *
220
     * @param \eZ\Publish\SPI\Persistence\Content\VersionInfo $versionInfo
221
     * @param \eZ\Publish\SPI\Persistence\Content\Field[] $fields
222
     *
223
     * @return int ID
224
     */
225
    public function insertVersion(VersionInfo $versionInfo, array $fields)
226
    {
227
        /** @var $q \eZ\Publish\Core\Persistence\Database\InsertQuery */
228
        $q = $this->dbHandler->createInsertQuery();
229
        $q->insertInto(
230
            $this->dbHandler->quoteTable('ezcontentobject_version')
231
        )->set(
232
            $this->dbHandler->quoteColumn('id'),
233
            $this->dbHandler->getAutoIncrementValue('ezcontentobject_version', 'id')
234
        )->set(
235
            $this->dbHandler->quoteColumn('version'),
236
            $q->bindValue($versionInfo->versionNo, null, \PDO::PARAM_INT)
237
        )->set(
238
            $this->dbHandler->quoteColumn('modified'),
239
            $q->bindValue($versionInfo->modificationDate, null, \PDO::PARAM_INT)
240
        )->set(
241
            $this->dbHandler->quoteColumn('creator_id'),
242
            $q->bindValue($versionInfo->creatorId, null, \PDO::PARAM_INT)
243
        )->set(
244
            $this->dbHandler->quoteColumn('created'),
245
            $q->bindValue($versionInfo->creationDate, null, \PDO::PARAM_INT)
246
        )->set(
247
            $this->dbHandler->quoteColumn('status'),
248
            $q->bindValue($versionInfo->status, null, \PDO::PARAM_INT)
249
        )->set(
250
            $this->dbHandler->quoteColumn('initial_language_id'),
251
            $q->bindValue(
252
                $this->languageHandler->loadByLanguageCode($versionInfo->initialLanguageCode)->id,
253
                null,
254
                \PDO::PARAM_INT
255
            )
256
        )->set(
257
            $this->dbHandler->quoteColumn('contentobject_id'),
258
            $q->bindValue($versionInfo->contentInfo->id, null, \PDO::PARAM_INT)
259
        )->set(
260
            // As described in field mapping document
261
            $this->dbHandler->quoteColumn('workflow_event_pos'),
262
            $q->bindValue(0, null, \PDO::PARAM_INT)
263
        )->set(
264
            $this->dbHandler->quoteColumn('language_mask'),
265
            $q->bindValue(
266
                $this->generateLanguageMask(
267
                    $fields,
268
                    $versionInfo->initialLanguageCode,
269
                    $versionInfo->contentInfo->alwaysAvailable
270
                ),
271
                null,
272
                \PDO::PARAM_INT
273
            )
274
        );
275
276
        $q->prepare()->execute();
277
278
        return $this->dbHandler->lastInsertId(
279
            $this->dbHandler->getSequenceName('ezcontentobject_version', 'id')
280
        );
281
    }
282
283
    /**
284
     * Updates an existing content identified by $contentId in respect to $struct.
285
     *
286
     * @param int $contentId
287
     * @param \eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct $struct
288
     * @param \eZ\Publish\SPI\Persistence\Content\VersionInfo $prePublishVersionInfo Provided on publish
289
     */
290
    public function updateContent($contentId, MetadataUpdateStruct $struct, VersionInfo $prePublishVersionInfo = null)
291
    {
292
        $q = $this->dbHandler->createUpdateQuery();
293
        $q->update($this->dbHandler->quoteTable('ezcontentobject'));
294
295
        if (isset($struct->name)) {
296
            $q->set(
297
                $this->dbHandler->quoteColumn('name'),
298
                $q->bindValue($struct->name, null, \PDO::PARAM_STR)
299
            );
300
        }
301
        if (isset($struct->mainLanguageId)) {
302
            $q->set(
303
                $this->dbHandler->quoteColumn('initial_language_id'),
304
                $q->bindValue($struct->mainLanguageId, null, \PDO::PARAM_INT)
305
            );
306
        }
307
        if (isset($struct->modificationDate)) {
308
            $q->set(
309
                $this->dbHandler->quoteColumn('modified'),
310
                $q->bindValue($struct->modificationDate, null, \PDO::PARAM_INT)
311
            );
312
        }
313
        if (isset($struct->ownerId)) {
314
            $q->set(
315
                $this->dbHandler->quoteColumn('owner_id'),
316
                $q->bindValue($struct->ownerId, null, \PDO::PARAM_INT)
317
            );
318
        }
319
        if (isset($struct->publicationDate)) {
320
            $q->set(
321
                $this->dbHandler->quoteColumn('published'),
322
                $q->bindValue($struct->publicationDate, null, \PDO::PARAM_INT)
323
            );
324
        }
325
        if (isset($struct->remoteId)) {
326
            $q->set(
327
                $this->dbHandler->quoteColumn('remote_id'),
328
                $q->bindValue($struct->remoteId, null, \PDO::PARAM_STR)
329
            );
330
        }
331
        if ($prePublishVersionInfo !== null) {
332
            $mask = $this->languageMaskGenerator->generateLanguageMaskFromLanguageCodes(
333
                $prePublishVersionInfo->languageCodes,
334
                $struct->alwaysAvailable ?? $prePublishVersionInfo->contentInfo->alwaysAvailable
335
            );
336
337
            $q->set(
338
                $this->dbHandler->quoteColumn('language_mask'),
339
                $q->bindValue($mask, null, \PDO::PARAM_INT)
340
            );
341
        }
342
        $q->where(
343
            $q->expr->eq(
344
                $this->dbHandler->quoteColumn('id'),
345
                $q->bindValue($contentId, null, \PDO::PARAM_INT)
346
            )
347
        );
348
        $q->prepare()->execute();
349
350
        // Handle alwaysAvailable flag update separately as it's a more complex task and has impact on several tables
351
        if (isset($struct->alwaysAvailable) || isset($struct->mainLanguageId)) {
352
            $this->updateAlwaysAvailableFlag($contentId, $struct->alwaysAvailable);
353
        }
354
    }
355
356
    /**
357
     * Updates version $versionNo for content identified by $contentId, in respect to $struct.
358
     *
359
     * @param int $contentId
360
     * @param int $versionNo
361
     * @param \eZ\Publish\SPI\Persistence\Content\UpdateStruct $struct
362
     */
363
    public function updateVersion($contentId, $versionNo, UpdateStruct $struct)
364
    {
365
        $q = $this->dbHandler->createUpdateQuery();
366
        $q->update(
367
            $this->dbHandler->quoteTable('ezcontentobject_version')
368
        )->set(
369
            $this->dbHandler->quoteColumn('creator_id'),
370
            $q->bindValue($struct->creatorId, null, \PDO::PARAM_INT)
371
        )->set(
372
            $this->dbHandler->quoteColumn('modified'),
373
            $q->bindValue($struct->modificationDate, null, \PDO::PARAM_INT)
374
        )->set(
375
            $this->dbHandler->quoteColumn('initial_language_id'),
376
            $q->bindValue($struct->initialLanguageId, null, \PDO::PARAM_INT)
377
        )->set(
378
            $this->dbHandler->quoteColumn('language_mask'),
379
            $q->expr->bitOr(
380
                $this->dbHandler->quoteColumn('language_mask'),
381
                $q->bindValue(
382
                    $this->generateLanguageMask(
383
                        $struct->fields,
384
                        $this->languageHandler->load($struct->initialLanguageId)->languageCode,
385
                        false
386
                    ),
387
                    null,
388
                    \PDO::PARAM_INT
389
                )
390
            )
391
        )->where(
392
            $q->expr->lAnd(
393
                $q->expr->eq(
394
                    $this->dbHandler->quoteColumn('contentobject_id'),
395
                    $q->bindValue($contentId, null, \PDO::PARAM_INT)
396
                ),
397
                $q->expr->eq(
398
                    $this->dbHandler->quoteColumn('version'),
399
                    $q->bindValue($versionNo, null, \PDO::PARAM_INT)
400
                )
401
            )
402
        );
403
        $q->prepare()->execute();
404
    }
405
406
    /**
407
     * Updates "always available" flag for Content identified by $contentId, in respect to
408
     * Content's current main language and optionally new $alwaysAvailable state.
409
     *
410
     * @param int $contentId
411
     * @param bool|null $alwaysAvailable New "always available" value or null if not defined
412
     */
413
    public function updateAlwaysAvailableFlag($contentId, $alwaysAvailable = null)
414
    {
415
        // We will need to know some info on the current language mask to update the flag
416
        // everywhere needed
417
        $contentInfoRow = $this->loadContentInfo($contentId);
418
        if (!isset($alwaysAvailable)) {
419
            $alwaysAvailable = (bool)$contentInfoRow['language_mask'] & 1;
420
        }
421
422
        /** @var $q \eZ\Publish\Core\Persistence\Database\UpdateQuery */
423
        $q = $this->dbHandler->createUpdateQuery();
424
        $q
425
            ->update($this->dbHandler->quoteTable('ezcontentobject'))
426
            ->set(
427
                $this->dbHandler->quoteColumn('language_mask'),
428
                $alwaysAvailable ?
429
                    $q->expr->bitOr($this->dbHandler->quoteColumn('language_mask'), 1) :
430
                    $q->expr->bitAnd($this->dbHandler->quoteColumn('language_mask'), -2)
431
            )
432
            ->where(
433
                $q->expr->eq(
434
                    $this->dbHandler->quoteColumn('id'),
435
                    $q->bindValue($contentId, null, \PDO::PARAM_INT)
436
                )
437
            );
438
        $q->prepare()->execute();
439
440
        // Now we need to update ezcontentobject_name
441
        /** @var $qName \eZ\Publish\Core\Persistence\Database\UpdateQuery */
442
        $qName = $this->dbHandler->createUpdateQuery();
443
        $qName
444
            ->update($this->dbHandler->quoteTable('ezcontentobject_name'))
445
            ->set(
446
                $this->dbHandler->quoteColumn('language_id'),
447
                $alwaysAvailable ?
448
                    $qName->expr->bitOr($this->dbHandler->quoteColumn('language_id'), 1) :
449
                    $qName->expr->bitAnd($this->dbHandler->quoteColumn('language_id'), -2)
450
            )
451
            ->where(
452
                $qName->expr->lAnd(
453
                    $qName->expr->eq(
454
                        $this->dbHandler->quoteColumn('contentobject_id'),
455
                        $qName->bindValue($contentId, null, \PDO::PARAM_INT)
456
                    ),
457
                    $qName->expr->eq(
458
                        $this->dbHandler->quoteColumn('content_version'),
459
                        $qName->bindValue(
460
                            $contentInfoRow['current_version'],
461
                            null,
462
                            \PDO::PARAM_INT
463
                        )
464
                    )
465
                )
466
            );
467
        $qName->prepare()->execute();
468
469
        // Now update ezcontentobject_attribute for current version
470
        // Create update query that will be reused
471
        /** @var $qAttr \eZ\Publish\Core\Persistence\Database\UpdateQuery */
472
        $qAttr = $this->dbHandler->createUpdateQuery();
473
        $qAttr
474
            ->update($this->dbHandler->quoteTable('ezcontentobject_attribute'))
475
            ->where(
476
                $qAttr->expr->lAnd(
477
                    $qAttr->expr->eq(
478
                        $this->dbHandler->quoteColumn('contentobject_id'),
479
                        $qAttr->bindValue($contentId, null, \PDO::PARAM_INT)
480
                    ),
481
                    $qAttr->expr->eq(
482
                        $this->dbHandler->quoteColumn('version'),
483
                        $qAttr->bindValue(
484
                            $contentInfoRow['current_version'],
485
                            null,
486
                            \PDO::PARAM_INT
487
                        )
488
                    )
489
                )
490
            );
491
492
        // If there is only a single language, update all fields and return
493
        if (!$this->languageMaskGenerator->isLanguageMaskComposite($contentInfoRow['language_mask'])) {
494
            $qAttr->set(
495
                $this->dbHandler->quoteColumn('language_id'),
496
                $alwaysAvailable ?
497
                    $qAttr->expr->bitOr($this->dbHandler->quoteColumn('language_id'), 1) :
498
                    $qAttr->expr->bitAnd($this->dbHandler->quoteColumn('language_id'), -2)
499
            );
500
            $qAttr->prepare()->execute();
501
502
            return;
503
        }
504
505
        // Otherwise:
506
        // 1. Remove always available flag on all fields
507
        $qAttr->set(
508
            $this->dbHandler->quoteColumn('language_id'),
509
            $qAttr->expr->bitAnd($this->dbHandler->quoteColumn('language_id'), -2)
510
        );
511
        $qAttr->prepare()->execute();
512
513
        // 2. If Content is always available set the flag only on fields in main language
514
        if ($alwaysAvailable) {
515
            $qAttr->set(
516
                $this->dbHandler->quoteColumn('language_id'),
517
                $qAttr->expr->bitOr($this->dbHandler->quoteColumn('language_id'), 1)
518
            );
519
            $qAttr->where(
520
                $qAttr->expr->gt(
521
                    $qAttr->expr->bitAnd(
522
                        $this->dbHandler->quoteColumn('language_id'),
523
                        $qAttr->bindValue($contentInfoRow['initial_language_id'], null, PDO::PARAM_INT)
524
                    ),
525
                    $qAttr->bindValue(0, null, PDO::PARAM_INT)
526
                )
527
            );
528
            $qAttr->prepare()->execute();
529
        }
530
    }
531
532
    /**
533
     * Sets the status of the version identified by $contentId and $version to $status.
534
     *
535
     * The $status can be one of STATUS_DRAFT, STATUS_PUBLISHED, STATUS_ARCHIVED
536
     *
537
     * @param int $contentId
538
     * @param int $version
539
     * @param int $status
540
     *
541
     * @return bool
542
     */
543
    public function setStatus($contentId, $version, $status)
544
    {
545
        $q = $this->dbHandler->createUpdateQuery();
546
        $q->update(
547
            $this->dbHandler->quoteTable('ezcontentobject_version')
548
        )->set(
549
            $this->dbHandler->quoteColumn('status'),
550
            $q->bindValue($status, null, \PDO::PARAM_INT)
551
        )->set(
552
            $this->dbHandler->quoteColumn('modified'),
553
            $q->bindValue(time(), null, \PDO::PARAM_INT)
554
        )->where(
555
            $q->expr->lAnd(
556
                $q->expr->eq(
557
                    $this->dbHandler->quoteColumn('contentobject_id'),
558
                    $q->bindValue($contentId, null, \PDO::PARAM_INT)
559
                ),
560
                $q->expr->eq(
561
                    $this->dbHandler->quoteColumn('version'),
562
                    $q->bindValue($version, null, \PDO::PARAM_INT)
563
                )
564
            )
565
        );
566
        $statement = $q->prepare();
567
        $statement->execute();
568
569
        if ((bool)$statement->rowCount() === false) {
570
            return false;
571
        }
572
573
        if ($status !== APIVersionInfo::STATUS_PUBLISHED) {
574
            return true;
575
        }
576
577
        // If the version's status is PUBLISHED, we set the content to published status as well
578
        $q = $this->dbHandler->createUpdateQuery();
579
        $q->update(
580
            $this->dbHandler->quoteTable('ezcontentobject')
581
        )->set(
582
            $this->dbHandler->quoteColumn('status'),
583
            $q->bindValue(ContentInfo::STATUS_PUBLISHED, null, \PDO::PARAM_INT)
584
        )->set(
585
            $this->dbHandler->quoteColumn('current_version'),
586
            $q->bindValue($version, null, \PDO::PARAM_INT)
587
        )->where(
588
            $q->expr->eq(
589
                $this->dbHandler->quoteColumn('id'),
590
                $q->bindValue($contentId, null, \PDO::PARAM_INT)
591
            )
592
        );
593
        $statement = $q->prepare();
594
        $statement->execute();
595
596
        return (bool)$statement->rowCount();
597
    }
598
599
    /**
600
     * Inserts a new field.
601
     *
602
     * Only used when a new field is created (i.e. a new object or a field in a
603
     * new language!). After that, field IDs need to stay the same, only the
604
     * version number changes.
605
     *
606
     * @param \eZ\Publish\SPI\Persistence\Content $content
607
     * @param \eZ\Publish\SPI\Persistence\Content\Field $field
608
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\StorageFieldValue $value
609
     *
610
     * @return int ID
611
     */
612
    public function insertNewField(Content $content, Field $field, StorageFieldValue $value)
613
    {
614
        $q = $this->dbHandler->createInsertQuery();
615
616
        $this->setInsertFieldValues($q, $content, $field, $value);
617
618
        // Insert with auto increment ID
619
        $q->set(
620
            $this->dbHandler->quoteColumn('id'),
621
            $this->dbHandler->getAutoIncrementValue('ezcontentobject_attribute', 'id')
622
        );
623
624
        $q->prepare()->execute();
625
626
        return $this->dbHandler->lastInsertId(
627
            $this->dbHandler->getSequenceName('ezcontentobject_attribute', 'id')
628
        );
629
    }
630
631
    /**
632
     * Inserts an existing field.
633
     *
634
     * Used to insert a field with an exsting ID but a new version number.
635
     *
636
     * @param Content $content
637
     * @param Field $field
638
     * @param StorageFieldValue $value
639
     */
640
    public function insertExistingField(Content $content, Field $field, StorageFieldValue $value)
641
    {
642
        $q = $this->dbHandler->createInsertQuery();
643
644
        $this->setInsertFieldValues($q, $content, $field, $value);
645
646
        $q->set(
647
            $this->dbHandler->quoteColumn('id'),
648
            $q->bindValue($field->id, null, \PDO::PARAM_INT)
649
        );
650
651
        $q->prepare()->execute();
652
    }
653
654
    /**
655
     * Sets field (ezcontentobject_attribute) values to the given query.
656
     *
657
     * @param \eZ\Publish\Core\Persistence\Database\InsertQuery $q
658
     * @param Content $content
659
     * @param Field $field
660
     * @param StorageFieldValue $value
661
     */
662
    protected function setInsertFieldValues(InsertQuery $q, Content $content, Field $field, StorageFieldValue $value)
663
    {
664
        $q->insertInto(
665
            $this->dbHandler->quoteTable('ezcontentobject_attribute')
666
        )->set(
667
            $this->dbHandler->quoteColumn('contentobject_id'),
668
            $q->bindValue($content->versionInfo->contentInfo->id, null, \PDO::PARAM_INT)
669
        )->set(
670
            $this->dbHandler->quoteColumn('contentclassattribute_id'),
671
            $q->bindValue($field->fieldDefinitionId, null, \PDO::PARAM_INT)
672
        )->set(
673
            $this->dbHandler->quoteColumn('data_type_string'),
674
            $q->bindValue($field->type)
675
        )->set(
676
            $this->dbHandler->quoteColumn('language_code'),
677
            $q->bindValue($field->languageCode)
678
        )->set(
679
            $this->dbHandler->quoteColumn('version'),
680
            $q->bindValue($field->versionNo, null, \PDO::PARAM_INT)
681
        )->set(
682
            $this->dbHandler->quoteColumn('data_float'),
683
            $q->bindValue($value->dataFloat)
684
        )->set(
685
            $this->dbHandler->quoteColumn('data_int'),
686
            $q->bindValue($value->dataInt, null, \PDO::PARAM_INT)
687
        )->set(
688
            $this->dbHandler->quoteColumn('data_text'),
689
            $q->bindValue($value->dataText)
690
        )->set(
691
            $this->dbHandler->quoteColumn('sort_key_int'),
692
            $q->bindValue($value->sortKeyInt, null, \PDO::PARAM_INT)
693
        )->set(
694
            $this->dbHandler->quoteColumn('sort_key_string'),
695
            $q->bindValue(mb_substr($value->sortKeyString, 0, 255))
696
        )->set(
697
            $this->dbHandler->quoteColumn('language_id'),
698
            $q->bindValue(
699
                $this->languageMaskGenerator->generateLanguageIndicator(
700
                    $field->languageCode,
701
                    $this->isLanguageAlwaysAvailable($content, $field->languageCode)
702
                ),
703
                null,
704
                \PDO::PARAM_INT
705
            )
706
        );
707
    }
708
709
    /**
710
     * Checks if $languageCode is always available in $content.
711
     *
712
     * @param \eZ\Publish\SPI\Persistence\Content $content
713
     * @param string $languageCode
714
     *
715
     * @return bool
716
     */
717
    protected function isLanguageAlwaysAvailable(Content $content, $languageCode)
718
    {
719
        return
720
            $content->versionInfo->contentInfo->alwaysAvailable &&
721
            $content->versionInfo->contentInfo->mainLanguageCode === $languageCode
722
        ;
723
    }
724
725
    /**
726
     * Updates an existing field.
727
     *
728
     * @param Field $field
729
     * @param StorageFieldValue $value
730
     */
731
    public function updateField(Field $field, StorageFieldValue $value)
732
    {
733
        // Note, no need to care for language_id here, since Content->$alwaysAvailable
734
        // cannot change on update
735
        $q = $this->dbHandler->createUpdateQuery();
736
        $this->setFieldUpdateValues($q, $value);
737
        $q->where(
738
            $q->expr->lAnd(
739
                $q->expr->eq(
740
                    $this->dbHandler->quoteColumn('id'),
741
                    $q->bindValue($field->id, null, \PDO::PARAM_INT)
742
                ),
743
                $q->expr->eq(
744
                    $this->dbHandler->quoteColumn('version'),
745
                    $q->bindValue($field->versionNo, null, \PDO::PARAM_INT)
746
                )
747
            )
748
        );
749
        $q->prepare()->execute();
750
    }
751
752
    /**
753
     * Sets update fields for $value on $q.
754
     *
755
     * @param \eZ\Publish\Core\Persistence\Database\UpdateQuery $q
756
     * @param StorageFieldValue $value
757
     */
758
    protected function setFieldUpdateValues(UpdateQuery $q, StorageFieldValue $value)
759
    {
760
        $q->update(
761
            $this->dbHandler->quoteTable('ezcontentobject_attribute')
762
        )->set(
763
            $this->dbHandler->quoteColumn('data_float'),
764
            $q->bindValue($value->dataFloat)
765
        )->set(
766
            $this->dbHandler->quoteColumn('data_int'),
767
            $q->bindValue($value->dataInt, null, \PDO::PARAM_INT)
768
        )->set(
769
            $this->dbHandler->quoteColumn('data_text'),
770
            $q->bindValue($value->dataText)
771
        )->set(
772
            $this->dbHandler->quoteColumn('sort_key_int'),
773
            $q->bindValue($value->sortKeyInt, null, \PDO::PARAM_INT)
774
        )->set(
775
            $this->dbHandler->quoteColumn('sort_key_string'),
776
            $q->bindValue(mb_substr($value->sortKeyString, 0, 255))
777
        );
778
    }
779
780
    /**
781
     * Updates an existing, non-translatable field.
782
     *
783
     * @param \eZ\Publish\SPI\Persistence\Content\Field $field
784
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\StorageFieldValue $value
785
     * @param int $contentId
786
     */
787
    public function updateNonTranslatableField(
788
        Field $field,
789
        StorageFieldValue $value,
790
        $contentId
791
    ) {
792
        // Note, no need to care for language_id here, since Content->$alwaysAvailable
793
        // cannot change on update
794
        $q = $this->dbHandler->createUpdateQuery();
795
        $this->setFieldUpdateValues($q, $value);
796
        $q->where(
797
            $q->expr->lAnd(
798
                $q->expr->eq(
799
                    $this->dbHandler->quoteColumn('contentclassattribute_id'),
800
                    $q->bindValue($field->fieldDefinitionId, null, \PDO::PARAM_INT)
801
                ),
802
                $q->expr->eq(
803
                    $this->dbHandler->quoteColumn('contentobject_id'),
804
                    $q->bindValue($contentId, null, \PDO::PARAM_INT)
805
                ),
806
                $q->expr->eq(
807
                    $this->dbHandler->quoteColumn('version'),
808
                    $q->bindValue($field->versionNo, null, \PDO::PARAM_INT)
809
                )
810
            )
811
        );
812
        $q->prepare()->execute();
813
    }
814
815
    /**
816
     * {@inheritdoc}
817
     */
818
    public function load($contentId, $version = null, array $translations = null)
819
    {
820
        return $this->internalLoadContent([$contentId], $version, $translations);
0 ignored issues
show
Bug introduced by
It seems like $translations defined by parameter $translations on line 818 can also be of type array; however, eZ\Publish\Core\Persiste...::internalLoadContent() does only seem to accept null|array<integer,string>, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
821
    }
822
823
    /**
824
     * {@inheritdoc}
825
     */
826
    public function loadContentList(array $contentIds, array $translations = null): array
827
    {
828
        return $this->internalLoadContent($contentIds, null, $translations);
0 ignored issues
show
Bug introduced by
It seems like $translations defined by parameter $translations on line 826 can also be of type array; however, eZ\Publish\Core\Persiste...::internalLoadContent() does only seem to accept null|array<integer,string>, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
829
    }
830
831
    /**
832
     * @see load(), loadContentList()
833
     *
834
     * @param array $contentIds
835
     * @param int|null $version
836
     * @param string[]|null $translations
837
     *
838
     * @return array
839
     */
840
    private function internalLoadContent(array $contentIds, int $version = null, array $translations = null): array
841
    {
842
        $queryBuilder = $this->connection->createQueryBuilder();
843
        $expr = $queryBuilder->expr();
844
        $queryBuilder
845
            ->select(
846
                'c.id AS ezcontentobject_id',
847
                'c.contentclass_id AS ezcontentobject_contentclass_id',
848
                'c.section_id AS ezcontentobject_section_id',
849
                'c.owner_id AS ezcontentobject_owner_id',
850
                'c.remote_id AS ezcontentobject_remote_id',
851
                'c.current_version AS ezcontentobject_current_version',
852
                'c.initial_language_id AS ezcontentobject_initial_language_id',
853
                'c.modified AS ezcontentobject_modified',
854
                'c.published AS ezcontentobject_published',
855
                'c.status AS ezcontentobject_status',
856
                'c.name AS ezcontentobject_name',
857
                'c.language_mask AS ezcontentobject_language_mask',
858
                'v.id AS ezcontentobject_version_id',
859
                'v.version AS ezcontentobject_version_version',
860
                'v.modified AS ezcontentobject_version_modified',
861
                'v.creator_id AS ezcontentobject_version_creator_id',
862
                'v.created AS ezcontentobject_version_created',
863
                'v.status AS ezcontentobject_version_status',
864
                'v.language_mask AS ezcontentobject_version_language_mask',
865
                'v.initial_language_id AS ezcontentobject_version_initial_language_id',
866
                'a.id AS ezcontentobject_attribute_id',
867
                'a.contentclassattribute_id AS ezcontentobject_attribute_contentclassattribute_id',
868
                'a.data_type_string AS ezcontentobject_attribute_data_type_string',
869
                'a.language_code AS ezcontentobject_attribute_language_code',
870
                'a.language_id AS ezcontentobject_attribute_language_id',
871
                'a.data_float AS ezcontentobject_attribute_data_float',
872
                'a.data_int AS ezcontentobject_attribute_data_int',
873
                'a.data_text AS ezcontentobject_attribute_data_text',
874
                'a.sort_key_int AS ezcontentobject_attribute_sort_key_int',
875
                'a.sort_key_string AS ezcontentobject_attribute_sort_key_string',
876
                't.main_node_id AS ezcontentobject_tree_main_node_id'
877
            )
878
            ->from('ezcontentobject', 'c')
879
            ->innerJoin(
880
                'c',
881
                'ezcontentobject_version',
882
                'v',
883
                $expr->andX(
884
                    $expr->eq('c.id', 'v.contentobject_id'),
885
                    $expr->eq('v.version', $version ?? 'c.current_version')
886
                )
887
            )
888
            ->innerJoin(
889
                'v',
890
                'ezcontentobject_attribute',
891
                'a',
892
                $expr->andX(
893
                    $expr->eq('v.contentobject_id', 'a.contentobject_id'),
894
                    $expr->eq('v.version', 'a.version')
895
                )
896
            )
897
            ->leftJoin(
898
                'c',
899
                'ezcontentobject_tree',
900
                't',
901
                $expr->andX(
902
                    $expr->eq('c.id', 't.contentobject_id'),
903
                    $expr->eq('t.node_id', 't.main_node_id')
904
                )
905
            );
906
907
        $queryBuilder->where(
908
            $expr->in(
909
                'c.id',
910
                $queryBuilder->createNamedParameter($contentIds, Connection::PARAM_INT_ARRAY)
911
            )
912
        );
913
914
        if (!empty($translations)) {
915
            $queryBuilder->andWhere(
916
                $expr->in(
917
                    'a.language_code',
918
                    $queryBuilder->createNamedParameter($translations, Connection::PARAM_STR_ARRAY)
919
                )
920
            );
921
        }
922
923
        return $queryBuilder->execute()->fetchAll(FetchMode::ASSOCIATIVE);
924
    }
925
926
    /**
927
     * Get query builder to load Content Info data.
928
     *
929
     * @see loadContentInfo(), loadContentInfoByRemoteId(), loadContentInfoList(), loadContentInfoByLocationId()
930
     *
931
     * @return \Doctrine\DBAL\Query\QueryBuilder
932
     */
933
    private function createLoadContentInfoQueryBuilder(): DoctrineQueryBuilder
934
    {
935
        $queryBuilder = $this->connection->createQueryBuilder();
936
        $expr = $queryBuilder->expr();
937
        $queryBuilder
938
            ->select('c.*', 't.main_node_id AS ezcontentobject_tree_main_node_id')
939
            ->from('ezcontentobject', 'c')
940
            ->leftJoin(
941
                'c',
942
                'ezcontentobject_tree',
943
                't',
944
                $expr->andX(
945
                    $expr->eq('c.id', 't.contentobject_id'),
946
                    $expr->eq('t.node_id', 't.main_node_id')
947
                )
948
            );
949
950
        return $queryBuilder;
951
    }
952
953
    /**
954
     * Loads info for content identified by $contentId.
955
     * Will basically return a hash containing all field values for ezcontentobject table plus some additional keys:
956
     *  - always_available => Boolean indicating if content's language mask contains alwaysAvailable bit field
957
     *  - main_language_code => Language code for main (initial) language. E.g. "eng-GB".
958
     *
959
     * @param int $contentId
960
     *
961
     * @throws \eZ\Publish\Core\Base\Exceptions\NotFoundException
962
     *
963
     * @return array
964
     */
965 View Code Duplication
    public function loadContentInfo($contentId)
966
    {
967
        $queryBuilder = $this->createLoadContentInfoQueryBuilder();
968
        $queryBuilder
969
            ->where('c.id = :id')
970
            ->setParameter('id', $contentId, ParameterType::INTEGER);
971
972
        $results = $queryBuilder->execute()->fetchAll(FetchMode::ASSOCIATIVE);
973
        if (empty($results)) {
974
            throw new NotFound('content', "id: $contentId");
975
        }
976
977
        return $results[0];
978
    }
979
980
    public function loadContentInfoList(array $contentIds)
981
    {
982
        $queryBuilder = $this->createLoadContentInfoQueryBuilder();
983
        $queryBuilder
984
            ->where('c.id IN (:ids)')
985
            ->setParameter('ids', $contentIds, Connection::PARAM_INT_ARRAY);
986
987
        return $queryBuilder->execute()->fetchAll(FetchMode::ASSOCIATIVE);
988
    }
989
990
    /**
991
     * Loads info for a content object identified by its remote ID.
992
     *
993
     * Returns an array with the relevant data.
994
     *
995
     * @param mixed $remoteId
996
     *
997
     * @throws \eZ\Publish\Core\Base\Exceptions\NotFoundException
998
     *
999
     * @return array
1000
     */
1001 View Code Duplication
    public function loadContentInfoByRemoteId($remoteId)
1002
    {
1003
        $queryBuilder = $this->createLoadContentInfoQueryBuilder();
1004
        $queryBuilder
1005
            ->where('c.remote_id = :id')
1006
            ->setParameter('id', $remoteId, ParameterType::STRING);
1007
1008
        $results = $queryBuilder->execute()->fetchAll(FetchMode::ASSOCIATIVE);
1009
        if (empty($results)) {
1010
            throw new NotFound('content', "remote_id: $remoteId");
1011
        }
1012
1013
        return $results[0];
1014
    }
1015
1016
    /**
1017
     * Loads info for a content object identified by its location ID (node ID).
1018
     *
1019
     * Returns an array with the relevant data.
1020
     *
1021
     * @param int $locationId
1022
     *
1023
     * @throws \eZ\Publish\Core\Base\Exceptions\NotFoundException
1024
     *
1025
     * @return array
1026
     */
1027
    public function loadContentInfoByLocationId($locationId)
1028
    {
1029
        $queryBuilder = $this->createLoadContentInfoQueryBuilder();
1030
        $queryBuilder
1031
            ->where('t.main_node_id = :id')
1032
            ->setParameter('id', $locationId, ParameterType::INTEGER);
1033
1034
        $results = $queryBuilder->execute()->fetchAll(FetchMode::ASSOCIATIVE);
1035
        if (empty($results)) {
1036
            throw new NotFound('content', "main_node_id: $locationId");
1037
        }
1038
1039
        return $results[0];
1040
    }
1041
1042
    /**
1043
     * Loads version info for content identified by $contentId and $versionNo.
1044
     * Will basically return a hash containing all field values from ezcontentobject_version table plus following keys:
1045
     *  - names => Hash of content object names. Key is the language code, value is the name.
1046
     *  - languages => Hash of language ids. Key is the language code (e.g. "eng-GB"), value is the language numeric id without the always available bit.
1047
     *  - initial_language_code => Language code for initial language in this version.
1048
     *
1049
     * @param int $contentId
1050
     * @param int $versionNo
1051
     *
1052
     * @return array
1053
     */
1054 View Code Duplication
    public function loadVersionInfo($contentId, $versionNo)
1055
    {
1056
        $query = $this->queryBuilder->createVersionInfoFindQuery();
1057
        $query->where(
1058
            $query->expr->lAnd(
1059
                $query->expr->eq(
1060
                    $this->dbHandler->quoteColumn('contentobject_id', 'ezcontentobject_version'),
1061
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1062
                ),
1063
                $query->expr->eq(
1064
                    $this->dbHandler->quoteColumn('version', 'ezcontentobject_version'),
1065
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1066
                )
1067
            )
1068
        );
1069
        $statement = $query->prepare();
1070
        $statement->execute();
1071
1072
        return $statement->fetchAll(\PDO::FETCH_ASSOC);
1073
    }
1074
1075
    /**
1076
     * Returns data for all versions with given status created by the given $userId.
1077
     *
1078
     * @param int $userId
1079
     * @param int $status
1080
     *
1081
     * @return string[][]
1082
     */
1083
    public function listVersionsForUser($userId, $status = VersionInfo::STATUS_DRAFT)
1084
    {
1085
        $query = $this->queryBuilder->createVersionInfoFindQuery();
1086
        $query->where(
1087
            $query->expr->lAnd(
1088
                $query->expr->eq(
1089
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject_version'),
1090
                    $query->bindValue($status, null, \PDO::PARAM_INT)
1091
                ),
1092
                $query->expr->eq(
1093
                    $this->dbHandler->quoteColumn('creator_id', 'ezcontentobject_version'),
1094
                    $query->bindValue($userId, null, \PDO::PARAM_INT)
1095
                )
1096
            )
1097
        );
1098
1099
        return $this->listVersionsHelper($query);
1100
    }
1101
1102
    /**
1103
     * Returns all version data for the given $contentId, optionally filtered by status.
1104
     *
1105
     * Result is returned with oldest version first (using version id as it has index and is auto increment).
1106
     *
1107
     * @param mixed $contentId
1108
     * @param mixed|null $status Optional argument to filter versions by status, like {@see VersionInfo::STATUS_ARCHIVED}.
1109
     * @param int $limit Limit for items returned, -1 means none.
1110
     *
1111
     * @return string[][]
1112
     */
1113
    public function listVersions($contentId, $status = null, $limit = -1)
1114
    {
1115
        $query = $this->queryBuilder->createVersionInfoFindQuery();
1116
1117
        $filter = $query->expr->eq(
1118
            $this->dbHandler->quoteColumn('contentobject_id', 'ezcontentobject_version'),
1119
            $query->bindValue($contentId, null, \PDO::PARAM_INT)
1120
        );
1121
1122
        if ($status !== null) {
1123
            $filter = $query->expr->lAnd(
1124
                $filter,
1125
                $query->expr->eq(
1126
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject_version'),
1127
                    $query->bindValue($status, null, \PDO::PARAM_INT)
1128
                )
1129
            );
1130
        }
1131
1132
        $query->where($filter);
1133
1134
        if ($limit > 0) {
1135
            $query->limit($limit);
1136
        }
1137
1138
        return $this->listVersionsHelper($query);
1139
    }
1140
1141
    /**
1142
     * Helper for {@see listVersions()} and {@see listVersionsForUser()} that filters duplicates
1143
     * that are the result of the cartesian product performed by createVersionInfoFindQuery().
1144
     *
1145
     * @param \eZ\Publish\Core\Persistence\Database\SelectQuery $query
1146
     *
1147
     * @return string[][]
1148
     */
1149
    private function listVersionsHelper(SelectQuery $query)
1150
    {
1151
        $query->orderBy(
1152
            $this->dbHandler->quoteColumn('id', 'ezcontentobject_version')
1153
        );
1154
1155
        $statement = $query->prepare();
1156
        $statement->execute();
1157
1158
        $results = array();
1159
        $previousId = null;
1160
        foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1161
            if ($row['ezcontentobject_version_id'] == $previousId) {
1162
                continue;
1163
            }
1164
1165
            $previousId = $row['ezcontentobject_version_id'];
1166
            $results[] = $row;
1167
        }
1168
1169
        return $results;
1170
    }
1171
1172
    /**
1173
     * Returns all version numbers for the given $contentId.
1174
     *
1175
     * @param mixed $contentId
1176
     *
1177
     * @return int[]
1178
     */
1179
    public function listVersionNumbers($contentId)
1180
    {
1181
        $query = $this->dbHandler->createSelectQuery();
1182
        $query->selectDistinct(
1183
            $this->dbHandler->quoteColumn('version')
1184
        )->from(
1185
            $this->dbHandler->quoteTable('ezcontentobject_version')
1186
        )->where(
1187
            $query->expr->eq(
1188
                $this->dbHandler->quoteColumn('contentobject_id'),
1189
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1190
            )
1191
        );
1192
1193
        $statement = $query->prepare();
1194
        $statement->execute();
1195
1196
        return $statement->fetchAll(\PDO::FETCH_COLUMN);
1197
    }
1198
1199
    /**
1200
     * Returns last version number for content identified by $contentId.
1201
     *
1202
     * @param int $contentId
1203
     *
1204
     * @return int
1205
     */
1206
    public function getLastVersionNumber($contentId)
1207
    {
1208
        $query = $this->dbHandler->createSelectQuery();
1209
        $query->select(
1210
            $query->expr->max($this->dbHandler->quoteColumn('version'))
1211
        )->from(
1212
            $this->dbHandler->quoteTable('ezcontentobject_version')
1213
        )->where(
1214
            $query->expr->eq(
1215
                $this->dbHandler->quoteColumn('contentobject_id'),
1216
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1217
            )
1218
        );
1219
1220
        $statement = $query->prepare();
1221
        $statement->execute();
1222
1223
        return (int)$statement->fetchColumn();
1224
    }
1225
1226
    /**
1227
     * Returns all IDs for locations that refer to $contentId.
1228
     *
1229
     * @param int $contentId
1230
     *
1231
     * @return int[]
1232
     */
1233
    public function getAllLocationIds($contentId)
1234
    {
1235
        $query = $this->dbHandler->createSelectQuery();
1236
        $query->select(
1237
            $this->dbHandler->quoteColumn('node_id')
1238
        )->from(
1239
            $this->dbHandler->quoteTable('ezcontentobject_tree')
1240
        )->where(
1241
            $query->expr->eq(
1242
                $this->dbHandler->quoteColumn('contentobject_id'),
1243
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1244
            )
1245
        );
1246
1247
        $statement = $query->prepare();
1248
        $statement->execute();
1249
1250
        return $statement->fetchAll(\PDO::FETCH_COLUMN);
1251
    }
1252
1253
    /**
1254
     * Returns all field IDs of $contentId grouped by their type.
1255
     * If $versionNo is set only field IDs for that version are returned.
1256
     * If $languageCode is set, only field IDs for that language are returned.
1257
     *
1258
     * @param int $contentId
1259
     * @param int|null $versionNo
1260
     * @param string|null $languageCode
1261
     *
1262
     * @return int[][]
1263
     */
1264
    public function getFieldIdsByType($contentId, $versionNo = null, $languageCode = null)
1265
    {
1266
        $query = $this->dbHandler->createSelectQuery();
1267
        $query->select(
1268
            $this->dbHandler->quoteColumn('id'),
1269
            $this->dbHandler->quoteColumn('data_type_string')
1270
        )->from(
1271
            $this->dbHandler->quoteTable('ezcontentobject_attribute')
1272
        )->where(
1273
            $query->expr->eq(
1274
                $this->dbHandler->quoteColumn('contentobject_id'),
1275
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1276
            )
1277
        );
1278
1279
        if (isset($versionNo)) {
1280
            $query->where(
1281
                $query->expr->eq(
1282
                    $this->dbHandler->quoteColumn('version'),
1283
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1284
                )
1285
            );
1286
        }
1287
1288
        if (isset($languageCode)) {
1289
            $query->where(
1290
                $query->expr->eq(
1291
                    $this->dbHandler->quoteColumn('language_code'),
1292
                    $query->bindValue($languageCode, null, \PDO::PARAM_STR)
1293
                )
1294
            );
1295
        }
1296
1297
        $statement = $query->prepare();
1298
        $statement->execute();
1299
1300
        $result = array();
1301
        foreach ($statement->fetchAll() as $row) {
1302
            if (!isset($result[$row['data_type_string']])) {
1303
                $result[$row['data_type_string']] = array();
1304
            }
1305
            $result[$row['data_type_string']][] = (int)$row['id'];
1306
        }
1307
1308
        return $result;
1309
    }
1310
1311
    /**
1312
     * Deletes relations to and from $contentId.
1313
     * If $versionNo is set only relations for that version are deleted.
1314
     *
1315
     * @param int $contentId
1316
     * @param int|null $versionNo
1317
     */
1318
    public function deleteRelations($contentId, $versionNo = null)
1319
    {
1320
        $query = $this->dbHandler->createDeleteQuery();
1321
        $query->deleteFrom(
1322
            $this->dbHandler->quoteTable('ezcontentobject_link')
1323
        );
1324
1325
        if (isset($versionNo)) {
1326
            $query->where(
1327
                $query->expr->lAnd(
1328
                    $query->expr->eq(
1329
                        $this->dbHandler->quoteColumn('from_contentobject_id'),
1330
                        $query->bindValue($contentId, null, \PDO::PARAM_INT)
1331
                    ),
1332
                    $query->expr->eq(
1333
                        $this->dbHandler->quoteColumn('from_contentobject_version'),
1334
                        $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1335
                    )
1336
                )
1337
            );
1338
        } else {
1339
            $query->where(
1340
                $query->expr->lOr(
1341
                    $query->expr->eq(
1342
                        $this->dbHandler->quoteColumn('from_contentobject_id'),
1343
                        $query->bindValue($contentId, null, \PDO::PARAM_INT)
1344
                    ),
1345
                    $query->expr->eq(
1346
                        $this->dbHandler->quoteColumn('to_contentobject_id'),
1347
                        $query->bindValue($contentId, null, \PDO::PARAM_INT)
1348
                    )
1349
                )
1350
            );
1351
        }
1352
1353
        $query->prepare()->execute();
1354
    }
1355
1356
    /**
1357
     * Removes relations to Content with $contentId from Relation and RelationList field type fields.
1358
     *
1359
     * @param int $contentId
1360
     */
1361
    public function removeReverseFieldRelations($contentId)
1362
    {
1363
        $query = $this->dbHandler->createSelectQuery();
1364
        $query
1365
            ->select('ezcontentobject_attribute.*')
1366
            ->from('ezcontentobject_attribute')
1367
            ->innerJoin(
1368
                'ezcontentobject_link',
1369
                $query->expr->lAnd(
1370
                    $query->expr->eq(
1371
                        $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link'),
1372
                        $this->dbHandler->quoteColumn('contentobject_id', 'ezcontentobject_attribute')
1373
                    ),
1374
                    $query->expr->eq(
1375
                        $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link'),
1376
                        $this->dbHandler->quoteColumn('version', 'ezcontentobject_attribute')
1377
                    ),
1378
                    $query->expr->eq(
1379
                        $this->dbHandler->quoteColumn('contentclassattribute_id', 'ezcontentobject_link'),
1380
                        $this->dbHandler->quoteColumn('contentclassattribute_id', 'ezcontentobject_attribute')
1381
                    )
1382
                )
1383
            )
1384
            ->where(
1385
                $query->expr->eq(
1386
                    $this->dbHandler->quoteColumn('to_contentobject_id', 'ezcontentobject_link'),
1387
                    $query->bindValue($contentId, null, PDO::PARAM_INT)
1388
                ),
1389
                $query->expr->gt(
1390
                    $query->expr->bitAnd(
1391
                        $this->dbHandler->quoteColumn('relation_type', 'ezcontentobject_link'),
1392
                        $query->bindValue(8, null, PDO::PARAM_INT)
1393
                    ),
1394
                    0
1395
                )
1396
            );
1397
1398
        $statement = $query->prepare();
1399
        $statement->execute();
1400
1401
        while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
1402
            if ($row['data_type_string'] === 'ezobjectrelation') {
1403
                $this->removeRelationFromRelationField($row);
1404
            }
1405
1406
            if ($row['data_type_string'] === 'ezobjectrelationlist') {
1407
                $this->removeRelationFromRelationListField($contentId, $row);
1408
            }
1409
        }
1410
    }
1411
1412
    /**
1413
     * Updates field value of RelationList field type identified by given $row data,
1414
     * removing relations toward given $contentId.
1415
     *
1416
     * @param int $contentId
1417
     * @param array $row
1418
     */
1419
    protected function removeRelationFromRelationListField($contentId, array $row)
1420
    {
1421
        $document = new DOMDocument('1.0', 'utf-8');
1422
        $document->loadXML($row['data_text']);
1423
1424
        $xpath = new DOMXPath($document);
1425
        $xpathExpression = "//related-objects/relation-list/relation-item[@contentobject-id='{$contentId}']";
1426
1427
        $relationItems = $xpath->query($xpathExpression);
1428
        foreach ($relationItems as $relationItem) {
1429
            $relationItem->parentNode->removeChild($relationItem);
1430
        }
1431
1432
        $query = $this->dbHandler->createUpdateQuery();
1433
        $query
1434
            ->update('ezcontentobject_attribute')
1435
            ->set(
1436
                'data_text',
1437
                $query->bindValue($document->saveXML(), null, PDO::PARAM_STR)
1438
            )
1439
            ->where(
1440
                $query->expr->lAnd(
1441
                    $query->expr->eq(
1442
                        $this->dbHandler->quoteColumn('id'),
1443
                        $query->bindValue($row['id'], null, PDO::PARAM_INT)
1444
                    ),
1445
                    $query->expr->eq(
1446
                        $this->dbHandler->quoteColumn('version'),
1447
                        $query->bindValue($row['version'], null, PDO::PARAM_INT)
1448
                    )
1449
                )
1450
            );
1451
1452
        $query->prepare()->execute();
1453
    }
1454
1455
    /**
1456
     * Updates field value of Relation field type identified by given $row data,
1457
     * removing relation data.
1458
     *
1459
     * @param array $row
1460
     */
1461
    protected function removeRelationFromRelationField(array $row)
1462
    {
1463
        $query = $this->dbHandler->createUpdateQuery();
1464
        $query
1465
            ->update('ezcontentobject_attribute')
1466
            ->set('data_int', $query->bindValue(null, null, PDO::PARAM_INT))
1467
            ->set('sort_key_int', $query->bindValue(0, null, PDO::PARAM_INT))
1468
            ->where(
1469
                $query->expr->lAnd(
1470
                    $query->expr->eq(
1471
                        $this->dbHandler->quoteColumn('id'),
1472
                        $query->bindValue($row['id'], null, PDO::PARAM_INT)
1473
                    ),
1474
                    $query->expr->eq(
1475
                        $this->dbHandler->quoteColumn('version'),
1476
                        $query->bindValue($row['version'], null, PDO::PARAM_INT)
1477
                    )
1478
                )
1479
            );
1480
1481
        $query->prepare()->execute();
1482
    }
1483
1484
    /**
1485
     * Deletes the field with the given $fieldId.
1486
     *
1487
     * @param int $fieldId
1488
     */
1489
    public function deleteField($fieldId)
1490
    {
1491
        $query = $this->dbHandler->createDeleteQuery();
1492
        $query->deleteFrom(
1493
            $this->dbHandler->quoteTable('ezcontentobject_attribute')
1494
        )->where(
1495
            $query->expr->eq(
1496
                $this->dbHandler->quoteColumn('id'),
1497
                $query->bindValue($fieldId, null, \PDO::PARAM_INT)
1498
            )
1499
        );
1500
1501
        $query->prepare()->execute();
1502
    }
1503
1504
    /**
1505
     * Deletes all fields of $contentId in all versions.
1506
     * If $versionNo is set only fields for that version are deleted.
1507
     *
1508
     * @param int $contentId
1509
     * @param int|null $versionNo
1510
     */
1511
    public function deleteFields($contentId, $versionNo = null)
1512
    {
1513
        $query = $this->dbHandler->createDeleteQuery();
1514
        $query->deleteFrom('ezcontentobject_attribute')
1515
            ->where(
1516
                $query->expr->eq(
1517
                    $this->dbHandler->quoteColumn('contentobject_id'),
1518
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1519
                )
1520
            );
1521
1522
        if (isset($versionNo)) {
1523
            $query->where(
1524
                $query->expr->eq(
1525
                    $this->dbHandler->quoteColumn('version'),
1526
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1527
                )
1528
            );
1529
        }
1530
1531
        $query->prepare()->execute();
1532
    }
1533
1534
    /**
1535
     * Deletes all versions of $contentId.
1536
     * If $versionNo is set only that version is deleted.
1537
     *
1538
     * @param int $contentId
1539
     * @param int|null $versionNo
1540
     */
1541
    public function deleteVersions($contentId, $versionNo = null)
1542
    {
1543
        $query = $this->dbHandler->createDeleteQuery();
1544
        $query->deleteFrom('ezcontentobject_version')
1545
            ->where(
1546
                $query->expr->eq(
1547
                    $this->dbHandler->quoteColumn('contentobject_id'),
1548
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1549
                )
1550
            );
1551
1552
        if (isset($versionNo)) {
1553
            $query->where(
1554
                $query->expr->eq(
1555
                    $this->dbHandler->quoteColumn('version'),
1556
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1557
                )
1558
            );
1559
        }
1560
1561
        $query->prepare()->execute();
1562
    }
1563
1564
    /**
1565
     * Deletes all names of $contentId.
1566
     * If $versionNo is set only names for that version are deleted.
1567
     *
1568
     * @param int $contentId
1569
     * @param int|null $versionNo
1570
     */
1571
    public function deleteNames($contentId, $versionNo = null)
1572
    {
1573
        $query = $this->dbHandler->createDeleteQuery();
1574
        $query->deleteFrom('ezcontentobject_name')
1575
            ->where(
1576
                $query->expr->eq(
1577
                    $this->dbHandler->quoteColumn('contentobject_id'),
1578
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1579
                )
1580
            );
1581
1582
        if (isset($versionNo)) {
1583
            $query->where(
1584
                $query->expr->eq(
1585
                    $this->dbHandler->quoteColumn('content_version'),
1586
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1587
                )
1588
            );
1589
        }
1590
1591
        $query->prepare()->execute();
1592
    }
1593
1594
    /**
1595
     * Sets the name for Content $contentId in version $version to $name in $language.
1596
     *
1597
     * @param int $contentId
1598
     * @param int $version
1599
     * @param string $name
1600
     * @param string $language
1601
     */
1602
    public function setName($contentId, $version, $name, $language)
1603
    {
1604
        $language = $this->languageHandler->loadByLanguageCode($language);
1605
1606
        // Is it an insert or an update ?
1607
        $qSelect = $this->dbHandler->createSelectQuery();
1608
        $qSelect
1609
            ->select(
1610
                $qSelect->alias($qSelect->expr->count('*'), 'count')
1611
            )
1612
            ->from($this->dbHandler->quoteTable('ezcontentobject_name'))
1613
            ->where(
1614
                $qSelect->expr->lAnd(
1615
                    $qSelect->expr->eq($this->dbHandler->quoteColumn('contentobject_id'), $qSelect->bindValue($contentId)),
1616
                    $qSelect->expr->eq($this->dbHandler->quoteColumn('content_version'), $qSelect->bindValue($version)),
1617
                    $qSelect->expr->eq($this->dbHandler->quoteColumn('content_translation'), $qSelect->bindValue($language->languageCode))
1618
                )
1619
            );
1620
        $stmt = $qSelect->prepare();
1621
        $stmt->execute();
1622
        $res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
1623
1624
        $insert = $res[0]['count'] == 0;
1625
        if ($insert) {
1626
            $q = $this->dbHandler->createInsertQuery();
1627
            $q->insertInto($this->dbHandler->quoteTable('ezcontentobject_name'));
1628
        } else {
1629
            $q = $this->dbHandler->createUpdateQuery();
1630
            $q->update($this->dbHandler->quoteTable('ezcontentobject_name'))
1631
                ->where(
1632
                    $q->expr->lAnd(
1633
                        $q->expr->eq($this->dbHandler->quoteColumn('contentobject_id'), $q->bindValue($contentId)),
1634
                        $q->expr->eq($this->dbHandler->quoteColumn('content_version'), $q->bindValue($version)),
1635
                        $q->expr->eq($this->dbHandler->quoteColumn('content_translation'), $q->bindValue($language->languageCode))
1636
                    )
1637
                );
1638
        }
1639
1640
        $q->set(
1641
            $this->dbHandler->quoteColumn('contentobject_id'),
1642
            $q->bindValue($contentId, null, \PDO::PARAM_INT)
1643
        )->set(
1644
            $this->dbHandler->quoteColumn('content_version'),
1645
            $q->bindValue($version, null, \PDO::PARAM_INT)
1646
        )->set(
1647
            $this->dbHandler->quoteColumn('language_id'),
1648
            '(' . $this->getLanguageQuery()->getQuery() . ')'
1649
        )->set(
1650
            $this->dbHandler->quoteColumn('content_translation'),
1651
            $q->bindValue($language->languageCode)
1652
        )->set(
1653
            $this->dbHandler->quoteColumn('real_translation'),
1654
            $q->bindValue($language->languageCode)
1655
        )->set(
1656
            $this->dbHandler->quoteColumn('name'),
1657
            $q->bindValue($name)
1658
        );
1659
        $q->bindValue($language->id, ':languageId', \PDO::PARAM_INT);
1660
        $q->bindValue($contentId, ':contentId', \PDO::PARAM_INT);
1661
        $q->prepare()->execute();
1662
    }
1663
1664
    /**
1665
     * Returns a language sub select query for setName.
1666
     *
1667
     * Return sub select query which gets proper language mask for alwaysAvailable Content.
1668
     *
1669
     * @return \eZ\Publish\Core\Persistence\Database\SelectQuery
1670
     */
1671
    private function getLanguageQuery()
1672
    {
1673
        $languageQuery = $this->dbHandler->createSelectQuery();
1674
        $languageQuery
1675
            ->select(
1676
                $languageQuery->expr->searchedCase(
1677
                    [
1678
                        $languageQuery->expr->lAnd(
1679
                            $languageQuery->expr->eq(
1680
                                $this->dbHandler->quoteColumn('initial_language_id'),
1681
                                ':languageId'
1682
                            ),
1683
                            // wrap bitwise check into another "neq" to provide cross-DBMS compatibility
1684
                            $languageQuery->expr->neq(
1685
                                $languageQuery->expr->bitAnd(
1686
                                    $this->dbHandler->quoteColumn('language_mask'),
1687
                                    ':languageId'
1688
                                ),
1689
                                0
1690
                            )
1691
                        ),
1692
                        $languageQuery->expr->bitOr(
1693
                            ':languageId',
1694
                            1
1695
                        ),
1696
                    ],
1697
                    ':languageId'
1698
                )
1699
            )
1700
            ->from('ezcontentobject')
1701
            ->where(
1702
                $languageQuery->expr->eq(
1703
                    'id',
1704
                    ':contentId'
1705
                )
1706
            );
1707
1708
        return $languageQuery;
1709
    }
1710
1711
    /**
1712
     * Deletes the actual content object referred to by $contentId.
1713
     *
1714
     * @param int $contentId
1715
     */
1716
    public function deleteContent($contentId)
1717
    {
1718
        $query = $this->dbHandler->createDeleteQuery();
1719
        $query->deleteFrom('ezcontentobject')
1720
            ->where(
1721
                $query->expr->eq(
1722
                    $this->dbHandler->quoteColumn('id'),
1723
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1724
                )
1725
            );
1726
1727
        $query->prepare()->execute();
1728
    }
1729
1730
    /**
1731
     * Loads relations from $contentId to published content, optionally only from $contentVersionNo.
1732
     *
1733
     * $relationType can also be filtered.
1734
     *
1735
     * @param int $contentId
1736
     * @param int $contentVersionNo
1737
     * @param int $relationType
1738
     *
1739
     * @return string[][] array of relation data
1740
     */
1741
    public function loadRelations($contentId, $contentVersionNo = null, $relationType = null)
1742
    {
1743
        $query = $this->queryBuilder->createRelationFindQuery();
1744
        $query->innerJoin(
1745
            $query->alias(
1746
                $this->dbHandler->quoteTable('ezcontentobject'),
1747
                'ezcontentobject_to'
1748
            ),
1749
            $query->expr->lAnd(
1750
                $query->expr->eq(
1751
                    $this->dbHandler->quoteColumn('to_contentobject_id', 'ezcontentobject_link'),
1752
                    $this->dbHandler->quoteColumn('id', 'ezcontentobject_to')
1753
                ),
1754
                $query->expr->eq(
1755
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject_to'),
1756
                    $query->bindValue(1, null, \PDO::PARAM_INT)
1757
                )
1758
            )
1759
        )->where(
1760
            $query->expr->eq(
1761
                $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link'),
1762
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1763
            )
1764
        );
1765
1766
        // source version number
1767
        if (isset($contentVersionNo)) {
1768
            $query->where(
1769
                $query->expr->eq(
1770
                    $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link'),
1771
                    $query->bindValue($contentVersionNo, null, \PDO::PARAM_INT)
1772
                )
1773
            );
1774
        } else { // from published version only
1775
            $query->from(
1776
                $this->dbHandler->quoteTable('ezcontentobject')
1777
            )->where(
1778
                $query->expr->lAnd(
1779
                    $query->expr->eq(
1780
                        $this->dbHandler->quoteColumn('id', 'ezcontentobject'),
1781
                        $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link')
1782
                    ),
1783
                    $query->expr->eq(
1784
                        $this->dbHandler->quoteColumn('current_version', 'ezcontentobject'),
1785
                        $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link')
1786
                    )
1787
                )
1788
            );
1789
        }
1790
1791
        // relation type
1792 View Code Duplication
        if (isset($relationType)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1793
            $query->where(
1794
                $query->expr->gt(
1795
                    $query->expr->bitAnd(
1796
                        $this->dbHandler->quoteColumn('relation_type', 'ezcontentobject_link'),
1797
                        $query->bindValue($relationType, null, \PDO::PARAM_INT)
1798
                    ),
1799
                    0
1800
                )
1801
            );
1802
        }
1803
1804
        $statement = $query->prepare();
1805
        $statement->execute();
1806
1807
        return $statement->fetchAll(\PDO::FETCH_ASSOC);
1808
    }
1809
1810
    /**
1811
     * Loads data that related to $toContentId.
1812
     *
1813
     * @param int $toContentId
1814
     * @param int $relationType
1815
     *
1816
     * @return mixed[][] Content data, array structured like {@see \eZ\Publish\Core\Persistence\Legacy\Content\Gateway::load()}
1817
     */
1818
    public function loadReverseRelations($toContentId, $relationType = null)
1819
    {
1820
        $query = $this->queryBuilder->createRelationFindQuery();
1821
        $query->where(
1822
            $query->expr->eq(
1823
                $this->dbHandler->quoteColumn('to_contentobject_id', 'ezcontentobject_link'),
1824
                $query->bindValue($toContentId, null, \PDO::PARAM_INT)
1825
            )
1826
        );
1827
1828
        // ezcontentobject join
1829
        $query->from(
1830
            $this->dbHandler->quoteTable('ezcontentobject')
1831
        )->where(
1832
            $query->expr->lAnd(
1833
                $query->expr->eq(
1834
                    $this->dbHandler->quoteColumn('id', 'ezcontentobject'),
1835
                    $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link')
1836
                ),
1837
                $query->expr->eq(
1838
                    $this->dbHandler->quoteColumn('current_version', 'ezcontentobject'),
1839
                    $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link')
1840
                ),
1841
                $query->expr->eq(
1842
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject'),
1843
                    $query->bindValue(1, null, \PDO::PARAM_INT)
1844
                )
1845
            )
1846
        );
1847
1848
        // relation type
1849 View Code Duplication
        if (isset($relationType)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1850
            $query->where(
1851
                $query->expr->gt(
1852
                    $query->expr->bitAnd(
1853
                        $this->dbHandler->quoteColumn('relation_type', 'ezcontentobject_link'),
1854
                        $query->bindValue($relationType, null, \PDO::PARAM_INT)
1855
                    ),
1856
                    0
1857
                )
1858
            );
1859
        }
1860
1861
        $statement = $query->prepare();
1862
1863
        $statement->execute();
1864
1865
        return $statement->fetchAll(\PDO::FETCH_ASSOC);
1866
    }
1867
1868
    /**
1869
     * Inserts a new relation database record.
1870
     *
1871
     * @param \eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct $createStruct
1872
     *
1873
     * @return int ID the inserted ID
1874
     */
1875 View Code Duplication
    public function insertRelation(RelationCreateStruct $createStruct)
1876
    {
1877
        $q = $this->dbHandler->createInsertQuery();
1878
        $q->insertInto(
1879
            $this->dbHandler->quoteTable('ezcontentobject_link')
1880
        )->set(
1881
            $this->dbHandler->quoteColumn('id'),
1882
            $this->dbHandler->getAutoIncrementValue('ezcontentobject_link', 'id')
1883
        )->set(
1884
            $this->dbHandler->quoteColumn('contentclassattribute_id'),
1885
            $q->bindValue((int)$createStruct->sourceFieldDefinitionId, null, \PDO::PARAM_INT)
1886
        )->set(
1887
            $this->dbHandler->quoteColumn('from_contentobject_id'),
1888
            $q->bindValue($createStruct->sourceContentId, null, \PDO::PARAM_INT)
1889
        )->set(
1890
            $this->dbHandler->quoteColumn('from_contentobject_version'),
1891
            $q->bindValue($createStruct->sourceContentVersionNo, null, \PDO::PARAM_INT)
1892
        )->set(
1893
            $this->dbHandler->quoteColumn('relation_type'),
1894
            $q->bindValue($createStruct->type, null, \PDO::PARAM_INT)
1895
        )->set(
1896
            $this->dbHandler->quoteColumn('to_contentobject_id'),
1897
            $q->bindValue($createStruct->destinationContentId, null, \PDO::PARAM_INT)
1898
        );
1899
1900
        $q->prepare()->execute();
1901
1902
        return $this->dbHandler->lastInsertId(
1903
            $this->dbHandler->getSequenceName('ezcontentobject_link', 'id')
1904
        );
1905
    }
1906
1907
    /**
1908
     * Deletes the relation with the given $relationId.
1909
     *
1910
     * @param int $relationId
1911
     * @param int $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
1912
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
1913
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
1914
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
1915
     */
1916
    public function deleteRelation($relationId, $type)
1917
    {
1918
        // Legacy Storage stores COMMON, LINK and EMBED types using bitmask, therefore first load
1919
        // existing relation type by given $relationId for comparison
1920
        /** @var $query \eZ\Publish\Core\Persistence\Database\SelectQuery */
1921
        $query = $this->dbHandler->createSelectQuery();
1922
        $query->select(
1923
            $this->dbHandler->quoteColumn('relation_type')
1924
        )->from(
1925
            $this->dbHandler->quoteTable('ezcontentobject_link')
1926
        )->where(
1927
            $query->expr->eq(
1928
                $this->dbHandler->quoteColumn('id'),
1929
                $query->bindValue($relationId, null, \PDO::PARAM_INT)
1930
            )
1931
        );
1932
1933
        $statement = $query->prepare();
1934
        $statement->execute();
1935
        $loadedRelationType = $statement->fetchColumn();
1936
1937
        if (!$loadedRelationType) {
1938
            return;
1939
        }
1940
1941
        // If relation type matches then delete
1942
        if ($loadedRelationType == $type) {
1943
            /** @var $query \eZ\Publish\Core\Persistence\Database\DeleteQuery */
1944
            $query = $this->dbHandler->createDeleteQuery();
1945
            $query->deleteFrom(
1946
                'ezcontentobject_link'
1947
            )->where(
1948
                $query->expr->eq(
1949
                    $this->dbHandler->quoteColumn('id'),
1950
                    $query->bindValue($relationId, null, \PDO::PARAM_INT)
1951
                )
1952
            );
1953
1954
            $query->prepare()->execute();
1955
        } elseif ($loadedRelationType & $type) { // If relation type is composite update bitmask
1956
            /** @var $query \eZ\Publish\Core\Persistence\Database\UpdateQuery */
1957
            $query = $this->dbHandler->createUpdateQuery();
1958
            $query->update(
1959
                $this->dbHandler->quoteTable('ezcontentobject_link')
1960
            )->set(
1961
                $this->dbHandler->quoteColumn('relation_type'),
1962
                $query->expr->bitAnd(
1963
                    $this->dbHandler->quoteColumn('relation_type'),
1964
                    $query->bindValue(~$type, null, \PDO::PARAM_INT)
1965
                )
1966
            )->where(
1967
                $query->expr->eq(
1968
                    $this->dbHandler->quoteColumn('id'),
1969
                    $query->bindValue($relationId, null, \PDO::PARAM_INT)
1970
                )
1971
            );
1972
1973
            $query->prepare()->execute();
1974
        } else {
1975
            // No match, do nothing
1976
        }
1977
    }
1978
1979
    /**
1980
     * Returns all Content IDs for a given $contentTypeId.
1981
     *
1982
     * @param int $contentTypeId
1983
     *
1984
     * @return int[]
1985
     */
1986
    public function getContentIdsByContentTypeId($contentTypeId)
1987
    {
1988
        $query = $this->dbHandler->createSelectQuery();
1989
        $query
1990
            ->select($this->dbHandler->quoteColumn('id'))
1991
            ->from($this->dbHandler->quoteTable('ezcontentobject'))
1992
            ->where(
1993
                $query->expr->eq(
1994
                    $this->dbHandler->quoteColumn('contentclass_id'),
1995
                    $query->bindValue($contentTypeId, null, PDO::PARAM_INT)
1996
                )
1997
            );
1998
1999
        $statement = $query->prepare();
2000
        $statement->execute();
2001
2002
        return $statement->fetchAll(PDO::FETCH_COLUMN);
2003
    }
2004
2005
    /**
2006
     * Load name data for set of content id's and corresponding version number.
2007
     *
2008
     * @param array[] $rows array of hashes with 'id' and 'version' to load names for
2009
     *
2010
     * @return array
2011
     */
2012
    public function loadVersionedNameData($rows)
2013
    {
2014
        $query = $this->queryBuilder->createNamesQuery();
2015
        $conditions = array();
2016
        foreach ($rows as $row) {
2017
            $conditions[] = $query->expr->lAnd(
2018
                $query->expr->eq(
2019
                    $this->dbHandler->quoteColumn('contentobject_id'),
2020
                    $query->bindValue($row['id'], null, \PDO::PARAM_INT)
2021
                ),
2022
                $query->expr->eq(
2023
                    $this->dbHandler->quoteColumn('content_version'),
2024
                    $query->bindValue($row['version'], null, \PDO::PARAM_INT)
2025
                )
2026
            );
2027
        }
2028
2029
        $query->where($query->expr->lOr($conditions));
2030
        $stmt = $query->prepare();
2031
        $stmt->execute();
2032
2033
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
2034
    }
2035
2036
    /**
2037
     * Batch method for copying all relation meta data for copied Content object.
2038
     *
2039
     * {@inheritdoc}
2040
     *
2041
     * @param int $originalContentId
2042
     * @param int $copiedContentId
2043
     * @param int|null $versionNo If specified only copy for a given version number, otherwise all.
2044
     */
2045
    public function copyRelations($originalContentId, $copiedContentId, $versionNo = null)
2046
    {
2047
        // Given we can retain all columns, we just create copies with new `from_contentobject_id` using INSERT INTO SELECT
2048
        $sql = 'INSERT INTO ezcontentobject_link ( contentclassattribute_id, from_contentobject_id, from_contentobject_version, relation_type, to_contentobject_id )
2049
                SELECT  L2.contentclassattribute_id, :copied_id, L2.from_contentobject_version, L2.relation_type, L2.to_contentobject_id
2050
                FROM    ezcontentobject_link AS L2
2051
                WHERE   L2.from_contentobject_id = :original_id';
2052
2053
        if ($versionNo) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $versionNo of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
2054
            $stmt = $this->connection->prepare($sql . ' AND L2.from_contentobject_version = :version');
2055
            $stmt->bindValue('version', $versionNo, PDO::PARAM_INT);
2056
        } else {
2057
            $stmt = $this->connection->prepare($sql);
2058
        }
2059
2060
        $stmt->bindValue('original_id', $originalContentId, PDO::PARAM_INT);
2061
        $stmt->bindValue('copied_id', $copiedContentId, PDO::PARAM_INT);
2062
2063
        $stmt->execute();
2064
    }
2065
2066
    /**
2067
     * Remove the specified translation from the Content Object Version.
2068
     *
2069
     * @param int $contentId
2070
     * @param string $languageCode language code of the translation
2071
     * @throws \Doctrine\DBAL\DBALException
2072
     */
2073 View Code Duplication
    public function deleteTranslationFromContent($contentId, $languageCode)
2074
    {
2075
        $language = $this->languageHandler->loadByLanguageCode($languageCode);
2076
2077
        $this->connection->beginTransaction();
2078
        try {
2079
            $this->deleteTranslationFromContentVersions($contentId, $language->id);
2080
            $this->deleteTranslationFromContentNames($contentId, $languageCode);
2081
            $this->deleteTranslationFromContentObject($contentId, $language->id);
2082
2083
            $this->connection->commit();
2084
        } catch (DBALException $e) {
2085
            $this->connection->rollBack();
2086
            throw $e;
2087
        }
2088
    }
2089
2090
    /**
2091
     * Delete Content fields (attributes) for the given Translation.
2092
     * If $versionNo is given, fields for that Version only will be deleted.
2093
     *
2094
     * @param string $languageCode
2095
     * @param int $contentId
2096
     * @param int $versionNo (optional) filter by versionNo
2097
     */
2098 View Code Duplication
    public function deleteTranslatedFields($languageCode, $contentId, $versionNo = null)
2099
    {
2100
        $query = $this->connection->createQueryBuilder();
2101
        $query
2102
            ->delete('ezcontentobject_attribute')
2103
            ->where('contentobject_id = :contentId')
2104
            ->andWhere('language_code = :languageCode')
2105
            ->setParameters(
2106
                [
2107
                    ':contentId' => $contentId,
2108
                    ':languageCode' => $languageCode,
2109
                ]
2110
            )
2111
        ;
2112
2113
        if (null !== $versionNo) {
2114
            $query
2115
                ->andWhere('version = :versionNo')
2116
                ->setParameter(':versionNo', $versionNo)
2117
            ;
2118
        }
2119
2120
        $query->execute();
2121
    }
2122
2123
    /**
2124
     * Delete the specified Translation from the given Version.
2125
     *
2126
     * @param int $contentId
2127
     * @param int $versionNo
2128
     * @param string $languageCode
2129
     * @throws \Doctrine\DBAL\DBALException
2130
     */
2131 View Code Duplication
    public function deleteTranslationFromVersion($contentId, $versionNo, $languageCode)
2132
    {
2133
        $language = $this->languageHandler->loadByLanguageCode($languageCode);
2134
2135
        $this->connection->beginTransaction();
2136
        try {
2137
            $this->deleteTranslationFromContentVersions($contentId, $language->id, $versionNo);
2138
            $this->deleteTranslationFromContentNames($contentId, $languageCode, $versionNo);
2139
2140
            $this->connection->commit();
2141
        } catch (DBALException $e) {
2142
            $this->connection->rollBack();
2143
            throw $e;
2144
        }
2145
    }
2146
2147
    /**
2148
     * Delete translation from the ezcontentobject_name table.
2149
     *
2150
     * @param int $contentId
2151
     * @param string $languageCode
2152
     * @param int $versionNo optional, if specified, apply to this Version only.
2153
     */
2154 View Code Duplication
    private function deleteTranslationFromContentNames($contentId, $languageCode, $versionNo = null)
2155
    {
2156
        $query = $this->connection->createQueryBuilder();
2157
        $query
2158
            ->delete('ezcontentobject_name')
2159
            ->where('contentobject_id=:contentId')
2160
            ->andWhere('real_translation=:languageCode')
2161
            ->setParameters(
2162
                [
2163
                    ':languageCode' => $languageCode,
2164
                    ':contentId' => $contentId,
2165
                ]
2166
            )
2167
        ;
2168
2169
        if (null !== $versionNo) {
2170
            $query
2171
                ->andWhere('content_version = :versionNo')
2172
                ->setParameter(':versionNo', $versionNo)
2173
            ;
2174
        }
2175
2176
        $query->execute();
2177
    }
2178
2179
    /**
2180
     * Remove language from language_mask of ezcontentobject.
2181
     *
2182
     * @param int $contentId
2183
     * @param int $languageId
2184
     * @throws \eZ\Publish\Core\Base\Exceptions\BadStateException
2185
     */
2186
    private function deleteTranslationFromContentObject($contentId, $languageId)
2187
    {
2188
        $query = $this->connection->createQueryBuilder();
2189
        $query->update('ezcontentobject')
2190
            // parameter for bitwise operation has to be placed verbatim (w/o binding) for this to work cross-DBMS
2191
            ->set('language_mask', 'language_mask & ~ ' . $languageId)
2192
            ->set('modified', ':now')
2193
            ->where('id = :contentId')
2194
            ->andWhere(
2195
            // make sure removed translation is not the last one (incl. alwaysAvailable)
2196
                $query->expr()->andX(
2197
                    'language_mask & ~ ' . $languageId . ' <> 0',
2198
                    'language_mask & ~ ' . $languageId . ' <> 1'
2199
                )
2200
            )
2201
            ->setParameter(':now', time())
2202
            ->setParameter(':contentId', $contentId)
2203
        ;
2204
2205
        $rowCount = $query->execute();
2206
2207
        // no rows updated means that most likely somehow it was the last remaining translation
2208
        if ($rowCount === 0) {
2209
            throw new BadStateException(
2210
                '$languageCode',
2211
                'Specified translation is the only one Content Object Version has'
2212
            );
2213
        }
2214
    }
2215
2216
    /**
2217
     * Remove language from language_mask of ezcontentobject_version and update initialLanguageId
2218
     * if it matches the removed one.
2219
     *
2220
     * @param int $contentId
2221
     * @param int $languageId
2222
     * @param int $versionNo optional, if specified, apply to this Version only.
2223
     * @throws \eZ\Publish\Core\Base\Exceptions\BadStateException
2224
     */
2225
    private function deleteTranslationFromContentVersions($contentId, $languageId, $versionNo = null)
2226
    {
2227
        $query = $this->connection->createQueryBuilder();
2228
        $query->update('ezcontentobject_version')
2229
            // parameter for bitwise operation has to be placed verbatim (w/o binding) for this to work cross-DBMS
2230
            ->set('language_mask', 'language_mask & ~ ' . $languageId)
2231
            ->set('modified', ':now')
2232
            // update initial_language_id only if it matches removed translation languageId
2233
            ->set(
2234
                'initial_language_id',
2235
                'CASE WHEN initial_language_id = :languageId ' .
2236
                'THEN (SELECT initial_language_id AS main_language_id FROM ezcontentobject c WHERE c.id = :contentId) ' .
2237
                'ELSE initial_language_id END'
2238
            )
2239
            ->where('contentobject_id = :contentId')
2240
            ->andWhere(
2241
            // make sure removed translation is not the last one (incl. alwaysAvailable)
2242
                $query->expr()->andX(
2243
                    'language_mask & ~ ' . $languageId . ' <> 0',
2244
                    'language_mask & ~ ' . $languageId . ' <> 1'
2245
                )
2246
            )
2247
            ->setParameter(':now', time())
2248
            ->setParameter(':contentId', $contentId)
2249
            ->setParameter(':languageId', $languageId)
2250
        ;
2251
2252
        if (null !== $versionNo) {
2253
            $query
2254
                ->andWhere('version = :versionNo')
2255
                ->setParameter(':versionNo', $versionNo)
2256
            ;
2257
        }
2258
2259
        $rowCount = $query->execute();
2260
2261
        // no rows updated means that most likely somehow it was the last remaining translation
2262
        if ($rowCount === 0) {
2263
            throw new BadStateException(
2264
                '$languageCode',
2265
                'Specified translation is the only one Content Object Version has'
2266
            );
2267
        }
2268
    }
2269
}
2270