Completed
Push — master ( 97e40f...89ec5c )
by André
40:26 queued 12:35
created

DoctrineDatabase::internalLoadContentInfo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 13
nc 1
nop 3
dl 0
loc 16
rs 9.4285
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
    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
     * @see loadContentInfo(), loadContentInfoByRemoteId(), loadContentInfoList()
856
     *
857
     * @param string $column
858
     * @param array $ids Array of int, or if $bindype is set to Connection::PARAM_STR_ARRAY then array of string
859
     * @param int $bindType One of Connection::PARAM_*_ARRAY constants.
860
     *
861
     * @return array
862
     */
863
    private function internalLoadContentInfo(string $column, array $ids, int $bindType = Connection::PARAM_INT_ARRAY): array
864
    {
865
        $q = $this->connection->createQueryBuilder();
866
        $q
867
            ->select('c.*', 't.main_node_id AS ezcontentobject_tree_main_node_id')
868
            ->from('ezcontentobject', 'c')
869
            ->leftJoin(
870
                'c',
871
                'ezcontentobject_tree',
872
                't',
873
                'c.id = t.contentobject_id AND t.node_id = t.main_node_id'
874
            )->where("c.${column} IN (:ids)")
875
            ->setParameter('ids', $ids, $bindType);
876
877
        return $q->execute()->fetchAll();
878
    }
879
880
    /**
881
     * Loads info for content identified by $contentId.
882
     * Will basically return a hash containing all field values for ezcontentobject table plus some additional keys:
883
     *  - always_available => Boolean indicating if content's language mask contains alwaysAvailable bit field
884
     *  - main_language_code => Language code for main (initial) language. E.g. "eng-GB".
885
     *
886
     * @param int $contentId
887
     *
888
     * @throws \eZ\Publish\Core\Base\Exceptions\NotFoundException
889
     *
890
     * @return array
891
     */
892 View Code Duplication
    public function loadContentInfo($contentId)
893
    {
894
        $results = $this->internalLoadContentInfo('id', [$contentId]);
895
        if (empty($results)) {
896
            throw new NotFound('content', "id: $contentId");
897
        }
898
899
        return $results[0];
900
    }
901
902
    public function loadContentInfoList(array $contentIds)
903
    {
904
        return $this->internalLoadContentInfo('id', $contentIds);
905
    }
906
907
    /**
908
     * Loads info for a content object identified by its remote ID.
909
     *
910
     * Returns an array with the relevant data.
911
     *
912
     * @param mixed $remoteId
913
     *
914
     * @throws \eZ\Publish\Core\Base\Exceptions\NotFoundException
915
     *
916
     * @return array
917
     */
918 View Code Duplication
    public function loadContentInfoByRemoteId($remoteId)
919
    {
920
        $results = $this->internalLoadContentInfo('remote_id', [$remoteId], Connection::PARAM_STR_ARRAY);
921
        if (empty($results)) {
922
            throw new NotFound('content', "remote_id: $remoteId");
923
        }
924
925
        return $results[0];
926
    }
927
928
    /**
929
     * Loads version info for content identified by $contentId and $versionNo.
930
     * Will basically return a hash containing all field values from ezcontentobject_version table plus following keys:
931
     *  - names => Hash of content object names. Key is the language code, value is the name.
932
     *  - 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.
933
     *  - initial_language_code => Language code for initial language in this version.
934
     *
935
     * @param int $contentId
936
     * @param int $versionNo
937
     *
938
     * @return array
939
     */
940 View Code Duplication
    public function loadVersionInfo($contentId, $versionNo)
941
    {
942
        $query = $this->queryBuilder->createVersionInfoFindQuery();
943
        $query->where(
944
            $query->expr->lAnd(
945
                $query->expr->eq(
946
                    $this->dbHandler->quoteColumn('contentobject_id', 'ezcontentobject_version'),
947
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
948
                ),
949
                $query->expr->eq(
950
                    $this->dbHandler->quoteColumn('version', 'ezcontentobject_version'),
951
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
952
                )
953
            )
954
        );
955
        $statement = $query->prepare();
956
        $statement->execute();
957
958
        return $statement->fetchAll(\PDO::FETCH_ASSOC);
959
    }
960
961
    /**
962
     * Returns data for all versions with given status created by the given $userId.
963
     *
964
     * @param int $userId
965
     * @param int $status
966
     *
967
     * @return string[][]
968
     */
969
    public function listVersionsForUser($userId, $status = VersionInfo::STATUS_DRAFT)
970
    {
971
        $query = $this->queryBuilder->createVersionInfoFindQuery();
972
        $query->where(
973
            $query->expr->lAnd(
974
                $query->expr->eq(
975
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject_version'),
976
                    $query->bindValue($status, null, \PDO::PARAM_INT)
977
                ),
978
                $query->expr->eq(
979
                    $this->dbHandler->quoteColumn('creator_id', 'ezcontentobject_version'),
980
                    $query->bindValue($userId, null, \PDO::PARAM_INT)
981
                )
982
            )
983
        );
984
985
        return $this->listVersionsHelper($query);
986
    }
987
988
    /**
989
     * Returns all version data for the given $contentId, optionally filtered by status.
990
     *
991
     * Result is returned with oldest version first (using version id as it has index and is auto increment).
992
     *
993
     * @param mixed $contentId
994
     * @param mixed|null $status Optional argument to filter versions by status, like {@see VersionInfo::STATUS_ARCHIVED}.
995
     * @param int $limit Limit for items returned, -1 means none.
996
     *
997
     * @return string[][]
998
     */
999
    public function listVersions($contentId, $status = null, $limit = -1)
1000
    {
1001
        $query = $this->queryBuilder->createVersionInfoFindQuery();
1002
1003
        $filter = $query->expr->eq(
1004
            $this->dbHandler->quoteColumn('contentobject_id', 'ezcontentobject_version'),
1005
            $query->bindValue($contentId, null, \PDO::PARAM_INT)
1006
        );
1007
1008
        if ($status !== null) {
1009
            $filter = $query->expr->lAnd(
1010
                $filter,
1011
                $query->expr->eq(
1012
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject_version'),
1013
                    $query->bindValue($status, null, \PDO::PARAM_INT)
1014
                )
1015
            );
1016
        }
1017
1018
        $query->where($filter);
1019
1020
        if ($limit > 0) {
1021
            $query->limit($limit);
1022
        }
1023
1024
        return $this->listVersionsHelper($query);
1025
    }
