You are here

function shurly_rate_limit_allowed in ShURLy 8

Same name and namespace in other branches
  1. 6 shurly.module \shurly_rate_limit_allowed()
  2. 7 shurly.module \shurly_rate_limit_allowed()

Check rate limit for this user return an array in the following format array( 'allowed' => TRUE/FALSE 'rate' => number of requests allowed 'time' => period of time in minutes )

3 calls to shurly_rate_limit_allowed()
ShurlyCreateForm::validateForm in src/Form/ShurlyCreateForm.php
Form validation handler.
shurly_expand in ./shurly.module
Function to get the long url.
shurly_shorten in ./shurly.module
API function to shorten a URL.

File

./shurly.module, line 231
Description http://www.youtube.com/watch?v=Qo7qoonzTCE.

Code

function shurly_rate_limit_allowed($account = NULL) {
  if (!isset($account)) {
    $account = \Drupal::currentUser();
  }

  // @FIXME
  // Could not extract the default value because it is either indeterminate, or
  // not scalar. You'll need to provide a default value in
  // config/install/shurly.settings.yml and config/schema/shurly.schema.yml.
  $settings = \Drupal::config('shurly.settings')
    ->get('shurly_throttle');

  // Get the roles of a user.
  $roles = $account
    ->getRoles();
  if (is_array($roles)) {
    $rids = array_keys($roles);
    $use_rid = array_shift($rids);

    // Get list of roles with permission to create short URLs.
    $creating_roles = user_roles(FALSE, 'Create short URLs');
    foreach ($roles as $rid => $name) {

      // Check that this role has permission to create URLs, otherwise discard it.
      if (array_key_exists($rid, $creating_roles)) {

        // Find the lightest role... if roles are the same weight, use the next role.
        $settings[$use_rid]['weight'] = isset($settings[$use_rid]['weight']) ? $settings[$use_rid]['weight'] : 0;
        $settings[$rid]['weight'] = isset($settings[$rid]['weight']) ? $settings[$rid]['weight'] : 0;
        $use_rid = $settings[$use_rid]['weight'] < $settings[$rid]['weight'] ? $use_rid : $rid;

        // Create array index if not exists for rate and time.
        $settings[$use_rid]['rate'] = isset($settings[$use_rid]['rate']) ? $settings[$use_rid]['rate'] : NULL;
        $settings[$use_rid]['time'] = isset($settings[$use_rid]['time']) ? $settings[$use_rid]['time'] : NULL;
      }
    }
  }
  if (!empty($settings) && is_numeric($settings[$use_rid]['rate']) && is_numeric($settings[$use_rid]['time'])) {

    // See if it's allowed.
    $allowed = shurly_flood_is_allowed('shurly', $settings[$use_rid]['rate'], $settings[$use_rid]['time'] * 60);

    // Increment the counter.
    shurly_flood_register_event('shurly', $settings[$use_rid]['time'] * 60);
    $return = [
      'allowed' => $allowed,
      'rate' => $settings[$use_rid]['rate'],
      'time' => $settings[$use_rid]['time'],
    ];
  }
  else {

    // Not set... don't do a flood check.
    $return = [
      'allowed' => TRUE,
    ];
  }
  return $return;
}