Пример #1
0
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $session = $this->get('phpcr.session');
     $file = $input->getArgument('file');
     $pretty = $input->getOption('pretty');
     $exportDocument = $input->getOption('document');
     $dialog = $this->get('helper.question');
     if (file_exists($file)) {
         $confirmed = true;
         if (false === $input->getOption('no-interaction')) {
             $confirmed = $dialog->ask($input, $output, new ConfirmationQuestion('File already exists, overwrite?'));
         }
         if (false === $confirmed) {
             return;
         }
     }
     $stream = fopen($file, 'w');
     $absPath = $input->getArgument('absPath');
     PathHelper::assertValidAbsolutePath($absPath);
     if (true === $exportDocument) {
         $session->exportDocumentView($absPath, $stream, $input->getOption('skip-binary'), $input->getOption('no-recurse'));
     } else {
         $session->exportSystemView($absPath, $stream, $input->getOption('skip-binary'), $input->getOption('no-recurse'));
     }
     fclose($stream);
     if ($pretty) {
         $xml = new \DOMDocument(1.0);
         $xml->load($file);
         $xml->preserveWhitespace = true;
         $xml->formatOutput = true;
         $xml->save($file);
     }
 }
 public function preFlush(ManagerEventArgs $args)
 {
     if (empty($this->stack)) {
         return;
     }
     $metadataFactory = $args->getObjectManager()->getMetadataFactory();
     foreach ($this->stack as $data) {
         $children = $data['children'];
         $ctMetadata = $data['ct_metadata'];
         $childrenField = $data['field'];
         $index = 0;
         foreach ($children as $child) {
             $childMetadata = $metadataFactory->getMetadataFor(ClassUtils::getRealClass(get_class($child)));
             $expectedId = $this->encoder->encode($childrenField, $index++);
             $identifier = $childMetadata->getIdentifierValue($child);
             $idGenerator = $childMetadata->idGenerator;
             if ($idGenerator !== ClassMetadata::GENERATOR_TYPE_ASSIGNED) {
                 throw new \InvalidArgumentException(sprintf('Currently, all documents which belong to a mapped collection must use the ' . 'assigned ID generator strategy, "%s" is using "%s".', $childMetadata->getName(), $idGenerator));
             }
             if (!$identifier || PathHelper::getNodeName($identifier) !== $expectedId) {
                 throw new \InvalidArgumentException(sprintf('Child mapped to content type "%s" on field "%s" has an unexpected ID "%s". ' . 'It is currently necessary to envoke the CollectionIdentifierUpdater on all ' . 'documents (at least those which have collections) before they are persisted.', $ctMetadata->getType(), $childrenField, $identifier));
             }
         }
     }
 }
 private function doSerializeResource(Resource $resource, $depth = 0)
 {
     $data = array();
     $repositoryAlias = $this->registry->getRepositoryAlias($resource->getRepository());
     $data['repository_alias'] = $repositoryAlias;
     $data['repository_type'] = $this->registry->getRepositoryType($resource->getRepository());
     $data['payload_alias'] = $this->payloadAliasRegistry->getPayloadAlias($resource);
     $data['payload_type'] = null;
     if ($resource instanceof CmfResource) {
         $data['payload_type'] = $resource->getPayloadType();
     }
     $data['path'] = $resource->getPath();
     $data['label'] = $data['node_name'] = PathHelper::getNodeName($data['path']);
     $data['repository_path'] = $resource->getRepositoryPath();
     $enhancers = $this->enhancerRegistry->getEnhancers($repositoryAlias);
     $children = array();
     foreach ($resource->listChildren() as $name => $childResource) {
         $children[$name] = array();
         if ($depth < 2) {
             $children[$name] = $this->doSerializeResource($childResource, $depth + 1);
         }
     }
     $data['children'] = $children;
     if ($resource instanceof BodyResource) {
         $data['body'] = $resource->getBody();
     }
     foreach ($enhancers as $enhancer) {
         $data = $enhancer->enhance($data, $resource);
     }
     return $data;
 }
 /**
  * @param PersistEvent $event
  *
  * @throws DocumentManagerException
  */
 public function handlePersist(PersistEvent $event)
 {
     $options = $event->getOptions();
     $this->validateOptions($options);
     $document = $event->getDocument();
     $parentPath = null;
     $nodeName = null;
     if ($options['path']) {
         $parentPath = PathHelper::getParentPath($options['path']);
         $nodeName = PathHelper::getNodeName($options['path']);
     }
     if ($options['parent_path']) {
         $parentPath = $options['parent_path'];
     }
     if ($parentPath) {
         $event->setParentNode($this->resolveParent($parentPath, $options));
     }
     if ($options['node_name']) {
         if (!$event->hasParentNode()) {
             throw new DocumentManagerException(sprintf('The "node_name" option can only be used either with the "parent_path" option ' . 'or when a parent node has been established by a previous subscriber. ' . 'When persisting document: %s', DocumentHelper::getDebugTitle($document)));
         }
         $nodeName = $options['node_name'];
     }
     if (!$nodeName) {
         return;
     }
     if ($event->hasNode()) {
         $this->renameNode($event->getNode(), $nodeName);
         return;
     }
     $node = $this->strategy->createNodeForDocument($document, $event->getParentNode(), $nodeName);
     $event->setNode($node);
 }