1026
1027
    /**
1028
     * Helper for {@see listVersions()} and {@see listVersionsForUser()} that filters duplicates
1029
     * that are the result of the cartesian product performed by createVersionInfoFindQuery().
1030
     *
1031
     * @param \eZ\Publish\Core\Persistence\Database\SelectQuery $query
1032
     *
1033
     * @return string[][]
1034
     */
1035
    private function listVersionsHelper(SelectQuery $query)
1036
    {
1037
        $query->orderBy(
1038
            $this->dbHandler->quoteColumn('id', 'ezcontentobject_version')
1039
        );
1040
1041
        $statement = $query->prepare();
1042
        $statement->execute();
1043
1044
        $results = array();
1045
        $previousId = null;
1046
        foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $row) {
1047
            if ($row['ezcontentobject_version_id'] == $previousId) {
1048
                continue;
1049
            }
1050
1051
            $previousId = $row['ezcontentobject_version_id'];
1052
            $results[] = $row;
1053
        }
1054
1055
        return $results;
1056
    }
1057
1058
    /**
1059
     * Returns all version numbers for the given $contentId.
1060
     *
1061
     * @param mixed $contentId
1062
     *
1063
     * @return int[]
1064
     */
1065
    public function listVersionNumbers($contentId)
1066
    {
1067
        $query = $this->dbHandler->createSelectQuery();
1068
        $query->selectDistinct(
1069
            $this->dbHandler->quoteColumn('version')
1070
        )->from(
1071
            $this->dbHandler->quoteTable('ezcontentobject_version')
1072
        )->where(
1073
            $query->expr->eq(
1074
                $this->dbHandler->quoteColumn('contentobject_id'),
1075
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1076
            )
1077
        );
1078
1079
        $statement = $query->prepare();
1080
        $statement->execute();
1081
1082
        return $statement->fetchAll(\PDO::FETCH_COLUMN);
1083
    }
1084
1085
    /**
1086
     * Returns last version number for content identified by $contentId.
1087
     *
1088
     * @param int $contentId
1089
     *
1090
     * @return int
1091
     */
1092
    public function getLastVersionNumber($contentId)
1093
    {
1094
        $query = $this->dbHandler->createSelectQuery();
1095
        $query->select(
1096
            $query->expr->max($this->dbHandler->quoteColumn('version'))
1097
        )->from(
1098
            $this->dbHandler->quoteTable('ezcontentobject_version')
1099
        )->where(
1100
            $query->expr->eq(
1101
                $this->dbHandler->quoteColumn('contentobject_id'),
1102
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1103
            )
1104
        );
1105
1106
        $statement = $query->prepare();
1107
        $statement->execute();
1108
1109
        return (int)$statement->fetchColumn();
1110
    }
1111
1112
    /**
1113
     * Returns all IDs for locations that refer to $contentId.
1114
     *
1115
     * @param int $contentId
1116
     *
1117
     * @return int[]
1118
     */
1119
    public function getAllLocationIds($contentId)
1120
    {
1121
        $query = $this->dbHandler->createSelectQuery();
1122
        $query->select(
1123
            $this->dbHandler->quoteColumn('node_id')
1124
        )->from(
1125
            $this->dbHandler->quoteTable('ezcontentobject_tree')
1126
        )->where(
1127
            $query->expr->eq(
1128
                $this->dbHandler->quoteColumn('contentobject_id'),
1129
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1130
            )
1131
        );
1132
1133
        $statement = $query->prepare();
1134
        $statement->execute();
1135
1136
        return $statement->fetchAll(\PDO::FETCH_COLUMN);
1137
    }
1138
1139
    /**
1140
     * Returns all field IDs of $contentId grouped by their type.
1141
     * If $versionNo is set only field IDs for that version are returned.
1142
     * If $languageCode is set, only field IDs for that language are returned.
1143
     *
1144
     * @param int $contentId
1145
     * @param int|null $versionNo
1146
     * @param string|null $languageCode
1147
     *
1148
     * @return int[][]
1149
     */
1150
    public function getFieldIdsByType($contentId, $versionNo = null, $languageCode = null)
1151
    {
1152
        $query = $this->dbHandler->createSelectQuery();
1153
        $query->select(
1154
            $this->dbHandler->quoteColumn('id'),
1155
            $this->dbHandler->quoteColumn('data_type_string')
1156
        )->from(
1157
            $this->dbHandler->quoteTable('ezcontentobject_attribute')
1158
        )->where(
1159
            $query->expr->eq(
1160
                $this->dbHandler->quoteColumn('contentobject_id'),
1161
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1162
            )
1163
        );
1164
1165
        if (isset($versionNo)) {
1166
            $query->where(
1167
                $query->expr->eq(
1168
                    $this->dbHandler->quoteColumn('version'),
1169
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1170
                )
1171
            );
1172
        }
1173
1174
        if (isset($languageCode)) {
1175
            $query->where(
1176
                $query->expr->eq(
1177
                    $this->dbHandler->quoteColumn('language_code'),
1178
                    $query->bindValue($languageCode, null, \PDO::PARAM_STR)
1179
                )
1180
            );
1181
        }
1182
1183
        $statement = $query->prepare();
1184
        $statement->execute();
1185
1186
        $result = array();
1187
        foreach ($statement->fetchAll() as $row) {
1188
            if (!isset($result[$row['data_type_string']])) {
1189
                $result[$row['data_type_string']] = array();
1190
            }
1191
            $result[$row['data_type_string']][] = (int)$row['id'];
1192
        }
1193
1194
        return $result;
1195
    }
1196
1197
    /**
1198
     * Deletes relations to and from $contentId.
1199
     * If $versionNo is set only relations for that version are deleted.
1200
     *
1201
     * @param int $contentId
1202
     * @param int|null $versionNo
1203
     */
