/**
  * {@inheritdoc}
  */
 public function applies(array $request = array(), $method = \RestfulInterface::GET)
 {
     // Don't attempt to authenticate during a Drush call, for example registry
     // rebuild.
     // @todo perhaps this should be a patch upstream (for the restful module)
     if (drupal_is_cli()) {
         return FALSE;
     }
     return parent::applies($request, $method);
 }
Пример #2
0
 /**
  * Default constructor
  *
  * @param AliasStorageInterface $storage
  */
 public function __construct(AliasStorageInterface $storage, $excludeAdminPath = true, $doCache = true)
 {
     $this->storage = $storage;
     $this->excludeAdminPath = $excludeAdminPath;
     $this->doCache = $doCache;
     $this->whitelist = $this->whitelistInit();
     if (null === $this->whitelist) {
         $this->whitelistRebuild();
     }
     // Drush context should not cache anything
     if (drupal_is_cli()) {
         $this->doCache = false;
     }
     if ($this->doCache) {
         $this->cacheKey = 'sf:' . current_path();
     }
     $this->data += [self::ALIAS => [], self::SOURCE => []];
 }
Пример #3
0
function dev_environment()
{
    # running through drush?
    if (drupal_is_cli()) {
        return 'drush';
    }
    # Ruben & Yannick
    if ($_SERVER['HTTP_HOST'] == 'comfortenergy.ruben.localhost') {
        return 'ruben';
    }
    if ($_SERVER['HTTP_HOST'] == 'comfortenergy.yannick.localhost') {
        return 'yannick';
    }
    # localhost
    if (strpos($_SERVER['HTTP_HOST'], 'localhost') != FALSE) {
        return 'localhost';
    }
    # geert/dev/qa/acc
    if (preg_match('{^comfort-energy-be\\.(geert|leuven|dev|qa|acc)\\.agency\\.be$}', $_SERVER['HTTP_HOST'], $matches)) {
        return $matches[1];
    }
    # not running on a dev environment
    return false;
}
 /**
  * Assert equality of 2 arrays.
  */
 protected function assertArray($actual, $expected, $message = 'Array values are equal', $strict_keys = FALSE)
 {
     $fail_count = 0;
     // Make this assertion universal.
     if (is_scalar($actual) && is_scalar($expected)) {
         return $this->assertEqual($actual, $expected, $message);
     }
     $expected = (array) $expected;
     $actual = (array) $actual;
     if (count($actual) != count($expected)) {
         $fail_count++;
     } else {
         foreach ($expected as $expected_k => $expected_v) {
             foreach ($actual as $actual_k => $actual_v) {
                 if ($expected_v == $actual_v) {
                     if ($strict_keys) {
                         if ($expected_k != $actual_k) {
                             $fail_count++;
                             // No need to proceed.
                             break 2;
                         }
                     }
                     continue 2;
                 }
             }
             $fail_count++;
             // No need to proceed.
             break;
         }
     }
     $pass = $fail_count === 0;
     if (!$pass) {
         $message = empty($message) ? $message : rtrim($message, '.') . '. ';
         if (drupal_is_cli()) {
             $message .= 'Expected: ' . print_r($expected, TRUE) . ' Actual: ' . print_r($actual, TRUE);
         } else {
             $message .= 'Expected: <pre>' . print_r($expected, TRUE) . '</pre> Actual: <pre>' . print_r($actual, TRUE) . '</pre>';
         }
     }
     return $this->assertTrue($pass, $message);
 }