Пример #5
0
 public function setRouteRoot($routeRoot)
 {
     // make limitation on base path work
     parent::setRootPath($routeRoot);
     // TODO: fix widget to show root node when root is selectable
     // https://github.com/sonata-project/SonataDoctrinePhpcrAdminBundle/issues/148
     $this->routeRoot = PathHelper::getParentPath($routeRoot);
 }
Пример #6
0
 /**
  * {@inheritdoc}
  */
 public function mapPathToId($path, $rootPath = null)
 {
     // The path is being the id
     $id = PathHelper::absolutizePath($path, '/');
     if (is_string($rootPath) && 0 !== strpos($id, $rootPath)) {
         throw new \OutOfBoundsException(sprintf('The path "%s" is out of the root path "%s" were the file system is located.', $path, $rootPath));
     }
     return $id;
 }
Пример #7
0
 /**
  * @param string $path
  *
  * @return Route
  */
 protected function createRoute($path)
 {
     $parentPath = PathHelper::getParentPath($path);
     $parent = $this->getDm()->find(null, $parentPath);
     $name = PathHelper::getNodeName($path);
     $route = new Route();
     $route->setPosition($parent, $name);
     $this->getDm()->persist($route);
     $this->getDm()->flush();
     return $route;
 }
Пример #8
0
 public function removeProperty($workspace, $path)
 {
     $propertyName = PathHelper::getNodeName($path);
     $nodePath = PathHelper::getParentPath($path);
     $node = $this->nodeReader->readNode($workspace, $nodePath);
     $property = $node->getProperty($propertyName);
     if (in_array($property['type'], array('Reference', 'WeakReference'))) {
         $this->index->deindexReferrer($node->getPropertyValue(Storage::INTERNAL_UUID), $propertyName, $property['type'] === 'Reference' ? false : true);
     }
     $node->removeProperty($propertyName);
     $this->nodeWriter->writeNode($workspace, $nodePath, $node);
 }
 /**
  * Finds the parent route document by concatenating the basepaths with the
  * requested path.
  *
  * @return null|object
  */
 protected function findParentRoute($requestedPath)
 {
     $manager = $this->getManagerForClass('Symfony\\Cmf\\Bundle\\RoutingBundle\\Doctrine\\Phpcr\\Route');
     $parentPaths = array();
     foreach ($this->routeBasePaths as $basepath) {
         $parentPaths[] = PathHelper::getParentPath($basepath . $requestedPath);
     }
     $parentRoutes = $manager->findMany(null, $parentPaths);
     if (0 === count($parentRoutes)) {
         return;
     }
     return $parentRoutes->first();
 }
 /**
  * {@inheritdoc}
  */
 public function create(Request $request)
 {
     $routes = array();
     $manager = $this->getManagerForClass('Symfony\\Cmf\\Bundle\\RoutingBundle\\Doctrine\\Phpcr\\Route');
     $parentPath = PathHelper::getParentPath($this->routeBasePath . $request->getPathInfo());
     $parentRoute = $manager->find(null, $parentPath);
     if (!$parentRoute) {
         return $routes;
     }
     if ($parentRoute instanceof Route) {
         $routes[$parentRoute->getName()] = $parentRoute;
     }
     return $routes;
 }