1204
    public function deleteRelations($contentId, $versionNo = null)
1205
    {
1206
        $query = $this->dbHandler->createDeleteQuery();
1207
        $query->deleteFrom(
1208
            $this->dbHandler->quoteTable('ezcontentobject_link')
1209
        );
1210
1211
        if (isset($versionNo)) {
1212
            $query->where(
1213
                $query->expr->lAnd(
1214
                    $query->expr->eq(
1215
                        $this->dbHandler->quoteColumn('from_contentobject_id'),
1216
                        $query->bindValue($contentId, null, \PDO::PARAM_INT)
1217
                    ),
1218
                    $query->expr->eq(
1219
                        $this->dbHandler->quoteColumn('from_contentobject_version'),
1220
                        $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1221
                    )
1222
                )
1223
            );
1224
        } else {
1225
            $query->where(
1226
                $query->expr->lOr(
1227
                    $query->expr->eq(
1228
                        $this->dbHandler->quoteColumn('from_contentobject_id'),
1229
                        $query->bindValue($contentId, null, \PDO::PARAM_INT)
1230
                    ),
1231
                    $query->expr->eq(
1232
                        $this->dbHandler->quoteColumn('to_contentobject_id'),
1233
                        $query->bindValue($contentId, null, \PDO::PARAM_INT)
1234
                    )
1235
                )
1236
            );
1237
        }
1238
1239
        $query->prepare()->execute();
1240
    }
1241
1242
    /**
1243
     * Removes relations to Content with $contentId from Relation and RelationList field type fields.
1244
     *
1245
     * @param int $contentId
1246
     */
1247
    public function removeReverseFieldRelations($contentId)
1248
    {
1249
        $query = $this->dbHandler->createSelectQuery();
1250
        $query
1251
            ->select('ezcontentobject_attribute.*')
1252
            ->from('ezcontentobject_attribute')
1253
            ->innerJoin(
1254
                'ezcontentobject_link',
1255
                $query->expr->lAnd(
1256
                    $query->expr->eq(
1257
                        $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link'),
1258
                        $this->dbHandler->quoteColumn('contentobject_id', 'ezcontentobject_attribute')
1259
                    ),
1260
                    $query->expr->eq(
1261
                        $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link'),
1262
                        $this->dbHandler->quoteColumn('version', 'ezcontentobject_attribute')
1263
                    ),
1264
                    $query->expr->eq(
1265
                        $this->dbHandler->quoteColumn('contentclassattribute_id', 'ezcontentobject_link'),
1266
                        $this->dbHandler->quoteColumn('contentclassattribute_id', 'ezcontentobject_attribute')
1267
                    )
1268
                )
1269
            )
1270
            ->where(
1271
                $query->expr->eq(
1272
                    $this->dbHandler->quoteColumn('to_contentobject_id', 'ezcontentobject_link'),
1273
                    $query->bindValue($contentId, null, PDO::PARAM_INT)
1274
                ),
1275
                $query->expr->gt(
1276
                    $query->expr->bitAnd(
1277
                        $this->dbHandler->quoteColumn('relation_type', 'ezcontentobject_link'),
1278
                        $query->bindValue(8, null, PDO::PARAM_INT)
1279
                    ),
1280
                    0
1281
                )
1282
            );
1283
1284
        $statement = $query->prepare();
1285
        $statement->execute();
1286
1287
        while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
1288
            if ($row['data_type_string'] === 'ezobjectrelation') {
1289
                $this->removeRelationFromRelationField($row);
1290
            }
1291
1292
            if ($row['data_type_string'] === 'ezobjectrelationlist') {
1293
                $this->removeRelationFromRelationListField($contentId, $row);
1294
            }
1295
        }
1296
    }
1297
1298
    /**
1299
     * Updates field value of RelationList field type identified by given $row data,
1300
     * removing relations toward given $contentId.
1301
     *
1302
     * @param int $contentId
1303
     * @param array $row
1304
     */
1305
    protected function removeRelationFromRelationListField($contentId, array $row)
1306
    {
1307
        $document = new DOMDocument('1.0', 'utf-8');
1308
        $document->loadXML($row['data_text']);
1309
1310
        $xpath = new DOMXPath($document);
1311
        $xpathExpression = "//related-objects/relation-list/relation-item[@contentobject-id='{$contentId}']";
1312
1313
        $relationItems = $xpath->query($xpathExpression);
1314
        foreach ($relationItems as $relationItem) {
1315
            $relationItem->parentNode->removeChild($relationItem);
1316
        }
1317
1318
        $query = $this->dbHandler->createUpdateQuery();
1319
        $query
1320
            ->update('ezcontentobject_attribute')
1321
            ->set(
1322
                'data_text',
1323
                $query->bindValue($document->saveXML(), null, PDO::PARAM_STR)
1324
            )
1325
            ->where(
1326
                $query->expr->lAnd(
1327
                    $query->expr->eq(
1328
                        $this->dbHandler->quoteColumn('id'),
1329
                        $query->bindValue($row['id'], null, PDO::PARAM_INT)
1330
                    ),
1331
                    $query->expr->eq(
1332
                        $this->dbHandler->quoteColumn('version'),
1333
                        $query->bindValue($row['version'], null, PDO::PARAM_INT)
1334
                    )
1335
                )
1336
            );
1337
1338
        $query->prepare()->execute();
1339
    }
1340
1341
    /**
1342
     * Updates field value of Relation field type identified by given $row data,
1343
     * removing relation data.
1344
     *
1345
     * @param array $row
1346
     */
1347
    protected function removeRelationFromRelationField(array $row)
1348
    {
1349
        $query = $this->dbHandler->createUpdateQuery();
1350
        $query
1351
            ->update('ezcontentobject_attribute')
1352
            ->set('data_int', $query->bindValue(null, null, PDO::PARAM_INT))
1353
            ->set('sort_key_int', $query->bindValue(0, null, PDO::PARAM_INT))
1354
            ->where(
1355
                $query->expr->lAnd(
1356
                    $query->expr->eq(
1357
                        $this->dbHandler->quoteColumn('id'),
1358
                        $query->bindValue($row['id'], null, PDO::PARAM_INT)
1359
                    ),
1360
                    $query->expr->eq(
1361
                        $this->dbHandler->quoteColumn('version'),
1362
                        $query->bindValue($row['version'], null, PDO::PARAM_INT)
1363
                    )
1364
                )
1365
            );
1366
1367
        $query->prepare()->execute();
1368
    }
