Completed
Push — ezp_30827 ( 809fcf...031a3c )
by
unknown
60:02 queued 46:04
created

ContentService::loadContentDraftList()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 3
nop 3
dl 0
loc 32
rs 9.0968
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * File containing the eZ\Publish\Core\Repository\ContentService 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\Repository;
10
11
use eZ\Publish\API\Repository\ContentService as ContentServiceInterface;
12
use eZ\Publish\API\Repository\PermissionResolver;
13
use eZ\Publish\API\Repository\Repository as RepositoryInterface;
14
use eZ\Publish\Core\FieldType\FieldTypeRegistry;
15
use eZ\Publish\API\Repository\Values\Content\ContentDraftList;
16
use eZ\Publish\API\Repository\Values\Content\DraftList\Item\ContentDraftListItem;
17
use eZ\Publish\API\Repository\Values\Content\DraftList\Item\UnauthorizedContentDraftListItem;
18
use eZ\Publish\API\Repository\Values\User\UserReference;
19
use eZ\Publish\Core\Repository\Values\Content\Location;
20
use eZ\Publish\API\Repository\Values\Content\Language;
21
use eZ\Publish\SPI\Persistence\Handler;
22
use eZ\Publish\API\Repository\Values\Content\ContentUpdateStruct as APIContentUpdateStruct;
23
use eZ\Publish\API\Repository\Values\ContentType\ContentType;
24
use eZ\Publish\API\Repository\Values\Content\ContentCreateStruct as APIContentCreateStruct;
25
use eZ\Publish\API\Repository\Values\Content\ContentMetadataUpdateStruct;
26
use eZ\Publish\API\Repository\Values\Content\Content as APIContent;
27
use eZ\Publish\API\Repository\Values\Content\VersionInfo as APIVersionInfo;
28
use eZ\Publish\API\Repository\Values\Content\ContentInfo;
29
use eZ\Publish\API\Repository\Values\User\User;
30
use eZ\Publish\API\Repository\Values\Content\LocationCreateStruct;
31
use eZ\Publish\API\Repository\Values\Content\Field;
32
use eZ\Publish\API\Repository\Values\Content\Relation as APIRelation;
33
use eZ\Publish\API\Repository\Exceptions\NotFoundException as APINotFoundException;
34
use eZ\Publish\Core\Base\Exceptions\BadStateException;
35
use eZ\Publish\Core\Base\Exceptions\NotFoundException;
36
use eZ\Publish\Core\Base\Exceptions\InvalidArgumentException;
37
use eZ\Publish\Core\Base\Exceptions\ContentValidationException;
38
use eZ\Publish\Core\Base\Exceptions\ContentFieldValidationException;
39
use eZ\Publish\Core\Base\Exceptions\UnauthorizedException;
40
use eZ\Publish\Core\FieldType\ValidationError;
41
use eZ\Publish\Core\Repository\Values\Content\VersionInfo;
42
use eZ\Publish\Core\Repository\Values\Content\ContentCreateStruct;
43
use eZ\Publish\Core\Repository\Values\Content\ContentUpdateStruct;
44
use eZ\Publish\SPI\Limitation\Target;
45
use eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct as SPIMetadataUpdateStruct;
46
use eZ\Publish\SPI\Persistence\Content\CreateStruct as SPIContentCreateStruct;
47
use eZ\Publish\SPI\Persistence\Content\UpdateStruct as SPIContentUpdateStruct;
48
use eZ\Publish\SPI\Persistence\Content\Field as SPIField;
49
use eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct as SPIRelationCreateStruct;
50
use Exception;
51
52
/**
53
 * This class provides service methods for managing content.
54
 *
55
 * @example Examples/content.php
56
 */