Пример #11
0
 public function getNodePath($workspace, $path, $withFilename = true)
 {
     $path = PathHelper::normalizePath($path);
     if (substr($path, 0, 1) == '/') {
         $path = substr($path, 1);
     }
     if ($path) {
         $path .= '/';
     }
     $nodeRecordPath = Storage::WORKSPACE_PATH . '/' . $workspace . '/' . $path . 'node.yml';
     if ($withFilename === false) {
         $nodeRecordPath = dirname($nodeRecordPath);
     }
     return $nodeRecordPath;
 }
 protected function loadPhpcr($config, XmlFileLoader $loader, ContainerBuilder $container)
 {
     $loader->load('services-phpcr.xml');
     $loader->load('migrator-phpcr.xml');
     $prefix = $this->getAlias() . '.persistence.phpcr';
     $container->setParameter($prefix . '.basepath', $config['basepath']);
     $container->setParameter($prefix . '.menu_basepath', PathHelper::getParentPath($config['basepath']));
     if ($config['use_sonata_admin']) {
         $this->loadSonataAdmin($config, $loader, $container);
     } elseif (isset($config['sonata_admin'])) {
         throw new InvalidConfigurationException('Do not define sonata_admin options when use_sonata_admin is set to false');
     }
     $container->setParameter($prefix . '.manager_name', $config['manager_name']);
     $container->setParameter($prefix . '.document.class', $config['document_class']);
 }
Пример #13
0
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $session = $this->get('phpcr.session');
     $file = $input->getArgument('file');
     $parentAbsPath = $input->getArgument('parentAbsPath');
     $uuidBehavior = $input->getOption('uuid-behavior');
     if (!in_array($uuidBehavior, $this->uuidBehaviors)) {
         throw new \Exception(sprintf("The specified uuid behavior \"%s\" is invalid, you should use one of:\n%s", $uuidBehavior, '    - ' . implode("\n    - ", $this->uuidBehaviors)));
     }
     if (!file_exists($file)) {
         throw new \InvalidArgumentException(sprintf('The file "%s" does not exist', $file));
     }
     PathHelper::assertValidAbsolutePath($parentAbsPath);
     $uuidBehavior = constant('\\PHPCR\\ImportUUIDBehaviorInterface::IMPORT_UUID_' . strtoupper(str_replace('-', '_', $uuidBehavior)));
     $session->importXml($parentAbsPath, $file, $uuidBehavior);
 }
 private function resolveSiblingName($siblingId, NodeInterface $parentNode, NodeInterface $node)
 {
     if (null === $siblingId) {
         return;
     }
     $siblingPath = $siblingId;
     if (UUIDHelper::isUUID($siblingId)) {
         $siblingPath = $this->nodeManager->find($siblingId)->getPath();
     }
     if ($siblingPath !== null && PathHelper::getParentPath($siblingPath) !== $parentNode->getPath()) {
         throw new DocumentManagerException(sprintf('Cannot reorder documents which are not siblings. Trying to reorder "%s" to "%s"', $node->getPath(), $siblingPath));
     }
     if (null !== $siblingPath) {
         return PathHelper::getNodeName($siblingPath);
     }
     return $node->getName();
 }
Пример #15
0
 /**
  * {@inheritDoc}
  */
 public function init(ManagerRegistry $registry)
 {
     /** @var $dm DocumentManager */
     $dm = $registry->getManagerForClass('Symfony\\Cmf\\Bundle\\SimpleCmsBundle\\Doctrine\\Phpcr\\Page');
     if ($dm->find(null, $this->basePath)) {
         return;
     }
     $session = $dm->getPhpcrSession();
     NodeHelper::createPath($session, PathHelper::getParentPath($this->basePath));
     $page = new $this->documentClass();
     $page->setId($this->basePath);
     $page->setLabel('Home');
     $page->setTitle('Homepage');
     $page->setBody('Autocreated Homepage');
     $dm->persist($page);
     $dm->flush();
 }
