Completed
Push — 6.13 ( 7c8b93...8ade82 )
by
unknown
65:32 queued 44:18
created

createLoadContentInfoQueryBuilder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
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 eZ\Publish\Core\Base\Exceptions\BadStateException;
14
use eZ\Publish\Core\Persistence\Legacy\Content\Gateway;
15
use eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase\QueryBuilder;
16
use eZ\Publish\Core\Persistence\Database\DatabaseHandler;
17
use eZ\Publish\Core\Persistence\Database\UpdateQuery;
18
use eZ\Publish\Core\Persistence\Database\InsertQuery;
19
use eZ\Publish\Core\Persistence\Database\SelectQuery;
20
use eZ\Publish\Core\Persistence\Legacy\Content\StorageFieldValue;
21
use eZ\Publish\Core\Persistence\Legacy\Content\Language\MaskGenerator as LanguageMaskGenerator;
22
use eZ\Publish\SPI\Persistence\Content;
23
use eZ\Publish\SPI\Persistence\Content\CreateStruct;
24
use eZ\Publish\SPI\Persistence\Content\UpdateStruct;
25
use eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct;
26
use eZ\Publish\SPI\Persistence\Content\ContentInfo;
27
use eZ\Publish\SPI\Persistence\Content\VersionInfo;
28
use eZ\Publish\SPI\Persistence\Content\Field;
29
use eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct as RelationCreateStruct;
30
use eZ\Publish\SPI\Persistence\Content\Language\Handler as LanguageHandler;
31
use eZ\Publish\Core\Base\Exceptions\NotFoundException as NotFound;
32
use eZ\Publish\API\Repository\Values\Content\VersionInfo as APIVersionInfo;
33
use DOMXPath;
34
use DOMDocument;
35
use PDO;
36
37
/**
38
 * Doctrine database based content gateway.
39
 */
40
class DoctrineDatabase extends Gateway
41
{
42
    /**
43
     * eZ Doctrine database handler.
44
     *
45
     * @var \eZ\Publish\Core\Persistence\Database\DatabaseHandler
46
     */
47
    protected $dbHandler;
48
49
    /**
50
     * The native Doctrine connection.
51
     *
52
     * Meant to be used to transition from eZ/Zeta interface to Doctrine.
53
     *
54
     * @var \Doctrine\DBAL\Connection
55
     */
56
    protected $connection;
57
58
    /**
59
     * Query builder.
60
     *
61
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase\QueryBuilder
62
     */
63
    protected $queryBuilder;
64
65
    /**
66
     * Caching language handler.
67
     *
68
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\Language\CachingHandler
69
     */
70
    protected $languageHandler;
71
72
    /**
73
     * Language mask generator.
74
     *
75
     * @var \eZ\Publish\Core\Persistence\Legacy\Content\Language\MaskGenerator
76
     */
77
    protected $languageMaskGenerator;
78
79
    /**
80
     * Creates a new gateway based on $db.
81
     *
82
     * @param \eZ\Publish\Core\Persistence\Database\DatabaseHandler $db
83
     * @param \Doctrine\DBAL\Connection $connection
84
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase\QueryBuilder $queryBuilder
85
     * @param \eZ\Publish\SPI\Persistence\Content\Language\Handler $languageHandler
86
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\Language\MaskGenerator $languageMaskGenerator
87
     */
88
    public function __construct(
89
        DatabaseHandler $db,
90
        Connection $connection,
91
        QueryBuilder $queryBuilder,
92
        LanguageHandler $languageHandler,
93
        LanguageMaskGenerator $languageMaskGenerator
94
    ) {
95
        $this->dbHandler = $db;
96
        $this->connection = $connection;
97
        $this->queryBuilder = $queryBuilder;
98
        $this->languageHandler = $languageHandler;
0 ignored issues
show
Documentation Bug introduced by
$languageHandler is of type object<eZ\Publish\SPI\Pe...ntent\Language\Handler>, but the property $languageHandler was declared to be of type object<eZ\Publish\Core\P...anguage\CachingHandler>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
99
        $this->languageMaskGenerator = $languageMaskGenerator;
100
    }
101
102
    /**
103
     * Get context definition for external storage layers.
104
     *
105
     * @return array
106
     */
107
    public function getContext()
108
    {
109
        return array(
110
            'identifier' => 'LegacyStorage',
111
            'connection' => $this->dbHandler,
112
        );
113
    }
114
115
    /**
116
     * Inserts a new content object.
117
     *
118
     * @param \eZ\Publish\SPI\Persistence\Content\CreateStruct $struct
119
     * @param mixed $currentVersionNo
120
     *
121
     * @return int ID
122
     */
123
    public function insertContentObject(CreateStruct $struct, $currentVersionNo = 1)
124
    {
125
        $initialLanguageId = !empty($struct->mainLanguageId) ? $struct->mainLanguageId : $struct->initialLanguageId;
126
        $initialLanguageCode = $this->languageHandler->load($initialLanguageId)->languageCode;
127
128
        if (isset($struct->name[$initialLanguageCode])) {
129
            $name = $struct->name[$initialLanguageCode];
130
        } else {
131
            $name = '';
132
        }
133
134
        $q = $this->dbHandler->createInsertQuery();
135
        $q->insertInto(
136
            $this->dbHandler->quoteTable('ezcontentobject')
137
        )->set(
138
            $this->dbHandler->quoteColumn('id'),
139
            $this->dbHandler->getAutoIncrementValue('ezcontentobject', 'id')
140
        )->set(
141
            $this->dbHandler->quoteColumn('current_version'),
142
            $q->bindValue($currentVersionNo, null, \PDO::PARAM_INT)
143
        )->set(
144
            $this->dbHandler->quoteColumn('name'),
145
            $q->bindValue($name, null, \PDO::PARAM_STR)
146
        )->set(
147
            $this->dbHandler->quoteColumn('contentclass_id'),
148
            $q->bindValue($struct->typeId, null, \PDO::PARAM_INT)
149
        )->set(
150
            $this->dbHandler->quoteColumn('section_id'),
151
            $q->bindValue($struct->sectionId, null, \PDO::PARAM_INT)
152
        )->set(
153
            $this->dbHandler->quoteColumn('owner_id'),
154
            $q->bindValue($struct->ownerId, null, \PDO::PARAM_INT)
155
        )->set(
156
            $this->dbHandler->quoteColumn('initial_language_id'),
157
            $q->bindValue($initialLanguageId, null, \PDO::PARAM_INT)
158
        )->set(
159
            $this->dbHandler->quoteColumn('remote_id'),
160
            $q->bindValue($struct->remoteId, null, \PDO::PARAM_STR)
161
        )->set(
162
            $this->dbHandler->quoteColumn('modified'),
163
            $q->bindValue(0, null, \PDO::PARAM_INT)
164
        )->set(
165
            $this->dbHandler->quoteColumn('published'),
166
            $q->bindValue(0, null, \PDO::PARAM_INT)
167
        )->set(
168
            $this->dbHandler->quoteColumn('status'),
169
            $q->bindValue(ContentInfo::STATUS_DRAFT, null, \PDO::PARAM_INT)
170
        )->set(
171
            $this->dbHandler->quoteColumn('language_mask'),
172
            $q->bindValue(
173
                $this->generateLanguageMask(
174
                    $struct->fields,
175
                    $initialLanguageCode,
176
                    $struct->alwaysAvailable
177
                ),
178
                null,
179
                \PDO::PARAM_INT
180
            )
181
        );
182
183
        $q->prepare()->execute();
184
185
        return $this->dbHandler->lastInsertId(
186
            $this->dbHandler->getSequenceName('ezcontentobject', 'id')
187
        );
188
    }
189
190
    /**
191
     * Generates a language mask for $version.
192
     *
193
     * @param \eZ\Publish\SPI\Persistence\Content\Field[] $fields
194
     * @param string $initialLanguageCode
195
     * @param bool $alwaysAvailable
196
     *
197
     * @return int
198
     */
199
    protected function generateLanguageMask(array $fields, $initialLanguageCode, $alwaysAvailable)
200
    {
201
        $languages = array($initialLanguageCode => true);
202 View Code Duplication
        foreach ($fields as $field) {
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...
203
            if (isset($languages[$field->languageCode])) {
204
                continue;
205
            }
206
207
            $languages[$field->languageCode] = true;
208
        }
209
210
        if ($alwaysAvailable) {
211
            $languages['always-available'] = true;
212
        }
213
214
        return $this->languageMaskGenerator->generateLanguageMask($languages);
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
            $languages = [];
333
            foreach ($prePublishVersionInfo->languageCodes as $languageCodes) {
334
                if (!isset($languages[$languageCodes])) {
335
                    $languages[$languageCodes] = true;
336
                }
337
            }
338
339
            $languages['always-available'] = isset($struct->alwaysAvailable) ? $struct->alwaysAvailable :
340
                $prePublishVersionInfo->contentInfo->alwaysAvailable;
341
342
            $mask = $this->languageMaskGenerator->generateLanguageMask($languages);
343
344
            $q->set(
345
                $this->dbHandler->quoteColumn('language_mask'),
346
                $q->bindValue($mask, null, \PDO::PARAM_INT)
347
            );
348
        }
349
        $q->where(
350
            $q->expr->eq(
351
                $this->dbHandler->quoteColumn('id'),
352
                $q->bindValue($contentId, null, \PDO::PARAM_INT)
353
            )
354
        );
355
        $q->prepare()->execute();
356
357
        // Handle alwaysAvailable flag update separately as it's a more complex task and has impact on several tables
358
        if (isset($struct->alwaysAvailable) || isset($struct->mainLanguageId)) {
359
            $this->updateAlwaysAvailableFlag($contentId, $struct->alwaysAvailable);
360
        }
361
    }
362
363
    /**
364
     * Updates version $versionNo for content identified by $contentId, in respect to $struct.
365
     *
366
     * @param int $contentId
367
     * @param int $versionNo
368
     * @param \eZ\Publish\SPI\Persistence\Content\UpdateStruct $struct
369
     */
370
    public function updateVersion($contentId, $versionNo, UpdateStruct $struct)
