Check Phar

Download the remote release information for the phar version of
the library and compare it against what we currently have.

@return string Info URI.
13148
public static function check_phar() {
		// Not checking or can't check, we're done!
		if (! \BLOBCOMMON_PHAR_UPDATES ||
			(false === ($remote = static::get_release_info('Phar URI', static::PHAR_TEMPLATE)))
		) {
			return;
		}

		$current = \get_option('blob-common_installed', false);

		// Everything is current, let's get out of here!
		if (
			! $remote['date_created'] ||
			! $remote['url'] ||
			($remote['date_created'] === $current)
		) {
			return;
		}

		// Generate a unique name for the temporary download.
		$dir = \dirname(\BLOBCOMMON_PHAR_PATH) . '/';
		$file = 'blob-common.phar.new.' . \microtime(true);
		$file = \wp_unique_filename($dir, $file);

		// Download it.
		$response = \wp_remote_get($remote['url']);
		if (200 !== \wp_remote_retrieve_response_code($response)) {
			return;
		}

		// Save it.
		if (@\file_put_contents("{$dir}{$file}", \wp_remote_retrieve_body($response))) {
			@\chmod("{$dir}{$file}", \BLOBCOMMON_CHMOD_FILE);
			// Check the hash.
			if (@\md5_file("{$dir}{$file}") === $remote['checksum']) {
				// Move the file somewhere more permanent. We won't
				// actually load it until the next go around.
				@\rename("{$dir}{$file}", "{$dir}blob-common.phar.new");

				// Update the option so we don't redownload it.
				\update_option('blob-common_installed', $remote['date_created']);
			}
			// It failed; delete it.
			else {
				@\unlink("{$dir}{$file}");
			}
		}
	}
383099
public function getPackageInfo()
    {
        $fileName = $this->getConfigParam('sShopDir') . "/pkg.info";
        $rev = @file_get_contents($fileName);
        $rev = str_replace("\n", "<br>", $rev);

        if (!$rev) {
            return false;
        }

        return $rev;
    }
292304
protected function getResourceInfo()
    {
        if (($this->currentVersion !== null) &&
             (($info = \Arbit\VCSWrapper\Cache\Manager::get($this->path, $this->currentVersion, 'info')) !== false))
        {
            return $info;
        }

        $log = $this->getResourceLog();

        // Fecth for specified version, if set
        if ($this->currentVersion !== null) {
            $info = $log[$this->currentVersion];
        } else {
            $info = end($log);
        }

        $this->currentVersion = $info->version;
        \Arbit\VCSWrapper\Cache\Manager::cache($this->path, $this->currentVersion, 'info', $info);

        return $info;
    }
435174
protected function http_version()
	{
		if (strpos($this->data, "\x0A") !== false && strtoupper(substr($this->data, 0, 5)) === 'HTTP/')
		{
			$len = strspn($this->data, '0123456789.', 5);
			$this->http_version = substr($this->data, 5, $len);
			$this->position += 5 + $len;
			if (substr_count($this->http_version, '.') <= 1)
			{
				$this->http_version = (float) $this->http_version;
				$this->position += strspn($this->data, "\x09\x20", $this->position);
				$this->state = 'status';
			}
			else
			{
				$this->state = false;
			}
		}
		else
		{
			$this->state = false;
		}
	}
248980
protected static function build_update_source() {
		// We need to copy the latest version of our Phar files.
		$bin_dir = \dirname(\BOB_ROOT_DIR) . '/bin/';
		$out_dir = static::get_plugin_dir() . 'lib/';

		log::print('Copying Phar archives…');

		// TODO: add 'blob-common.phar' to the list below.
		foreach (array('test.phar') as $file) {
			if (\is_file("{$out_dir}{$file}")) {
				\unlink("{$out_dir}{$file}");
			}

			\copy("{$bin_dir}{$file}", "{$out_dir}{$file}");
			\chmod("{$out_dir}{$file}", 0644);
		}
	}
878552
public static function getVersion() {
		if (empty(self::$version)) {
			$filename = Application::get(['application', 'path_full']) . (Application::isDeployed() ? '../../../deployed' : '../../deployed');
			self::$version = filemtime($filename);
		}
		return self::$version;
	}