1369
1370
    /**
1371
     * Deletes the field with the given $fieldId.
1372
     *
1373
     * @param int $fieldId
1374
     */
1375
    public function deleteField($fieldId)
1376
    {
1377
        $query = $this->dbHandler->createDeleteQuery();
1378
        $query->deleteFrom(
1379
            $this->dbHandler->quoteTable('ezcontentobject_attribute')
1380
        )->where(
1381
            $query->expr->eq(
1382
                $this->dbHandler->quoteColumn('id'),
1383
                $query->bindValue($fieldId, null, \PDO::PARAM_INT)
1384
            )
1385
        );
1386
1387
        $query->prepare()->execute();
1388
    }
1389
1390
    /**
1391
     * Deletes all fields of $contentId in all versions.
1392
     * If $versionNo is set only fields for that version are deleted.
1393
     *
1394
     * @param int $contentId
1395
     * @param int|null $versionNo
1396
     */
1397
    public function deleteFields($contentId, $versionNo = null)
1398
    {
1399
        $query = $this->dbHandler->createDeleteQuery();
1400
        $query->deleteFrom('ezcontentobject_attribute')
1401
            ->where(
1402
                $query->expr->eq(
1403
                    $this->dbHandler->quoteColumn('contentobject_id'),
1404
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1405
                )
1406
            );
1407
1408
        if (isset($versionNo)) {
1409
            $query->where(
1410
                $query->expr->eq(
1411
                    $this->dbHandler->quoteColumn('version'),
1412
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1413
                )
1414
            );
1415
        }
1416
1417
        $query->prepare()->execute();
1418
    }
1419
1420
    /**
1421
     * Deletes all versions of $contentId.
1422
     * If $versionNo is set only that version is deleted.
1423
     *
1424
     * @param int $contentId
1425
     * @param int|null $versionNo
1426
     */
1427
    public function deleteVersions($contentId, $versionNo = null)
1428
    {
1429
        $query = $this->dbHandler->createDeleteQuery();
1430
        $query->deleteFrom('ezcontentobject_version')
1431
            ->where(
1432
                $query->expr->eq(
1433
                    $this->dbHandler->quoteColumn('contentobject_id'),
1434
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1435
                )
1436
            );
1437
1438
        if (isset($versionNo)) {
1439
            $query->where(
1440
                $query->expr->eq(
1441
                    $this->dbHandler->quoteColumn('version'),
1442
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1443
                )
1444
            );
1445
        }
1446
1447
        $query->prepare()->execute();
1448
    }
1449
1450
    /**
1451
     * Deletes all names of $contentId.
1452
     * If $versionNo is set only names for that version are deleted.
1453
     *
1454
     * @param int $contentId
1455
     * @param int|null $versionNo
1456
     */
1457
    public function deleteNames($contentId, $versionNo = null)
1458
    {
1459
        $query = $this->dbHandler->createDeleteQuery();
1460
        $query->deleteFrom('ezcontentobject_name')
1461
            ->where(
1462
                $query->expr->eq(
1463
                    $this->dbHandler->quoteColumn('contentobject_id'),
1464
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1465
                )
1466
            );
1467
1468
        if (isset($versionNo)) {
1469
            $query->where(
1470
                $query->expr->eq(
1471
                    $this->dbHandler->quoteColumn('content_version'),
1472
                    $query->bindValue($versionNo, null, \PDO::PARAM_INT)
1473
                )
1474
            );
1475
        }
1476
1477
        $query->prepare()->execute();
1478
    }
1479
1480
    /**
1481
     * Sets the name for Content $contentId in version $version to $name in $language.
1482
     *
1483
     * @param int $contentId
1484
     * @param int $version
1485
     * @param string $name
1486
     * @param string $language
1487
     */
1488
    public function setName($contentId, $version, $name, $language)
1489
    {
1490
        $language = $this->languageHandler->loadByLanguageCode($language);
1491
1492
        // Is it an insert or an update ?
1493
        $qSelect = $this->dbHandler->createSelectQuery();
1494
        $qSelect
1495
            ->select(
1496
                $qSelect->alias($qSelect->expr->count('*'), 'count')
1497
            )
1498
            ->from($this->dbHandler->quoteTable('ezcontentobject_name'))
1499
            ->where(
1500
                $qSelect->expr->lAnd(
1501
                    $qSelect->expr->eq($this->dbHandler->quoteColumn('contentobject_id'), $qSelect->bindValue($contentId)),
1502
                    $qSelect->expr->eq($this->dbHandler->quoteColumn('content_version'), $qSelect->bindValue($version)),
1503
                    $qSelect->expr->eq($this->dbHandler->quoteColumn('content_translation'), $qSelect->bindValue($language->languageCode))
1504
                )
1505
            );
1506
        $stmt = $qSelect->prepare();
1507
        $stmt->execute();
1508
        $res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
1509
1510
        $insert = $res[0]['count'] == 0;
1511
        if ($insert) {
1512
            $q = $this->dbHandler->createInsertQuery();
1513
            $q->insertInto($this->dbHandler->quoteTable('ezcontentobject_name'));
1514
        } else {
1515
            $q = $this->dbHandler->createUpdateQuery();
1516
            $q->update($this->dbHandler->quoteTable('ezcontentobject_name'))
1517
                ->where(
1518
                    $q->expr->lAnd(
1519
                        $q->expr->eq($this->dbHandler->quoteColumn('contentobject_id'), $q->bindValue($contentId)),
1520
                        $q->expr->eq($this->dbHandler->quoteColumn('content_version'), $q->bindValue($version)),
1521
                        $q->expr->eq($this->dbHandler->quoteColumn('content_translation'), $q->bindValue($language->languageCode))
1522
                    )
1523
                );
1524
        }
1525
1526
        $q->set(
1527
            $this->dbHandler->quoteColumn('contentobject_id'),
1528
            $q->bindValue($contentId, null, \PDO::PARAM_INT)
1529
        )->set(
1530
            $this->dbHandler->quoteColumn('content_version'),
1531
            $q->bindValue($version, null, \PDO::PARAM_INT)
1532
        )->set(
1533
            $this->dbHandler->quoteColumn('language_id'),
1534
            '(' . $this->getLanguageQuery()->getQuery() . ')'
1535
        )->set(
1536
            $this->dbHandler->quoteColumn('content_translation'),
1537
            $q->bindValue($language->languageCode)
1538
        )->set(
1539
            $this->dbHandler->quoteColumn('real_translation'),
1540
            $q->bindValue($language->languageCode)
1541
        )->set(
1542
            $this->dbHandler->quoteColumn('name'),
1543
            $q->bindValue($name)
1544
        );
1545
        $q->bindValue($language->id, ':languageId', \PDO::PARAM_INT);
1546
        $q->bindValue($contentId, ':contentId', \PDO::PARAM_INT);
1547
        $q->prepare()->execute();
1548
    }
