Retorna/Controla a versão mais atual

@param string $url
@param int $recursiveVersion
@return int
339221
private function getLastVersion(string $url, int $recursiveVersion = 99): int
    {
        $recursiveVersion++;
        for ($idVersion = $this->backup; $idVersion > 0; $idVersion--) {
            if (!file_exists("{$url}#{$idVersion}.json")) {
                break;
            } elseif ($idVersion === 1) {
                //chegou ao limite e não encontrou vaga.
                //Rename files to remove last and free first
                for ($i = $this->backup; $i > 1; $i--) {
                    if ($i < $recursiveVersion)
                        rename("{$url}#" . ($i - 1) . ".json", "{$url}#{$i}.json");
                }
                break;
            }
        }

        return $idVersion;
    }
1009688
protected function doRawList($dir, $recursive = false)
    {
        $connection = $this->connection;

        return $this->retry(function () use ($connection, $dir, $recursive) {
            $res = @ftp_rawlist($connection, $dir, $recursive);

            if (false === $res) {
                throw new \RuntimeException("Rawlist failed: ".$dir);
            }

            $items = array();

            foreach ($res as $child) {
                $chunks = preg_split("/\s+/", $child);
                list($item['rights'], $item['number'], $item['user'], $item['group'], $item['size'], $item['month'], $item['day'], $item['time']) = $chunks;
                $item['type'] = $chunks[0]{0}
                === 'd' ? 'directory' : 'file';
                array_splice($chunks, 0, 8);
                $item['name'] = implode(" ", $chunks);
                $item['pathname'] = \rtrim($dir, '/').'/'.$item['name'];
                $items[] = $item;
            }

            return $items;
        });
    }
405028
public function getCurrentRemoteVersion(Updater $updater)
    {
        /** Switch remote request errors to HttpRequestExceptions */
        set_error_handler(array($updater, 'throwHttpRequestException'));
        $version = get_contents($this->getVersionUrl());
        restore_error_handler();
        if (false === $version) {
            throw new HttpRequestException(sprintf(
                'Request to URL failed: %s', $this->getVersionUrl()
            ));
        }
        if (empty($version)) {
            throw new HttpRequestException(
                'Version request returned empty response.'
            );
        }
        if (!preg_match('%^[a-z0-9]{40}%', $version, $matches)) {
            throw new HttpRequestException(
                'Version request returned incorrectly formatted response.'
            );
        }

        return $matches[0];
    }
765930
public function generateDefaultOccurrences(CalendarEventVersion $version)
    {
        $repetitions = $version->getRepetitionEntityCollection();
        $query = $this->entityManager->createQuery('delete from calendar:CalendarEventVersionOccurrence o where o.version = :version');
        $query->setParameter('version', $version);
        $query->execute();

        foreach($repetitions as $repetitionEntity) {

            $repetition = $repetitionEntity->getRepetitionObject();

            $start = $repetition->getStartDateTimestamp() - 1;

            $datetime = new \DateTime('+5 years', $repetition->getTimezone());
            $end = $datetime->getTimestamp();

            $this->occurrenceFactory->generateOccurrences($version, $repetitionEntity, $start, $end);
        }
    }
1098430
public function setPath($path, $recursive = true)
    {
        if (!is_string($path) || preg_match(NodeInterface::MATCH_PATTERN_PATH, $path) !== 1) {
            throw new \InvalidArgumentException('Invalid path "' . $path . '" (a path must be a valid string, be absolute (starting with a slash) and contain only the allowed characters).', 1284369857);
        }

        if ($path === $this->path) {
            return;
        }

        if ($recursive === true) {
            foreach ($this->getChildNodeData() as $childNodeData) {
                $childNodeData->setPath(NodePaths::addNodePathSegment($path, $childNodeData->getName()));
            }
        }

        $pathBeforeChange = $this->path;

        $this->path = $path;
        $this->calculatePathHash();
        $this->parentPath = NodePaths::getParentPath($path);
        $this->calculateParentPathHash();
        $this->depth = NodePaths::getPathDepth($path);

        if ($pathBeforeChange !== null) {
            // this method is called both for changing the path AND in the constructor of Node; so we only want to do
            // these things below if called OUTSIDE a constructor.
            $this->emitNodePathChanged($this);
            $this->addOrUpdate();
        }
    }
1355398
public function activate($versionNumber, $oldVersionNumber = '')
    {
        $runtimeManager = $this->framework->getRuntimeManager();
        $runtimeManager->addEventHandler('\\Zepi\\Turbo\\Event\\FinalizeOutput', '\\Zepi\\Core\\Defaults\\EventHandler\\DefaultOutputRenderer', 9999);
        $runtimeManager->addEventHandler('\\Zepi\\Turbo\\Event\\RouteNotFound', '\\Zepi\\Core\\Defaults\\EventHandler\\DefaultRouteNotFound', 9999);
    }