371
    {
372
        $q = $this->dbHandler->createUpdateQuery();
373
        $q->update(
374
            $this->dbHandler->quoteTable('ezcontentobject_version')
375
        )->set(
376
            $this->dbHandler->quoteColumn('creator_id'),
377
            $q->bindValue($struct->creatorId, null, \PDO::PARAM_INT)
378
        )->set(
379
            $this->dbHandler->quoteColumn('modified'),
380
            $q->bindValue($struct->modificationDate, null, \PDO::PARAM_INT)
381
        )->set(
382
            $this->dbHandler->quoteColumn('initial_language_id'),
383
            $q->bindValue($struct->initialLanguageId, null, \PDO::PARAM_INT)
384
        )->set(
385
            $this->dbHandler->quoteColumn('language_mask'),
386
            $q->expr->bitOr(
387
                $this->dbHandler->quoteColumn('language_mask'),
388
                $q->bindValue(
389
                    $this->generateLanguageMask(
390
                        $struct->fields,
391
                        $this->languageHandler->load($struct->initialLanguageId)->languageCode,
392
                        false
393
                    ),
394
                    null,
395
                    \PDO::PARAM_INT
396
                )
397
            )
398
        )->where(
399
            $q->expr->lAnd(
400
                $q->expr->eq(
401
                    $this->dbHandler->quoteColumn('contentobject_id'),
402
                    $q->bindValue($contentId, null, \PDO::PARAM_INT)
403
                ),
404
                $q->expr->eq(
405
                    $this->dbHandler->quoteColumn('version'),
406
                    $q->bindValue($versionNo, null, \PDO::PARAM_INT)
407
                )
408
            )
409
        );
410
        $q->prepare()->execute();
411
    }
412
413
    /**
414
     * Updates "always available" flag for Content identified by $contentId, in respect to
415
     * Content's current main language and optionally new $alwaysAvailable state.
416
     *
417
     * @param int $contentId
418
     * @param bool|null $alwaysAvailable New "always available" value or null if not defined
419
     */
420
    public function updateAlwaysAvailableFlag($contentId, $alwaysAvailable = null)
421
    {
422
        // We will need to know some info on the current language mask to update the flag
423
        // everywhere needed
424
        $contentInfoRow = $this->loadContentInfo($contentId);
425
        if (!isset($alwaysAvailable)) {
426
            $alwaysAvailable = (bool)$contentInfoRow['language_mask'] & 1;
427
        }
428
429
        /** @var $q \eZ\Publish\Core\Persistence\Database\UpdateQuery */
430
        $q = $this->dbHandler->createUpdateQuery();
431
        $q
432
            ->update($this->dbHandler->quoteTable('ezcontentobject'))
433
            ->set(
434
                $this->dbHandler->quoteColumn('language_mask'),
435
                $alwaysAvailable ?
436
                    $q->expr->bitOr($this->dbHandler->quoteColumn('language_mask'), 1) :
437
                    $q->expr->bitAnd($this->dbHandler->quoteColumn('language_mask'), -2)
438
            )
439
            ->where(
440
                $q->expr->eq(
441
                    $this->dbHandler->quoteColumn('id'),
442
                    $q->bindValue($contentId, null, \PDO::PARAM_INT)
443
                )
444
            );
445
        $q->prepare()->execute();
446
447
        // Now we need to update ezcontentobject_name
448
        /** @var $qName \eZ\Publish\Core\Persistence\Database\UpdateQuery */
449
        $qName = $this->dbHandler->createUpdateQuery();
450
        $qName
451
            ->update($this->dbHandler->quoteTable('ezcontentobject_name'))
452
            ->set(
453
                $this->dbHandler->quoteColumn('language_id'),
454
                $alwaysAvailable ?
455
                    $qName->expr->bitOr($this->dbHandler->quoteColumn('language_id'), 1) :
456
                    $qName->expr->bitAnd($this->dbHandler->quoteColumn('language_id'), -2)
457
            )
458
            ->where(
459
                $qName->expr->lAnd(
460
                    $qName->expr->eq(
461
                        $this->dbHandler->quoteColumn('contentobject_id'),
462
                        $qName->bindValue($contentId, null, \PDO::PARAM_INT)
463
                    ),
464
                    $qName->expr->eq(
465
                        $this->dbHandler->quoteColumn('content_version'),
466
                        $qName->bindValue(
467
                            $contentInfoRow['current_version'],
468
                            null,
469
                            \PDO::PARAM_INT
470
                        )
471
                    )
472
                )
473
            );
474
        $qName->prepare()->execute();
475
476
        // Now update ezcontentobject_attribute for current version
477
        // Create update query that will be reused
478
        /** @var $qAttr \eZ\Publish\Core\Persistence\Database\UpdateQuery */
479
        $qAttr = $this->dbHandler->createUpdateQuery();
480
        $qAttr
481
            ->update($this->dbHandler->quoteTable('ezcontentobject_attribute'))
482
            ->where(
483
                $qAttr->expr->lAnd(
484
                    $qAttr->expr->eq(
485
                        $this->dbHandler->quoteColumn('contentobject_id'),
486
                        $qAttr->bindValue($contentId, null, \PDO::PARAM_INT)
487
                    ),
488
                    $qAttr->expr->eq(
489
                        $this->dbHandler->quoteColumn('version'),
490
                        $qAttr->bindValue(
491
                            $contentInfoRow['current_version'],
492
                            null,
493
                            \PDO::PARAM_INT
494
                        )
495
                    )
496
                )
497
            );
498
499
        // If there is only a single language, update all fields and return
500
        if (!$this->languageMaskGenerator->isLanguageMaskComposite($contentInfoRow['language_mask'])) {
501
            $qAttr->set(
502
                $this->dbHandler->quoteColumn('language_id'),
503
                $alwaysAvailable ?
504
                    $qAttr->expr->bitOr($this->dbHandler->quoteColumn('language_id'), 1) :
505
                    $qAttr->expr->bitAnd($this->dbHandler->quoteColumn('language_id'), -2)
506
            );
507
            $qAttr->prepare()->execute();
508
509
            return;
510
        }
511
512
        // Otherwise:
513
        // 1. Remove always available flag on all fields
514
        $qAttr->set(
515
            $this->dbHandler->quoteColumn('language_id'),
516
            $qAttr->expr->bitAnd($this->dbHandler->quoteColumn('language_id'), -2)
517
        );
518
        $qAttr->prepare()->execute();
519
520
        // 2. If Content is always available set the flag only on fields in main language
521
        if ($alwaysAvailable) {
522
            $qAttr->set(
523
                $this->dbHandler->quoteColumn('language_id'),
524
                $qAttr->expr->bitOr($this->dbHandler->quoteColumn('language_id'), 1)
525
            );
526
            $qAttr->where(
527
                $qAttr->expr->gt(
528
                    $qAttr->expr->bitAnd(
529
                        $this->dbHandler->quoteColumn('language_id'),
530
                        $qAttr->bindValue($contentInfoRow['initial_language_id'], null, PDO::PARAM_INT)
531
                    ),
532
                    $qAttr->bindValue(0, null, PDO::PARAM_INT)
533
                )
534
            );
535
            $qAttr->prepare()->execute();
536
        }
537
    }
538
539
    /**
540
     * Sets the status of the version identified by $contentId and $version to $status.
541
     *
542
     * The $status can be one of STATUS_DRAFT, STATUS_PUBLISHED, STATUS_ARCHIVED
543
     *
544
     * @param int $contentId
545
     * @param int $version
546
     * @param int $status
547
     *
548
     * @return bool
549
     */
550
    public function setStatus($contentId, $version, $status)
551
    {
552
        $q = $this->dbHandler->createUpdateQuery();
553
        $q->update(
554
            $this->dbHandler->quoteTable('ezcontentobject_version')
555
        )->set(
556
            $this->dbHandler->quoteColumn('status'),
557
            $q->bindValue($status, null, \PDO::PARAM_INT)
558
        )->set(
559
            $this->dbHandler->quoteColumn('modified'),
560
            $q->bindValue(time(), null, \PDO::PARAM_INT)
561
        )->where(
562
            $q->expr->lAnd(
563
                $q->expr->eq(
564
                    $this->dbHandler->quoteColumn('contentobject_id'),
565
                    $q->bindValue($contentId, null, \PDO::PARAM_INT)
566
                ),
567
                $q->expr->eq(
568
                    $this->dbHandler->quoteColumn('version'),
569
                    $q->bindValue($version, null, \PDO::PARAM_INT)
570
                )
571
            )
572
        );
573
        $statement = $q->prepare();
574
        $statement->execute();
575
576
        if ((bool)$statement->rowCount() === false) {
577
            return false;
578
        }
579
580
        if ($status !== APIVersionInfo::STATUS_PUBLISHED) {
581
            return true;
582
        }
583
584
        // If the version's status is PUBLISHED, we set the content to published status as well
585
        $q = $this->dbHandler->createUpdateQuery();
586
        $q->update(
587
            $this->dbHandler->quoteTable('ezcontentobject')
588
        )->set(
589
            $this->dbHandler->quoteColumn('status'),
590
            $q->bindValue(ContentInfo::STATUS_PUBLISHED, null, \PDO::PARAM_INT)
591
        )->set(
592
            $this->dbHandler->quoteColumn('current_version'),
593
            $q->bindValue($version, null, \PDO::PARAM_INT)
594
        )->where(
595
            $q->expr->eq(
596
                $this->dbHandler->quoteColumn('id'),
597
                $q->bindValue($contentId, null, \PDO::PARAM_INT)
598
            )
599
        );
600
        $statement = $q->prepare();
601
        $statement->execute();
602
603
        return (bool)$statement->rowCount();
604
    }
605
606
    /**
607
     * Inserts a new field.
608
     *
609
     * Only used when a new field is created (i.e. a new object or a field in a
610
     * new language!). After that, field IDs need to stay the same, only the
611
     * version number changes.
612
     *
613
     * @param \eZ\Publish\SPI\Persistence\Content $content
614
     * @param \eZ\Publish\SPI\Persistence\Content\Field $field
615
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\StorageFieldValue $value
616
     *
617
     * @return int ID
618
     */
619
    public function insertNewField(Content $content, Field $field, StorageFieldValue $value)
620
    {
621
        $q = $this->dbHandler->createInsertQuery();
622
623
        $this->setInsertFieldValues($q, $content, $field, $value);
624
625
        // Insert with auto increment ID
626
        $q->set(
627
            $this->dbHandler->quoteColumn('id'),
628
            $this->dbHandler->getAutoIncrementValue('ezcontentobject_attribute', 'id')
629
        );
630
631
        $q->prepare()->execute();
632
633
        return $this->dbHandler->lastInsertId(
634
            $this->dbHandler->getSequenceName('ezcontentobject_attribute', 'id')
635
        );
636
    }
