You are here

function cors_init in CORS 7

Implements hook_init().

File

./cors.module, line 86
Allows Cross-origin resource sharing.

Code

function cors_init() {
  $domains = variable_get('cors_domains', array());
  $current_path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
  $request_headers = getallheaders();
  $headers = array(
    'all' => array(
      'Access-Control-Allow-Origin' => array(),
      'Access-Control-Allow-Credentials' => array(),
    ),
    'OPTIONS' => array(
      'Access-Control-Allow-Methods' => array(),
      'Access-Control-Allow-Headers' => array(),
    ),
  );
  foreach ($domains as $path => $settings) {
    $settings = explode("|", $settings);
    $page_match = drupal_match_path($current_path, $path);
    if ($current_path != $_GET['q']) {
      $page_match = $page_match || drupal_match_path($_GET['q'], $path);
    }
    if ($page_match) {
      if (!empty($settings[0])) {
        $origins = explode(',', trim($settings[0]));
        foreach ($origins as $origin) {
          if ($origin === '<mirror>') {
            if (!empty($request_headers['Origin'])) {
              $headers['all']['Access-Control-Allow-Origin'][] = $request_headers['Origin'];

              // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin#CORS_and_caching
              $headers['all']['Vary'] = 'Origin';
            }
          }
          else {
            $headers['all']['Access-Control-Allow-Origin'][] = $origin;
            if ($origin !== '*') {

              // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin#CORS_and_caching
              $headers['all']['Vary'] = 'Origin';
            }
          }
        }
      }
      if (!empty($settings[1])) {
        $headers['OPTIONS']['Access-Control-Allow-Methods'] = explode(',', trim($settings[1]));
      }
      if (!empty($settings[2])) {
        $headers['OPTIONS']['Access-Control-Allow-Headers'] = explode(',', trim($settings[2]));
      }
      if (!empty($settings[3])) {
        $headers['all']['Access-Control-Allow-Credentials'] = explode(',', trim($settings[3]));
      }
    }
  }
  foreach ($headers as $method => $allowed) {
    if ($method === 'all' || $method === $_SERVER['REQUEST_METHOD']) {
      foreach ($allowed as $header => $values) {
        if (!empty($values)) {
          foreach ($values as $value) {
            drupal_add_http_header($header, $value, TRUE);
          }
        }
      }
    }
  }
}