Пример #16
0
 /**
  * {@inheritdoc}
  */
 public function getRouteCollectionForRequest(Request $request)
 {
     $collection = new RouteCollection();
     $path = $request->getPathInfo();
     $prefix = $this->requestAnalyzer->getResourceLocatorPrefix();
     if (!empty($prefix) && strpos($path, $prefix) === 0) {
         $path = PathHelper::relativizePath($path, $prefix);
     }
     $route = $this->findRouteByPath($path, $request->getLocale());
     if ($route && array_key_exists($route->getId(), $this->symfonyRouteCache)) {
         $collection->add(self::ROUTE_PREFIX . $route->getId(), $this->symfonyRouteCache[$route->getId()]);
         return $collection;
     }
     if (!$route || !$this->routeDefaultsProvider->supports($route->getEntityClass()) || !$this->routeDefaultsProvider->isPublished($route->getEntityClass(), $route->getEntityId(), $route->getLocale())) {
         return $collection;
     }
     $collection->add(self::ROUTE_PREFIX . $route->getId(), $this->createRoute($route, $request));
     return $collection;
 }
 /**
  * {@inheritdoc}
  */
 public function init(ManagerRegistry $registry)
 {
     /** @var $dm DocumentManager */
     $dm = $registry->getManagerForClass('AppBundle\\Document\\SeoPage');
     if ($dm->find(null, $this->basePath)) {
         return;
     }
     $session = $dm->getPhpcrSession();
     NodeHelper::createPath($session, PathHelper::getParentPath($this->basePath));
     /** @var \AppBundle\Document\SeoPage $page */
     $page = new $this->documentClass();
     $page->setId($this->basePath);
     $page->setLabel('Home');
     $page->setTitle('Homepage');
     $page->setBody('Autocreated Homepage');
     $page->setIsVisibleForSitemap(true);
     $dm->persist($page);
     $dm->flush();
 }
Пример #18
0
 /**
  * {@inheritDoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $helper = $this->getPhpcrHelper();
     $session = $this->getPhpcrSession();
     $path = $input->getArgument('path');
     $type = $input->getOption('type');
     $dump = $input->getOption('dump');
     $setProp = $input->getOption('set-prop');
     $removeProp = $input->getOption('remove-prop');
     $addMixins = $input->getOption('add-mixin');
     $removeMixins = $input->getOption('remove-mixin');
     try {
         $node = $session->getNode($path);
     } catch (PathNotFoundException $e) {
         $node = null;
     }
     if ($node) {
         $nodeType = $node->getPrimaryNodeType()->getName();
         $output->writeln(sprintf('<info>Node at path </info>%s <info>already exists and has primary type</info> %s.', $path, $nodeType));
         if ($nodeType != $type) {
             $output->writeln(sprintf('<error>You have specified node type "%s" but the existing node is of type "%s"</error>', $type, $nodeType));
             return 1;
         }
     } else {
         $nodeName = PathHelper::getNodeName($path);
         $parentPath = PathHelper::getParentPath($path);
         try {
             $parentNode = $session->getNode($parentPath);
         } catch (PathNotFoundException $e) {
             $output->writeln(sprintf('<error>Parent path "%s" does not exist</error>', $parentPath));
             return 2;
         }
         $output->writeln(sprintf('<info>Creating node: </info> %s [%s]', $path, $type));
         $node = $parentNode->addNode($nodeName, $type);
     }
     $helper->processNode($output, $node, array('setProp' => $setProp, 'removeProp' => $removeProp, 'addMixins' => $addMixins, 'removeMixins' => $removeMixins, 'dump' => $dump));
     $session->save();
     return 0;
 }
Пример #19
0
 /**
  * Reorder $moved (child of $parent) before or after $target
  *
  * @param string $parent the id of the parent
  * @param string $moved the id of the child being moved
  * @param string $target the id of the target node
  * @param bool $before insert before or after the target
  * 
  * @return void
  */
 public function reorder($parent, $moved, $target, $before)
 {
     $parentNode = $this->session->getNode($parent);
     $targetName = PathHelper::getNodeName($target);
     if (!$before) {
         $nodesIterator = $parentNode->getNodes();
         $nodesIterator->rewind();
         while ($nodesIterator->valid()) {
             if ($nodesIterator->key() == $targetName) {
                 break;
             }
             $nodesIterator->next();
         }
         $targetName = null;
         if ($nodesIterator->valid()) {
             $nodesIterator->next();
             if ($nodesIterator->valid()) {
                 $targetName = $nodesIterator->key();
             }
         }
     }
     $parentNode->orderBefore(PathHelper::getNodeName($moved), $targetName);
     $this->session->save();
 }