637
638
    /**
639
     * Inserts an existing field.
640
     *
641
     * Used to insert a field with an exsting ID but a new version number.
642
     *
643
     * @param Content $content
644
     * @param Field $field
645
     * @param StorageFieldValue $value
646
     */
647
    public function insertExistingField(Content $content, Field $field, StorageFieldValue $value)
648
    {
649
        $q = $this->dbHandler->createInsertQuery();
650
651
        $this->setInsertFieldValues($q, $content, $field, $value);
652
653
        $q->set(
654
            $this->dbHandler->quoteColumn('id'),
655
            $q->bindValue($field->id, null, \PDO::PARAM_INT)
656
        );
657
658
        $q->prepare()->execute();
659
    }
660
661
    /**
662
     * Sets field (ezcontentobject_attribute) values to the given query.
663
     *
664
     * @param \eZ\Publish\Core\Persistence\Database\InsertQuery $q
665
     * @param Content $content
666
     * @param Field $field
667
     * @param StorageFieldValue $value
668
     */
669
    protected function setInsertFieldValues(InsertQuery $q, Content $content, Field $field, StorageFieldValue $value)
670
    {
671
        $q->insertInto(
672
            $this->dbHandler->quoteTable('ezcontentobject_attribute')
673
        )->set(
674
            $this->dbHandler->quoteColumn('contentobject_id'),
675
            $q->bindValue($content->versionInfo->contentInfo->id, null, \PDO::PARAM_INT)
676
        )->set(
677
            $this->dbHandler->quoteColumn('contentclassattribute_id'),
678
            $q->bindValue($field->fieldDefinitionId, null, \PDO::PARAM_INT)
679
        )->set(
680
            $this->dbHandler->quoteColumn('data_type_string'),
681
            $q->bindValue($field->type)
682
        )->set(
683
            $this->dbHandler->quoteColumn('language_code'),
684
            $q->bindValue($field->languageCode)
685
        )->set(
686
            $this->dbHandler->quoteColumn('version'),
687
            $q->bindValue($field->versionNo, null, \PDO::PARAM_INT)
688
        )->set(
689
            $this->dbHandler->quoteColumn('data_float'),
690
            $q->bindValue($value->dataFloat)
691
        )->set(
692
            $this->dbHandler->quoteColumn('data_int'),
693
            $q->bindValue($value->dataInt, null, \PDO::PARAM_INT)
694
        )->set(
695
            $this->dbHandler->quoteColumn('data_text'),
696
            $q->bindValue($value->dataText)
697
        )->set(
698
            $this->dbHandler->quoteColumn('sort_key_int'),
699
            $q->bindValue($value->sortKeyInt, null, \PDO::PARAM_INT)
700
        )->set(
701
            $this->dbHandler->quoteColumn('sort_key_string'),
702
            $q->bindValue(mb_substr($value->sortKeyString, 0, 255))
703
        )->set(
704
            $this->dbHandler->quoteColumn('language_id'),
705
            $q->bindValue(
706
                $this->languageMaskGenerator->generateLanguageIndicator(
707
                    $field->languageCode,
708
                    $this->isLanguageAlwaysAvailable($content, $field->languageCode)
709
                ),
710
                null,
711
                \PDO::PARAM_INT
712
            )
713
        );
714
    }
715
716
    /**
717
     * Checks if $languageCode is always available in $content.
718
     *
719
     * @param \eZ\Publish\SPI\Persistence\Content $content
720
     * @param string $languageCode
721
     *
722
     * @return bool
723
     */
724
    protected function isLanguageAlwaysAvailable(Content $content, $languageCode)
725
    {
726
        return
727
            $content->versionInfo->contentInfo->alwaysAvailable &&
728
            $content->versionInfo->contentInfo->mainLanguageCode === $languageCode
729
        ;
730
    }
731
732
    /**
733
     * Updates an existing field.
734
     *
735
     * @param Field $field
736
     * @param StorageFieldValue $value
737
     */
738
    public function updateField(Field $field, StorageFieldValue $value)
739
    {
740
        // Note, no need to care for language_id here, since Content->$alwaysAvailable
741
        // cannot change on update
742
        $q = $this->dbHandler->createUpdateQuery();
743
        $this->setFieldUpdateValues($q, $value);
744
        $q->where(
745
            $q->expr->lAnd(
746
                $q->expr->eq(
747
                    $this->dbHandler->quoteColumn('id'),
748
                    $q->bindValue($field->id, null, \PDO::PARAM_INT)
749
                ),
750
                $q->expr->eq(
751
                    $this->dbHandler->quoteColumn('version'),
752
                    $q->bindValue($field->versionNo, null, \PDO::PARAM_INT)
753
                )
754
            )
755
        );
756
        $q->prepare()->execute();
757
    }
758
759
    /**
760
     * Sets update fields for $value on $q.
761
     *
762
     * @param \eZ\Publish\Core\Persistence\Database\UpdateQuery $q
763
     * @param StorageFieldValue $value
764
     */
765
    protected function setFieldUpdateValues(UpdateQuery $q, StorageFieldValue $value)
766
    {
767
        $q->update(
768
            $this->dbHandler->quoteTable('ezcontentobject_attribute')
769
        )->set(
770
            $this->dbHandler->quoteColumn('data_float'),
771
            $q->bindValue($value->dataFloat)
772
        )->set(
773
            $this->dbHandler->quoteColumn('data_int'),
774
            $q->bindValue($value->dataInt, null, \PDO::PARAM_INT)
775
        )->set(
776
            $this->dbHandler->quoteColumn('data_text'),
777
            $q->bindValue($value->dataText)
778
        )->set(
779
            $this->dbHandler->quoteColumn('sort_key_int'),
780
            $q->bindValue($value->sortKeyInt, null, \PDO::PARAM_INT)
781
        )->set(
782
            $this->dbHandler->quoteColumn('sort_key_string'),
783
            $q->bindValue(mb_substr($value->sortKeyString, 0, 255))
784
        );
785
    }
786
787
    /**
788
     * Updates an existing, non-translatable field.
789
     *
790
     * @param \eZ\Publish\SPI\Persistence\Content\Field $field
791
     * @param \eZ\Publish\Core\Persistence\Legacy\Content\StorageFieldValue $value
792
     * @param int $contentId
793
     */
794
    public function updateNonTranslatableField(
795
        Field $field,
796
        StorageFieldValue $value,
797
        $contentId
798
    ) {
799
        // Note, no need to care for language_id here, since Content->$alwaysAvailable
800
        // cannot change on update
801
        $q = $this->dbHandler->createUpdateQuery();
802
        $this->setFieldUpdateValues($q, $value);
803
        $q->where(
804
            $q->expr->lAnd(
805
                $q->expr->eq(
806
                    $this->dbHandler->quoteColumn('contentclassattribute_id'),
807
                    $q->bindValue($field->fieldDefinitionId, null, \PDO::PARAM_INT)
808
                ),
809
                $q->expr->eq(
810
                    $this->dbHandler->quoteColumn('contentobject_id'),
811
                    $q->bindValue($contentId, null, \PDO::PARAM_INT)
812
                ),
813
                $q->expr->eq(
814
                    $this->dbHandler->quoteColumn('version'),
815
                    $q->bindValue($field->versionNo, null, \PDO::PARAM_INT)
816
                )
817
            )
818
        );
819
        $q->prepare()->execute();
820
    }
821
822
    /**
823
     * Loads data for a content object.
824
     *
825
     * Returns an array with the relevant data.
826
     *
827
     * @param mixed $contentId
828
     * @param mixed $version
829
     * @param string[] $translations
830
     *
831
     * @return array
832
     */
833 View Code Duplication
    public function load($contentId, $version, array $translations = null)
834
    {
835
        $query = $this->queryBuilder->createFindQuery($translations);
836
        $query->where(
837
            $query->expr->lAnd(
838
                $query->expr->eq(
839
                    $this->dbHandler->quoteColumn('id', 'ezcontentobject'),
840
                    $query->bindValue($contentId)
841
                ),
842
                $query->expr->eq(
843
                    $this->dbHandler->quoteColumn('version', 'ezcontentobject_version'),
844
                    $query->bindValue($version)
845
                )
846
            )
847
        );
848
        $statement = $query->prepare();
849
        $statement->execute();
850
851
        return $statement->fetchAll(\PDO::FETCH_ASSOC);
852
    }
853
854
    /**
855
     * {@inheritdoc}
856
     */
857
    public function loadContentList(array $contentIds, array $translations = null)
858
    {
859
        return $this->internalLoadContent($contentIds, null, $translations);
0 ignored issues
show
Bug introduced by
It seems like $translations defined by parameter $translations on line 857 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...
860
    }
861
862
    /**
863
     * @see loadContentList()
864
     *
865
     * @param array $contentIds
866
     * @param int $version
867
     * @param string[]|null $translations
868
     *
869
     * @return array
870
     */
871
    private function internalLoadContent(array $contentIds, $version = null, array $translations = null)