501086
protected function return_repo_type() {
		$arr         = [];
		$arr['type'] = $this->type->type;

		switch ( $this->type->git ) {
			case 'github':
				$arr['git']           = 'github';
				$arr['base_uri']      = 'https://api.github.com';
				$arr['base_download'] = 'https://github.com';
				break;
			case 'bitbucket':
				$arr['git'] = 'bitbucket';
				if ( empty( $this->type->enterprise ) ) {
					$arr['base_uri']      = 'https://api.bitbucket.org';
					$arr['base_download'] = 'https://bitbucket.org';
				} else {
					$arr['base_uri']      = $this->type->enterprise_api;
					$arr['base_download'] = $this->type->enterprise;
				}
				break;
			case 'gitlab':
				$arr['git']           = 'gitlab';
				$arr['base_uri']      = 'https://gitlab.com/api/v4';
				$arr['base_download'] = 'https://gitlab.com';
				break;
			case 'gitea':
				$arr['git']           = 'gitea';
				$arr['base_uri']      = $this->type->enterprise . '/api/v1';
				$arr['base_download'] = $this->type->enterprise;
				break;
		}

		return $arr;
	}
387441
public static function getSvnInfo() {
		global $pgIP;

		// http://svnbook.red-bean.com/nightly/en/svn.developer.insidewc.html
		$entries = $pgIP . '/.svn/entries';

		if( !file_exists( $entries ) ) {
			return false;
		}

		$lines = file( $entries );
		if( !count( $lines ) ) {
			return false;
		}

		// check if file is xml (subversion release <= 1.3) or not (subversion release = 1.4)
		if( preg_match( '/^<\?xml/', $lines[0] ) ) {
			return false;
		}

		// Subversion is release 1.4 or above.
		if( count( $lines ) < 11 ) {
			return false;
		}

		$info = array(
			'checkout-rev'  => intval( trim( $lines[3] ) ),
			'url'           => trim( $lines[4] ),
			'repo-url'      => trim( $lines[5] ),
			'directory-rev' => intval( trim( $lines[10] ) )
		);

		return $info;
	}
1295487
public function getVersion()
    {
        $request = $this->apiRequestFactory->createRequest('GET', $this->getBaseUri() . '/version');
        $response = $this->httpClient->sendRequest($request);

        return $this->getResult($response, Version::class);
    }
100063
public function getUrlAttribute()
    {
        if ($this->disk == 'public') {
            return url($this->storage->url($this->path));
        }

        return config('media.download', false) ? url(str_finish(config('media.download'), '/') . $this->id) : null;
    }
1098486
protected function download()
    {
        $this->data_url = $this->job['data']['sources'][$this->job['done']];

        $filename = md5($this->data_url);
        $destination = gplcart_file_private_module('installer', "$filename.zip", true);
        $result = $this->file_transfer->download($this->data_url, 'zip', $destination);

        if ($result === true) {
            return $this->file_transfer->getTransferred();
        }

        $this->setError($result);
        return false;
    }
456641
public function download(Updater $updater)
    {
        /* Switch remote request errors to HttpRequestExceptions */
        set_error_handler(array($updater, 'throwHttpRequestException'));

        $remoteUrl = sprintf(
            self::REMOTE_PHAR,
            $this->getCurrentRemoteVersion($updater)
        );

        $result = humbug_get_contents($remoteUrl);
        restore_error_handler();

        if (false === $result) {
            throw new HttpRequestException(sprintf(
                'Request to URL failed: %s', $remoteUrl
            ));
        }

        file_put_contents($updater->getTempPharFile(), $result);
    }
181150
public static function getApplicationUpdateInformation()
    {
        $app = Application::getFacadeApplication();
        $cache = $app->make('cache');
        $r = $cache->getItem('APP_UPDATE_INFO');
        if ($r->isMiss()) {
            $r->lock();
            $result = static::getLatestAvailableUpdate();
            $r->set($result)->save();
        } else {
            $result = $r->get();
        }

        return $result;
    }
1203027
public static function getBundledCaBundlePath()
    {
        $caBundleFile = __DIR__.'/../res/cacert.pem';

        // cURL does not understand 'phar://' paths
        // see https://github.com/composer/ca-bundle/issues/10
        if (0 === strpos($caBundleFile, 'phar://')) {
            file_put_contents(
                $tempCaBundleFile = tempnam(sys_get_temp_dir(), 'openssl-ca-bundle-'),
                file_get_contents($caBundleFile)
            );

            register_shutdown_function(function() use ($tempCaBundleFile) {
                @unlink($tempCaBundleFile);
            });

            $caBundleFile = $tempCaBundleFile;
        }

        return $caBundleFile;
    }
