Completed
Push — master ( 65ba07...f0ec2b )
by André
104:16 queued 82:47
created

deleteTranslationFromContentAttributes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 10

Duplication

Lines 17
Ratio 100 %

Importance

Changes 0
Metric Value
dl 17
loc 17
c 0
b 0
f 0
cc 1
eloc 10
nc 1
nop 2
rs 9.4285
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
            $q->bindValue($language->id, null, \PDO::PARAM_INT)
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->prepare()->execute();
1540
    }
1541
1542
    /**
1543
     * Deletes the actual content object referred to by $contentId.
1544
     *
1545
     * @param int $contentId
1546
     */
1547
    public function deleteContent($contentId)
1548
    {
1549
        $query = $this->dbHandler->createDeleteQuery();
1550
        $query->deleteFrom('ezcontentobject')
1551
            ->where(
1552
                $query->expr->eq(
1553
                    $this->dbHandler->quoteColumn('id'),
1554
                    $query->bindValue($contentId, null, \PDO::PARAM_INT)
1555
                )
1556
            );
1557
1558
        $query->prepare()->execute();
1559
    }
1560
1561
    /**
1562
     * Loads relations from $contentId to published content, optionally only from $contentVersionNo.
1563
     *
1564
     * $relationType can also be filtered.
1565
     *
1566
     * @param int $contentId
1567
     * @param int $contentVersionNo
1568
     * @param int $relationType
1569
     *
1570
     * @return string[][] array of relation data
1571
     */
1572
    public function loadRelations($contentId, $contentVersionNo = null, $relationType = null)
1573
    {
1574
        $query = $this->queryBuilder->createRelationFindQuery();
1575
        $query->innerJoin(
1576
            $query->alias(
1577
                $this->dbHandler->quoteTable('ezcontentobject'),
1578
                'ezcontentobject_to'
1579
            ),
1580
            $query->expr->lAnd(
1581
                $query->expr->eq(
1582
                    $this->dbHandler->quoteColumn('to_contentobject_id', 'ezcontentobject_link'),
1583
                    $this->dbHandler->quoteColumn('id', 'ezcontentobject_to')
1584
                ),
1585
                $query->expr->eq(
1586
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject_to'),
1587
                    $query->bindValue(1, null, \PDO::PARAM_INT)
1588
                )
1589
            )
1590
        )->where(
1591
            $query->expr->eq(
1592
                $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link'),
1593
                $query->bindValue($contentId, null, \PDO::PARAM_INT)
1594
            )
1595
        );
1596
1597
        // source version number
1598
        if (isset($contentVersionNo)) {
1599
            $query->where(
1600
                $query->expr->eq(
1601
                    $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link'),
1602
                    $query->bindValue($contentVersionNo, null, \PDO::PARAM_INT)
1603
                )
1604
            );
1605
        } else { // from published version only
1606
            $query->from(
1607
                $this->dbHandler->quoteTable('ezcontentobject')
1608
            )->where(
1609
                $query->expr->lAnd(
1610
                    $query->expr->eq(
1611
                        $this->dbHandler->quoteColumn('id', 'ezcontentobject'),
1612
                        $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link')
1613
                    ),
1614
                    $query->expr->eq(
1615
                        $this->dbHandler->quoteColumn('current_version', 'ezcontentobject'),
1616
                        $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link')
1617
                    )
1618
                )
1619
            );
1620
        }
1621
1622
        // relation type
1623 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...
1624
            $query->where(
1625
                $query->expr->gt(
1626
                    $query->expr->bitAnd(
1627
                        $this->dbHandler->quoteColumn('relation_type', 'ezcontentobject_link'),
1628
                        $query->bindValue($relationType, null, \PDO::PARAM_INT)
1629
                    ),
1630
                    0
1631
                )
1632
            );
1633
        }
1634
1635
        $statement = $query->prepare();
1636
        $statement->execute();
1637
1638
        return $statement->fetchAll(\PDO::FETCH_ASSOC);
1639
    }
1640
1641
    /**
1642
     * Loads data that related to $toContentId.
1643
     *
1644
     * @param int $toContentId
1645
     * @param int $relationType
1646
     *
1647
     * @return mixed[][] Content data, array structured like {@see \eZ\Publish\Core\Persistence\Legacy\Content\Gateway::load()}
1648
     */
