/** * Construct controller. * * @throws Controller_API_Exception on invalid version, rate limit exceeded, invalid format */ public function before() { // Log request $api_request = Model_API_Request::factory(); $api_request->ip = Request::$client_ip; $api_request->request = $this->request->uri() . (empty($_REQUEST) ? '' : '?' . http_build_query($_REQUEST)); $api_request->created = time(); $api_request->save(); // Check version $this->version = $this->request->param('version'); if (!in_array($this->version, self::$_versions)) { throw new Controller_API_Exception('Invalid version'); } $this->data['version'] = $this->version; // Rate limit $rate_limit = (int) Kohana::$config->load('api.rate_limit'); $rate_span = (int) Kohana::$config->load('api.rate_span'); if ($rate_limit) { $requests = Model_API_Request::request_count(time() - $rate_span, Request::$client_ip); $requests_left = $rate_limit - $requests; if ($requests_left < 0) { throw new Controller_API_Exception('Request limit reached'); } $this->data['requests'] = $requests; $this->data['requests_left'] = $requests_left; $this->data['request_window'] = $rate_span; } // Check format $this->format = $this->request->param('format'); !$this->format and $this->format = self::FORMAT_JSON; if (!in_array($this->format, self::$_formats)) { throw new Controller_API_Exception('Invalid format'); } parent::before(); }