872
    {
873
        $queryBuilder = $this->connection->createQueryBuilder();
874
        $expr = $queryBuilder->expr();
875
        $queryBuilder
876
            ->select(
877
                'c.id AS ezcontentobject_id',
878
                'c.contentclass_id AS ezcontentobject_contentclass_id',
879
                'c.section_id AS ezcontentobject_section_id',
880
                'c.owner_id AS ezcontentobject_owner_id',
881
                'c.remote_id AS ezcontentobject_remote_id',
882
                'c.current_version AS ezcontentobject_current_version',
883
                'c.initial_language_id AS ezcontentobject_initial_language_id',
884
                'c.modified AS ezcontentobject_modified',
885
                'c.published AS ezcontentobject_published',
886
                'c.status AS ezcontentobject_status',
887
                'c.name AS ezcontentobject_name',
888
                'c.language_mask AS ezcontentobject_language_mask',
889
                'v.id AS ezcontentobject_version_id',
890
                'v.version AS ezcontentobject_version_version',
891
                'v.modified AS ezcontentobject_version_modified',
892
                'v.creator_id AS ezcontentobject_version_creator_id',
893
                'v.created AS ezcontentobject_version_created',
894
                'v.status AS ezcontentobject_version_status',
895
                'v.language_mask AS ezcontentobject_version_language_mask',
896
                'v.initial_language_id AS ezcontentobject_version_initial_language_id',
897
                'a.id AS ezcontentobject_attribute_id',
898
                'a.contentclassattribute_id AS ezcontentobject_attribute_contentclassattribute_id',
899
                'a.data_type_string AS ezcontentobject_attribute_data_type_string',
900
                'a.language_code AS ezcontentobject_attribute_language_code',
901
                'a.language_id AS ezcontentobject_attribute_language_id',
902
                'a.data_float AS ezcontentobject_attribute_data_float',
903
                'a.data_int AS ezcontentobject_attribute_data_int',
904
                'a.data_text AS ezcontentobject_attribute_data_text',
905
                'a.sort_key_int AS ezcontentobject_attribute_sort_key_int',
906
                'a.sort_key_string AS ezcontentobject_attribute_sort_key_string',
907
                't.main_node_id AS ezcontentobject_tree_main_node_id'
908
            )
909
            ->from('ezcontentobject', 'c')
910
            ->innerJoin(
911
                'c',
912
                'ezcontentobject_version',
913
                'v',
914
                $expr->andX(
915
                    $expr->eq('c.id', 'v.contentobject_id'),
916
                    $expr->eq('v.version', $version ?: 'c.current_version')
917
                )
918
            )
919
            ->innerJoin(
920
                'v',
921
                'ezcontentobject_attribute',
922
                'a',
923
                $expr->andX(
924
                    $expr->eq('v.contentobject_id', 'a.contentobject_id'),
925
                    $expr->eq('v.version', 'a.version')
926
                )
927
            )
928
            ->leftJoin(
929
                'c',
930
                'ezcontentobject_tree',
931
                't',
932
                $expr->andX(
933
                    $expr->eq('c.id', 't.contentobject_id'),
934
                    $expr->eq('t.node_id', 't.main_node_id')
935
                )
936
            );
937
938
        $queryBuilder->where(
939
            $expr->in(
940
                'c.id',
941
                $queryBuilder->createNamedParameter($contentIds, Connection::PARAM_INT_ARRAY)
942
            )
943
        );
944
945
        if (!empty($translations)) {
946
            $queryBuilder->andWhere(
947
                $expr->in(
948
                    'a.language_code',
949
                    $queryBuilder->createNamedParameter($translations, Connection::PARAM_STR_ARRAY)
950
                )
951
            );
952
        }
953
954
        return $queryBuilder->execute()->fetchAll(PDO::FETCH_ASSOC);
955
    }
956
957
    /**
958
     * Get query builder to load Content Info data.
959
     *
960
     * @see loadContentInfo(), loadContentInfoByRemoteId(), loadContentInfoList(), loadContentInfoByLocationId()
961
     *
962
     * @return \Doctrine\DBAL\Query\QueryBuilder
963
     */
964
    private function createLoadContentInfoQueryBuilder()
965
    {
966
        $queryBuilder = $this->connection->createQueryBuilder();
967
        $expr = $queryBuilder->expr();
968
        $queryBuilder
969
            ->select('c.*', 't.main_node_id AS ezcontentobject_tree_main_node_id')
970
            ->from('ezcontentobject', 'c')
971
            ->leftJoin(
972
                'c',
973
                'ezcontentobject_tree',
974
                't',
975
                $expr->andX(
976
                    $expr->eq('c.id', 't.contentobject_id'),
977
                    $expr->eq('t.node_id', 't.main_node_id')
978
                )
979
            );
980
981
        return $queryBuilder;
982
    }
983
984
    /**
985
     * Loads info for content identified by $contentId.
986
     * Will basically return a hash containing all field values for ezcontentobject table plus some additional keys:
987
     *  - always_available => Boolean indicating if content's language mask contains alwaysAvailable bit field
988
     *  - main_language_code => Language code for main (initial) language. E.g. "eng-GB".
989
     *
990
     * @param int $contentId
991
     *
992
     * @throws \eZ\Publish\Core\Base\Exceptions\NotFoundException
993
     *
994
     * @return array
995
     */
996 View Code Duplication
    public function loadContentInfo($contentId)
997
    {
998
        $queryBuilder = $this->createLoadContentInfoQueryBuilder();
999
        $queryBuilder
1000
            ->where('c.id = :id')
1001
            ->setParameter('id', $contentId, PDO::PARAM_INT);
1002
1003
        $results = $queryBuilder->execute()->fetchAll(PDO::FETCH_ASSOC);
1004
        if (empty($results)) {
1005
            throw new NotFound('content', "id: $contentId");
1006
        }
1007
1008
        return $results[0];
1009
    }
1010
1011
    public function loadContentInfoList(array $contentIds)
1012
    {
1013
        $queryBuilder = $this->createLoadContentInfoQueryBuilder();
1014
        $queryBuilder
1015
            ->where('c.id IN (:ids)')
1016
            ->setParameter('ids', $contentIds, Connection::PARAM_INT_ARRAY);
1017
1018
        return $queryBuilder->execute()->fetchAll(PDO::FETCH_ASSOC);
1019
    }
1020
1021
    /**
1022
     * Loads info for a content object identified by its remote ID.
1023
     *
1024
     * Returns an array with the relevant data.
1025
     *
1026
     * @param mixed $remoteId
1027
     *
1028
     * @throws \eZ\Publish\Core\Base\Exceptions\NotFoundException
1029
     *
1030
     * @return array
1031
     */
1032 View Code Duplication
    public function loadContentInfoByRemoteId($remoteId)
1033
    {
1034
        $queryBuilder = $this->createLoadContentInfoQueryBuilder();
1035
        $queryBuilder
1036
            ->where('c.remote_id = :id')
1037
            ->setParameter('id', $remoteId, PDO::PARAM_STR);
1038
1039
        $results = $queryBuilder->execute()->fetchAll(PDO::FETCH_ASSOC);
1040
        if (empty($results)) {
1041
            throw new NotFound('content', "remote_id: $remoteId");
1042
        }
1043
1044
        return $results[0];
1045
    }
1046
1047
    /**
1048
     * Loads info for a content object identified by its location ID (node ID).
1049
     *
1050
     * Returns an array with the relevant data.
1051
     *
1052
     * @param int $locationId
1053
     *
1054
     * @throws \eZ\Publish\Core\Base\Exceptions\NotFoundException
1055
     *
1056
     * @return array
1057
     */
1058 View Code Duplication
    public function loadContentInfoByLocationId($locationId)
1059
    {
1060
        $queryBuilder = $this->createLoadContentInfoQueryBuilder();
1061
        $queryBuilder
1062
            ->where('t.main_node_id = :id')
1063
            ->setParameter('id', $locationId, PDO::PARAM_INT);
1064
1065
        $results = $queryBuilder->execute()->fetchAll(PDO::FETCH_ASSOC);
1066
        if (empty($results)) {
1067
            throw new NotFound('content', "main_node_id: $locationId");
1068
        }
1069
1070
        return $results[0];
1071
    }
1072
1073
    /**
1074
     * Loads version info for content identified by $contentId and $versionNo.
1075
     * Will basically return a hash containing all field values from ezcontentobject_version table plus following keys:
1076
     *  - names => Hash of content object names. Key is the language code, value is the name.
1077
     *  - 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.
1078
     *  - initial_language_code => Language code for initial language in this version.
1079
     *
1080
     * @param int $contentId
1081
     * @param int $versionNo
1082
     *
1083
     * @return array
1084
     */
1085 View Code Duplication
    public function loadVersionInfo($contentId, $versionNo)
1086
    {
1087
        $query = $this->queryBuilder->createVersionInfoFindQuery();
1088
        $query->where(
1089
            $query->expr->lAnd(
1090
                $query->expr->eq(
1091
                    $this->dbHandler->quoteColumn('contentobject_id', 'ezcontentobject_version'),
1092
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1093
                ),
1094
                $query->expr->eq(
1095
                    $this->dbHandler->quoteColumn('version', 'ezcontentobject_version'),
1096
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1097
                )
1098
            )
1099
        );
1100
        $statement = $query->prepare();
1101
        $statement->execute();
1102
1103
        return $statement->fetchAll(\PDO::FETCH_ASSOC);
1104
    }
1105
1106
    /**
1107
     * Returns data for all versions with given status created by the given $userId.
1108
     *
1109
     * @param int $userId
1110
     * @param int $status
1111
     *
1112
     * @return string[][]
1113
     */
1114
    public function listVersionsForUser($userId, $status = VersionInfo::STATUS_DRAFT)
1115
    {
1116
        $query = $this->queryBuilder->createVersionInfoFindQuery();
1117
        $query->where(
1118
            $query->expr->lAnd(
1119
                $query->expr->eq(
1120
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject_version'),
1121
                    $query->bindValue($status, null, \PDO::PARAM_INT)
1122
                ),
1123
                $query->expr->eq(
1124
                    $this->dbHandler->quoteColumn('creator_id', 'ezcontentobject_version'),
1125
                    $query->bindValue($userId, null, \PDO::PARAM_INT)
1126
                )
1127
            )
1128
        );
1129
1130
        return $this->listVersionsHelper($query);
1131
    }
1132
1133
    /**
1134
     * Returns all version data for the given $contentId, optionally filtered by status.
1135
     *
1136
     * Result is returned with oldest version first (using version id as it has index and is auto increment).
1137
     *
1138
     * @param mixed $contentId
1139
     * @param mixed|null $status Optional argument to filter versions by status, like {@see VersionInfo::STATUS_ARCHIVED}.
1140
     * @param int $limit Limit for items returned, -1 means none.
1141
     *
1142
     * @return string[][]
1143
     */
1144
    public function listVersions($contentId, $status = null, $limit = -1)
1145
    {
1146
        $query = $this->queryBuilder->createVersionInfoFindQuery();
1147
1148
        $filter = $query->expr->eq(
1149
            $this->dbHandler->quoteColumn('contentobject_id', 'ezcontentobject_version'),
1150
            $query->bindValue($contentId, null, \PDO::PARAM_INT)
1151
        );
1152
1153
        if ($status !== null) {
1154
            $filter = $query->expr->lAnd(
1155
                $filter,
1156
                $query->expr->eq(
1157
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject_version'),
1158
                    $query->bindValue($status, null, \PDO::PARAM_INT)
1159
                )
1160
            );
1161
        }
1162
1163
        $query->where($filter);
1164
1165
        if ($limit > 0) {
1166
            $query->limit($limit);
1167
        }
1168
1169
        return $this->listVersionsHelper($query);
1170
    }