1649
    public function loadReverseRelations($toContentId, $relationType = null)
1650
    {
1651
        $query = $this->queryBuilder->createRelationFindQuery();
1652
        $query->where(
1653
            $query->expr->eq(
1654
                $this->dbHandler->quoteColumn('to_contentobject_id', 'ezcontentobject_link'),
1655
                $query->bindValue($toContentId, null, \PDO::PARAM_INT)
1656
            )
1657
        );
1658
1659
        // ezcontentobject join
1660
        $query->from(
1661
            $this->dbHandler->quoteTable('ezcontentobject')
1662
        )->where(
1663
            $query->expr->lAnd(
1664
                $query->expr->eq(
1665
                    $this->dbHandler->quoteColumn('id', 'ezcontentobject'),
1666
                    $this->dbHandler->quoteColumn('from_contentobject_id', 'ezcontentobject_link')
1667
                ),
1668
                $query->expr->eq(
1669
                    $this->dbHandler->quoteColumn('current_version', 'ezcontentobject'),
1670
                    $this->dbHandler->quoteColumn('from_contentobject_version', 'ezcontentobject_link')
1671
                ),
1672
                $query->expr->eq(
1673
                    $this->dbHandler->quoteColumn('status', 'ezcontentobject'),
1674
                    $query->bindValue(1, null, \PDO::PARAM_INT)
1675
                )
1676
            )
1677
        );
1678
1679
        // relation type
1680 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...
1681
            $query->where(
1682
                $query->expr->gt(
1683
                    $query->expr->bitAnd(
1684
                        $this->dbHandler->quoteColumn('relation_type', 'ezcontentobject_link'),
1685
                        $query->bindValue($relationType, null, \PDO::PARAM_INT)
1686
                    ),
1687
                    0
1688
                )
1689
            );
1690
        }
1691
1692
        $statement = $query->prepare();
1693
1694
        $statement->execute();
1695
1696
        return $statement->fetchAll(\PDO::FETCH_ASSOC);
1697
    }
1698
1699
    /**
1700
     * Inserts a new relation database record.
1701
     *
1702
     * @param \eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct $createStruct
1703
     *
1704
     * @return int ID the inserted ID
1705
     */
1706 View Code Duplication
    public function insertRelation(RelationCreateStruct $createStruct)
1707
    {
1708
        $q = $this->dbHandler->createInsertQuery();
1709
        $q->insertInto(
1710
            $this->dbHandler->quoteTable('ezcontentobject_link')
1711
        )->set(
1712
            $this->dbHandler->quoteColumn('id'),
1713
            $this->dbHandler->getAutoIncrementValue('ezcontentobject_link', 'id')
1714
        )->set(
1715
            $this->dbHandler->quoteColumn('contentclassattribute_id'),
1716
            $q->bindValue((int)$createStruct->sourceFieldDefinitionId, null, \PDO::PARAM_INT)
1717
        )->set(
1718
            $this->dbHandler->quoteColumn('from_contentobject_id'),
1719
            $q->bindValue($createStruct->sourceContentId, null, \PDO::PARAM_INT)
1720
        )->set(
1721
            $this->dbHandler->quoteColumn('from_contentobject_version'),
1722
            $q->bindValue($createStruct->sourceContentVersionNo, null, \PDO::PARAM_INT)
1723
        )->set(
1724
            $this->dbHandler->quoteColumn('relation_type'),
1725
            $q->bindValue($createStruct->type, null, \PDO::PARAM_INT)
1726
        )->set(
1727
            $this->dbHandler->quoteColumn('to_contentobject_id'),
1728
            $q->bindValue($createStruct->destinationContentId, null, \PDO::PARAM_INT)
1729
        );
1730
1731
        $q->prepare()->execute();
1732
1733
        return $this->dbHandler->lastInsertId(
1734
            $this->dbHandler->getSequenceName('ezcontentobject_link', 'id')
1735
        );
1736
    }
1737
1738
    /**
1739
     * Deletes the relation with the given $relationId.
1740
     *
1741
     * @param int $relationId
1742
     * @param int $type {@see \eZ\Publish\API\Repository\Values\Content\Relation::COMMON,
1743
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::EMBED,
1744
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::LINK,
1745
     *                 \eZ\Publish\API\Repository\Values\Content\Relation::FIELD}
1746
     */
