Returns an archive with the required content.

@param array $nodes[] the nodes being exported

@throws ExportResourceException

@return array
328163
public function download(array $elements, $forceArchive = false)
    {
        $data = array();

        if (count($elements) === 0) {
            throw new ExportResourceException('No resources were selected.');
        }

        $archive = new \ZipArchive();
        $pathArch = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $this->ut->generateGuid() . '.zip';
        $archive->open($pathArch, \ZipArchive::CREATE);
        $nodes = $this->expandResources($elements);

        if (!$forceArchive && count($nodes) === 1) {
            $event = $this->dispatcher->dispatch(
                "download_{$nodes[0]->getResourceType()->getName()}",
                'DownloadResource',
                array($this->getResourceFromNode($this->getRealTarget($nodes[0])))
            );
            $extension = $event->getExtension();
            $data['name'] = empty($extension) ?
                $nodes[0]->getName() :
                $nodes[0]->getName() . '.' . $extension;
            $data['file'] = $event->getItem();
            $data['mimeType'] = $nodes[0]->getResourceType()->getName() === 'file' ?
                $nodes[0]->getMimeType():
                'text/plain';

            return $data;
        }

        if (isset($elements[0])) {
            $currentDir = $elements[0];
        } else {
            $archive->addEmptyDir($elements[0]->getName());
        }

        foreach ($nodes as $node) {
            //we only download is we can...
            if ($this->container->get('security.context')->isGranted('EXPORT', $node)) {
                $node = $this->getRealTarget($node);
                $resource = $this->getResourceFromNode($node);

                if ($resource) {
                    if (get_class($resource) === 'Claroline\CoreBundle\Entity\Resource\ResourceShortcut') {
                        $node = $resource->getTarget();
                    }

                    $filename = $this->getRelativePath($currentDir, $node) . $node->getName();
                    $resource = $this->getResourceFromNode($node);

                    //if it's a file, we may have to add the extension back in case someone removed it from the name
                    if ($node->getResourceType()->getName() === 'file') {
                        $extension = '.' . pathinfo($resource->getHashName(), PATHINFO_EXTENSION);
                        if (!preg_match("#$extension#", $filename)) $filename .= $extension;
                    }

                    if ($node->getResourceType()->getName() !== 'directory') {
                        $event = $this->dispatcher->dispatch(
                            "download_{$node->getResourceType()->getName()}",
                            'DownloadResource',
                            array($resource)
                        );

                        $obj = $event->getItem();

                        if ($obj !== null) {
                            $archive->addFile($obj, iconv(mb_detect_encoding($filename), $this->getEncoding(), $filename));
                        } else {
                             $archive->addFromString(iconv(mb_detect_encoding($filename), $this->getEncoding(), $filename), '');
                        }
                    } else {
                        $archive->addEmptyDir(iconv(mb_detect_encoding($filename), $this->getEncoding(), $filename));
                    }

                    $this->dispatcher->dispatch('log', 'Log\LogResourceExport', array($node));
                }
            }
        }

        $archive->close();
        $tmpList = $this->container->getParameter('claroline.param.platform_generated_archive_path');
        file_put_contents($tmpList, $pathArch . "\n", FILE_APPEND);
        $data['name'] = 'archive.zip';
        $data['file'] = $pathArch;
        $data['mimeType'] = 'application/zip';

        return $data;
    }
902548
public function exports(array $names)
    {
        $url = self::$base_url.'/get?'.http_build_query(['names' => $names]);

        return self::$curl->get($url);
    }
