public static string|bool
downloadPackage
(mixed $url, mixed $target = false)
/**
* Downloads a package
*
* @param string $url URL of file to download
* @param string|bool $target Download target filename or false to get the filename from the URL
*
* @return string|boolean Path to downloaded package or boolean false on failure
*
* @since 3.1
*/
public static function downloadPackage($url, $target = false)
{
// Capture PHP errors
$track_errors = ini_get('track_errors');
ini_set('track_errors', true);
// Set user agent
$version = new Version();
ini_set('user_agent', $version->getUserAgent('Installer'));
// Load installer plugins, and allow URL and headers modification
$headers = array();
PluginHelper::importPlugin('installer');
Factory::getApplication()->triggerEvent('onInstallerBeforePackageDownload', array(&$url, &$headers));
try {
$response = HttpFactory::getHttp()->get($url, $headers);
} catch (\RuntimeException $exception) {
Log::add(Text::sprintf('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT', $exception->getMessage()), Log::WARNING, 'jerror');
return false;
}
// Convert keys of headers to lowercase, to accommodate for case variations
$headers = array_change_key_case($response->headers, CASE_LOWER);
if (302 == $response->code && !empty($headers['location'])) {
return self::downloadPackage($headers['location']);
} elseif (200 != $response->code) {
Log::add(Text::sprintf('JLIB_INSTALLER_ERROR_DOWNLOAD_SERVER_CONNECT', $response->code), Log::WARNING, 'jerror');
return false;
}
// Parse the Content-Disposition header to get the file name
if (!empty($headers['content-disposition']) && preg_match("/\\s*filename\\s?=\\s?(.*)/", $headers['content-disposition'][0], $parts)) {
$flds = explode(';', $parts[1]);
$target = trim($flds[0], '"');
}
$tmpPath = Factory::getApplication()->get('tmp_path');
// Set the target path if not given
if (!$target) {
$target = $tmpPath . '/' . self::getFilenameFromUrl($url);
} else {
$target = $tmpPath . '/' . basename($target);
}
// Write buffer to file
File::write($target, $response->body);
// Restore error tracking to what it was before
ini_set('track_errors', $track_errors);
// Bump the max execution time because not using built in php zip libs are slow
@set_time_limit(ini_get('max_execution_time'));
// Return the name of the downloaded package
return basename($target);
}