Пример #20
0
 /**
  * Generates a content-tree with paths of given content array.
  *
  * @param Content[] $contents
  *
  * @return Content[]
  */
 private function generateTreeByPath(array $contents)
 {
     $childrenByPath = [];
     foreach ($contents as $content) {
         $path = PathHelper::getParentPath($content->getPath());
         if (!isset($childrenByPath[$path])) {
             $childrenByPath[$path] = [];
         }
         $order = $content['order'];
         while (isset($childrenByPath[$path][$order])) {
             ++$order;
         }
         $childrenByPath[$path][$order] = $content;
     }
     foreach ($contents as $content) {
         if (!isset($childrenByPath[$content->getPath()])) {
             continue;
         }
         ksort($childrenByPath[$content->getPath()]);
         $content->setChildren(array_values($childrenByPath[$content->getPath()]));
     }
     ksort($childrenByPath['/']);
     return array_values($childrenByPath['/']);
 }
Пример #21
0
 public function testRemoveVersion()
 {
     $doc = $this->dm->find($this->typeVersion, '/functional/versionTestObj');
     $this->dm->checkpoint($doc);
     $linearVersionHistory = $this->dm->getAllLinearVersions($doc);
     $lastVersion = end($linearVersionHistory);
     $lastVersionName = $lastVersion['name'];
     // Create a new version so that we are not trying to remove the last version
     $this->dm->checkpoint($doc);
     // Remove the version
     $version = $this->dm->findVersionByName($this->typeVersion, '/functional/versionTestObj', $lastVersionName);
     $removedVersionPath = $version->id;
     $this->dm->removeVersion($version);
     // Check it's not in the history anymore
     $this->assertFalse($this->dm->getPhpcrSession()->nodeExists(PathHelper::getParentPath($removedVersionPath)));
     return $lastVersionName;
 }