1171
1172
    /**
1173
     * Helper for {@see listVersions()} and {@see listVersionsForUser()} that filters duplicates
1174
     * that are the result of the cartesian product performed by createVersionInfoFindQuery().
1175
     *
1176
     * @param \eZ\Publish\Core\Persistence\Database\SelectQuery $query
1177
     *
1178
     * @return string[][]
1179
     */
1180
    private function listVersionsHelper(SelectQuery $query)
1181
    {
1182
        $query->orderBy(
1183
            $this->dbHandler->quoteColumn('id', 'ezcontentobject_version')
1184
        );
1185
1186
        $statement = $query->prepare();
1187
        $statement->execute();
1188
1189
        $results = array();
1190
        $previousId = null;
1191
        foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1192
            if ($row['ezcontentobject_version_id'] == $previousId) {
1193
                continue;
1194
            }
1195
1196
            $previousId = $row['ezcontentobject_version_id'];
1197
            $results[] = $row;
1198
        }
1199
1200
        return $results;
1201
    }
1202
1203
    /**
1204
     * Returns all version numbers for the given $contentId.
1205
     *
1206
     * @param mixed $contentId
1207
     *
1208
     * @return int[]
1209
     */
1210
    public function listVersionNumbers($contentId)
1211
    {
1212
        $query = $this->dbHandler->createSelectQuery();
1213
        $query->selectDistinct(
1214
            $this->dbHandler->quoteColumn('version')
1215
        )->from(
1216
            $this->dbHandler->quoteTable('ezcontentobject_version')
1217
        )->where(
1218
            $query->expr->eq(
1219
                $this->dbHandler->quoteColumn('contentobject_id'),
1220
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1221
            )
1222
        );
1223
1224
        $statement = $query->prepare();
1225
        $statement->execute();
1226
1227
        return $statement->fetchAll(\PDO::FETCH_COLUMN);
1228
    }
1229
1230
    /**
1231
     * Returns last version number for content identified by $contentId.
1232
     *
1233
     * @param int $contentId
1234
     *
1235
     * @return int
1236
     */
1237
    public function getLastVersionNumber($contentId)
1238
    {
1239
        $query = $this->dbHandler->createSelectQuery();
1240
        $query->select(
1241
            $query->expr->max($this->dbHandler->quoteColumn('version'))
1242
        )->from(
1243
            $this->dbHandler->quoteTable('ezcontentobject_version')
1244
        )->where(
1245
            $query->expr->eq(
1246
                $this->dbHandler->quoteColumn('contentobject_id'),
1247
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1248
            )
1249
        );
1250
1251
        $statement = $query->prepare();
1252
        $statement->execute();
1253
1254
        return (int)$statement->fetchColumn();
1255
    }
1256
1257
    /**
1258
     * Returns all IDs for locations that refer to $contentId.
1259
     *
1260
     * @param int $contentId
1261
     *
1262
     * @return int[]
1263
     */
1264
    public function getAllLocationIds($contentId)
1265
    {
1266
        $query = $this->dbHandler->createSelectQuery();
1267
        $query->select(
1268
            $this->dbHandler->quoteColumn('node_id')
1269
        )->from(
1270
            $this->dbHandler->quoteTable('ezcontentobject_tree')
1271
        )->where(
1272
            $query->expr->eq(
1273
                $this->dbHandler->quoteColumn('contentobject_id'),
1274
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1275
            )
1276
        );
1277
1278
        $statement = $query->prepare();
1279
        $statement->execute();
1280
1281
        return $statement->fetchAll(\PDO::FETCH_COLUMN);
1282
    }
1283
1284
    /**
1285
     * Returns all field IDs of $contentId grouped by their type.
1286
     * If $versionNo is set only field IDs for that version are returned.
1287
     * If $languageCode is set, only field IDs for that language are returned.
1288
     *
1289
     * @param int $contentId
1290
     * @param int|null $versionNo
1291
     * @param string|null $languageCode
1292
     *
1293
     * @return int[][]
1294
     */
1295
    public function getFieldIdsByType($contentId, $versionNo = null, $languageCode = null)
1296
    {
1297
        $query = $this->dbHandler->createSelectQuery();
1298
        $query->select(
1299
            $this->dbHandler->quoteColumn('id'),
1300
            $this->dbHandler->quoteColumn('data_type_string')
1301
        )->from(
1302
            $this->dbHandler->quoteTable('ezcontentobject_attribute')
1303
        )->where(
1304
            $query->expr->eq(
1305
                $this->dbHandler->quoteColumn('contentobject_id'),
1306
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1307
            )
1308
        );
1309
1310
        if (isset($versionNo)) {
1311
            $query->where(
1312
                $query->expr->eq(
1313
                    $this->dbHandler->quoteColumn('version'),
1314
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1315
                )
1316
            );
1317
        }
1318
1319
        if (isset($languageCode)) {
1320
            $query->where(
1321
                $query->expr->eq(
1322
                    $this->dbHandler->quoteColumn('language_code'),
1323
                    $query->bindValue($languageCode, null, \PDO::PARAM_STR)
1324
                )
1325
            );
1326
        }
1327
1328
        $statement = $query->prepare();
1329
        $statement->execute();
1330
1331
        $result = array();
1332
        foreach ($statement->fetchAll() as $row) {
1333
            if (!isset($result[$row['data_type_string']])) {
1334
                $result[$row['data_type_string']] = array();
1335
            }
1336
            $result[$row['data_type_string']][] = (int)$row['id'];
1337
        }
1338
1339
        return $result;
1340
    }
1341
1342
    /**
1343
     * Deletes relations to and from $contentId.
1344
     * If $versionNo is set only relations for that version are deleted.
1345
     *
1346
     * @param int $contentId
1347
     * @param int|null $versionNo
1348
     */
1349
    public function deleteRelations($contentId, $versionNo = null)
1350
    {
1351
        $query = $this->dbHandler->createDeleteQuery();
1352
        $query->deleteFrom(
1353
            $this->dbHandler->quoteTable('ezcontentobject_link')
1354
        );
1355
1356
        if (isset($versionNo)) {
1357
            $query->where(
1358
                $query->expr->lAnd(
1359
                    $query->expr->eq(
1360
                        $this->dbHandler->quoteColumn('from_contentobject_id'),
1361
                        $query->bindValue($contentId, null, \PDO::PARAM_INT)
1362
                    ),
1363
                    $query->expr->eq(
1364
                        $this->dbHandler->quoteColumn('from_contentobject_version'),
1365
                        $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1366
                    )
1367
                )
1368
            );
1369
        } else {
1370
            $query->where(
1371
                $query->expr->lOr(
1372
                    $query->expr->eq(
1373
                        $this->dbHandler->quoteColumn('from_contentobject_id'),
1374
                        $query->bindValue($contentId, null, \PDO::PARAM_INT)
1375
                    ),
1376
                    $query->expr->eq(
1377
                        $this->dbHandler->quoteColumn('to_contentobject_id'),
1378
                        $query->bindValue($contentId, null, \PDO::PARAM_INT)
1379
                    )
1380
                )
1381
            );
1382
        }
1383
1384
        $query->prepare()->execute();
1385
    }
1386
1387
    /**
1388
     * Removes relations to Content with $contentId from Relation and RelationList field type fields.
1389
     *
1390
     * @param int $contentId
1391
     */
1392
    public function removeReverseFieldRelations($contentId)
1393
    {
1394
        $query = $this->dbHandler->createSelectQuery();
1395
        $query
1396
            ->select('ezcontentobject_attribute.*')
1397
            ->from('ezcontentobject_attribute')
1398
            ->innerJoin(
1399
                'ezcontentobject_link',
1400
                $query->expr->lAnd(
1401
                    $query->expr->eq(
1402
                        $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link'),
1403
                        $this->dbHandler->quoteColumn('contentobject_id', 'ezcontentobject_attribute')
1404
                    ),
1405
                    $query->expr->eq(
1406
                        $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link'),
1407
                        $this->dbHandler->quoteColumn('version', 'ezcontentobject_attribute')
1408
                    ),
1409
                    $query->expr->eq(
1410
                        $this->dbHandler->quoteColumn('contentclassattribute_id', 'ezcontentobject_link'),
1411
                        $this->dbHandler->quoteColumn('contentclassattribute_id', 'ezcontentobject_attribute')
1412
                    )
1413
                )
1414
            )
1415
            ->where(
1416
                $query->expr->eq(
1417
                    $this->dbHandler->quoteColumn('to_contentobject_id', 'ezcontentobject_link'),
1418
                    $query->bindValue($contentId, null, PDO::PARAM_INT)
1419
                ),
1420
                $query->expr->gt(
1421
                    $query->expr->bitAnd(
1422
                        $this->dbHandler->quoteColumn('relation_type', 'ezcontentobject_link'),
1423
                        $query->bindValue(8, null, PDO::PARAM_INT)
1424
                    ),
1425
                    0
1426
                )
1427
            );
1428
1429
        $statement = $query->prepare();
1430
        $statement->execute();
1431
1432
        while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
1433
            if ($row['data_type_string'] === 'ezobjectrelation') {
1434
                $this->removeRelationFromRelationField($row);
1435
            }
1436
1437
            if ($row['data_type_string'] === 'ezobjectrelationlist') {
1438
                $this->removeRelationFromRelationListField($contentId, $row);
1439
            }
1440
        }
1441
    }
1442
1443
    /**
1444
     * Updates field value of RelationList field type identified by given $row data,
1445
     * removing relations toward given $contentId.
1446
     *
1447
     * @param int $contentId
1448
     * @param array $row
1449
     */
1450
    protected function removeRelationFromRelationListField($contentId, array $row)
1451
    {
1452
        $document = new DOMDocument('1.0', 'utf-8');
1453
        $document->loadXML($row['data_text']);
1454
1455
        $xpath = new DOMXPath($document);
1456
        $xpathExpression = "//related-objects/relation-list/relation-item[@contentobject-id='{$contentId}']";
1457
1458
        $relationItems = $xpath->query($xpathExpression);
1459
        foreach ($relationItems as $relationItem) {
1460
            $relationItem->parentNode->removeChild($relationItem);
1461
        }
1462
1463
        $query = $this->dbHandler->createUpdateQuery();
1464
        $query
1465
            ->update('ezcontentobject_attribute')
1466
            ->set(
1467
                'data_text',
1468
                $query->bindValue($document->saveXML(), null, PDO::PARAM_STR)
1469
            )
1470
            ->where(
1471
                $query->expr->lAnd(
1472
                    $query->expr->eq(
1473
                        $this->dbHandler->quoteColumn('id'),
1474
                        $query->bindValue($row['id'], null, PDO::PARAM_INT)
1475
                    ),
1476
                    $query->expr->eq(
1477
                        $this->dbHandler->quoteColumn('version'),
1478
                        $query->bindValue($row['version'], null, PDO::PARAM_INT)
1479
                    )
1480
                )
1481
            );
1482
1483
        $query->prepare()->execute();
1484
    }