Пример #5
0
 $conf['page_cache_maximum_age'] = 300;
 // We can't use an external cache if we are trying to invoke these hooks.
 $conf['page_cache_invoke_hooks'] = FALSE;
 if (!empty($site_settings['flags']['memcache_enabled']) && !empty($site_settings['memcache_inc'])) {
     $conf['cache_backends'][] = $site_settings['memcache_inc'];
     $conf['cache_default_class'] = 'MemCacheDrupal';
     $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
     // The oembed cache in many cases should not evict data (given that data
     // is obtained from costly API calls and is not expected to change when
     // refreshed), so is more suited to the database than to memcache.
     $conf['cache_class_cache_oembed'] = 'DrupalDatabaseCache';
 }
 // Until the site installation finishes, noone should be able to visit the
 // site, unless the site is being installed via install.php and the user has
 // the correct token to access it.
 if (!drupal_is_cli() && !empty($site_settings['flags']['access_restricted']['enabled'])) {
     $token_match = !empty($site_settings['flags']['access_restricted']['token']) && !empty($_GET['site_install_token']) && $_GET['site_install_token'] == $site_settings['flags']['access_restricted']['token'];
     $path_match = $_SERVER['SCRIPT_NAME'] == $GLOBALS['base_path'] . 'install.php';
     if (!$token_match || !$path_match) {
         header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service unavailable');
         if (!empty($site_settings['flags']['access_restricted']['reason'])) {
             print $site_settings['flags']['access_restricted']['reason'];
         }
         exit;
     }
 }
 if (!empty($site_settings['conf'])) {
     foreach ((array) $site_settings['conf'] as $key => $value) {
         $conf[$key] = $value;
     }
 }
 /**
  * @see _drupal_bootstrap_page_header
  */
 public function sendResponseHeaders()
 {
     if (!drupal_is_cli()) {
         drupal_page_header();
     }
 }
 /**
  * Import all the terms with given pids as parents.
  */
 private function importTerms($TermsElement, $pids = array())
 {
     $parents = array();
     foreach ($TermsElement as $term) {
         $termAttributes = $term->attributes();
         // Do not import disabled terms
         if ($termAttributes['enabled'] == 'false' && drupal_is_cli()) {
             drush_log('skipped disabled term: ' . $termAttributes['id'], 'warning');
             continue;
         }
         // If it has children, also import them.
         if (isset($term->term)) {
             $child_pids = $pids;
             $child_pids['p' . (count($pids) + 1)] = (string) $termAttributes['id'];
             $this->importTerms($term->term, $child_pids);
         }
         $parentId = trim((string) $termAttributes['parentid']);
         $parents[(string) $termAttributes['id']] = $parentId;
         $record = array('tid' => (string) $termAttributes['id'], 'language' => LANGUAGE_NONE, 'name' => (string) $termAttributes['label'], 'did' => (string) $termAttributes['domain'], 'parent' => empty($parentId) ? $parentId : NULL, 'show_term' => $termAttributes['show'] == 'true' ? 1 : 0, 'slug' => culturefeed_search_slug((string) $termAttributes['label'], 128));
         $record += $pids;
         // Get all the parent ids (p1, p2, p3...)
         /* if (!empty($parentId)) {
                 $parentWasTerm = TRUE;
                 $currTerm = $term;
                 $termParents = array();
         
                 // Loop through parents untill we find a non-term node.
                 while ($parentWasTerm) {
         
                 // Get parent of current term, and check if it's also a term.
                 $parent_node = $currTerm->xpath('parent::*');
                 $parent = $parent_node[0];
                 if (!$parent) {
                 break;
                 }
         
                 if ($parent->getName() == 'term') {
                 $termParents[] = (string) $parent->attributes()->id;
                 $currTerm = $parent;
                 }
                 else {
                 $parentWasTerm = FALSE;
                 }
                 }
         
                 foreach ($termParents as $i => $id) {
                 $record['p' . ($i + 1)] = $id;
                 }
         
                 } */
         // Always save label as undefined language so we can fallback.
         $this->logMessages[] = array('message' => 'Imported term ' . $record['name'] . ' ' . $parentId . ' for domain ' . $record['did'], 'code' => 'success');
         drupal_write_record('culturefeed_search_terms', $record);
         // Import other languages.
         foreach (array('nl', 'en', 'de', 'fr') as $language) {
             $key = 'label' . $language;
             if (isset($termAttributes[$key]) && !empty($termAttributes[$key])) {
                 $record['language'] = $language;
                 $record['name'] = (string) $termAttributes[$key];
                 drupal_write_record('culturefeed_search_terms', $record);
                 $this->logMessages[] = array('message' => 'Imported term ' . $record['name'] . ' ' . $parentId . ' in language ' . $record['language'], 'code' => 'success');
             }
         }
     }
 }