Пример #22
0
 /**
  * Executes all document insertions
  *
  * @param array $documents array of all to be inserted documents
  */
 private function executeInserts($documents)
 {
     // sort the documents to insert parents first but maintain child order
     $oids = array();
     foreach ($documents as $oid => $document) {
         if (!$this->contains($oid)) {
             continue;
         }
         $oids[$oid] = $this->getDocumentId($document);
     }
     $order = array_flip(array_values($oids));
     uasort($oids, function ($a, $b) use($order) {
         // compute the node depths
         $aCount = substr_count($a, '/');
         $bCount = substr_count($b, '/');
         // ensure that the original order is maintained for nodes with the same depth
         if ($aCount === $bCount) {
             return $order[$a] < $order[$b] ? -1 : 1;
         }
         return $aCount < $bCount ? -1 : 1;
     });
     $associationChangesets = $associationUpdates = array();
     foreach ($oids as $oid => $id) {
         $document = $documents[$oid];
         $class = $this->dm->getClassMetadata(get_class($document));
         // PHPCR does not validate nullable unless we would start to
         // generate custom node types, which we at the moment don't.
         // the ORM can delegate this validation to the relational database
         // that is using a strict schema
         foreach ($class->fieldMappings as $fieldName) {
             if (!isset($this->documentChangesets[$oid]['fields'][$fieldName]) && !$class->isNullable($fieldName) && !$this->isAutocreatedProperty($class, $fieldName)) {
                 throw new PHPCRException(sprintf('Field "%s" of class "%s" is not nullable', $fieldName, $class->name));
             }
         }
         $parentNode = $this->session->getNode(PathHelper::getParentPath($id));
         $nodename = PathHelper::getNodeName($id);
         $node = $parentNode->addNode($nodename, $class->nodeType);
         if ($class->node) {
             $this->originalData[$oid][$class->node] = $node;
         }
         if ($class->nodename) {
             $this->originalData[$oid][$class->nodename] = $nodename;
         }
         try {
             $node->addMixin('phpcr:managed');
         } catch (NoSuchNodeTypeException $e) {
             throw new PHPCRException('Register phpcr:managed node type first. See https://github.com/doctrine/phpcr-odm/wiki/Custom-node-type-phpcr:managed');
         }
         foreach ($class->mixins as $mixin) {
             $node->addMixin($mixin);
         }
         if ($class->identifier) {
             $class->setIdentifierValue($document, $id);
         }
         if ($class->node) {
             $class->reflFields[$class->node]->setValue($document, $node);
         }
         if ($class->nodename) {
             // make sure this reflects the id generator strategy generated id
             $class->reflFields[$class->nodename]->setValue($document, $node->getName());
         }
         // make sure this reflects the id generator strategy generated id
         if ($class->parentMapping && !$class->reflFields[$class->parentMapping]->getValue($document)) {
             $class->reflFields[$class->parentMapping]->setValue($document, $this->getOrCreateProxyFromNode($parentNode, $this->getCurrentLocale($document, $class)));
         }
         if ($this->writeMetadata) {
             $this->documentClassMapper->writeMetadata($this->dm, $node, $class->name);
         }
         $this->setMixins($class, $node, $document);
         $fields = isset($this->documentChangesets[$oid]['fields']) ? $this->documentChangesets[$oid]['fields'] : array();
         foreach ($fields as $fieldName => $fieldValue) {
             // Ignore translatable fields (they will be persisted by the translation strategy)
             if (in_array($fieldName, $class->translatableFields)) {
                 continue;
             }
             if (in_array($fieldName, $class->fieldMappings)) {
                 $mapping = $class->mappings[$fieldName];
                 $type = PropertyType::valueFromName($mapping['type']);
                 if (null === $fieldValue) {
                     continue;
                 }
                 if ($mapping['multivalue'] && $fieldValue) {
                     $fieldValue = (array) $fieldValue;
                     if (isset($mapping['assoc'])) {
                         $fieldValue = $this->processAssoc($node, $mapping, $fieldValue);
                     }
                 }
                 $node->setProperty($mapping['property'], $fieldValue, $type);
             } elseif (in_array($fieldName, $class->referenceMappings) || in_array($fieldName, $class->referrersMappings)) {
                 $associationUpdates[$oid] = $document;
                 //populate $associationChangesets to force executeUpdates($associationUpdates)
                 //to only update association fields
                 $data = isset($associationChangesets[$oid]['fields']) ? $associationChangesets[$oid]['fields'] : array();
                 $data[$fieldName] = array(null, $fieldValue);
                 $associationChangesets[$oid] = array('fields' => $data);
             }
         }
         $this->doSaveTranslation($document, $node, $class);
         if ($invoke = $this->eventListenersInvoker->getSubscribedSystems($class, Event::postPersist)) {
             $this->eventListenersInvoker->invoke($class, Event::postPersist, $document, new LifecycleEventArgs($document, $this->dm), $invoke);
         }
     }
     $this->documentChangesets = array_merge($this->documentChangesets, $associationChangesets);
     $this->executeUpdates($associationUpdates, false);
 }
Пример #23
0
 /**
  * Return file name
  *
  * @param  string $path file path
  * @return string
  * @author Dmitry (dio) Levashov
  **/
 protected function _basename($path)
 {
     return PathHelper::getNodeName($path);
 }
Пример #24
0
 /**
  * Set or update the path, depth, name and parent reference
  *
  * @param string  $path the new path this item lives at
  * @param boolean $move whether this item is being moved in session context
  *      and should store the current path until the next save operation.
  *
  * @private
  */
 public function setPath($path, $move = false)
 {
     if ($move && is_null($this->oldPath)) {
         try {
             $this->checkState();
         } catch (InvalidItemStateException $e) {
             // do not break if object manager tells the move to a child that was removed in backend
             return;
         }
         $this->oldPath = $this->path;
     }
     $this->path = $path;
     $this->depth = '/' === $path ? 0 : substr_count($path, '/');
     $this->name = PathHelper::getNodeName($path);
     $this->parentPath = 0 === $this->depth ? null : PathHelper::getParentPath($path);
 }