1485
1486
    /**
1487
     * Updates field value of Relation field type identified by given $row data,
1488
     * removing relation data.
1489
     *
1490
     * @param array $row
1491
     */
1492
    protected function removeRelationFromRelationField(array $row)
1493
    {
1494
        $query = $this->dbHandler->createUpdateQuery();
1495
        $query
1496
            ->update('ezcontentobject_attribute')
1497
            ->set('data_int', $query->bindValue(null, null, PDO::PARAM_INT))
1498
            ->set('sort_key_int', $query->bindValue(0, null, PDO::PARAM_INT))
1499
            ->where(
1500
                $query->expr->lAnd(
1501
                    $query->expr->eq(
1502
                        $this->dbHandler->quoteColumn('id'),
1503
                        $query->bindValue($row['id'], null, PDO::PARAM_INT)
1504
                    ),
1505
                    $query->expr->eq(
1506
                        $this->dbHandler->quoteColumn('version'),
1507
                        $query->bindValue($row['version'], null, PDO::PARAM_INT)
1508
                    )
1509
                )
1510
            );
1511
1512
        $query->prepare()->execute();
1513
    }
1514
1515
    /**
1516
     * Deletes the field with the given $fieldId.
1517
     *
1518
     * @param int $fieldId
1519
     */
1520
    public function deleteField($fieldId)
1521
    {
1522
        $query = $this->dbHandler->createDeleteQuery();
1523
        $query->deleteFrom(
1524
            $this->dbHandler->quoteTable('ezcontentobject_attribute')
1525
        )->where(
1526
            $query->expr->eq(
1527
                $this->dbHandler->quoteColumn('id'),
1528
                $query->bindValue($fieldId, null, \PDO::PARAM_INT)
1529
            )
1530
        );
1531
1532
        $query->prepare()->execute();
1533
    }
1534
1535
    /**
1536
     * Deletes all fields of $contentId in all versions.
1537
     * If $versionNo is set only fields for that version are deleted.
1538
     *
1539
     * @param int $contentId
1540
     * @param int|null $versionNo
1541
     */
1542
    public function deleteFields($contentId, $versionNo = null)
1543
    {
1544
        $query = $this->dbHandler->createDeleteQuery();
1545
        $query->deleteFrom('ezcontentobject_attribute')
1546
            ->where(
1547
                $query->expr->eq(
1548
                    $this->dbHandler->quoteColumn('contentobject_id'),
1549
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1550
                )
1551
            );
1552
1553
        if (isset($versionNo)) {
1554
            $query->where(
1555
                $query->expr->eq(
1556
                    $this->dbHandler->quoteColumn('version'),
1557
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1558
                )
1559
            );
1560
        }
1561
1562
        $query->prepare()->execute();
1563
    }
1564
1565
    /**
1566
     * Deletes all versions of $contentId.
1567
     * If $versionNo is set only that version is deleted.
1568
     *
1569
     * @param int $contentId
1570
     * @param int|null $versionNo
1571
     */
1572
    public function deleteVersions($contentId, $versionNo = null)
1573
    {
1574
        $query = $this->dbHandler->createDeleteQuery();
1575
        $query->deleteFrom('ezcontentobject_version')
1576
            ->where(
1577
                $query->expr->eq(
1578
                    $this->dbHandler->quoteColumn('contentobject_id'),
1579
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1580
                )
1581
            );
1582
1583
        if (isset($versionNo)) {
1584
            $query->where(
1585
                $query->expr->eq(
1586
                    $this->dbHandler->quoteColumn('version'),
1587
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1588
                )
1589
            );
1590
        }
1591
1592
        $query->prepare()->execute();
1593
    }
1594
1595
    /**
1596
     * Deletes all names of $contentId.
1597
     * If $versionNo is set only names for that version are deleted.
1598
     *
1599
     * @param int $contentId
1600
     * @param int|null $versionNo
1601
     */
1602
    public function deleteNames($contentId, $versionNo = null)
1603
    {
1604
        $query = $this->dbHandler->createDeleteQuery();
1605
        $query->deleteFrom('ezcontentobject_name')
1606
            ->where(
1607
                $query->expr->eq(
1608
                    $this->dbHandler->quoteColumn('contentobject_id'),
1609
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1610
                )
1611
            );
1612
1613
        if (isset($versionNo)) {
1614
            $query->where(
1615
                $query->expr->eq(
1616
                    $this->dbHandler->quoteColumn('content_version'),
1617
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1618
                )
1619
            );
1620
        }
1621
1622
        $query->prepare()->execute();
1623
    }
1624
1625
    /**
1626
     * Sets the name for Content $contentId in version $version to $name in $language.
1627
     *
1628
     * @param int $contentId
1629
     * @param int $version
1630
     * @param string $name
1631
     * @param string $language
1632
     */
1633
    public function setName($contentId, $version, $name, $language)
1634
    {
1635
        $language = $this->languageHandler->loadByLanguageCode($language);
1636
1637
        // Is it an insert or an update ?
1638
        $qSelect = $this->dbHandler->createSelectQuery();
1639
        $qSelect
1640
            ->select(
1641
                $qSelect->alias($qSelect->expr->count('*'), 'count')
1642
            )
1643
            ->from($this->dbHandler->quoteTable('ezcontentobject_name'))
1644
            ->where(
1645
                $qSelect->expr->lAnd(
1646
                    $qSelect->expr->eq($this->dbHandler->quoteColumn('contentobject_id'), $qSelect->bindValue($contentId)),
1647
                    $qSelect->expr->eq($this->dbHandler->quoteColumn('content_version'), $qSelect->bindValue($version)),
1648
                    $qSelect->expr->eq($this->dbHandler->quoteColumn('content_translation'), $qSelect->bindValue($language->languageCode))
1649
                )
1650
            );
1651
        $stmt = $qSelect->prepare();
1652
        $stmt->execute();
1653
        $res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
1654
1655
        $insert = $res[0]['count'] == 0;
1656
        if ($insert) {
1657
            $q = $this->dbHandler->createInsertQuery();
1658
            $q->insertInto($this->dbHandler->quoteTable('ezcontentobject_name'));
1659
        } else {
1660
            $q = $this->dbHandler->createUpdateQuery();
1661
            $q->update($this->dbHandler->quoteTable('ezcontentobject_name'))
1662
                ->where(
1663
                    $q->expr->lAnd(
1664
                        $q->expr->eq($this->dbHandler->quoteColumn('contentobject_id'), $q->bindValue($contentId)),
1665
                        $q->expr->eq($this->dbHandler->quoteColumn('content_version'), $q->bindValue($version)),
1666
                        $q->expr->eq($this->dbHandler->quoteColumn('content_translation'), $q->bindValue($language->languageCode))
1667
                    )
1668
                );
1669
        }
1670
1671
        $q->set(
1672
            $this->dbHandler->quoteColumn('contentobject_id'),
1673
            $q->bindValue($contentId, null, \PDO::PARAM_INT)
1674
        )->set(
1675
            $this->dbHandler->quoteColumn('content_version'),
1676
            $q->bindValue($version, null, \PDO::PARAM_INT)
1677
        )->set(
1678
            $this->dbHandler->quoteColumn('language_id'),
1679
            '(' . $this->getLanguageQuery()->getQuery() . ')'
1680
        )->set(
1681
            $this->dbHandler->quoteColumn('content_translation'),
1682
            $q->bindValue($language->languageCode)
1683
        )->set(
1684
            $this->dbHandler->quoteColumn('real_translation'),
1685
            $q->bindValue($language->languageCode)
1686
        )->set(
1687
            $this->dbHandler->quoteColumn('name'),
1688
            $q->bindValue($name)
1689
        );
1690
        $q->bindValue($language->id, ':languageId', \PDO::PARAM_INT);
1691
        $q->bindValue($contentId, ':contentId', \PDO::PARAM_INT);
1692
        $q->prepare()->execute();
1693
    }
1694
1695
    /**
1696
     * Returns a language sub select query for setName.
1697
     *
1698
     * Return sub select query which gets proper language mask for alwaysAvailable Content.
1699
     *
1700
     * @return \eZ\Publish\Core\Persistence\Database\SelectQuery
1701
     */
1702
    private function getLanguageQuery()
1703
    {
1704
        $languageQuery = $this->dbHandler->createSelectQuery();
1705
        $languageQuery
1706
            ->select(
1707
                $languageQuery->expr->searchedCase(
1708
                    [
1709
                        $languageQuery->expr->lAnd(
1710
                            $languageQuery->expr->eq(
1711
                                $this->dbHandler->quoteColumn('initial_language_id'),
1712
                                ':languageId'
1713
                            ),
1714
                            // wrap bitwise check into another "neq" to provide cross-DBMS compatibility
1715
                            $languageQuery->expr->neq(
1716
                                $languageQuery->expr->bitAnd(
1717
                                    $this->dbHandler->quoteColumn('language_mask'),
1718
                                    ':languageId'
1719
                                ),
1720
                                0
1721
                            )
1722
                        ),
1723
                        $languageQuery->expr->bitOr(
1724
                            ':languageId',
1725
                            1
1726
                        ),
1727
                    ],
1728
                    ':languageId'
1729
                )
1730
            )
1731
            ->from('ezcontentobject')
1732
            ->where(
1733
                $languageQuery->expr->eq(
1734
                    'id',
1735
                    ':contentId'
1736
                )
1737
            );
1738
1739
        return $languageQuery;
1740
    }
1741
1742
    /**
1743
     * Deletes the actual content object referred to by $contentId.
1744
     *
1745
     * @param int $contentId
1746
     */
1747
    public function deleteContent($contentId)
1748
    {
1749
        $query = $this->dbHandler->createDeleteQuery();
1750
        $query->deleteFrom('ezcontentobject')
1751
            ->where(
1752
                $query->expr->eq(
1753
                    $this->dbHandler->quoteColumn('id'),
1754
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1755
                )
1756
            );
1757
1758
        $query->prepare()->execute();
1759
    }