144841
public function changeOwner( $userName, $recursive = FALSE )
	{
		if( !$userName )
			throw new InvalidArgumentException( 'User missing' );
		$number	= (int) chown( $this->folderName, $userName );

		if( !$recursive )
			return $number;
		$iterator = new RecursiveIteratorIterator(
			new RecursiveDirectoryIterator( $this->folderName ),
			RecursiveIteratorIterator::SELF_FIRST
		);
		foreach( $iterator as $item )
			$number += (int) chown( $item, $userName );
		return $number;
	}
371892
public static function toObject($resource, $recursive = false) {
        if (static::isObject($resource)) {
            if (!$recursive) {
                return $resource;
            }

        } else if (static::isArray($resource)) {
            // Continue

        } else if (static::isJson($resource)) {
            $resource = json_decode($resource, true);

        } else if (static::isSerialized($resource)) {
            $resource = unserialize($resource);

        } else if (static::isXml($resource)) {
            $resource = static::xmlToArray(simplexml_load_string($resource));
        }

        return static::buildObject($resource);
    }
1194677
public function traverse(Link $url = null)
    {
        if ($url === null) {            
            $url = $this->baseUrl;
        }
                
        $this->links[$url->getAbsoluteUrl(false)] = $url;        
        $this->traverseSingle($url, 0);

        for($depth=1; $depth< $this->maxDepth; $depth++){ 
            $this->log(LogLevel::DEBUG, "crwaling in depth#".$depth);
            if(!isset($this->childrenByDepth[$depth])){
                $this->log(LogLevel::INFO, "skipping level#".$depth." no items found");
                continue;
            }
            
            $count=1;                        
            foreach($this->childrenByDepth[$depth] as $parentUrl => $parentChilds){                
                $this->log(LogLevel::DEBUG, '('.$count."/".count($this->childrenByDepth[$depth]).") crawling links of ".$parentUrl. ' count of links '.count($parentChilds));
                $parentLink = $this->links[$parentUrl];
                foreach($parentChilds as $childUrl){
                    $childLink = new Link($childUrl,$parentLink);
                    $this->traverseSingle($childLink, $depth);
                }
                $count++;
            }
            
        }
        
        return $this;
    }
396363
public function setRewrittenUrl($locale, $url)
    {
        $currentUrl = $this->getRewrittenUrl($locale);
        if ($currentUrl == $url || null === $url) {
            /* no url update */

            return $this;
        }

        try {
            $resolver = new RewritingResolver($url);

            /* we can reassign old url */
            if (null === $resolver->redirectedToUrl) {
                /* else ... */
                if ($resolver->view == $this->getRewrittenUrlViewName() && $resolver->viewId == $this->getId()) {
                    /* it's an url related to the current object */

                    if ($resolver->locale != $locale) {
                        /* it is an url related to this product for another locale */
                        throw new UrlRewritingException(Translator::getInstance()->trans('URL_ALREADY_EXISTS'), UrlRewritingException::URL_ALREADY_EXISTS);
                    }

                    if (\count($resolver->otherParameters) > 0) {
                        /* it is an url related to this product but with more arguments */
                        throw new UrlRewritingException(Translator::getInstance()->trans('URL_ALREADY_EXISTS'), UrlRewritingException::URL_ALREADY_EXISTS);
                    }

                    /* here it must be a deprecated url */
                } else {
                    /* already related to another object */
                    throw new UrlRewritingException(Translator::getInstance()->trans('URL_ALREADY_EXISTS'), UrlRewritingException::URL_ALREADY_EXISTS);
                }
            }
        } catch (UrlRewritingException $e) {
            /* It's all good if URL is not found */
            if ($e->getCode() !== UrlRewritingException::URL_NOT_FOUND) {
                throw $e;
            }
        }

        /* set the new URL */
        if (isset($resolver)) {
            /* erase the old one */
            $rewritingUrl = RewritingUrlQuery::create()->findOneByUrl($url);
            $rewritingUrl->setView($this->getRewrittenUrlViewName())
                ->setViewId($this->getId())
                ->setViewLocale($locale)
                ->setRedirected(null)
                ->save()
            ;

            /* erase additional arguments if any : only happens in case it erases a deprecated url */
            RewritingArgumentQuery::create()->filterByRewritingUrl($rewritingUrl)->deleteAll();
        } else {
            /* just create it */
            $rewritingUrl = new RewritingUrl();
            $rewritingUrl->setUrl($url)
                ->setView($this->getRewrittenUrlViewName())
                ->setViewId($this->getId())
                ->setViewLocale($locale)
                ->save()
            ;
        }

        /* deprecate the old one if needed */
        if (null !== $oldRewritingUrl = RewritingUrlQuery::create()->findOneByUrl($currentUrl)) {
            $oldRewritingUrl->setRedirected($rewritingUrl->getId())->save();
        }

        return $this;
    }
1336971
public static function rowCount(String $file = '/', Bool $recursive = true) : Int
    {
        $file = self::rpath($file);

        if( ! file_exists($file) )
        {
            throw new Exception\FileNotFoundException(NULL, $file);
        }

        if( is_file($file) )
        {
            return count( file($file) );
        }
        elseif( is_dir($file) )
        {
            $files = FileList::allFiles($file, $recursive);

            $rowCount = 0;

            foreach( $files as $f )
            {
                if( is_file($f) )
                {
                    $rowCount += count( file($f) );
                }
            }

            return $rowCount;
        }
        else
        {
            return false;
        }
    }
669431
public function getExtReference($url)
    {
        $path = parse_url($url, PHP_URL_PATH);
        if ($path === false) {
            throw new \InvalidArgumentException(sprintf('URL %s', $url));
        }

        $id = null;
        $collection = null;

        if (!isset($this->resolvingCache[$path])) {
            foreach ($this->router->getRouteCollection()->all() as $route) {
                list($collection, $id) = $this->getDataFromRoute($route, $path);
                if ($collection !== null && $id !== null) {
                    $this->resolvingCache[$path] = $route;
                    return ExtReference::create($collection, $id);
                }
            }
        } else {
            list($collection, $id) = $this->getDataFromRoute($this->resolvingCache[$path], $path);
            return ExtReference::create($collection, $id);
        }

        throw new \InvalidArgumentException(sprintf('Could not read URL %s', $url));
    }
97026
public static function getVersionForNumber(int $versionNumber) : self
    {
        if ($versionNumber < 1 || $versionNumber > 40) {
            throw new InvalidArgumentException('Version number must be between 1 and 40');
        }

        return self::versions()[$versionNumber - 1];
    }
200160
public static function getLinkCount($url = false)
    {
        $data = static::getCols('2048', $url);
        return (parent::noDataDefaultValue() == $data) ? $data :
            $data['uid'];
    }
1260549
public function current()
  {
    // Work around pre-PHP 5.5 issue that prevents `empty($this->count())`:
    if (!isset($this->_objects)) {
      $this->_loadFrom($this->_href);
    }

    if ($this->_position >= sizeof($this->_objects)) {
      if (isset($this->_links['next'])) {
        $this->_loadFrom($this->_links['next']);
        $this->_position = 0;
      }
      else if (empty($this->_objects) && ($this->_position == 0)) {
        return null;
      }
      else {
        throw new Recurly_Error("Pager is not in a valid state");
      }
    }

    return $this->_objects[$this->_position];
  }
65898
public function listed(string $url, $returnType = false)
    {
        if (empty($this->apiKey)) {
            throw new Exception('A Google Safebrowsing API key has not been specified');
        }

        // Retrieve the result from SafeBrowsing
        $result = $this->getSafebrowsingResult($url);

        // Check for exististance of the supplied URL in any matches
        if (is_object($result) and isset($result->matches)) {
            foreach ($result->matches as $match) {
                if ($match->threat->url == $url) {
                    // Return the Threat Type if requested,
                    // otherwise return true
                    if ($returnType) {
                        return $match->threatType;
                    }
                    
                    return true;
                }
            }
        }

        return false;
    }
1092803
function reroute($url=NULL,$permanent=FALSE,$die=TRUE) {
		if (!$url)
			$url=$this->hive['REALM'];
		if (is_array($url))
			$url=call_user_func_array([$this,'alias'],$url);
		elseif (preg_match('/^(?:@?([^\/()?]+)(?:(\(.+?)\))*(\?.+)*)/',
			$url,$parts) &&
			isset($this->hive['ALIASES'][$parts[1]]))
			$url=$this->hive['ALIASES'][$parts[1]];
		$url=$this->build($url,isset($parts[2])?$this->parse($parts[2]):[]).
			(isset($parts[3])?$parts[3]:'');
		if (($handler=$this->hive['ONREROUTE']) &&
			$this->call($handler,[$url,$permanent,$die])!==FALSE)
			return;
		if ($url[0]!='/' && !preg_match('/^\w+:\/\//i',$url))
			$url='/'.$url;
		if ($url[0]=='/' && (empty($url[1]) || $url[1]!='/')) {
			$port=$this->hive['PORT'];
			$port=in_array($port,[80,443])?'':(':'.$port);
			$url=$this->hive['SCHEME'].'://'.
				$this->hive['HOST'].$port.$this->hive['BASE'].$url;
		}
		if ($this->hive['CLI'])
			$this->mock('GET '.$url.' [cli]');
		else {
			header('Location: '.$url);
			$this->status($permanent?301:302);
			if ($die)
				die;
		}
	}