Пример #25
0
 /**
  * {@inheritDoc}
  * @throws RepositoryException when no binary data found
  */
 public function getBinaryStream($path)
 {
     $this->assertLoggedIn();
     $nodePath = PathHelper::getParentPath($path);
     $nodeId = $this->getSystemIdForNode($nodePath);
     $propertyName = PathHelper::getNodeName($path);
     $data = $this->getConnection()->fetchAll('SELECT data, idx FROM phpcr_binarydata WHERE node_id = ? AND property_name = ? AND workspace_name = ?', array($nodeId, $propertyName, $this->workspaceName));
     if (count($data) === 0) {
         throw new RepositoryException('No binary data found in stream');
     }
     $streams = array();
     foreach ($data as $row) {
         if (is_resource($row['data'])) {
             $stream = $row['data'];
         } else {
             $stream = fopen('php://memory', 'rwb+');
             fwrite($stream, $row['data']);
             rewind($stream);
         }
         $streams[] = $stream;
     }
     if (count($data) === 1) {
         // we don't know if this is a multivalue property or not.
         // TODO we should have something more efficient to know this. a flag in the database?
         // TODO use self::getProperty()->isMultiple() once implemented
         $node = $this->getNode($nodePath);
         if (!is_array($node->{':' . $propertyName})) {
             return reset($streams);
         }
     }
     return $streams;
 }
 public function addNode($workspaceName, \DOMElement $node)
 {
     $properties = $this->getAttributes($node);
     $uuid = isset($properties['jcr:uuid']['value'][0]) ? (string) $properties['jcr:uuid']['value'][0] : UUIDHelper::generateUUID();
     $this->ids[$uuid] = $id = isset($this->expectedNodes[$uuid]) ? $this->expectedNodes[$uuid] : self::$idCounter++;
     $dom = new \DOMDocument('1.0', 'UTF-8');
     $phpcrNode = $dom->createElement('sv:node');
     foreach ($this->namespaces as $namespace => $uri) {
         $phpcrNode->setAttribute('xmlns:' . $namespace, $uri);
     }
     $dom->appendChild($phpcrNode);
     foreach ($properties as $propertyName => $propertyData) {
         if ($propertyName == 'jcr:uuid') {
             continue;
         }
         if (!isset($this->jcrTypes[$propertyData['type']])) {
             throw new \InvalidArgumentException('"' . $propertyData['type'] . '" is not a valid JCR type.');
         }
         $phpcrNode->appendChild($this->createPropertyNode($workspaceName, $propertyName, $propertyData, $id, $dom, $phpcrNode));
     }
     list($parentPath, $childPath) = $this->getPath($node);
     $namespace = '';
     $name = $node->getAttributeNS($this->namespaces['sv'], 'name');
     if (count($parts = explode(':', $name, 2)) == 2) {
         list($namespace, $name) = $parts;
     }
     if ($namespace == 'jcr' && $name == 'root') {
         $id = 1;
         $childPath = '/';
         $parentPath = '';
         $name = '';
         $namespace = '';
     }
     $this->addRow('phpcr_nodes', array('id' => $id, 'path' => $childPath, 'parent' => $parentPath, 'local_name' => $name, 'namespace' => $namespace, 'workspace_name' => $workspaceName, 'identifier' => $uuid, 'type' => $properties['jcr:primaryType']['value'][0], 'props' => $dom->saveXML(), 'depth' => PathHelper::getPathDepth($childPath), 'sort_order' => $id - 2));
     return $this;
 }