1760
1761
    /**
1762
     * Loads relations from $contentId to published content, optionally only from $contentVersionNo.
1763
     *
1764
     * $relationType can also be filtered.
1765
     *
1766
     * @param int $contentId
1767
     * @param int $contentVersionNo
1768
     * @param int $relationType
1769
     *
1770
     * @return string[][] array of relation data
1771
     */
1772
    public function loadRelations($contentId, $contentVersionNo = null, $relationType = null)
1773
    {
1774
        $query = $this->queryBuilder->createRelationFindQuery();
1775
        $query->innerJoin(
1776
            $query->alias(
1777
                $this->dbHandler->quoteTable('ezcontentobject'),
1778
                'ezcontentobject_to'
1779
            ),
1780
            $query->expr->lAnd(
1781
                $query->expr->eq(
1782
                    $this->dbHandler->quoteColumn('to_contentobject_id', 'ezcontentobject_link'),
1783
                    $this->dbHandler->quoteColumn('id', 'ezcontentobject_to')
1784
                ),
1785
                $query->expr->eq(
1786
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject_to'),
1787
                    $query->bindValue(1, null, \PDO::PARAM_INT)
1788
                )
1789
            )
1790
        )->where(
1791
            $query->expr->eq(
1792
                $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link'),
1793
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1794
            )
1795
        );
1796
1797
        // source version number
1798
        if (isset($contentVersionNo)) {
1799
            $query->where(
1800
                $query->expr->eq(
1801
                    $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link'),
1802
                    $query->bindValue($contentVersionNo, null, \PDO::PARAM_INT)
1803
                )
1804
            );
1805
        } else { // from published version only
1806
            $query->from(
1807
                $this->dbHandler->quoteTable('ezcontentobject')
1808
            )->where(
1809
                $query->expr->lAnd(
1810
                    $query->expr->eq(
1811
                        $this->dbHandler->quoteColumn('id', 'ezcontentobject'),
1812
                        $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link')
1813
                    ),
1814
                    $query->expr->eq(
1815
                        $this->dbHandler->quoteColumn('current_version', 'ezcontentobject'),
1816
                        $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link')
1817
                    )
1818
                )
1819
            );
1820
        }
1821
1822
        // relation type
1823 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...
1824
            $query->where(
1825
                $query->expr->gt(
1826
                    $query->expr->bitAnd(
1827
                        $this->dbHandler->quoteColumn('relation_type', 'ezcontentobject_link'),
1828
                        $query->bindValue($relationType, null, \PDO::PARAM_INT)
1829
                    ),
1830
                    0
1831
                )
1832
            );
1833
        }
1834
1835
        $statement = $query->prepare();
1836
        $statement->execute();
1837
1838
        return $statement->fetchAll(\PDO::FETCH_ASSOC);
1839
    }
1840
1841
    /**
1842
     * Loads data that related to $toContentId.
1843
     *
1844
     * @param int $toContentId
1845
     * @param int $relationType
1846
     *
1847
     * @return mixed[][] Content data, array structured like {@see \eZ\Publish\Core\Persistence\Legacy\Content\Gateway::load()}
1848
     */
1849
    public function loadReverseRelations($toContentId, $relationType = null)
1850
    {
1851
        $query = $this->queryBuilder->createRelationFindQuery();
1852
        $query->where(
1853
            $query->expr->eq(
1854
                $this->dbHandler->quoteColumn('to_contentobject_id', 'ezcontentobject_link'),
1855
                $query->bindValue($toContentId, null, \PDO::PARAM_INT)
1856
            )
1857
        );
1858
1859
        // ezcontentobject join
1860
        $query->from(
1861
            $this->dbHandler->quoteTable('ezcontentobject')
1862
        )->where(
1863
            $query->expr->lAnd(
1864
                $query->expr->eq(
1865
                    $this->dbHandler->quoteColumn('id', 'ezcontentobject'),
1866
                    $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link')
1867
                ),
1868
                $query->expr->eq(
1869
                    $this->dbHandler->quoteColumn('current_version', 'ezcontentobject'),
1870
                    $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link')
1871
                ),
1872
                $query->expr->eq(
1873
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject'),
1874
                    $query->bindValue(1, null, \PDO::PARAM_INT)
1875
                )
1876
            )
1877
        );
1878
1879
        // relation type
1880 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...
1881
            $query->where(
1882
                $query->expr->gt(
1883
                    $query->expr->bitAnd(
1884
                        $this->dbHandler->quoteColumn('relation_type', 'ezcontentobject_link'),
1885
                        $query->bindValue($relationType, null, \PDO::PARAM_INT)
1886
                    ),
1887
                    0
1888
                )
1889
            );
1890
        }
1891
1892
        $statement = $query->prepare();
1893
1894
        $statement->execute();
1895
1896
        return $statement->fetchAll(\PDO::FETCH_ASSOC);
1897
    }
1898
1899
    /**
1900
     * Inserts a new relation database record.
1901
     *
1902
     * @param \eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct $createStruct
1903
     *
1904
     * @return int ID the inserted ID
1905
     */
1906 View Code Duplication
    public function insertRelation(RelationCreateStruct $createStruct)
1907
    {
1908
        $q = $this->dbHandler->createInsertQuery();
1909
        $q->insertInto(
1910
            $this->dbHandler->quoteTable('ezcontentobject_link')
1911
        )->set(
1912
            $this->dbHandler->quoteColumn('id'),
1913
            $this->dbHandler->getAutoIncrementValue('ezcontentobject_link', 'id')
1914
        )->set(
1915
            $this->dbHandler->quoteColumn('contentclassattribute_id'),
1916
            $q->bindValue((int)$createStruct->sourceFieldDefinitionId, null, \PDO::PARAM_INT)
1917
        )->set(
1918
            $this->dbHandler->quoteColumn('from_contentobject_id'),
1919
            $q->bindValue($createStruct->sourceContentId, null, \PDO::PARAM_INT)
1920
        )->set(
1921
            $this->dbHandler->quoteColumn('from_contentobject_version'),
1922
            $q->bindValue($createStruct->sourceContentVersionNo, null, \PDO::PARAM_INT)
1923
        )->set(
1924
            $this->dbHandler->quoteColumn('relation_type'),
1925
            $q->bindValue($createStruct->type, null, \PDO::PARAM_INT)
1926
        )->set(
1927
            $this->dbHandler->quoteColumn('to_contentobject_id'),
1928
            $q->bindValue($createStruct->destinationContentId, null, \PDO::PARAM_INT)
1929
        );
1930
1931
        $q->prepare()->execute();
1932
1933
        return $this->dbHandler->lastInsertId(
1934
            $this->dbHandler->getSequenceName('ezcontentobject_link', 'id')
1935
        );
1936
    }
1937
1938
    /**
1939
     * Deletes the relation with the given $relationId.
1940
     *
1941
     * @param int $relationId
1942
     * @param int $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
1943
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
1944
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
1945
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
1946
     */
1947
    public function deleteRelation($relationId, $type)
1948
    {
1949
        // Legacy Storage stores COMMON, LINK and EMBED types using bitmask, therefore first load
1950
        // existing relation type by given $relationId for comparison
1951
        /** @var $query \eZ\Publish\Core\Persistence\Database\SelectQuery */
1952
        $query = $this->dbHandler->createSelectQuery();
1953
        $query->select(
1954
            $this->dbHandler->quoteColumn('relation_type')
1955
        )->from(
1956
            $this->dbHandler->quoteTable('ezcontentobject_link')
1957
        )->where(
1958
            $query->expr->eq(
1959
                $this->dbHandler->quoteColumn('id'),
1960
                $query->bindValue($relationId, null, \PDO::PARAM_INT)
1961
            )
1962
        );
1963
1964
        $statement = $query->prepare();
1965
        $statement->execute();
1966
        $loadedRelationType = $statement->fetchColumn();
1967
1968
        if (!$loadedRelationType) {
1969
            return;
1970
        }
1971
1972
        // If relation type matches then delete
1973
        if ($loadedRelationType == $type) {
1974
            /** @var $query \eZ\Publish\Core\Persistence\Database\DeleteQuery */
1975
            $query = $this->dbHandler->createDeleteQuery();
1976
            $query->deleteFrom(
1977
                'ezcontentobject_link'
1978
            )->where(
1979
                $query->expr->eq(
1980
                    $this->dbHandler->quoteColumn('id'),
1981
                    $query->bindValue($relationId, null, \PDO::PARAM_INT)
1982
                )
1983
            );
1984
1985
            $query->prepare()->execute();
1986
        } elseif ($loadedRelationType & $type) { // If relation type is composite update bitmask
1987
            /** @var $query \eZ\Publish\Core\Persistence\Database\UpdateQuery */
1988
            $query = $this->dbHandler->createUpdateQuery();
1989
            $query->update(
1990
                $this->dbHandler->quoteTable('ezcontentobject_link')
1991
            )->set(
1992
                $this->dbHandler->quoteColumn('relation_type'),
1993
                $query->expr->bitAnd(
1994
                    $this->dbHandler->quoteColumn('relation_type'),
1995
                    $query->bindValue(~$type, null, \PDO::PARAM_INT)
1996
                )
1997
            )->where(
1998
                $query->expr->eq(
1999
                    $this->dbHandler->quoteColumn('id'),
2000
                    $query->bindValue($relationId, null, \PDO::PARAM_INT)
2001
                )
2002
            );
2003
2004
            $query->prepare()->execute();
2005
        } else {
2006
            // No match, do nothing
2007
        }
2008
    }
2009
2010
    /**
2011
     * Returns all Content IDs for a given $contentTypeId.
2012
     *
2013
     * @param int $contentTypeId
2014
     *
2015
     * @return int[]
2016
     */
2017
    public function getContentIdsByContentTypeId($contentTypeId)
2018
    {
2019
        $query = $this->dbHandler->createSelectQuery();
2020
        $query
2021
            ->select($this->dbHandler->quoteColumn('id'))
2022
            ->from($this->dbHandler->quoteTable('ezcontentobject'))
2023
            ->where(
2024
                $query->expr->eq(
2025
                    $this->dbHandler->quoteColumn('contentclass_id'),
2026
                    $query->bindValue($contentTypeId, null, PDO::PARAM_INT)
2027
                )
2028
            );
2029
2030
        $statement = $query->prepare();
2031
        $statement->execute();
2032
2033
        return $statement->fetchAll(PDO::FETCH_COLUMN);
2034
    }