1549
1550
    /**
1551
     * Returns a language sub select query for setName.
1552
     *
1553
     * Return sub select query which gets proper language mask for alwaysAvailable Content.
1554
     *
1555
     * @return \eZ\Publish\Core\Persistence\Database\SelectQuery
1556
     */
1557
    private function getLanguageQuery()
1558
    {
1559
        $languageQuery = $this->dbHandler->createSelectQuery();
1560
        $languageQuery
1561
            ->select(
1562
                $languageQuery->expr->searchedCase(
1563
                    [
1564
                        $languageQuery->expr->lAnd(
1565
                            $languageQuery->expr->eq(
1566
                                $this->dbHandler->quoteColumn('initial_language_id'),
1567
                                ':languageId'
1568
                            ),
1569
                            // wrap bitwise check into another "neq" to provide cross-DBMS compatibility
1570
                            $languageQuery->expr->neq(
1571
                                $languageQuery->expr->bitAnd(
1572
                                    $this->dbHandler->quoteColumn('language_mask'),
1573
                                    ':languageId'
1574
                                ),
1575
                                0
1576
                            )
1577
                        ),
1578
                        $languageQuery->expr->bitOr(
1579
                            ':languageId',
1580
                            1
1581
                        ),
1582
                    ],
1583
                    ':languageId'
1584
                )
1585
            )
1586
            ->from('ezcontentobject')
1587
            ->where(
1588
                $languageQuery->expr->eq(
1589
                    'id',
1590
                    ':contentId'
1591
                )
1592
            );
1593
1594
        return $languageQuery;
1595
    }
1596
1597
    /**
1598
     * Deletes the actual content object referred to by $contentId.
1599
     *
1600
     * @param int $contentId
1601
     */
1602
    public function deleteContent($contentId)
1603
    {
1604
        $query = $this->dbHandler->createDeleteQuery();
1605
        $query->deleteFrom('ezcontentobject')
1606
            ->where(
1607
                $query->expr->eq(
1608
                    $this->dbHandler->quoteColumn('id'),
1609
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1610
                )
1611
            );
1612
1613
        $query->prepare()->execute();
1614
    }
1615
1616
    /**
1617
     * Loads relations from $contentId to published content, optionally only from $contentVersionNo.
1618
     *
1619
     * $relationType can also be filtered.
1620
     *
1621
     * @param int $contentId
1622
     * @param int $contentVersionNo
1623
     * @param int $relationType
1624
     *
1625
     * @return string[][] array of relation data
1626
     */
1627
    public function loadRelations($contentId, $contentVersionNo = null, $relationType = null)
1628
    {
1629
        $query = $this->queryBuilder->createRelationFindQuery();
1630
        $query->innerJoin(
1631
            $query->alias(
1632
                $this->dbHandler->quoteTable('ezcontentobject'),
1633
                'ezcontentobject_to'
1634
            ),
1635
            $query->expr->lAnd(
1636
                $query->expr->eq(
1637
                    $this->dbHandler->quoteColumn('to_contentobject_id', 'ezcontentobject_link'),
1638
                    $this->dbHandler->quoteColumn('id', 'ezcontentobject_to')
1639
                ),
1640
                $query->expr->eq(
1641
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject_to'),
1642
                    $query->bindValue(1, null, \PDO::PARAM_INT)
1643
                )
1644
            )
1645
        )->where(
1646
            $query->expr->eq(
1647
                $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link'),
1648
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1649
            )
1650
        );
1651
1652
        // source version number
1653
        if (isset($contentVersionNo)) {
1654
            $query->where(
1655
                $query->expr->eq(
1656
                    $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link'),
1657
                    $query->bindValue($contentVersionNo, null, \PDO::PARAM_INT)
1658
                )
1659
            );
1660
        } else { // from published version only
1661
            $query->from(
1662
                $this->dbHandler->quoteTable('ezcontentobject')
1663
            )->where(
1664
                $query->expr->lAnd(
1665
                    $query->expr->eq(
1666
                        $this->dbHandler->quoteColumn('id', 'ezcontentobject'),
1667
                        $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link')
1668
                    ),
1669
                    $query->expr->eq(
1670
                        $this->dbHandler->quoteColumn('current_version', 'ezcontentobject'),
1671
                        $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link')
1672
                    )
1673
                )
1674
            );
1675
        }
1676
1677
        // relation type
1678 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...
1679
            $query->where(
1680
                $query->expr->gt(
1681
                    $query->expr->bitAnd(
1682
                        $this->dbHandler->quoteColumn('relation_type', 'ezcontentobject_link'),
1683
                        $query->bindValue($relationType, null, \PDO::PARAM_INT)
1684
                    ),
1685
                    0
1686
                )
1687
            );
1688
        }
1689
1690
        $statement = $query->prepare();
1691
        $statement->execute();
1692
1693
        return $statement->fetchAll(\PDO::FETCH_ASSOC);
1694
    }
