Create content policy.

@param  \Illuminate\Contracts\Auth\Authenticatable  $user
@param  \Orchestra\Story\Model\Content  $content

@return bool
192561
public function create(Authenticatable $user, Content $content)
    {
        $type = $content->getAttribute('type');

        return $this->can("create {$type}") || $this->can("manage {$type}");
    }
1266651
protected function prepareTpl(&$content)
    {
        $this->modx->loadClass('modParser', '', false, true);
        $parser = new Parser($this->modx);
        $this->modx->toPlaceholders($this->profile);
        $this->modx->toPlaceholders($this->request->args());
        $parser->processElementTags('', $content);
    }
431440
protected function getContentTypeUserPermissions($contentTypeSlug, $user = null)
    {
        if ($user === null) {
            return $this->app['permissions']->getContentTypePermissions();
        }

        return $this->app['permissions']->getContentTypeUserPermissions($contentTypeSlug, $user);
    }
994917
public function mapContent(Content $content)
    {
        $locations = $this->locationHandler->loadLocationsByContent($content->versionInfo->contentInfo->id);
        $section = $this->sectionHandler->load($content->versionInfo->contentInfo->sectionId);
        $mainLocation = null;
        $locationDocuments = array();
        foreach ($locations as $location) {
            $locationDocuments[] = $this->mapContentLocation($location, $content);
        }

        // UserGroups and Users are Content, but permissions cascade is achieved through
        // Locations hierarchy. We index all ancestor Location Content ids of all
        // Locations of an owner.
        $ancestorLocationsContentIds = $this->getAncestorLocationsContentIds(
            $content->versionInfo->contentInfo->ownerId
        );
        // Add owner user id as it can also be considered as user group.
        $ancestorLocationsContentIds[] = $content->versionInfo->contentInfo->ownerId;

        $fields = array(
            new Field(
                'id',
                $content->versionInfo->contentInfo->id,
                new FieldType\IdentifierField()
            ),
            new Field(
                'type',
                $content->versionInfo->contentInfo->contentTypeId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'version',
                $content->versionInfo->versionNo,
                new FieldType\IdentifierField()
            ),
            new Field(
                'status',
                $content->versionInfo->status,
                new FieldType\IdentifierField()
            ),
            new Field(
                'name',
                $content->versionInfo->contentInfo->name,
                new FieldType\StringField()
            ),
            new Field(
                'creator',
                $content->versionInfo->creatorId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'owner',
                $content->versionInfo->contentInfo->ownerId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'owner_user_group',
                $ancestorLocationsContentIds,
                new FieldType\MultipleIdentifierField()
            ),
            new Field(
                'section',
                $content->versionInfo->contentInfo->sectionId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'section_identifier',
                $section->identifier,
                new FieldType\IdentifierField()
            ),
            new Field(
                'section_name',
                $section->name,
                new FieldType\StringField()
            ),
            new Field(
                'remote_id',
                $content->versionInfo->contentInfo->remoteId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'modified',
                $content->versionInfo->contentInfo->modificationDate,
                new FieldType\DateField()
            ),
            new Field(
                'published',
                $content->versionInfo->contentInfo->publicationDate,
                new FieldType\DateField()
            ),
            new Field(
                'language_code',
                array_keys($content->versionInfo->names),
                new FieldType\MultipleStringField()
            ),
            new Field(
                'always_available',
                $content->versionInfo->contentInfo->alwaysAvailable,
                new FieldType\BooleanField()
            ),
            new Field(
                'locations',
                $locationDocuments,
                new FieldType\DocumentField()
            ),
        );

        $contentType = $this->contentTypeHandler->load($content->versionInfo->contentInfo->contentTypeId);
        $fields[] = new Field(
            'group',
            $contentType->groupIds,
            new FieldType\MultipleIdentifierField()
        );
        $fields[] = new Field(
            'fields',
            $this->mapFields($content, $contentType),
            new FieldType\DocumentField()
        );

        $fields[] = new Field(
            'object_state',
            $this->getObjectStateIds($content->versionInfo->contentInfo->id),
            new FieldType\MultipleIdentifierField()
        );

        $document = new Document(
            array(
                'id' => $content->versionInfo->contentInfo->id,
                'type' => 'content',
                'fields' => $fields,
            )
        );

        return $document;
    }
1071650
protected function createResponse($content = '', $statusCode = 200, $contentType = 'application/json')
    {
        if ('' === $content && 'application/json' === $contentType) {
            $content = '{}';
        }

        $response = new Response($content, $statusCode);
        $response->headers->set('Content-Type', $contentType);

        return $response;
    }
