Skip to content

Instantly share code, notes, and snippets.

@SOF3
Last active June 2, 2016 10:19
Show Gist options
  • Save SOF3/964fd38de23c352b62fee0aa193fbcf0 to your computer and use it in GitHub Desktop.
Save SOF3/964fd38de23c352b62fee0aa193fbcf0 to your computer and use it in GitHub Desktop.
RewriteRule "^/([A-Za-z0-9]([A-Za-z0-9\-]*[A-Za-z0-9\-])?)/([A-Za-z0-9_\-]+)(/([^\.]+))?\.(zip|tar|gz|phar|php|pmf)" /index.php?username=$1&repo=$3&version=$5&extension=$6
<?php
function curl_get($page, $timeout = 5, &$ch = null){
$ch = curl_init($page);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["User-Agent: PocketMine-Plugin-Redirect/1.0"]);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
function test_exists($url, $timeout = 5, &$ret = null){
$ret = curl_get($url, $timeout, $ch);
return curl_getinfo($ch, CURLINFO_HTTP_CODE) < 400;
}
$username = $_REQUEST["username"];
$repo = $_REQUEST["repo"];
$version = (string) $_REQUEST["version"];
$extension = $_REQUEST["extension"];
if(!$version){
if(!test_exists("https://api.github.com/repos/$username/$repo/releases/latest", 10, $ret)){
http_response_code(404);
header("Content-Type: text/plain");
echo "No such repo or no latest release";
exit;
}
$release = json_decode($ret);
}else{
$ret = curl_get("https://api.github.com/repos/$username/$repo/releases");
$releases = json_decode($ret);
foreach($releases as $release){
if($release->tag_name === $version){
$ok = true;
break;
}
}
if(!isset($ok)){
http_response_code(404);
header("Content-Type: text/plain");
echo "No such repo or release";
exit;
}
unset($ok);
}
if(!is_object($release) or !isset($release->assets) or !is_array($release->assets)){
http_response_code(500);
header("Content-Type: text/plain");
echo "Error parsing GitHub API response";
exit;
}
$results = [];
foreach($release->assets as $asset){
$ext = end(explode(".", $asset->name));
if($ext === $extension){
$results[] = $asset;
}
}
if(count($results) > 1){
// TODO: raise warning: "multiple files with the required extension; will choose first file"
}elseif(count($results) === 0){
http_response_code(404);
header("Content-Type: text/plain");
echo "No binaries in release with such file extension";
exit;
}
$asset = $results[0];
header("Content-Type: " . $asset->content_type);
echo curl_get($asset->browser_download_url);
// NOTE: refer to http://stackoverflow.com/a/1342760 in case memory issues are encountered
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment