Process file dispersion.

@param string $finalTarget

@return string
@throws \Xloit\Bridge\Zend\Filter\Exception\NoSuchDirectoryException
772883
protected function fileDispersion($finalTarget)
    {
        if (strpos($finalTarget, DIRECTORY_SEPARATOR . 'original_image' . DIRECTORY_SEPARATOR) !== false) {
            return $finalTarget;
        }
        if ($this->isFileDispersionEnabled()) {
            $file           = pathinfo($finalTarget, PATHINFO_BASENAME);
            $dispersionPath = $this->getDispersionPath($file);
            $directory      = pathinfo($finalTarget, PATHINFO_DIRNAME) . $dispersionPath;
            $finalTarget    = $directory . $file;

            $this->setTargetDirectory($directory);
            $this->createFolders();
        }

        return $finalTarget;
    }
1317547
public function get($targetName)
    {
        if (InstallTarget::DEFAULT_TARGET === $targetName) {
            return $this->getDefaultTarget();
        }

        if (!isset($this->targets[$targetName])) {
            throw NoSuchTargetException::forTargetName($targetName);
        }

        return $this->targets[$targetName];
    }
1351630
private function getDispersionPath($fileName)
    {
        $char           = 0;
        $dispersionPath = DIRECTORY_SEPARATOR . 'original_image' . DIRECTORY_SEPARATOR;

        while ($char < 2 && $char < strlen($fileName)) {
            /** @noinspection IsEmptyFunctionUsageInspection */
            if (empty($dispersionPath)) {
                $dispersionPath = DIRECTORY_SEPARATOR . ('.' === $fileName[$char] ? '_' : $fileName[$char]);
            } else {
                $dispersionPath =
                    $this->addDirectorySeparator($dispersionPath) . ('.' === $fileName[$char] ? '_' : $fileName[$char]);
            }

            $char++;
        }

        return $dispersionPath . DIRECTORY_SEPARATOR;
    }
197337
public function finalReviewStepAction()
    {
        $request = $this->getCurrentRequest();
        $basket = $this->get('sonata.basket');

        $violations = $this
            ->get('validator')
            ->validate($basket, ['elements', 'delivery', 'payment']);

        if ($violations->count() > 0) {
            // basket not valid

            // todo : add flash message rendering in template
            foreach ($violations as $violation) {
                $this->get('session')->getFlashBag()->add('error', 'Error: '.$violation->getMessage());
            }

            return new RedirectResponse($this->generateUrl('sonata_basket_index'));
        }

        if ('POST' === $request->getMethod()) {
            if ($request->get('tac')) {
                // send the basket to the payment callback
                return $this->forward('SonataPaymentBundle:Payment:sendbank');
            }
        }

        $this->get('sonata.seo.page')->setTitle($this->get('translator')->trans('basket_review_title', [], 'SonataBasketBundle'));

        return $this->render('SonataBasketBundle:Basket:final_review_step.html.twig', [
            'basket' => $basket,
            'tac_error' => 'POST' === $request->getMethod(),
        ]);
    }
593084
protected function replaceLinkTargets($processedContent)
    {
        $noOpenerString = $this->fusionValue('setNoOpener') ? ' rel="noopener"' : '';
        $externalLinkTarget = trim($this->fusionValue('externalLinkTarget'));
        $resourceLinkTarget = trim($this->fusionValue('resourceLinkTarget'));
        if ($externalLinkTarget === '' && $resourceLinkTarget === '') {
            return $processedContent;
        }
        $controllerContext = $this->runtime->getControllerContext();
        $host = $controllerContext->getRequest()->getHttpRequest()->getUri()->getHost();
        $processedContent = preg_replace_callback(
            '~<a .*?href="(.*?)".*?>~i',
            function ($matches) use ($externalLinkTarget, $resourceLinkTarget, $host, $noOpenerString) {
                list($linkText, $linkHref) = $matches;
                $uriHost = parse_url($linkHref, PHP_URL_HOST);
                $target = null;
                if ($externalLinkTarget !== '' && is_string($uriHost) && $uriHost !== $host) {
                    $target = $externalLinkTarget;
                }
                if ($resourceLinkTarget !== '' && strpos($linkHref, '_Resources') !== false) {
                    $target = $resourceLinkTarget;
                }
                if ($target === null) {
                    return $linkText;
                }
                if (preg_match_all('~target="(.*?)~i', $linkText, $targetMatches)) {
                    return preg_replace('/target=".*?"/', sprintf('target="%s"%s', $target, $target === '_blank' ? $noOpenerString : ''), $linkText);
                }
                return str_replace('<a', sprintf('<a target="%s"%s', $target, $target === '_blank' ? $noOpenerString : ''), $linkText);
            },
            $processedContent
        );
        return $processedContent;
    }
1121705
public function pollStatusIterator($finalizeResponse)
    {
        $iterations = 0;
        while ($iterations < self::MAX_POLLING_ITERATIONS) {
            $delay = $iterations == 0 ? 0 : self::POLLING_IDLE_TIME;
            yield $this->pollStatusAsync(['items' => $finalizeResponse['importId']], $delay);
            $iterations++;
        }
    }
997041
public function getTargetDirectory(): string
    {
        $directoryName = $this->getRootRelatedPath($this->getFactorySpecificConfig()['directory']);

        $this->assertDirectoryIsWriteable($directoryName);

        return $directoryName;
    }
