/**
  * Returns content name, translated, from a ContentInfo object.
  * By default this method uses prioritized languages, unless $forcedLanguage is provided.
  *
  * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo
  * @param string $forcedLanguage Locale we want the content name translation in (e.g. "fre-FR"). Null by default (takes current locale)
  *
  * @todo Remove ContentService usage when translated names are available in ContentInfo (see https://jira.ez.no/browse/EZP-21755)
  *
  * @return string
  */
 public function getTranslatedContentNameByContentInfo(ContentInfo $contentInfo, $forcedLanguage = null)
 {
     if (isset($forcedLanguage) && $forcedLanguage === $contentInfo->mainLanguageCode) {
         return $contentInfo->name;
     }
     return $this->getTranslatedContentName($this->contentService->loadContentByContentInfo($contentInfo), $forcedLanguage);
 }
 /**
  * Creates and prepares content create structure.
  *
  * @param array $data
  * @return \eZ\Publish\API\Repository\Values\Content\ContentCreateStruct
  */
 private function getContentCreateStruct($data)
 {
     $contentType = $this->contentTypeService->loadContentTypeByIdentifier($data['content_type']);
     $struct = $this->contentService->newContentCreateStruct($contentType, '');
     $this->fillValueObject($struct, $data, ['content_type']);
     return $struct;
 }
Ejemplo n.º 3
0
    public function previewContentAction( $contentId, $versionNo, $language, $siteAccessName = null )
    {
        try
        {
            $content = $this->contentService->loadContent( $contentId, array( $language ), $versionNo );
            $location = $this->previewHelper->getPreviewLocation( $contentId );
        }
        catch ( UnauthorizedException $e )
        {
            throw new AccessDeniedException();
        }

        if ( !$this->securityContext->isGranted( new AuthorizationAttribute( 'content', 'versionread', array( 'valueObject' => $content ) ) ) )
        {
            throw new AccessDeniedException();
        }

        $siteAccess = $this->previewHelper->getOriginalSiteAccess();
        // Only switch if $siteAccessName is set and different from original
        if ( $siteAccessName !== null && $siteAccessName !== $siteAccess->name )
        {
            $siteAccess = $this->previewHelper->changeConfigScope( $siteAccessName );
        }

        $response = $this->kernel->handle(
            $this->getForwardRequest( $location, $content, $siteAccess ),
            HttpKernelInterface::SUB_REQUEST
        );
        $response->headers->remove( 'cache-control' );
        $response->headers->remove( 'expires' );

        $this->previewHelper->restoreConfigScope();

        return $response;
    }
 /**
  * Parse input structure
  *
  * @param array $data
  * @param \eZ\Publish\Core\REST\Common\Input\ParsingDispatcher $parsingDispatcher
  *
  * @return \eZ\Publish\API\Repository\Values\Content\ContentUpdateStruct
  */
 public function parse(array $data, ParsingDispatcher $parsingDispatcher)
 {
     $contentUpdateStruct = $this->contentService->newContentUpdateStruct();
     // Missing initial language code
     if (array_key_exists('initialLanguageCode', $data)) {
         $contentUpdateStruct->initialLanguageCode = $data['initialLanguageCode'];
     }
     // @todo Where to set the user?
     // @todo Where to set modification date?
     if (array_key_exists('fields', $data)) {
         if (!is_array($data['fields']) || !array_key_exists('field', $data['fields']) || !is_array($data['fields']['field'])) {
             throw new Exceptions\Parser("Invalid 'fields' element for VersionUpdate.");
         }
         $contentId = $this->requestParser->parseHref($data['__url'], 'contentId');
         foreach ($data['fields']['field'] as $fieldData) {
             if (!array_key_exists('fieldDefinitionIdentifier', $fieldData)) {
                 throw new Exceptions\Parser("Missing 'fieldDefinitionIdentifier' element in field data for VersionUpdate.");
             }
             if (!array_key_exists('fieldValue', $fieldData)) {
                 throw new Exceptions\Parser("Missing 'fieldValue' element for '{$fieldData['fieldDefinitionIdentifier']}' identifier in VersionUpdate.");
             }
             $fieldValue = $this->fieldTypeParser->parseFieldValue($contentId, $fieldData['fieldDefinitionIdentifier'], $fieldData['fieldValue']);
             $languageCode = null;
             if (array_key_exists('languageCode', $fieldData)) {
                 $languageCode = $fieldData['languageCode'];
             }
             $contentUpdateStruct->setField($fieldData['fieldDefinitionIdentifier'], $fieldValue, $languageCode);
         }
     }
     return $contentUpdateStruct;
 }