1187729
public function loadContent($contentId, Request $request)
    {
        $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);

        $mainLocation = null;
        if (!empty($contentInfo->mainLocationId)) {
            $mainLocation = $this->repository->getLocationService()->loadLocation($contentInfo->mainLocationId);
        }

        $contentType = $this->repository->getContentTypeService()->loadContentType($contentInfo->contentTypeId);

        $contentVersion = null;
        $relations = null;
        if ($this->getMediaType($request) === 'application/vnd.ez.api.content') {
            $languages = Language::ALL;
            if ($request->query->has('languages')) {
                $languages = explode(',', $request->query->get('languages'));
            }

            $contentVersion = $this->repository->getContentService()->loadContent($contentId, $languages);
            $relations = $this->repository->getContentService()->loadRelations($contentVersion->getVersionInfo());
        }

        $restContent = new Values\RestContent(
            $contentInfo,
            $mainLocation,
            $contentVersion,
            $contentType,
            $relations,
            $request->getPathInfo()
        );

        if ($contentInfo->mainLocationId === null) {
            return $restContent;
        }

        return new Values\CachedValue(
            $restContent,
            array('locationId' => $contentInfo->mainLocationId)
        );
    }
567334
public function import($content, User $user)
    {
        $content = str_replace('xmlns=', 'ns=', $content); // For getting something from the \SimpleXMLElement
        $xml = new \SimpleXMLElement($content);

        $portfolio = $this->retrievePortfolioFromXml($xml, $user);

        return $portfolio;
    }
1043681
public function isContentStatusTransitionAllowed($fromStatus, $toStatus, $user, $contenttype, $contentid = null)
    {
        $perm = $this->getContentStatusTransitionPermission($fromStatus, $toStatus);
        if ($perm === null) {
            // Bypass permission check if no actual transition is to happen
            return true;
        }

        return $this->isAllowed($perm, $user, $contenttype, $contentid);
    }
640405
public static function createFromContent(
        string $content,
        ?InternetMediaTypeInterface $contentType = null
    ): WebResourceInterface {
        $className = get_called_class();

        return new $className(WebResourceProperties::create([
            WebResourceProperties::ARG_CONTENT => $content,
            WebResourceProperties::ARG_CONTENT_TYPE => $contentType,
        ]));
    }
1308710
private function getAuthor(ApiContent $contentValue, ApiContentType $contentType)
    {
        $author = $contentValue->getFieldValue(
            $this->value->getConfiguredFieldIdentifier('author', $contentType)
        );

        if (null === $author) {
            try {
                $ownerId = empty($contentValue->contentInfo->ownerId) ? $this->defaultAuthorId : $contentValue->contentInfo->ownerId;
                $userContentInfo = $this->contentService->loadContentInfo($ownerId);
                $author = $userContentInfo->name;
            } catch (UnauthorizedException $e) {
                $author = '';
            }
        }

        return (string) $author;
    }