1747
    public function deleteRelation($relationId, $type)
1748
    {
1749
        // Legacy Storage stores COMMON, LINK and EMBED types using bitmask, therefore first load
1750
        // existing relation type by given $relationId for comparison
1751
        /** @var $query \eZ\Publish\Core\Persistence\Database\SelectQuery */
1752
        $query = $this->dbHandler->createSelectQuery();
1753
        $query->select(
1754
            $this->dbHandler->quoteColumn('relation_type')
1755
        )->from(
1756
            $this->dbHandler->quoteTable('ezcontentobject_link')
1757
        )->where(
1758
            $query->expr->eq(
1759
                $this->dbHandler->quoteColumn('id'),
1760
                $query->bindValue($relationId, null, \PDO::PARAM_INT)
1761
            )
1762
        );
1763
1764
        $statement = $query->prepare();
1765
        $statement->execute();
1766
        $loadedRelationType = $statement->fetchColumn();
1767
1768
        if (!$loadedRelationType) {
1769
            return;
1770
        }
1771
1772
        // If relation type matches then delete
1773
        if ($loadedRelationType == $type) {
1774
            /** @var $query \eZ\Publish\Core\Persistence\Database\DeleteQuery */
1775
            $query = $this->dbHandler->createDeleteQuery();
1776
            $query->deleteFrom(
1777
                'ezcontentobject_link'
1778
            )->where(
1779
                $query->expr->eq(
1780
                    $this->dbHandler->quoteColumn('id'),
1781
                    $query->bindValue($relationId, null, \PDO::PARAM_INT)
1782
                )
1783
            );
1784
1785
            $query->prepare()->execute();
1786
        } elseif ($loadedRelationType & $type) { // If relation type is composite update bitmask
1787
            /** @var $query \eZ\Publish\Core\Persistence\Database\UpdateQuery */
1788
            $query = $this->dbHandler->createUpdateQuery();
1789
            $query->update(
1790
                $this->dbHandler->quoteTable('ezcontentobject_link')
1791
            )->set(
1792
                $this->dbHandler->quoteColumn('relation_type'),
1793
                $query->expr->bitAnd(
1794
                    $this->dbHandler->quoteColumn('relation_type'),
1795
                    $query->bindValue(~$type, null, \PDO::PARAM_INT)
1796
                )
1797
            )->where(
1798
                $query->expr->eq(
1799
                    $this->dbHandler->quoteColumn('id'),
1800
                    $query->bindValue($relationId, null, \PDO::PARAM_INT)
1801
                )
1802
            );
1803
1804
            $query->prepare()->execute();
1805
        } else {
1806
            // No match, do nothing
1807
        }
1808
    }
1809
1810
    /**
1811
     * Returns all Content IDs for a given $contentTypeId.
1812
     *
1813
     * @param int $contentTypeId
1814
     *
1815
     * @return int[]
1816
     */
1817
    public function getContentIdsByContentTypeId($contentTypeId)
1818
    {
1819
        $query = $this->dbHandler->createSelectQuery();
1820
        $query
1821
            ->select($this->dbHandler->quoteColumn('id'))
1822
            ->from($this->dbHandler->quoteTable('ezcontentobject'))
1823
            ->where(
1824
                $query->expr->eq(
1825
                    $this->dbHandler->quoteColumn('contentclass_id'),
1826
                    $query->bindValue($contentTypeId, null, PDO::PARAM_INT)
1827
                )
1828
            );
1829
1830
        $statement = $query->prepare();
1831
        $statement->execute();
1832
1833
        return $statement->fetchAll(PDO::FETCH_COLUMN);
1834
    }
1835
1836
    /**
1837
     * Load name data for set of content id's and corresponding version number.
1838
     *
1839
     * @param array[] $rows array of hashes with 'id' and 'version' to load names for
1840
     *
1841
     * @return array
1842
     */
1843
    public function loadVersionedNameData($rows)