Ejemplo n.º 5
0
 /**
  * Parses the given $value for the field $fieldDefIdentifier in the content
  * identified by $contentInfoId.
  *
  * @param string $contentInfoId
  * @param string $fieldDefIdentifier
  * @param mixed $value
  *
  * @return mixed
  */
 public function parseFieldValue($contentInfoId, $fieldDefIdentifier, $value)
 {
     $contentInfo = $this->contentService->loadContentInfo($contentInfoId);
     $contentType = $this->contentTypeService->loadContentType($contentInfo->contentTypeId);
     $fieldDefinition = $contentType->getFieldDefinition($fieldDefIdentifier);
     return $this->parseValue($fieldDefinition->fieldTypeIdentifier, $value);
 }
Ejemplo n.º 6
0
 /**
  * Converts internal links (ezcontent:// and ezlocation://) to URLs.
  *
  * @param \DOMDocument $document
  *
  * @return \DOMDocument
  */
 public function convert(DOMDocument $document)
 {
     $document = clone $document;
     $xpath = new DOMXPath($document);
     $xpath->registerNamespace("docbook", "http://docbook.org/ns/docbook");
     $linkAttributeExpression = "starts-with( @xlink:href, 'ezlocation://' ) or starts-with( @xlink:href, 'ezcontent://' )";
     $xpathExpression = "//docbook:link[{$linkAttributeExpression}]|//docbook:ezlink";
     /** @var \DOMElement $link */
     foreach ($xpath->query($xpathExpression) as $link) {
         // Set resolved href to number character as a default if it can't be resolved
         $hrefResolved = "#";
         $href = $link->getAttribute("xlink:href");
         $location = null;
         preg_match("~^(.+://)?([^#]*)?(#.*|\\s*)?\$~", $href, $matches);
         list(, $scheme, $id, $fragment) = $matches;
         if ($scheme === "ezcontent://") {
             try {
                 $contentInfo = $this->contentService->loadContentInfo($id);
                 $location = $this->locationService->loadLocation($contentInfo->mainLocationId);
                 $hrefResolved = $this->urlAliasRouter->generate($location) . $fragment;
             } catch (APINotFoundException $e) {
                 if ($this->logger) {
                     $this->logger->warning("While generating links for richtext, could not locate " . "Content object with ID " . $id);
                 }
             } catch (APIUnauthorizedException $e) {
                 if ($this->logger) {
                     $this->logger->notice("While generating links for richtext, unauthorized to load " . "Content object with ID " . $id);
                 }
             }
         } else {
             if ($scheme === "ezlocation://") {
                 try {
                     $location = $this->locationService->loadLocation($id);
                     $hrefResolved = $this->urlAliasRouter->generate($location) . $fragment;
                 } catch (APINotFoundException $e) {
                     if ($this->logger) {
                         $this->logger->warning("While generating links for richtext, could not locate " . "Location with ID " . $id);
                     }
                 } catch (APIUnauthorizedException $e) {
                     if ($this->logger) {
                         $this->logger->notice("While generating links for richtext, unauthorized to load " . "Location with ID " . $id);
                     }
                 }
             } else {
                 $hrefResolved = $href;
             }
         }
         $hrefAttributeName = "xlink:href";
         // For embeds set the resolved href to the separate attribute
         // Original href needs to be preserved in order to generate link parameters
         // This will need to change with introduction of UrlService and removal of URL link
         // resolving in external storage
         if ($link->localName === "ezlink") {
             $hrefAttributeName = "href_resolved";
         }
         $link->setAttribute($hrefAttributeName, $hrefResolved);
     }
     return $document;
 }
 protected function setUp()
 {
     parent::setUp();
     $this->matcherFactoryMock = $this->getMock('eZ\\Publish\\Core\\MVC\\Symfony\\Matcher\\MatcherFactoryInterface');
     $this->configResolverMock = $this->getMock('eZ\\Publish\\Core\\MVC\\ConfigResolverInterface');
     $this->contentServiceMock = $this->getMock('eZ\\Publish\\API\\Repository\\ContentService');
     $this->contentServiceMock->expects($this->any())->method('loadContentByContentInfo')->will($this->returnValue(new Content()));
 }
Ejemplo n.º 8
0
 public function handleAction(Request $request)
 {
     $user = $this->userService->loadUserByCredentials($request->username, $request->password);
     $this->repository->setCurrentUser($user);
     $contentCreateStruct = $this->contentProvider->newContentCreateStructFromRequest($request);
     $locationCreateStruct = $this->contentProvider->newLocationCreateStructFromRequest($request);
     $content = $this->contentService->createContent($contentCreateStruct, array($locationCreateStruct));
     $this->contentService->publishVersion($content->versionInfo);
 }