Пример #8
0
 public function start()
 {
     // Command line clients do not support cookies nor sessions.
     if (!$this->started && !drupal_is_cli()) {
         if (!$this->sessionIsEmpty()) {
             // Keep data from already set data, even if the session has not been
             // started yet, some pieces of software may have set $_SESSION super
             // global data before us: this is an artifact of the lazzy session
             // creation feature.
             $currentData = $_SESSION;
             session_start();
             $_SESSION += $currentData;
         } else {
             session_start();
         }
         $this->started = TRUE;
     }
 }
 *
 * Drush script for updating the hard coded title argument with a custom
 * argument.
 *
 * @arguments:
 *  - batch: Set the number to process each time. 250 by default.
 *  - memory_limit: The extended amount of memory for the script.
 *    500 by default.
 *  - id: The message ID. Used when you want to start the processing from a
 *    specific message.
 *
 *  @example:
 *
 *    drush scr update_message_arguments.php --id=30 --batch=450 --memory_limit=4000
 */
if (!drupal_is_cli()) {
    // The file is not reachable via web browser.
    return;
}
$batch = drush_get_option('batch', 250);
$memory_limit = drush_get_option('memory_limit', 500);
$id = drush_get_option('id', 1);
// Count how much messages we have.
$query = new EntityFieldQuery();
$max = $query->entityCondition('entity_type', 'message')->propertyCondition('mid', $id, '>=')->count()->execute();
$i = 0;
while ($max > $i) {
    // Collect the messages in batches.
    $query = new EntityFieldQuery();
    $result = $query->entityCondition('entity_type', 'message')->propertyCondition('mid', $id, '>=')->propertyOrderBy('mid', 'ASC')->range(0, $batch)->execute();
    if (empty($result['message'])) {
 /**
  * Create warning messages from message-parameters given as values array
  *
  * @param $values
  *   Array of message parameters keyed by the analyzer name, with the
  *   following properties:
  *   - nid: Node id of the meter.
  *   - message_type: The messages id in drupal's message stack, e.g.
  *   'anomalous_consumption'.
  *   - arguments: Array of message arguments.
  */
 protected function createMessages($values)
 {
     if (empty($values)) {
         // Nothing to do.
         return;
     }
     // Output message.
     $message = format_string('** Generating @n notifications', array('@n' => count($values)));
     if (drupal_is_cli()) {
         drush_log($message, 'ok');
     } else {
         debug($message);
     }
     foreach ($values as $value) {
         // Generate the message.
         // Get the node and user account.
         $node = node_load($value['nid']);
         $user_account = user_load($node->uid);
         // Get meter-account from meter-node
         $wrapper = entity_metadata_wrapper('node', $node);
         $meter_account = $wrapper->{OG_AUDIENCE_FIELD}->value();
         // Create message and set fields.
         $message = message_create($value['message_type'], array('arguments' => $value['arguments']), $user_account);
         $wrapper = entity_metadata_wrapper('message', $message);
         $wrapper->field_meter->set($node);
         $wrapper->field_meter_account->set($meter_account);
         $wrapper->field_message_meter_title->set($value['meter_title']);
         $wrapper->field_message_place_description->set($value['description']);
         $wrapper->field_message_place_address->set($value['address']);
         $wrapper->field_event_timestamp->set($value['event_timestamp']);
         $wrapper->save();
         // Output message.
         $message = "** Notification issued: \n" . print_r($values, TRUE);
         if (drupal_is_cli()) {
             drush_log($message);
         } else {
             debug($message);
         }
     }
 }
Пример #11
0
 /**
  * Returns the git clone file system directory path.
  *
  * @param bool $create
  *   Toggle determining whether or not to create the directory if it does not
  *   exist.
  * @param bool $absolute
  *   Toggle determining whether or not to return the entire system path. If
  *   FALSE, it will be prefixed with the gitclone:// stream wrapper.
  *
  * @return string|FALSE
  *   The git clone path or FALSE on error.
  */
 public function getPath($create = TRUE, $absolute = TRUE)
 {
     if (empty($this->refType) || empty($this->ref) || empty($this->name)) {
         return FALSE;
     }
     $path = "gitclone://{$this->refType}/{$this->name}";
     if ($create) {
         if (!is_dir($path) && !drupal_mkdir($path, NULL, TRUE)) {
             drupal_set_message(t('The directory %directory does not exist and could not be created.', array('%directory' => $path)), 'error');
             return FALSE;
         }
         if (is_dir($path) && !is_writable($path) && !drupal_chmod($path)) {
             drupal_set_message(t('The directory %directory exists but is not writable and could not be made writable.', array('%directory' => $path)), 'error');
             return FALSE;
         }
     } else {
         if (!is_dir($path)) {
             return FALSE;
         }
         if (!drupal_is_cli() && is_dir($path) && !is_writable($path) && !drupal_chmod($path)) {
             drupal_set_message(t('The directory %directory exists but is not writable and could not be made writable.', array('%directory' => $path)), 'error');
         }
     }
     if ($absolute) {
         return drupal_realpath($path);
     }
     return $path;
 }
 /**
  * Overrides SearchApiEntityDataSourceController::startTracking().
  *
  * Reverts the behavior to always use getAllItemIds(), instead of taking a
  * shortcut via "base table".
  *
  * This method will also be called when the multilingual configuration of an
  * index changes, to take care of new and/or out-dated IDs.
  */
 public function startTracking(array $indexes)
 {
     if (!$this->table) {
         return;
     }
     // We first clear the tracking table for all indexes, so we can just insert
     // all items again without any key conflicts.
     $this->stopTracking($indexes);
     $operations = array();
     // Find out number of all entities to be processed.
     foreach ($indexes as $index) {
         $entity_ids = $this->getTrackableEntityIds($index);
         $steps = ceil(count($entity_ids) / $index->options['cron_limit']);
         for ($step = 0; $step < $steps; $step++) {
             $operations[] = array('search_api_et_batch_queue_entities', array($index, $entity_ids, $step));
         }
     }
     // This might be called both from web interface as well as from drush.
     $t = drupal_is_cli() ? 'dt' : 't';
     $batch = array('title' => $t('Adding items to the index queue'), 'operations' => $operations, 'finished' => 'search_api_et_batch_queue_entities_finished', 'progress_message' => $t('Completed about @percentage% of the queueing operation.'), 'file' => drupal_get_path('module', 'search_api_et') . '/search_api_et.batch.inc');
     batch_set($batch);
     if (drupal_is_cli()) {
         // Calling drush_backend_batch_process() to start batch execution directly
         // from here doesn't work for some unknown reason, so we need to call it
         // from a shutdown function instead.
         drupal_register_shutdown_function('search_api_et_shutdown_batch_process');
     } else {
         batch_process();
     }
 }
 /**
  * Detects whether the script is running from a command line environment.
  *
  * @param RequestInterface $request.
  *   The request.
  *
  * @return bool
  *   TRUE if a command line environment is detected. FALSE otherwise.
  */
 protected function isCli(RequestInterface $request)
 {
     // Needed to detect if run-tests.sh is running the tests.
     $cli = $request->getHeaders()->get('User-Agent')->getValueString() == 'Drupal command line';
     return $cli || drupal_is_cli();
 }
 /**
  * Detects whether the script is running from a command line environment.
  *
  * @return bool
  *   TRUE if a command line environment is detected. FALSE otherwise.
  */
 protected function isCli() {
   // Needed to detect if run-tests.sh is running the tests.
   $cli = \RestfulManager::getRequestHttpHeader('User-Agent') == 'Drupal command line';
   return $cli || drupal_is_cli();
 }
Пример #15
0
    {
        return file_exists('/var/acquia');
    }
}
// HTTP_HOST can be empty during early drush bootstrap. Also, check that we're
// on an Acquia server so we don't run this code for local development.
if (empty($_SERVER['HTTP_HOST']) || !is_acquia_host()) {
    return;
}
require_once dirname(__FILE__) . '/g/sites.inc';
// Drush site-install gets confused about the uri when we specify the
// --sites-subdir option. The HTTP_HOST is set incorrectly and we can't
// find it in the sites.json. By specifying the --acsf-install-uri option
// with the value of the standard domain, we can catch that here and
// correct the uri argument for drush site installs.
if (drupal_is_cli() && function_exists('drush_get_option') && ($http_host = drush_get_option('acsf-install-uri', FALSE))) {
    $host = $_SERVER['HTTP_HOST'] = $http_host;
    // Match the expected drupal sites.php key. @see conf_path().
    $dir = implode('.', array_reverse(explode(':', $host)));
} else {
    $host = rtrim($_SERVER['HTTP_HOST'], '.');
    // Match the expected drupal sites.php key. @see conf_path().
    $dir = implode('.', array_reverse(explode(':', $host)));
}
if (!GARDENS_SITE_DATA_USE_APC) {
    // gardens_site_data_refresh_one() will do a full parse if the domain is in
    // the file at all and a single line parse fails.
    $data = gardens_site_data_refresh_one($host);
} elseif (($data = gardens_site_data_cache_get($host)) !== 0) {
    if (empty($data)) {
        // Note - when set to use APC, we never parse the whole file on a web
Пример #16
0
/**
 * Utility methods for use in protecting an environment via basic auth or IP whitelist.
 */
function ac_protect_this_site()
{
    global $conf;
    $client_ip = ip_address();
    // Test if we are using drush (command-line interface)
    $cli = drupal_is_cli();
    // Default to not skipping the auth check
    $skip_auth_check = FALSE;
    // Is the user on the VPN? Default to FALSE.
    $on_vpn = $cli ? TRUE : FALSE;
    if (!empty($client_ip) && !empty($conf['ah_whitelist'])) {
        $on_vpn = ah_ip_in_list($client_ip, $conf['ah_whitelist']);
        $skip_auth_check = $skip_auth_check || $on_vpn;
    }
    // If the IP is not explicitly whitelisted check to see if the IP is blacklisted.
    if (!$on_vpn && !empty($client_ip) && !empty($conf['ah_blacklist'])) {
        if (ah_ip_in_list($client_ip, $conf['ah_blacklist'])) {
            ah_page_403($client_ip);
        }
    }
    // Check if we should skip auth check for this page.
    if (ah_path_skip_auth()) {
        $skip_auth_check = TRUE;
    }
    // Check if we should disable cache for this page.
    if (ah_path_no_cache()) {
        $conf['page_cache_maximum_age'] = 0;
    }
    // Is the page restricted to whitelist only? Default to FALSE.
    $restricted_page = FALSE;
    // Check to see whether this page is restricted.
    if (!empty($conf['ah_restricted_paths']) && ah_paths_restrict()) {
        $restricted_page = TRUE;
    }
    $protect_ip = !empty($conf['ah_whitelist']);
    $protect_password = !empty($conf['ah_basic_auth_credentials']);
    // Do not protect command line requests, e.g. Drush.
    if ($cli) {
        $protect_ip = FALSE;
        $protect_password = FALSE;
    }
    // Un-comment to disable protection, e.g. for load tests.
    // $skip_auth_check = TRUE;
    // $on_vpn = TRUE;
    // If not on whitelisted IP prevent access to protected pages.
    if ($protect_ip && !$on_vpn && $restricted_page) {
        ah_page_403($client_ip);
    }
    // If not skipping auth, check basic auth.
    if ($protect_password && !$skip_auth_check) {
        ah_check_basic_auth();
    }
}
 /**
  * Output debug message, either through drush_log or debug.
  *
  * @param $message
  *    The message to output. Can use @time_from, @time_to as placeholders.
  * @param int $indentation
  *    Message indentation. That number of spaces will precede the message string.
  * @param null $time_from
  *    Timestamp. Will be converted to text and replace @time_from placeholder.
  * @param null $time_to
  *    Timestamp. Will be converted to text and replace @time_to placeholder.
  */
 public static function debugMessage($message, $indentation = 0, $time_from = NULL, $time_to = NULL)
 {
     // Prepare message string.
     $options = array('@time_from' => date('Y-m-d H:i', $time_from), '@time_to' => date('Y-m-d H:i', $time_to));
     $message = str_repeat(' ', $indentation) . format_string($message, $options);
     // Output message.
     if (drupal_is_cli()) {
         drush_log($message);
     } else {
         debug($message);
     }
 }