protected function _check_limit($controller_method)
{
// They are special, or it might not even have a limit
if (empty($this->rest->ignore_limits) === FALSE) {
// Everything is fine
return TRUE;
}
$api_key = isset($this->rest->key) ? $this->rest->key : '';
switch ($this->config->item('rest_limits_method')) {
case 'IP_ADDRESS':
$limited_uri = 'ip-address:' . $this->input->ip_address();
$api_key = $this->input->ip_address();
break;
case 'API_KEY':
$limited_uri = 'api-key:' . $api_key;
break;
case 'METHOD_NAME':
$limited_uri = 'method-name:' . $controller_method;
break;
case 'ROUTED_URL':
default:
$limited_uri = $this->uri->ruri_string();
if (strpos(strrev($limited_uri), strrev($this->response->format)) === 0) {
$limited_uri = substr($limited_uri, 0, -strlen($this->response->format) - 1);
}
$limited_uri = 'uri:' . $limited_uri . ':' . $this->request->method;
// It's good to differentiate GET from PUT
break;
}
if (isset($this->methods[$controller_method]['limit']) === FALSE) {
// Everything is fine
return TRUE;
}
// How many times can you get to this method in a defined time_limit (default: 1 hour)?
$limit = $this->methods[$controller_method]['limit'];
$time_limit = isset($this->methods[$controller_method]['time']) ? $this->methods[$controller_method]['time'] : 3600;
// 3600 = 60 * 60
// Get data about a keys' usage and limit to one row
$result = $this->rest->db->where('uri', $limited_uri)->where('api_key', $api_key)->get($this->config->item('rest_limits_table'))->row();
// No calls have been made for this key
if ($result === NULL) {
// Create a new row for the following key
$this->rest->db->insert($this->config->item('rest_limits_table'), ['uri' => $limited_uri, 'api_key' => $api_key, 'count' => 1, 'hour_started' => time()]);
} elseif ($result->hour_started < time() - $time_limit) {
// Reset the started period and count
$this->rest->db->where('uri', $limited_uri)->where('api_key', $api_key)->set('hour_started', time())->set('count', 1)->update($this->config->item('rest_limits_table'));
} else {
// The limit has been exceeded
if ($result->count >= $limit) {
return FALSE;
}
// Increase the count by one
$this->rest->db->where('uri', $limited_uri)->where('api_key', $api_key)->set('count', 'count + 1', FALSE)->update($this->config->item('rest_limits_table'));
}
return TRUE;
}