1844
    {
1845
        $query = $this->queryBuilder->createNamesQuery();
1846
        $conditions = array();
1847
        foreach ($rows as $row) {
1848
            $conditions[] = $query->expr->lAnd(
1849
                $query->expr->eq(
1850
                    $this->dbHandler->quoteColumn('contentobject_id'),
1851
                    $query->bindValue($row['id'], null, \PDO::PARAM_INT)
1852
                ),
1853
                $query->expr->eq(
1854
                    $this->dbHandler->quoteColumn('content_version'),
1855
                    $query->bindValue($row['version'], null, \PDO::PARAM_INT)
1856
                )
1857
            );
1858
        }
1859
1860
        $query->where($query->expr->lOr($conditions));
1861
        $stmt = $query->prepare();
1862
        $stmt->execute();
1863
1864
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
1865
    }
1866
1867
    /**
1868
     * Batch method for copying all relation meta data for copied Content object.
1869
     *
1870
     * {@inheritdoc}
1871
     *
1872
     * @param int $originalContentId
1873
     * @param int $copiedContentId
1874
     * @param int|null $versionNo If specified only copy for a given version number, otherwise all.
1875
     */
1876
    public function copyRelations($originalContentId, $copiedContentId, $versionNo = null)
1877
    {
1878
        // Given we can retain all columns, we just create copies with new `from_contentobject_id` using INSERT INTO SELECT
1879
        $sql = 'INSERT INTO ezcontentobject_link ( contentclassattribute_id, from_contentobject_id, from_contentobject_version, relation_type, to_contentobject_id )
1880
                SELECT  L2.contentclassattribute_id, :copied_id, L2.from_contentobject_version, L2.relation_type, L2.to_contentobject_id
1881
                FROM    ezcontentobject_link AS L2
1882
                WHERE   L2.from_contentobject_id = :original_id';
1883
1884
        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...
1885
            $stmt = $this->connection->prepare($sql . ' AND L2.from_contentobject_version = :version');
1886
            $stmt->bindValue('version', $versionNo, PDO::PARAM_INT);
1887
        } else {
1888
            $stmt = $this->connection->prepare($sql);
1889
        }
1890
1891
        $stmt->bindValue('original_id', $originalContentId, PDO::PARAM_INT);
1892
        $stmt->bindValue('copied_id', $copiedContentId, PDO::PARAM_INT);
1893
1894
        $stmt->execute();
1895
    }
1896
1897
    /**
1898
     * Remove the specified translation from the Content Object Version.
1899
     *
1900
     * @param int $contentId
1901
     * @param string $languageCode language code of the translation
1902
     * @throws \Doctrine\DBAL\DBALException
1903
     */
1904
    public function removeTranslationFromContent($contentId, $languageCode)
1905
    {
1906
        $language = $this->languageHandler->loadByLanguageCode($languageCode);
1907
1908
        $this->connection->beginTransaction();
1909
        try {
1910
            $this->deleteTranslationFromContentVersions($contentId, $language->id);
1911
            $this->deleteTranslationFromContentObject($contentId, $language->id);
1912
1913
            $this->deleteTranslationFromContentAttributes($contentId, $languageCode);
1914
            $this->deleteTranslationFromContentNames($contentId, $languageCode);
1915
1916
            $this->connection->commit();
1917
        } catch (DBALException $e) {
1918
            $this->connection->rollBack();
1919
            throw $e;
1920
        }
1921
    }
1922
1923
    /**
1924
     * Delete translation from the ezcontentobject_attribute table.
1925
     *
1926
     * @param int $contentId
1927
     * @param string $languageCode
1928
     */
1929 View Code Duplication
    private function deleteTranslationFromContentAttributes($contentId, $languageCode)
1930
    {
1931
        $query = $this->connection->createQueryBuilder();
1932
        $query
1933
            ->delete('ezcontentobject_attribute')
1934
            ->where('contentobject_id = :contentId')
1935
            ->andWhere('language_code = :languageCode')
1936
            ->setParameters(
1937
                [
1938
                    ':contentId' => $contentId,
1939
                    ':languageCode' => $languageCode,
1940
                ]
1941
            )
1942
        ;
1943
1944
        $query->execute();
1945
    }
1946
1947
    /**
1948
     * Delete translation from the ezcontentobject_name table.
1949
     *
1950
     * @param $contentId
1951
     * @param $languageCode
1952
     */