57
class ContentService implements ContentServiceInterface
58
{
59
    /** @var \eZ\Publish\Core\Repository\Repository */
60
    protected $repository;
61
62
    /** @var \eZ\Publish\SPI\Persistence\Handler */
63
    protected $persistenceHandler;
64
65
    /** @var array */
66
    protected $settings;
67
68
    /** @var \eZ\Publish\Core\Repository\Helper\DomainMapper */
69
    protected $domainMapper;
70
71
    /** @var \eZ\Publish\Core\Repository\Helper\RelationProcessor */
72
    protected $relationProcessor;
73
74
    /** @var \eZ\Publish\Core\Repository\Helper\NameSchemaService */
75
    protected $nameSchemaService;
76
77
    /** @var \eZ\Publish\Core\FieldType\FieldTypeRegistry */
78
    protected $fieldTypeRegistry;
79
80
    /** @var \eZ\Publish\API\Repository\PermissionResolver */
81
    private $permissionResolver;
82
83
    public function __construct(
84
        RepositoryInterface $repository,
85
        Handler $handler,
86
        Helper\DomainMapper $domainMapper,
87
        Helper\RelationProcessor $relationProcessor,
88
        Helper\NameSchemaService $nameSchemaService,
89
        FieldTypeRegistry $fieldTypeRegistry,
90
        PermissionResolver $permissionResolver,
91
        array $settings = []
92
    ) {
93
        $this->repository = $repository;
0 ignored issues
show
Documentation Bug introduced by
It seems like $repository of type object<eZ\Publish\API\Repository\Repository> is incompatible with the declared type object<eZ\Publish\Core\Repository\Repository> of property $repository.

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

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

Loading history...
94
        $this->persistenceHandler = $handler;
95
        $this->domainMapper = $domainMapper;
96
        $this->relationProcessor = $relationProcessor;
97
        $this->nameSchemaService = $nameSchemaService;
98
        $this->fieldTypeRegistry = $fieldTypeRegistry;
99
        // Union makes sure default settings are ignored if provided in argument
100
        $this->settings = $settings + [
101
            // Version archive limit (0-50), only enforced on publish, not on un-publish.
102
            'default_version_archive_limit' => 5,
103
        ];
104
        $this->permissionResolver = $permissionResolver;
105
    }
106
107
    /**
108
     * Loads a content info object.
109
     *
110
     * To load fields use loadContent
111
     *
112
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to read the content
113
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException - if the content with the given id does not exist
114
     *
115
     * @param int $contentId
116
     *
117
     * @return \eZ\Publish\API\Repository\Values\Content\ContentInfo
118
     */
119
    public function loadContentInfo($contentId)
120
    {
121
        $contentInfo = $this->internalLoadContentInfo($contentId);
122
        if (!$this->permissionResolver->canUser('content', 'read', $contentInfo)) {
123
            throw new UnauthorizedException('content', 'read', ['contentId' => $contentId]);
124
        }
125
126
        return $contentInfo;
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     */
132
    public function loadContentInfoList(array $contentIds): iterable
133
    {
134
        $contentInfoList = [];
135
        $spiInfoList = $this->persistenceHandler->contentHandler()->loadContentInfoList($contentIds);
136
        foreach ($spiInfoList as $id => $spiInfo) {
137
            $contentInfo = $this->domainMapper->buildContentInfoDomainObject($spiInfo);
138
            if ($this->permissionResolver->canUser('content', 'read', $contentInfo)) {
139
                $contentInfoList[$id] = $contentInfo;
140
            }
141
        }
142
143
        return $contentInfoList;
144
    }
145
146
    /**
147
     * Loads a content info object.
148
     *
149
     * To load fields use loadContent
150
     *
151
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException - if the content with the given id does not exist
152
     *
153
     * @param mixed $id
154
     * @param bool $isRemoteId
155
     *
156
     * @return \eZ\Publish\API\Repository\Values\Content\ContentInfo
157
     */
158
    public function internalLoadContentInfo($id, $isRemoteId = false)
159
    {
160
        try {
161
            $method = $isRemoteId ? 'loadContentInfoByRemoteId' : 'loadContentInfo';
162
163
            return $this->domainMapper->buildContentInfoDomainObject(
164
                $this->persistenceHandler->contentHandler()->$method($id)
165
            );
166
        } catch (APINotFoundException $e) {
167
            throw new NotFoundException(
168
                'Content',
169
                $id,
170
                $e
171
            );
172
        }
173
    }
174
175
    /**
176
     * Loads a content info object for the given remoteId.
177
     *
178
     * To load fields use loadContent
179
     *
180
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to read the content
181
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException - if the content with the given remote id does not exist
182
     *
183
     * @param string $remoteId
184
     *
185
     * @return \eZ\Publish\API\Repository\Values\Content\ContentInfo
186
     */
187
    public function loadContentInfoByRemoteId($remoteId)
188
    {
189
        $contentInfo = $this->internalLoadContentInfo($remoteId, true);
190
191
        if (!$this->permissionResolver->canUser('content', 'read', $contentInfo)) {
192
            throw new UnauthorizedException('content', 'read', ['remoteId' => $remoteId]);
193
        }
194
195
        return $contentInfo;
196
    }
197
198
    /**
199
     * Loads a version info of the given content object.
200
     *
201
     * If no version number is given, the method returns the current version
202
     *
203
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException - if the version with the given number does not exist
204
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to load this version
205
     *
206
     * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
207
     * @param int $versionNo the version number. If not given the current version is returned.
208
     *
209
     * @return \eZ\Publish\API\Repository\Values\Content\VersionInfo
210
     */
211
    public function loadVersionInfo(ContentInfo $contentInfo, $versionNo = null)
212
    {
213
        return $this->loadVersionInfoById($contentInfo->id, $versionNo);
214
    }
215
216
    /**
217
     * Loads a version info of the given content object id.
218
     *
219
     * If no version number is given, the method returns the current version
220
     *
221
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException - if the version with the given number does not exist
222
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to load this version
223
     *
224
     * @param mixed $contentId
225
     * @param int $versionNo the version number. If not given the current version is returned.
226
     *
227
     * @return \eZ\Publish\API\Repository\Values\Content\VersionInfo
228
     */
229
    public function loadVersionInfoById($contentId, $versionNo = null)
230
    {
231
        try {
232
            $spiVersionInfo = $this->persistenceHandler->contentHandler()->loadVersionInfo(
233
                $contentId,
234
                $versionNo
235
            );
236
        } catch (APINotFoundException $e) {
237
            throw new NotFoundException(
238
                'VersionInfo',
239
                [
240
                    'contentId' => $contentId,
241
                    'versionNo' => $versionNo,
242
                ],
243
                $e
244
            );
245
        }
246
247
        $versionInfo = $this->domainMapper->buildVersionInfoDomainObject($spiVersionInfo);
248
249
        if ($versionInfo->isPublished()) {
250
            $function = 'read';
251
        } else {
252
            $function = 'versionread';
253
        }
254
255
        if (!$this->permissionResolver->canUser('content', $function, $versionInfo)) {
256
            throw new UnauthorizedException('content', $function, ['contentId' => $contentId]);
257
        }
258
259
        return $versionInfo;
260
    }
261
262
    /**
263
     * {@inheritdoc}
264
     */
265
    public function loadContentByContentInfo(ContentInfo $contentInfo, array $languages = null, $versionNo = null, $useAlwaysAvailable = true)
266
    {
267
        // Change $useAlwaysAvailable to false to avoid contentInfo lookup if we know alwaysAvailable is disabled
268
        if ($useAlwaysAvailable && !$contentInfo->alwaysAvailable) {
269
            $useAlwaysAvailable = false;
270
        }
271
272
        return $this->loadContent(
273
            $contentInfo->id,
274
            $languages,
275
            $versionNo,// On purpose pass as-is and not use $contentInfo, to make sure to return actual current version on null
276
            $useAlwaysAvailable
277
        );
278
    }
279
280
    /**
281
     * {@inheritdoc}
282
     */
283
    public function loadContentByVersionInfo(APIVersionInfo $versionInfo, array $languages = null, $useAlwaysAvailable = true)
284
    {
285
        // Change $useAlwaysAvailable to false to avoid contentInfo lookup if we know alwaysAvailable is disabled
286
        if ($useAlwaysAvailable && !$versionInfo->getContentInfo()->alwaysAvailable) {
287
            $useAlwaysAvailable = false;
288
        }
289
290
        return $this->loadContent(
291
            $versionInfo->getContentInfo()->id,
292
            $languages,
293
            $versionInfo->versionNo,
294
            $useAlwaysAvailable
295
        );
296
    }
297
298
    /**
299
     * {@inheritdoc}
300
     */
301
    public function loadContent($contentId, array $languages = null, $versionNo = null, $useAlwaysAvailable = true)
302
    {
303
        $content = $this->internalLoadContent($contentId, $languages, $versionNo, false, $useAlwaysAvailable);
304
305
        if (!$this->permissionResolver->canUser('content', 'read', $content)) {
306
            throw new UnauthorizedException('content', 'read', ['contentId' => $contentId]);
307
        }
308
        if (
309
            !$content->getVersionInfo()->isPublished()
310
            && !$this->permissionResolver->canUser('content', 'versionread', $content)
311
        ) {
312
            throw new UnauthorizedException('content', 'versionread', ['contentId' => $contentId, 'versionNo' => $versionNo]);
313
        }
314
315
        return $content;
316
    }
317
318
    /**
319
     * Loads content in a version of the given content object.
320
     *
321
     * If no version number is given, the method returns the current version
322
     *
323
     * @internal
324
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException if the content or version with the given id and languages does not exist
325
     *
326
     * @param mixed $id
327
     * @param array|null $languages A language priority, filters returned fields and is used as prioritized language code on
328
     *                         returned value object. If not given all languages are returned.
329
     * @param int|null $versionNo the version number. If not given the current version is returned
330
     * @param bool $isRemoteId
331
     * @param bool $useAlwaysAvailable Add Main language to \$languages if true (default) and if alwaysAvailable is true
332
     *
333
     * @return \eZ\Publish\API\Repository\Values\Content\Content
334
     */
335
    public function internalLoadContent($id, array $languages = null, $versionNo = null, $isRemoteId = false, $useAlwaysAvailable = true)
336
    {
337
        try {
338
            // Get Content ID if lookup by remote ID
339
            if ($isRemoteId) {
340
                $spiContentInfo = $this->persistenceHandler->contentHandler()->loadContentInfoByRemoteId($id);
341
                $id = $spiContentInfo->id;
342
                // Set $isRemoteId to false as the next loads will be for content id now that we have it (for exception use now)
343
                $isRemoteId = false;
344
            }
345
346
            $loadLanguages = $languages;
347
            $alwaysAvailableLanguageCode = null;
348
            // Set main language on $languages filter if not empty (all) and $useAlwaysAvailable being true
349
            // @todo Move use always available logic to SPI load methods, like done in location handler in 7.x
350
            if (!empty($loadLanguages) && $useAlwaysAvailable) {
351
                if (!isset($spiContentInfo)) {
352
                    $spiContentInfo = $this->persistenceHandler->contentHandler()->loadContentInfo($id);
353
                }
354
355
                if ($spiContentInfo->alwaysAvailable) {
356
                    $loadLanguages[] = $alwaysAvailableLanguageCode = $spiContentInfo->mainLanguageCode;
357
                    $loadLanguages = array_unique($loadLanguages);
358
                }
359
            }
360
361
            $spiContent = $this->persistenceHandler->contentHandler()->load(
362
                $id,
363
                $versionNo,
364
                $loadLanguages
0 ignored issues
show
Bug introduced by
It seems like $loadLanguages defined by $languages on line 346 can also be of type array; however, eZ\Publish\SPI\Persistence\Content\Handler::load() does only seem to accept null|array<integer,string>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
365
            );
366
        } catch (APINotFoundException $e) {
367
            throw new NotFoundException(
368
                'Content',
369
                [
370
                    $isRemoteId ? 'remoteId' : 'id' => $id,
371
                    'languages' => $languages,
372
                    'versionNo' => $versionNo,
373
                ],
374
                $e
375
            );
376
        }
377
378
        return $this->domainMapper->buildContentDomainObject(
379
            $spiContent,
380
            $this->repository->getContentTypeService()->loadContentType(
381
                $spiContent->versionInfo->contentInfo->contentTypeId
382
            ),
383
            $languages ?? [],
384
            $alwaysAvailableLanguageCode
385
        );
386
    }
387
388
    /**
389
     * Loads content in a version for the content object reference by the given remote id.
390
     *
391
     * If no version is given, the method returns the current version
392
     *
393
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException - if the content or version with the given remote id does not exist
394
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException If the user has no access to read content and in case of un-published content: read versions
395
     *
396
     * @param string $remoteId
397
     * @param array $languages A language filter for fields. If not given all languages are returned
398
     * @param int $versionNo the version number. If not given the current version is returned
399
     * @param bool $useAlwaysAvailable Add Main language to \$languages if true (default) and if alwaysAvailable is true
400
     *
401
     * @return \eZ\Publish\API\Repository\Values\Content\Content
402
     */
403
    public function loadContentByRemoteId($remoteId, array $languages = null, $versionNo = null, $useAlwaysAvailable = true)
404
    {
405
        $content = $this->internalLoadContent($remoteId, $languages, $versionNo, true, $useAlwaysAvailable);
406
407
        if (!$this->permissionResolver->canUser('content', 'read', $content)) {
408
            throw new UnauthorizedException('content', 'read', ['remoteId' => $remoteId]);
409
        }
410
411
        if (
412
            !$content->getVersionInfo()->isPublished()
413
            && !$this->permissionResolver->canUser('content', 'versionread', $content)
414
        ) {
415
            throw new UnauthorizedException('content', 'versionread', ['remoteId' => $remoteId, 'versionNo' => $versionNo]);
416
        }
417
418
        return $content;
419
    }
420
421
    /**
422
     * Bulk-load Content items by the list of ContentInfo Value Objects.
423
     *
424
     * Note: it does not throw exceptions on load, just ignores erroneous Content item.
425
     * Moreover, since the method works on pre-loaded ContentInfo list, it is assumed that user is
426
     * allowed to access every Content on the list.
427
     *
428
     * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo[] $contentInfoList
429
     * @param string[] $languages A language priority, filters returned fields and is used as prioritized language code on
430
     *                            returned value object. If not given all languages are returned.
431
     * @param bool $useAlwaysAvailable Add Main language to \$languages if true (default) and if alwaysAvailable is true,
432
     *                                 unless all languages have been asked for.
433
     *
434
     * @return \eZ\Publish\API\Repository\Values\Content\Content[] list of Content items with Content Ids as keys
435
     */
436
    public function loadContentListByContentInfo(
437
        array $contentInfoList,
438
        array $languages = [],
439
        $useAlwaysAvailable = true
440
    ) {
441
        $loadAllLanguages = $languages === Language::ALL;
442
        $contentIds = [];
443
        $contentTypeIds = [];
444
        $translations = $languages;
445
        foreach ($contentInfoList as $contentInfo) {
446
            $contentIds[] = $contentInfo->id;
447
            $contentTypeIds[] = $contentInfo->contentTypeId;
448
            // Unless we are told to load all languages, we add main language to translations so they are loaded too
449
            // Might in some case load more languages then intended, but prioritised handling will pick right one
450
            if (!$loadAllLanguages && $useAlwaysAvailable && $contentInfo->alwaysAvailable) {
451
                $translations[] = $contentInfo->mainLanguageCode;
452
            }
453
        }
454
455
        $contentList = [];
456
        $translations = array_unique($translations);
457
        $spiContentList = $this->persistenceHandler->contentHandler()->loadContentList(
458
            $contentIds,
459
            $translations
460
        );
461
        $contentTypeList = $this->repository->getContentTypeService()->loadContentTypeList(
462
            array_unique($contentTypeIds),
463
            $languages
464
        );
465
        foreach ($spiContentList as $contentId => $spiContent) {
466
            $contentInfo = $spiContent->versionInfo->contentInfo;
467
            $contentList[$contentId] = $this->domainMapper->buildContentDomainObject(
468
                $spiContent,
469
                $contentTypeList[$contentInfo->contentTypeId],
470
                $languages,
471
                $contentInfo->alwaysAvailable ? $contentInfo->mainLanguageCode : null
472
            );
473
        }
474
475
        return $contentList;
476
    }
477
478
    /**
479
     * Creates a new content draft assigned to the authenticated user.
480
     *
481
     * If a different userId is given in $contentCreateStruct it is assigned to the given user
482
     * but this required special rights for the authenticated user
483
     * (this is useful for content staging where the transfer process does not
484
     * have to authenticate with the user which created the content object in the source server).
485
     * The user has to publish the draft if it should be visible.
486
     * In 4.x at least one location has to be provided in the location creation array.
487
     *
488
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to create the content in the given location
489
     * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if the provided remoteId exists in the system, required properties on
490
     *                                                                        struct are missing or invalid, or if multiple locations are under the
491
     *                                                                        same parent.
492
     * @throws \eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException if a field in the $contentCreateStruct is not valid,
493
     *                                                                               or if a required field is missing / set to an empty value.
494
     * @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException If field definition does not exist in the ContentType,
495
     *                                                                          or value is set for non-translatable field in language
496
     *                                                                          other than main.
497
     *
498
     * @param \eZ\Publish\API\Repository\Values\Content\ContentCreateStruct $contentCreateStruct
499
     * @param \eZ\Publish\API\Repository\Values\Content\LocationCreateStruct[] $locationCreateStructs For each location parent under which a location should be created for the content
500
     *
501
     * @return \eZ\Publish\API\Repository\Values\Content\Content - the newly created content draft
502
     */
503
    public function createContent(APIContentCreateStruct $contentCreateStruct, array $locationCreateStructs = [])
504
    {
505
        if ($contentCreateStruct->mainLanguageCode === null) {
506
            throw new InvalidArgumentException('$contentCreateStruct', "'mainLanguageCode' property must be set");
507
        }
508
509
        if ($contentCreateStruct->contentType === null) {
510
            throw new InvalidArgumentException('$contentCreateStruct', "'contentType' property must be set");
511
        }
512
513
        $contentCreateStruct = clone $contentCreateStruct;
514
515
        if ($contentCreateStruct->ownerId === null) {
516
            $contentCreateStruct->ownerId = $this->permissionResolver->getCurrentUserReference()->getUserId();
517
        }
518
519
        if ($contentCreateStruct->alwaysAvailable === null) {
520
            $contentCreateStruct->alwaysAvailable = $contentCreateStruct->contentType->defaultAlwaysAvailable ?: false;
521
        }
522
523
        $contentCreateStruct->contentType = $this->repository->getContentTypeService()->loadContentType(
524
            $contentCreateStruct->contentType->id
525
        );
526
527
        if (empty($contentCreateStruct->sectionId)) {
528
            if (isset($locationCreateStructs[0])) {
529
                $location = $this->repository->getLocationService()->loadLocation(
530
                    $locationCreateStructs[0]->parentLocationId
531
                );
532
                $contentCreateStruct->sectionId = $location->contentInfo->sectionId;
533
            } else {
534
                $contentCreateStruct->sectionId = 1;
535
            }
536
        }
537
538
        if (!$this->permissionResolver->canUser('content', 'create', $contentCreateStruct, $locationCreateStructs)) {
539
            throw new UnauthorizedException(
540
                'content',
541
                'create',
542
                [
543
                    'parentLocationId' => isset($locationCreateStructs[0]) ?
544
                            $locationCreateStructs[0]->parentLocationId :
545
                            null,
546
                    'sectionId' => $contentCreateStruct->sectionId,
547
                ]
548
            );
549
        }
550
551
        if (!empty($contentCreateStruct->remoteId)) {
552
            try {
553
                $this->loadContentByRemoteId($contentCreateStruct->remoteId);
554
555
                throw new InvalidArgumentException(
556
                    '$contentCreateStruct',
557
                    "Another content with remoteId '{$contentCreateStruct->remoteId}' exists"
558
                );
559
            } catch (APINotFoundException $e) {
560
                // Do nothing
561
            }
562
        } else {
563
            $contentCreateStruct->remoteId = $this->domainMapper->getUniqueHash($contentCreateStruct);
564
        }
565
566
        $spiLocationCreateStructs = $this->buildSPILocationCreateStructs($locationCreateStructs);
567
568
        $languageCodes = $this->getLanguageCodesForCreate($contentCreateStruct);
569
        $fields = $this->mapFieldsForCreate($contentCreateStruct);
570
571
        $fieldValues = [];
572
        $spiFields = [];
573
        $allFieldErrors = [];
574
        $inputRelations = [];
575
        $locationIdToContentIdMapping = [];
576
577
        foreach ($contentCreateStruct->contentType->getFieldDefinitions() as $fieldDefinition) {
578
            /** @var $fieldType \eZ\Publish\Core\FieldType\FieldType */
579
            $fieldType = $this->fieldTypeRegistry->getFieldType(
580
                $fieldDefinition->fieldTypeIdentifier
581
            );
582
583
            foreach ($languageCodes as $languageCode) {
584
                $isEmptyValue = false;
585
                $valueLanguageCode = $fieldDefinition->isTranslatable ? $languageCode : $contentCreateStruct->mainLanguageCode;
586
                $isLanguageMain = $languageCode === $contentCreateStruct->mainLanguageCode;
587
                if (isset($fields[$fieldDefinition->identifier][$valueLanguageCode])) {
588
                    $fieldValue = $fields[$fieldDefinition->identifier][$valueLanguageCode]->value;
589
                } else {
590
                    $fieldValue = $fieldDefinition->defaultValue;
591
                }
592
593
                $fieldValue = $fieldType->acceptValue($fieldValue);
594
595
                if ($fieldType->isEmptyValue($fieldValue)) {
596
                    $isEmptyValue = true;
597
                    if ($fieldDefinition->isRequired) {
598
                        $allFieldErrors[$fieldDefinition->id][$languageCode] = new ValidationError(
599
                            "Value for required field definition '%identifier%' with language '%languageCode%' is empty",
600
                            null,
601
                            ['%identifier%' => $fieldDefinition->identifier, '%languageCode%' => $languageCode],
602
                            'empty'
603
                        );
604
                    }
605
                } else {
606
                    $fieldErrors = $fieldType->validate(
607
                        $fieldDefinition,
608
                        $fieldValue
609
                    );
610
                    if (!empty($fieldErrors)) {
611
                        $allFieldErrors[$fieldDefinition->id][$languageCode] = $fieldErrors;
612
                    }
613
                }
614
615
                if (!empty($allFieldErrors)) {
616
                    continue;
617
                }
618
619
                $this->relationProcessor->appendFieldRelations(
620
                    $inputRelations,
621
                    $locationIdToContentIdMapping,
622
                    $fieldType,
623
                    $fieldValue,
624
                    $fieldDefinition->id
625
                );
626
                $fieldValues[$fieldDefinition->identifier][$languageCode] = $fieldValue;
627
628
                // Only non-empty value for: translatable field or in main language
629
                if (
630
                    (!$isEmptyValue && $fieldDefinition->isTranslatable) ||
631
                    (!$isEmptyValue && $isLanguageMain)
632
                ) {
633
                    $spiFields[] = new SPIField(
634
                        [
635
                            'id' => null,
636
                            'fieldDefinitionId' => $fieldDefinition->id,
637
                            'type' => $fieldDefinition->fieldTypeIdentifier,
638
                            'value' => $fieldType->toPersistenceValue($fieldValue),
639
                            'languageCode' => $languageCode,
640
                            'versionNo' => null,
641
                        ]
642
                    );
643
                }
644
            }
645
        }
646
647
        if (!empty($allFieldErrors)) {
648
            throw new ContentFieldValidationException($allFieldErrors);
649
        }
650
651
        $spiContentCreateStruct = new SPIContentCreateStruct(
652
            [
653
                'name' => $this->nameSchemaService->resolve(
654
                    $contentCreateStruct->contentType->nameSchema,
655
                    $contentCreateStruct->contentType,
656
                    $fieldValues,
657
                    $languageCodes
658
                ),
659
                'typeId' => $contentCreateStruct->contentType->id,
660
                'sectionId' => $contentCreateStruct->sectionId,
661
                'ownerId' => $contentCreateStruct->ownerId,
662
                'locations' => $spiLocationCreateStructs,
663
                'fields' => $spiFields,
664
                'alwaysAvailable' => $contentCreateStruct->alwaysAvailable,
665
                'remoteId' => $contentCreateStruct->remoteId,
666
                'modified' => isset($contentCreateStruct->modificationDate) ? $contentCreateStruct->modificationDate->getTimestamp() : time(),
667
                'initialLanguageId' => $this->persistenceHandler->contentLanguageHandler()->loadByLanguageCode(
668
                    $contentCreateStruct->mainLanguageCode
669
                )->id,
670
            ]
671
        );
672
673
        $defaultObjectStates = $this->getDefaultObjectStates();
674
675
        $this->repository->beginTransaction();
676
        try {
677
            $spiContent = $this->persistenceHandler->contentHandler()->create($spiContentCreateStruct);
678
            $this->relationProcessor->processFieldRelations(
679
                $inputRelations,
680
                $spiContent->versionInfo->contentInfo->id,
681
                $spiContent->versionInfo->versionNo,
682
                $contentCreateStruct->contentType
683
            );
684
685
            $objectStateHandler = $this->persistenceHandler->objectStateHandler();
686
            foreach ($defaultObjectStates as $objectStateGroupId => $objectState) {
687
                $objectStateHandler->setContentState(
688
                    $spiContent->versionInfo->contentInfo->id,
689
                    $objectStateGroupId,
690
                    $objectState->id
691
                );
692
            }
693
694
            $this->repository->commit();
695
        } catch (Exception $e) {
696
            $this->repository->rollback();
697
            throw $e;
698
        }
699
700
        return $this->domainMapper->buildContentDomainObject(
701
            $spiContent,
702
            $contentCreateStruct->contentType
703
        );
704
    }
705
706
    /**
707
     * Returns an array of default content states with content state group id as key.
708
     *
709
     * @return \eZ\Publish\SPI\Persistence\Content\ObjectState[]
710
     */
711
    protected function getDefaultObjectStates()
712
    {
713
        $defaultObjectStatesMap = [];
714
        $objectStateHandler = $this->persistenceHandler->objectStateHandler();
715
716
        foreach ($objectStateHandler->loadAllGroups() as $objectStateGroup) {
717
            foreach ($objectStateHandler->loadObjectStates($objectStateGroup->id) as $objectState) {
718
                // Only register the first object state which is the default one.
719
                $defaultObjectStatesMap[$objectStateGroup->id] = $objectState;
720
                break;
721
            }
722
        }
723
724
        return $defaultObjectStatesMap;
725
    }
726
727
    /**
728
     * Returns all language codes used in given $fields.
729
     *
730
     * @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException if no field value is set in main language
731
     *
732
     * @param \eZ\Publish\API\Repository\Values\Content\ContentCreateStruct $contentCreateStruct
733
     *
734
     * @return string[]
735
     */
736
    protected function getLanguageCodesForCreate(APIContentCreateStruct $contentCreateStruct)
737
    {
738
        $languageCodes = [];
739
740
        foreach ($contentCreateStruct->fields as $field) {
741
            if ($field->languageCode === null || isset($languageCodes[$field->languageCode])) {
742
                continue;
743
            }
744
745
            $this->persistenceHandler->contentLanguageHandler()->loadByLanguageCode(
746
                $field->languageCode
747
            );
748
            $languageCodes[$field->languageCode] = true;
749
        }
750
751
        if (!isset($languageCodes[$contentCreateStruct->mainLanguageCode])) {
752
            $this->persistenceHandler->contentLanguageHandler()->loadByLanguageCode(
753
                $contentCreateStruct->mainLanguageCode
754
            );
755
            $languageCodes[$contentCreateStruct->mainLanguageCode] = true;
756
        }
757
758
        return array_keys($languageCodes);
759
    }
760
761
    /**
762
     * Returns an array of fields like $fields[$field->fieldDefIdentifier][$field->languageCode].
763
     *
764
     * @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException If field definition does not exist in the ContentType
765
     *                                                                          or value is set for non-translatable field in language
766
     *                                                                          other than main
767
     *
768
     * @param \eZ\Publish\API\Repository\Values\Content\ContentCreateStruct $contentCreateStruct
769
     *
770
     * @return array
771
     */
772
    protected function mapFieldsForCreate(APIContentCreateStruct $contentCreateStruct)
773
    {
774
        $fields = [];
775
776
        foreach ($contentCreateStruct->fields as $field) {
777
            $fieldDefinition = $contentCreateStruct->contentType->getFieldDefinition($field->fieldDefIdentifier);
778
779
            if ($fieldDefinition === null) {
780
                throw new ContentValidationException(
781
                    "Field definition '%identifier%' does not exist in given ContentType",
782
                    ['%identifier%' => $field->fieldDefIdentifier]
783
                );
784
            }
785
786
            if ($field->languageCode === null) {
787
                $field = $this->cloneField(
788
                    $field,
789
                    ['languageCode' => $contentCreateStruct->mainLanguageCode]
790
                );
791
            }
792
793
            if (!$fieldDefinition->isTranslatable && ($field->languageCode != $contentCreateStruct->mainLanguageCode)) {
794
                throw new ContentValidationException(
795
                    "A value is set for non translatable field definition '%identifier%' with language '%languageCode%'",
796
                    ['%identifier%' => $field->fieldDefIdentifier, '%languageCode%' => $field->languageCode]
797
                );
798
            }
799
800
            $fields[$field->fieldDefIdentifier][$field->languageCode] = $field;
801
        }
802
803
        return $fields;
804
    }
805
806
    /**
807
     * Clones $field with overriding specific properties from given $overrides array.
808
     *
809
     * @param Field $field
810
     * @param array $overrides
811
     *
812
     * @return Field
813
     */
814
    private function cloneField(Field $field, array $overrides = [])
815
    {
816
        $fieldData = array_merge(
817
            [
818
                'id' => $field->id,
819
                'value' => $field->value,
820
                'languageCode' => $field->languageCode,
821
                'fieldDefIdentifier' => $field->fieldDefIdentifier,
822
                'fieldTypeIdentifier' => $field->fieldTypeIdentifier,
823
            ],
824
            $overrides
825
        );
826
827
        return new Field($fieldData);
828
    }
829
830
    /**
831
     * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
832
     *
833
     * @param \eZ\Publish\API\Repository\Values\Content\LocationCreateStruct[] $locationCreateStructs
834
     *
835
     * @return \eZ\Publish\SPI\Persistence\Content\Location\CreateStruct[]
836
     */
837
    protected function buildSPILocationCreateStructs(array $locationCreateStructs)
838
    {
839
        $spiLocationCreateStructs = [];
840
        $parentLocationIdSet = [];
841
        $mainLocation = true;
842
843
        foreach ($locationCreateStructs as $locationCreateStruct) {
844
            if (isset($parentLocationIdSet[$locationCreateStruct->parentLocationId])) {
845
                throw new InvalidArgumentException(
846
                    '$locationCreateStructs',
847
                    "Multiple LocationCreateStructs with the same parent Location '{$locationCreateStruct->parentLocationId}' are given"
848
                );
849
            }
850
851
            if (!array_key_exists($locationCreateStruct->sortField, Location::SORT_FIELD_MAP)) {
852
                $locationCreateStruct->sortField = Location::SORT_FIELD_NAME;
853
            }
854
855
            if (!array_key_exists($locationCreateStruct->sortOrder, Location::SORT_ORDER_MAP)) {
856
                $locationCreateStruct->sortOrder = Location::SORT_ORDER_ASC;
857
            }
858
859
            $parentLocationIdSet[$locationCreateStruct->parentLocationId] = true;
860
            $parentLocation = $this->repository->getLocationService()->loadLocation(
861
                $locationCreateStruct->parentLocationId
862
            );
863
864
            $spiLocationCreateStructs[] = $this->domainMapper->buildSPILocationCreateStruct(
865
                $locationCreateStruct,
866
                $parentLocation,
867
                $mainLocation,
868
                // For Content draft contentId and contentVersionNo are set in ContentHandler upon draft creation
869
                null,
870
                null
871
            );
872
873
            // First Location in the list will be created as main Location
874
            $mainLocation = false;
875
        }
876
877
        return $spiLocationCreateStructs;
878
    }
879
880
    /**
881
     * Updates the metadata.
882
     *
883
     * (see {@link ContentMetadataUpdateStruct}) of a content object - to update fields use updateContent
884
     *
885
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to update the content meta data
886
     * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if the remoteId in $contentMetadataUpdateStruct is set but already exists
887
     *
888
     * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
889
     * @param \eZ\Publish\API\Repository\Values\Content\ContentMetadataUpdateStruct $contentMetadataUpdateStruct
890
     *
891
     * @return \eZ\Publish\API\Repository\Values\Content\Content the content with the updated attributes
892
     */
893
    public function updateContentMetadata(ContentInfo $contentInfo, ContentMetadataUpdateStruct $contentMetadataUpdateStruct)
894
    {
895
        $propertyCount = 0;
896
        foreach ($contentMetadataUpdateStruct as $propertyName => $propertyValue) {
0 ignored issues
show
Bug introduced by
The expression $contentMetadataUpdateStruct of type object<eZ\Publish\API\Re...ntMetadataUpdateStruct> is not traversable.
Loading history...
897
            if (isset($contentMetadataUpdateStruct->$propertyName)) {
898
                $propertyCount += 1;
899
            }
900
        }
901
        if ($propertyCount === 0) {
902
            throw new InvalidArgumentException(
903
                '$contentMetadataUpdateStruct',
904
                'At least one property must be set'
905
            );
906
        }
907
908
        $loadedContentInfo = $this->loadContentInfo($contentInfo->id);
909
910
        if (!$this->permissionResolver->canUser('content', 'edit', $loadedContentInfo)) {
911
            throw new UnauthorizedException('content', 'edit', ['contentId' => $loadedContentInfo->id]);
912
        }
913
914
        if (isset($contentMetadataUpdateStruct->remoteId)) {
915
            try {
916
                $existingContentInfo = $this->loadContentInfoByRemoteId($contentMetadataUpdateStruct->remoteId);
917
918
                if ($existingContentInfo->id !== $loadedContentInfo->id) {
919
                    throw new InvalidArgumentException(
920
                        '$contentMetadataUpdateStruct',
921
                        "Another content with remoteId '{$contentMetadataUpdateStruct->remoteId}' exists"
922
                    );
923
                }
924
            } catch (APINotFoundException $e) {
925
                // Do nothing
926
            }
927
        }
928
929
        $this->repository->beginTransaction();
930
        try {
931
            if ($propertyCount > 1 || !isset($contentMetadataUpdateStruct->mainLocationId)) {
932
                $this->persistenceHandler->contentHandler()->updateMetadata(
933
                    $loadedContentInfo->id,
934
                    new SPIMetadataUpdateStruct(
935
                        [
936
                            'ownerId' => $contentMetadataUpdateStruct->ownerId,
937
                            'publicationDate' => isset($contentMetadataUpdateStruct->publishedDate) ?
938
                                $contentMetadataUpdateStruct->publishedDate->getTimestamp() :
939
                                null,
940
                            'modificationDate' => isset($contentMetadataUpdateStruct->modificationDate) ?
941
                                $contentMetadataUpdateStruct->modificationDate->getTimestamp() :
942
                                null,
943
                            'mainLanguageId' => isset($contentMetadataUpdateStruct->mainLanguageCode) ?
944
                                $this->repository->getContentLanguageService()->loadLanguage(
945
                                    $contentMetadataUpdateStruct->mainLanguageCode
946
                                )->id :
947
                                null,
948
                            'alwaysAvailable' => $contentMetadataUpdateStruct->alwaysAvailable,
949
                            'remoteId' => $contentMetadataUpdateStruct->remoteId,
950
                            'name' => $contentMetadataUpdateStruct->name,
951
                        ]
952
                    )
953
                );
954
            }
955
956
            // Change main location
957
            if (isset($contentMetadataUpdateStruct->mainLocationId)
958
                && $loadedContentInfo->mainLocationId !== $contentMetadataUpdateStruct->mainLocationId) {
959
                $this->persistenceHandler->locationHandler()->changeMainLocation(
960
                    $loadedContentInfo->id,
961
                    $contentMetadataUpdateStruct->mainLocationId
962
                );
963
            }
964
965
            // Republish URL aliases to update always-available flag
966
            if (isset($contentMetadataUpdateStruct->alwaysAvailable)
967
                && $loadedContentInfo->alwaysAvailable !== $contentMetadataUpdateStruct->alwaysAvailable) {
968
                $content = $this->loadContent($loadedContentInfo->id);
969
                $this->publishUrlAliasesForContent($content, false);
970
            }
971
972
            $this->repository->commit();
973
        } catch (Exception $e) {
974
            $this->repository->rollback();
975
            throw $e;
976
        }
977
978
        return isset($content) ? $content : $this->loadContent($loadedContentInfo->id);
979
    }
980
981
    /**
982
     * Publishes URL aliases for all locations of a given content.
983
     *
984
     * @param \eZ\Publish\API\Repository\Values\Content\Content $content
985
     * @param bool $updatePathIdentificationString this parameter is legacy storage specific for updating
986
     *                      ezcontentobject_tree.path_identification_string, it is ignored by other storage engines
987
     */
988
    protected function publishUrlAliasesForContent(APIContent $content, $updatePathIdentificationString = true)
989
    {
990
        $urlAliasNames = $this->nameSchemaService->resolveUrlAliasSchema($content);
991
        $locations = $this->repository->getLocationService()->loadLocations(
992
            $content->getVersionInfo()->getContentInfo()
993
        );
994
        $urlAliasHandler = $this->persistenceHandler->urlAliasHandler();
995
        foreach ($locations as $location) {
996
            foreach ($urlAliasNames as $languageCode => $name) {
997
                $urlAliasHandler->publishUrlAliasForLocation(
998
                    $location->id,
999
                    $location->parentLocationId,
1000
                    $name,
1001
                    $languageCode,
1002
                    $content->contentInfo->alwaysAvailable,
1003
                    $updatePathIdentificationString ? $languageCode === $content->contentInfo->mainLanguageCode : false
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $languageCode (integer) and $content->contentInfo->mainLanguageCode (string) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
1004
                );
1005
            }
1006
            // archive URL aliases of Translations that got deleted
1007
            $urlAliasHandler->archiveUrlAliasesForDeletedTranslations(
1008
                $location->id,
1009
                $location->parentLocationId,
1010
                $content->versionInfo->languageCodes
1011
            );
1012
        }
1013
    }
1014
1015
    /**
1016
     * Deletes a content object including all its versions and locations including their subtrees.
1017
     *
1018
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to delete the content (in one of the locations of the given content object)
1019
     *
1020
     * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
1021
     *
1022
     * @return mixed[] Affected Location Id's
1023
     */
1024
    public function deleteContent(ContentInfo $contentInfo)
1025
    {
1026
        $contentInfo = $this->internalLoadContentInfo($contentInfo->id);
1027
1028
        if (!$this->permissionResolver->canUser('content', 'remove', $contentInfo)) {
1029
            throw new UnauthorizedException('content', 'remove', ['contentId' => $contentInfo->id]);
1030
        }
1031
1032
        $affectedLocations = [];
1033
        $this->repository->beginTransaction();
1034
        try {
1035
            // Load Locations first as deleting Content also deletes belonging Locations
1036
            $spiLocations = $this->persistenceHandler->locationHandler()->loadLocationsByContent($contentInfo->id);
1037
            $this->persistenceHandler->contentHandler()->deleteContent($contentInfo->id);
1038
            $urlAliasHandler = $this->persistenceHandler->urlAliasHandler();
1039
            foreach ($spiLocations as $spiLocation) {
1040
                $urlAliasHandler->locationDeleted($spiLocation->id);
1041
                $affectedLocations[] = $spiLocation->id;
1042
            }
1043
            $this->repository->commit();
1044
        } catch (Exception $e) {
1045
            $this->repository->rollback();
1046
            throw $e;
1047
        }
1048
1049
        return $affectedLocations;
1050
    }
1051
1052
    /**
1053
     * Creates a draft from a published or archived version.
1054
     *
1055
     * If no version is given, the current published version is used.
1056
     * 4.x: The draft is created with the initialLanguage code of the source version or if not present with the main language.
1057
     * It can be changed on updating the version.
1058
     *
1059
     * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
1060
     * @param \eZ\Publish\API\Repository\Values\Content\VersionInfo $versionInfo
1061
     * @param \eZ\Publish\API\Repository\Values\User\User $creator if set given user is used to create the draft - otherwise the current-user is used
1062
     *
1063
     * @return \eZ\Publish\API\Repository\Values\Content\Content - the newly created content draft
1064
     *
1065
     * @throws \eZ\Publish\API\Repository\Exceptions\ForbiddenException
1066
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException if the current-user is not allowed to create the draft
1067
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the current-user is not allowed to create the draft
1068
     */
1069
    public function createContentDraft(ContentInfo $contentInfo, APIVersionInfo $versionInfo = null, User $creator = null)
1070
    {
1071
        $contentInfo = $this->loadContentInfo($contentInfo->id);
1072
1073
        if ($versionInfo !== null) {
1074
            // Check that given $contentInfo and $versionInfo belong to the same content
1075
            if ($versionInfo->getContentInfo()->id != $contentInfo->id) {
1076
                throw new InvalidArgumentException(
1077
                    '$versionInfo',
1078
                    'VersionInfo does not belong to the same content as given ContentInfo'
1079
                );
1080
            }
1081
1082
            $versionInfo = $this->loadVersionInfoById($contentInfo->id, $versionInfo->versionNo);
1083
1084
            switch ($versionInfo->status) {
1085
                case VersionInfo::STATUS_PUBLISHED:
1086
                case VersionInfo::STATUS_ARCHIVED:
1087
                    break;
1088
1089
                default:
1090
                    // @todo: throw an exception here, to be defined
1091
                    throw new BadStateException(
1092
                        '$versionInfo',
1093
                        'Draft can not be created from a draft version'
1094
                    );
1095
            }
1096
1097
            $versionNo = $versionInfo->versionNo;
1098
        } elseif ($contentInfo->published) {
1099
            $versionNo = $contentInfo->currentVersionNo;
1100
        } else {
1101
            // @todo: throw an exception here, to be defined
1102
            throw new BadStateException(
1103
                '$contentInfo',
1104
                'Content is not published, draft can be created only from published or archived version'
1105
            );
1106
        }
1107
1108
        if ($creator === null) {
1109
            $creator = $this->permissionResolver->getCurrentUserReference();
1110
        }
1111
1112
        if (!$this->permissionResolver->canUser(
1113
            'content',
1114
            'edit',
1115
            $contentInfo,
1116
            [
1117
                (new Target\Builder\VersionBuilder())
1118
                    ->changeStatusTo(APIVersionInfo::STATUS_DRAFT)
1119
                    ->build(),
1120
            ]
1121
        )) {
1122
            throw new UnauthorizedException(
1123
                'content',
1124
                'edit',
1125
                ['contentId' => $contentInfo->id]
1126
            );
1127
        }
1128
1129
        $this->repository->beginTransaction();
1130
        try {
1131
            $spiContent = $this->persistenceHandler->contentHandler()->createDraftFromVersion(
1132
                $contentInfo->id,
1133
                $versionNo,
1134
                $creator->getUserId()
1135
            );
1136
            $this->repository->commit();
1137
        } catch (Exception $e) {
1138
            $this->repository->rollback();
1139
            throw $e;
1140
        }
1141
1142
        return $this->domainMapper->buildContentDomainObject(
1143
            $spiContent,
1144
            $this->repository->getContentTypeService()->loadContentType(
1145
                $spiContent->versionInfo->contentInfo->contentTypeId
1146
            )
1147
        );
1148
    }
1149
1150
    public function countContentDrafts(?User $user = null): int
1151
    {
1152
        if ($this->permissionResolver->hasAccess('content', 'versionread') === false) {
1153
            return 0;
1154
        }
1155
1156
        return $this->persistenceHandler->contentHandler()->countDraftsForUser(
1157
            $this->resolveUser($user)->getUserId()
1158
        );
1159
    }
1160
1161
    /**
1162
     * Loads drafts for a user.
1163
     *
1164
     * If no user is given the drafts for the authenticated user are returned
1165
     *
1166
     * @param \eZ\Publish\API\Repository\Values\User\User|null $user
1167
     *
1168
     * @return \eZ\Publish\API\Repository\Values\Content\VersionInfo[] Drafts owned by the given user
1169
     *
1170
     * @throws \eZ\Publish\API\Repository\Exceptions\BadStateException
1171
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
1172
     * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
1173
     */
1174
    public function loadContentDrafts(User $user = null)
1175
    {
1176
        // throw early if user has absolutely no access to versionread
1177
        if ($this->permissionResolver->hasAccess('content', 'versionread') === false) {
1178
            throw new UnauthorizedException('content', 'versionread');
1179
        }
1180
1181
        $spiVersionInfoList = $this->persistenceHandler->contentHandler()->loadDraftsForUser(
1182
            $this->resolveUser($user)->getUserId()
1183
        );
1184
        $versionInfoList = [];
1185
        foreach ($spiVersionInfoList as $spiVersionInfo) {
1186
            $versionInfo = $this->domainMapper->buildVersionInfoDomainObject($spiVersionInfo);
1187
            // @todo: Change this to filter returned drafts by permissions instead of throwing
1188
            if (!$this->permissionResolver->canUser('content', 'versionread', $versionInfo)) {
1189
                throw new UnauthorizedException('content', 'versionread', ['contentId' => $versionInfo->contentInfo->id]);
1190
            }
1191
1192
            $versionInfoList[] = $versionInfo;
1193
        }
1194
1195
        return $versionInfoList;
1196
    }
1197
1198
    public function loadContentDraftList(?User $user = null, int $offset = 0, int $limit = -1): ContentDraftList
1199
    {
1200
        $list = new ContentDraftList();
1201
        if ($this->permissionResolver->hasAccess('content', 'versionread') === false) {
1202
            return $list;
1203
        }
1204
1205
        $list->totalCount = $this->persistenceHandler->contentHandler()->countDraftsForUser(
1206
            $this->resolveUser($user)->getUserId()
1207
        );
1208
        if ($list->totalCount > 0) {
1209
            $spiVersionInfoList = $this->persistenceHandler->contentHandler()->loadDraftListForUser(
1210
                $this->resolveUser($user)->getUserId(),
1211
                $offset,
1212
                $limit
1213
            );
1214
            foreach ($spiVersionInfoList as $spiVersionInfo) {
1215
                $versionInfo = $this->domainMapper->buildVersionInfoDomainObject($spiVersionInfo);
1216
                if ($this->permissionResolver->canUser('content', 'versionread', $versionInfo)) {
1217
                    $list->items[] = new ContentDraftListItem($versionInfo);
1218
                } else {
1219
                    $list->items[] = new UnauthorizedContentDraftListItem(
1220
                        'content',
1221
                        'versionread',
1222
                        ['contentId' => $versionInfo->contentInfo->id]
1223
                    );
1224
                }
1225
            }
1226
        }
1227
1228
        return $list;
1229
    }
1230
1231
    /**
1232
     * Updates the fields of a draft.
1233
     *
1234
     * @param \eZ\Publish\API\Repository\Values\Content\VersionInfo $versionInfo
1235
     * @param \eZ\Publish\API\Repository\Values\Content\ContentUpdateStruct $contentUpdateStruct
1236
     *
1237
     * @return \eZ\Publish\API\Repository\Values\Content\Content the content draft with the updated fields
1238
     *
1239
     * @throws \eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException if a field in the $contentCreateStruct is not valid,
1240
     *                                                                               or if a required field is missing / set to an empty value.
1241
     * @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException If field definition does not exist in the ContentType,
1242
     *                                                                          or value is set for non-translatable field in language
1243
     *                                                                          other than main.
1244
     *
1245
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to update this version
1246
     * @throws \eZ\Publish\API\Repository\Exceptions\BadStateException if the version is not a draft
1247
     * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if a property on the struct is invalid.
1248
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
1249
     */
1250
    public function updateContent(APIVersionInfo $versionInfo, APIContentUpdateStruct $contentUpdateStruct)
1251
    {
1252
        $contentUpdateStruct = clone $contentUpdateStruct;
1253
1254
        /** @var $content \eZ\Publish\Core\Repository\Values\Content\Content */
1255
        $content = $this->loadContent(
1256
            $versionInfo->getContentInfo()->id,
1257
            null,
1258
            $versionInfo->versionNo
1259
        );
1260
        if (!$content->versionInfo->isDraft()) {
1261
            throw new BadStateException(
1262
                '$versionInfo',
1263
                'Version is not a draft and can not be updated'
1264
            );
1265
        }
1266
1267
        if (!$this->repository->getPermissionResolver()->canUser(
1268
            'content',
1269
            'edit',
1270
            $content,
1271
            [
1272
                (new Target\Builder\VersionBuilder())
1273
                    ->updateFieldsTo(
1274
                        $contentUpdateStruct->initialLanguageCode,
1275
                        $contentUpdateStruct->fields
1276
                    )
1277
                    ->build(),
1278
            ]
1279
        )) {
1280
            throw new UnauthorizedException('content', 'edit', ['contentId' => $content->id]);
1281
        }
1282
1283
        $mainLanguageCode = $content->contentInfo->mainLanguageCode;
1284
        if ($contentUpdateStruct->initialLanguageCode === null) {
1285
            $contentUpdateStruct->initialLanguageCode = $mainLanguageCode;
1286
        }
1287
1288
        $allLanguageCodes = $this->getLanguageCodesForUpdate($contentUpdateStruct, $content);
1289
        $contentLanguageHandler = $this->persistenceHandler->contentLanguageHandler();
1290
        foreach ($allLanguageCodes as $languageCode) {
1291
            $contentLanguageHandler->loadByLanguageCode($languageCode);
1292
        }
1293
1294
        $updatedLanguageCodes = $this->getUpdatedLanguageCodes($contentUpdateStruct);
1295
        $contentType = $this->repository->getContentTypeService()->loadContentType(
1296
            $content->contentInfo->contentTypeId
1297
        );
1298
        $fields = $this->mapFieldsForUpdate(
1299
            $contentUpdateStruct,
1300
            $contentType,
1301
            $mainLanguageCode
1302
        );
1303
1304
        $fieldValues = [];
1305
        $spiFields = [];
1306
        $allFieldErrors = [];
1307
        $inputRelations = [];
1308
        $locationIdToContentIdMapping = [];
1309
1310
        foreach ($contentType->getFieldDefinitions() as $fieldDefinition) {
1311
            /** @var $fieldType \eZ\Publish\SPI\FieldType\FieldType */
1312
            $fieldType = $this->fieldTypeRegistry->getFieldType(
1313
                $fieldDefinition->fieldTypeIdentifier
1314
            );
1315
1316
            foreach ($allLanguageCodes as $languageCode) {
1317
                $isCopied = $isEmpty = $isRetained = false;
1318
                $isLanguageNew = !in_array($languageCode, $content->versionInfo->languageCodes);
1319
                $isLanguageUpdated = in_array($languageCode, $updatedLanguageCodes);
1320
                $valueLanguageCode = $fieldDefinition->isTranslatable ? $languageCode : $mainLanguageCode;
1321
                $isFieldUpdated = isset($fields[$fieldDefinition->identifier][$valueLanguageCode]);
1322
                $isProcessed = isset($fieldValues[$fieldDefinition->identifier][$valueLanguageCode]);
1323
1324
                if (!$isFieldUpdated && !$isLanguageNew) {
1325
                    $isRetained = true;
1326
                    $fieldValue = $content->getField($fieldDefinition->identifier, $valueLanguageCode)->value;
1327
                } elseif (!$isFieldUpdated && $isLanguageNew && !$fieldDefinition->isTranslatable) {
1328
                    $isCopied = true;
1329
                    $fieldValue = $content->getField($fieldDefinition->identifier, $valueLanguageCode)->value;
1330
                } elseif ($isFieldUpdated) {
1331
                    $fieldValue = $fields[$fieldDefinition->identifier][$valueLanguageCode]->value;
1332
                } else {
1333
                    $fieldValue = $fieldDefinition->defaultValue;
1334
                }
1335
1336
                $fieldValue = $fieldType->acceptValue($fieldValue);
1337
1338
                if ($fieldType->isEmptyValue($fieldValue)) {
1339
                    $isEmpty = true;
1340
                    if ($isLanguageUpdated && $fieldDefinition->isRequired) {
1341
                        $allFieldErrors[$fieldDefinition->id][$languageCode] = new ValidationError(
1342
                            "Value for required field definition '%identifier%' with language '%languageCode%' is empty",
1343
                            null,
1344
                            ['%identifier%' => $fieldDefinition->identifier, '%languageCode%' => $languageCode],
1345
                            'empty'
1346
                        );
1347
                    }
1348
                } elseif ($isLanguageUpdated) {
1349
                    $fieldErrors = $fieldType->validate(
1350
                        $fieldDefinition,
1351
                        $fieldValue
1352
                    );
1353
                    if (!empty($fieldErrors)) {
1354
                        $allFieldErrors[$fieldDefinition->id][$languageCode] = $fieldErrors;
1355
                    }
1356
                }
1357
1358
                if (!empty($allFieldErrors)) {
1359
                    continue;
1360
                }
1361
1362
                $this->relationProcessor->appendFieldRelations(
1363
                    $inputRelations,
1364
                    $locationIdToContentIdMapping,
1365
                    $fieldType,
1366
                    $fieldValue,
1367
                    $fieldDefinition->id
1368
                );
1369
                $fieldValues[$fieldDefinition->identifier][$languageCode] = $fieldValue;
1370
1371
                if ($isRetained || $isCopied || ($isLanguageNew && $isEmpty) || $isProcessed) {
1372
                    continue;
1373
                }
1374
1375
                $spiFields[] = new SPIField(
1376
                    [
1377
                        'id' => $isLanguageNew ?
1378
                            null :
1379
                            $content->getField($fieldDefinition->identifier, $languageCode)->id,
1380
                        'fieldDefinitionId' => $fieldDefinition->id,
1381
                        'type' => $fieldDefinition->fieldTypeIdentifier,
1382
                        'value' => $fieldType->toPersistenceValue($fieldValue),
1383
                        'languageCode' => $languageCode,
1384
                        'versionNo' => $versionInfo->versionNo,
1385
                    ]
1386
                );
1387
            }
1388
        }
1389
1390
        if (!empty($allFieldErrors)) {
1391
            throw new ContentFieldValidationException($allFieldErrors);
1392
        }
1393
1394
        $spiContentUpdateStruct = new SPIContentUpdateStruct(
1395
            [
1396
                'name' => $this->nameSchemaService->resolveNameSchema(
1397
                    $content,
1398
                    $fieldValues,
1399
                    $allLanguageCodes,
1400
                    $contentType
1401
                ),
1402
                'creatorId' => $contentUpdateStruct->creatorId ?: $this->permissionResolver->getCurrentUserReference()->getUserId(),
1403
                'fields' => $spiFields,
1404
                'modificationDate' => time(),
1405
                'initialLanguageId' => $this->persistenceHandler->contentLanguageHandler()->loadByLanguageCode(
1406
                    $contentUpdateStruct->initialLanguageCode
1407
                )->id,
1408
            ]
1409
        );
1410
        $existingRelations = $this->loadRelations($versionInfo);
1411
1412
        $this->repository->beginTransaction();
1413
        try {
1414
            $spiContent = $this->persistenceHandler->contentHandler()->updateContent(
1415
                $versionInfo->getContentInfo()->id,
1416
                $versionInfo->versionNo,
1417
                $spiContentUpdateStruct
1418
            );
1419
            $this->relationProcessor->processFieldRelations(
1420
                $inputRelations,
1421
                $spiContent->versionInfo->contentInfo->id,
1422
                $spiContent->versionInfo->versionNo,
1423
                $contentType,
1424
                $existingRelations
1425
            );
1426
            $this->repository->commit();
1427
        } catch (Exception $e) {
1428
            $this->repository->rollback();
1429
            throw $e;
1430
        }
1431
1432
        return $this->domainMapper->buildContentDomainObject(
1433
            $spiContent,
1434
            $contentType
1435
        );
1436
    }
1437
1438
    /**
1439
     * Returns only updated language codes.
1440
     *
1441
     * @param \eZ\Publish\API\Repository\Values\Content\ContentUpdateStruct $contentUpdateStruct
1442
     *
1443
     * @return array
1444
     */
1445
    private function getUpdatedLanguageCodes(APIContentUpdateStruct $contentUpdateStruct)
1446
    {
1447
        $languageCodes = [
1448
            $contentUpdateStruct->initialLanguageCode => true,
1449
        ];
1450
1451
        foreach ($contentUpdateStruct->fields as $field) {
1452
            if ($field->languageCode === null || isset($languageCodes[$field->languageCode])) {
1453
                continue;
1454
            }
1455
1456
            $languageCodes[$field->languageCode] = true;
1457
        }
1458
1459
        return array_keys($languageCodes);
1460
    }
1461
1462
    /**
1463
     * Returns all language codes used in given $fields.
1464
     *
1465
     * @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException if no field value exists in initial language
1466
     *
1467
     * @param \eZ\Publish\API\Repository\Values\Content\ContentUpdateStruct $contentUpdateStruct
1468
     * @param \eZ\Publish\API\Repository\Values\Content\Content $content
1469
     *
1470
     * @return array
1471
     */
1472
    protected function getLanguageCodesForUpdate(APIContentUpdateStruct $contentUpdateStruct, APIContent $content)
1473
    {
1474
        $languageCodes = array_fill_keys($content->versionInfo->languageCodes, true);
1475
        $languageCodes[$contentUpdateStruct->initialLanguageCode] = true;
1476
1477
        $updatedLanguageCodes = $this->getUpdatedLanguageCodes($contentUpdateStruct);
1478
        foreach ($updatedLanguageCodes as $languageCode) {
1479
            $languageCodes[$languageCode] = true;
1480
        }
1481
1482
        return array_keys($languageCodes);
1483
    }
1484
1485
    /**
1486
     * Returns an array of fields like $fields[$field->fieldDefIdentifier][$field->languageCode].
1487
     *
1488
     * @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException If field definition does not exist in the ContentType
1489
     *                                                                          or value is set for non-translatable field in language
1490
     *                                                                          other than main
1491
     *
1492
     * @param \eZ\Publish\API\Repository\Values\Content\ContentUpdateStruct $contentUpdateStruct
1493
     * @param \eZ\Publish\API\Repository\Values\ContentType\ContentType $contentType
1494
     * @param string $mainLanguageCode
1495
     *
1496
     * @return array
1497
     */
1498
    protected function mapFieldsForUpdate(
1499
        APIContentUpdateStruct $contentUpdateStruct,
1500
        ContentType $contentType,
1501
        $mainLanguageCode
1502
    ) {
1503
        $fields = [];
1504
1505
        foreach ($contentUpdateStruct->fields as $field) {
1506
            $fieldDefinition = $contentType->getFieldDefinition($field->fieldDefIdentifier);
1507
1508
            if ($fieldDefinition === null) {
1509
                throw new ContentValidationException(
1510
                    "Field definition '%identifier%' does not exist in given ContentType",
1511
                    ['%identifier%' => $field->fieldDefIdentifier]
1512
                );
1513
            }
1514
1515
            if ($field->languageCode === null) {
1516
                if ($fieldDefinition->isTranslatable) {
1517
                    $languageCode = $contentUpdateStruct->initialLanguageCode;
1518
                } else {
1519
                    $languageCode = $mainLanguageCode;
1520
                }
1521
                $field = $this->cloneField($field, ['languageCode' => $languageCode]);
1522
            }
1523
1524
            if (!$fieldDefinition->isTranslatable && ($field->languageCode != $mainLanguageCode)) {
1525
                throw new ContentValidationException(
1526
                    "A value is set for non translatable field definition '%identifier%' with language '%languageCode%'",
1527
                    ['%identifier%' => $field->fieldDefIdentifier, '%languageCode%' => $field->languageCode]
1528
                );
1529
            }
1530
1531
            $fields[$field->fieldDefIdentifier][$field->languageCode] = $field;
1532
        }
1533
1534
        return $fields;
1535
    }
1536
1537
    /**
1538
     * Publishes a content version.
1539
     *
1540
     * Publishes a content version and deletes archive versions if they overflow max archive versions.
1541
     * Max archive versions are currently a configuration, but might be moved to be a param of ContentType in the future.
1542
     *
1543
     * @param \eZ\Publish\API\Repository\Values\Content\VersionInfo $versionInfo
1544
     * @param string[] $translations
1545
     *
1546
     * @return \eZ\Publish\API\Repository\Values\Content\Content
1547
     *
1548
     * @throws \eZ\Publish\API\Repository\Exceptions\BadStateException if the version is not a draft
1549
     * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
1550
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
1551
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
1552
     */
1553
    public function publishVersion(APIVersionInfo $versionInfo, array $translations = Language::ALL)
1554
    {
1555
        $content = $this->internalLoadContent(
1556
            $versionInfo->contentInfo->id,
1557
            null,
1558
            $versionInfo->versionNo
1559
        );
1560
1561
        $fromContent = null;
0 ignored issues
show
Unused Code introduced by
$fromContent is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1562
        if ($content->contentInfo->currentVersionNo !== $versionInfo->versionNo) {
1563
            $fromContent = $this->internalLoadContent(
1564
                $content->contentInfo->id,
1565
                null,
1566
                $content->contentInfo->currentVersionNo
1567
            );
1568
            // should not occur now, might occur in case of un-publish
1569
            if (!$fromContent->contentInfo->isPublished()) {
1570
                $fromContent = null;
0 ignored issues
show
Unused Code introduced by
$fromContent is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1571
            }
1572
        }
1573
1574
        if (!$this->permissionResolver->canUser(
1575
            'content',
1576
            'publish',
1577
            $content
1578
        )) {
1579
            throw new UnauthorizedException(
1580
                'content', 'publish', ['contentId' => $content->id]
1581
            );
1582
        }
1583
1584
        $this->repository->beginTransaction();
1585
        try {
1586
            $this->copyTranslationsFromPublishedVersion($content->versionInfo, $translations);
1587
            $content = $this->internalPublishVersion($content->getVersionInfo(), null);
1588
            $this->repository->commit();
1589
        } catch (Exception $e) {
1590
            $this->repository->rollback();
1591
            throw $e;
1592
        }
1593
1594
        return $content;
1595
    }
1596
1597
    /**
1598
     * @param \eZ\Publish\API\Repository\Values\Content\VersionInfo $versionInfo
1599
     * @param array $translations
1600
     *
1601
     * @throws \eZ\Publish\API\Repository\Exceptions\BadStateException
1602
     * @throws \eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException
1603
     * @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException
1604
     * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
1605
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
1606
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
1607
     */
1608
    protected function copyTranslationsFromPublishedVersion(APIVersionInfo $versionInfo, array $translations = []): void
1609
    {
1610
        $contendId = $versionInfo->contentInfo->id;
1611
1612
        $currentContent = $this->internalLoadContent($contendId);
1613
        $currentVersionInfo = $currentContent->versionInfo;
1614
1615
        // Copying occurs only if:
1616
        // - There is published Version
1617
        // - Published version is older than the currently published one unless specific translations are provided.
1618
        if (!$currentVersionInfo->isPublished() ||
1619
            ($versionInfo->versionNo >= $currentVersionInfo->versionNo && empty($translations))) {
1620
            return;
1621
        }
1622
1623
        if (empty($translations)) {
1624
            $languagesToCopy = array_diff(
1625
                $currentVersionInfo->languageCodes,
1626
                $versionInfo->languageCodes
1627
            );
1628
        } else {
1629
            $languagesToCopy = array_diff(
1630
                $currentVersionInfo->languageCodes,
1631
                $translations
1632
            );
1633
        }
1634
1635
        if (empty($languagesToCopy)) {
1636
            return;
1637
        }
1638
1639
        $contentType = $this->repository->getContentTypeService()->loadContentType(
1640
            $currentVersionInfo->contentInfo->contentTypeId
1641
        );
1642
1643
        // Find only translatable fields to update with selected languages
1644
        $updateStruct = $this->newContentUpdateStruct();
1645
        $updateStruct->initialLanguageCode = $versionInfo->initialLanguageCode;
1646
1647
        foreach ($currentContent->getFields() as $field) {
1648
            $fieldDefinition = $contentType->getFieldDefinition($field->fieldDefIdentifier);
1649
1650
            if ($fieldDefinition->isTranslatable && in_array($field->languageCode, $languagesToCopy)) {
1651
                $updateStruct->setField($field->fieldDefIdentifier, $field->value, $field->languageCode);
1652
            }
1653
        }
1654
1655
        $this->updateContent($versionInfo, $updateStruct);
1656
    }
1657
1658
    /**
1659
     * Publishes a content version.
1660
     *
1661
     * Publishes a content version and deletes archive versions if they overflow max archive versions.
1662
     * Max archive versions are currently a configuration, but might be moved to be a param of ContentType in the future.
1663
     *
1664
     * @throws \eZ\Publish\API\Repository\Exceptions\BadStateException if the version is not a draft
1665
     *
1666
     * @param \eZ\Publish\API\Repository\Values\Content\VersionInfo $versionInfo
1667
     * @param int|null $publicationDate If null existing date is kept if there is one, otherwise current time is used.
1668
     *
1669
     * @return \eZ\Publish\API\Repository\Values\Content\Content
1670
     */
1671
    protected function internalPublishVersion(APIVersionInfo $versionInfo, $publicationDate = null)
1672
    {
1673
        if (!$versionInfo->isDraft()) {
1674
            throw new BadStateException('$versionInfo', 'Only versions in draft status can be published.');
1675
        }
1676
1677
        $currentTime = $this->getUnixTimestamp();
1678
        if ($publicationDate === null && $versionInfo->versionNo === 1) {
1679
            $publicationDate = $currentTime;
1680
        }
1681
1682
        $metadataUpdateStruct = new SPIMetadataUpdateStruct();
1683
        $metadataUpdateStruct->publicationDate = $publicationDate;
1684
        $metadataUpdateStruct->modificationDate = $currentTime;
1685
1686
        $contentId = $versionInfo->getContentInfo()->id;
1687
        $spiContent = $this->persistenceHandler->contentHandler()->publish(
1688
            $contentId,
1689
            $versionInfo->versionNo,
1690
            $metadataUpdateStruct
1691
        );
1692
1693
        $content = $this->domainMapper->buildContentDomainObject(
1694
            $spiContent,
1695
            $this->repository->getContentTypeService()->loadContentType(
1696
                $spiContent->versionInfo->contentInfo->contentTypeId
1697
            )
1698
        );
1699
1700
        $this->publishUrlAliasesForContent($content);
1701
1702
        // Delete version archive overflow if any, limit is 0-50 (however 0 will mean 1 if content is unpublished)
1703
        $archiveList = $this->persistenceHandler->contentHandler()->listVersions(
1704
            $contentId,
1705
            APIVersionInfo::STATUS_ARCHIVED,
1706
            100 // Limited to avoid publishing taking to long, besides SE limitations this is why limit is max 50
1707
        );
1708
1709
        $maxVersionArchiveCount = max(0, min(50, $this->settings['default_version_archive_limit']));
1710
        while (!empty($archiveList) && count($archiveList) > $maxVersionArchiveCount) {
1711
            /** @var \eZ\Publish\SPI\Persistence\Content\VersionInfo $archiveVersion */
1712
            $archiveVersion = array_shift($archiveList);
1713
            $this->persistenceHandler->contentHandler()->deleteVersion(
1714
                $contentId,
1715
                $archiveVersion->versionNo
1716
            );
1717
        }
1718
1719
        return $content;
1720
    }
1721
1722
    /**
1723
     * @return int
1724
     */
1725
    protected function getUnixTimestamp()
1726
    {
1727
        return time();
1728
    }
1729
1730
    /**
1731
     * Removes the given version.
1732
     *
1733
     * @throws \eZ\Publish\API\Repository\Exceptions\BadStateException if the version is in
1734
     *         published state or is a last version of Content in non draft state
1735
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to remove this version
1736
     *
1737
     * @param \eZ\Publish\API\Repository\Values\Content\VersionInfo $versionInfo
1738
     */
1739
    public function deleteVersion(APIVersionInfo $versionInfo)
1740
    {
1741
        if ($versionInfo->isPublished()) {
1742
            throw new BadStateException(
1743
                '$versionInfo',
1744
                'Version is published and can not be removed'
1745
            );
1746
        }
1747
1748
        if (!$this->permissionResolver->canUser('content', 'versionremove', $versionInfo)) {
1749
            throw new UnauthorizedException(
1750
                'content',
1751
                'versionremove',
1752
                ['contentId' => $versionInfo->contentInfo->id, 'versionNo' => $versionInfo->versionNo]
1753
            );
1754
        }
1755
1756
        $versionList = $this->persistenceHandler->contentHandler()->listVersions(
1757
            $versionInfo->contentInfo->id,
1758
            null,
1759
            2
1760
        );
1761
1762
        if (count($versionList) === 1 && !$versionInfo->isDraft()) {
1763
            throw new BadStateException(
1764
                '$versionInfo',
1765
                'Version is the last version of the Content and can not be removed'
1766
            );
1767
        }
1768
1769
        $this->repository->beginTransaction();
1770
        try {
1771
            $this->persistenceHandler->contentHandler()->deleteVersion(
1772
                $versionInfo->getContentInfo()->id,
1773
                $versionInfo->versionNo
1774
            );
1775
            $this->repository->commit();
1776
        } catch (Exception $e) {
1777
            $this->repository->rollback();
1778
            throw $e;
1779
        }
1780
    }
1781
1782
    /**
1783
     * Loads all versions for the given content.
1784
     *
1785
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to list versions
1786
     * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if the given status is invalid
1787
     *
1788
     * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
1789
     * @param int|null $status
1790
     *
1791
     * @return \eZ\Publish\API\Repository\Values\Content\VersionInfo[] Sorted by creation date
1792
     */
1793
    public function loadVersions(ContentInfo $contentInfo, ?int $status = null)
1794
    {
1795
        if (!$this->permissionResolver->canUser('content', 'versionread', $contentInfo)) {
1796
            throw new UnauthorizedException('content', 'versionread', ['contentId' => $contentInfo->id]);
1797
        }
1798
1799
        if ($status !== null && !in_array((int)$status, [VersionInfo::STATUS_DRAFT, VersionInfo::STATUS_PUBLISHED, VersionInfo::STATUS_ARCHIVED], true)) {
1800
            throw new InvalidArgumentException(
1801
                'status',
1802
                sprintf(
1803
                    'it can be one of %d (draft), %d (published), %d (archived), %d given',
1804
                    VersionInfo::STATUS_DRAFT, VersionInfo::STATUS_PUBLISHED, VersionInfo::STATUS_ARCHIVED, $status
1805
                ));
1806
        }
1807
1808
        $spiVersionInfoList = $this->persistenceHandler->contentHandler()->listVersions($contentInfo->id, $status);
1809
1810
        $versions = [];
1811
        foreach ($spiVersionInfoList as $spiVersionInfo) {
1812
            $versionInfo = $this->domainMapper->buildVersionInfoDomainObject($spiVersionInfo);
1813
            if (!$this->permissionResolver->canUser('content', 'versionread', $versionInfo)) {
1814
                throw new UnauthorizedException('content', 'versionread', ['versionId' => $versionInfo->id]);
1815
            }
1816
1817
            $versions[] = $versionInfo;
1818
        }
1819
1820
        return $versions;
1821
    }
1822
1823
    /**
1824
     * Copies the content to a new location. If no version is given,
1825
     * all versions are copied, otherwise only the given version.
1826
     *
1827
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to copy the content to the given location
1828
     *
1829
     * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
1830
     * @param \eZ\Publish\API\Repository\Values\Content\LocationCreateStruct $destinationLocationCreateStruct the target location where the content is copied to
1831
     * @param \eZ\Publish\API\Repository\Values\Content\VersionInfo $versionInfo
1832
     *
1833
     * @return \eZ\Publish\API\Repository\Values\Content\Content
1834
     */
1835
    public function copyContent(ContentInfo $contentInfo, LocationCreateStruct $destinationLocationCreateStruct, APIVersionInfo $versionInfo = null)
1836
    {
1837
        $destinationLocation = $this->repository->getLocationService()->loadLocation(
1838
            $destinationLocationCreateStruct->parentLocationId
1839
        );
1840
        if (!$this->permissionResolver->canUser('content', 'create', $contentInfo, [$destinationLocation])) {
1841
            throw new UnauthorizedException(
1842
                'content',
1843
                'create',
1844
                [
1845
                    'parentLocationId' => $destinationLocationCreateStruct->parentLocationId,
1846
                    'sectionId' => $contentInfo->sectionId,
1847
                ]
1848
            );
1849
        }
1850
        if (!$this->permissionResolver->canUser('content', 'manage_locations', $contentInfo, [$destinationLocation])) {
1851
            throw new UnauthorizedException('content', 'manage_locations', ['contentId' => $contentInfo->id]);
1852
        }
1853
1854
        $defaultObjectStates = $this->getDefaultObjectStates();
1855
1856
        $this->repository->beginTransaction();
1857
        try {
1858
            $spiContent = $this->persistenceHandler->contentHandler()->copy(
1859
                $contentInfo->id,
1860
                $versionInfo ? $versionInfo->versionNo : null,
1861
                $this->permissionResolver->getCurrentUserReference()->getUserId()
1862
            );
1863
1864
            $objectStateHandler = $this->persistenceHandler->objectStateHandler();
1865
            foreach ($defaultObjectStates as $objectStateGroupId => $objectState) {
1866
                $objectStateHandler->setContentState(
1867
                    $spiContent->versionInfo->contentInfo->id,
1868
                    $objectStateGroupId,
1869
                    $objectState->id
1870
                );
1871
            }
1872
1873
            $content = $this->internalPublishVersion(
1874
                $this->domainMapper->buildVersionInfoDomainObject($spiContent->versionInfo),
1875
                $spiContent->versionInfo->creationDate
1876
            );
1877
1878
            $this->repository->getLocationService()->createLocation(
1879
                $content->getVersionInfo()->getContentInfo(),
1880
                $destinationLocationCreateStruct
1881
            );
1882
            $this->repository->commit();
1883
        } catch (Exception $e) {
1884
            $this->repository->rollback();
1885
            throw $e;
1886
        }
1887
1888
        return $this->internalLoadContent($content->id);
1889
    }
1890
1891
    /**
1892
     * Loads all outgoing relations for the given version.
1893
     *
1894
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to read this version
1895
     *
1896
     * @param \eZ\Publish\API\Repository\Values\Content\VersionInfo $versionInfo
1897
     *
1898
     * @return \eZ\Publish\API\Repository\Values\Content\Relation[]
1899
     */
1900
    public function loadRelations(APIVersionInfo $versionInfo)
1901
    {
1902
        if ($versionInfo->isPublished()) {
1903
            $function = 'read';
1904
        } else {
1905
            $function = 'versionread';
1906
        }
1907
1908
        if (!$this->permissionResolver->canUser('content', $function, $versionInfo)) {
1909
            throw new UnauthorizedException('content', $function);
1910
        }
1911
1912
        $contentInfo = $versionInfo->getContentInfo();
1913
        $spiRelations = $this->persistenceHandler->contentHandler()->loadRelations(
1914
            $contentInfo->id,
1915
            $versionInfo->versionNo
1916
        );
1917
1918
        /** @var $relations \eZ\Publish\API\Repository\Values\Content\Relation[] */
1919
        $relations = [];
1920
        foreach ($spiRelations as $spiRelation) {
1921
            $destinationContentInfo = $this->internalLoadContentInfo($spiRelation->destinationContentId);
1922
            if (!$this->permissionResolver->canUser('content', 'read', $destinationContentInfo)) {
1923
                continue;
1924
            }
1925
1926
            $relations[] = $this->domainMapper->buildRelationDomainObject(
1927
                $spiRelation,
1928
                $contentInfo,
1929
                $destinationContentInfo
1930
            );
1931
        }
1932
1933
        return $relations;
1934
    }
1935
1936
    /**
1937
     * {@inheritdoc}
1938
     */
1939
    public function countReverseRelations(ContentInfo $contentInfo): int
1940
    {
1941
        if (!$this->permissionResolver->canUser('content', 'reverserelatedlist', $contentInfo)) {
1942
            return 0;
1943
        }
1944
1945
        return $this->persistenceHandler->contentHandler()->countReverseRelations(
1946
            $contentInfo->id
1947
        );
1948
    }
1949
1950
    /**
1951
     * Loads all incoming relations for a content object.
1952
     *
1953
     * The relations come only from published versions of the source content objects
1954
     *
1955
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to read this version
1956
     *
1957
     * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
1958
     *
1959
     * @return \eZ\Publish\API\Repository\Values\Content\Relation[]
1960
     */
1961
    public function loadReverseRelations(ContentInfo $contentInfo)
1962
    {
1963
        if (!$this->permissionResolver->canUser('content', 'reverserelatedlist', $contentInfo)) {
1964
            throw new UnauthorizedException('content', 'reverserelatedlist', ['contentId' => $contentInfo->id]);
1965
        }
1966
1967
        $spiRelations = $this->persistenceHandler->contentHandler()->loadReverseRelations(
1968
            $contentInfo->id
1969
        );
1970
1971
        $returnArray = [];
1972
        foreach ($spiRelations as $spiRelation) {
1973
            $sourceContentInfo = $this->internalLoadContentInfo($spiRelation->sourceContentId);
1974
            if (!$this->permissionResolver->canUser('content', 'read', $sourceContentInfo)) {
1975
                continue;
1976
            }
1977
1978
            $returnArray[] = $this->domainMapper->buildRelationDomainObject(
1979
                $spiRelation,
1980
                $sourceContentInfo,
1981
                $contentInfo
1982
            );
1983
        }
1984
1985
        return $returnArray;
1986
    }
1987
1988
    /**
1989
     * Adds a relation of type common.
1990
     *
1991
     * The source of the relation is the content and version
1992
     * referenced by $versionInfo.
1993
     *
1994
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to edit this version
1995
     * @throws \eZ\Publish\API\Repository\Exceptions\BadStateException if the version is not a draft
1996
     *
1997
     * @param \eZ\Publish\API\Repository\Values\Content\VersionInfo $sourceVersion
1998
     * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $destinationContent the destination of the relation
1999
     *
2000
     * @return \eZ\Publish\API\Repository\Values\Content\Relation the newly created relation
2001
     */
2002
    public function addRelation(APIVersionInfo $sourceVersion, ContentInfo $destinationContent)
2003
    {
2004
        $sourceVersion = $this->loadVersionInfoById(
2005
            $sourceVersion->contentInfo->id,
2006
            $sourceVersion->versionNo
2007
        );
2008
2009
        if (!$sourceVersion->isDraft()) {
2010
            throw new BadStateException(
2011
                '$sourceVersion',
2012
                'Relations of type common can only be added to versions of status draft'
2013
            );
2014
        }
2015
2016
        if (!$this->permissionResolver->canUser('content', 'edit', $sourceVersion)) {
2017
            throw new UnauthorizedException('content', 'edit', ['contentId' => $sourceVersion->contentInfo->id]);
2018
        }
2019
2020
        $sourceContentInfo = $sourceVersion->getContentInfo();
2021
2022
        $this->repository->beginTransaction();
2023
        try {
2024
            $spiRelation = $this->persistenceHandler->contentHandler()->addRelation(
2025
                new SPIRelationCreateStruct(
2026
                    [
2027
                        'sourceContentId' => $sourceContentInfo->id,
2028
                        'sourceContentVersionNo' => $sourceVersion->versionNo,
2029
                        'sourceFieldDefinitionId' => null,
2030
                        'destinationContentId' => $destinationContent->id,
2031
                        'type' => APIRelation::COMMON,
2032
                    ]
2033
                )
2034
            );
2035
            $this->repository->commit();
2036
        } catch (Exception $e) {
2037
            $this->repository->rollback();
2038
            throw $e;
2039
        }
2040
2041
        return $this->domainMapper->buildRelationDomainObject($spiRelation, $sourceContentInfo, $destinationContent);
2042
    }
2043
2044
    /**
2045
     * Removes a relation of type COMMON from a draft.
2046
     *
2047
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed edit this version
2048
     * @throws \eZ\Publish\API\Repository\Exceptions\BadStateException if the version is not a draft
2049
     * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if there is no relation of type COMMON for the given destination
2050
     *
2051
     * @param \eZ\Publish\API\Repository\Values\Content\VersionInfo $sourceVersion
2052
     * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $destinationContent
2053
     */
2054
    public function deleteRelation(APIVersionInfo $sourceVersion, ContentInfo $destinationContent)
2055
    {
2056
        $sourceVersion = $this->loadVersionInfoById(
2057
            $sourceVersion->contentInfo->id,
2058
            $sourceVersion->versionNo
2059
        );
2060
2061
        if (!$sourceVersion->isDraft()) {
2062
            throw new BadStateException(
2063
                '$sourceVersion',
2064
                'Relations of type common can only be removed from versions of status draft'
2065
            );
2066
        }
2067
2068
        if (!$this->permissionResolver->canUser('content', 'edit', $sourceVersion)) {
2069
            throw new UnauthorizedException('content', 'edit', ['contentId' => $sourceVersion->contentInfo->id]);
2070
        }
2071
2072
        $spiRelations = $this->persistenceHandler->contentHandler()->loadRelations(
2073
            $sourceVersion->getContentInfo()->id,
2074
            $sourceVersion->versionNo,
2075
            APIRelation::COMMON
2076
        );
2077
2078
        if (empty($spiRelations)) {
2079
            throw new InvalidArgumentException(
2080
                '$sourceVersion',
2081
                'There are no relations of type COMMON for the given destination'
2082
            );
2083
        }
2084
2085
        // there should be only one relation of type COMMON for each destination,
2086
        // but in case there were ever more then one, we will remove them all
2087
        // @todo: alternatively, throw BadStateException?
2088
        $this->repository->beginTransaction();
2089
        try {
2090
            foreach ($spiRelations as $spiRelation) {
2091
                if ($spiRelation->destinationContentId == $destinationContent->id) {
2092
                    $this->persistenceHandler->contentHandler()->removeRelation(
2093
                        $spiRelation->id,
2094
                        APIRelation::COMMON
2095
                    );
2096
                }
2097
            }
2098
            $this->repository->commit();
2099
        } catch (Exception $e) {
2100
            $this->repository->rollback();
2101
            throw $e;
2102
        }
2103
    }
2104
2105
    /**
2106
     * {@inheritdoc}
2107
     */
2108
    public function removeTranslation(ContentInfo $contentInfo, $languageCode)
2109
    {
2110
        @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2111
            __METHOD__ . ' is deprecated, use deleteTranslation instead',
2112
            E_USER_DEPRECATED
2113
        );
2114
        $this->deleteTranslation($contentInfo, $languageCode);
2115
    }
2116
2117
    /**
2118
     * Delete Content item Translation from all Versions (including archived ones) of a Content Object.
2119
     *
2120
     * NOTE: this operation is risky and permanent, so user interface should provide a warning before performing it.
2121
     *
2122
     * @throws \eZ\Publish\API\Repository\Exceptions\BadStateException if the specified Translation
2123
     *         is the Main Translation of a Content Item.
2124
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed
2125
     *         to delete the content (in one of the locations of the given Content Item).
2126
     * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if languageCode argument
2127
     *         is invalid for the given content.
2128
     *
2129
     * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
2130
     * @param string $languageCode
2131
     *
2132
     * @since 6.13
2133
     */
2134
    public function deleteTranslation(ContentInfo $contentInfo, $languageCode)
2135
    {
2136
        if ($contentInfo->mainLanguageCode === $languageCode) {
2137
            throw new BadStateException(
2138
                '$languageCode',
2139
                'Specified translation is the main translation of the Content Object'
2140
            );
2141
        }
2142
2143
        $translationWasFound = false;
2144
        $this->repository->beginTransaction();
2145
        try {
2146
            foreach ($this->loadVersions($contentInfo) as $versionInfo) {
2147
                if (!$this->permissionResolver->canUser('content', 'remove', $versionInfo)) {
2148
                    throw new UnauthorizedException(
2149
                        'content',
2150
                        'remove',
2151
                        ['contentId' => $contentInfo->id, 'versionNo' => $versionInfo->versionNo]
2152
                    );
2153
                }
2154
2155
                if (!in_array($languageCode, $versionInfo->languageCodes)) {
2156
                    continue;
2157
                }
2158
2159
                $translationWasFound = true;
2160
2161
                // If the translation is the version's only one, delete the version
2162
                if (count($versionInfo->languageCodes) < 2) {
2163
                    $this->persistenceHandler->contentHandler()->deleteVersion(
2164
                        $versionInfo->getContentInfo()->id,
2165
                        $versionInfo->versionNo
2166
                    );
2167
                }
2168
            }
2169
2170
            if (!$translationWasFound) {
2171
                throw new InvalidArgumentException(
2172
                    '$languageCode',
2173
                    sprintf(
2174
                        '%s does not exist in the Content item(id=%d)',
2175
                        $languageCode,
2176
                        $contentInfo->id
2177
                    )
2178
                );
2179
            }
2180
2181
            $this->persistenceHandler->contentHandler()->deleteTranslationFromContent(
2182
                $contentInfo->id,
2183
                $languageCode
2184
            );
2185
            $locationIds = array_map(
2186
                function (Location $location) {
2187
                    return $location->id;
2188
                },
2189
                $this->repository->getLocationService()->loadLocations($contentInfo)
2190
            );
2191
            $this->persistenceHandler->urlAliasHandler()->translationRemoved(
2192
                $locationIds,
2193
                $languageCode
2194
            );
2195
            $this->repository->commit();
2196
        } catch (InvalidArgumentException $e) {
2197
            $this->repository->rollback();
2198
            throw $e;
2199
        } catch (BadStateException $e) {
2200
            $this->repository->rollback();
2201
            throw $e;
2202
        } catch (UnauthorizedException $e) {
2203
            $this->repository->rollback();
2204
            throw $e;
2205
        } catch (Exception $e) {
2206
            $this->repository->rollback();
2207
            // cover generic unexpected exception to fulfill API promise on @throws
2208
            throw new BadStateException('$contentInfo', 'Translation removal failed', $e);
2209
        }
2210
    }
2211
2212
    /**
2213
     * Delete specified Translation from a Content Draft.
2214
     *
2215
     * @throws \eZ\Publish\API\Repository\Exceptions\BadStateException if the specified Translation
2216
     *         is the only one the Content Draft has or it is the main Translation of a Content Object.
2217
     * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed
2218
     *         to edit the Content (in one of the locations of the given Content Object).
2219
     * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if languageCode argument
2220
     *         is invalid for the given Draft.
2221
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException if specified Version was not found
2222
     *
2223
     * @param \eZ\Publish\API\Repository\Values\Content\VersionInfo $versionInfo Content Version Draft
2224
     * @param string $languageCode Language code of the Translation to be removed
2225
     *
2226
     * @return \eZ\Publish\API\Repository\Values\Content\Content Content Draft w/o the specified Translation
2227
     *
2228
     * @since 6.12
2229
     */
2230
    public function deleteTranslationFromDraft(APIVersionInfo $versionInfo, $languageCode)
2231
    {
2232
        if (!$versionInfo->isDraft()) {
2233
            throw new BadStateException(
2234
                '$versionInfo',
2235
                'Version is not a draft, so Translations cannot be modified. Create a Draft before proceeding'
2236
            );
2237
        }
2238
2239
        if ($versionInfo->contentInfo->mainLanguageCode === $languageCode) {
2240
            throw new BadStateException(
2241
                '$languageCode',
2242
                'Specified Translation is the main Translation of the Content Object. Change it before proceeding.'
2243
            );
2244
        }
2245
2246
        if (!$this->permissionResolver->canUser('content', 'edit', $versionInfo->contentInfo)) {
2247
            throw new UnauthorizedException(
2248
                'content', 'edit', ['contentId' => $versionInfo->contentInfo->id]
2249
            );
2250
        }
2251
2252
        if (!in_array($languageCode, $versionInfo->languageCodes)) {
2253
            throw new InvalidArgumentException(
2254
                '$languageCode',
2255
                sprintf(
2256
                    'The Version (ContentId=%d, VersionNo=%d) is not translated into %s',
2257
                    $versionInfo->contentInfo->id,
2258
                    $versionInfo->versionNo,
2259
                    $languageCode
2260
                )
2261
            );
2262
        }
2263
2264
        if (count($versionInfo->languageCodes) === 1) {
2265
            throw new BadStateException(
2266
                '$languageCode',
2267
                'Specified Translation is the only one Content Object Version has'
2268
            );
2269
        }
2270
2271
        $this->repository->beginTransaction();
2272
        try {
2273
            $spiContent = $this->persistenceHandler->contentHandler()->deleteTranslationFromDraft(
2274
                $versionInfo->contentInfo->id,
2275
                $versionInfo->versionNo,
2276
                $languageCode
2277
            );
2278
            $this->repository->commit();
2279
2280
            return $this->domainMapper->buildContentDomainObject(
2281
                $spiContent,
2282
                $this->repository->getContentTypeService()->loadContentType(
2283
                    $spiContent->versionInfo->contentInfo->contentTypeId
2284
                )
2285
            );
2286
        } catch (APINotFoundException $e) {
2287
            // avoid wrapping expected NotFoundException in BadStateException handled below
2288
            $this->repository->rollback();
2289
            throw $e;
2290
        } catch (Exception $e) {
2291
            $this->repository->rollback();
2292
            // cover generic unexpected exception to fulfill API promise on @throws
2293
            throw new BadStateException('$contentInfo', 'Translation removal failed', $e);
2294
        }
2295
    }
2296
2297
    /**
2298
     * Hides Content by making all the Locations appear hidden.
2299
     * It does not persist hidden state on Location object itself.
2300
     *
2301
     * Content hidden by this API can be revealed by revealContent API.
2302
     *
2303
     * @see revealContent
2304
     *
2305
     * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
2306
     */
2307
    public function hideContent(ContentInfo $contentInfo): void
2308
    {
2309
        if (!$this->permissionResolver->canUser('content', 'hide', $contentInfo)) {
2310
            throw new UnauthorizedException('content', 'hide', ['contentId' => $contentInfo->id]);
2311
        }
2312
2313
        $this->repository->beginTransaction();
2314
        try {
2315
            $this->persistenceHandler->contentHandler()->updateMetadata(
2316
                $contentInfo->id,
2317
                new SPIMetadataUpdateStruct([
2318
                    'isHidden' => true,
2319
                ])
2320
            );
2321
            $locationHandler = $this->persistenceHandler->locationHandler();
2322
            $childLocations = $locationHandler->loadLocationsByContent($contentInfo->id);
2323
            foreach ($childLocations as $childLocation) {
2324
                $locationHandler->setInvisible($childLocation->id);
2325
            }
2326
            $this->repository->commit();
2327
        } catch (Exception $e) {
2328
            $this->repository->rollback();
2329
            throw $e;
2330
        }
2331
    }
2332
2333
    /**
2334
     * Reveals Content hidden by hideContent API.
2335
     * Locations which were hidden before hiding Content will remain hidden.
2336
     *
2337
     * @see hideContent
2338
     *
2339
     * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
2340
     */
2341
    public function revealContent(ContentInfo $contentInfo): void
2342
    {
2343
        if (!$this->permissionResolver->canUser('content', 'hide', $contentInfo)) {
2344
            throw new UnauthorizedException('content', 'hide', ['contentId' => $contentInfo->id]);
2345
        }
2346
2347
        $this->repository->beginTransaction();
2348
        try {
2349
            $this->persistenceHandler->contentHandler()->updateMetadata(
2350
                $contentInfo->id,
2351
                new SPIMetadataUpdateStruct([
2352
                    'isHidden' => false,
2353
                ])
2354
            );
2355
            $locationHandler = $this->persistenceHandler->locationHandler();
2356
            $childLocations = $locationHandler->loadLocationsByContent($contentInfo->id);
2357
            foreach ($childLocations as $childLocation) {
2358
                $locationHandler->setVisible($childLocation->id);
2359
            }
2360
            $this->repository->commit();
2361
        } catch (Exception $e) {
2362
            $this->repository->rollback();
2363
            throw $e;
2364
        }
2365
    }
2366
2367
    /**
2368
     * Instantiates a new content create struct object.
2369
     *
2370
     * alwaysAvailable is set to the ContentType's defaultAlwaysAvailable
2371
     *
2372
     * @param \eZ\Publish\API\Repository\Values\ContentType\ContentType $contentType
2373
     * @param string $mainLanguageCode
2374
     *
2375
     * @return \eZ\Publish\API\Repository\Values\Content\ContentCreateStruct
2376
     */
2377
    public function newContentCreateStruct(ContentType $contentType, $mainLanguageCode)
2378
    {
2379
        return new ContentCreateStruct(
2380
            [
2381
                'contentType' => $contentType,
2382
                'mainLanguageCode' => $mainLanguageCode,
2383
                'alwaysAvailable' => $contentType->defaultAlwaysAvailable,
2384
            ]
2385
        );
2386
    }
2387
2388
    /**
2389
     * Instantiates a new content meta data update struct.
2390
     *
2391
     * @return \eZ\Publish\API\Repository\Values\Content\ContentMetadataUpdateStruct
2392
     */
2393
    public function newContentMetadataUpdateStruct()
2394
    {
2395
        return new ContentMetadataUpdateStruct();
2396
    }
2397
2398
    /**
2399
     * Instantiates a new content update struct.
2400
     *
2401
     * @return \eZ\Publish\API\Repository\Values\Content\ContentUpdateStruct
2402
     */
2403
    public function newContentUpdateStruct()
2404
    {
2405
        return new ContentUpdateStruct();
2406
    }
2407
2408
    /**
2409
     * @param \eZ\Publish\API\Repository\Values\User\User|null $user
2410
     *
2411
     * @return \eZ\Publish\API\Repository\Values\User\UserReference
2412
     */
2413
    private function resolveUser(?User $user): UserReference
2414
    {
2415
        if ($user === null) {
2416
            $user = $this->permissionResolver->getCurrentUserReference();
2417
        }
2418
2419
        return $user;
2420
    }
2421
}
2422