1695
1696
    /**
1697
     * Loads data that related to $toContentId.
1698
     *
1699
     * @param int $toContentId
1700
     * @param int $relationType
1701
     *
1702
     * @return mixed[][] Content data, array structured like {@see \eZ\Publish\Core\Persistence\Legacy\Content\Gateway::load()}
1703
     */
1704
    public function loadReverseRelations($toContentId, $relationType = null)
1705
    {
1706
        $query = $this->queryBuilder->createRelationFindQuery();
1707
        $query->where(
1708
            $query->expr->eq(
1709
                $this->dbHandler->quoteColumn('to_contentobject_id', 'ezcontentobject_link'),
1710
                $query->bindValue($toContentId, null, \PDO::PARAM_INT)
1711
            )
1712
        );
1713
1714
        // ezcontentobject join
1715
        $query->from(
1716
            $this->dbHandler->quoteTable('ezcontentobject')
1717
        )->where(
1718
            $query->expr->lAnd(
1719
                $query->expr->eq(
1720
                    $this->dbHandler->quoteColumn('id', 'ezcontentobject'),
1721
                    $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link')
1722
                ),
1723
                $query->expr->eq(
1724
                    $this->dbHandler->quoteColumn('current_version', 'ezcontentobject'),
1725
                    $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link')
1726
                ),
1727
                $query->expr->eq(
1728
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject'),
1729
                    $query->bindValue(1, null, \PDO::PARAM_INT)
1730
                )
1731
            )
1732
        );
1733
1734
        // relation type
1735 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...
1736
            $query->where(
1737
                $query->expr->gt(
1738
                    $query->expr->bitAnd(
1739
                        $this->dbHandler->quoteColumn('relation_type', 'ezcontentobject_link'),
1740
                        $query->bindValue($relationType, null, \PDO::PARAM_INT)
1741
                    ),
1742
                    0
1743
                )
1744
            );
1745
        }
1746
1747
        $statement = $query->prepare();
1748
1749
        $statement->execute();
1750
1751
        return $statement->fetchAll(\PDO::FETCH_ASSOC);
1752
    }
1753
1754
    /**
1755
     * Inserts a new relation database record.
1756
     *
1757
     * @param \eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct $createStruct
1758
     *
1759
     * @return int ID the inserted ID
1760
     */
1761 View Code Duplication
    public function insertRelation(RelationCreateStruct $createStruct)
1762
    {
1763
        $q = $this->dbHandler->createInsertQuery();
1764
        $q->insertInto(
1765
            $this->dbHandler->quoteTable('ezcontentobject_link')
1766
        )->set(
1767
            $this->dbHandler->quoteColumn('id'),
1768
            $this->dbHandler->getAutoIncrementValue('ezcontentobject_link', 'id')
1769
        )->set(
1770
            $this->dbHandler->quoteColumn('contentclassattribute_id'),
1771
            $q->bindValue((int)$createStruct->sourceFieldDefinitionId, null, \PDO::PARAM_INT)
1772
        )->set(
1773
            $this->dbHandler->quoteColumn('from_contentobject_id'),
1774
            $q->bindValue($createStruct->sourceContentId, null, \PDO::PARAM_INT)
1775
        )->set(
1776
            $this->dbHandler->quoteColumn('from_contentobject_version'),
1777
            $q->bindValue($createStruct->sourceContentVersionNo, null, \PDO::PARAM_INT)
1778
        )->set(
1779
            $this->dbHandler->quoteColumn('relation_type'),
1780
            $q->bindValue($createStruct->type, null, \PDO::PARAM_INT)
1781
        )->set(
1782
            $this->dbHandler->quoteColumn('to_contentobject_id'),
1783
            $q->bindValue($createStruct->destinationContentId, null, \PDO::PARAM_INT)
1784
        );
1785
1786
        $q->prepare()->execute();
1787
1788
        return $this->dbHandler->lastInsertId(
1789
            $this->dbHandler->getSequenceName('ezcontentobject_link', 'id')
1790
        );
1791
    }
1792
1793
    /**
1794
     * Deletes the relation with the given $relationId.
1795
     *
1796
     * @param int $relationId
1797
     * @param int $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
1798
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
1799
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
1800
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
1801
     */
1802
    public function deleteRelation($relationId, $type)
1803
    {
1804
        // Legacy Storage stores COMMON, LINK and EMBED types using bitmask, therefore first load
1805
        // existing relation type by given $relationId for comparison
1806
        /** @var $query \eZ\Publish\Core\Persistence\Database\SelectQuery */
1807
        $query = $this->dbHandler->createSelectQuery();
1808
        $query->select(
1809
            $this->dbHandler->quoteColumn('relation_type')
1810
        )->from(
1811
            $this->dbHandler->quoteTable('ezcontentobject_link')
1812
        )->where(
1813
            $query->expr->eq(
1814
                $this->dbHandler->quoteColumn('id'),
1815
                $query->bindValue($relationId, null, \PDO::PARAM_INT)
1816
            )
1817
        );
1818
1819
        $statement = $query->prepare();
1820
        $statement->execute();
1821
        $loadedRelationType = $statement->fetchColumn();
1822
1823
        if (!$loadedRelationType) {
1824
            return;
1825
        }
1826
1827
        // If relation type matches then delete
1828
        if ($loadedRelationType == $type) {
1829
            /** @var $query \eZ\Publish\Core\Persistence\Database\DeleteQuery */
1830
            $query = $this->dbHandler->createDeleteQuery();
1831
            $query->deleteFrom(
1832
                'ezcontentobject_link'
1833
            )->where(
1834
                $query->expr->eq(
1835
                    $this->dbHandler->quoteColumn('id'),
1836
                    $query->bindValue($relationId, null, \PDO::PARAM_INT)
1837
                )
1838
            );
1839
1840
            $query->prepare()->execute();
1841
        } elseif ($loadedRelationType & $type) { // If relation type is composite update bitmask
1842
            /** @var $query \eZ\Publish\Core\Persistence\Database\UpdateQuery */
1843
            $query = $this->dbHandler->createUpdateQuery();
1844
            $query->update(
1845
                $this->dbHandler->quoteTable('ezcontentobject_link')
1846
            )->set(
1847
                $this->dbHandler->quoteColumn('relation_type'),
1848
                $query->expr->bitAnd(
1849
                    $this->dbHandler->quoteColumn('relation_type'),
1850
                    $query->bindValue(~$type, null, \PDO::PARAM_INT)
1851
                )
1852
            )->where(
1853
                $query->expr->eq(
1854
                    $this->dbHandler->quoteColumn('id'),
1855
                    $query->bindValue($relationId, null, \PDO::PARAM_INT)
1856
                )
1857
            );
1858
1859
            $query->prepare()->execute();
1860
        } else {
1861
            // No match, do nothing
1862
        }
1863
    }