892912
public function getArchives()
    {
        $all_posts = $this->getBlogPosts();
        $years = [];
        $months = [];

        foreach ($all_posts as $post) {
            if (preg_match('/^(\d\d\d\d)-(\d\d)-/', $post->PublishDate, $match)) {
                if (empty($years[$match[1]])) {
                    $years[$match[1]] = 1;
                } else {
                    $years[$match[1]]++;
                }
                if (empty($months[$match[1] . '-' . $match[2]])) {
                    $months[$match[1] . '-' . $match[2]] = 1;
                } else {
                    $months[$match[1] . '-' . $match[2]]++;
                }
            }
        }
        $output = ArrayData::create([
            'Years' => ArrayList::create(),
            'Months' => ArrayList::create(),
        ]);
        $link_base = $this->Link() . 'archive/';

        foreach ($years as $year => $count) {
            $yr = DBYear::create();
            $yr->setValue($year);
            $cnt = DBInt::create();
            $cnt->setValue($count);
            $result = ArrayData::create([
                'Year' => $yr,
                'Count' => $cnt,
                'Link' => $link_base . $year . '/'
            ]);
            $output->Years->push($result);
        }

        foreach ($months as $month => $count) {
            $mth = DBDate::create();
            $mth->setValue($month . '-01');
            $cnt = DBInt::create();
            $cnt->setValue($count);
            $result = ArrayData::create([
                'Month' => $mth,
                'Count' => $cnt,
                'Link' => $link_base . str_replace('-', '/', $month) . '/'
            ]);
            $output->Months->push($result);
        }

        return $output;
    }
917575
public function getNodes($content)
    {
        $items = array();
        $document = $this->createDocumentFromXML($content);
        $nodes = $document->getElementsByTagName('item');
        if ($nodes->length) {
            foreach ($nodes as $node) {
                try {
                    $item = $this->create($node);
                    $items[] = $item;
                } catch (\Exception $e) {
                    throw new RuntimeException($e->getMessage());
                }
            }
        }

        return $items;
    }
861112
public static function sortNodes($nodes)
    {
        // saves node paths
        foreach ($nodes as $node) {
            if (!isset($node->__path__)) {
                $node->__path__ = Dom::_getNodePath($node);
            }
        }

        // sorts elements in the same order they appear in the document
        usort(
            $nodes,
            function ($node0, $node1) {
                $path0 = $node0->__path__;
                $path1 = $node1->__path__;
                $count0 = count($path0);
                $count1 = count($path1);
                $len = min($count0, $count1);

                for ($i = 0; $i < $len; $i++) {
                    if ($path0[$i] != $path1[$i]) {
                        return $path0[$i] > $path1[$i];
                    }
                }

                return $count0 > $count1;
            }
        );
        
        // unsets __path__
        foreach ($nodes as $node) {
            unset($node->__path__);
        }
        
        return $nodes;
    }
124473
public function getFromArray(
        array $resources
    ) {
        $root = (empty($resources[0])) ? null : $resources[0];
        $siteId = (empty($resources[1])) ? null : $resources[1];
        $pages = (empty($resources[2])) ? null : $resources[2];
        $pageType = (empty($resources[3])) ? null : $resources[3];
        $pageName = (empty($resources[4])) ? null : $resources[4];

        return $this->get(
            $root,
            $siteId,
            $pages,
            $pageType,
            $pageName
        );
    }