28002
protected function checkUpdates()
    {
        // Avoid checking more than once in this process.
        if (self::$checkedUpdates) {
            return;
        }
        self::$checkedUpdates = true;

        // Check that the Phar extension is available.
        if (!extension_loaded('Phar')) {
            return;
        }

        // Get the filename of the Phar, or stop if this instance of the CLI is
        // not a Phar.
        $pharFilename = \Phar::running(false);
        if (!$pharFilename) {
            return;
        }

        // Check if the file is writable.
        if (!is_writable($pharFilename)) {
            return;
        }

        // Check if updates are configured.
        $config = $this->config();
        if (!$config->get('updates.check')) {
            return;
        }

        // Determine an embargo time, after which updates can be checked.
        $timestamp = time();
        $embargoTime = $timestamp - $config->get('updates.check_interval');

        // Stop if updates were last checked after the embargo time.
        /** @var \Platformsh\Cli\Service\State $state */
        $state = $this->getService('state');
        if ($state->get('updates.last_checked') > $embargoTime) {
            return;
        }

        // Stop if the Phar was updated after the embargo time.
        if (filemtime($pharFilename) > $embargoTime) {
            return;
        }

        // Ensure classes are auto-loaded if they may be needed after the
        // update.
        /** @var \Platformsh\Cli\Service\Shell $shell */
        $shell = $this->getService('shell');
        /** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
        $questionHelper = $this->getService('question_helper');
        $currentVersion = $this->config()->get('application.version');

        /** @var \Platformsh\Cli\Service\SelfUpdater $cliUpdater */
        $cliUpdater = $this->getService('self_updater');
        $cliUpdater->setAllowMajor(true);
        $cliUpdater->setTimeout(5);

        try {
            $newVersion = $cliUpdater->update(null, $currentVersion);
        } catch (\RuntimeException $e) {
            if (strpos($e->getMessage(), 'Failed to download') !== false) {
                $this->stdErr->writeln('<error>' . $e->getMessage() . '</error>');
                $newVersion = false;
            } else {
                throw $e;
            }
        }

        $state->set('updates.last_checked', $timestamp);

        // If the update was successful, and it's not a major version change,
        // then prompt the user to continue after updating.
        if ($newVersion !== false) {
            $exitCode = 0;
            list($currentMajorVersion,) = explode('.', $currentVersion, 2);
            list($newMajorVersion,) = explode('.', $newVersion, 2);
            if ($newMajorVersion === $currentMajorVersion
                && isset($this->input)
                && $this->input instanceof ArgvInput
                && is_executable($pharFilename)) {
                $originalCommand = $this->input->__toString();
                $questionText = "\n"
                    . 'Original command: <info>' . $originalCommand . '</info>'
                    . "\n\n" . 'Continue?';
                if ($questionHelper->confirm($questionText)) {
                    $this->stdErr->writeln('');
                    $exitCode = $shell->executeSimple(escapeshellarg($pharFilename) . ' ' . $originalCommand);
                }
            }
            exit($exitCode);
        }

        $this->stdErr->writeln('');
    }
520496
private function downloadNewVersion()
    {
        // check for permissions in local filesystem before start downloading files
        if (!is_writable($this->currentInstallerFile)) {
            throw new IOException('Symfony Installer update failed: the "'.$this->currentInstallerFile.'" file could not be written');
        }

        if (!is_writable($this->tempDir)) {
            throw new IOException('Symfony Installer update failed: the "'.$this->tempDir.'" directory used to download files temporarily could not be written');
        }

        if (false === $newInstaller = $this->getUrlContents($this->remoteInstallerFile)) {
            throw new \RuntimeException('The new version of the Symfony Installer couldn\'t be downloaded from the server.');
        }

        $newInstallerPermissions = $this->currentInstallerFile ? fileperms($this->currentInstallerFile) : 0777 & ~umask();
        $this->fs->dumpFile($this->newInstallerFile, $newInstaller, $newInstallerPermissions);

        return $this;
    }
923094
protected function determineProtocolVersion()
    {
        $params = $this->getServerParams();
        
        if (isset($params['SERVER_PROTOCOL'])) {
            list($protocol, $version) = explode('/', $params['SERVER_PROTOCOL']) + [1 => null];
        }
        
        return isset($protocol) && $protocol === 'HTTP' ? $version : "1.1";
    }