1864
1865
    /**
1866
     * Returns all Content IDs for a given $contentTypeId.
1867
     *
1868
     * @param int $contentTypeId
1869
     *
1870
     * @return int[]
1871
     */
1872
    public function getContentIdsByContentTypeId($contentTypeId)
1873
    {
1874
        $query = $this->dbHandler->createSelectQuery();
1875
        $query
1876
            ->select($this->dbHandler->quoteColumn('id'))
1877
            ->from($this->dbHandler->quoteTable('ezcontentobject'))
1878
            ->where(
1879
                $query->expr->eq(
1880
                    $this->dbHandler->quoteColumn('contentclass_id'),
1881
                    $query->bindValue($contentTypeId, null, PDO::PARAM_INT)
1882
                )
1883
            );
1884
1885
        $statement = $query->prepare();
1886
        $statement->execute();
1887
1888
        return $statement->fetchAll(PDO::FETCH_COLUMN);
1889
    }
1890
1891
    /**
1892
     * Load name data for set of content id's and corresponding version number.
1893
     *
1894
     * @param array[] $rows array of hashes with 'id' and 'version' to load names for
1895
     *
1896
     * @return array
1897
     */
1898
    public function loadVersionedNameData($rows)
1899
    {
1900
        $query = $this->queryBuilder->createNamesQuery();
1901
        $conditions = array();
1902
        foreach ($rows as $row) {
1903
            $conditions[] = $query->expr->lAnd(
1904
                $query->expr->eq(
1905
                    $this->dbHandler->quoteColumn('contentobject_id'),
1906
                    $query->bindValue($row['id'], null, \PDO::PARAM_INT)
1907
                ),
1908
                $query->expr->eq(
1909
                    $this->dbHandler->quoteColumn('content_version'),
1910
                    $query->bindValue($row['version'], null, \PDO::PARAM_INT)
1911
                )
1912
            );
1913
        }
1914
1915
        $query->where($query->expr->lOr($conditions));
1916
        $stmt = $query->prepare();
1917
        $stmt->execute();
1918
1919
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
1920
    }
1921
1922
    /**
1923
     * Batch method for copying all relation meta data for copied Content object.
1924
     *
1925
     * {@inheritdoc}
1926
     *
1927
     * @param int $originalContentId
1928
     * @param int $copiedContentId
1929
     * @param int|null $versionNo If specified only copy for a given version number, otherwise all.
1930
     */
1931
    public function copyRelations($originalContentId, $copiedContentId, $versionNo = null)
1932
    {
1933
        // Given we can retain all columns, we just create copies with new `from_contentobject_id` using INSERT INTO SELECT
1934
        $sql = 'INSERT INTO ezcontentobject_link ( contentclassattribute_id, from_contentobject_id, from_contentobject_version, relation_type, to_contentobject_id )
1935
                SELECT  L2.contentclassattribute_id, :copied_id, L2.from_contentobject_version, L2.relation_type, L2.to_contentobject_id
1936
                FROM    ezcontentobject_link AS L2
1937
                WHERE   L2.from_contentobject_id = :original_id';
1938
1939
        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...
1940
            $stmt = $this->connection->prepare($sql . ' AND L2.from_contentobject_version = :version');
1941
            $stmt->bindValue('version', $versionNo, PDO::PARAM_INT);
1942
        } else {
1943
            $stmt = $this->connection->prepare($sql);
1944
        }
1945
1946
        $stmt->bindValue('original_id', $originalContentId, PDO::PARAM_INT);
1947
        $stmt->bindValue('copied_id', $copiedContentId, PDO::PARAM_INT);
1948
1949
        $stmt->execute();
1950
    }
1951
1952
    /**
1953
     * Remove the specified translation from the Content Object Version.
1954
     *
1955
     * @param int $contentId
1956
     * @param string $languageCode language code of the translation
1957
     * @throws \Doctrine\DBAL\DBALException
1958
     */
1959 View Code Duplication
    public function deleteTranslationFromContent($contentId, $languageCode)
1960
    {
1961
        $language = $this->languageHandler->loadByLanguageCode($languageCode);
1962
1963
        $this->connection->beginTransaction();
1964
        try {
1965
            $this->deleteTranslationFromContentVersions($contentId, $language->id);
1966
            $this->deleteTranslationFromContentNames($contentId, $languageCode);
1967
            $this->deleteTranslationFromContentObject($contentId, $language->id);
1968
1969
            $this->connection->commit();
1970
        } catch (DBALException $e) {
1971
            $this->connection->rollBack();
1972
            throw $e;
1973
        }
1974
    }
1975
1976
    /**
1977
     * Delete Content fields (attributes) for the given Translation.
1978
     * If $versionNo is given, fields for that Version only will be deleted.
1979
     *
1980
     * @param string $languageCode
1981
     * @param int $contentId
1982
     * @param int $versionNo (optional) filter by versionNo
1983
     */
1984 View Code Duplication
    public function deleteTranslatedFields($languageCode, $contentId, $versionNo = null)
1985
    {
1986
        $query = $this->connection->createQueryBuilder();
1987
        $query
1988
            ->delete('ezcontentobject_attribute')
1989
            ->where('contentobject_id = :contentId')
1990
            ->andWhere('language_code = :languageCode')
1991
            ->setParameters(
1992
                [
1993
                    ':contentId' => $contentId,
1994
                    ':languageCode' => $languageCode,
1995
                ]
1996
            )
1997
        ;
1998
1999
        if (null !== $versionNo) {
2000
            $query
2001
                ->andWhere('version = :versionNo')
2002
                ->setParameter(':versionNo', $versionNo)
2003
            ;
2004
        }
2005
2006
        $query->execute();
2007
    }
