Example #1
0
 public static function respond($data, $exit = true)
 {
     if (extension_loaded('newrelic')) {
         newrelic_disable_autorum();
     }
     $text = json_encode($data);
     if ($text === false) {
         throw new Exception('Failed to encode json data, json_last_error=' . json_last_error());
     }
     header('Content-type: application/json', true);
     print $text;
     Site::finishRequest($exit);
 }
Example #2
0
 public static function terminate()
 {
     Site::finishRequest();
 }
<?php

namespace Gatekeeper;

use Cache;
use Gatekeeper\Metrics\Metrics;
$Endpoint = $_EVENT['request']->getEndpoint();
$url = $_EVENT['request']->getUrl();
// attempt to load response from cache if enabled for this endpoint
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $Endpoint->CachingEnabled) {
    $cacheKey = "response:{$Endpoint->ID}:{$url}";
    if ($cachedResponse = Cache::fetch($cacheKey)) {
        if ($cachedResponse['expires'] < $_EVENT['request']->getStartTime()) {
            Cache::delete($cacheKey);
            $cachedResponse = false;
        } else {
            foreach ($cachedResponse['headers'] as $header) {
                header($header);
            }
            print $cachedResponse['body'];
            $_EVENT['metrics']['endpointResponsesCached'] = Metrics::appendCounter("endpoints/{$Endpoint->ID}/responsesCached");
            $_EVENT['metrics']['endpointBytesCached'] = Metrics::appendCounter("endpoints/{$Endpoint->ID}/bytesCached", strlen($cachedResponse['body']));
            \Site::finishRequest();
        }
    }
}
 public static function handleInadaquateAccess($requiredAccountLevel)
 {
     printf('Sorry, you must have %s access to do that', $requiredAccountLevel);
     Site::finishRequest();
 }
 public static function handleMediaRequest($mediaID)
 {
     if (empty($mediaID) || !is_numeric($mediaID)) {
         static::throwError('Missing or invalid media_id');
     }
     // get media
     try {
         $Media = Media::getById($mediaID);
     } catch (UserUnauthorizedException $e) {
         return static::throwUnauthorizedError('You are not authorized to download this media');
     }
     if (!$Media) {
         static::throwNotFoundError('Media ID #%u was not found', $media_id);
     }
     if (static::$responseMode == 'json' || $_SERVER['HTTP_ACCEPT'] == 'application/json') {
         JSON::translateAndRespond(array('success' => true, 'data' => $Media));
     } else {
         // determine variant
         if ($variant = static::shiftPath()) {
             if (!$Media->isVariantAvailable($variant)) {
                 return static::throwNotFoundError('Requested variant is not available');
             }
         } else {
             $variant = 'original';
         }
         // send caching headers
         $expires = 60 * 60 * 24 * 365;
         header("Cache-Control: public, max-age={$expires}");
         header('Expires: ' . gmdate('D, d M Y H:i:s \\G\\M\\T', time() + $expires));
         header('Pragma: public');
         // media are immutable for a given URL, so no need to actually check anything if the browser wants to revalidate its cache
         if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) || !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
             header('HTTP/1.0 304 Not Modified');
             exit;
         }
         // initialize response
         set_time_limit(0);
         $filePath = $Media->getFilesystemPath($variant);
         $fp = fopen($filePath, 'rb');
         $size = filesize($filePath);
         $length = $filesize;
         $start = 0;
         $end = $size - 1;
         header('Content-Type: ' . $Media->getMIMEType($variant));
         header('ETag: media-' . $Media->ID . '-' . $variant);
         header('Accept-Ranges: bytes');
         // interpret range requests
         if (!empty($_SERVER['HTTP_RANGE'])) {
             $chunkStart = $start;
             $chunkEnd = $end;
             list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
             if (strpos($range, ',') !== false) {
                 header('HTTP/1.1 416 Requested Range Not Satisfiable');
                 header("Content-Range: bytes {$start}-{$end}/{$size}");
                 exit;
             }
             if ($range == '-') {
                 $chunkStart = $size - substr($range, 1);
             } else {
                 $range = explode('-', $range);
                 $chunkStart = $range[0];
                 $chunkEnd = isset($range[1]) && is_numeric($range[1]) ? $range[1] : $size;
             }
             $chunkEnd = $chunkEnd > $end ? $end : $chunkEnd;
             if ($chunkStart > $chunkEnd || $chunkStart > $size - 1 || $chunkEnd >= $size) {
                 header('HTTP/1.1 416 Requested Range Not Satisfiable');
                 header("Content-Range: bytes {$start}-{$end}/{$size}");
                 exit;
             }
             $start = $chunkStart;
             $end = $chunkEnd;
             $length = $end - $start + 1;
             fseek($fp, $start);
             header('HTTP/1.1 206 Partial Content');
         }
         // finish response
         header("Content-Range: bytes {$start}-{$end}/{$size}");
         header("Content-Length: {$length}");
         $buffer = 1024 * 8;
         while (!feof($fp) && ($p = ftell($fp)) <= $end) {
             if ($p + $buffer > $end) {
                 $buffer = $end - $p + 1;
             }
             echo fread($fp, $buffer);
             flush();
         }
         fclose($fp);
         Site::finishRequest();
     }
 }