Ejemplo n.º 9
0
 /**
  * Renders the comments list for content with id $contentId
  * Comment form might also be included
  *
  * @param mixed $contentId
  */
 public function renderForContentAction( $contentId )
 {
     return new Response(
         $this->commentsRenderer->renderForContent(
             $this->contentService->loadContentInfo( $contentId ),
             $this->request
         )
     );
 }
 public function setPostCategories($postId, Request $request)
 {
     $this->login($request->request->get('username'), $request->request->get('password'));
     // @todo Replace categories instead of adding
     $contentInfo = $this->contentService->loadContentInfo($postId);
     foreach ($request->request->get('categories') as $category) {
         $this->locationService->createLocation($contentInfo, $this->locationService->newLocationCreateStruct($category['categoryId']));
     }
     return new Response(true);
 }
Ejemplo n.º 11
0
 public function findNodes(LocationQuery $query)
 {
     $searchResult = $this->searchService->findLocations($query, ['languages' => $this->prioritizedLanguages, 'useAlwaysAvailable' => $this->useAlwaysAvailable]);
     foreach ($searchResult->searchHits as $searchHit) {
         /** @var \eZ\Publish\API\Repository\Values\Content\Location $location */
         $location = $searchHit->valueObject;
         $searchHit->valueObject = $this->domainObjectMapper->mapNode($location, $this->contentService->loadContent($location->contentInfo->id, [$searchHit->matchedTranslation], $location->contentInfo->currentVersionNo), $searchHit->matchedTranslation);
     }
     return $searchResult;
 }
 /**
  * Used by the REST API to reference downloadable files.
  * It redirects (permanently) to the standard ez_content_download route, based on the language of the field
  * passed as an argument, using the language switcher.
  *
  * @param mixed $contentId
  * @param int $fieldId
  * @param \Symfony\Component\HttpFoundation\Request $request
  *
  * @return \Symfony\Component\HttpFoundation\RedirectResponse
  */
 public function redirectToContentDownloadAction($contentId, $fieldId, Request $request)
 {
     $content = $this->contentService->loadContent($contentId);
     $field = $this->findFieldInContent($fieldId, $content);
     $params = array('content' => $content, 'fieldIdentifier' => $field->fieldDefIdentifier, 'language' => $field->languageCode);
     if ($request->query->has('version')) {
         $params['version'] = $request->query->get('version');
     }
     $downloadUrl = $this->router->generate($this->routeReferenceGenerator->generate('ez_content_download', $params));
     return new RedirectResponse($downloadUrl, 301);
 }
Ejemplo n.º 13
0
 public function purgeForContent($contentId)
 {
     $contentInfo = $this->contentService->loadContentInfo($contentId);
     $event = new ContentCacheClearEvent($contentInfo);
     $this->eventDispatcher->dispatch(MVCEvents::CACHE_CLEAR_CONTENT, $event);
     $locationIds = [];
     foreach ($event->getLocationsToClear() as $location) {
         $locationIds[] = $location->id;
     }
     $this->purgeClient->purge(array_unique($locationIds));
 }
Ejemplo n.º 14
0
 /**
  * Displays the gallery.
  *
  * @param \eZ\Publish\Core\MVC\Symfony\View\ContentView $view
  * @param \Symfony\Component\HttpFoundation\Request $request
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function displayGalleryAction(ContentView $view, Request $request)
 {
     $languages = $this->configResolver->getParameter('languages');
     $location = $view->getLocation();
     $query = new Query();
     $query->query = $this->childrenCriteria->generateChildCriterion($location, $languages);
     $pager = new Pagerfanta(new ContentSearchAdapter($query, $this->searchService));
     $pager->setMaxPerPage($this->galleryImagesLimit);
     $pager->setCurrentPage($request->get('page', 1));
     $view->addParameters(['location' => $location, 'content' => $this->contentService->loadContentByContentInfo($view->getLocation()->getContentInfo()), 'images' => $pager]);
     return $view;
 }
 /**
  * {@inheritdoc}
  */
 public function purgeForContent($contentId, $locationIds = [])
 {
     $contentInfo = $this->contentService->loadContentInfo($contentId);
     // Can only gather relevant locations using ContentCacheClearEvent on published content
     if ($contentInfo->published) {
         $event = new ContentCacheClearEvent($contentInfo);
         $this->eventDispatcher->dispatch(MVCEvents::CACHE_CLEAR_CONTENT, $event);
         foreach ($event->getLocationsToClear() as $location) {
             $locationIds[] = $location->id;
         }
     }
     $this->purgeClient->purge(array_unique($locationIds));
 }
Ejemplo n.º 16
0
 /**
  * @param mixed $contentId ID of a valid Content
  * @param string $fieldIdentifier Field Definition identifier of the Field the file must be downloaded from
  * @param string $filename
  * @param \Symfony\Component\HttpFoundation\Request $request
  *
  * @return \eZ\Bundle\EzPublishIOBundle\BinaryStreamResponse
  */
 public function downloadBinaryFileAction($contentId, $fieldIdentifier, $filename, Request $request)
 {
     if ($request->query->has('version')) {
         $content = $this->contentService->loadContent($contentId, null, $request->query->get('version'));
     } else {
         $content = $this->contentService->loadContent($contentId);
     }
     $field = $this->translationHelper->getTranslatedField($content, $fieldIdentifier, $request->query->has('inLanguage') ? $request->query->get('inLanguage') : null);
     if (!$field instanceof Field) {
         throw new InvalidArgumentException("'{$fieldIdentifier}' field not present on content #{$content->contentInfo->id} '{$content->contentInfo->name}'");
     }
     $response = new BinaryStreamResponse($this->ioService->loadBinaryFile($field->value->id), $this->ioService);
     $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
     return $response;
 }
 /**
  * Returns a valid Location object for $contentId.
  * Will either load mainLocationId (if available) or build a virtual Location object.
  *
  * @param mixed $contentId
  *
  * @return \eZ\Publish\API\Repository\Values\Content\Location|null Null when content does not have location
  */
 public function getPreviewLocation($contentId)
 {
     // contentInfo must be reloaded as content is not published yet (e.g. no mainLocationId)
     $contentInfo = $this->contentService->loadContentInfo($contentId);
     // mainLocationId already exists, content has been published at least once.
     if ($contentInfo->mainLocationId) {
         $location = $this->locationService->loadLocation($contentInfo->mainLocationId);
     } else {
         // @todo In future releases this will be a full draft location when this feature
         // is implemented. Or it might return null when content does not have location,
         // but for now we can't detect that so we return a virtual draft location
         $location = new Location(array('contentInfo' => $contentInfo, 'status' => Location::STATUS_DRAFT));
     }
     return $location;
 }
Ejemplo n.º 18
0
    /**
     * Returns a valid Location object for $contentId.
     * Will either load mainLocationId (if available) or build a virtual Location object.
     *
     * @param mixed $contentId
     *
     * @return \eZ\Publish\API\Repository\Values\Content\Location|null Null when content does not have location
     */
    public function getPreviewLocation( $contentId )
    {
        // contentInfo must be reloaded as content is not published yet (e.g. no mainLocationId)
        $contentInfo = $this->contentService->loadContentInfo( $contentId );
        // mainLocationId already exists, content has been published at least once.
        if ( $contentInfo->mainLocationId )
        {
            $location = $this->locationService->loadLocation( $contentInfo->mainLocationId );
        }
        // New Content, never published, create a virtual location object.
        else
        {
            // @todo In future releases this will be a full draft location when this feature
            // is implemented. Or it might return null when content does not have location,
            // but for now we can't detect that so we return a virtual draft location
            $location = new Location(
                array(
                    // Faking using root locationId
                    'id' => $this->configResolver->getParameter( 'content.tree_root.location_id' ),
                    'contentInfo' => $contentInfo,
                    'status' => Location::STATUS_DRAFT
                )
            );
        }

        return $location;
    }
Ejemplo n.º 19
0
 /**
  * Updates object states of content
  * An object state in the input overrides the state of the object state group.
  *
  * @param $contentId
  *
  * @throws \eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException
  *
  * @return \eZ\Publish\Core\REST\Common\Values\ContentObjectStates
  */
 public function setObjectStatesForContent($contentId, Request $request)
 {
     $newObjectStates = $this->inputDispatcher->parse(new Message(array('Content-Type' => $request->headers->get('Content-Type')), $request->getContent()));
     $countByGroups = array();
     foreach ($newObjectStates as $newObjectState) {
         $groupId = (int) $newObjectState->groupId;
         if (array_key_exists($groupId, $countByGroups)) {
             ++$countByGroups[$groupId];
         } else {
             $countByGroups[$groupId] = 1;
         }
     }
     foreach ($countByGroups as $groupId => $count) {
         if ($count > 1) {
             throw new ForbiddenException("Multiple object states provided for group with ID {$groupId}");
         }
     }
     $contentInfo = $this->contentService->loadContentInfo($contentId);
     $contentObjectStates = array();
     foreach ($newObjectStates as $newObjectState) {
         $objectStateGroup = $this->objectStateService->loadObjectStateGroup($newObjectState->groupId);
         $this->objectStateService->setContentState($contentInfo, $objectStateGroup, $newObjectState->objectState);
         $contentObjectStates[(int) $objectStateGroup->id] = $newObjectState;
     }
     return new ContentObjectStates($contentObjectStates);
 }