816445
public function gets($length = 0)
	{
		if (!$this->fh)
		{
			throw new FilesystemException('File not open');
		}

		// Capture PHP errors
		$php_errormsg = 'Error Unknown';
		$trackErrors  = ini_get('track_errors');
		ini_set('track_errors', true);

		switch ($this->processingmethod)
		{
			case 'gz':
				$res = $length ? gzgets($this->fh, $length) : gzgets($this->fh);

				break;

			case 'bz':
			case 'f':
			default:
				$res = $length ? fgets($this->fh, $length) : fgets($this->fh);

				break;
		}

		// Restore error tracking to what it was before
		ini_set('track_errors', $trackErrors);

		if (!$res)
		{
			throw new FilesystemException($php_errormsg);
		}

		// Return the result
		return $res;
	}
81382
public static function directoryDiff($source, $target)
    {
        $sourceFiles = self::globr($source, '*');
        $targetFiles = self::globr($target, '*');

        $sourceFiles = array_map(function ($file) use ($source) {
            return str_replace($source, '', $file);
        }, $sourceFiles);

        $targetFiles = array_map(function ($file) use ($target) {
            return str_replace($target, '', $file);
        }, $targetFiles);

        $diff = array_diff($targetFiles, $sourceFiles);

        return array_values($diff);
    }
965423
protected function fixCaseInsensitiveFilename($finalTarget)
    {
        $targetFile = basename($finalTarget);

        if ($this->isCaseInsensitiveFilename()) {
            $finalTarget = str_replace(
                $targetFile, StringUtils::lower($targetFile), $finalTarget
            );
        }

        return $finalTarget;
    }
542873
static function RedirectRelative($target, $noExit = false)
    {
        session_write_close();
        $dirName =  dirname($_SERVER["PHP_SELF"]);
        if ($dirName == "/")
            $dirName = "";
        header("Location: " .  "http://" . $_SERVER["HTTP_HOST"]
            . $dirName
            . "/" .  $target);
        if (!$noExit)
        {
            exit();
        }
    }
595064
protected function doExecute()
    {
        $root = $this->io->getArgument(0, WINDWALKER_ROOT . '/src');

        $dirs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root));

        $count = 0;

        foreach ($dirs as $file) {
            /** @var $file \SplFileInfo */
            if (!$file->isFile() || $file->getExtension() != 'php') {
                continue;
            }

            $content = file_get_contents($file);

            $length = strlen($content);

            $lastChar = $content[$length - 1];

            if ($lastChar == "\n") {
                continue;
            }

            $count++;

            $this->out('Add new line to: ' . $file);

            switch ($lastChar) {
                case ' ' :
                    $content = substr($content, 0, -1);
                    break;

                case '}' :
                    $content .= "\n";
                    break;
            }

            file_put_contents($file, $content);
        }

        if ($count) {
            $this->out($count . ' files add new line.');
        } else {
            $this->out('No file found.');
        }
    }
478643
public function finalize($finalize)
    {
        switch ($this->query['type']) {
            case Query::TYPE_MAP_REDUCE:
                $this->query['mapReduce']['options']['finalize'] = $finalize;
                break;

            case Query::TYPE_GROUP:
                $this->query['group']['options']['finalize'] = $finalize;
                break;

            default:
                throw new BadMethodCallException('mapReduce(), map() or group() must be called before finalize()');
        }

        return $this;
    }
909822
public function process(ContainerBuilder $container)
    {
        if ($container->hasDefinition('webit_shipment.serializer.model_handler')) {
            $locator = $container->getDefinition('jms_serializer.metadata.file_locator');
            $dirs = $locator->getArgument(0);
            $dirs['Webit\Shipment'] = '%kernel.root_dir%/../vendor/webit/shipment/src/Resources/serializer';
            $locator->replaceArgument(0, $dirs);
        }
    }
225167
public function process($filename, $actualFileName)
    {
        // Check if the processing should be done
        if(!$this->shouldProcess($filename))
        {
            // No need to process the file, so bypass
            return $this->getFinalName($filename);
        }
        
        // Otherwise write the file and return the new file name
        return $this->write(Compiler::compile(file_get_contents($filename)), $actualFileName);
    }
829046
protected function resolveLinkDetailsFromLinkTarget(string $redirectTarget): array
    {
        // build the target URL, take force SSL into account etc.
        $linkService = GeneralUtility::makeInstance(LinkService::class);
        try {
            $linkDetails = $linkService->resolve($redirectTarget);
            switch ($linkDetails['type']) {
                case LinkService::TYPE_URL:
                    // all set up, nothing to do
                    break;
                case LinkService::TYPE_FILE:
                    /** @var File $file */
                    $file = $linkDetails['file'];
                    if ($file instanceof File) {
                        $linkDetails['url'] = $file->getPublicUrl();
                    }
                    break;
                case LinkService::TYPE_FOLDER:
                    /** @var Folder $folder */
                    $folder = $linkDetails['folder'];
                    if ($folder instanceof Folder) {
                        $linkDetails['url'] = $folder->getPublicUrl();
                    }
                    break;
                default:
                    // we have to return the link details without having a "URL" parameter

            }
        } catch (InvalidPathException $e) {
            return [];
        }
        return $linkDetails;
    }
617205
public static function lastModifiedFolder($path)
    {
        $last_modified = 0;

        /** @var UniformResourceLocator $locator */
        $locator = Grav::instance()['locator'];
        $flags = \RecursiveDirectoryIterator::SKIP_DOTS;
        if ($locator->isStream($path)) {
            $directory = $locator->getRecursiveIterator($path, $flags);
        } else {
            $directory = new \RecursiveDirectoryIterator($path, $flags);
        }
        $filter  = new RecursiveFolderFilterIterator($directory);
        $iterator = new \RecursiveIteratorIterator($filter, \RecursiveIteratorIterator::SELF_FIRST);

        /** @var \RecursiveDirectoryIterator $file */
        foreach ($iterator as $dir) {
            $dir_modified = $dir->getMTime();
            if ($dir_modified > $last_modified) {
                $last_modified = $dir_modified;
            }
        }

        return $last_modified;
    }