2008
2009
    /**
2010
     * Delete the specified Translation from the given Version.
2011
     *
2012
     * @param int $contentId
2013
     * @param int $versionNo
2014
     * @param string $languageCode
2015
     * @throws \Doctrine\DBAL\DBALException
2016
     */
2017 View Code Duplication
    public function deleteTranslationFromVersion($contentId, $versionNo, $languageCode)
2018
    {
2019
        $language = $this->languageHandler->loadByLanguageCode($languageCode);
2020
2021
        $this->connection->beginTransaction();
2022
        try {
2023
            $this->deleteTranslationFromContentVersions($contentId, $language->id, $versionNo);
2024
            $this->deleteTranslationFromContentNames($contentId, $languageCode, $versionNo);
2025
2026
            $this->connection->commit();
2027
        } catch (DBALException $e) {
2028
            $this->connection->rollBack();
2029
            throw $e;
2030
        }
2031
    }
2032
2033
    /**
2034
     * Delete translation from the ezcontentobject_name table.
2035
     *
2036
     * @param int $contentId
2037
     * @param string $languageCode
2038
     * @param int $versionNo optional, if specified, apply to this Version only.
2039
     */
2040 View Code Duplication
    private function deleteTranslationFromContentNames($contentId, $languageCode, $versionNo = null)
2041
    {
2042
        $query = $this->connection->createQueryBuilder();
2043
        $query
2044
            ->delete('ezcontentobject_name')
2045
            ->where('contentobject_id=:contentId')
2046
            ->andWhere('real_translation=:languageCode')
2047
            ->setParameters(
2048
                [
2049
                    ':languageCode' => $languageCode,
2050
                    ':contentId' => $contentId,
2051
                ]
2052
            )
2053
        ;
2054
2055
        if (null !== $versionNo) {
2056
            $query
2057
                ->andWhere('content_version = :versionNo')
2058
                ->setParameter(':versionNo', $versionNo)
2059
            ;
2060
        }
2061
2062
        $query->execute();
2063
    }
2064
2065
    /**
2066
     * Remove language from language_mask of ezcontentobject.
2067
     *
2068
     * @param int $contentId
2069
     * @param int $languageId
2070
     * @throws \eZ\Publish\Core\Base\Exceptions\BadStateException
2071
     */
2072
    private function deleteTranslationFromContentObject($contentId, $languageId)
2073
    {
2074
        $query = $this->connection->createQueryBuilder();
2075
        $query->update('ezcontentobject')
2076
            // parameter for bitwise operation has to be placed verbatim (w/o binding) for this to work cross-DBMS
2077
            ->set('language_mask', 'language_mask & ~ ' . $languageId)
2078
            ->set('modified', ':now')
2079
            ->where('id = :contentId')
2080
            ->andWhere(
2081
            // make sure removed translation is not the last one (incl. alwaysAvailable)
2082
                $query->expr()->andX(
2083
                    'language_mask & ~ ' . $languageId . ' <> 0',
2084
                    'language_mask & ~ ' . $languageId . ' <> 1'
2085
                )
2086
            )
2087
            ->setParameter(':now', time())
2088
            ->setParameter(':contentId', $contentId)
2089
        ;
2090
2091
        $rowCount = $query->execute();
2092
2093
        // no rows updated means that most likely somehow it was the last remaining translation
2094
        if ($rowCount === 0) {
2095
            throw new BadStateException(
2096
                '$languageCode',
2097
                'Specified translation is the only one Content Object Version has'
2098
            );
2099
        }
2100
    }
2101
2102
    /**
2103
     * Remove language from language_mask of ezcontentobject_version and update initialLanguageId
2104
     * if it matches the removed one.
2105
     *
2106
     * @param int $contentId
2107
     * @param int $languageId
2108
     * @param int $versionNo optional, if specified, apply to this Version only.
2109
     * @throws \eZ\Publish\Core\Base\Exceptions\BadStateException
2110
     */
2111
    private function deleteTranslationFromContentVersions($contentId, $languageId, $versionNo = null)
2112
    {
2113
        $query = $this->connection->createQueryBuilder();
2114
        $query->update('ezcontentobject_version')
2115
            // parameter for bitwise operation has to be placed verbatim (w/o binding) for this to work cross-DBMS
2116
            ->set('language_mask', 'language_mask & ~ ' . $languageId)
2117
            ->set('modified', ':now')
2118
            // update initial_language_id only if it matches removed translation languageId
2119
            ->set(
2120
                'initial_language_id',
2121
                'CASE WHEN initial_language_id = :languageId ' .
2122
                'THEN (SELECT initial_language_id AS main_language_id FROM ezcontentobject c WHERE c.id = :contentId) ' .
2123
                'ELSE initial_language_id END'
2124
            )
2125
            ->where('contentobject_id = :contentId')
2126
            ->andWhere(
2127
            // make sure removed translation is not the last one (incl. alwaysAvailable)
2128
                $query->expr()->andX(
2129
                    'language_mask & ~ ' . $languageId . ' <> 0',
2130
                    'language_mask & ~ ' . $languageId . ' <> 1'
2131
                )
2132
            )
2133
            ->setParameter(':now', time())
2134
            ->setParameter(':contentId', $contentId)
2135
            ->setParameter(':languageId', $languageId)
2136
        ;
2137
2138
        if (null !== $versionNo) {
2139
            $query
2140
                ->andWhere('version = :versionNo')
2141
                ->setParameter(':versionNo', $versionNo)
2142
            ;
2143
        }
2144
2145
        $rowCount = $query->execute();
2146
2147
        // no rows updated means that most likely somehow it was the last remaining translation
2148
        if ($rowCount === 0) {
2149
            throw new BadStateException(
2150
                '$languageCode',
2151
                'Specified translation is the only one Content Object Version has'
2152
            );
2153
        }
2154
    }
2155
}
2156