113773
protected function getChildren(NodeBuilder $node)
    {
        return $node
            ->arrayNode('variables')
                ->info('Variables about the servers')
                ->children()
                    ->scalarNode('directory_separator')->defaultValue('/')->end()
                    ->scalarNode('line_endings')->defaultValue("\n")->end()
                ->end()
            ->end()
            ->arrayNode('directories')
                ->info("Paths/names of folders to use on server.\nFull path of current release will be at {root_directory}/{app_directory}/{current}/{subdirectory}")
                ->children()
                    ->scalarNode('app_directory')
                        ->info("The folder the application will be deployed in.\nLeave empty to use `application_name` as your folder name")
                    ->end()
                    ->scalarNode('subdirectory')
                        ->info("If the core of your application (ie. where dependencies/migrations/etc.) need to be run is in a subdirectory, specify it there (per example 'my_subdirectory')")
                    ->end()
                    ->scalarNode('current')
                        ->info('The name of the folder containing the current release')
                        ->defaultValue('current')
                    ->end()
                    ->scalarNode('releases')
                        ->info('The name of the folder containing all past and current releases')
                        ->defaultValue('releases')
                    ->end()
                    ->scalarNode('shared')
                        ->info('The name of the folder containing files shared between releases')
                        ->defaultValue('shared')
                    ->end()
                ->end()
            ->end()
            ->enumNode('symlink')
                ->info('The way symlinks are created')
                ->values(['absolute', 'relative'])
                ->defaultValue('absolute')
            ->end()
            ->integerNode('keep_releases')
                ->info('The number of releases to keep on server at all times')
                ->min(0)
                ->defaultValue(4)
            ->end()
            ->arrayNode('shared')
                ->info('A list of folders/file to be shared between releases')
                ->example(['logs', 'public/uploads'])
                ->prototype('scalar')->end()
            ->end()
            ->arrayNode('permissions')
                ->info('Files permissions related settings')
                ->children()
                    ->arrayNode('files')
                        ->info('The folders and files to set as web writable')
                        ->example(['storage', 'public'])
                        ->prototype('scalar')->end()
                    ->end()
                    ->closureNode('callback')
                        ->info('What actions will be executed to set permissions on the folder above')
                        ->defaultValue(function ($file) {
                            return [
                                'chmod -R 755 '.$file,
                                'chmod -R g+s '.$file,
                                'chown -R www-data:www-data '.$file,
                            ];
                        })
                    ->end()
                ->end()
            ->end()
            ->scalarNode('sudo')
                ->info("Enable use of sudo for some commands\nYou can specify a sudo user by doing\n'sudo' => 'the_user'")
                ->defaultTrue()
            ->end()
            ->arrayNode('sudoed')
                ->info('An array of commands to run under sudo')
                ->defaultValue([])
                ->prototype('scalar')->end()
            ->end()
            ->booleanNode('shell')
                ->info('If enabled will force a shell to be created which is required for some tools like RVM or NVM')
                ->defaultTrue()
            ->end()
            ->arrayNode('shelled')
                ->info('An array of commands to run under shell')
                ->defaultValue(['which', 'ruby', 'npm', 'bower', 'bundle', 'grunt'])
                ->prototype('scalar')->end()
            ->end();
    }
695727
protected function getNumUnvisitedChildren(Node $node) {
    $cacheSection = $this->getRequestValue('cacheSection');
    $exportedOids = $this->cache->get($cacheSection, self::CACHE_KEY_EXPORTED_OIDS);

    $childOIDs = [];
    $mapper = $node->getMapper();
    $relations = $mapper->getRelations('child');
    foreach ($relations as $relation) {
      if ($relation->getOtherNavigability()) {
        $childValue = $node->getValue($relation->getOtherRole());
        if ($childValue != null) {
          $children = $relation->isMultiValued() ? $childValue : [$childValue];
          foreach ($children as $child) {
            $childOIDs[] = $child->getOID();
          }
        }
      }
    }
    $numUnvisitedChildren = 0;
    foreach ($childOIDs as $childOid) {
      if (!in_array($childOid->__toString(), $exportedOids)) {
        $numUnvisitedChildren++;
      }
    }
    return $numUnvisitedChildren;
  }
729270
public function export(ResourceNode $resourceNode)
    {
        /** @var DownloadResourceEvent $event */
        $event = $this->dispatcher->dispatch(
            static::eventName('export', $resourceNode), // old download
            DownloadResourceEvent::class,
            [$this->getResourceFromNode($resourceNode)]
        );

        return $event;
    }
533644
public function traverseFile(array $nodes, $filename)
    {
        // Set the correct state on each visitor
        foreach ($this->visitors as $visitor) {
            if ($visitor instanceof AbstractNodeVisitor) {
                $visitor->setFilename($filename);
            }
        }

        return $this->traverse($nodes);
    }
1367423
private function block($nodes)
    {
        $code = $this->walk($nodes, 0);
        $key = ucfirst(md5($code));

        if (!isset($this->blocks[$key])) {
            $this->blocks[$key] = sprintf($this->prepare(self::BLOCK_FUNCTION, 0), $key, $code);
        }

        return $key;
    }