Пример #27
0
    /**
     * {@inheritDoc}
     */
    public function getBinaryStream($path)
    {
        $this->assertLoggedIn();

        $nodePath = PathHelper::getParentPath($path);
        $nodeId = $this->pathExists($nodePath);
        $propertyName = PathHelper::getNodeName($path);

        $data = $this->conn->fetchAll(
            'SELECT data, idx FROM phpcr_binarydata WHERE node_id = ? AND property_name = ? AND workspace_name = ?',
            array($nodeId, $propertyName, $this->workspaceName)
        );

        $streams = array();
        foreach ($data as $row) {
            if (is_resource($row['data'])) {
                $stream = $row['data'];
            } else {
                $stream = fopen('php://memory', 'rwb+');
                fwrite($stream, $row['data']);
                rewind($stream);
            }

            $streams[] = $stream;
        }

        // TODO even a multi value field could have only one value stored
        // we need to also fetch if the property is multi valued instead of this count() check
        if (count($data) > 1) {
            return $streams;
        }

        return reset($streams);
    }
Пример #28
0
 /**
  * Check if this node name is valid. Returns null if valid, an exception otherwise.
  *
  * @param string $nodeName The node local name
  *
  * @return RepositoryException|null
  */
 public function isValidNodename($nodeName)
 {
     try {
         $parts = explode(':', $nodeName);
         if (1 > count($parts) || 2 < count($parts)) {
             return new RepositoryException("Name contains illegal characters: {$nodeName}");
         }
         if (0 === strlen($parts[0])) {
             return new RepositoryException("Name may not be empty: {$nodeName}");
         }
         PathHelper::assertValidLocalName($parts[0]);
         if (2 == count($parts)) {
             // [0] was the namespace prefix, also check the name
             PathHelper::assertValidLocalName($parts[1]);
             if (0 === strlen($parts[1])) {
                 return new RepositoryException("Local name may not be empty: {$nodeName}");
             }
         }
     } catch (RepositoryException $e) {
         return $e;
     }
     return null;
 }
Пример #29
0
 /**
  * changes path node to history node.
  *
  * @param NodeInterface    $node
  * @param SessionInterface $session
  * @param string           $absSrcPath
  * @param string           $absDestPath
  */
 private function changePathToHistory(NodeInterface $node, SessionInterface $session, $absSrcPath, $absDestPath)
 {
     // get new path node
     $relPath = str_replace($absSrcPath, '', $node->getPath());
     $newPath = PathHelper::normalizePath($absDestPath . $relPath);
     $newPathNode = $session->getNode($newPath);
     // set history to true and set content to new path
     $node->setProperty('sulu:content', $newPathNode);
     $node->setProperty('sulu:history', true);
     // get referenced history
     /** @var PropertyInterface $property */
     foreach ($node->getReferences('sulu:content') as $property) {
         $property->getParent()->setProperty('sulu:content', $newPathNode);
     }
 }
Пример #30
0
 /**
  * {@inheritDoc}
  *
  * @api
  */
 public function restore($removeExisting, $version, $absPath = null)
 {
     if ($this->objectManager->hasPendingChanges()) {
         throw new InvalidItemStateException('You may not call restore when there pending unsaved changes');
     }
     if (is_string($version)) {
         if (!is_string($absPath)) {
             throw new InvalidArgumentException('To restore version by version name you need to specify the path to the node you want to restore to this name');
         }
         $vh = $this->getVersionHistory($absPath);
         $version = $vh->getVersion($version);
         $versionPath = $version->getPath();
         $nodePath = $absPath;
     } elseif (is_array($version)) {
         // @codeCoverageIgnoreStart
         throw new NotImplementedException('TODO: implement restoring a list of versions');
         // @codeCoverageIgnoreEnd
     } elseif ($version instanceof VersionInterface && is_string($absPath)) {
         // @codeCoverageIgnoreStart
         throw new NotImplementedException('TODO: implement restoring a version to a specified path');
         // @codeCoverageIgnoreEnd
     } elseif ($version instanceof VersionInterface) {
         $versionPath = $version->getPath();
         $nodePath = $this->objectManager->getNodeByIdentifier($version->getContainingHistory()->getVersionableIdentifier())->getPath();
     } else {
         throw new InvalidArgumentException();
     }
     $this->objectManager->restore($removeExisting, $versionPath, $nodePath);
     $version->setCachedPredecessorsDirty();
     if ($history = $this->objectManager->getCachedNode(PathHelper::getParentPath($version->getPath()), 'Version\\VersionHistory')) {
         $history->notifyHistoryChanged();
     }
 }