<?php
/**
 * @file
 * This files provides support functions to be called from Drupal /sites/default/settings.php
 */
define('PATH_ACCESS_FILE', '/var/www/access/');
define('PATH_SITES_DEFAULT', "/sites/default/");


define('VDA_API_THEME_SWITCH_DEVICE_MOBILE', 'mobile');
//define('VDA_API_THEME_SWITCH_MOBILE', 'bartik_sabre');
//define('VDA_API_THEME_SWITCH_DESKTOP', 'bartik_sabre');
define('VDA_API_THEME_SWITCH_ADMIN', 'admin');


/*
 *    vda_api_get_databases()
 *	  Determine our credentials for this site
 */
function vda_api_get_databases() {

  global $databases;

  $host = $_SERVER['HTTP_HOST'];

  if (empty($host) || ($host == 'default')) {
    $file = DRUPAL_ROOT.'/host.php';
    require($file);
    $host = $_ENV['HTTP_HOST'];
    //echo "File: $file\n";
    //echo "Host: $host\n";
  }

  // ex. expected url:
  //  sabre.simmetry-qms.net, sabre.simmetry-scheduler.net
  // or
  //  svaa-qms.simmetry-su.net, svaa-scheduler.simmetry-su.net
  $domain_parts = explode('.', $host);
  $subdomain = $domain_parts[0];
  $app_name = '';
  $suffix = '';
  $customer = '';
  $matches = array();
  if (preg_match('~simmetry\-(qms|scheduler)~i', $domain_parts[1], $matches)) {
    if (!empty($matches[1])) {
      $app_name = $matches[1];
      $customer = $subdomain;
      $suffix = ".$customer";
    }
  } else {
    // old structure
    $subdomain_parts = explode('-', $domain_parts[0]);
    $app_name = $subdomain_parts[1];
    $customer = $subdomain_parts[0];
    //print_r($subdomain_parts);
  }

  $_ENV['APPNAME'] = $app_name;
  $_ENV['CUSTOMER'] = $customer;

  $access_file = PATH_ACCESS_FILE . "access-${app_name}.${customer}.php";

  $databases = array();
  if (is_readable($access_file)) {
    require_once $access_file;

    $_ENV['ENVIRONMENT'] = ${'access_' . $app_name . '_environment'};
    $_ENV['SALT'] = ${"salt_$app_name"};

    $databases = ${'access_' . $app_name . '_databases'};

  } else {
    print "<br />Access file is not readable.  Contact your system administrator.<br />".
           "$access_file<br />";
    //print_r($domain_parts);
  }

}

/*
 *  vda_api_get_salt()
 */
function vda_api_get_salt() {
  if (!empty($_ENV['SALT'])) {
    return $_ENV['SALT'];
  } else {
    $appname = $_ENV['APPNAME'];
    $customer = $_ENV['CUSTOMER'];
    return file_get_contents(PATH_ACCESS_FILE . "salt-${appname}.${customer}.txt");
  }
}


/*
 *  vda_api_base_url()
 *
 *  RET:  $base_url
 */
function vda_api_base_url() {
  //$scheme = (!empty($_SERVER['HTTP_X_REMOTE_SCHEME'])) ? $_SERVER['HTTP_X_REMOTE_SCHEME'] : 'http';
  $scheme = (!empty($_SERVER['HTTPS'])) ? 'https' : 'http';
  return "$scheme://{$_SERVER['HTTP_HOST']}";
}


/*
 *  vda_api_fast_404()
 *
 *  RET:  $conf
 *  IN:  $domain_parts    //array of domain parts
 */
function vda_api_fast_404() {

  global $conf;

  $conf['404_fast_paths_exclude'] = '/\/(?:styles)\//';
  $conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp|pdf|doc|zip|dat|aspx|axd)$/i';
  $conf['404_fast_html'] = '<html xmlns="http://www.w3.org/1999/xhtml"><head><title>404 Not Found</title></head><body><h1>Oops, Not Found</h1><p>The requested URL "@path" was not found on this server.</p></body></html>';

  /**
 * By default, fast 404s are returned as part of the normal page request
 * process, which will properly serve valid pages that happen to match and will
 * also log actual 404s to the Drupal log. Alternatively you can choose to
 * return a 404 now by uncommenting the following line. This will reduce server
 * load, but will cause even valid pages that happen to match the pattern to
 * return 404s, rather than the actual page. It will also prevent the Drupal
 * system log entry. Ensure you understand the effects of this before enabling.
 *
 * To enable this functionality, remove the leading hash sign below.
 */
  drupal_fast_404();

}


/*
 *  vda_api_set_time_limit()
 *
 *  IN:  $domain_parts    //array of domain parts
 */
/*
function api_set_time_limit() {
  // Allow php scripts to run for a bit longer on certain pages
  switch($_ENV['SITECODE']) {
  case 'sh':
  case 'ah':
  case 'oh':
  case 'sp':
    if (!empty($_ENV['SITECONFIG']['subdomain']) && $_ENV['SITECONFIG']['subdomain'] == 'www') {
      set_time_limit(30); // default
      $_ENV['CUSTOM_TIME_LIMIT'] = false;

      if (strpos($_SERVER['REQUEST_URI'], 'admin/reports/doctor') !== false) {
        set_time_limit(600);
        $_ENV['CUSTOM_TIME_LIMIT'] = true;
      }
      if (strpos($_SERVER['REQUEST_URI'], 'admin/reports/practice') !== false) {
        set_time_limit(600);
        $_ENV['CUSTOM_TIME_LIMIT'] = true;
      }
      if (strpos($_SERVER['REQUEST_URI'], 'admin/reports/ip_tracking') !== false) { // #5218
        set_time_limit(600);
        $_ENV['CUSTOM_TIME_LIMIT'] = true;
      }
    } else {
      set_time_limit(600);
      $_ENV['CUSTOM_TIME_LIMIT'] = true;
    }
    break;

  default:
  }
}
 *
 */