318526
public function action(Content $content, ContentType $contentType, $duplicate)
    {
        $contentTypeSlug = $contentType['slug'];
        $new = $content->getId() === null ?: false;
        $oldStatus = $content->getStatus();
        $allStatuses = ['published', 'held', 'draft', 'timed'];
        $allowedStatuses = [];

        foreach ($allStatuses as $status) {
            if ($this->users->isContentStatusTransitionAllowed($oldStatus, $status, $contentTypeSlug, $content->getId())) {
                $allowedStatuses[] = $status;
            }
        }

        // For duplicating a record, clear base field values.
        if ($duplicate) {
            $content->setId('');
            $content->setSlug('');
            $content->setDatecreated('');
            $content->setDatepublish('');
            $content->setDatedepublish(null);
            $content->setDatechanged('');
            $content->setUsername('');
            $content->setOwnerid('');

            $this->loggerFlash->info(Trans::__('contenttypes.generic.duplicated-finalize', ['%contenttype%' => $contentTypeSlug]));
        }

        // Set the users and the current owner of this content.
        if ($new || $duplicate) {
            // For brand-new and duplicated items, the creator becomes the owner.
            $contentowner = $this->users->getCurrentUser();
        } else {
            // For existing items, we'll just keep the current owner.
            $contentowner = $this->users->getUser($content->getOwnerid());
        }

        // Build list of incoming non inverted related records.
        $incomingNotInverted = [];
        $count = 0;
        $limit = $this->config->get('general/compatibility/incoming_relations_limit', false);
        foreach ($content->getRelation()->incoming($content) as $relation) {
            /** @var Relations $relation */
            if ($relation->isInverted()) {
                continue;
            }
            $fromContentType = $relation->getFromContenttype();

            if ($this->query) {
                $this->em->setQueryService($this->query);
            }
            $record = $this->em->getContent($fromContentType . '/' . $relation->getFromId());

            if ($record) {
                $incomingNotInverted[$fromContentType][] = $record;
            }

            // Do not try to load more than X records or db will fail
            ++$count;
            if ($limit && $count > $limit) {
                break;
            }
        }

        /** @var Content $templateFieldsEntity */
        $templateFieldsEntity = $content->getTemplatefields();
        $templateFields = [];
        if ($templateFieldsEntity instanceof TemplateFields) {
            /** @var ContentType $templateFieldsContentType */
            $templateFieldsContentType = $templateFieldsEntity->getContenttype();
            $templateFields = $templateFieldsContentType->getFields();
            $templateFieldsContentType['fields'] = $templateFields;
        }

        // Temporary choice option resolver. Will be removed with Forms work circa Bolt 3.5.
        $choiceResolver = new Resolver\Choice($this->query);

        // Intersect the set taxonomies with actually existing ones, because bogus ones are just confusing.
        $existingTaxonomies = array_intersect(array_keys($this->config->get('taxonomy')), (array) $contentType['taxonomy']);

        // Build context for Twig.
        $contextCan = [
            'upload'             => $this->users->isAllowed('files:uploads'),
            'publish'            => $this->users->isAllowed('contenttype:' . $contentTypeSlug . ':publish:' . $content->getId()),
            'depublish'          => $this->users->isAllowed('contenttype:' . $contentTypeSlug . ':depublish:' . $content->getId()),
            'change_ownership'   => $this->users->isAllowed('contenttype:' . $contentTypeSlug . ':change-ownership:' . $content->getId()),
        ];
        $contextHas = [
            'incoming_relations' => count($incomingNotInverted) > 0,
            'relations'          => isset($contentType['relations']),
            'tabs'               => $contentType['groups'] !== [],
            'taxonomy'           => $existingTaxonomies !== [],
            'templatefields'     => count($templateFields) > 0,
        ];
        $contextValues = [
            'datepublish'        => $this->getPublishingDate($content->getDatepublish(), true),
            'datedepublish'      => $this->getPublishingDate($content->getDatedepublish()),
            'select_choices'     => $choiceResolver->get($contentType, (array) $templateFields),
        ];
        $context = [
            'incoming_not_inv' => $incomingNotInverted,
            'contenttype'      => $contentType,
            'content'          => $content,
            'allowed_status'   => $allowedStatuses,
            'contentowner'     => $contentowner,
            'duplicate'        => $duplicate,
            'fields'           => $this->config->fields->fields(),
            'fieldtemplates'   => $this->getTemplateFieldTemplates($contentType, $content),
            'fieldtypes'       => $this->getUsedFieldtypes($contentType, $content, $contextHas),
            'templatefields'   => $templateFields,
            'groups'           => $this->createGroupTabs($contentType, $contextHas),
            'can'              => $contextCan,
            'has'              => $contextHas,
            'values'           => $contextValues,
            'relations_list'   => $this->getRelationsList($contentType),
        ];

        return $context;
    }
12318
private function mapUserToVersion(User $user, Request $request)
    {
        $content = $this->repository->getContentService()->loadContent($user->id);
        $request->headers->set('Url', $request->getPathInfo());

        return new Version(
            $content,
            $this->repository->getContentTypeService()->loadContentType($content->contentInfo->contentTypeId),
            $this->repository->getContentService()->loadRelations($content->getVersionInfo()),
            $request->getPathInfo()
        );
    }
615528
public static function createFromContent(
        string $content,
        ?InternetMediaTypeInterface $contentType = null,
        ?string $type = null
    ): WebResourceInterface {
        $className = get_called_class();

        return new $className(SitemapProperties::create([
            SitemapProperties::ARG_CONTENT => $content,
            SitemapProperties::ARG_CONTENT_TYPE => $contentType,
            SitemapProperties::ARG_TYPE => $type,
        ]));
    }
1043648
public function setOwner(ContentInterface $owner = null)
    {
        if ($owner instanceof Content) {
            $this->content = $owner;
        } elseif ($owner instanceof Template) {
            $this->template = $owner;
        } elseif ($owner === null) {
            $this->template = null;
            $this->content = null;
        } else {
            throw new \Exception(sprintf('BlockInterface owner can only be of type Content or Template, not the provided %s type.', get_class($owner)));
        }

        return $this;
    }
700525
public function addContent(string $content, string $contentType, ?string $charset = null): Message
    {
        $charset = $charset ?: $this->getCharset();

        $this->content[] = [
            'content'      => $content,
            'content_type' => $contentType,
            'charset'      => $charset
        ];

        return $this;
    }
929406
public function setContent($content)
    {
        if (!$json = json_encode($content)) {
            $this->setResponseCode(self::HTTP_INTERNAL_SERVER_ERROR);
            $json = json_encode(['status' => 'error', 'error_message' => json_last_error_msg()]);
        }

        $this->content = $json;

        return $this;
    }
937782
public function createExistingFieldsInNewVersion(Content $content)
    {
        foreach ($content->fields as $field) {
            $this->createExistingFieldInNewVersion($field, $content);
        }
    }