Ejemplo n.º 20
0
 /**
  * Generates a URL for a location, from the given parameters.
  *
  * It is possible to directly pass a Location object as the route name, as the ChainRouter allows it through ChainedRouterInterface.
  *
  * If $name is a route name, the "location" key in $parameters must be set to a valid eZ\Publish\API\Repository\Values\Content\Location object.
  * "locationId" can also be provided.
  *
  * If the generator is not able to generate the url, it must throw the RouteNotFoundException
  * as documented below.
  *
  * @see UrlAliasRouter::supports()
  *
  * @param string|\eZ\Publish\API\Repository\Values\Content\Location $name The name of the route or a Location instance
  * @param mixed $parameters An array of parameters
  * @param int $referenceType The type of reference to be generated (one of the constants)
  *
  * @throws \LogicException
  * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
  * @throws \InvalidArgumentException
  *
  * @return string The generated URL
  *
  * @api
  */
 public function generate($name, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
 {
     // Direct access to Location
     if ($name instanceof Location) {
         return $this->generator->generate($name, $parameters, $referenceType);
     }
     // Normal route name
     if ($name === self::URL_ALIAS_ROUTE_NAME) {
         if (isset($parameters['location']) || isset($parameters['locationId'])) {
             // Check if location is a valid Location object
             if (isset($parameters['location']) && !$parameters['location'] instanceof Location) {
                 throw new LogicException("When generating an UrlAlias route, 'location' parameter must be a valid eZ\\Publish\\API\\Repository\\Values\\Content\\Location.");
             }
             $location = isset($parameters['location']) ? $parameters['location'] : $this->locationService->loadLocation($parameters['locationId']);
             unset($parameters['location'], $parameters['locationId'], $parameters['viewType'], $parameters['layout']);
             return $this->generator->generate($location, $parameters, $referenceType);
         }
         if (isset($parameters['contentId'])) {
             $contentInfo = $this->contentService->loadContentInfo($parameters['contentId']);
             unset($parameters['contentId'], $parameters['viewType'], $parameters['layout']);
             if (empty($contentInfo->mainLocationId)) {
                 throw new LogicException('Cannot generate an UrlAlias route for content without main location.');
             }
             return $this->generator->generate($this->locationService->loadLocation($contentInfo->mainLocationId), $parameters, $referenceType);
         }
         throw new InvalidArgumentException("When generating an UrlAlias route, either 'location', 'locationId' or 'contentId' must be provided.");
     }
     throw new RouteNotFoundException('Could not match route');
 }
Ejemplo n.º 21
0
 /**
  * Assigns the user to a user group
  *
  * @param $userId
  *
  * @throws \eZ\Publish\Core\REST\Server\Exceptions\ForbiddenException
  * @return \eZ\Publish\Core\REST\Server\Values\UserGroupRefList
  */
 public function assignUserToUserGroup($userId)
 {
     $user = $this->userService->loadUser($userId);
     try {
         $userGroupLocation = $this->locationService->loadLocation($this->extractLocationIdFromPath($this->request->query->get('group')));
     } catch (APINotFoundException $e) {
         throw new Exceptions\ForbiddenException($e->getMessage());
     }
     try {
         $userGroup = $this->userService->loadUserGroup($userGroupLocation->contentId);
     } catch (APINotFoundException $e) {
         throw new Exceptions\ForbiddenException($e->getMessage());
     }
     try {
         $this->userService->assignUserToUserGroup($user, $userGroup);
     } catch (InvalidArgumentException $e) {
         throw new Exceptions\ForbiddenException($e->getMessage());
     }
     $userGroups = $this->userService->loadUserGroupsOfUser($user);
     $restUserGroups = array();
     foreach ($userGroups as $userGroup) {
         $userGroupContentInfo = $userGroup->getVersionInfo()->getContentInfo();
         $userGroupLocation = $this->locationService->loadLocation($userGroupContentInfo->mainLocationId);
         $contentType = $this->contentTypeService->loadContentType($userGroupContentInfo->contentTypeId);
         $restUserGroups[] = new Values\RestUserGroup($userGroup, $contentType, $userGroupContentInfo, $userGroupLocation, $this->contentService->loadRelations($userGroup->getVersionInfo()));
     }
     return new Values\UserGroupRefList($restUserGroups, $this->router->generate('ezpublish_rest_loadUserGroupsOfUser', array('userId' => $userId)), $userId);
 }
Ejemplo n.º 22
0
 /**
  * @When /^I create an edit request for this draft$/
  */
 public function iCreateAnEditRequestForThisDraft()
 {
     $url = sprintf('/content/objects/%d/versions/%d', $this->currentDraft->content->id, $this->currentDraft->content->versionInfo->versionNo);
     $this->restContext->createRequest('patch', $url);
     $this->restContext->requestObject = new VersionUpdate(['contentUpdateStruct' => $this->contentService->newContentUpdateStruct(), 'contentType' => $this->currentDraft->contentType]);
     $this->restContext->setHeaderWithObject('content-type', 'VersionUpdate');
 }
Ejemplo n.º 23
0
 /**
  * Visit struct returned by controllers.
  *
  * @param \eZ\Publish\Core\REST\Common\Output\Visitor $visitor
  * @param \eZ\Publish\Core\REST\Common\Output\Generator $generator
  * @param \eZ\Publish\Core\REST\Server\Values\RestExecutedView $data
  */
 public function visit(Visitor $visitor, Generator $generator, $data)
 {
     $generator->startObjectElement('View');
     $visitor->setHeader('Content-Type', $generator->getMediaType('View'));
     $generator->startAttribute('href', $this->router->generate('ezpublish_rest_views_load', array('viewId' => $data->identifier)));
     $generator->endAttribute('href');
     $generator->startValueElement('identifier', $data->identifier);
     $generator->endValueElement('identifier');
     // BEGIN Query
     $generator->startObjectElement('Query');
     $generator->endObjectElement('Query');
     // END Query
     // BEGIN Result
     $generator->startObjectElement('Result', 'ViewResult');
     $generator->startAttribute('href', $this->router->generate('ezpublish_rest_views_load_results', array('viewId' => $data->identifier)));
     $generator->endAttribute('href');
     // BEGIN Result metadata
     $generator->startValueElement('count', $data->searchResults->totalCount);
     $generator->endValueElement('count');
     $generator->startValueElement('time', $data->searchResults->time);
     $generator->endValueElement('time');
     $generator->startValueElement('timedOut', $generator->serializeBool($data->searchResults->timedOut));
     $generator->endValueElement('timedOut');
     $generator->startValueElement('maxScore', $data->searchResults->maxScore);
     $generator->endValueElement('maxScore');
     // END Result metadata
     // BEGIN searchHits
     $generator->startHashElement('searchHits');
     $generator->startList('searchHit');
     foreach ($data->searchResults->searchHits as $searchHit) {
         $generator->startObjectElement('searchHit');
         $generator->startAttribute('score', 0);
         $generator->endAttribute('score');
         $generator->startAttribute('index', 0);
         $generator->endAttribute('index');
         $generator->startObjectElement('value');
         // @todo Refactor
         if ($searchHit->valueObject instanceof ApiValues\Content) {
             /** @var \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo */
             $contentInfo = $searchHit->valueObject->contentInfo;
             $valueObject = new RestContentValue($contentInfo, $this->locationService->loadLocation($contentInfo->mainLocationId), $searchHit->valueObject, $this->contentTypeService->loadContentType($contentInfo->contentTypeId), $this->contentService->loadRelations($searchHit->valueObject->getVersionInfo()));
         } elseif ($searchHit->valueObject instanceof ApiValues\Location) {
             $valueObject = $searchHit->valueObject;
         } elseif ($searchHit->valueObject instanceof ApiValues\ContentInfo) {
             $valueObject = new RestContentValue($searchHit->valueObject);
         } else {
             throw new Exceptions\InvalidArgumentException('Unhandled object type');
         }
         $visitor->visitValueObject($valueObject);
         $generator->endObjectElement('value');
         $generator->endObjectElement('searchHit');
     }
     $generator->endList('searchHit');
     $generator->endHashElement('searchHits');
     // END searchHits
     $generator->endObjectElement('Result');
     // END Result
     $generator->endObjectElement('View');
 }
Ejemplo n.º 24
0
 /**
  * Converts internal links (eznode:// and ezobject://) to URLs.
  *
  * @param \DOMDocument $xmlDoc
  *
  * @return string|null
  */
 public function convert(DOMDocument $xmlDoc)
 {
     $xpath = new DOMXPath($xmlDoc);
     $elements = $xpath->query('//link|//embed|//embed-inline');
     /** @var \DOMElement $element */
     foreach ($elements as $element) {
         $location = null;
         if ($this->elementHasAttribute($element, 'object_id')) {
             try {
                 $contentInfo = $this->contentService->loadContentInfo($this->getElementAttribute($element, 'object_id'));
                 $location = $this->locationService->loadLocation($contentInfo->mainLocationId);
             } catch (APINotFoundException $e) {
                 if ($this->logger) {
                     $this->logger->warning('While generating links for xmltext, could not locate ' . 'Content object with ID ' . $this->getElementAttribute($element, 'object_id'));
                 }
             } catch (APIUnauthorizedException $e) {
                 if ($this->logger) {
                     $this->logger->notice('While generating links for xmltext, unauthorized to load ' . 'Content object with ID ' . $this->getElementAttribute($element, 'object_id'));
                 }
             }
         }
         if ($this->elementHasAttribute($element, 'node_id')) {
             try {
                 $location = $this->locationService->loadLocation($this->getElementAttribute($element, 'node_id'));
             } catch (APINotFoundException $e) {
                 if ($this->logger) {
                     $this->logger->warning('While generating links for xmltext, could not locate ' . 'Location with ID ' . $this->getElementAttribute($element, 'node_id'));
                 }
             } catch (APIUnauthorizedException $e) {
                 if ($this->logger) {
                     $this->logger->notice('While generating links for xmltext, unauthorized to load ' . 'Location with ID ' . $this->getElementAttribute($element, 'node_id'));
                 }
             }
         }
         if ($location !== null) {
             $element->setAttribute('url', $this->urlAliasRouter->generate($location));
         }
         // Copy temporary URL if it exists and is not set at this point
         if (!$element->hasAttribute('url') && $element->hasAttribute(EmbedLinking::TEMP_PREFIX . 'url')) {
             $element->setAttribute('url', $element->getAttribute(EmbedLinking::TEMP_PREFIX . 'url'));
         }
         if ($this->elementHasAttribute($element, 'anchor_name')) {
             $element->setAttribute('url', $element->getAttribute('url') . '#' . $this->getElementAttribute($element, 'anchor_name'));
         }
     }
 }
 /**
  * Loads the main location for $contentId.
  *
  * If the content does not have a location (yet), but has a Location draft, it is returned instead.
  * Location drafts do not have an id (it is set to null), and can be tested using the isDraft() method.
  *
  * If the content doesn't have a location nor a location draft, null is returned.
  *
  * @param mixed $contentId
  *
  * @return \eZ\Publish\API\Repository\Values\Content\Location|null
  */
 public function loadMainLocation($contentId)
 {
     $location = null;
     $contentInfo = $this->contentService->loadContentInfo($contentId);
     // mainLocationId already exists, content has been published at least once.
     if ($contentInfo->mainLocationId) {
         $location = $this->locationService->loadLocation($contentInfo->mainLocationId);
     } elseif (!$contentInfo->published) {
         // New Content, never published, create a virtual location object.
         // In cases content is missing locations this will return empty array
         $parentLocations = $this->locationHandler->loadParentLocationsForDraftContent($contentInfo->id);
         if (empty($parentLocations)) {
             return null;
         }
         $location = new Location(array('contentInfo' => $contentInfo, 'status' => Location::STATUS_DRAFT, 'parentLocationId' => $parentLocations[0]->id, 'depth' => $parentLocations[0]->depth + 1, 'pathString' => $parentLocations[0]->pathString . '/x'));
     }
     return $location;
 }
Ejemplo n.º 26
0
 /**
  * Returns Site Node object for the given Repository $location.
  *
  * @throws \Netgen\EzPlatformSiteApi\Core\Site\Exceptions\TranslationNotMatchedException
  *
  * @param \eZ\Publish\API\Repository\Values\Content\Location $location
  *
  * @return \Netgen\EzPlatformSiteApi\API\Values\Node
  */
 private function getSiteNode(APILocation $location)
 {
     $versionInfo = $this->contentService->loadVersionInfoById($location->contentInfo->id);
     $languageCode = $this->getLanguage($versionInfo->languageCodes, $versionInfo->contentInfo->mainLanguageCode, $versionInfo->contentInfo->alwaysAvailable);
     if ($languageCode === null) {
         throw new TranslationNotMatchedException($versionInfo->contentInfo->id, $this->getContext($versionInfo));
     }
     return $this->domainObjectMapper->mapNode($location, $this->contentService->loadContent($location->contentInfo->id, [$languageCode], $location->contentInfo->currentVersionNo), $languageCode);
 }
Ejemplo n.º 27
0
 /**
  * Loads all locations for content object.
  *
  * @param mixed $contentId
  *
  * @return \eZ\Publish\Core\REST\Server\Values\LocationList
  */
 public function loadLocationsForContent($contentId, Request $request)
 {
     $restLocations = array();
     $contentInfo = $this->contentService->loadContentInfo($contentId);
     foreach ($this->locationService->loadLocations($contentInfo) as $location) {
         $restLocations[] = new Values\RestLocation($location, $this->locationService->getLocationChildCount($location));
     }
     return new Values\CachedValue(new Values\LocationList($restLocations, $request->getPathInfo()), array('locationId' => $contentInfo->mainLocationId));
 }
Ejemplo n.º 28
0
 public function testGetTranslatedNameByContentInfoForcedLanguageMainLanguage()
 {
     $name = 'Name in main language';
     $mainLanguage = 'eng-GB';
     $contentInfo = new ContentInfo(array('id' => 123, 'mainLanguageCode' => $mainLanguage, 'name' => $name));
     $this->configResolver->expects($this->never())->method('getParameter');
     $this->contentService->expects($this->never())->method('loadContentByContentInfo');
     $this->assertSame($name, $this->translationHelper->getTranslatedContentNameByContentInfo($contentInfo, $mainLanguage));
 }
Ejemplo n.º 29
0
 /**
  * Parse input structure.
  *
  * @param array $data
  * @param \eZ\Publish\Core\REST\Common\Input\ParsingDispatcher $parsingDispatcher
  *
  * @return \eZ\Publish\Core\REST\Server\Values\RestUserGroupUpdateStruct
  */
 public function parse(array $data, ParsingDispatcher $parsingDispatcher)
 {
     $parsedData = array();
     if (array_key_exists('mainLanguageCode', $data)) {
         $parsedData['mainLanguageCode'] = $data['mainLanguageCode'];
     }
     if (array_key_exists('Section', $data) && is_array($data['Section'])) {
         if (!array_key_exists('_href', $data['Section'])) {
             throw new Exceptions\Parser("Missing '_href' attribute for Section element in UserGroupUpdate.");
         }
         $parsedData['sectionId'] = $this->requestParser->parseHref($data['Section']['_href'], 'sectionId');
     }
     if (array_key_exists('remoteId', $data)) {
         $parsedData['remoteId'] = $data['remoteId'];
     }
     if (array_key_exists('fields', $data)) {
         $groupLocationParts = explode('/', $this->requestParser->parseHref($data['__url'], 'groupPath'));
         $groupLocation = $this->locationService->loadLocation(array_pop($groupLocationParts));
         if (!is_array($data['fields']) || !array_key_exists('field', $data['fields']) || !is_array($data['fields']['field'])) {
             throw new Exceptions\Parser("Invalid 'fields' element for UserGroupUpdate.");
         }
         $parsedData['fields'] = array();
         foreach ($data['fields']['field'] as $fieldData) {
             if (!array_key_exists('fieldDefinitionIdentifier', $fieldData)) {
                 throw new Exceptions\Parser("Missing 'fieldDefinitionIdentifier' element in field data for UserGroupUpdate.");
             }
             if (!array_key_exists('fieldValue', $fieldData)) {
                 throw new Exceptions\Parser("Missing 'fieldValue' element for '{$fieldData['fieldDefinitionIdentifier']}' identifier in UserGroupUpdate.");
             }
             $fieldValue = $this->fieldTypeParser->parseFieldValue($groupLocation->contentId, $fieldData['fieldDefinitionIdentifier'], $fieldData['fieldValue']);
             $languageCode = null;
             if (array_key_exists('languageCode', $fieldData)) {
                 $languageCode = $fieldData['languageCode'];
             }
             $parsedData['fields'][$fieldData['fieldDefinitionIdentifier']] = array('fieldValue' => $fieldValue, 'languageCode' => $languageCode);
         }
     }
     $userGroupUpdateStruct = $this->userService->newUserGroupUpdateStruct();
     if (!empty($parsedData)) {
         if (array_key_exists('mainLanguageCode', $parsedData) || array_key_exists('remoteId', $parsedData)) {
             $userGroupUpdateStruct->contentMetadataUpdateStruct = $this->contentService->newContentMetadataUpdateStruct();
             if (array_key_exists('mainLanguageCode', $parsedData)) {
                 $userGroupUpdateStruct->contentMetadataUpdateStruct->mainLanguageCode = $parsedData['mainLanguageCode'];
             }
             if (array_key_exists('remoteId', $parsedData)) {
                 $userGroupUpdateStruct->contentMetadataUpdateStruct->remoteId = $parsedData['remoteId'];
             }
         }
         if (array_key_exists('fields', $parsedData)) {
             $userGroupUpdateStruct->contentUpdateStruct = $this->contentService->newContentUpdateStruct();
             foreach ($parsedData['fields'] as $fieldDefinitionIdentifier => $fieldValue) {
                 $userGroupUpdateStruct->contentUpdateStruct->setField($fieldDefinitionIdentifier, $fieldValue['fieldValue'], $fieldValue['languageCode']);
             }
         }
     }
     return new RestUserGroupUpdateStruct($userGroupUpdateStruct, array_key_exists('sectionId', $parsedData) ? $parsedData['sectionId'] : null);
 }
 /**
  * Gets ContentType ID based on $contentId.
  *
  * @param mixed $contentId
  *
  * @return int|null
  */
 protected function getContentTypeId($contentId)
 {
     $contentTypeId = null;
     try {
         $contentTypeId = $this->contentService->loadContentInfo($contentId)->contentTypeId;
     } catch (\Exception $e) {
     }
     return $contentTypeId;
 }