602781
private function getOuterMostArrayNode(Node $node): Node
    {
        $outerMostArrayParent = $node;

        do {
            if ($node instanceof Node\Expr\Array_) {
                $outerMostArrayParent = $node;
            }
        } while ($node = $node->getAttribute(ParentConnectorVisitor::PARENT_KEY));

        return $outerMostArrayParent;
    }
586993
public function getListNodes($nodes)
    {
        $xPath = new DOMXPath($this->getDomXml());
        $nodeList = $xPath->query("//SUBMENU[@cl='" . implode("' or @cl='", $nodes) . "']");

        return ($nodeList->length) ? $nodeList : null;
    }
590161
public function getDataByItems(array $items)
    {
        $output = [];
        foreach ($items as $item) {
            try {
                $output[] = $this->getDataByItem($item);
            } catch (ExtractorException $e) {
                \common_Logger::e('ERROR on item ' . $item->getUri() . ' : ' . $e->getMessage());
            }
        }

        if (empty($output)) {
            throw new ExtractorException('No data item to export.');
        }

        return $output;
    }
473205
public function export($node, $exportType = 'full')
    {
        if (!$this->isAliasOfMasterCollection() || (($this->c instanceof Page) && $this->c->isMasterCollection())) {
            // We have the OR up here so that master collections that you have duplicated from other
            // master collections export properly.
            $blockNode = $node->addChild('block');
            $blockNode->addAttribute('type', $this->getBlockTypeHandle());
            $blockNode->addAttribute('name', $this->getBlockName());
            if ($this->getBlockFilename() != '') {
                $blockNode->addAttribute('custom-template', $this->getBlockFilename());
            }
            if ($this->overrideBlockTypeContainerSettings()) {
                $blockNode->addAttribute('custom-container-settings', $this->enableBlockContainer() ? 1 : 0);
            }
            if (($this->c instanceof Page) && $this->c->isMasterCollection()) {
                $mcBlockID = Loader::helper('validation/identifier')->getString(8);
                ContentExporter::addMasterCollectionBlockID($this, $mcBlockID);
                $blockNode->addAttribute('mc-block-id', $mcBlockID);
            }

            if ($exportType == 'full') {
                $style = $this->getCustomStyle();
                if (is_object($style)) {
                    $set = $style->getStyleSet();
                    $set->export($blockNode);
                }
                if ($this->overrideBlockTypeCacheSettings()) {
                    $settings = $this->getBlockCacheSettingsObject();
                    $blockNode['cache-output'] = $settings->cacheBlockOutput();
                    $blockNode['cache-output-lifetime'] = $settings->getBlockOutputCacheLifetime();
                    $blockNode['cache-output-on-post'] = $settings->cacheBlockOutputOnPost();
                    $blockNode['cache-output-for-registered-users'] = $settings->cacheBlockOutputForRegisteredUsers();
                }
                $bc = $this->getController();
                $bc->export($blockNode);
            }
        } else {
            $blockNode = $node->addChild('block');
            $blockNode->addAttribute('mc-block-id', ContentExporter::getMasterCollectionTemporaryBlockID($this));
        }
    }
1270203
public function transform($node)
    {
        $blocksData = $this->transformBlock($node);
        $documentData = array(
            'id' => $node->getNodeId() . '-' . $node->getLanguage(). '-' . $node->getSiteId(),
            'elementId' => $node->getId(),
            'nodeId' => $node->getNodeId(),
            'siteId' => $node->getSiteId(),
            'language' => $node->getLanguage(),
            'name' => $node->getName(),
            'blocks' => $blocksData
        );

        if (!is_null($node->getUpdatedAt())) {
            $documentData['updatedAt'] = $node->getUpdatedAt()->getTimestamp();
        }

        $document = new Document($documentData['id'], $documentData);

        return $document;
    }
610217
protected function getFirstExternalNode($node)
    {
        $nodes = func_get_args();
        foreach ($nodes as $node) {
            /** @var Node $node */
            if ($node->isLocalhost() === false) {
                return $node;
            }
        }

        return null;
    }