/*
 *  vda_api_php_ini_set()
 *
 *  standardizes php ini settings for all VH sites
 */
function vda_api_php_ini_set() {

  if ($_ENV['ENVIRONMENT'] != 'prod') {
    // Turn On PHP Error Reporting
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
  }
  /**
  * Some distributions of Linux (most notably Debian) ship their PHP
  * installations with garbage collection (gc) disabled. Since Drupal depends on
  * PHP's garbage collection for clearing sessions, ensure that garbage
  * collection occurs by using the most common settings.
  */
  ini_set('session.gc_probability', 1);
  ini_set('session.gc_divisor', 100);

  /**
  * Set session lifetime (in seconds), i.e. the time from the user's last visit
  * to the active session may be deleted by the session garbage collector. When
  * a session is deleted, authenticated users are logged out, and the contents
  * of the user's $_SESSION variable is discarded.
  */
  ini_set('session.gc_maxlifetime', 100000);

  /**
  * Set session cookie lifetime (in seconds), i.e. the time from the session is
  * created to the cookie expires, i.e. when the browser is expected to discard
  * the cookie. The value 0 means "until the browser is closed".
  */
  ini_set('session.cookie_lifetime',  200000);

  /* these have been commented out of all settings.php files
   * included here for past reference only
  ini_set('arg_separator.output',     '&amp;');
  ini_set('magic_quotes_runtime',     0);
  ini_set('magic_quotes_sybase',      0);
  ini_set('session.cache_expire',     200000);
  ini_set('session.cache_limiter',    'none');
  ini_set('session.save_handler',     'user');
  ini_set('session.use_cookies',      1);
  ini_set('session.use_only_cookies', 1);
  ini_set('session.use_trans_sid',    0);
  ini_set('url_rewriter.tags',        '');
   *
   */
}

/*
 *  vda_api_conf_extras()
 *
 *  standardizes additional conf settings for all vh sites
 *
 *  RET:  $conf (optional)
 */
function vda_api_conf_extras() {
  global $conf;

  // extra config for all sites
  $conf['omit_vary_cookie'] = False;

  // Configuration option to set max number of shortcuts on the shortcut bar
  // http://api.drupal.org/api/drupal/modules!shortcut!shortcut.admin.inc/function/shortcut_max_slots/7
  $conf['shortcut_max_slots'] = 20;

  // Clear out old js/css after 10 days instead of the 30 default
  $conf['drupal_stale_file_threshold'] = 864000;

  $conf['drupal_http_request_fails'] = FALSE;

  // detect theme from URI
  //_vda_api_theme_detect();
}

/*
function _vda_api_theme_detect() {

  // Is this an admin url?
  // match on:
  //   /node/add or /node/add/[content-type]
  //   /node/12345/nodequeue
  //   /node/12345/edit
  //   /node/12345/webform
  //   /node/12345/webform/email
  //   /taxonomy/term/12345/edit
  //   /admin

  // NOT admin url:  /node/add/forum

  // Admin Theme Check
  $pattern = "/^\/node\/[0-9]+\/edit/";
  $bAdmin = false;

  if (preg_match($pattern, $_SERVER['REQUEST_URI'], $matches)) {
    # for node/1234/edit urls, check if this is for the forums,
    # if so use non-admin theme

    # HANDLE THIS IN vh_mobile_theme_switch module -- can't do dbaccess yet
    //$item = menu_get_item();
    //if (!empty($item['map'][1]->type) && ($item['map'][1]->type != 'forum')) {
    //  $bAdmin = true;
    //}
    $bAdmin = true;
  } else {
    $pattern = '/^\/(node\/add(?!\/forum)|node\/[0-9]+\/(?:.*)?|taxonomy\/term\/[0-9]+\/edit|admin)/';
    if (preg_match($pattern, $_SERVER['REQUEST_URI'])) {
      $bAdmin = true;
    }
  }

  // admin exceptions
  $pattern = "/^\/node\/[0-9]+\/done/";
  if (preg_match($pattern, $_SERVER['REQUEST_URI'])) {
      $bAdmin = false;
  }

  global $custom_theme;
  $custom_theme = VDA_API_THEME_SWITCH_DESKTOP;

  if ($bAdmin) {
    $custom_theme = VDA_API_THEME_SWITCH_ADMIN;

  } else if (!empty($_SERVER['HTTP_X_UA_DEVICE']) &&
      ($_SERVER['HTTP_X_UA_DEVICE'] == VDA_API_THEME_SWITCH_DEVICE_MOBILE)) {
    $custom_theme = VDA_API_THEME_SWITCH_MOBILE;

  }

  $_ENV['THEME_DETECT'] = $custom_theme;
  $_ENV['DEVICE'] = $_SERVER['HTTP_X_UA_DEVICE'];
  return $custom_theme;
}
 *
 */