2035
2036
    /**
2037
     * Load name data for set of content id's and corresponding version number.
2038
     *
2039
     * @param array[] $rows array of hashes with 'id' and 'version' to load names for
2040
     *
2041
     * @return array
2042
     */
2043
    public function loadVersionedNameData($rows)
2044
    {
2045
        $query = $this->queryBuilder->createNamesQuery();
2046
        $conditions = array();
2047
        foreach ($rows as $row) {
2048
            $conditions[] = $query->expr->lAnd(
2049
                $query->expr->eq(
2050
                    $this->dbHandler->quoteColumn('contentobject_id'),
2051
                    $query->bindValue($row['id'], null, \PDO::PARAM_INT)
2052
                ),
2053
                $query->expr->eq(
2054
                    $this->dbHandler->quoteColumn('content_version'),
2055
                    $query->bindValue($row['version'], null, \PDO::PARAM_INT)
2056
                )
2057
            );
2058
        }
2059
2060
        $query->where($query->expr->lOr($conditions));
2061
        $stmt = $query->prepare();
2062
        $stmt->execute();
2063
2064
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
2065
    }
2066
2067
    /**
2068
     * Batch method for copying all relation meta data for copied Content object.
2069
     *
2070
     * {@inheritdoc}
2071
     *
2072
     * @param int $originalContentId
2073
     * @param int $copiedContentId
2074
     * @param int|null $versionNo If specified only copy for a given version number, otherwise all.
2075
     */
2076
    public function copyRelations($originalContentId, $copiedContentId, $versionNo = null)
2077
    {
2078
        // Given we can retain all columns, we just create copies with new `from_contentobject_id` using INSERT INTO SELECT
2079
        $sql = 'INSERT INTO ezcontentobject_link ( contentclassattribute_id, from_contentobject_id, from_contentobject_version, relation_type, to_contentobject_id )
2080
                SELECT  L2.contentclassattribute_id, :copied_id, L2.from_contentobject_version, L2.relation_type, L2.to_contentobject_id
2081
                FROM    ezcontentobject_link AS L2
2082
                WHERE   L2.from_contentobject_id = :original_id';
2083
2084
        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...
2085
            $stmt = $this->connection->prepare($sql . ' AND L2.from_contentobject_version = :version');
2086
            $stmt->bindValue('version', $versionNo, PDO::PARAM_INT);
2087
        } else {
2088
            $stmt = $this->connection->prepare($sql);
2089
        }
2090
2091
        $stmt->bindValue('original_id', $originalContentId, PDO::PARAM_INT);
2092
        $stmt->bindValue('copied_id', $copiedContentId, PDO::PARAM_INT);
2093
2094
        $stmt->execute();
2095
    }
2096
2097
    /**
2098
     * Remove the specified translation from the Content Object Version.
2099
     *
2100
     * @param int $contentId
2101
     * @param string $languageCode language code of the translation
2102
     * @throws \Doctrine\DBAL\DBALException
2103
     */
2104 View Code Duplication
    public function deleteTranslationFromContent($contentId, $languageCode)
2105
    {
2106
        $language = $this->languageHandler->loadByLanguageCode($languageCode);
2107
2108
        $this->connection->beginTransaction();
2109
        try {
2110
            $this->deleteTranslationFromContentVersions($contentId, $language->id);
2111
            $this->deleteTranslationFromContentNames($contentId, $languageCode);
2112
            $this->deleteTranslationFromContentObject($contentId, $language->id);
2113
2114
            $this->connection->commit();
2115
        } catch (DBALException $e) {
2116
            $this->connection->rollBack();
2117
            throw $e;
2118
        }
2119
    }
2120
2121
    /**
2122
     * Delete Content fields (attributes) for the given Translation.
2123
     * If $versionNo is given, fields for that Version only will be deleted.
2124
     *
2125
     * @param string $languageCode
2126
     * @param int $contentId
2127
     * @param int $versionNo (optional) filter by versionNo
2128
     */
2129 View Code Duplication
    public function deleteTranslatedFields($languageCode, $contentId, $versionNo = null)
2130
    {
2131
        $query = $this->connection->createQueryBuilder();
2132
        $query
2133
            ->delete('ezcontentobject_attribute')
2134
            ->where('contentobject_id = :contentId')
2135
            ->andWhere('language_code = :languageCode')
2136
            ->setParameters(
2137
                [
2138
                    ':contentId' => $contentId,
2139
                    ':languageCode' => $languageCode,
2140
                ]
2141
            )
2142
        ;
2143
2144
        if (null !== $versionNo) {
2145
            $query
2146
                ->andWhere('version = :versionNo')
2147
                ->setParameter(':versionNo', $versionNo)
2148
            ;
2149
        }
2150
2151
        $query->execute();
2152
    }
2153
2154
    /**
2155
     * Delete the specified Translation from the given Version.
2156
     *
2157
     * @param int $contentId
2158
     * @param int $versionNo
2159
     * @param string $languageCode
2160
     * @throws \Doctrine\DBAL\DBALException
2161
     */
2162 View Code Duplication
    public function deleteTranslationFromVersion($contentId, $versionNo, $languageCode)
2163
    {
2164
        $language = $this->languageHandler->loadByLanguageCode($languageCode);
2165
2166
        $this->connection->beginTransaction();
2167
        try {
2168
            $this->deleteTranslationFromContentVersions($contentId, $language->id, $versionNo);
2169
            $this->deleteTranslationFromContentNames($contentId, $languageCode, $versionNo);
2170
2171
            $this->connection->commit();
2172
        } catch (DBALException $e) {
2173
            $this->connection->rollBack();
2174
            throw $e;
2175
        }
2176
    }
2177
2178
    /**
2179
     * Delete translation from the ezcontentobject_name table.
2180
     *
2181
     * @param int $contentId
2182
     * @param string $languageCode
2183
     * @param int $versionNo optional, if specified, apply to this Version only.
2184
     */
2185 View Code Duplication
    private function deleteTranslationFromContentNames($contentId, $languageCode, $versionNo = null)
2186
    {
2187
        $query = $this->connection->createQueryBuilder();
2188
        $query
2189
            ->delete('ezcontentobject_name')
2190
            ->where('contentobject_id=:contentId')
2191
            ->andWhere('real_translation=:languageCode')
2192
            ->setParameters(
2193
                [
2194
                    ':languageCode' => $languageCode,
2195
                    ':contentId' => $contentId,
2196
                ]
2197
            )
2198
        ;
2199
2200
        if (null !== $versionNo) {
2201
            $query
2202
                ->andWhere('content_version = :versionNo')
2203
                ->setParameter(':versionNo', $versionNo)
2204
            ;
2205
        }
2206
2207
        $query->execute();
2208
    }
2209
2210
    /**
2211
     * Remove language from language_mask of ezcontentobject.
2212
     *
2213
     * @param int $contentId
2214
     * @param int $languageId
2215
     * @throws \eZ\Publish\Core\Base\Exceptions\BadStateException
2216
     */
2217
    private function deleteTranslationFromContentObject($contentId, $languageId)
2218
    {
2219
        $query = $this->connection->createQueryBuilder();
2220
        $query->update('ezcontentobject')
2221
            // parameter for bitwise operation has to be placed verbatim (w/o binding) for this to work cross-DBMS
2222
            ->set('language_mask', 'language_mask & ~ ' . $languageId)
2223
            ->set('modified', ':now')
2224
            ->where('id = :contentId')
2225
            ->andWhere(
2226
            // make sure removed translation is not the last one (incl. alwaysAvailable)
2227
                $query->expr()->andX(
2228
                    'language_mask & ~ ' . $languageId . ' <> 0',
2229
                    'language_mask & ~ ' . $languageId . ' <> 1'
2230
                )
2231
            )
2232
            ->setParameter(':now', time())
2233
            ->setParameter(':contentId', $contentId)
2234
        ;
2235
2236
        $rowCount = $query->execute();
2237
2238
        // no rows updated means that most likely somehow it was the last remaining translation
2239
        if ($rowCount === 0) {
2240
            throw new BadStateException(
2241
                '$languageCode',
2242
                'Specified translation is the only one Content Object Version has'
2243
            );
2244
        }
2245
    }
2246
2247
    /**
2248
     * Remove language from language_mask of ezcontentobject_version and update initialLanguageId
2249
     * if it matches the removed one.
2250
     *
2251
     * @param int $contentId
2252
     * @param int $languageId
2253
     * @param int $versionNo optional, if specified, apply to this Version only.
2254
     * @throws \eZ\Publish\Core\Base\Exceptions\BadStateException
2255
     */
2256
    private function deleteTranslationFromContentVersions($contentId, $languageId, $versionNo = null)
2257
    {
2258
        $query = $this->connection->createQueryBuilder();
2259
        $query->update('ezcontentobject_version')
2260
            // parameter for bitwise operation has to be placed verbatim (w/o binding) for this to work cross-DBMS
2261
            ->set('language_mask', 'language_mask & ~ ' . $languageId)
2262
            ->set('modified', ':now')
2263
            // update initial_language_id only if it matches removed translation languageId
2264
            ->set(
2265
                'initial_language_id',
2266
                'CASE WHEN initial_language_id = :languageId ' .
2267
                'THEN (SELECT initial_language_id AS main_language_id FROM ezcontentobject c WHERE c.id = :contentId) ' .
2268
                'ELSE initial_language_id END'
2269
            )
2270
            ->where('contentobject_id = :contentId')
2271
            ->andWhere(
2272
            // make sure removed translation is not the last one (incl. alwaysAvailable)
2273
                $query->expr()->andX(
2274
                    'language_mask & ~ ' . $languageId . ' <> 0',
2275
                    'language_mask & ~ ' . $languageId . ' <> 1'
2276
                )
2277
            )
2278
            ->setParameter(':now', time())
2279
            ->setParameter(':contentId', $contentId)
2280
            ->setParameter(':languageId', $languageId)
2281
        ;
2282
2283
        if (null !== $versionNo) {
2284
            $query
2285
                ->andWhere('version = :versionNo')
2286
                ->setParameter(':versionNo', $versionNo)
2287
            ;
2288
        }
2289
2290
        $rowCount = $query->execute();
2291
2292
        // no rows updated means that most likely somehow it was the last remaining translation
2293
        if ($rowCount === 0) {
2294
            throw new BadStateException(
2295
                '$languageCode',
2296
                'Specified translation is the only one Content Object Version has'
2297
            );
2298
        }
2299
    }
2300
}
2301