1953 View Code Duplication
    private function deleteTranslationFromContentNames($contentId, $languageCode)
1954
    {
1955
        $query = $this->connection->createQueryBuilder();
1956
        $query
1957
            ->delete('ezcontentobject_name')
1958
            ->where('contentobject_id=:contentId')
1959
            ->andWhere('real_translation=:languageCode')
1960
            ->setParameters(
1961
                [
1962
                    ':languageCode' => $languageCode,
1963
                    ':contentId' => $contentId,
1964
                ]
1965
            )
1966
        ;
1967
1968
        $query->execute();
1969
    }
1970
1971
    /**
1972
     * Remove language from language_mask of ezcontentobject.
1973
     *
1974
     * @param int $contentId
1975
     * @param int $languageId
1976
     * @throws \eZ\Publish\Core\Base\Exceptions\BadStateException
1977
     */
1978
    private function deleteTranslationFromContentObject($contentId, $languageId)
1979
    {
1980
        $query = $this->connection->createQueryBuilder();
1981
        $query->update('ezcontentobject')
1982
            // parameter for bitwise operation has to be placed verbatim (w/o binding) for this to work cross-DBMS
1983
            ->set('language_mask', 'language_mask & ~ ' . $languageId)
1984
            ->set('modified', ':now')
1985
            ->where('id = :contentId')
1986
            ->andWhere(
1987
            // make sure removed translation is not the last one (incl. alwaysAvailable)
1988
                $query->expr()->orX(
1989
                    'language_mask & ~ ' . $languageId . ' <> 0',
1990
                    'language_mask & ~ ' . $languageId . ' <> 1'
1991
                )
1992
            )
1993
            ->setParameter(':now', time())
1994
            ->setParameter(':contentId', $contentId)
1995
        ;
1996
1997
        $rowCount = $query->execute();
1998
1999
        // no rows updated means that most likely somehow it was the last remaining translation
2000
        if ($rowCount === 0) {
2001
            throw new BadStateException(
2002
                '$languageCode',
2003
                'Specified translation is the only one Content Object Version has'
2004
            );
2005
        }
2006
    }
2007
2008
    /**
2009
     * Remove language from language_mask of ezcontentobject_version and update initialLanguageId
2010
     * if it matches the removed one.
2011
     *
2012
     * @param int $contentId
2013
     * @param int $languageId
2014
     * @throws \eZ\Publish\Core\Base\Exceptions\BadStateException
2015
     */
2016
    private function deleteTranslationFromContentVersions($contentId, $languageId)
2017
    {
2018
        $query = $this->connection->createQueryBuilder();
2019
        $query->update('ezcontentobject_version')
2020
            // parameter for bitwise operation has to be placed verbatim (w/o binding) for this to work cross-DBMS
2021
            ->set('language_mask', 'language_mask & ~ ' . $languageId)
2022
            ->set('modified', ':now')
2023
            // update initial_language_id only if it matches removed translation languageId
2024
            ->set(
2025
                'initial_language_id',
2026
                'CASE WHEN initial_language_id = :languageId ' .
2027
                'THEN (SELECT initial_language_id AS main_language_id FROM ezcontentobject c WHERE c.id = :contentId) ' .
2028
                'ELSE initial_language_id END'
2029
            )
2030
            ->where('contentobject_id = :contentId')
2031
            ->andWhere(
2032
            // make sure removed translation is not the last one (incl. alwaysAvailable)
2033
                $query->expr()->orX(
2034
                    'language_mask & ~ ' . $languageId . ' <> 0',
2035
                    'language_mask & ~ ' . $languageId . ' <> 1'
2036
                )
2037
            )
2038
            ->setParameter(':now', time())
2039
            ->setParameter(':contentId', $contentId)
2040
            ->setParameter(':languageId', $languageId)
2041
        ;
2042
2043
        $rowCount = $query->execute();
2044
2045
        // no rows updated means that most likely somehow it was the last remaining translation
2046
        if ($rowCount === 0) {
2047
            throw new BadStateException(
2048
                '$languageCode',
2049
                'Specified translation is the only one Content Object Version has'
2050
            );
2051
        }
2052
    }
2053
}
2054