Completed
Push — master ( d9c656...9fc60c )
by André
53:37 queued 39:21
created

DoctrineDatabase::getLanguageQuery()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 39
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

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