We Are Now Offering
FREE SHIPPING !

System Scan

Scan


[07/26/2021 07:23:13]

*******************************************************BEGIN SCANNING*******************************************************************

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__wine_cellar.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__milano_roll.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__glass_sets.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__u_bracket.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__acrylic_sign_holder_kit.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__spigot_clamps.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__picture_rails.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__roll_up.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__tamper_proof_screws.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__light_fixture_shades.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__bracket_blank_bom.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__acrylic_wall_frame_kit.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__vinyl_bom.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__caps.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__floating_shelf.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__foam_board.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__category.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__screws.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__cartridges.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__affordable_standoffs_kit.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__hardware.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__multi_mount_hardware.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__tools.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__quick_snap.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__roll.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__cable_rod_supports.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__drill_bit.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__roll_general_formulation.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__barrels.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__sign_blanks.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__snap_caps.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__olfa.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__sign_poster_holder.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__tclamp.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__screws_cover.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__panel_hanger.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__z_clip.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__sign_bracket.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__glass.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__literature_displays.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__combination_screws.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__washers_tubing.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__sign_clamp.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__light_bulbs.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__hanging_cable_rod.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__studs.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__board.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__ez_rack.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__real_estate_sign.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__a_frame.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__custom.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__poster_displays_stands.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__button_fix.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__rapid_tac.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__transferrite.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__sneeze_guard_kit_with_acrylic.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__board_stake_bom.xls) Do no exist in Mirror

Folder [download] File in Original=(/var/www/sites/drupal/download/product_type__edge_grip_standoffs.xls) Do no exist in Mirror

Folder [download] diferent quatities! Mirror=(19) | Original=(77)

Folder [download] file size different! File=(download/product_type__vinyl_tools.xls) Mirror=(232448) | Original=(162816) -> Dif = (-69632 Bytes)

Folder [download] file size different! File=(download/product_type__acrylic_sneeze_guard_kit.xls) Mirror=(53760) | Original=(13312) -> Dif = (-40448 Bytes)

Folder [download] file size different! File=(download/product_type__acrylic.xls) Mirror=(14336) | Original=(142848) -> Dif = (128512 Bytes)

Folder [download] file size different! File=(download/product_type__shoulder_screws.xls) Mirror=(642560) | Original=(289280) -> Dif = (-353280 Bytes)

Folder [download] file size different! File=(download/product_type__suspended_system.xls) Mirror=(123904) | Original=(28160) -> Dif = (-95744 Bytes)

Folder [download] file size different! File=(download/product_type__standoff.xls) Mirror=(6762496) | Original=(842240) -> Dif = (-5920256 Bytes)

Folder [download] file size different! File=(download/product_type__female_to_female_standoffs.xls) Mirror=(5702144) | Original=(2172928) -> Dif = (-3529216 Bytes)

Folder [download] file size different! File=(download/product_type__hooks_accesories.xls) Mirror=(153088) | Original=(32256) -> Dif = (-120832 Bytes)

Folder [download] file size different! File=(download/product_type__male_female_standoffs.xls) Mirror=(2711552) | Original=(719872) -> Dif = (-1991680 Bytes)

Folder [download] file size different! File=(download/product_type__light_fixture_arms.xls) Mirror=(93184) | Original=(28672) -> Dif = (-64512 Bytes)

Folder [download] file size different! File=(download/product_type__vinyl.xls) Mirror=(1510400) | Original=(13434880) -> Dif = (11924480 Bytes)

Folder [download] file size different! File=(download/product_type__projecting_gripper.xls) Mirror=(78848) | Original=(47104) -> Dif = (-31744 Bytes)

Folder [download] file size different! File=(download/product_type__male_to_male_standoff.xls) Mirror=(259584) | Original=(99328) -> Dif = (-160256 Bytes)

Folder [download] file size different! File=(download/product_type__spacer.xls) Mirror=(2669056) | Original=(1059840) -> Dif = (-1609216 Bytes)

Folder [download] file size different! File=(download/product_type__jackscrews.xls) Mirror=(113664) | Original=(35328) -> Dif = (-78336 Bytes)

Folder [download] file size different! File=(download/product_type__electronics_spacers.xls) Mirror=(3755520) | Original=(1606144) -> Dif = (-2149376 Bytes)

Folder [download] file size different! File=(download/product_type__cable_rod.xls) Mirror=(628224) | Original=(45568) -> Dif = (-582656 Bytes)

Folder [download] file size different! File=(download/product_type__light_fixture_kits.xls) Mirror=(306688) | Original=(196608) -> Dif = (-110080 Bytes)

Folder [download] file size different! File=(download/product_type__clamp_sneeze_guards.xls) Mirror=(49152) | Original=(25600) -> Dif = (-23552 Bytes)

Folder [download] file content different! File=(download/product_type__vinyl_tools.xls)

Folder [download] file content different! File=(download/product_type__acrylic_sneeze_guard_kit.xls)

Folder [download] file content different! File=(download/product_type__acrylic.xls)

Folder [download] file content different! File=(download/product_type__shoulder_screws.xls)

Folder [download] file content different! File=(download/product_type__suspended_system.xls)

Folder [download] file content different! File=(download/product_type__standoff.xls)

Folder [download] file content different! File=(download/product_type__female_to_female_standoffs.xls)

Folder [download] file content different! File=(download/product_type__hooks_accesories.xls)

Folder [download] file content different! File=(download/product_type__male_female_standoffs.xls)

Folder [download] file content different! File=(download/product_type__light_fixture_arms.xls)

Folder [download] file content different! File=(download/product_type__vinyl.xls)

Folder [download] file content different! File=(download/product_type__projecting_gripper.xls)

Folder [download] file content different! File=(download/product_type__male_to_male_standoff.xls)

Folder [download] file content different! File=(download/product_type__spacer.xls)

Folder [download] file content different! File=(download/product_type__jackscrews.xls)

Folder [download] file content different! File=(download/product_type__electronics_spacers.xls)

Folder [download] file content different! File=(download/product_type__cable_rod.xls)

Folder [download] file content different! File=(download/product_type__light_fixture_kits.xls)

Folder [download] file content different! File=(download/product_type__clamp_sneeze_guards.xls)

Folder [includes] file size different! File=(includes/bootstrap.inc) Mirror=(135983) | Original=(135989) -> Dif = (6 Bytes)

Folder [includes] file size different! File=(includes/common.inc) Mirror=(330673) | Original=(330680) -> Dif = (7 Bytes)

Folder [includes] file content different! File=(includes/bootstrap.inc)
<?php
<?php



/**
* @file
* Functions that need to be loaded on every Drupal request.
*/

/**
* The current system version.
*/
define('VERSION', '7.56');

/**
* Core API compatibility.
*/
define('DRUPAL_CORE_COMPATIBILITY', '7.x');

/**
* Minimum supported version of PHP.
*/
define('DRUPAL_MINIMUM_PHP', '5.2.4');

/**
* Minimum recommended value of PHP memory_limit.
*/
define('DRUPAL_MINIMUM_PHP_MEMORY_LIMIT', '32M');

/**
* Error reporting level: display no errors.
*/
define('ERROR_REPORTING_HIDE', 0);

/**
* Error reporting level: display errors and warnings.
*/
define('ERROR_REPORTING_DISPLAY_SOME', 1);

/**
* Error reporting level: display all messages.
*/
define('ERROR_REPORTING_DISPLAY_ALL', 2);

/**
* Indicates that the item should never be removed unless explicitly selected.
*
* The item may be removed using cache_clear_all() with a cache ID.
*/
define('CACHE_PERMANENT', 0);

/**
* Indicates that the item should be removed at the next general cache wipe.
*/
define('CACHE_TEMPORARY', -1);

/**
* @defgroup logging_severity_levels Logging severity levels
* @{
* Logging severity levels as defined in RFC 3164.
*
* The WATCHDOG_* constant definitions correspond to the logging severity levels
* defined in RFC 3164, section 4.1.1. PHP supplies predefined LOG_* constants
* for use in the syslog() function, but their values on Windows builds do not
* correspond to RFC 3164. The associated PHP bug report was closed with the
* comment, "And it's also not a bug, as Windows just have less log levels,"
* and "So the behavior you're seeing is perfectly normal."
*
* @see http://www.faqs.org/rfcs/rfc3164.html
* @see http://bugs.php.net/bug.php?id=18090
* @see http://php.net/manual/function.syslog.php
* @see http://php.net/manual/network.constants.php
* @see watchdog()
* @see watchdog_severity_levels()
*/

/**
* Log message severity -- Emergency: system is unusable.
*/
define('WATCHDOG_EMERGENCY', 0);

/**
* Log message severity -- Alert: action must be taken immediately.
*/
define('WATCHDOG_ALERT', 1);

/**
* Log message severity -- Critical conditions.
*/
define('WATCHDOG_CRITICAL', 2);

/**
* Log message severity -- Error conditions.
*/
define('WATCHDOG_ERROR', 3);

/**
* Log message severity -- Warning conditions.
*/
define('WATCHDOG_WARNING', 4);

/**
* Log message severity -- Normal but significant conditions.
*/
define('WATCHDOG_NOTICE', 5);

/**
* Log message severity -- Informational messages.
*/
define('WATCHDOG_INFO', 6);

/**
* Log message severity -- Debug-level messages.
*/
define('WATCHDOG_DEBUG', 7);

/**
* @} End of "defgroup logging_severity_levels".
*/

/**
* First bootstrap phase: initialize configuration.
*/
define('DRUPAL_BOOTSTRAP_CONFIGURATION', 0);

/**
* Second bootstrap phase: try to serve a cached page.
*/
define('DRUPAL_BOOTSTRAP_PAGE_CACHE', 1);

/**
* Third bootstrap phase: initialize database layer.
*/
define('DRUPAL_BOOTSTRAP_DATABASE', 2);

/**
* Fourth bootstrap phase: initialize the variable system.
*/
define('DRUPAL_BOOTSTRAP_VARIABLES', 3);

/**
* Fifth bootstrap phase: initialize session handling.
*/
define('DRUPAL_BOOTSTRAP_SESSION', 4);

/**
* Sixth bootstrap phase: set up the page header.
*/
define('DRUPAL_BOOTSTRAP_PAGE_HEADER', 5);

/**
* Seventh bootstrap phase: find out language of the page.
*/
define('DRUPAL_BOOTSTRAP_LANGUAGE', 6);

/**
* Final bootstrap phase: Drupal is fully loaded; validate and fix input data.
*/
define('DRUPAL_BOOTSTRAP_FULL', 7);

/**
* Role ID for anonymous users; should match what's in the "role" table.
*/
define('DRUPAL_ANONYMOUS_RID', 1);

/**
* Role ID for authenticated users; should match what's in the "role" table.
*/
define('DRUPAL_AUTHENTICATED_RID', 2);

/**
* The number of bytes in a kilobyte.
*
* For more information, visit http://en.wikipedia.org/wiki/Kilobyte.
*/
define('DRUPAL_KILOBYTE', 1024);

/**
* The language code used when no language is explicitly assigned.
*
* Defined by ISO639-2 for "Undetermined".
*/
define('LANGUAGE_NONE', 'und');

/**
* The type of language used to define the content language.
*/
define('LANGUAGE_TYPE_CONTENT', 'language_content');

/**
* The type of language used to select the user interface.
*/
define('LANGUAGE_TYPE_INTERFACE', 'language');

/**
* The type of language used for URLs.
*/
define('LANGUAGE_TYPE_URL', 'language_url');

/**
* Language written left to right. Possible value of $language->direction.
*/
define('LANGUAGE_LTR', 0);

/**
* Language written right to left. Possible value of $language->direction.
*/
define('LANGUAGE_RTL', 1);

/**
* Time of the current request in seconds elapsed since the Unix Epoch.
*
* This differs from $_SERVER['REQUEST_TIME'], which is stored as a float
* since PHP 5.4.0. Float timestamps confuse most PHP functions
* (including date_create()).
*
* @see http://php.net/manual/reserved.variables.server.php
* @see http://php.net/manual/function.time.php
*/
define('REQUEST_TIME', (int) $_SERVER['REQUEST_TIME']);

/**
* Flag used to indicate that text is not sanitized, so run check_plain().
*
* @see drupal_set_title()
*/
define('CHECK_PLAIN', 0);

/**
* Flag used to indicate that text has already been sanitized.
*
* @see drupal_set_title()
*/
define('PASS_THROUGH', -1);

/**
* Signals that the registry lookup cache should be reset.
*/
define('REGISTRY_RESET_LOOKUP_CACHE', 1);

/**
* Signals that the registry lookup cache should be written to storage.
*/
define('REGISTRY_WRITE_LOOKUP_CACHE', 2);

/**
* Regular expression to match PHP function names.
*
* @see http://php.net/manual/language.functions.php
*/
define('DRUPAL_PHP_FUNCTION_PATTERN', '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*');

/**
* A RFC7231 Compliant date.
*
* http://tools.ietf.org/html/rfc7231#section-7.1.1.1
*
* Example: Sun, 06 Nov 1994 08:49:37 GMT
*
* This constant was introduced in PHP 7.0.19 and PHP 7.1.5 but needs to be
* defined by Drupal for earlier PHP versions.
*/
if (!defined('DATE_RFC7231')) {
define('DATE_RFC7231', 'D, d M Y H:i:s \G\M\T');
}

/**
* Provides a caching wrapper to be used in place of large array structures.
*
* This class should be extended by systems that need to cache large amounts
* of data and have it represented as an array to calling functions. These
* arrays can become very large, so ArrayAccess is used to allow different
* strategies to be used for caching internally (lazy loading, building caches
* over time etc.). This can dramatically reduce the amount of data that needs
* to be loaded from cache backends on each request, and memory usage from
* static caches of that same data.
*
* Note that array_* functions do not work with ArrayAccess. Systems using
* DrupalCacheArray should use this only internally. If providing API functions
* that return the full array, this can be cached separately or returned
* directly. However since DrupalCacheArray holds partial content by design, it
* should be a normal PHP array or otherwise contain the full structure.
*
* Note also that due to limitations in PHP prior to 5.3.4, it is impossible to
* write directly to the contents of nested arrays contained in this object.
* Only writes to the top-level array elements are possible. So if you
* previously had set $object['foo'] = array(1, 2, 'bar' => 'baz'), but later
* want to change the value of 'bar' from 'baz' to 'foobar', you cannot do so
* a targeted write like $object['foo']['bar'] = 'foobar'. Instead, you must
* overwrite the entire top-level 'foo' array with the entire set of new
* values: $object['foo'] = array(1, 2, 'bar' => 'foobar'). Due to this same
* limitation, attempts to create references to any contained data, nested or
* otherwise, will fail silently. So $var = &$object['foo'] will not throw an
* error, and $var will be populated with the contents of $object['foo'], but
* that data will be passed by value, not reference. For more information on
* the PHP limitation, see the note in the official PHP documentation at·
* http://php.net/manual/arrayaccess.offsetget.php on
* ArrayAccess::offsetGet().
*
* By default, the class accounts for caches where calling functions might
* request keys in the array that won't exist even after a cache rebuild. This
* prevents situations where a cache rebuild would be triggered over and over
* due to a 'missing' item. These cases are stored internally as a value of
* NULL. This means that the offsetGet() and offsetExists() methods
* must be overridden if caching an array where the top level values can
* legitimately be NULL, and where $object->offsetExists() needs to correctly
* return (equivalent to array_key_exists() vs. isset()). This should not
* be necessary in the majority of cases.
*
* Classes extending this class must override at least the
* resolveCacheMiss() method to have a working implementation.
*
* offsetSet() is not overridden by this class by default. In practice this
* means that assigning an offset via arrayAccess will only apply while the
* object is in scope and will not be written back to the persistent cache.
* This follows a similar pattern to static vs. persistent caching in
* procedural code. Extending classes may wish to alter this behavior, for
* example by overriding offsetSet() and adding an automatic call to persist().
*
* @see SchemaCache
*/
abstract class DrupalCacheArray implements ArrayAccess {

/**
* A cid to pass to cache_set() and cache_get().
*/
protected $cid;

/**
* A bin to pass to cache_set() and cache_get().
*/
protected $bin;

/**
* An array of keys to add to the cache at the end of the request.
*/
protected $keysToPersist = array();

/**
* Storage for the data itself.
*/
protected $storage = array();

/**
* Constructs a DrupalCacheArray object.
*
* @param $cid
* The cid for the array being cached.
* @param $bin
* The bin to cache the array.
*/
public function __construct($cid, $bin) {
$this->cid = $cid;
$this->bin = $bin;

if ($cached = cache_get($this->cid, $this->bin)) {
$this->storage = $cached->data;
}
}

/**
* Implements ArrayAccess::offsetExists().
*/
public function offsetExists($offset) {
return $this->offsetGet($offset) !== NULL;
}

/**
* Implements ArrayAccess::offsetGet().
*/
public function offsetGet($offset) {
if (isset($this->storage[$offset]) || array_key_exists($offset, $this->storage)) {
return $this->storage[$offset];
}
else {
return $this->resolveCacheMiss($offset);
}
}

/**
* Implements ArrayAccess::offsetSet().
*/
public function offsetSet($offset, $value) {
$this->storage[$offset] = $value;
}

/**
* Implements ArrayAccess::offsetUnset().
*/
public function offsetUnset($offset) {
unset($this->storage[$offset]);
}

/**
* Flags an offset value to be written to the persistent cache.
*
* If a value is assigned to a cache object with offsetSet(), by default it
* will not be written to the persistent cache unless it is flagged with this
* method. This allows items to be cached for the duration of a request,
* without necessarily writing back to the persistent cache at the end.
*
* @param $offset
* The array offset that was requested.
* @param $persist
* Optional boolean to specify whether the offset should be persisted or
* not, defaults to TRUE. When called with $persist = FALSE the offset will
* be unflagged so that it will not be written at the end of the request.
*/
protected function persist($offset, $persist = TRUE) {
$this->keysToPersist[$offset] = $persist;
}

/**
* Resolves a cache miss.
*
* When an offset is not found in the object, this is treated as a cache
* miss. This method allows classes implementing the interface to look up
* the actual value and allow it to be cached.
*
* @param $offset
* The offset that was requested.
*
* @return
* The value of the offset, or NULL if no value was found.
*/
abstract protected function resolveCacheMiss($offset);

/**
* Writes a value to the persistent cache immediately.
*
* @param $data
* The data to write to the persistent cache.
* @param $lock
* Whether to acquire a lock before writing to cache.
*/
protected function set($data, $lock = TRUE) {
// Lock cache writes to help avoid stampedes.
// To implement locking for cache misses, override __construct().
$lock_name = $this->cid . ':' . $this->bin;
if (!$lock || lock_acquire($lock_name)) {
if ($cached = cache_get($this->cid, $this->bin)) {
$data = $cached->data + $data;
}
cache_set($this->cid, $data, $this->bin);
if ($lock) {
lock_release($lock_name);
}
}
}

/**
* Destructs the DrupalCacheArray object.
*/
public function __destruct() {
$data = array();
foreach ($this->keysToPersist as $offset => $persist) {
if ($persist) {
$data[$offset] = $this->storage[$offset];
}
}
if (!empty($data)) {
$this->set($data);
}
}
}

/**
* Starts the timer with the specified name.
*
* If you start and stop the same timer multiple times, the measured intervals
* will be accumulated.
*
* @param $name
* The name of the timer.
*/
function timer_start($name) {
global $timers;

$timers[$name]['start'] = microtime(TRUE);
$timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
}

/**
* Reads the current timer value without stopping the timer.
*
* @param $name
* The name of the timer.
*
* @return
* The current timer value in ms.
*/
function timer_read($name) {
global $timers;

if (isset($timers[$name]['start'])) {
$stop = microtime(TRUE);
$diff = round(($stop - $timers[$name]['start']) * 1000, 2);

if (isset($timers[$name]['time'])) {
$diff += $timers[$name]['time'];
}
return $diff;
}
return $timers[$name]['time'];
}

/**
* Stops the timer with the specified name.
*
* @param $name
* The name of the timer.
*
* @return
* A timer array. The array contains the number of times the timer has been
* started and stopped (count) and the accumulated timer value in ms (time).
*/
function timer_stop($name) {
global $timers;

if (isset($timers[$name]['start'])) {
$stop = microtime(TRUE);
$diff = round(($stop - $timers[$name]['start']) * 1000, 2);
if (isset($timers[$name]['time'])) {
$timers[$name]['time'] += $diff;
}
else {
$timers[$name]['time'] = $diff;
}
unset($timers[$name]['start']);
}

return $timers[$name];
}

/**
* Returns the appropriate configuration directory.
*
* Returns the configuration path based on the site's hostname, port, and
* pathname. See default.settings.php for examples on how the URL is converted
* to a directory.
*
* @param bool $require_settings
* Only configuration directories with an existing settings.php file
* will be recognized. Defaults to TRUE. During initial installation,
* this is set to FALSE so that Drupal can detect a matching directory,
* then create a new settings.php file in it.
* @param bool $reset
* Force a full search for matching directories even if one had been
* found previously. Defaults to FALSE.
*
* @return
* The path of the matching directory.
*
* @see default.settings.php
*/
function conf_path($require_settings = TRUE, $reset = FALSE) {
$conf = &drupal_static(__FUNCTION__, '');

if ($conf && !$reset) {
return $conf;
}

$confdir = 'sites';

$sites = array();
if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/sites.php')) {
// This will overwrite $sites with the desired mappings.
include(DRUPAL_ROOT . '/' . $confdir . '/sites.php');
}

$uri = explode('/', $_SERVER['SCRIPT_NAME'] ? $_SERVER['SCRIPT_NAME'] : $_SERVER['SCRIPT_FILENAME']);
$server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
for ($i = count($uri) - 1; $i > 0; $i--) {
for ($j = count($server); $j > 0; $j--) {
$dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
if (isset($sites[$dir]) && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $sites[$dir])) {
$dir = $sites[$dir];
}
if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir . '/settings.php') || (!$require_settings && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir))) {
$conf = "$confdir/$dir";
return $conf;
}
}
}
$conf = "$confdir/default";
return $conf;
}

/**
* Sets appropriate server variables needed for command line scripts to work.
*
* This function can be called by command line scripts before bootstrapping
* Drupal, to ensure that the page loads with the desired server parameters.
* This is because many parts of Drupal assume that they are running in a web
* browser and therefore use information from the global PHP $_SERVER variable
* that does not get set when Drupal is run from the command line.
*
* In many cases, the default way in which this function populates the $_SERVER
* variable is sufficient, and it can therefore be called without passing in
* any input. However, command line scripts running on a multisite installation
* (or on any installation that has settings.php stored somewhere other than
* the sites/default folder) need to pass in the URL of the site to allow
* Drupal to detect the correct location of the settings.php file. Passing in
* the 'url' parameter is also required for functions like request_uri() to
* return the expected values.
*
* Most other parameters do not need to be passed in, but may be necessary in
* some cases; for example, if Drupal's ip_address() function needs to return
* anything but the standard localhost value ('127.0.0.1'), the command line
* script should pass in the desired value via the 'REMOTE_ADDR' key.
*
* @param $variables
* (optional) An associative array of variables within $_SERVER that should
* be replaced. If the special element 'url' is provided in this array, it
* will be used to populate some of the server defaults; it should be set to
* the URL of the current page request, excluding any $_GET request but
* including the script name (e.g., http://www.example.com/mysite/index.php).
*
* @see conf_path()
* @see request_uri()
* @see ip_address()
*/
function drupal_override_server_variables($variables = array()) {
// Allow the provided URL to override any existing values in $_SERVER.
if (isset($variables['url'])) {
$url = parse_url($variables['url']);
if (isset($url['host'])) {
$_SERVER['HTTP_HOST'] = $url['host'];
}
if (isset($url['path'])) {
$_SERVER['SCRIPT_NAME'] = $url['path'];
}
unset($variables['url']);
}
// Define default values for $_SERVER keys. These will be used if $_SERVER
// does not already define them and no other values are passed in to this
// function.
$defaults = array(
'HTTP_HOST' => 'localhost',
'SCRIPT_NAME' => NULL,
'REMOTE_ADDR' => '127.0.0.1',
'REQUEST_METHOD' => 'GET',
'SERVER_NAME' => NULL,
'SERVER_SOFTWARE' => NULL,
'HTTP_USER_AGENT' => NULL,
);
// Replace elements of the $_SERVER array, as appropriate.
$_SERVER = $variables + $_SERVER + $defaults;
}

/**
* Initializes the PHP environment.
*/
function drupal_environment_initialize() {
if (!isset($_SERVER['HTTP_REFERER'])) {
$_SERVER['HTTP_REFERER'] = '';
}
if (!isset($_SERVER['SERVER_PROTOCOL']) || ($_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.0' && $_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.1')) {
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
}

if (isset($_SERVER['HTTP_HOST'])) {
// As HTTP_HOST is user input, ensure it only contains characters allowed
// in hostnames. See RFC 952 (and RFC 2181).
// $_SERVER['HTTP_HOST'] is lowercased here per specifications.
$_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']);
if (!drupal_valid_http_host($_SERVER['HTTP_HOST'])) {
// HTTP_HOST is invalid, e.g. if containing slashes it may be an attack.
header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
exit;
}
}
else {
// Some pre-HTTP/1.1 clients will not send a Host header. Ensure the key is
// defined for E_ALL compliance.
$_SERVER['HTTP_HOST'] = '';
}

// When clean URLs are enabled, emulate ?q=foo/bar using REQUEST_URI. It is
// not possible to append the query string using mod_rewrite without the B
// flag (this was added in Apache 2.2.8), because mod_rewrite unescapes the
// path before passing it on to PHP. This is a problem when the path contains
// e.g. "&" or "%" that have special meanings in URLs and must be encoded.
$_GET['q'] = request_path();

// Enforce E_ALL, but allow users to set levels not part of E_ALL.
error_reporting(E_ALL | error_reporting());

// Override PHP settings required for Drupal to work properly.
// sites/default/default.settings.php contains more runtime settings.
// The .htaccess file contains settings that cannot be changed at runtime.

// Don't escape quotes when reading files from the database, disk, etc.
ini_set('magic_quotes_runtime', '0');
// Use session cookies, not transparent sessions that puts the session id in
// the query string.
ini_set('session.use_cookies', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.use_trans_sid', '0');
// Don't send HTTP headers using PHP's session handler.
// An empty string is used here to disable the cache limiter.
ini_set('session.cache_limiter', '');
// Use httponly session cookies.
ini_set('session.cookie_httponly', '1');

// Set sane locale settings, to ensure consistent string, dates, times and
// numbers handling.
setlocale(LC_ALL, 'C');
}

/**
* Validates that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
*
* @return
* TRUE if only containing valid characters, or FALSE otherwise.
*/
function drupal_valid_http_host($host) {
// Limit the length of the host name to 1000 bytes to prevent DoS attacks with
// long host names.
return strlen($host) <= 1000
// Limit the number of subdomains and port separators to prevent DoS attacks
// in conf_path().
&& substr_count($host, '.') <= 100
&& substr_count($host, ':') <= 100
&& preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host);
}

/**
* Checks whether an HTTPS request is being served.
*
* @return bool
* TRUE if the request is HTTPS, FALSE otherwise.
*/
function drupal_is_https() {
return isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
}

/**
* Sets the base URL, cookie domain, and session name from configuration.
*/
function drupal_settings_initialize() {
global $base_url, $base_path, $base_root;

// Export these settings.php variables to the global namespace.
global $databases, $cookie_domain, $conf, $installed_profile, $update_free_access, $db_url, $db_prefix, $drupal_hash_salt, $is_https, $base_secure_url, $base_insecure_url;
$conf = array();

if (file_exists(DRUPAL_ROOT . '/' . conf_path() . '/settings.php')) {
include_once DRUPAL_ROOT . '/' . conf_path() . '/settings.php';
}
$is_https = drupal_is_https();

if (isset($base_url)) {
// Parse fixed base URL from settings.php.
$parts = parse_url($base_url);
if (!isset($parts['path'])) {
$parts['path'] = '';
}
$base_path = $parts['path'] . '/';
// Build $base_root (everything until first slash after "scheme://").
$base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
}
else {
// Create base URL.
$http_protocol = $is_https ? 'https' : 'http';
$base_root = $http_protocol . '://' . $_SERVER['HTTP_HOST'];

$base_url = $base_root;

// $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
// be modified by a visitor.
if ($dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/')) {
$base_path = $dir;
$base_url .= $base_path;
$base_path .= '/';
}
else {
$base_path = '/';
}
}
$base_secure_url = str_replace('http://', 'https://', $base_url);
$base_insecure_url = str_replace('https://', 'http://', $base_url);

if ($cookie_domain) {
// If the user specifies the cookie domain, also use it for session name.
$session_name = $cookie_domain;
}
else {
// Otherwise use $base_url as session name, without the protocol
// to use the same session identifiers across HTTP and HTTPS.
list( , $session_name) = explode('://', $base_url, 2);
// HTTP_HOST can be modified by a visitor, but we already sanitized it
// in drupal_settings_initialize().
if (!empty($_SERVER['HTTP_HOST'])) {
$cookie_domain = $_SERVER['HTTP_HOST'];
// Strip leading periods, www., and port numbers from cookie domain.
$cookie_domain = ltrim($cookie_domain, '.');
if (strpos($cookie_domain, 'www.') === 0) {
$cookie_domain = substr($cookie_domain, 4);
}
$cookie_domain = explode(':', $cookie_domain);
$cookie_domain = '.' . $cookie_domain[0];
}
}
// Per RFC 2109, cookie domains must contain at least one dot other than the
// first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
ini_set('session.cookie_domain', $cookie_domain);
}
// To prevent session cookies from being hijacked, a user can configure the
// SSL version of their website to only transfer session cookies via SSL by
// using PHP's session.cookie_secure setting. The browser will then use two
// separate session cookies for the HTTPS and HTTP versions of the site. So we
// must use different session identifiers for HTTPS and HTTP to prevent a
// cookie collision.
if ($is_https) {
ini_set('session.cookie_secure', TRUE);
}
$prefix = ini_get('session.cookie_secure') ? 'SSESS' : 'SESS';
session_name($prefix . substr(hash('sha256', $session_name), 0, 32));
}

/**
* Returns and optionally sets the filename for a system resource.
*
* The filename, whether provided, cached, or retrieved from the database, is
* only returned if the file exists.
*
* This function plays a key role in allowing Drupal's resources (modules
* and themes) to be located in different places depending on a site's
* configuration. For example, a module 'foo' may legally be located
* in any of these three places:
*
* modules/foo/foo.module
* sites/all/modules/foo/foo.module
* sites/example.com/modules/foo/foo.module
*
* Calling drupal_get_filename('module', 'foo') will give you one of
* the above, depending on where the module is located.
*
* @param $type
* The type of the item (theme, theme_engine, module, profile).
* @param $name
* The name of the item for which the filename is requested.
* @param $filename
* The filename of the item if it is to be set explicitly rather
* than by consulting the database.
* @param bool $trigger_error
* Whether to trigger an error when a file is missing or has unexpectedly
* moved. This defaults to TRUE, but can be set to FALSE by calling code that
* merely wants to check whether an item exists in the filesystem.
*
* @return
* The filename of the requested item or NULL if the item is not found.
*/
function drupal_get_filename($type, $name, $filename = NULL, $trigger_error = TRUE) {
// The $files static variable will hold the locations of all requested files.
// We can be sure that any file listed in this static variable actually
// exists as all additions have gone through a file_exists() check.
// The location of files will not change during the request, so do not use
// drupal_static().
static $files = array();

// Profiles are a special case: they have a fixed location and naming.
if ($type == 'profile') {
$profile_filename = "profiles/$name/$name.profile";
$files[$type][$name] = file_exists($profile_filename) ? $profile_filename : FALSE;
}
if (!isset($files[$type])) {
$files[$type] = array();
}

if (!empty($filename) && file_exists($filename)) {
// Prime the static cache with the provided filename.
$files[$type][$name] = $filename;
}
elseif (isset($files[$type][$name])) {
// This item had already been found earlier in the request, either through
// priming of the static cache (for example, in system_list()), through a
// lookup in the {system} table, or through a file scan (cached or not). Do
// nothing.
}
else {
// Look for the filename listed in the {system} table. Verify that we have
// an active database connection before doing so, since this function is
// called both before we have a database connection (i.e. during
// installation) and when a database connection fails.
$database_unavailable = TRUE;
try {
if (function_exists('db_query')) {
$file = db_query("SELECT filename FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
if ($file !== FALSE && file_exists(DRUPAL_ROOT . '/' . $file)) {
$files[$type][$name] = $file;
}
$database_unavailable = FALSE;
}
}
catch (Exception $e) {
// The database table may not exist because Drupal is not yet installed,
// the database might be down, or we may have done a non-database cache
// flush while $conf['page_cache_without_database'] = TRUE and
// $conf['page_cache_invoke_hooks'] = TRUE. We have a fallback for these
// cases so we hide the error completely.
}
// Fall back to searching the filesystem if the database could not find the
// file or the file does not exist at the path returned by the database.
if (!isset($files[$type][$name])) {
$files[$type][$name] = _drupal_get_filename_fallback($type, $name, $trigger_error, $database_unavailable);
}
}

if (isset($files[$type][$name])) {
return $files[$type][$name];
}
}

/**
* Performs a cached file system scan as a fallback when searching for a file.
*
* This function looks for the requested file by triggering a file scan,
* caching the new location if the file has moved and caching the miss
* if the file is missing. If a file had been marked as missing in a previous
* file scan, or if it has been marked as moved and is still in the last known
* location, no new file scan will be performed.
*
* @param string $type
* The type of the item (theme, theme_engine, module, profile).
* @param string $name
* The name of the item for which the filename is requested.
* @param bool $trigger_error
* Whether to trigger an error when a file is missing or has unexpectedly
* moved.
* @param bool $database_unavailable
* Whether this function is being called because the Drupal database could
* not be queried for the file's location.
*
* @return
* The filename of the requested item or NULL if the item is not found.
*
* @see drupal_get_filename()
*/
function _drupal_get_filename_fallback($type, $name, $trigger_error, $database_unavailable) {
$file_scans = &_drupal_file_scan_cache();
$filename = NULL;

// If the cache indicates that the item is missing, or we can verify that the
// item exists in the location the cache says it exists in, use that.
if (isset($file_scans[$type][$name]) && ($file_scans[$type][$name] === FALSE || file_exists($file_scans[$type][$name]))) {
$filename = $file_scans[$type][$name];
}
// Otherwise, perform a new file scan to find the item.
else {
$filename = _drupal_get_filename_perform_file_scan($type, $name);
// Update the static cache, and mark the persistent cache for updating at
// the end of the page request. See drupal_file_scan_write_cache().
$file_scans[$type][$name] = $filename;
$file_scans['#write_cache'] = TRUE;
}

// If requested, trigger a user-level warning about the missing or
// unexpectedly moved file. If the database was unavailable, do not trigger a
// warning in the latter case, though, since if the {system} table could not
// be queried there is no way to know if the location found here was
// "unexpected" or not.
if ($trigger_error) {
$error_type = $filename === FALSE ? 'missing' : 'moved';
if ($error_type == 'missing' || !$database_unavailable) {
_drupal_get_filename_fallback_trigger_error($type, $name, $error_type);
}
}

// The cache stores FALSE for files that aren't found (to be able to
// distinguish them from files that have not yet been searched for), but
// drupal_get_filename() expects NULL for these instead, so convert to NULL
// before returning.
if ($filename === FALSE) {
$filename = NULL;
}
return $filename;
}

/**
* Returns the current list of cached file system scan results.
*
* @return
* An associative array tracking the most recent file scan results for all
* files that have had scans performed. The keys are the type and name of the
* item that was searched for, and the values can be either:
* - Boolean FALSE if the item was not found in the file system.
* - A string pointing to the location where the item was found.
*/
function &_drupal_file_scan_cache() {
$file_scans = &drupal_static(__FUNCTION__, array());

// The file scan results are stored in a persistent cache (in addition to the
// static cache) but because this function can be called before the
// persistent cache is available, we must merge any items that were found
// earlier in the page request into the results from the persistent cache.
if (!isset($file_scans['#cache_merge_done'])) {
try {
if (function_exists('cache_get')) {
$cache = cache_get('_drupal_file_scan_cache', 'cache_bootstrap');
if (!empty($cache->data)) {
// File scan results from the current request should take precedence
// over the results from the persistent cache, since they are newer.
$file_scans = drupal_array_merge_deep($cache->data, $file_scans);
}
// Set a flag to indicate that the persistent cache does not need to be
// merged again.
$file_scans['#cache_merge_done'] = TRUE;
}
}
catch (Exception $e) {
// Hide the error.
}
}

return $file_scans;
}

/**
* Performs a file system scan to search for a system resource.
*
* @param $type
* The type of the item (theme, theme_engine, module, profile).
* @param $name
* The name of the item for which the filename is requested.
*
* @return
* The filename of the requested item or FALSE if the item is not found.
*
* @see drupal_get_filename()
* @see _drupal_get_filename_fallback()
*/
function _drupal_get_filename_perform_file_scan($type, $name) {
// The location of files will not change during the request, so do not use
// drupal_static().
static $dirs = array(), $files = array();

// We have a consistent directory naming: modules, themes...
$dir = $type . 's';
if ($type == 'theme_engine') {
$dir = 'themes/engines';
$extension = 'engine';
}
elseif ($type == 'theme') {
$extension = 'info';
}
else {
$extension = $type;
}

// Check if we had already scanned this directory/extension combination.
if (!isset($dirs[$dir][$extension])) {
// Log that we have now scanned this directory/extension combination
// into a static variable so as to prevent unnecessary file scans.
$dirs[$dir][$extension] = TRUE;
if (!function_exists('drupal_system_listing')) {
require_once DRUPAL_ROOT . '/includes/common.inc';
}
// Scan the appropriate directories for all files with the requested
// extension, not just the file we are currently looking for. This
// prevents unnecessary scans from being repeated when this function is
// called more than once in the same page request.
$matches = drupal_system_listing("/^" . DRUPAL_PHP_FUNCTION_PATTERN . "\.$extension$/", $dir, 'name', 0);
foreach ($matches as $matched_name => $file) {
// Log the locations found in the file scan into a static variable.
$files[$type][$matched_name] = $file->uri;
}
}

// Return the results of the file system scan, or FALSE to indicate the file
// was not found.
return isset($files[$type][$name]) ? $files[$type][$name] : FALSE;
}

/**
* Triggers a user-level warning for missing or unexpectedly moved files.
*
* @param $type
* The type of the item (theme, theme_engine, module, profile).
* @param $name
* The name of the item for which the filename is requested.
* @param $error_type
* The type of the error ('missing' or 'moved').
*
* @see drupal_get_filename()
* @see _drupal_get_filename_fallback()
*/
function _drupal_get_filename_fallback_trigger_error($type, $name, $error_type) {
// Hide messages due to known bugs that will appear on a lot of sites.
// @todo Remove this in https://www.drupal.org/node/2383823
if (empty($name)) {
return;
}

// Make sure we only show any missing or moved file errors only once per
// request.
static $errors_triggered = array();
if (empty($errors_triggered[$type][$name][$error_type])) {
// Use _drupal_trigger_error_with_delayed_logging() here since these are
// triggered during low-level operations that cannot necessarily be
// interrupted by a watchdog() call.
if ($error_type == 'missing') {
_drupal_trigger_error_with_delayed_logging(format_string('The following @type is missing from the file system: %name. For information about how to fix this, see <a href="@documentation">the documentation page</a>.', array('@type' => $type, '%name' => $name, '@documentation' => 'https://www.drupal.org/node/2487215')), E_USER_WARNING);
}
elseif ($error_type == 'moved') {
_drupal_trigger_error_with_delayed_logging(format_string('The following @type has moved within the file system: %name. In order to fix this, clear caches or put the @type back in its original location. For more information, see <a href="@documentation">the documentation page</a>.', array('@type' => $type, '%name' => $name, '@documentation' => 'https://www.drupal.org/node/2487215')), E_USER_WARNING);
}
$errors_triggered[$type][$name][$error_type] = TRUE;
}
}

/**
* Invokes trigger_error() with logging delayed until the end of the request.
*
* This is an alternative to PHP's trigger_error() function which can be used
* during low-level Drupal core operations that need to avoid being interrupted
* by a watchdog() call.
*
* Normally, Drupal's error handler calls watchdog() in response to a
* trigger_error() call. However, this invokes hook_watchdog() which can run
* arbitrary code. If the trigger_error() happens in the middle of an
* operation such as a rebuild operation which should not be interrupted by
* arbitrary code, that could potentially break or trigger the rebuild again.
* This function protects against that by delaying the watchdog() call until
* the end of the current page request.
*
* This is an internal function which should only be called by low-level Drupal
* core functions. It may be removed in a future Drupal 7 release.
*
* @param string $error_msg
* The error message to trigger. As with trigger_error() itself, this is
* limited to 1024 bytes; additional characters beyond that will be removed.
* @param int $error_type
* (optional) The type of error. This should be one of the E_USER family of
* constants. As with trigger_error() itself, this defaults to E_USER_NOTICE
* if not provided.
*
* @see _drupal_log_error()
*/
function _drupal_trigger_error_with_delayed_logging($error_msg, $error_type = E_USER_NOTICE) {
$delay_logging = &drupal_static(__FUNCTION__, FALSE);
$delay_logging = TRUE;
trigger_error($error_msg, $error_type);
$delay_logging = FALSE;
}

/**
* Writes the file scan cache to the persistent cache.
*
* This cache stores all files marked as missing or moved after a file scan
* to prevent unnecessary file scans in subsequent requests. This cache is
* cleared in system_list_reset() (i.e. after a module/theme rebuild).
*/
function drupal_file_scan_write_cache() {
// Only write to the persistent cache if requested, and if we know that any
// data previously in the cache was successfully loaded and merged in by
// _drupal_file_scan_cache().
$file_scans = &_drupal_file_scan_cache();
if (isset($file_scans['#write_cache']) && isset($file_scans['#cache_merge_done'])) {
unset($file_scans['#write_cache']);
cache_set('_drupal_file_scan_cache', $file_scans, 'cache_bootstrap');
}
}

/**
* Loads the persistent variable table.
*
* The variable table is composed of values that have been saved in the table
* with variable_set() as well as those explicitly specified in the
* configuration file.
*/
function variable_initialize($conf = array()) {
// NOTE: caching the variables improves performance by 20% when serving
// cached pages.
if ($cached = cache_get('variables', 'cache_bootstrap')) {
$variables = $cached->data;
}
else {
// Cache miss. Avoid a stampede.
$name = 'variable_init';
if (!lock_acquire($name, 1)) {
// Another request is building the variable cache.
// Wait, then re-run this function.
lock_wait($name);
return variable_initialize($conf);
}
else {
// Proceed with variable rebuild.
$variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
cache_set('variables', $variables, 'cache_bootstrap');
lock_release($name);
}
}

foreach ($conf as $name => $value) {
$variables[$name] = $value;
}

return $variables;
}

/**
* Returns a persistent variable.
*
* Case-sensitivity of the variable_* functions depends on the database
* collation used. To avoid problems, always use lower case for persistent
* variable names.
*
* @param $name
* The name of the variable to return.
* @param $default
* The default value to use if this variable has never been set.
*
* @return
* The value of the variable. Unserialization is taken care of as necessary.
*
* @see variable_del()
* @see variable_set()
*/
function variable_get($name, $default = NULL) {
global $conf;

return isset($conf[$name]) ? $conf[$name] : $default;
}

/**
* Sets a persistent variable.
*
* Case-sensitivity of the variable_* functions depends on the database
* collation used. To avoid problems, always use lower case for persistent
* variable names.
*
* @param $name
* The name of the variable to set.
* @param $value
* The value to set. This can be any PHP data type; these functions take care
* of serialization as necessary.
*
* @see variable_del()
* @see variable_get()
*/
function variable_set($name, $value) {
global $conf;

db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();

cache_clear_all('variables', 'cache_bootstrap');

$conf[$name] = $value;
}

/**
* Unsets a persistent variable.
*
* Case-sensitivity of the variable_* functions depends on the database
* collation used. To avoid problems, always use lower case for persistent
* variable names.
*
* @param $name
* The name of the variable to undefine.
*
* @see variable_get()
* @see variable_set()
*/
function variable_del($name) {
global $conf;

db_delete('variable')
->condition('name', $name)
->execute();
cache_clear_all('variables', 'cache_bootstrap');

unset($conf[$name]);
}

/**
* Retrieves the current page from the cache.
*
* Note: we do not serve cached pages to authenticated users, or to anonymous
* users when $_SESSION is non-empty. $_SESSION may contain status messages
* from a form submission, the contents of a shopping cart, or other user-
* specific content that should not be cached and displayed to other users.
*
* @param $check_only
* (optional) Set to TRUE to only return whether a previous call found a
* cache entry.
*
* @return
* The cache object, if the page was found in the cache, NULL otherwise.
*/
function drupal_page_get_cache($check_only = FALSE) {
global $base_root;
static $cache_hit = FALSE;

if ($check_only) {
return $cache_hit;
}

if (drupal_page_is_cacheable()) {
$cache = cache_get($base_root . request_uri(), 'cache_page');
if ($cache !== FALSE) {
$cache_hit = TRUE;
}
return $cache;
}
}

/**
* Determines the cacheability of the current page.
*
* @param $allow_caching
* Set to FALSE if you want to prevent this page from being cached.
*
* @return
* TRUE if the current page can be cached, FALSE otherwise.
*/
function drupal_page_is_cacheable($allow_caching = NULL) {
$allow_caching_static = &drupal_static(__FUNCTION__, TRUE);
if (isset($allow_caching)) {
$allow_caching_static = $allow_caching;
}

return $allow_caching_static && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')
&& !drupal_is_cli();
}

/**
* Invokes a bootstrap hook in all bootstrap modules that implement it.
*
* @param $hook
* The name of the bootstrap hook to invoke.
*
* @see bootstrap_hooks()
*/
function bootstrap_invoke_all($hook) {
// Bootstrap modules should have been loaded when this function is called, so
// we don't need to tell module_list() to reset its internal list (and we
// therefore leave the first parameter at its default value of FALSE). We
// still pass in TRUE for the second parameter, though; in case this is the
// first time during the bootstrap that module_list() is called, we want to
// make sure that its internal cache is primed with the bootstrap modules
// only.
foreach (module_list(FALSE, TRUE) as $module) {
drupal_load('module', $module);
module_invoke($module, $hook);
}
}

/**
* Includes a file with the provided type and name.
*
* This prevents including a theme, engine, module, etc., more than once.
*
* @param $type
* The type of item to load (i.e. theme, theme_engine, module).
* @param $name
* The name of the item to load.
*
* @return
* TRUE if the item is loaded or has already been loaded.
*/
function drupal_load($type, $name) {
// Once a file is included this can't be reversed during a request so do not
// use drupal_static() here.
static $files = array();

if (isset($files[$type][$name])) {
return TRUE;
}

$filename = drupal_get_filename($type, $name);

if ($filename) {
include_once DRUPAL_ROOT . '/' . $filename;
$files[$type][$name] = TRUE;

return TRUE;
}

return FALSE;
}

/**
* Sets an HTTP response header for the current page.
*
* Note: When sending a Content-Type header, always include a 'charset' type,
* too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
*
* @param $name
* The HTTP header name, or the special 'Status' header name.
* @param $value
* The HTTP header value; if equal to FALSE, the specified header is unset.
* If $name is 'Status', this is expected to be a status code followed by a
* reason phrase, e.g. "404 Not Found".
* @param $append
* Whether to append the value to an existing header or to replace it.
*/
function drupal_add_http_header($name, $value, $append = FALSE) {
// The headers as name/value pairs.
$headers = &drupal_static('drupal_http_headers', array());

$name_lower = strtolower($name);
_drupal_set_preferred_header_name($name);

if ($value === FALSE) {
$headers[$name_lower] = FALSE;
}
elseif (isset($headers[$name_lower]) && $append) {
// Multiple headers with identical names may be combined using comma (RFC
// 2616, section 4.2).
$headers[$name_lower] .= ',' . $value;
}
else {
$headers[$name_lower] = $value;
}
drupal_send_headers(array($name => $headers[$name_lower]), TRUE);
}

/**
* Gets the HTTP response headers for the current page.
*
* @param $name
* An HTTP header name. If omitted, all headers are returned as name/value
* pairs. If an array value is FALSE, the header has been unset.
*
* @return
* A string containing the header value, or FALSE if the header has been set,
* or NULL if the header has not been set.
*/
function drupal_get_http_header($name = NULL) {
$headers = &drupal_static('drupal_http_headers', array());
if (isset($name)) {
$name = strtolower($name);
return isset($headers[$name]) ? $headers[$name] : NULL;
}
else {
return $headers;
}
}

/**
* Sets the preferred name for the HTTP header.
*
* Header names are case-insensitive, but for maximum compatibility they should
* follow "common form" (see RFC 2617, section 4.2).
*/
function _drupal_set_preferred_header_name($name = NULL) {
static $header_names = array();

if (!isset($name)) {
return $header_names;
}
$header_names[strtolower($name)] = $name;
}

/**
* Sends the HTTP response headers that were previously set, adding defaults.
*
* Headers are set in drupal_add_http_header(). Default headers are not set
* if they have been replaced or unset using drupal_add_http_header().
*
* @param array $default_headers
* (optional) An array of headers as name/value pairs.
* @param bool $only_default
* (optional) If TRUE and headers have already been sent, send only the
* specified headers.
*/
function drupal_send_headers($default_headers = array(), $only_default = FALSE) {
$headers_sent = &drupal_static(__FUNCTION__, FALSE);
$headers = drupal_get_http_header();
if ($only_default && $headers_sent) {
$headers = array();
}
$headers_sent = TRUE;

$header_names = _drupal_set_preferred_header_name();
foreach ($default_headers as $name => $value) {
$name_lower = strtolower($name);
if (!isset($headers[$name_lower])) {
$headers[$name_lower] = $value;
$header_names[$name_lower] = $name;
}
}
foreach ($headers as $name_lower => $value) {
if ($name_lower == 'status') {
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $value);
}
// Skip headers that have been unset.
elseif ($value !== FALSE) {
header($header_names[$name_lower] . ': ' . $value);
}
}
}

/**
* Sets HTTP headers in preparation for a page response.
*
* Authenticated users are always given a 'no-cache' header, and will fetch a
* fresh page on every request. This prevents authenticated users from seeing
* locally cached pages.
*
* ETag and Last-Modified headers are not set per default for authenticated
* users so that browsers do not send If-Modified-Since headers from
* authenticated user pages. drupal_serve_page_from_cache() will set appropriate
* ETag and Last-Modified headers for cached pages.
*
* @see drupal_page_set_cache()
*/
function drupal_page_header() {
$headers_sent = &drupal_static(__FUNCTION__, FALSE);
if ($headers_sent) {
return TRUE;
}
$headers_sent = TRUE;

$default_headers = array(
'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
'Cache-Control' => 'no-cache, must-revalidate',
// Prevent browsers from sniffing a response and picking a MIME type
// different from the declared content-type, since that can lead to
// XSS and other vulnerabilities.
'X-Content-Type-Options' => 'nosniff',
);
drupal_send_headers($default_headers);
}

/**
* Sets HTTP headers in preparation for a cached page response.
*
* The headers allow as much as possible in proxies and browsers without any
* particular knowledge about the pages. Modules can override these headers
* using drupal_add_http_header().
*
* If the request is conditional (using If-Modified-Since and If-None-Match),
* and the conditions match those currently in the cache, a 304 Not Modified
* response is sent.
*/
function drupal_serve_page_from_cache(stdClass $cache) {
// Negotiate whether to use compression.
$page_compression = !empty($cache->data['page_compressed']);
$return_compressed = $page_compression && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE;

// Get headers set in hook_boot(). Keys are lower-case.
$hook_boot_headers = drupal_get_http_header();

// Headers generated in this function, that may be replaced or unset using
// drupal_add_http_headers(). Keys are mixed-case.
$default_headers = array();

foreach ($cache->data['headers'] as $name => $value) {
// In the case of a 304 response, certain headers must be sent, and the
// remaining may not (see RFC 2616, section 10.3.5). Do not override
// headers set in hook_boot().
$name_lower = strtolower($name);
if (in_array($name_lower, array('content-location', 'expires', 'cache-control', 'vary')) && !isset($hook_boot_headers[$name_lower])) {
drupal_add_http_header($name, $value);
unset($cache->data['headers'][$name]);
}
}

// If the client sent a session cookie, a cached copy will only be served
// to that one particular client due to Vary: Cookie. Thus, do not set
// max-age > 0, allowing the page to be cached by external proxies, when a
// session cookie is present unless the Vary header has been replaced or
// unset in hook_boot().
$max_age = !isset($_COOKIE[session_name()]) || isset($hook_boot_headers['vary']) ? variable_get('page_cache_maximum_age', 0) : 0;
$default_headers['Cache-Control'] = 'public, max-age=' . $max_age;

// Entity tag should change if the output changes.
$etag = '"' . $cache->created . '-' . intval($return_compressed) . '"';
header('Etag: ' . $etag);

// See if the client has provided the required HTTP headers.
$if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : FALSE;
$if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : FALSE;

if ($if_modified_since && $if_none_match
&& $if_none_match == $etag // etag must match
&& $if_modified_since == $cache->created) { // if-modified-since must match
header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
drupal_send_headers($default_headers);
return;
}

// Send the remaining headers.
foreach ($cache->data['headers'] as $name => $value) {
drupal_add_http_header($name, $value);
}

$default_headers['Last-Modified'] = gmdate(DATE_RFC7231, $cache->created);

// HTTP/1.0 proxies does not support the Vary header, so prevent any caching
// by sending an Expires date in the past. HTTP/1.1 clients ignores the
// Expires header if a Cache-Control: max-age= directive is specified (see RFC
// 2616, section 14.9.3).
$default_headers['Expires'] = 'Sun, 19 Nov 1978 05:00:00 GMT';

drupal_send_headers($default_headers);

// Allow HTTP proxies to cache pages for anonymous users without a session
// cookie. The Vary header is used to indicates the set of request-header
// fields that fully determines whether a cache is permitted to use the
// response to reply to a subsequent request for a given URL without
// revalidation. If a Vary header has been set in hook_boot(), it is assumed
// that the module knows how to cache the page.
if (!isset($hook_boot_headers['vary']) && !variable_get('omit_vary_cookie')) {
header('Vary: Cookie');
}

if ($page_compression) {
header('Vary: Accept-Encoding', FALSE);
// If page_compression is enabled, the cache contains gzipped data.
if ($return_compressed) {
// $cache->data['body'] is already gzip'ed, so make sure
// zlib.output_compression does not compress it once more.
ini_set('zlib.output_compression', '0');
header('Content-Encoding: gzip');
}
else {
// The client does not support compression, so unzip the data in the
// cache. Strip the gzip header and run uncompress.
$cache->data['body'] = gzinflate(substr(substr($cache->data['body'], 10), 0, -8));
}
}

// Print the page.
print $cache->data['body'];
}

/**
* Defines the critical hooks that force modules to always be loaded.
*/
function bootstrap_hooks() {
return array('boot', 'exit', 'watchdog', 'language_init');
}

/**
* Unserializes and appends elements from a serialized string.
*
* @param $obj
* The object to which the elements are appended.
* @param $field
* The attribute of $obj whose value should be unserialized.
*/
function drupal_unpack($obj, $field = 'data') {
if ($obj->$field && $data = unserialize($obj->$field)) {
foreach ($data as $key => $value) {
if (!empty($key) && !isset($obj->$key)) {
$obj->$key = $value;
}
}
}
return $obj;
}

/**
* Translates a string to the current language or to a given language.
*
* The t() function serves two purposes. First, at run-time it translates
* user-visible text into the appropriate language. Second, various mechanisms
* that figure out what text needs to be translated work off t() -- the text
* inside t() calls is added to the database of strings to be translated.
* These strings are expected to be in English, so the first argument should
* always be in English. To enable a fully-translatable site, it is important
* that all human-readable text that will be displayed on the site or sent to
* a user is passed through the t() function, or a related function. See the
* @link http://drupal.org/node/322729 Localization API @endlink pages for
* more information, including recommendations on how to break up or not
* break up strings for translation.
*
* @section sec_translating_vars Translating Variables
* You should never use t() to translate variables, such as calling
* @code t($text); @endcode, unless the text that the variable holds has been
* passed through t() elsewhere (e.g., $text is one of several translated
* literal strings in an array). It is especially important never to call
* @code t($user_text); @endcode, where $user_text is some text that a user
* entered - doing that can lead to cross-site scripting and other security
* problems. However, you can use variable substitution in your string, to put
* variable text such as user names or link URLs into translated text. Variable
* substitution looks like this:
* @code
* $text = t("@name's blog", array('@name' => format_username($account)));
* @endcode
* Basically, you can put variables like @name into your string, and t() will
* substitute their sanitized values at translation time. (See the
* Localization API pages referenced above and the documentation of
* format_string() for details about how to define variables in your string.)
* Translators can then rearrange the string as necessary for the language
* (e.g., in Spanish, it might be "blog de @name").
*
* @section sec_alt_funcs_install Use During Installation Phase
* During the Drupal installation phase, some resources used by t() wil not be
* available to code that needs localization. See st() and get_t() for
* alternatives.
*
* @section sec_context String context
* Matching source strings are normally only translated once, and the same
* translation is used everywhere that has a matching string. However, in some
* cases, a certain English source string needs to have multiple translations.
* One example of this is the string "May", which could be used as either a
* full month name or a 3-letter abbreviated month. In other languages where
* the month name for May has more than 3 letters, you would need to provide
* two different translations (one for the full name and one abbreviated), and
* the correct form would need to be chosen, depending on how "May" is being
* used. To facilitate this, the "May" string should be provided with two
* different contexts in the $options parameter when calling t(). For example:
* @code
* t('May', array(), array('context' => 'Long month name')
* t('May', array(), array('context' => 'Abbreviated month name')
* @endcode
* See https://localize.drupal.org/node/2109 for more information.
*
* @param $string
* A string containing the English string to translate.
* @param $args
* An associative array of replacements to make after translation. Based
* on the first character of the key, the value is escaped and/or themed.
* See format_string() for details.
* @param $options
* An associative array of additional options, with the following elements:
* - 'langcode' (defaults to the current language): The language code to
* translate to a language other than what is used to display the page.
* - 'context' (defaults to the empty context): A string giving the context
* that the source string belongs to. See @ref sec_context above for more
* information.
*
* @return
* The translated string.
*
* @see st()
* @see get_t()
* @see format_string()
* @ingroup sanitization
*/
function t($string, array $args = array(), array $options = array()) {
global $language;
static $custom_strings;

// Merge in default.
if (empty($options['langcode'])) {
$options['langcode'] = isset($language->language) ? $language->language : 'en';
}
if (empty($options['context'])) {
$options['context'] = '';
}

// First, check for an array of customized strings. If present, use the array
// *instead of* database lookups. This is a high performance way to provide a
// handful of string replacements. See settings.php for examples.
// Cache the $custom_strings variable to improve performance.
if (!isset($custom_strings[$options['langcode']])) {
$custom_strings[$options['langcode']] = variable_get('locale_custom_strings_' . $options['langcode'], array());
}
// Custom strings work for English too, even if locale module is disabled.
if (isset($custom_strings[$options['langcode']][$options['context']][$string])) {
$string = $custom_strings[$options['langcode']][$options['context']][$string];
}
// Translate with locale module if enabled.
elseif ($options['langcode'] != 'en' && function_exists('locale')) {
$string = locale($string, $options['context'], $options['langcode']);
}
if (empty($args)) {
return $string;
}
else {
return format_string($string, $args);
}
}

/**
* Formats a string for HTML display by replacing variable placeholders.
*
* This function replaces variable placeholders in a string with the requested
* values and escapes the values so they can be safely displayed as HTML. It
* should be used on any unknown text that is intended to be printed to an HTML
* page (especially text that may have come from untrusted users, since in that
* case it prevents cross-site scripting and other security problems).
*
* In most cases, you should use t() rather than calling this function
* directly, since it will translate the text (on non-English-only sites) in
* addition to formatting it.
*
* @param $string
* A string containing placeholders.
* @param $args
* An associative array of replacements to make. Occurrences in $string of
* any key in $args are replaced with the corresponding value, after optional
* sanitization and formatting. The type of sanitization and formatting
* depends on the first character of the key:
* - @variable: Escaped to HTML using check_plain(). Use this as the default
* choice for anything displayed on a page on the site.
* - %variable: Escaped to HTML and formatted using drupal_placeholder(),
* which makes it display as <em>emphasized</em> text.
* - !variable: Inserted as is, with no sanitization or formatting. Only use
* this for text that has already been prepared for HTML display (for
* example, user-supplied text that has already been run through
* check_plain() previously, or is expected to contain some limited HTML
* tags and has already been run through filter_xss() previously).
*
* @see t()
* @ingroup sanitization
*/
function format_string($string, array $args = array()) {
// Transform arguments before inserting them.
foreach ($args as $key => $value) {
switch ($key[0]) {
case '@':
// Escaped only.
$args[$key] = check_plain($value);
break;

case '%':
default:
// Escaped and placeholder.
$args[$key] = drupal_placeholder($value);
break;

case '!':
// Pass-through.
}
}
return strtr($string, $args);
}

/**
* Encodes special characters in a plain-text string for display as HTML.
*
* Also validates strings as UTF-8 to prevent cross site scripting attacks on
* Internet Explorer 6.
*
* @param string $text
* The text to be checked or processed.
*
* @return string
* An HTML safe version of $text. If $text is not valid UTF-8, an empty string
* is returned and, on PHP < 5.4, a warning may be issued depending on server
* configuration (see @link https://bugs.php.net/bug.php?id=47494 @endlink).
*
* @see drupal_validate_utf8()
* @ingroup sanitization
*/
function check_plain($text) {
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

/**
* Checks whether a string is valid UTF-8.
*
* All functions designed to filter input should use drupal_validate_utf8
* to ensure they operate on valid UTF-8 strings to prevent bypass of the
* filter.
*
* When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
* as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
* bytes. When these subsequent bytes are HTML control characters such as
* quotes or angle brackets, parts of the text that were deemed safe by filters
* end up in locations that are potentially unsafe; An onerror attribute that
* is outside of a tag, and thus deemed safe by a filter, can be interpreted
* by the browser as if it were inside the tag.
*
* The function does not return FALSE for strings containing character codes
* above U+10FFFF, even though these are prohibited by RFC 3629.
*
* @param $text
* The text to check.
*
* @return
* TRUE if the text is valid UTF-8, FALSE if not.
*/
function drupal_validate_utf8($text) {
if (strlen($text) == 0) {
return TRUE;
}
// With the PCRE_UTF8 modifier 'u', preg_match() fails silently on strings
// containing invalid UTF-8 byte sequences. It does not reject character
// codes above U+10FFFF (represented by 4 or more octets), though.
return (preg_match('/^./us', $text) == 1);
}

/**
* Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
*
* Because $_SERVER['REQUEST_URI'] is only available on Apache, we generate an
* equivalent using other environment variables.
*/
function request_uri() {
if (isset($_SERVER['REQUEST_URI'])) {
$uri = $_SERVER['REQUEST_URI'];
}
else {
if (isset($_SERVER['argv'])) {
$uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
}
elseif (isset($_SERVER['QUERY_STRING'])) {
$uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
}
else {
$uri = $_SERVER['SCRIPT_NAME'];
}
}
// Prevent multiple slashes to avoid cross site requests via the Form API.
$uri = '/' . ltrim($uri, '/');

return $uri;
}

/**
* Logs an exception.
*
* This is a wrapper function for watchdog() which automatically decodes an
* exception.
*
* @param $type
* The category to which this message belongs.
* @param $exception
* The exception that is going to be logged.
* @param $message
* The message to store in the log. If empty, a text that contains all useful
* information about the passed-in exception is used.
* @param $variables
* Array of variables to replace in the message on display. Defaults to the
* return value of _drupal_decode_exception().
* @param $severity
* The severity of the message, as per RFC 3164.
* @param $link
* A link to associate with the message.
*
* @see watchdog()
* @see _drupal_decode_exception()
*/
function watchdog_exception($type, Exception $exception, $message = NULL, $variables = array(), $severity = WATCHDOG_ERROR, $link = NULL) {

// Use a default value if $message is not set.
if (empty($message)) {
// The exception message is run through check_plain() by _drupal_decode_exception().
$message = '%type: !message in %function (line %line of %file).';
}
// $variables must be an array so that we can add the exception information.
if (!is_array($variables)) {
$variables = array();
}

require_once DRUPAL_ROOT . '/includes/errors.inc';
$variables += _drupal_decode_exception($exception);
watchdog($type, $message, $variables, $severity, $link);
}

/**
* Logs a system message.
*
* @param $type
* The category to which this message belongs. Can be any string, but the
* general practice is to use the name of the module calling watchdog().
* @param $message
* The message to store in the log. Keep $message translatable
* by not concatenating dynamic values into it! Variables in the
* message should be added by using placeholder strings alongside
* the variables argument to declare the value of the placeholders.
* See t() for documentation on how $message and $variables interact.
* @param $variables
* Array of variables to replace in the message on display or
* NULL if message is already translated or not possible to
* translate.
* @param $severity
* The severity of the message; one of the following values as defined in
* @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
* - WATCHDOG_EMERGENCY: Emergency, system is unusable.
* - WATCHDOG_ALERT: Alert, action must be taken immediately.
* - WATCHDOG_CRITICAL: Critical conditions.
* - WATCHDOG_ERROR: Error conditions.
* - WATCHDOG_WARNING: Warning conditions.
* - WATCHDOG_NOTICE: (default) Normal but significant conditions.
* - WATCHDOG_INFO: Informational messages.
* - WATCHDOG_DEBUG: Debug-level messages.
* @param $link
* A link to associate with the message.
*
* @see watchdog_severity_levels()
* @see hook_watchdog()
*/
function watchdog($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL) {
global $user, $base_root;

static $in_error_state = FALSE;

// It is possible that the error handling will itself trigger an error. In that case, we could
// end up in an infinite loop. To avoid that, we implement a simple static semaphore.
if (!$in_error_state && function_exists('module_implements')) {
$in_error_state = TRUE;

// The user object may not exist in all conditions, so 0 is substituted if needed.
$user_uid = isset($user->uid) ? $user->uid : 0;

// Prepare the fields to be logged
$log_entry = array(
'type' => $type,
'message' => $message,
'variables' => $variables,
'severity' => $severity,
'link' => $link,
'user' => $user,
'uid' => $user_uid,
'request_uri' => $base_root . request_uri(),
'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
'ip' => ip_address(),
// Request time isn't accurate for long processes, use time() instead.
'timestamp' => time(),
);

// Call the logging hooks to log/process the message
foreach (module_implements('watchdog') as $module) {
module_invoke($module, 'watchdog', $log_entry);
}

// It is critical that the semaphore is only cleared here, in the parent
// watchdog() call (not outside the loop), to prevent recursive execution.
$in_error_state = FALSE;
}
}

/**
* Sets a message to display to the user.
*
* Messages are stored in a session variable and displayed in page.tpl.php via
* the $messages theme variable.
*
* Example usage:
* @code
* drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
* @endcode
*
* @param string $message
* (optional) The translated message to be displayed to the user. For
* consistency with other messages, it should begin with a capital letter and
* end with a period.
* @param string $type
* (optional) The message's type. Defaults to 'status'. These values are
* supported:
* - 'status'
* - 'warning'
* - 'error'
* @param bool $repeat
* (optional) If this is FALSE and the message is already set, then the
* message won't be repeated. Defaults to TRUE.
*
* @return array|null
* A multidimensional array with keys corresponding to the set message types.
* The indexed array values of each contain the set messages for that type.
* Or, if there are no messages set, the function returns NULL.
*
* @see drupal_get_messages()
* @see theme_status_messages()
*/
function drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE) {

//by ugarte core_log messagess
if ($type == 'error') if (function_exists('core_log')) core_log('Drupal Set Message: '.$message, false, 'E');
////////////////////////////////////////////////////////

//by ugarte trace_add messagess
if ($type == 'error') if (function_exists('trace_add')) trace_add('Error: '.$message);
////////////////////////////////////////////////////////

if ($message || $message === '0' || $message === 0) {
if (!isset($_SESSION['messages'][$type])) {
$_SESSION['messages'][$type] = array();
}

if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
$_SESSION['messages'][$type][] = $message;
}

// Mark this page as being uncacheable.
drupal_page_is_cacheable(FALSE);
}

// Messages not set when DB connection fails.
return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
}

/**
* Returns all messages that have been set with drupal_set_message().
*
* @param string $type
* (optional) Limit the messages returned by type. Defaults to NULL, meaning
* all types. These values are supported:
* - NULL
* - 'status'
* - 'warning'
* - 'error'
* @param bool $clear_queue
* (optional) If this is TRUE, the queue will be cleared of messages of the
* type specified in the $type parameter. Otherwise the queue will be left
* intact. Defaults to TRUE.
*
* @return array
* A multidimensional array with keys corresponding to the set message types.
* The indexed array values of each contain the set messages for that type.
* The messages returned are limited to the type specified in the $type
* parameter. If there are no messages of the specified type, an empty array
* is returned.
*
* @see drupal_set_message()
* @see theme_status_messages()
*/
function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
if ($messages = drupal_set_message()) {
if ($type) {
if ($clear_queue) {
unset($_SESSION['messages'][$type]);
}
if (isset($messages[$type])) {
return array($type => $messages[$type]);
}
}
else {
if ($clear_queue) {
unset($_SESSION['messages']);
}
return $messages;
}
}
return array();
}

/**
* Gets the title of the current page.
*
* The title is displayed on the page and in the title bar.
*
* @return
* The current page's title.
*/
function drupal_get_title() {
$title = drupal_set_title();

// During a bootstrap, menu.inc is not included and thus we cannot provide a title.
if (!isset($title) && function_exists('menu_get_active_title')) {
$title = check_plain(menu_get_active_title());
}

return $title;
}

/**
* Sets the title of the current page.
*
* The title is displayed on the page and in the title bar.
*
* @param $title
* Optional string value to assign to the page title; or if set to NULL
* (default), leaves the current title unchanged.
* @param $output
* Optional flag - normally should be left as CHECK_PLAIN. Only set to
* PASS_THROUGH if you have already removed any possibly dangerous code
* from $title using a function like check_plain() or filter_xss(). With this
* flag the string will be passed through unchanged.
*
* @return
* The updated title of the current page.
*/
function drupal_set_title($title = NULL, $output = CHECK_PLAIN) {
$stored_title = &drupal_static(__FUNCTION__);

if (isset($title)) {
$stored_title = ($output == PASS_THROUGH) ? $title : check_plain($title);
}

return $stored_title;
}

/**
* Checks to see if an IP address has been blocked.
*
* Blocked IP addresses are stored in the database by default. However for
* performance reasons we allow an override in settings.php. This allows us
* to avoid querying the database at this critical stage of the bootstrap if
* an administrative interface for IP address blocking is not required.
*
* @param $ip
* IP address to check.
*
* @return bool
* TRUE if access is denied, FALSE if access is allowed.
*/
function drupal_is_denied($ip) {
// Because this function is called on every page request, we first check
// for an array of IP addresses in settings.php before querying the
// database.
$blocked_ips = variable_get('blocked_ips');
$denied = FALSE;
if (isset($blocked_ips) && is_array($blocked_ips)) {
$denied = in_array($ip, $blocked_ips);
}
// Only check if database.inc is loaded already. If
// $conf['page_cache_without_database'] = TRUE; is set in settings.php,
// then the database won't be loaded here so the IPs in the database
// won't be denied. However the user asked explicitly not to use the
// database and also in this case it's quite likely that the user relies
// on higher performance solutions like a firewall.
elseif (class_exists('Database', FALSE)) {
$denied = (bool)db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();
}
return $denied;
}

/**
* Handles denied users.
*
* @param $ip
* IP address to check. Prints a message and exits if access is denied.
*/
function drupal_block_denied($ip) {
// Deny access to blocked IP addresses - t() is not yet available.
if (drupal_is_denied($ip)) {
header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
print 'Sorry, ' . check_plain(ip_address()) . ' has been banned.';
exit();
}
}

/**
* Returns a URL-safe, base64 encoded string of highly randomized bytes (over the full 8-bit range).
*
* @param $byte_count
* The number of random bytes to fetch and base64 encode.
*
* @return string
* The base64 encoded result will have a length of up to 4 * $byte_count.
*/
function drupal_random_key($byte_count = 32) {
return drupal_base64_encode(drupal_random_bytes($byte_count));
}

/**
* Returns a URL-safe, base64 encoded version of the supplied string.
*
* @param $string
* The string to convert to base64.
*
* @return string
*/
function drupal_base64_encode($string) {
$data = base64_encode($string);
// Modify the output so it's safe to use in URLs.
return strtr($data, array('+' => '-', '/' => '_', '=' => ''));
}

/**
* Returns a string of highly randomized bytes (over the full 8-bit range).
*
* This function is better than simply calling mt_rand() or any other built-in
* PHP function because it can return a long string of bytes (compared to < 4
* bytes normally from mt_rand()) and uses the best available pseudo-random
* source.
*
* @param $count
* The number of characters (bytes) to return in the string.
*/
function drupal_random_bytes($count) {
// $random_state does not use drupal_static as it stores random bytes.
static $random_state, $bytes, $has_openssl;

$missing_bytes = $count - strlen($bytes);

if ($missing_bytes > 0) {
// PHP versions prior 5.3.4 experienced openssl_random_pseudo_bytes()
// locking on Windows and rendered it unusable.
if (!isset($has_openssl)) {
$has_openssl = version_compare(PHP_VERSION, '5.3.4', '>=') && function_exists('openssl_random_pseudo_bytes');
}

// openssl_random_pseudo_bytes() will find entropy in a system-dependent
// way.
if ($has_openssl) {
$bytes .= openssl_random_pseudo_bytes($missing_bytes);
}

// Else, read directly from /dev/urandom, which is available on many *nix
// systems and is considered cryptographically secure.
elseif ($fh = @fopen('/dev/urandom', 'rb')) {
// PHP only performs buffered reads, so in reality it will always read
// at least 4096 bytes. Thus, it costs nothing extra to read and store
// that much so as to speed any additional invocations.
$bytes .= fread($fh, max(4096, $missing_bytes));
fclose($fh);
}

// If we couldn't get enough entropy, this simple hash-based PRNG will
// generate a good set of pseudo-random bytes on any system.
// Note that it may be important that our $random_state is passed
// through hash() prior to being rolled into $output, that the two hash()
// invocations are different, and that the extra input into the first one -
// the microtime() - is prepended rather than appended. This is to avoid
// directly leaking $random_state via the $output stream, which could
// allow for trivial prediction of further "random" numbers.
if (strlen($bytes) < $count) {
// Initialize on the first call. The contents of $_SERVER includes a mix of
// user-specific and system information that varies a little with each page.
if (!isset($random_state)) {
$random_state = print_r($_SERVER, TRUE);
if (function_exists('getmypid')) {
// Further initialize with the somewhat random PHP process ID.
$random_state .= getmypid();
}
$bytes = '';
}

do {
$random_state = hash('sha256', microtime() . mt_rand() . $random_state);
$bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
}
while (strlen($bytes) < $count);
}
}
$output = substr($bytes, 0, $count);
$bytes = substr($bytes, $count);
return $output;
}

/**
* Calculates a base-64 encoded, URL-safe sha-256 hmac.
*
* @param string $data
* String to be validated with the hmac.
* @param string $key
* A secret string key.
*
* @return string
* A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and
* any = padding characters removed.
*/
function drupal_hmac_base64($data, $key) {
// Casting $data and $key to strings here is necessary to avoid empty string
// results of the hash function if they are not scalar values. As this
// function is used in security-critical contexts like token validation it is
// important that it never returns an empty string.
$hmac = base64_encode(hash_hmac('sha256', (string) $data, (string) $key, TRUE));
// Modify the hmac so it's safe to use in URLs.
return strtr($hmac, array('+' => '-', '/' => '_', '=' => ''));
}

/**
* Calculates a base-64 encoded, URL-safe sha-256 hash.
*
* @param $data
* String to be hashed.
*
* @return
* A base-64 encoded sha-256 hash, with + replaced with -, / with _ and
* any = padding characters removed.
*/
function drupal_hash_base64($data) {
$hash = base64_encode(hash('sha256', $data, TRUE));
// Modify the hash so it's safe to use in URLs.
return strtr($hash, array('+' => '-', '/' => '_', '=' => ''));
}

/**
* Merges multiple arrays, recursively, and returns the merged array.
*
* This function is similar to PHP's array_merge_recursive() function, but it
* handles non-array values differently. When merging values that are not both
* arrays, the latter value replaces the former rather than merging with it.
*
* Example:
* @code
* $link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => t('X'), 'class' => array('a', 'b')));
* $link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('c', 'd')));
*
* // This results in array('fragment' => array('x', 'y'), 'attributes' => array('title' => array(t('X'), t('Y')), 'class' => array('a', 'b', 'c', 'd'))).
* $incorrect = array_merge_recursive($link_options_1, $link_options_2);
*
* // This results in array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('a', 'b', 'c', 'd'))).
* $correct = drupal_array_merge_deep($link_options_1, $link_options_2);
* @endcode
*
* @param ...
* Arrays to merge.
*
* @return
* The merged array.
*
* @see drupal_array_merge_deep_array()
*/
function drupal_array_merge_deep() {
$args = func_get_args();
return drupal_array_merge_deep_array($args);
}

/**
* Merges multiple arrays, recursively, and returns the merged array.
*
* This function is equivalent to drupal_array_merge_deep(), except the
* input arrays are passed as a single array parameter rather than a variable
* parameter list.
*
* The following are equivalent:
* - drupal_array_merge_deep($a, $b);
* - drupal_array_merge_deep_array(array($a, $b));
*
* The following are also equivalent:
* - call_user_func_array('drupal_array_merge_deep', $arrays_to_merge);
* - drupal_array_merge_deep_array($arrays_to_merge);
*
* @see drupal_array_merge_deep()
*/
function drupal_array_merge_deep_array($arrays) {
$result = array();

foreach ($arrays as $array) {
foreach ($array as $key => $value) {
// Renumber integer keys as array_merge_recursive() does. Note that PHP
// automatically converts array keys that are integer strings (e.g., '1')
// to integers.
if (is_integer($key)) {
$result[] = $value;
}
// Recurse when both values are arrays.
elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
$result[$key] = drupal_array_merge_deep_array(array($result[$key], $value));
}
// Otherwise, use the latter value, overriding any previous value.
else {
$result[$key] = $value;
}
}
}

return $result;
}

/**
* Generates a default anonymous $user object.
*
* @return Object - the user object.
*/
function drupal_anonymous_user() {
$user = variable_get('drupal_anonymous_user_object', new stdClass);
$user->uid = 0;
$user->hostname = ip_address();
$user->roles = array();
$user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
$user->cache = 0;
return $user;
}

/**
* Ensures Drupal is bootstrapped to the specified phase.
*
* In order to bootstrap Drupal from another PHP script, you can use this code:
* @code
* define('DRUPAL_ROOT', '/path/to/drupal');
* require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
* drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
* @endcode
*
* @param int $phase
* A constant telling which phase to bootstrap to. When you bootstrap to a
* particular phase, all earlier phases are run automatically. Possible
* values:
* - DRUPAL_BOOTSTRAP_CONFIGURATION: Initializes configuration.
* - DRUPAL_BOOTSTRAP_PAGE_CACHE: Tries to serve a cached page.
* - DRUPAL_BOOTSTRAP_DATABASE: Initializes the database layer.
* - DRUPAL_BOOTSTRAP_VARIABLES: Initializes the variable system.
* - DRUPAL_BOOTSTRAP_SESSION: Initializes session handling.
* - DRUPAL_BOOTSTRAP_PAGE_HEADER: Sets up the page header.
* - DRUPAL_BOOTSTRAP_LANGUAGE: Finds out the language of the page.
* - DRUPAL_BOOTSTRAP_FULL: Fully loads Drupal. Validates and fixes input
* data.
* @param boolean $new_phase
* A boolean, set to FALSE if calling drupal_bootstrap from inside a
* function called from drupal_bootstrap (recursion).
*
* @return int
* The most recently completed phase.
*/
function drupal_bootstrap($phase = NULL, $new_phase = TRUE) {
// Not drupal_static(), because does not depend on any run-time information.
static $phases = array(
DRUPAL_BOOTSTRAP_CONFIGURATION,
DRUPAL_BOOTSTRAP_PAGE_CACHE,
DRUPAL_BOOTSTRAP_DATABASE,
DRUPAL_BOOTSTRAP_VARIABLES,
DRUPAL_BOOTSTRAP_SESSION,
DRUPAL_BOOTSTRAP_PAGE_HEADER,
DRUPAL_BOOTSTRAP_LANGUAGE,
DRUPAL_BOOTSTRAP_FULL,
);
// Not drupal_static(), because the only legitimate API to control this is to
// call drupal_bootstrap() with a new phase parameter.
static $final_phase;
// Not drupal_static(), because it's impossible to roll back to an earlier
// bootstrap state.
static $stored_phase = -1;

if (isset($phase)) {
// When not recursing, store the phase name so it's not forgotten while
// recursing but take care of not going backwards.
if ($new_phase && $phase >= $stored_phase) {
$final_phase = $phase;
}

// Call a phase if it has not been called before and is below the requested
// phase.
while ($phases && $phase > $stored_phase && $final_phase > $stored_phase) {
$current_phase = array_shift($phases);

// This function is re-entrant. Only update the completed phase when the
// current call actually resulted in a progress in the bootstrap process.
if ($current_phase > $stored_phase) {
$stored_phase = $current_phase;
}

switch ($current_phase) {
case DRUPAL_BOOTSTRAP_CONFIGURATION:
_drupal_bootstrap_configuration();
break;

case DRUPAL_BOOTSTRAP_PAGE_CACHE:
_drupal_bootstrap_page_cache();
break;

case DRUPAL_BOOTSTRAP_DATABASE:
_drupal_bootstrap_database();
break;

case DRUPAL_BOOTSTRAP_VARIABLES:
_drupal_bootstrap_variables();
break;

case DRUPAL_BOOTSTRAP_SESSION:
require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
drupal_session_initialize();
break;

case DRUPAL_BOOTSTRAP_PAGE_HEADER:
_drupal_bootstrap_page_header();
break;

case DRUPAL_BOOTSTRAP_LANGUAGE:
drupal_language_initialize();
break;

case DRUPAL_BOOTSTRAP_FULL:
require_once DRUPAL_ROOT . '/includes/common.inc';
_drupal_bootstrap_full();
break;
}
}
}
return $stored_phase;
}

/**
* Returns the time zone of the current user.
*/
function drupal_get_user_timezone() {
global $user;
if (variable_get('configurable_timezones', 1) && $user->uid && $user->timezone) {
return $user->timezone;
}
else {
// Ignore PHP strict notice if time zone has not yet been set in the php.ini
// configuration.
return variable_get('date_default_timezone', @date_default_timezone_get());
}
}

/**
* Gets a salt useful for hardening against SQL injection.
*
* @return
* A salt based on information in settings.php, not in the database.
*/
function drupal_get_hash_salt() {
global $drupal_hash_salt, $databases;
// If the $drupal_hash_salt variable is empty, a hash of the serialized
// database credentials is used as a fallback salt.
return empty($drupal_hash_salt) ? hash('sha256', serialize($databases)) : $drupal_hash_salt;
}

/**
* Provides custom PHP error handling.
*
* @param $error_level
* The level of the error raised.
* @param $message
* The error message.
* @param $filename
* The filename that the error was raised in.
* @param $line
* The line number the error was raised at.
* @param $context
* An array that points to the active symbol table at the point the error
* occurred.
*/
function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
require_once DRUPAL_ROOT . '/includes/errors.inc';
_drupal_error_handler_real($error_level, $message, $filename, $line, $context);
}

/**
* Provides custom PHP exception handling.
*
* Uncaught exceptions are those not enclosed in a try/catch block. They are
* always fatal: the execution of the script will stop as soon as the exception
* handler exits.
*
* @param $exception
* The exception object that was thrown.
*/
function _drupal_exception_handler($exception) {
require_once DRUPAL_ROOT . '/includes/errors.inc';

try {
// Log the message to the watchdog and return an error page to the user.
_drupal_log_error(_drupal_decode_exception($exception), TRUE);
}
catch (Exception $exception2) {
// Another uncaught exception was thrown while handling the first one.
// If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
if (error_displayable()) {
print '<h1>Additional uncaught exception thrown while handling exception.</h1>';
print '<h2>Original</h2><p>' . _drupal_render_exception_safe($exception) . '</p>';
print '<h2>Additional</h2><p>' . _drupal_render_exception_safe($exception2) . '</p><hr />';
}
}
}

/**
* Sets up the script environment and loads settings.php.
*/
function _drupal_bootstrap_configuration() {
// Set the Drupal custom error handler.
set_error_handler('_drupal_error_handler');
set_exception_handler('_drupal_exception_handler');

drupal_environment_initialize();
// Start a page timer:
timer_start('page');
// Initialize the configuration, including variables from settings.php.
drupal_settings_initialize();require_once DRUPAL_ROOT . '/includes/request-sanitizer.inc';DrupalRequestSanitizer::sanitize();
}

/**
* Attempts to serve a page from the cache.
*/
function _drupal_bootstrap_page_cache() {
global $user;

// Allow specifying special cache handlers in settings.php, like
// using memcached or files for storing cache information.
require_once DRUPAL_ROOT . '/includes/cache.inc';
foreach (variable_get('cache_backends', array()) as $include) {
require_once DRUPAL_ROOT . '/' . $include;
}
// Check for a cache mode force from settings.php.
if (variable_get('page_cache_without_database')) {
$cache_enabled = TRUE;
}
else {
drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE);
$cache_enabled = variable_get('cache');
}
drupal_block_denied(ip_address());
// If there is no session cookie and cache is enabled (or forced), try
// to serve a cached page.
if (!isset($_COOKIE[session_name()]) && $cache_enabled) {
// Make sure there is a user object because its timestamp will be
// checked, hook_boot might check for anonymous user etc.
$user = drupal_anonymous_user();
// Get the page from the cache.
$cache = drupal_page_get_cache();
// If there is a cached page, display it.
if (is_object($cache)) {
header('X-Drupal-Cache: HIT');
// Restore the metadata cached with the page.
$_GET['q'] = $cache->data['path'];
drupal_set_title($cache->data['title'], PASS_THROUGH);
date_default_timezone_set(drupal_get_user_timezone());
// If the skipping of the bootstrap hooks is not enforced, call
// hook_boot.
if (variable_get('page_cache_invoke_hooks', TRUE)) {
bootstrap_invoke_all('boot');
}
drupal_serve_page_from_cache($cache);
// If the skipping of the bootstrap hooks is not enforced, call
// hook_exit.
if (variable_get('page_cache_invoke_hooks', TRUE)) {
bootstrap_invoke_all('exit');
}
// We are done.
exit;
}
else {
header('X-Drupal-Cache: MISS');
}
}
}

/**
* Initializes the database system and registers autoload functions.
*/
function _drupal_bootstrap_database() {
// Redirect the user to the installation script if Drupal has not been
// installed yet (i.e., if no $databases array has been defined in the
// settings.php file) and we are not already installing.
if (empty($GLOBALS['databases']) && !drupal_installation_attempted()) {
include_once DRUPAL_ROOT . '/includes/install.inc';
install_goto('install.php');
}

// The user agent header is used to pass a database prefix in the request when
// running tests. However, for security reasons, it is imperative that we
// validate we ourselves made the request.
if ($test_prefix = drupal_valid_test_ua()) {
// Set the test run id for use in other parts of Drupal.
$test_info = &$GLOBALS['drupal_test_info'];
$test_info['test_run_id'] = $test_prefix;
$test_info['in_child_site'] = TRUE;

foreach ($GLOBALS['databases']['default'] as &$value) {
// Extract the current default database prefix.
if (!isset($value['prefix'])) {
$current_prefix = '';
}
elseif (is_array($value['prefix'])) {
$current_prefix = $value['prefix']['default'];
}
else {
$current_prefix = $value['prefix'];
}

// Remove the current database prefix and replace it by our own.
$value['prefix'] = array(
'default' => $current_prefix . $test_prefix,
);
}
}

// Initialize the database system. Note that the connection
// won't be initialized until it is actually requested.
require_once DRUPAL_ROOT . '/includes/database/database.inc';

// Register autoload functions so that we can access classes and interfaces.
// The database autoload routine comes first so that we can load the database
// system without hitting the database. That is especially important during
// the install or upgrade process.
spl_autoload_register('drupal_autoload_class');
spl_autoload_register('drupal_autoload_interface');
if (version_compare(PHP_VERSION, '5.4') >= 0) {
spl_autoload_register('drupal_autoload_trait');
}
}

/**
* Loads system variables and all enabled bootstrap modules.
*/
function _drupal_bootstrap_variables() {
global $conf;

// Initialize the lock system.
require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
lock_initialize();

// Load variables from the database, but do not overwrite variables set in settings.php.
$conf = variable_initialize(isset($conf) ? $conf : array());
// Load bootstrap modules.
require_once DRUPAL_ROOT . '/includes/module.inc';
module_load_all(TRUE);

// Sanitize the destination parameter (which is often used for redirects) to
// prevent open redirect attacks leading to other domains. Sanitize both
// $_GET['destination'] and $_REQUEST['destination'] to protect code that
// relies on either, but do not sanitize $_POST to avoid interfering with
// unrelated form submissions. The sanitization happens here because
// url_is_external() requires the variable system to be available.
if (isset($_GET['destination']) || isset($_REQUEST['destination'])) {
require_once DRUPAL_ROOT . '/includes/common.inc';
// If the destination is an external URL, remove it.
if (isset($_GET['destination']) && url_is_external($_GET['destination'])) {
unset($_GET['destination']);
unset($_REQUEST['destination']);
}

//by ugarte new patch

// Use the DrupalRequestSanitizer to ensure that the destination's query
// parameters are not dangerous.
if (isset($_GET['destination'])) {
DrupalRequestSanitizer::cleanDestination();
}


// If there's still something in $_REQUEST['destination'] that didn't come
// from $_GET, check it too.
if (isset($_REQUEST['destination']) && (!isset($_GET['destination']) || $_REQUEST['destination'] != $_GET['destination']) && url_is_external($_REQUEST['destination'])) {
unset($_REQUEST['destination']);
}
}
}

/**
* Invokes hook_boot(), initializes locking system, and sends HTTP headers.
*/
function _drupal_bootstrap_page_header() {
bootstrap_invoke_all('boot');

if (!drupal_is_cli()) {
ob_start();
drupal_page_header();
}
}

/**
* Returns the current bootstrap phase for this Drupal process.
*
* The current phase is the one most recently completed by drupal_bootstrap().
*
* @see drupal_bootstrap()
*/
function drupal_get_bootstrap_phase() {
return drupal_bootstrap(NULL, FALSE);
}

/**
* Returns the test prefix if this is an internal request from SimpleTest.
*
* @return
* Either the simpletest prefix (the string "simpletest" followed by any
* number of digits) or FALSE if the user agent does not contain a valid
* HMAC and timestamp.
*/
function drupal_valid_test_ua() {
// No reason to reset this.
static $test_prefix;

if (isset($test_prefix)) {
return $test_prefix;
}

if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/^(simpletest\d+);(.+);(.+);(.+)$/", $_SERVER['HTTP_USER_AGENT'], $matches)) {
list(, $prefix, $time, $salt, $hmac) = $matches;
$check_string = $prefix . ';' . $time . ';' . $salt;
// We use the salt from settings.php to make the HMAC key, since
// the database is not yet initialized and we can't access any Drupal variables.
// The file properties add more entropy not easily accessible to others.
$key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
$time_diff = REQUEST_TIME - $time;
// Since we are making a local request a 5 second time window is allowed,
// and the HMAC must match.
if ($time_diff >= 0 && $time_diff <= 5 && $hmac == drupal_hmac_base64($check_string, $key)) {
$test_prefix = $prefix;
return $test_prefix;
}
}

$test_prefix = FALSE;
return $test_prefix;
}

/**
* Generates a user agent string with a HMAC and timestamp for simpletest.
*/
function drupal_generate_test_ua($prefix) {
static $key;

if (!isset($key)) {
// We use the salt from settings.php to make the HMAC key, since
// the database is not yet initialized and we can't access any Drupal variables.
// The file properties add more entropy not easily accessible to others.
$key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
}
// Generate a moderately secure HMAC based on the database credentials.
$salt = uniqid('', TRUE);
$check_string = $prefix . ';' . time() . ';' . $salt;
return $check_string . ';' . drupal_hmac_base64($check_string, $key);
}

/**
* Enables use of the theme system without requiring database access.
*
* Loads and initializes the theme system for site installs, updates and when
* the site is in maintenance mode. This also applies when the database fails.
*
* @see _drupal_maintenance_theme()
*/
function drupal_maintenance_theme() {
require_once DRUPAL_ROOT . '/includes/theme.maintenance.inc';
_drupal_maintenance_theme();
}

/**
* Returns a simple 404 Not Found page.
*
* If fast 404 pages are enabled, and this is a matching page then print a
* simple 404 page and exit.
*
* This function is called from drupal_deliver_html_page() at the time when a
* a normal 404 page is generated, but it can also optionally be called directly
* from settings.php to prevent a Drupal bootstrap on these pages. See
* documentation in settings.php for the benefits and drawbacks of using this.
*
* Paths to dynamically-generated content, such as image styles, should also be
* accounted for in this function.
*/
function drupal_fast_404() {
$exclude_paths = variable_get('404_fast_paths_exclude', FALSE);
if ($exclude_paths && !preg_match($exclude_paths, $_GET['q'])) {
$fast_paths = variable_get('404_fast_paths', FALSE);
if ($fast_paths && preg_match($fast_paths, $_GET['q'])) {
drupal_add_http_header('Status', '404 Not Found');
$fast_404_html = variable_get('404_fast_html', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL "@path" was not found on this server.</p></body></html>');
// Replace @path in the variable with the page path.
print strtr($fast_404_html, array('@path' => check_plain(request_uri())));
exit;
}
}
}

/**
* Returns TRUE if a Drupal installation is currently being attempted.
*/
function drupal_installation_attempted() {
return defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'install';
}

/**
* Returns the name of the proper localization function.
*
* get_t() exists to support localization for code that might run during
* the installation phase, when some elements of the system might not have
* loaded.
*
* This would include implementations of hook_install(), which could run
* during the Drupal installation phase, and might also be run during
* non-installation time, such as while installing the module from the
* module administration page.
*
* Example usage:
* @code
* $t = get_t();
* $translated = $t('translate this');
* @endcode
*
* Use t() if your code will never run during the Drupal installation phase.
* Use st() if your code will only run during installation and never any other
* time. Use get_t() if your code could run in either circumstance.
*
* @see t()
* @see st()
* @ingroup sanitization
*/
function get_t() {
static $t;
// This is not converted to drupal_static because there is no point in
// resetting this as it can not change in the course of a request.
if (!isset($t)) {
$t = drupal_installation_attempted() ? 'st' : 't';
}
return $t;
}

/**
* Initializes all the defined language types.
*/
function drupal_language_initialize() {
$types = language_types();

// Ensure the language is correctly returned, even without multilanguage
// support. Also make sure we have a $language fallback, in case a language
// negotiation callback needs to do a full bootstrap.
// Useful for eg. XML/HTML 'lang' attributes.
$default = language_default();
foreach ($types as $type) {
$GLOBALS[$type] = $default;
}
if (drupal_multilingual()) {
include_once DRUPAL_ROOT . '/includes/language.inc';
foreach ($types as $type) {
$GLOBALS[$type] = language_initialize($type);
}
// Allow modules to react on language system initialization in multilingual
// environments.
bootstrap_invoke_all('language_init');
}
}

/**
* Returns a list of the built-in language types.
*
* @return
* An array of key-values pairs where the key is the language type and the
* value is its configurability.
*/
function drupal_language_types() {
return array(
LANGUAGE_TYPE_INTERFACE => TRUE,
LANGUAGE_TYPE_CONTENT => FALSE,
LANGUAGE_TYPE_URL => FALSE,
);
}

/**
* Returns TRUE if there is more than one language enabled.
*
* @return
* TRUE if more than one language is enabled.
*/
function drupal_multilingual() {
// The "language_count" variable stores the number of enabled languages to
// avoid unnecessarily querying the database when building the list of
// enabled languages on monolingual sites.
return variable_get('language_count', 1) > 1;
}

/**
* Returns an array of the available language types.
*
* @return
* An array of all language types where the keys of each are the language type
* name and its value is its configurability (TRUE/FALSE).
*/
function language_types() {
return array_keys(variable_get('language_types', drupal_language_types()));
}

/**
* Returns a list of installed languages, indexed by the specified key.
*
* @param $field
* (optional) The field to index the list with.
*
* @return
* An associative array, keyed on the values of $field.
* - If $field is 'weight' or 'enabled', the array is nested, with the outer
* array's values each being associative arrays with language codes as
* keys and language objects as values.
* - For all other values of $field, the array is only one level deep, and
* the array's values are language objects.
*/
function language_list($field = 'language') {
$languages = &drupal_static(__FUNCTION__);
// Init language list
if (!isset($languages)) {
if (drupal_multilingual() || module_exists('locale')) {
$languages['language'] = db_query('SELECT * FROM {languages} ORDER BY weight ASC, name ASC')->fetchAllAssoc('language');
// Users cannot uninstall the native English language. However, we allow
// it to be hidden from the installed languages. Therefore, at least one
// other language must be enabled then.
if (!$languages['language']['en']->enabled && !variable_get('language_native_enabled', TRUE)) {
unset($languages['language']['en']);
}
}
else {
// No locale module, so use the default language only.
$default = language_default();
$languages['language'][$default->language] = $default;
}
}

// Return the array indexed by the right field
if (!isset($languages[$field])) {
$languages[$field] = array();
foreach ($languages['language'] as $lang) {
// Some values should be collected into an array
if (in_array($field, array('enabled', 'weight'))) {
$languages[$field][$lang->$field][$lang->language] = $lang;
}
else {
$languages[$field][$lang->$field] = $lang;
}
}
}
return $languages[$field];
}

/**
* Returns the default language, as an object, or one of its properties.
*
* @param $property
* (optional) The property of the language object to return.
*
* @return
* Either the language object for the default language used on the site,
* or the property of that object named in the $property parameter.
*/
function language_default($property = NULL) {
$language = variable_get('language_default', (object) array('language' => 'en', 'name' => 'English', 'native' => 'English', 'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => ''));
return $property ? $language->$property : $language;
}

/**
* Returns the requested URL path of the page being viewed.
*
* Examples:
* - http://example.com/node/306 returns "node/306".
* - http://example.com/drupalfolder/node/306 returns "node/306" while
* base_path() returns "/drupalfolder/".
* - http://example.com/path/alias (which is a path alias for node/306) returns
* "path/alias" as opposed to the internal path.
* - http://example.com/index.php returns an empty string (meaning: front page).
* - http://example.com/index.php?page=1 returns an empty string.
*
* @return
* The requested Drupal URL path.
*
* @see current_path()
*/
function request_path() {
static $path;

if (isset($path)) {
return $path;
}

if (isset($_GET['q']) && is_string($_GET['q'])) {
// This is a request with a ?q=foo/bar query string. $_GET['q'] is
// overwritten in drupal_path_initialize(), but request_path() is called
// very early in the bootstrap process, so the original value is saved in
// $path and returned in later calls.
$path = $_GET['q'];
}
elseif (isset($_SERVER['REQUEST_URI'])) {
// This request is either a clean URL, or 'index.php', or nonsense.
// Extract the path from REQUEST_URI.
$request_path = strtok($_SERVER['REQUEST_URI'], '?');
$base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
// Unescape and strip $base_path prefix, leaving q without a leading slash.
$path = substr(urldecode($request_path), $base_path_len + 1);
// If the path equals the script filename, either because 'index.php' was
// explicitly provided in the URL, or because the server added it to
// $_SERVER['REQUEST_URI'] even when it wasn't provided in the URL (some
// versions of Microsoft IIS do this), the front page should be served.
if ($path == basename($_SERVER['PHP_SELF'])) {
$path = '';
}
}
else {
// This is the front page.
$path = '';
}

// Under certain conditions Apache's RewriteRule directive prepends the value
// assigned to $_GET['q'] with a slash. Moreover we can always have a trailing
// slash in place, hence we need to normalize $_GET['q'].
$path = trim($path, '/');

return $path;
}

/**
* Returns a component of the current Drupal path.
*
* When viewing a page at the path "admin/structure/types", for example, arg(0)
* returns "admin", arg(1) returns "structure", and arg(2) returns "types".
*
* Avoid use of this function where possible, as resulting code is hard to
* read. In menu callback functions, attempt to use named arguments. See the
* explanation in menu.inc for how to construct callbacks that take arguments.
* When attempting to use this function to load an element from the current
* path, e.g. loading the node on a node page, use menu_get_object() instead.
*
* @param $index
* The index of the component, where each component is separated by a '/'
* (forward-slash), and where the first component has an index of 0 (zero).
* @param $path
* A path to break into components. Defaults to the path of the current page.
*
* @return
* The component specified by $index, or NULL if the specified component was
* not found. If called without arguments, it returns an array containing all
* the components of the current path.
*/
function arg($index = NULL, $path = NULL) {
// Even though $arguments doesn't need to be resettable for any functional
// reasons (the result of explode() does not depend on any run-time
// information), it should be resettable anyway in case a module needs to
// free up the memory used by it.
// Use the advanced drupal_static() pattern, since this is called very often.
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
$drupal_static_fast['arguments'] = &drupal_static(__FUNCTION__);
}
$arguments = &$drupal_static_fast['arguments'];

if (!isset($path)) {
$path = $_GET['q'];
}
if (!isset($arguments[$path])) {
$arguments[$path] = explode('/', $path);
}
if (!isset($index)) {
return $arguments[$path];
}
if (isset($arguments[$path][$index])) {
return $arguments[$path][$index];
}
}

/**
* Returns the IP address of the client machine.
*
* If Drupal is behind a reverse proxy, we use the X-Forwarded-For header
* instead of $_SERVER['REMOTE_ADDR'], which would be the IP address of
* the proxy server, and not the client's. The actual header name can be
* configured by the reverse_proxy_header variable.
*
* @return
* IP address of client machine, adjusted for reverse proxy and/or cluster
* environments.
*/
function ip_address() {
$ip_address = &drupal_static(__FUNCTION__);

if (!isset($ip_address)) {
$ip_address = $_SERVER['REMOTE_ADDR'];

if (variable_get('reverse_proxy', 0)) {
$reverse_proxy_header = variable_get('reverse_proxy_header', 'HTTP_X_FORWARDED_FOR');
if (!empty($_SERVER[$reverse_proxy_header])) {
// If an array of known reverse proxy IPs is provided, then trust
// the XFF header if request really comes from one of them.
$reverse_proxy_addresses = variable_get('reverse_proxy_addresses', array());

// Turn XFF header into an array.
$forwarded = explode(',', $_SERVER[$reverse_proxy_header]);

// Trim the forwarded IPs; they may have been delimited by commas and spaces.
$forwarded = array_map('trim', $forwarded);

// Tack direct client IP onto end of forwarded array.
$forwarded[] = $ip_address;

// Eliminate all trusted IPs.
$untrusted = array_diff($forwarded, $reverse_proxy_addresses);

if (!empty($untrusted)) {
// The right-most IP is the most specific we can trust.
$ip_address = array_pop($untrusted);
}
else {
// All IP addresses in the forwarded array are configured proxy IPs
// (and thus trusted). We take the leftmost IP.
$ip_address = array_shift($forwarded);
}
}
}
}

return $ip_address;
}

/**
* @addtogroup schemaapi
* @{
*/

/**
* Gets the schema definition of a table, or the whole database schema.
*
* The returned schema will include any modifications made by any
* module that implements hook_schema_alter(). To get the schema without
* modifications, use drupal_get_schema_unprocessed().
*
*
* @param $table
* The name of the table. If not given, the schema of all tables is returned.
* @param $rebuild
* If true, the schema will be rebuilt instead of retrieved from the cache.
*/
function drupal_get_schema($table = NULL, $rebuild = FALSE) {
static $schema;

if ($rebuild || !isset($table)) {
$schema = drupal_get_complete_schema($rebuild);
}
elseif (!isset($schema)) {
$schema = new SchemaCache();
}

if (!isset($table)) {
return $schema;
}
if (isset($schema[$table])) {
return $schema[$table];
}
else {
return FALSE;
}
}

/**
* Extends DrupalCacheArray to allow for dynamic building of the schema cache.
*/
class SchemaCache extends DrupalCacheArray {

/**
* Constructs a SchemaCache object.
*/
public function __construct() {
// Cache by request method.
parent::__construct('schema:runtime:' . ($_SERVER['REQUEST_METHOD'] == 'GET'), 'cache');
}

/**
* Overrides DrupalCacheArray::resolveCacheMiss().
*/
protected function resolveCacheMiss($offset) {
$complete_schema = drupal_get_complete_schema();
$value = isset($complete_schema[$offset]) ? $complete_schema[$offset] : NULL;
$this->storage[$offset] = $value;
$this->persist($offset);
return $value;
}
}

/**
* Gets the whole database schema.
*
* The returned schema will include any modifications made by any
* module that implements hook_schema_alter().
*
* @param $rebuild
* If true, the schema will be rebuilt instead of retrieved from the cache.
*/
function drupal_get_complete_schema($rebuild = FALSE) {
static $schema = array();

if (empty($schema) || $rebuild) {
// Try to load the schema from cache.
if (!$rebuild && $cached = cache_get('schema')) {
$schema = $cached->data;
}
// Otherwise, rebuild the schema cache.
else {
$schema = array();
// Load the .install files to get hook_schema.
// On some databases this function may be called before bootstrap has
// been completed, so we force the functions we need to load just in case.
if (function_exists('module_load_all_includes')) {
// This function can be called very early in the bootstrap process, so
// we force the module_list() cache to be refreshed to ensure that it
// contains the complete list of modules before we go on to call
// module_load_all_includes().
module_list(TRUE);
module_load_all_includes('install');
}

require_once DRUPAL_ROOT . '/includes/common.inc';
// Invoke hook_schema for all modules.
foreach (module_implements('schema') as $module) {
// Cast the result of hook_schema() to an array, as a NULL return value
// would cause array_merge() to set the $schema variable to NULL as well.
// That would break modules which use $schema further down the line.
$current = (array) module_invoke($module, 'schema');
// Set 'module' and 'name' keys for each table, and remove descriptions,
// as they needlessly slow down cache_get() for every single request.
_drupal_schema_initialize($current, $module);
$schema = array_merge($schema, $current);
}

drupal_alter('schema', $schema);
// If the schema is empty, avoid saving it: some database engines require
// the schema to perform queries, and this could lead to infinite loops.
if (!empty($schema) && (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL)) {
cache_set('schema', $schema);
}
if ($rebuild) {
cache_clear_all('schema:', 'cache', TRUE);
}
}
}

return $schema;
}

/**
* @} End of "addtogroup schemaapi".
*/


/**
* @addtogroup registry
* @{
*/

/**
* Confirms that an interface is available.
*
* This function is rarely called directly. Instead, it is registered as an
* spl_autoload() handler, and PHP calls it for us when necessary.
*
* @param $interface
* The name of the interface to check or load.
*
* @return
* TRUE if the interface is currently available, FALSE otherwise.
*/
function drupal_autoload_interface($interface) {
return _registry_check_code('interface', $interface);
}

/**
* Confirms that a class is available.
*
* This function is rarely called directly. Instead, it is registered as an
* spl_autoload() handler, and PHP calls it for us when necessary.
*
* @param $class
* The name of the class to check or load.
*
* @return
* TRUE if the class is currently available, FALSE otherwise.
*/
function drupal_autoload_class($class) {
return _registry_check_code('class', $class);
}

/**
* Confirms that a trait is available.
*
* This function is rarely called directly. Instead, it is registered as an
* spl_autoload() handler, and PHP calls it for us when necessary.
*
* @param string $trait
* The name of the trait to check or load.
*
* @return bool
* TRUE if the trait is currently available, FALSE otherwise.
*/
function drupal_autoload_trait($trait) {
return _registry_check_code('trait', $trait);
}

/**
* Checks for a resource in the registry.
*
* @param $type
* The type of resource we are looking up, or one of the constants
* REGISTRY_RESET_LOOKUP_CACHE or REGISTRY_WRITE_LOOKUP_CACHE, which
* signal that we should reset or write the cache, respectively.
* @param $name
* The name of the resource, or NULL if either of the REGISTRY_* constants
* is passed in.
*
* @return
* TRUE if the resource was found, FALSE if not.
* NULL if either of the REGISTRY_* constants is passed in as $type.
*/
function _registry_check_code($type, $name = NULL) {
static $lookup_cache, $cache_update_needed;

if ($type == 'class' && class_exists($name) || $type == 'interface' && interface_exists($name) || $type == 'trait' && trait_exists($name)) {
return TRUE;
}

if (!isset($lookup_cache)) {
$lookup_cache = array();
if ($cache = cache_get('lookup_cache', 'cache_bootstrap')) {
$lookup_cache = $cache->data;
}
}

// When we rebuild the registry, we need to reset this cache so
// we don't keep lookups for resources that changed during the rebuild.
if ($type == REGISTRY_RESET_LOOKUP_CACHE) {
$cache_update_needed = TRUE;
$lookup_cache = NULL;
return;
}

// Called from drupal_page_footer, we write to permanent storage if there
// changes to the lookup cache for this request.
if ($type == REGISTRY_WRITE_LOOKUP_CACHE) {
if ($cache_update_needed) {
cache_set('lookup_cache', $lookup_cache, 'cache_bootstrap');
}
return;
}

// $type is either 'interface' or 'class', so we only need the first letter to
// keep the cache key unique.
$cache_key = $type[0] . $name;
if (isset($lookup_cache[$cache_key])) {
if ($lookup_cache[$cache_key]) {
include_once DRUPAL_ROOT . '/' . $lookup_cache[$cache_key];
}
return (bool) $lookup_cache[$cache_key];
}

// This function may get called when the default database is not active, but
// there is no reason we'd ever want to not use the default database for
// this query.
$file = Database::getConnection('default', 'default')
->select('registry', 'r', array('target' => 'default'))
->fields('r', array('filename'))
// Use LIKE here to make the query case-insensitive.
->condition('r.name', db_like($name), 'LIKE')
->condition('r.type', $type)
->execute()
->fetchField();

// Flag that we've run a lookup query and need to update the cache.
$cache_update_needed = TRUE;

// Misses are valuable information worth caching, so cache even if
// $file is FALSE.
$lookup_cache[$cache_key] = $file;

if ($file) {
include_once DRUPAL_ROOT . '/' . $file;
return TRUE;
}
else {
return FALSE;
}
}

/**
* Rescans all enabled modules and rebuilds the registry.
*
* Rescans all code in modules or includes directories, storing the location of
* each interface or class in the database.
*/
function registry_rebuild() {
system_rebuild_module_data();
registry_update();
}

/**
* Updates the registry based on the latest files listed in the database.
*
* This function should be used when system_rebuild_module_data() does not need
* to be called, because it is already known that the list of files in the
* {system} table matches those in the file system.
*
* @return
* TRUE if the registry was rebuilt, FALSE if another thread was rebuilding
* in parallel and the current thread just waited for completion.
*
* @see registry_rebuild()
*/
function registry_update() {
// install_system_module() calls module_enable() which calls into this
// function during initial system installation, so the lock system is neither
// loaded nor does its storage exist yet.
$in_installer = drupal_installation_attempted();
if (!$in_installer && !lock_acquire(__FUNCTION__)) {
// Another request got the lock, wait for it to finish.
lock_wait(__FUNCTION__);
return FALSE;
}

require_once DRUPAL_ROOT . '/includes/registry.inc';
_registry_update();

if (!$in_installer) {
lock_release(__FUNCTION__);
}
return TRUE;
}

/**
* @} End of "addtogroup registry".
*/

/**
* Provides central static variable storage.
*
* All functions requiring a static variable to persist or cache data within
* a single page request are encouraged to use this function unless it is
* absolutely certain that the static variable will not need to be reset during
* the page request. By centralizing static variable storage through this
* function, other functions can rely on a consistent API for resetting any
* other function's static variables.
*
* Example:
* @code
* function language_list($field = 'language') {
* $languages = &drupal_static(__FUNCTION__);
* if (!isset($languages)) {
* // If this function is being called for the first time after a reset,
* // query the database and execute any other code needed to retrieve
* // information about the supported languages.
* ...
* }
* if (!isset($languages[$field])) {
* // If this function is being called for the first time for a particular
* // index field, then execute code needed to index the information already
* // available in $languages by the desired field.
* ...
* }
* // Subsequent invocations of this function for a particular index field
* // skip the above two code blocks and quickly return the already indexed
* // information.
* return $languages[$field];
* }
* function locale_translate_overview_screen() {
* // When building the content for the translations overview page, make
* // sure to get completely fresh information about the supported languages.
* drupal_static_reset('language_list');
* ...
* }
* @endcode
*
* In a few cases, a function can have certainty that there is no legitimate
* use-case for resetting that function's static variable. This is rare,
* because when writing a function, it's hard to forecast all the situations in
* which it will be used. A guideline is that if a function's static variable
* does not depend on any information outside of the function that might change
* during a single page request, then it's ok to use the "static" keyword
* instead of the drupal_static() function.
*
* Example:
* @code
* function actions_do(...) {
* // $stack tracks the number of recursive calls.
* static $stack;
* $stack++;
* if ($stack > variable_get('actions_max_stack', 35)) {
* ...
* return;
* }
* ...
* $stack--;
* }
* @endcode
*
* In a few cases, a function needs a resettable static variable, but the
* function is called many times (100+) during a single page request, so
* every microsecond of execution time that can be removed from the function
* counts. These functions can use a more cumbersome, but faster variant of
* calling drupal_static(). It works by storing the reference returned by
* drupal_static() in the calling function's own static variable, thereby
* removing the need to call drupal_static() for each iteration of the function.
* Conceptually, it replaces:
* @code
* $foo = &drupal_static(__FUNCTION__);
* @endcode
* with:
* @code
* // Unfortunately, this does not work.
* static $foo = &drupal_static(__FUNCTION__);
* @endcode
* However, the above line of code does not work, because PHP only allows static
* variables to be initializied by literal values, and does not allow static
* variables to be assigned to references.
* - http://php.net/manual/language.variables.scope.php#language.variables.scope.static
* - http://php.net/manual/language.variables.scope.php#language.variables.scope.references
* The example below shows the syntax needed to work around both limitations.
* For benchmarks and more information, see http://drupal.org/node/619666.
*
* Example:
* @code
* function user_access($string, $account = NULL) {
* // Use the advanced drupal_static() pattern, since this is called very often.
* static $drupal_static_fast;
* if (!isset($drupal_static_fast)) {
* $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
* }
* $perm = &$drupal_static_fast['perm'];
* ...
* }
* @endcode
*
* @param $name
* Globally unique name for the variable. For a function with only one static,
* variable, the function name (e.g. via the PHP magic __FUNCTION__ constant)
* is recommended. For a function with multiple static variables add a
* distinguishing suffix to the function name for each one.
* @param $default_value
* Optional default value.
* @param $reset
* TRUE to reset one or all variables(s). This parameter is only used
* internally and should not be passed in; use drupal_static_reset() instead.
* (This function's return value should not be used when TRUE is passed in.)
*
* @return
* Returns a variable by reference.
*
* @see drupal_static_reset()
*/
function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
static $data = array(), $default = array();
// First check if dealing with a previously defined static variable.
if (isset($data[$name]) || array_key_exists($name, $data)) {
// Non-NULL $name and both $data[$name] and $default[$name] statics exist.
if ($reset) {
// Reset pre-existing static variable to its default value.
$data[$name] = $default[$name];
}
return $data[$name];
}
// Neither $data[$name] nor $default[$name] static variables exist.
if (isset($name)) {
if ($reset) {
// Reset was called before a default is set and yet a variable must be
// returned.
return $data;
}
// First call with new non-NULL $name. Initialize a new static variable.
$default[$name] = $data[$name] = $default_value;
return $data[$name];
}
// Reset all: ($name == NULL). This needs to be done one at a time so that
// references returned by earlier invocations of drupal_static() also get
// reset.
foreach ($default as $name => $value) {
$data[$name] = $value;
}
// As the function returns a reference, the return should always be a
// variable.
return $data;
}

/**
* Resets one or all centrally stored static variable(s).
*
* @param $name
* Name of the static variable to reset. Omit to reset all variables.
* Resetting all variables should only be used, for example, for running unit
* tests with a clean environment.
*/
function drupal_static_reset($name = NULL) {
drupal_static($name, NULL, TRUE);
}

/**
* Detects whether the current script is running in a command-line environment.
*/
function drupal_is_cli() {
return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
}

/**
* Formats text for emphasized display in a placeholder inside a sentence.
*
* Used automatically by format_string().
*
* @param $text
* The text to format (plain-text).
*
* @return
* The formatted text (html).
*/
function drupal_placeholder($text) {
return '<em class="placeholder">' . check_plain($text) . '</em>';
}

/**
* Registers a function for execution on shutdown.
*
* Wrapper for register_shutdown_function() that catches thrown exceptions to
* avoid "Exception thrown without a stack frame in Unknown".
*
* @param $callback
* The shutdown function to register.
* @param ...
* Additional arguments to pass to the shutdown function.
*
* @return
* Array of shutdown functions to be executed.
*
* @see register_shutdown_function()
* @ingroup php_wrappers
*/
function &drupal_register_shutdown_function($callback = NULL) {
// We cannot use drupal_static() here because the static cache is reset during
// batch processing, which breaks batch handling.
static $callbacks = array();

if (isset($callback)) {
// Only register the internal shutdown function once.
if (empty($callbacks)) {
register_shutdown_function('_drupal_shutdown_function');
}
$args = func_get_args();
array_shift($args);
// Save callback and arguments
$callbacks[] = array('callback' => $callback, 'arguments' => $args);
}
return $callbacks;
}

/**
* Executes registered shutdown functions.
*/
function _drupal_shutdown_function() {
$callbacks = &drupal_register_shutdown_function();

// Set the CWD to DRUPAL_ROOT as it is not guaranteed to be the same as it
// was in the normal context of execution.
chdir(DRUPAL_ROOT);

try {

/*
while (list($key, $callback) = each($callbacks)) {
call_user_func_array($callback['callback'], $callback['arguments']);
}
*/

// by ugarte the top code is old and was working ok
while ($callback = current($callbacks)) {
call_user_func_array($callback['callback'], $callback['arguments']);
next($callbacks);
}

}
catch (Exception $exception) {
// If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
require_once DRUPAL_ROOT . '/includes/errors.inc';
if (error_displayable()) {
print '<h1>Uncaught exception thrown in shutdown function.</h1>';
print '<p>' . _drupal_render_exception_safe($exception) . '</p><hr />';
}
}
}

/**
* Compares the memory required for an operation to the available memory.
*
* @param $required
* The memory required for the operation, expressed as a number of bytes with
* optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8bytes,
* 9mbytes).
* @param $memory_limit
* (optional) The memory limit for the operation, expressed as a number of
* bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G,
* 6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP
* memory_limit will be used. Defaults to NULL.
*
* @return
* TRUE if there is sufficient memory to allow the operation, or FALSE
* otherwise.
*/
function drupal_check_memory_limit($required, $memory_limit = NULL) {
if (!isset($memory_limit)) {
$memory_limit = ini_get('memory_limit');
}

// There is sufficient memory if:
// - No memory limit is set.
// - The memory limit is set to unlimited (-1).
// - The memory limit is greater than the memory required for the operation.
return ((!$memory_limit) || ($memory_limit == -1) || (parse_size($memory_limit) >= parse_size($required)));
}

/**
* Invalidates a PHP file from any active opcode caches.
*
* If the opcode cache does not support the invalidation of individual files,
* the entire cache will be flushed.
*
* @param string $filepath
* The absolute path of the PHP file to invalidate.
*/
function drupal_clear_opcode_cache($filepath) {
if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50300) {
// Below PHP 5.3, clearstatcache does not accept any function parameters.
clearstatcache();
}
else {
clearstatcache(TRUE, $filepath);
}

// Zend OPcache.
if (function_exists('opcache_invalidate')) {
opcache_invalidate($filepath, TRUE);
}
// APC.
if (function_exists('apc_delete_file')) {
// apc_delete_file() throws a PHP warning in case the specified file was
// not compiled yet.
// @see http://php.net/apc-delete-file
@apc_delete_file($filepath);
}
}


/**
* @file
* Functions that need to be loaded on every Drupal request.
*/

/**
* The current system version.
*/
define('VERSION', '7.56');

/**
* Core API compatibility.
*/
define('DRUPAL_CORE_COMPATIBILITY', '7.x');

/**
* Minimum supported version of PHP.
*/
define('DRUPAL_MINIMUM_PHP', '5.2.4');

/**
* Minimum recommended value of PHP memory_limit.
*/
define('DRUPAL_MINIMUM_PHP_MEMORY_LIMIT', '32M');

/**
* Error reporting level: display no errors.
*/
define('ERROR_REPORTING_HIDE', 0);

/**
* Error reporting level: display errors and warnings.
*/
define('ERROR_REPORTING_DISPLAY_SOME', 1);

/**
* Error reporting level: display all messages.
*/
define('ERROR_REPORTING_DISPLAY_ALL', 2);

/**
* Indicates that the item should never be removed unless explicitly selected.
*
* The item may be removed using cache_clear_all() with a cache ID.
*/
define('CACHE_PERMANENT', 0);

/**
* Indicates that the item should be removed at the next general cache wipe.
*/
define('CACHE_TEMPORARY', -1);

/**
* @defgroup logging_severity_levels Logging severity levels
* @{
* Logging severity levels as defined in RFC 3164.
*
* The WATCHDOG_* constant definitions correspond to the logging severity levels
* defined in RFC 3164, section 4.1.1. PHP supplies predefined LOG_* constants
* for use in the syslog() function, but their values on Windows builds do not
* correspond to RFC 3164. The associated PHP bug report was closed with the
* comment, "And it's also not a bug, as Windows just have less log levels,"
* and "So the behavior you're seeing is perfectly normal."
*
* @see http://www.faqs.org/rfcs/rfc3164.html
* @see http://bugs.php.net/bug.php?id=18090
* @see http://php.net/manual/function.syslog.php
* @see http://php.net/manual/network.constants.php
* @see watchdog()
* @see watchdog_severity_levels()
*/

/**
* Log message severity -- Emergency: system is unusable.
*/
define('WATCHDOG_EMERGENCY', 0);

/**
* Log message severity -- Alert: action must be taken immediately.
*/
define('WATCHDOG_ALERT', 1);

/**
* Log message severity -- Critical conditions.
*/
define('WATCHDOG_CRITICAL', 2);

/**
* Log message severity -- Error conditions.
*/
define('WATCHDOG_ERROR', 3);

/**
* Log message severity -- Warning conditions.
*/
define('WATCHDOG_WARNING', 4);

/**
* Log message severity -- Normal but significant conditions.
*/
define('WATCHDOG_NOTICE', 5);

/**
* Log message severity -- Informational messages.
*/
define('WATCHDOG_INFO', 6);

/**
* Log message severity -- Debug-level messages.
*/
define('WATCHDOG_DEBUG', 7);

/**
* @} End of "defgroup logging_severity_levels".
*/

/**
* First bootstrap phase: initialize configuration.
*/
define('DRUPAL_BOOTSTRAP_CONFIGURATION', 0);

/**
* Second bootstrap phase: try to serve a cached page.
*/
define('DRUPAL_BOOTSTRAP_PAGE_CACHE', 1);

/**
* Third bootstrap phase: initialize database layer.
*/
define('DRUPAL_BOOTSTRAP_DATABASE', 2);

/**
* Fourth bootstrap phase: initialize the variable system.
*/
define('DRUPAL_BOOTSTRAP_VARIABLES', 3);

/**
* Fifth bootstrap phase: initialize session handling.
*/
define('DRUPAL_BOOTSTRAP_SESSION', 4);

/**
* Sixth bootstrap phase: set up the page header.
*/
define('DRUPAL_BOOTSTRAP_PAGE_HEADER', 5);

/**
* Seventh bootstrap phase: find out language of the page.
*/
define('DRUPAL_BOOTSTRAP_LANGUAGE', 6);

/**
* Final bootstrap phase: Drupal is fully loaded; validate and fix input data.
*/
define('DRUPAL_BOOTSTRAP_FULL', 7);

/**
* Role ID for anonymous users; should match what's in the "role" table.
*/
define('DRUPAL_ANONYMOUS_RID', 1);

/**
* Role ID for authenticated users; should match what's in the "role" table.
*/
define('DRUPAL_AUTHENTICATED_RID', 2);

/**
* The number of bytes in a kilobyte.
*
* For more information, visit http://en.wikipedia.org/wiki/Kilobyte.
*/
define('DRUPAL_KILOBYTE', 1024);

/**
* The language code used when no language is explicitly assigned.
*
* Defined by ISO639-2 for "Undetermined".
*/
define('LANGUAGE_NONE', 'und');

/**
* The type of language used to define the content language.
*/
define('LANGUAGE_TYPE_CONTENT', 'language_content');

/**
* The type of language used to select the user interface.
*/
define('LANGUAGE_TYPE_INTERFACE', 'language');

/**
* The type of language used for URLs.
*/
define('LANGUAGE_TYPE_URL', 'language_url');

/**
* Language written left to right. Possible value of $language->direction.
*/
define('LANGUAGE_LTR', 0);

/**
* Language written right to left. Possible value of $language->direction.
*/
define('LANGUAGE_RTL', 1);

/**
* Time of the current request in seconds elapsed since the Unix Epoch.
*
* This differs from $_SERVER['REQUEST_TIME'], which is stored as a float
* since PHP 5.4.0. Float timestamps confuse most PHP functions
* (including date_create()).
*
* @see http://php.net/manual/reserved.variables.server.php
* @see http://php.net/manual/function.time.php
*/
define('REQUEST_TIME', (int) $_SERVER['REQUEST_TIME']);

/**
* Flag used to indicate that text is not sanitized, so run check_plain().
*
* @see drupal_set_title()
*/
define('CHECK_PLAIN', 0);

/**
* Flag used to indicate that text has already been sanitized.
*
* @see drupal_set_title()
*/
define('PASS_THROUGH', -1);

/**
* Signals that the registry lookup cache should be reset.
*/
define('REGISTRY_RESET_LOOKUP_CACHE', 1);

/**
* Signals that the registry lookup cache should be written to storage.
*/
define('REGISTRY_WRITE_LOOKUP_CACHE', 2);

/**
* Regular expression to match PHP function names.
*
* @see http://php.net/manual/language.functions.php
*/
define('DRUPAL_PHP_FUNCTION_PATTERN', '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*');

/**
* A RFC7231 Compliant date.
*
* http://tools.ietf.org/html/rfc7231#section-7.1.1.1
*
* Example: Sun, 06 Nov 1994 08:49:37 GMT
*
* This constant was introduced in PHP 7.0.19 and PHP 7.1.5 but needs to be
* defined by Drupal for earlier PHP versions.
*/
if (!defined('DATE_RFC7231')) {
define('DATE_RFC7231', 'D, d M Y H:i:s \G\M\T');
}

/**
* Provides a caching wrapper to be used in place of large array structures.
*
* This class should be extended by systems that need to cache large amounts
* of data and have it represented as an array to calling functions. These
* arrays can become very large, so ArrayAccess is used to allow different
* strategies to be used for caching internally (lazy loading, building caches
* over time etc.). This can dramatically reduce the amount of data that needs
* to be loaded from cache backends on each request, and memory usage from
* static caches of that same data.
*
* Note that array_* functions do not work with ArrayAccess. Systems using
* DrupalCacheArray should use this only internally. If providing API functions
* that return the full array, this can be cached separately or returned
* directly. However since DrupalCacheArray holds partial content by design, it
* should be a normal PHP array or otherwise contain the full structure.
*
* Note also that due to limitations in PHP prior to 5.3.4, it is impossible to
* write directly to the contents of nested arrays contained in this object.
* Only writes to the top-level array elements are possible. So if you
* previously had set $object['foo'] = array(1, 2, 'bar' => 'baz'), but later
* want to change the value of 'bar' from 'baz' to 'foobar', you cannot do so
* a targeted write like $object['foo']['bar'] = 'foobar'. Instead, you must
* overwrite the entire top-level 'foo' array with the entire set of new
* values: $object['foo'] = array(1, 2, 'bar' => 'foobar'). Due to this same
* limitation, attempts to create references to any contained data, nested or
* otherwise, will fail silently. So $var = &$object['foo'] will not throw an
* error, and $var will be populated with the contents of $object['foo'], but
* that data will be passed by value, not reference. For more information on
* the PHP limitation, see the note in the official PHP documentation at·
* http://php.net/manual/arrayaccess.offsetget.php on
* ArrayAccess::offsetGet().
*
* By default, the class accounts for caches where calling functions might
* request keys in the array that won't exist even after a cache rebuild. This
* prevents situations where a cache rebuild would be triggered over and over
* due to a 'missing' item. These cases are stored internally as a value of
* NULL. This means that the offsetGet() and offsetExists() methods
* must be overridden if caching an array where the top level values can
* legitimately be NULL, and where $object->offsetExists() needs to correctly
* return (equivalent to array_key_exists() vs. isset()). This should not
* be necessary in the majority of cases.
*
* Classes extending this class must override at least the
* resolveCacheMiss() method to have a working implementation.
*
* offsetSet() is not overridden by this class by default. In practice this
* means that assigning an offset via arrayAccess will only apply while the
* object is in scope and will not be written back to the persistent cache.
* This follows a similar pattern to static vs. persistent caching in
* procedural code. Extending classes may wish to alter this behavior, for
* example by overriding offsetSet() and adding an automatic call to persist().
*
* @see SchemaCache
*/
abstract class DrupalCacheArray implements ArrayAccess {

/**
* A cid to pass to cache_set() and cache_get().
*/
protected $cid;

/**
* A bin to pass to cache_set() and cache_get().
*/
protected $bin;

/**
* An array of keys to add to the cache at the end of the request.
*/
protected $keysToPersist = array();

/**
* Storage for the data itself.
*/
protected $storage = array();

/**
* Constructs a DrupalCacheArray object.
*
* @param $cid
* The cid for the array being cached.
* @param $bin
* The bin to cache the array.
*/
public function __construct($cid, $bin) {
$this->cid = $cid;
$this->bin = $bin;

if ($cached = cache_get($this->cid, $this->bin)) {
$this->storage = $cached->data;
}
}

/**
* Implements ArrayAccess::offsetExists().
*/
public function offsetExists($offset) {
return $this->offsetGet($offset) !== NULL;
}

/**
* Implements ArrayAccess::offsetGet().
*/
public function offsetGet($offset) {
if (isset($this->storage[$offset]) || array_key_exists($offset, $this->storage)) {
return $this->storage[$offset];
}
else {
return $this->resolveCacheMiss($offset);
}
}

/**
* Implements ArrayAccess::offsetSet().
*/
public function offsetSet($offset, $value) {
$this->storage[$offset] = $value;
}

/**
* Implements ArrayAccess::offsetUnset().
*/
public function offsetUnset($offset) {
unset($this->storage[$offset]);
}

/**
* Flags an offset value to be written to the persistent cache.
*
* If a value is assigned to a cache object with offsetSet(), by default it
* will not be written to the persistent cache unless it is flagged with this
* method. This allows items to be cached for the duration of a request,
* without necessarily writing back to the persistent cache at the end.
*
* @param $offset
* The array offset that was requested.
* @param $persist
* Optional boolean to specify whether the offset should be persisted or
* not, defaults to TRUE. When called with $persist = FALSE the offset will
* be unflagged so that it will not be written at the end of the request.
*/
protected function persist($offset, $persist = TRUE) {
$this->keysToPersist[$offset] = $persist;
}

/**
* Resolves a cache miss.
*
* When an offset is not found in the object, this is treated as a cache
* miss. This method allows classes implementing the interface to look up
* the actual value and allow it to be cached.
*
* @param $offset
* The offset that was requested.
*
* @return
* The value of the offset, or NULL if no value was found.
*/
abstract protected function resolveCacheMiss($offset);

/**
* Writes a value to the persistent cache immediately.
*
* @param $data
* The data to write to the persistent cache.
* @param $lock
* Whether to acquire a lock before writing to cache.
*/
protected function set($data, $lock = TRUE) {
// Lock cache writes to help avoid stampedes.
// To implement locking for cache misses, override __construct().
$lock_name = $this->cid . ':' . $this->bin;
if (!$lock || lock_acquire($lock_name)) {
if ($cached = cache_get($this->cid, $this->bin)) {
$data = $cached->data + $data;
}
cache_set($this->cid, $data, $this->bin);
if ($lock) {
lock_release($lock_name);
}
}
}

/**
* Destructs the DrupalCacheArray object.
*/
public function __destruct() {
$data = array();
foreach ($this->keysToPersist as $offset => $persist) {
if ($persist) {
$data[$offset] = $this->storage[$offset];
}
}
if (!empty($data)) {
$this->set($data);
}
}
}

/**
* Starts the timer with the specified name.
*
* If you start and stop the same timer multiple times, the measured intervals
* will be accumulated.
*
* @param $name
* The name of the timer.
*/
function timer_start($name) {
global $timers;

$timers[$name]['start'] = microtime(TRUE);
$timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
}

/**
* Reads the current timer value without stopping the timer.
*
* @param $name
* The name of the timer.
*
* @return
* The current timer value in ms.
*/
function timer_read($name) {
global $timers;

if (isset($timers[$name]['start'])) {
$stop = microtime(TRUE);
$diff = round(($stop - $timers[$name]['start']) * 1000, 2);

if (isset($timers[$name]['time'])) {
$diff += $timers[$name]['time'];
}
return $diff;
}
return $timers[$name]['time'];
}

/**
* Stops the timer with the specified name.
*
* @param $name
* The name of the timer.
*
* @return
* A timer array. The array contains the number of times the timer has been
* started and stopped (count) and the accumulated timer value in ms (time).
*/
function timer_stop($name) {
global $timers;

if (isset($timers[$name]['start'])) {
$stop = microtime(TRUE);
$diff = round(($stop - $timers[$name]['start']) * 1000, 2);
if (isset($timers[$name]['time'])) {
$timers[$name]['time'] += $diff;
}
else {
$timers[$name]['time'] = $diff;
}
unset($timers[$name]['start']);
}

return $timers[$name];
}

/**
* Returns the appropriate configuration directory.
*
* Returns the configuration path based on the site's hostname, port, and
* pathname. See default.settings.php for examples on how the URL is converted
* to a directory.
*
* @param bool $require_settings
* Only configuration directories with an existing settings.php file
* will be recognized. Defaults to TRUE. During initial installation,
* this is set to FALSE so that Drupal can detect a matching directory,
* then create a new settings.php file in it.
* @param bool $reset
* Force a full search for matching directories even if one had been
* found previously. Defaults to FALSE.
*
* @return
* The path of the matching directory.
*
* @see default.settings.php
*/
function conf_path($require_settings = TRUE, $reset = FALSE) {
$conf = &drupal_static(__FUNCTION__, '');

if ($conf && !$reset) {
return $conf;
}

$confdir = 'sites';

$sites = array();
if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/sites.php')) {
// This will overwrite $sites with the desired mappings.
include(DRUPAL_ROOT . '/' . $confdir . '/sites.php');
}

$uri = explode('/', $_SERVER['SCRIPT_NAME'] ? $_SERVER['SCRIPT_NAME'] : $_SERVER['SCRIPT_FILENAME']);
$server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
for ($i = count($uri) - 1; $i > 0; $i--) {
for ($j = count($server); $j > 0; $j--) {
$dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
if (isset($sites[$dir]) && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $sites[$dir])) {
$dir = $sites[$dir];
}
if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir . '/settings.php') || (!$require_settings && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir))) {
$conf = "$confdir/$dir";
return $conf;
}
}
}
$conf = "$confdir/default";
return $conf;
}

/**
* Sets appropriate server variables needed for command line scripts to work.
*
* This function can be called by command line scripts before bootstrapping
* Drupal, to ensure that the page loads with the desired server parameters.
* This is because many parts of Drupal assume that they are running in a web
* browser and therefore use information from the global PHP $_SERVER variable
* that does not get set when Drupal is run from the command line.
*
* In many cases, the default way in which this function populates the $_SERVER
* variable is sufficient, and it can therefore be called without passing in
* any input. However, command line scripts running on a multisite installation
* (or on any installation that has settings.php stored somewhere other than
* the sites/default folder) need to pass in the URL of the site to allow
* Drupal to detect the correct location of the settings.php file. Passing in
* the 'url' parameter is also required for functions like request_uri() to
* return the expected values.
*
* Most other parameters do not need to be passed in, but may be necessary in
* some cases; for example, if Drupal's ip_address() function needs to return
* anything but the standard localhost value ('127.0.0.1'), the command line
* script should pass in the desired value via the 'REMOTE_ADDR' key.
*
* @param $variables
* (optional) An associative array of variables within $_SERVER that should
* be replaced. If the special element 'url' is provided in this array, it
* will be used to populate some of the server defaults; it should be set to
* the URL of the current page request, excluding any $_GET request but
* including the script name (e.g., http://www.example.com/mysite/index.php).
*
* @see conf_path()
* @see request_uri()
* @see ip_address()
*/
function drupal_override_server_variables($variables = array()) {
// Allow the provided URL to override any existing values in $_SERVER.
if (isset($variables['url'])) {
$url = parse_url($variables['url']);
if (isset($url['host'])) {
$_SERVER['HTTP_HOST'] = $url['host'];
}
if (isset($url['path'])) {
$_SERVER['SCRIPT_NAME'] = $url['path'];
}
unset($variables['url']);
}
// Define default values for $_SERVER keys. These will be used if $_SERVER
// does not already define them and no other values are passed in to this
// function.
$defaults = array(
'HTTP_HOST' => 'localhost',
'SCRIPT_NAME' => NULL,
'REMOTE_ADDR' => '127.0.0.1',
'REQUEST_METHOD' => 'GET',
'SERVER_NAME' => NULL,
'SERVER_SOFTWARE' => NULL,
'HTTP_USER_AGENT' => NULL,
);
// Replace elements of the $_SERVER array, as appropriate.
$_SERVER = $variables + $_SERVER + $defaults;
}

/**
* Initializes the PHP environment.
*/
function drupal_environment_initialize() {
if (!isset($_SERVER['HTTP_REFERER'])) {
$_SERVER['HTTP_REFERER'] = '';
}
if (!isset($_SERVER['SERVER_PROTOCOL']) || ($_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.0' && $_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.1')) {
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
}

if (isset($_SERVER['HTTP_HOST'])) {
// As HTTP_HOST is user input, ensure it only contains characters allowed
// in hostnames. See RFC 952 (and RFC 2181).
// $_SERVER['HTTP_HOST'] is lowercased here per specifications.
$_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']);
if (!drupal_valid_http_host($_SERVER['HTTP_HOST'])) {
// HTTP_HOST is invalid, e.g. if containing slashes it may be an attack.
header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
exit;
}
}
else {
// Some pre-HTTP/1.1 clients will not send a Host header. Ensure the key is
// defined for E_ALL compliance.
$_SERVER['HTTP_HOST'] = '';
}

// When clean URLs are enabled, emulate ?q=foo/bar using REQUEST_URI. It is
// not possible to append the query string using mod_rewrite without the B
// flag (this was added in Apache 2.2.8), because mod_rewrite unescapes the
// path before passing it on to PHP. This is a problem when the path contains
// e.g. "&" or "%" that have special meanings in URLs and must be encoded.
$_GET['q'] = request_path();

// Enforce E_ALL, but allow users to set levels not part of E_ALL.
error_reporting(E_ALL | error_reporting());

// Override PHP settings required for Drupal to work properly.
// sites/default/default.settings.php contains more runtime settings.
// The .htaccess file contains settings that cannot be changed at runtime.

// Don't escape quotes when reading files from the database, disk, etc.
ini_set('magic_quotes_runtime', '0');
// Use session cookies, not transparent sessions that puts the session id in
// the query string.
ini_set('session.use_cookies', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.use_trans_sid', '0');
// Don't send HTTP headers using PHP's session handler.
// An empty string is used here to disable the cache limiter.
ini_set('session.cache_limiter', '');
// Use httponly session cookies.
ini_set('session.cookie_httponly', '1');

// Set sane locale settings, to ensure consistent string, dates, times and
// numbers handling.
setlocale(LC_ALL, 'C');
}

/**
* Validates that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
*
* @return
* TRUE if only containing valid characters, or FALSE otherwise.
*/
function drupal_valid_http_host($host) {
// Limit the length of the host name to 1000 bytes to prevent DoS attacks with
// long host names.
return strlen($host) <= 1000
// Limit the number of subdomains and port separators to prevent DoS attacks
// in conf_path().
&& substr_count($host, '.') <= 100
&& substr_count($host, ':') <= 100
&& preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host);
}

/**
* Checks whether an HTTPS request is being served.
*
* @return bool
* TRUE if the request is HTTPS, FALSE otherwise.
*/
function drupal_is_https() {
return isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
}

/**
* Sets the base URL, cookie domain, and session name from configuration.
*/
function drupal_settings_initialize() {
global $base_url, $base_path, $base_root;

// Export these settings.php variables to the global namespace.
global $databases, $cookie_domain, $conf, $installed_profile, $update_free_access, $db_url, $db_prefix, $drupal_hash_salt, $is_https, $base_secure_url, $base_insecure_url;
$conf = array();

if (file_exists(DRUPAL_ROOT . '/' . conf_path() . '/settings.php')) {
include_once DRUPAL_ROOT . '/' . conf_path() . '/settings.php';
}
$is_https = drupal_is_https();

if (isset($base_url)) {
// Parse fixed base URL from settings.php.
$parts = parse_url($base_url);
if (!isset($parts['path'])) {
$parts['path'] = '';
}
$base_path = $parts['path'] . '/';
// Build $base_root (everything until first slash after "scheme://").
$base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
}
else {
// Create base URL.
$http_protocol = $is_https ? 'https' : 'http';
$base_root = $http_protocol . '://' . $_SERVER['HTTP_HOST'];

$base_url = $base_root;

// $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
// be modified by a visitor.
if ($dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/')) {
$base_path = $dir;
$base_url .= $base_path;
$base_path .= '/';
}
else {
$base_path = '/';
}
}
$base_secure_url = str_replace('http://', 'https://', $base_url);
$base_insecure_url = str_replace('https://', 'http://', $base_url);

if ($cookie_domain) {
// If the user specifies the cookie domain, also use it for session name.
$session_name = $cookie_domain;
}
else {
// Otherwise use $base_url as session name, without the protocol
// to use the same session identifiers across HTTP and HTTPS.
list( , $session_name) = explode('://', $base_url, 2);
// HTTP_HOST can be modified by a visitor, but we already sanitized it
// in drupal_settings_initialize().
if (!empty($_SERVER['HTTP_HOST'])) {
$cookie_domain = $_SERVER['HTTP_HOST'];
// Strip leading periods, www., and port numbers from cookie domain.
$cookie_domain = ltrim($cookie_domain, '.');
if (strpos($cookie_domain, 'www.') === 0) {
$cookie_domain = substr($cookie_domain, 4);
}
$cookie_domain = explode(':', $cookie_domain);
$cookie_domain = '.' . $cookie_domain[0];
}
}
// Per RFC 2109, cookie domains must contain at least one dot other than the
// first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
ini_set('session.cookie_domain', $cookie_domain);
}
// To prevent session cookies from being hijacked, a user can configure the
// SSL version of their website to only transfer session cookies via SSL by
// using PHP's session.cookie_secure setting. The browser will then use two
// separate session cookies for the HTTPS and HTTP versions of the site. So we
// must use different session identifiers for HTTPS and HTTP to prevent a
// cookie collision.
if ($is_https) {
ini_set('session.cookie_secure', TRUE);
}
$prefix = ini_get('session.cookie_secure') ? 'SSESS' : 'SESS';
session_name($prefix . substr(hash('sha256', $session_name), 0, 32));
}

/**
* Returns and optionally sets the filename for a system resource.
*
* The filename, whether provided, cached, or retrieved from the database, is
* only returned if the file exists.
*
* This function plays a key role in allowing Drupal's resources (modules
* and themes) to be located in different places depending on a site's
* configuration. For example, a module 'foo' may legally be located
* in any of these three places:
*
* modules/foo/foo.module
* sites/all/modules/foo/foo.module
* sites/example.com/modules/foo/foo.module
*
* Calling drupal_get_filename('module', 'foo') will give you one of
* the above, depending on where the module is located.
*
* @param $type
* The type of the item (theme, theme_engine, module, profile).
* @param $name
* The name of the item for which the filename is requested.
* @param $filename
* The filename of the item if it is to be set explicitly rather
* than by consulting the database.
* @param bool $trigger_error
* Whether to trigger an error when a file is missing or has unexpectedly
* moved. This defaults to TRUE, but can be set to FALSE by calling code that
* merely wants to check whether an item exists in the filesystem.
*
* @return
* The filename of the requested item or NULL if the item is not found.
*/
function drupal_get_filename($type, $name, $filename = NULL, $trigger_error = TRUE) {
// The $files static variable will hold the locations of all requested files.
// We can be sure that any file listed in this static variable actually
// exists as all additions have gone through a file_exists() check.
// The location of files will not change during the request, so do not use
// drupal_static().
static $files = array();

// Profiles are a special case: they have a fixed location and naming.
if ($type == 'profile') {
$profile_filename = "profiles/$name/$name.profile";
$files[$type][$name] = file_exists($profile_filename) ? $profile_filename : FALSE;
}
if (!isset($files[$type])) {
$files[$type] = array();
}

if (!empty($filename) && file_exists($filename)) {
// Prime the static cache with the provided filename.
$files[$type][$name] = $filename;
}
elseif (isset($files[$type][$name])) {
// This item had already been found earlier in the request, either through
// priming of the static cache (for example, in system_list()), through a
// lookup in the {system} table, or through a file scan (cached or not). Do
// nothing.
}
else {
// Look for the filename listed in the {system} table. Verify that we have
// an active database connection before doing so, since this function is
// called both before we have a database connection (i.e. during
// installation) and when a database connection fails.
$database_unavailable = TRUE;
try {
if (function_exists('db_query')) {
$file = db_query("SELECT filename FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
if ($file !== FALSE && file_exists(DRUPAL_ROOT . '/' . $file)) {
$files[$type][$name] = $file;
}
$database_unavailable = FALSE;
}
}
catch (Exception $e) {
// The database table may not exist because Drupal is not yet installed,
// the database might be down, or we may have done a non-database cache
// flush while $conf['page_cache_without_database'] = TRUE and
// $conf['page_cache_invoke_hooks'] = TRUE. We have a fallback for these
// cases so we hide the error completely.
}
// Fall back to searching the filesystem if the database could not find the
// file or the file does not exist at the path returned by the database.
if (!isset($files[$type][$name])) {
$files[$type][$name] = _drupal_get_filename_fallback($type, $name, $trigger_error, $database_unavailable);
}
}

if (isset($files[$type][$name])) {
return $files[$type][$name];
}
}

/**
* Performs a cached file system scan as a fallback when searching for a file.
*
* This function looks for the requested file by triggering a file scan,
* caching the new location if the file has moved and caching the miss
* if the file is missing. If a file had been marked as missing in a previous
* file scan, or if it has been marked as moved and is still in the last known
* location, no new file scan will be performed.
*
* @param string $type
* The type of the item (theme, theme_engine, module, profile).
* @param string $name
* The name of the item for which the filename is requested.
* @param bool $trigger_error
* Whether to trigger an error when a file is missing or has unexpectedly
* moved.
* @param bool $database_unavailable
* Whether this function is being called because the Drupal database could
* not be queried for the file's location.
*
* @return
* The filename of the requested item or NULL if the item is not found.
*
* @see drupal_get_filename()
*/
function _drupal_get_filename_fallback($type, $name, $trigger_error, $database_unavailable) {
$file_scans = &_drupal_file_scan_cache();
$filename = NULL;

// If the cache indicates that the item is missing, or we can verify that the
// item exists in the location the cache says it exists in, use that.
if (isset($file_scans[$type][$name]) && ($file_scans[$type][$name] === FALSE || file_exists($file_scans[$type][$name]))) {
$filename = $file_scans[$type][$name];
}
// Otherwise, perform a new file scan to find the item.
else {
$filename = _drupal_get_filename_perform_file_scan($type, $name);
// Update the static cache, and mark the persistent cache for updating at
// the end of the page request. See drupal_file_scan_write_cache().
$file_scans[$type][$name] = $filename;
$file_scans['#write_cache'] = TRUE;
}

// If requested, trigger a user-level warning about the missing or
// unexpectedly moved file. If the database was unavailable, do not trigger a
// warning in the latter case, though, since if the {system} table could not
// be queried there is no way to know if the location found here was
// "unexpected" or not.
if ($trigger_error) {
$error_type = $filename === FALSE ? 'missing' : 'moved';
if ($error_type == 'missing' || !$database_unavailable) {
_drupal_get_filename_fallback_trigger_error($type, $name, $error_type);
}
}

// The cache stores FALSE for files that aren't found (to be able to
// distinguish them from files that have not yet been searched for), but
// drupal_get_filename() expects NULL for these instead, so convert to NULL
// before returning.
if ($filename === FALSE) {
$filename = NULL;
}
return $filename;
}

/**
* Returns the current list of cached file system scan results.
*
* @return
* An associative array tracking the most recent file scan results for all
* files that have had scans performed. The keys are the type and name of the
* item that was searched for, and the values can be either:
* - Boolean FALSE if the item was not found in the file system.
* - A string pointing to the location where the item was found.
*/
function &_drupal_file_scan_cache() {
$file_scans = &drupal_static(__FUNCTION__, array());

// The file scan results are stored in a persistent cache (in addition to the
// static cache) but because this function can be called before the
// persistent cache is available, we must merge any items that were found
// earlier in the page request into the results from the persistent cache.
if (!isset($file_scans['#cache_merge_done'])) {
try {
if (function_exists('cache_get')) {
$cache = cache_get('_drupal_file_scan_cache', 'cache_bootstrap');
if (!empty($cache->data)) {
// File scan results from the current request should take precedence
// over the results from the persistent cache, since they are newer.
$file_scans = drupal_array_merge_deep($cache->data, $file_scans);
}
// Set a flag to indicate that the persistent cache does not need to be
// merged again.
$file_scans['#cache_merge_done'] = TRUE;
}
}
catch (Exception $e) {
// Hide the error.
}
}

return $file_scans;
}

/**
* Performs a file system scan to search for a system resource.
*
* @param $type
* The type of the item (theme, theme_engine, module, profile).
* @param $name
* The name of the item for which the filename is requested.
*
* @return
* The filename of the requested item or FALSE if the item is not found.
*
* @see drupal_get_filename()
* @see _drupal_get_filename_fallback()
*/
function _drupal_get_filename_perform_file_scan($type, $name) {
// The location of files will not change during the request, so do not use
// drupal_static().
static $dirs = array(), $files = array();

// We have a consistent directory naming: modules, themes...
$dir = $type . 's';
if ($type == 'theme_engine') {
$dir = 'themes/engines';
$extension = 'engine';
}
elseif ($type == 'theme') {
$extension = 'info';
}
else {
$extension = $type;
}

// Check if we had already scanned this directory/extension combination.
if (!isset($dirs[$dir][$extension])) {
// Log that we have now scanned this directory/extension combination
// into a static variable so as to prevent unnecessary file scans.
$dirs[$dir][$extension] = TRUE;
if (!function_exists('drupal_system_listing')) {
require_once DRUPAL_ROOT . '/includes/common.inc';
}
// Scan the appropriate directories for all files with the requested
// extension, not just the file we are currently looking for. This
// prevents unnecessary scans from being repeated when this function is
// called more than once in the same page request.
$matches = drupal_system_listing("/^" . DRUPAL_PHP_FUNCTION_PATTERN . "\.$extension$/", $dir, 'name', 0);
foreach ($matches as $matched_name => $file) {
// Log the locations found in the file scan into a static variable.
$files[$type][$matched_name] = $file->uri;
}
}

// Return the results of the file system scan, or FALSE to indicate the file
// was not found.
return isset($files[$type][$name]) ? $files[$type][$name] : FALSE;
}

/**
* Triggers a user-level warning for missing or unexpectedly moved files.
*
* @param $type
* The type of the item (theme, theme_engine, module, profile).
* @param $name
* The name of the item for which the filename is requested.
* @param $error_type
* The type of the error ('missing' or 'moved').
*
* @see drupal_get_filename()
* @see _drupal_get_filename_fallback()
*/
function _drupal_get_filename_fallback_trigger_error($type, $name, $error_type) {
// Hide messages due to known bugs that will appear on a lot of sites.
// @todo Remove this in https://www.drupal.org/node/2383823
if (empty($name)) {
return;
}

// Make sure we only show any missing or moved file errors only once per
// request.
static $errors_triggered = array();
if (empty($errors_triggered[$type][$name][$error_type])) {
// Use _drupal_trigger_error_with_delayed_logging() here since these are
// triggered during low-level operations that cannot necessarily be
// interrupted by a watchdog() call.
if ($error_type == 'missing') {
_drupal_trigger_error_with_delayed_logging(format_string('The following @type is missing from the file system: %name. For information about how to fix this, see <a href="@documentation">the documentation page</a>.', array('@type' => $type, '%name' => $name, '@documentation' => 'https://www.drupal.org/node/2487215')), E_USER_WARNING);
}
elseif ($error_type == 'moved') {
_drupal_trigger_error_with_delayed_logging(format_string('The following @type has moved within the file system: %name. In order to fix this, clear caches or put the @type back in its original location. For more information, see <a href="@documentation">the documentation page</a>.', array('@type' => $type, '%name' => $name, '@documentation' => 'https://www.drupal.org/node/2487215')), E_USER_WARNING);
}
$errors_triggered[$type][$name][$error_type] = TRUE;
}
}

/**
* Invokes trigger_error() with logging delayed until the end of the request.
*
* This is an alternative to PHP's trigger_error() function which can be used
* during low-level Drupal core operations that need to avoid being interrupted
* by a watchdog() call.
*
* Normally, Drupal's error handler calls watchdog() in response to a
* trigger_error() call. However, this invokes hook_watchdog() which can run
* arbitrary code. If the trigger_error() happens in the middle of an
* operation such as a rebuild operation which should not be interrupted by
* arbitrary code, that could potentially break or trigger the rebuild again.
* This function protects against that by delaying the watchdog() call until
* the end of the current page request.
*
* This is an internal function which should only be called by low-level Drupal
* core functions. It may be removed in a future Drupal 7 release.
*
* @param string $error_msg
* The error message to trigger. As with trigger_error() itself, this is
* limited to 1024 bytes; additional characters beyond that will be removed.
* @param int $error_type
* (optional) The type of error. This should be one of the E_USER family of
* constants. As with trigger_error() itself, this defaults to E_USER_NOTICE
* if not provided.
*
* @see _drupal_log_error()
*/
function _drupal_trigger_error_with_delayed_logging($error_msg, $error_type = E_USER_NOTICE) {
$delay_logging = &drupal_static(__FUNCTION__, FALSE);
$delay_logging = TRUE;
trigger_error($error_msg, $error_type);
$delay_logging = FALSE;
}

/**
* Writes the file scan cache to the persistent cache.
*
* This cache stores all files marked as missing or moved after a file scan
* to prevent unnecessary file scans in subsequent requests. This cache is
* cleared in system_list_reset() (i.e. after a module/theme rebuild).
*/
function drupal_file_scan_write_cache() {
// Only write to the persistent cache if requested, and if we know that any
// data previously in the cache was successfully loaded and merged in by
// _drupal_file_scan_cache().
$file_scans = &_drupal_file_scan_cache();
if (isset($file_scans['#write_cache']) && isset($file_scans['#cache_merge_done'])) {
unset($file_scans['#write_cache']);
cache_set('_drupal_file_scan_cache', $file_scans, 'cache_bootstrap');
}
}

/**
* Loads the persistent variable table.
*
* The variable table is composed of values that have been saved in the table
* with variable_set() as well as those explicitly specified in the
* configuration file.
*/
function variable_initialize($conf = array()) {
// NOTE: caching the variables improves performance by 20% when serving
// cached pages.
if ($cached = cache_get('variables', 'cache_bootstrap')) {
$variables = $cached->data;
}
else {
// Cache miss. Avoid a stampede.
$name = 'variable_init';
if (!lock_acquire($name, 1)) {
// Another request is building the variable cache.
// Wait, then re-run this function.
lock_wait($name);
return variable_initialize($conf);
}
else {
// Proceed with variable rebuild.
$variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
cache_set('variables', $variables, 'cache_bootstrap');
lock_release($name);
}
}

foreach ($conf as $name => $value) {
$variables[$name] = $value;
}

return $variables;
}

/**
* Returns a persistent variable.
*
* Case-sensitivity of the variable_* functions depends on the database
* collation used. To avoid problems, always use lower case for persistent
* variable names.
*
* @param $name
* The name of the variable to return.
* @param $default
* The default value to use if this variable has never been set.
*
* @return
* The value of the variable. Unserialization is taken care of as necessary.
*
* @see variable_del()
* @see variable_set()
*/
function variable_get($name, $default = NULL) {
global $conf;

return isset($conf[$name]) ? $conf[$name] : $default;
}

/**
* Sets a persistent variable.
*
* Case-sensitivity of the variable_* functions depends on the database
* collation used. To avoid problems, always use lower case for persistent
* variable names.
*
* @param $name
* The name of the variable to set.
* @param $value
* The value to set. This can be any PHP data type; these functions take care
* of serialization as necessary.
*
* @see variable_del()
* @see variable_get()
*/
function variable_set($name, $value) {
global $conf;

db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();

cache_clear_all('variables', 'cache_bootstrap');

$conf[$name] = $value;
}

/**
* Unsets a persistent variable.
*
* Case-sensitivity of the variable_* functions depends on the database
* collation used. To avoid problems, always use lower case for persistent
* variable names.
*
* @param $name
* The name of the variable to undefine.
*
* @see variable_get()
* @see variable_set()
*/
function variable_del($name) {
global $conf;

db_delete('variable')
->condition('name', $name)
->execute();
cache_clear_all('variables', 'cache_bootstrap');

unset($conf[$name]);
}

/**
* Retrieves the current page from the cache.
*
* Note: we do not serve cached pages to authenticated users, or to anonymous
* users when $_SESSION is non-empty. $_SESSION may contain status messages
* from a form submission, the contents of a shopping cart, or other user-
* specific content that should not be cached and displayed to other users.
*
* @param $check_only
* (optional) Set to TRUE to only return whether a previous call found a
* cache entry.
*
* @return
* The cache object, if the page was found in the cache, NULL otherwise.
*/
function drupal_page_get_cache($check_only = FALSE) {
global $base_root;
static $cache_hit = FALSE;

if ($check_only) {
return $cache_hit;
}

if (drupal_page_is_cacheable()) {
$cache = cache_get($base_root . request_uri(), 'cache_page');
if ($cache !== FALSE) {
$cache_hit = TRUE;
}
return $cache;
}
}

/**
* Determines the cacheability of the current page.
*
* @param $allow_caching
* Set to FALSE if you want to prevent this page from being cached.
*
* @return
* TRUE if the current page can be cached, FALSE otherwise.
*/
function drupal_page_is_cacheable($allow_caching = NULL) {
$allow_caching_static = &drupal_static(__FUNCTION__, TRUE);
if (isset($allow_caching)) {
$allow_caching_static = $allow_caching;
}

return $allow_caching_static && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')
&& !drupal_is_cli();
}

/**
* Invokes a bootstrap hook in all bootstrap modules that implement it.
*
* @param $hook
* The name of the bootstrap hook to invoke.
*
* @see bootstrap_hooks()
*/
function bootstrap_invoke_all($hook) {
// Bootstrap modules should have been loaded when this function is called, so
// we don't need to tell module_list() to reset its internal list (and we
// therefore leave the first parameter at its default value of FALSE). We
// still pass in TRUE for the second parameter, though; in case this is the
// first time during the bootstrap that module_list() is called, we want to
// make sure that its internal cache is primed with the bootstrap modules
// only.
foreach (module_list(FALSE, TRUE) as $module) {
drupal_load('module', $module);
module_invoke($module, $hook);
}
}

/**
* Includes a file with the provided type and name.
*
* This prevents including a theme, engine, module, etc., more than once.
*
* @param $type
* The type of item to load (i.e. theme, theme_engine, module).
* @param $name
* The name of the item to load.
*
* @return
* TRUE if the item is loaded or has already been loaded.
*/
function drupal_load($type, $name) {
// Once a file is included this can't be reversed during a request so do not
// use drupal_static() here.
static $files = array();

if (isset($files[$type][$name])) {
return TRUE;
}

$filename = drupal_get_filename($type, $name);

if ($filename) {
include_once DRUPAL_ROOT . '/' . $filename;
$files[$type][$name] = TRUE;

return TRUE;
}

return FALSE;
}

/**
* Sets an HTTP response header for the current page.
*
* Note: When sending a Content-Type header, always include a 'charset' type,
* too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
*
* @param $name
* The HTTP header name, or the special 'Status' header name.
* @param $value
* The HTTP header value; if equal to FALSE, the specified header is unset.
* If $name is 'Status', this is expected to be a status code followed by a
* reason phrase, e.g. "404 Not Found".
* @param $append
* Whether to append the value to an existing header or to replace it.
*/
function drupal_add_http_header($name, $value, $append = FALSE) {
// The headers as name/value pairs.
$headers = &drupal_static('drupal_http_headers', array());

$name_lower = strtolower($name);
_drupal_set_preferred_header_name($name);

if ($value === FALSE) {
$headers[$name_lower] = FALSE;
}
elseif (isset($headers[$name_lower]) && $append) {
// Multiple headers with identical names may be combined using comma (RFC
// 2616, section 4.2).
$headers[$name_lower] .= ',' . $value;
}
else {
$headers[$name_lower] = $value;
}
drupal_send_headers(array($name => $headers[$name_lower]), TRUE);
}

/**
* Gets the HTTP response headers for the current page.
*
* @param $name
* An HTTP header name. If omitted, all headers are returned as name/value
* pairs. If an array value is FALSE, the header has been unset.
*
* @return
* A string containing the header value, or FALSE if the header has been set,
* or NULL if the header has not been set.
*/
function drupal_get_http_header($name = NULL) {
$headers = &drupal_static('drupal_http_headers', array());
if (isset($name)) {
$name = strtolower($name);
return isset($headers[$name]) ? $headers[$name] : NULL;
}
else {
return $headers;
}
}

/**
* Sets the preferred name for the HTTP header.
*
* Header names are case-insensitive, but for maximum compatibility they should
* follow "common form" (see RFC 2617, section 4.2).
*/
function _drupal_set_preferred_header_name($name = NULL) {
static $header_names = array();

if (!isset($name)) {
return $header_names;
}
$header_names[strtolower($name)] = $name;
}

/**
* Sends the HTTP response headers that were previously set, adding defaults.
*
* Headers are set in drupal_add_http_header(). Default headers are not set
* if they have been replaced or unset using drupal_add_http_header().
*
* @param array $default_headers
* (optional) An array of headers as name/value pairs.
* @param bool $only_default
* (optional) If TRUE and headers have already been sent, send only the
* specified headers.
*/
function drupal_send_headers($default_headers = array(), $only_default = FALSE) {
$headers_sent = &drupal_static(__FUNCTION__, FALSE);
$headers = drupal_get_http_header();
if ($only_default && $headers_sent) {
$headers = array();
}
$headers_sent = TRUE;

$header_names = _drupal_set_preferred_header_name();
foreach ($default_headers as $name => $value) {
$name_lower = strtolower($name);
if (!isset($headers[$name_lower])) {
$headers[$name_lower] = $value;
$header_names[$name_lower] = $name;
}
}
foreach ($headers as $name_lower => $value) {
if ($name_lower == 'status') {
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $value);
}
// Skip headers that have been unset.
elseif ($value !== FALSE) {
header($header_names[$name_lower] . ': ' . $value);
}
}
}

/**
* Sets HTTP headers in preparation for a page response.
*
* Authenticated users are always given a 'no-cache' header, and will fetch a
* fresh page on every request. This prevents authenticated users from seeing
* locally cached pages.
*
* ETag and Last-Modified headers are not set per default for authenticated
* users so that browsers do not send If-Modified-Since headers from
* authenticated user pages. drupal_serve_page_from_cache() will set appropriate
* ETag and Last-Modified headers for cached pages.
*
* @see drupal_page_set_cache()
*/
function drupal_page_header() {
$headers_sent = &drupal_static(__FUNCTION__, FALSE);
if ($headers_sent) {
return TRUE;
}
$headers_sent = TRUE;

$default_headers = array(
'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
'Cache-Control' => 'no-cache, must-revalidate',
// Prevent browsers from sniffing a response and picking a MIME type
// different from the declared content-type, since that can lead to
// XSS and other vulnerabilities.
'X-Content-Type-Options' => 'nosniff',
);
drupal_send_headers($default_headers);
}

/**
* Sets HTTP headers in preparation for a cached page response.
*
* The headers allow as much as possible in proxies and browsers without any
* particular knowledge about the pages. Modules can override these headers
* using drupal_add_http_header().
*
* If the request is conditional (using If-Modified-Since and If-None-Match),
* and the conditions match those currently in the cache, a 304 Not Modified
* response is sent.
*/
function drupal_serve_page_from_cache(stdClass $cache) {
// Negotiate whether to use compression.
$page_compression = !empty($cache->data['page_compressed']);
$return_compressed = $page_compression && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE;

// Get headers set in hook_boot(). Keys are lower-case.
$hook_boot_headers = drupal_get_http_header();

// Headers generated in this function, that may be replaced or unset using
// drupal_add_http_headers(). Keys are mixed-case.
$default_headers = array();

foreach ($cache->data['headers'] as $name => $value) {
// In the case of a 304 response, certain headers must be sent, and the
// remaining may not (see RFC 2616, section 10.3.5). Do not override
// headers set in hook_boot().
$name_lower = strtolower($name);
if (in_array($name_lower, array('content-location', 'expires', 'cache-control', 'vary')) && !isset($hook_boot_headers[$name_lower])) {
drupal_add_http_header($name, $value);
unset($cache->data['headers'][$name]);
}
}

// If the client sent a session cookie, a cached copy will only be served
// to that one particular client due to Vary: Cookie. Thus, do not set
// max-age > 0, allowing the page to be cached by external proxies, when a
// session cookie is present unless the Vary header has been replaced or
// unset in hook_boot().
$max_age = !isset($_COOKIE[session_name()]) || isset($hook_boot_headers['vary']) ? variable_get('page_cache_maximum_age', 0) : 0;
$default_headers['Cache-Control'] = 'public, max-age=' . $max_age;

// Entity tag should change if the output changes.
$etag = '"' . $cache->created . '-' . intval($return_compressed) . '"';
header('Etag: ' . $etag);

// See if the client has provided the required HTTP headers.
$if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : FALSE;
$if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : FALSE;

if ($if_modified_since && $if_none_match
&& $if_none_match == $etag // etag must match
&& $if_modified_since == $cache->created) { // if-modified-since must match
header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
drupal_send_headers($default_headers);
return;
}

// Send the remaining headers.
foreach ($cache->data['headers'] as $name => $value) {
drupal_add_http_header($name, $value);
}

$default_headers['Last-Modified'] = gmdate(DATE_RFC7231, $cache->created);

// HTTP/1.0 proxies does not support the Vary header, so prevent any caching
// by sending an Expires date in the past. HTTP/1.1 clients ignores the
// Expires header if a Cache-Control: max-age= directive is specified (see RFC
// 2616, section 14.9.3).
$default_headers['Expires'] = 'Sun, 19 Nov 1978 05:00:00 GMT';

drupal_send_headers($default_headers);

// Allow HTTP proxies to cache pages for anonymous users without a session
// cookie. The Vary header is used to indicates the set of request-header
// fields that fully determines whether a cache is permitted to use the
// response to reply to a subsequent request for a given URL without
// revalidation. If a Vary header has been set in hook_boot(), it is assumed
// that the module knows how to cache the page.
if (!isset($hook_boot_headers['vary']) && !variable_get('omit_vary_cookie')) {
header('Vary: Cookie');
}

if ($page_compression) {
header('Vary: Accept-Encoding', FALSE);
// If page_compression is enabled, the cache contains gzipped data.
if ($return_compressed) {
// $cache->data['body'] is already gzip'ed, so make sure
// zlib.output_compression does not compress it once more.
ini_set('zlib.output_compression', '0');
header('Content-Encoding: gzip');
}
else {
// The client does not support compression, so unzip the data in the
// cache. Strip the gzip header and run uncompress.
$cache->data['body'] = gzinflate(substr(substr($cache->data['body'], 10), 0, -8));
}
}

// Print the page.
print $cache->data['body'];
}

/**
* Defines the critical hooks that force modules to always be loaded.
*/
function bootstrap_hooks() {
return array('boot', 'exit', 'watchdog', 'language_init');
}

/**
* Unserializes and appends elements from a serialized string.
*
* @param $obj
* The object to which the elements are appended.
* @param $field
* The attribute of $obj whose value should be unserialized.
*/
function drupal_unpack($obj, $field = 'data') {
if ($obj->$field && $data = unserialize($obj->$field)) {
foreach ($data as $key => $value) {
if (!empty($key) && !isset($obj->$key)) {
$obj->$key = $value;
}
}
}
return $obj;
}

/**
* Translates a string to the current language or to a given language.
*
* The t() function serves two purposes. First, at run-time it translates
* user-visible text into the appropriate language. Second, various mechanisms
* that figure out what text needs to be translated work off t() -- the text
* inside t() calls is added to the database of strings to be translated.
* These strings are expected to be in English, so the first argument should
* always be in English. To enable a fully-translatable site, it is important
* that all human-readable text that will be displayed on the site or sent to
* a user is passed through the t() function, or a related function. See the
* @link http://drupal.org/node/322729 Localization API @endlink pages for
* more information, including recommendations on how to break up or not
* break up strings for translation.
*
* @section sec_translating_vars Translating Variables
* You should never use t() to translate variables, such as calling
* @code t($text); @endcode, unless the text that the variable holds has been
* passed through t() elsewhere (e.g., $text is one of several translated
* literal strings in an array). It is especially important never to call
* @code t($user_text); @endcode, where $user_text is some text that a user
* entered - doing that can lead to cross-site scripting and other security
* problems. However, you can use variable substitution in your string, to put
* variable text such as user names or link URLs into translated text. Variable
* substitution looks like this:
* @code
* $text = t("@name's blog", array('@name' => format_username($account)));
* @endcode
* Basically, you can put variables like @name into your string, and t() will
* substitute their sanitized values at translation time. (See the
* Localization API pages referenced above and the documentation of
* format_string() for details about how to define variables in your string.)
* Translators can then rearrange the string as necessary for the language
* (e.g., in Spanish, it might be "blog de @name").
*
* @section sec_alt_funcs_install Use During Installation Phase
* During the Drupal installation phase, some resources used by t() wil not be
* available to code that needs localization. See st() and get_t() for
* alternatives.
*
* @section sec_context String context
* Matching source strings are normally only translated once, and the same
* translation is used everywhere that has a matching string. However, in some
* cases, a certain English source string needs to have multiple translations.
* One example of this is the string "May", which could be used as either a
* full month name or a 3-letter abbreviated month. In other languages where
* the month name for May has more than 3 letters, you would need to provide
* two different translations (one for the full name and one abbreviated), and
* the correct form would need to be chosen, depending on how "May" is being
* used. To facilitate this, the "May" string should be provided with two
* different contexts in the $options parameter when calling t(). For example:
* @code
* t('May', array(), array('context' => 'Long month name')
* t('May', array(), array('context' => 'Abbreviated month name')
* @endcode
* See https://localize.drupal.org/node/2109 for more information.
*
* @param $string
* A string containing the English string to translate.
* @param $args
* An associative array of replacements to make after translation. Based
* on the first character of the key, the value is escaped and/or themed.
* See format_string() for details.
* @param $options
* An associative array of additional options, with the following elements:
* - 'langcode' (defaults to the current language): The language code to
* translate to a language other than what is used to display the page.
* - 'context' (defaults to the empty context): A string giving the context
* that the source string belongs to. See @ref sec_context above for more
* information.
*
* @return
* The translated string.
*
* @see st()
* @see get_t()
* @see format_string()
* @ingroup sanitization
*/
function t($string, array $args = array(), array $options = array()) {
global $language;
static $custom_strings;

// Merge in default.
if (empty($options['langcode'])) {
$options['langcode'] = isset($language->language) ? $language->language : 'en';
}
if (empty($options['context'])) {
$options['context'] = '';
}

// First, check for an array of customized strings. If present, use the array
// *instead of* database lookups. This is a high performance way to provide a
// handful of string replacements. See settings.php for examples.
// Cache the $custom_strings variable to improve performance.
if (!isset($custom_strings[$options['langcode']])) {
$custom_strings[$options['langcode']] = variable_get('locale_custom_strings_' . $options['langcode'], array());
}
// Custom strings work for English too, even if locale module is disabled.
if (isset($custom_strings[$options['langcode']][$options['context']][$string])) {
$string = $custom_strings[$options['langcode']][$options['context']][$string];
}
// Translate with locale module if enabled.
elseif ($options['langcode'] != 'en' && function_exists('locale')) {
$string = locale($string, $options['context'], $options['langcode']);
}
if (empty($args)) {
return $string;
}
else {
return format_string($string, $args);
}
}

/**
* Formats a string for HTML display by replacing variable placeholders.
*
* This function replaces variable placeholders in a string with the requested
* values and escapes the values so they can be safely displayed as HTML. It
* should be used on any unknown text that is intended to be printed to an HTML
* page (especially text that may have come from untrusted users, since in that
* case it prevents cross-site scripting and other security problems).
*
* In most cases, you should use t() rather than calling this function
* directly, since it will translate the text (on non-English-only sites) in
* addition to formatting it.
*
* @param $string
* A string containing placeholders.
* @param $args
* An associative array of replacements to make. Occurrences in $string of
* any key in $args are replaced with the corresponding value, after optional
* sanitization and formatting. The type of sanitization and formatting
* depends on the first character of the key:
* - @variable: Escaped to HTML using check_plain(). Use this as the default
* choice for anything displayed on a page on the site.
* - %variable: Escaped to HTML and formatted using drupal_placeholder(),
* which makes it display as <em>emphasized</em> text.
* - !variable: Inserted as is, with no sanitization or formatting. Only use
* this for text that has already been prepared for HTML display (for
* example, user-supplied text that has already been run through
* check_plain() previously, or is expected to contain some limited HTML
* tags and has already been run through filter_xss() previously).
*
* @see t()
* @ingroup sanitization
*/
function format_string($string, array $args = array()) {
// Transform arguments before inserting them.
foreach ($args as $key => $value) {
switch ($key[0]) {
case '@':
// Escaped only.
$args[$key] = check_plain($value);
break;

case '%':
default:
// Escaped and placeholder.
$args[$key] = drupal_placeholder($value);
break;

case '!':
// Pass-through.
}
}
return strtr($string, $args);
}

/**
* Encodes special characters in a plain-text string for display as HTML.
*
* Also validates strings as UTF-8 to prevent cross site scripting attacks on
* Internet Explorer 6.
*
* @param string $text
* The text to be checked or processed.
*
* @return string
* An HTML safe version of $text. If $text is not valid UTF-8, an empty string
* is returned and, on PHP < 5.4, a warning may be issued depending on server
* configuration (see @link https://bugs.php.net/bug.php?id=47494 @endlink).
*
* @see drupal_validate_utf8()
* @ingroup sanitization
*/
function check_plain($text) {
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

/**
* Checks whether a string is valid UTF-8.
*
* All functions designed to filter input should use drupal_validate_utf8
* to ensure they operate on valid UTF-8 strings to prevent bypass of the
* filter.
*
* When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
* as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
* bytes. When these subsequent bytes are HTML control characters such as
* quotes or angle brackets, parts of the text that were deemed safe by filters
* end up in locations that are potentially unsafe; An onerror attribute that
* is outside of a tag, and thus deemed safe by a filter, can be interpreted
* by the browser as if it were inside the tag.
*
* The function does not return FALSE for strings containing character codes
* above U+10FFFF, even though these are prohibited by RFC 3629.
*
* @param $text
* The text to check.
*
* @return
* TRUE if the text is valid UTF-8, FALSE if not.
*/
function drupal_validate_utf8($text) {
if (strlen($text) == 0) {
return TRUE;
}
// With the PCRE_UTF8 modifier 'u', preg_match() fails silently on strings
// containing invalid UTF-8 byte sequences. It does not reject character
// codes above U+10FFFF (represented by 4 or more octets), though.
return (preg_match('/^./us', $text) == 1);
}

/**
* Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
*
* Because $_SERVER['REQUEST_URI'] is only available on Apache, we generate an
* equivalent using other environment variables.
*/
function request_uri() {
if (isset($_SERVER['REQUEST_URI'])) {
$uri = $_SERVER['REQUEST_URI'];
}
else {
if (isset($_SERVER['argv'])) {
$uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
}
elseif (isset($_SERVER['QUERY_STRING'])) {
$uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
}
else {
$uri = $_SERVER['SCRIPT_NAME'];
}
}
// Prevent multiple slashes to avoid cross site requests via the Form API.
$uri = '/' . ltrim($uri, '/');

return $uri;
}

/**
* Logs an exception.
*
* This is a wrapper function for watchdog() which automatically decodes an
* exception.
*
* @param $type
* The category to which this message belongs.
* @param $exception
* The exception that is going to be logged.
* @param $message
* The message to store in the log. If empty, a text that contains all useful
* information about the passed-in exception is used.
* @param $variables
* Array of variables to replace in the message on display. Defaults to the
* return value of _drupal_decode_exception().
* @param $severity
* The severity of the message, as per RFC 3164.
* @param $link
* A link to associate with the message.
*
* @see watchdog()
* @see _drupal_decode_exception()
*/
function watchdog_exception($type, Exception $exception, $message = NULL, $variables = array(), $severity = WATCHDOG_ERROR, $link = NULL) {

// Use a default value if $message is not set.
if (empty($message)) {
// The exception message is run through check_plain() by _drupal_decode_exception().
$message = '%type: !message in %function (line %line of %file).';
}
// $variables must be an array so that we can add the exception information.
if (!is_array($variables)) {
$variables = array();
}

require_once DRUPAL_ROOT . '/includes/errors.inc';
$variables += _drupal_decode_exception($exception);
watchdog($type, $message, $variables, $severity, $link);
}

/**
* Logs a system message.
*
* @param $type
* The category to which this message belongs. Can be any string, but the
* general practice is to use the name of the module calling watchdog().
* @param $message
* The message to store in the log. Keep $message translatable
* by not concatenating dynamic values into it! Variables in the
* message should be added by using placeholder strings alongside
* the variables argument to declare the value of the placeholders.
* See t() for documentation on how $message and $variables interact.
* @param $variables
* Array of variables to replace in the message on display or
* NULL if message is already translated or not possible to
* translate.
* @param $severity
* The severity of the message; one of the following values as defined in
* @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
* - WATCHDOG_EMERGENCY: Emergency, system is unusable.
* - WATCHDOG_ALERT: Alert, action must be taken immediately.
* - WATCHDOG_CRITICAL: Critical conditions.
* - WATCHDOG_ERROR: Error conditions.
* - WATCHDOG_WARNING: Warning conditions.
* - WATCHDOG_NOTICE: (default) Normal but significant conditions.
* - WATCHDOG_INFO: Informational messages.
* - WATCHDOG_DEBUG: Debug-level messages.
* @param $link
* A link to associate with the message.
*
* @see watchdog_severity_levels()
* @see hook_watchdog()
*/
function watchdog($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL) {
global $user, $base_root;

static $in_error_state = FALSE;

// It is possible that the error handling will itself trigger an error. In that case, we could
// end up in an infinite loop. To avoid that, we implement a simple static semaphore.
if (!$in_error_state && function_exists('module_implements')) {
$in_error_state = TRUE;

// The user object may not exist in all conditions, so 0 is substituted if needed.
$user_uid = isset($user->uid) ? $user->uid : 0;

// Prepare the fields to be logged
$log_entry = array(
'type' => $type,
'message' => $message,
'variables' => $variables,
'severity' => $severity,
'link' => $link,
'user' => $user,
'uid' => $user_uid,
'request_uri' => $base_root . request_uri(),
'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
'ip' => ip_address(),
// Request time isn't accurate for long processes, use time() instead.
'timestamp' => time(),
);

// Call the logging hooks to log/process the message
foreach (module_implements('watchdog') as $module) {
module_invoke($module, 'watchdog', $log_entry);
}

// It is critical that the semaphore is only cleared here, in the parent
// watchdog() call (not outside the loop), to prevent recursive execution.
$in_error_state = FALSE;
}
}

/**
* Sets a message to display to the user.
*
* Messages are stored in a session variable and displayed in page.tpl.php via
* the $messages theme variable.
*
* Example usage:
* @code
* drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
* @endcode
*
* @param string $message
* (optional) The translated message to be displayed to the user. For
* consistency with other messages, it should begin with a capital letter and
* end with a period.
* @param string $type
* (optional) The message's type. Defaults to 'status'. These values are
* supported:
* - 'status'
* - 'warning'
* - 'error'
* @param bool $repeat
* (optional) If this is FALSE and the message is already set, then the
* message won't be repeated. Defaults to TRUE.
*
* @return array|null
* A multidimensional array with keys corresponding to the set message types.
* The indexed array values of each contain the set messages for that type.
* Or, if there are no messages set, the function returns NULL.
*
* @see drupal_get_messages()
* @see theme_status_messages()
*/
function drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE) {

//by ugarte core_log messagess
if ($type == 'error') if (function_exists('core_log')) core_log('Drupal Set Message: '.$message, false, 'E');
////////////////////////////////////////////////////////

//by ugarte trace_add messagess
if ($type == 'error') if (function_exists('trace_add')) trace_add('Error: '.$message);
////////////////////////////////////////////////////////

if ($message || $message === '0' || $message === 0) {
if (!isset($_SESSION['messages'][$type])) {
$_SESSION['messages'][$type] = array();
}

if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
$_SESSION['messages'][$type][] = $message;
}

// Mark this page as being uncacheable.
drupal_page_is_cacheable(FALSE);
}

// Messages not set when DB connection fails.
return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
}

/**
* Returns all messages that have been set with drupal_set_message().
*
* @param string $type
* (optional) Limit the messages returned by type. Defaults to NULL, meaning
* all types. These values are supported:
* - NULL
* - 'status'
* - 'warning'
* - 'error'
* @param bool $clear_queue
* (optional) If this is TRUE, the queue will be cleared of messages of the
* type specified in the $type parameter. Otherwise the queue will be left
* intact. Defaults to TRUE.
*
* @return array
* A multidimensional array with keys corresponding to the set message types.
* The indexed array values of each contain the set messages for that type.
* The messages returned are limited to the type specified in the $type
* parameter. If there are no messages of the specified type, an empty array
* is returned.
*
* @see drupal_set_message()
* @see theme_status_messages()
*/
function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
if ($messages = drupal_set_message()) {
if ($type) {
if ($clear_queue) {
unset($_SESSION['messages'][$type]);
}
if (isset($messages[$type])) {
return array($type => $messages[$type]);
}
}
else {
if ($clear_queue) {
unset($_SESSION['messages']);
}
return $messages;
}
}
return array();
}

/**
* Gets the title of the current page.
*
* The title is displayed on the page and in the title bar.
*
* @return
* The current page's title.
*/
function drupal_get_title() {
$title = drupal_set_title();

// During a bootstrap, menu.inc is not included and thus we cannot provide a title.
if (!isset($title) && function_exists('menu_get_active_title')) {
$title = check_plain(menu_get_active_title());
}

return $title;
}

/**
* Sets the title of the current page.
*
* The title is displayed on the page and in the title bar.
*
* @param $title
* Optional string value to assign to the page title; or if set to NULL
* (default), leaves the current title unchanged.
* @param $output
* Optional flag - normally should be left as CHECK_PLAIN. Only set to
* PASS_THROUGH if you have already removed any possibly dangerous code
* from $title using a function like check_plain() or filter_xss(). With this
* flag the string will be passed through unchanged.
*
* @return
* The updated title of the current page.
*/
function drupal_set_title($title = NULL, $output = CHECK_PLAIN) {
$stored_title = &drupal_static(__FUNCTION__);

if (isset($title)) {
$stored_title = ($output == PASS_THROUGH) ? $title : check_plain($title);
}

return $stored_title;
}

/**
* Checks to see if an IP address has been blocked.
*
* Blocked IP addresses are stored in the database by default. However for
* performance reasons we allow an override in settings.php. This allows us
* to avoid querying the database at this critical stage of the bootstrap if
* an administrative interface for IP address blocking is not required.
*
* @param $ip
* IP address to check.
*
* @return bool
* TRUE if access is denied, FALSE if access is allowed.
*/
function drupal_is_denied($ip) {
// Because this function is called on every page request, we first check
// for an array of IP addresses in settings.php before querying the
// database.
$blocked_ips = variable_get('blocked_ips');
$denied = FALSE;
if (isset($blocked_ips) && is_array($blocked_ips)) {
$denied = in_array($ip, $blocked_ips);
}
// Only check if database.inc is loaded already. If
// $conf['page_cache_without_database'] = TRUE; is set in settings.php,
// then the database won't be loaded here so the IPs in the database
// won't be denied. However the user asked explicitly not to use the
// database and also in this case it's quite likely that the user relies
// on higher performance solutions like a firewall.
elseif (class_exists('Database', FALSE)) {
$denied = (bool)db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();
}
return $denied;
}

/**
* Handles denied users.
*
* @param $ip
* IP address to check. Prints a message and exits if access is denied.
*/
function drupal_block_denied($ip) {
// Deny access to blocked IP addresses - t() is not yet available.
if (drupal_is_denied($ip)) {
header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
print 'Sorry, ' . check_plain(ip_address()) . ' has been banned.';
exit();
}
}

/**
* Returns a URL-safe, base64 encoded string of highly randomized bytes (over the full 8-bit range).
*
* @param $byte_count
* The number of random bytes to fetch and base64 encode.
*
* @return string
* The base64 encoded result will have a length of up to 4 * $byte_count.
*/
function drupal_random_key($byte_count = 32) {
return drupal_base64_encode(drupal_random_bytes($byte_count));
}

/**
* Returns a URL-safe, base64 encoded version of the supplied string.
*
* @param $string
* The string to convert to base64.
*
* @return string
*/
function drupal_base64_encode($string) {
$data = base64_encode($string);
// Modify the output so it's safe to use in URLs.
return strtr($data, array('+' => '-', '/' => '_', '=' => ''));
}

/**
* Returns a string of highly randomized bytes (over the full 8-bit range).
*
* This function is better than simply calling mt_rand() or any other built-in
* PHP function because it can return a long string of bytes (compared to < 4
* bytes normally from mt_rand()) and uses the best available pseudo-random
* source.
*
* @param $count
* The number of characters (bytes) to return in the string.
*/
function drupal_random_bytes($count) {
// $random_state does not use drupal_static as it stores random bytes.
static $random_state, $bytes, $has_openssl;

$missing_bytes = $count - strlen($bytes);

if ($missing_bytes > 0) {
// PHP versions prior 5.3.4 experienced openssl_random_pseudo_bytes()
// locking on Windows and rendered it unusable.
if (!isset($has_openssl)) {
$has_openssl = version_compare(PHP_VERSION, '5.3.4', '>=') && function_exists('openssl_random_pseudo_bytes');
}

// openssl_random_pseudo_bytes() will find entropy in a system-dependent
// way.
if ($has_openssl) {
$bytes .= openssl_random_pseudo_bytes($missing_bytes);
}

// Else, read directly from /dev/urandom, which is available on many *nix
// systems and is considered cryptographically secure.
elseif ($fh = @fopen('/dev/urandom', 'rb')) {
// PHP only performs buffered reads, so in reality it will always read
// at least 4096 bytes. Thus, it costs nothing extra to read and store
// that much so as to speed any additional invocations.
$bytes .= fread($fh, max(4096, $missing_bytes));
fclose($fh);
}

// If we couldn't get enough entropy, this simple hash-based PRNG will
// generate a good set of pseudo-random bytes on any system.
// Note that it may be important that our $random_state is passed
// through hash() prior to being rolled into $output, that the two hash()
// invocations are different, and that the extra input into the first one -
// the microtime() - is prepended rather than appended. This is to avoid
// directly leaking $random_state via the $output stream, which could
// allow for trivial prediction of further "random" numbers.
if (strlen($bytes) < $count) {
// Initialize on the first call. The contents of $_SERVER includes a mix of
// user-specific and system information that varies a little with each page.
if (!isset($random_state)) {
$random_state = print_r($_SERVER, TRUE);
if (function_exists('getmypid')) {
// Further initialize with the somewhat random PHP process ID.
$random_state .= getmypid();
}
$bytes = '';
}

do {
$random_state = hash('sha256', microtime() . mt_rand() . $random_state);
$bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
}
while (strlen($bytes) < $count);
}
}
$output = substr($bytes, 0, $count);
$bytes = substr($bytes, $count);
return $output;
}

/**
* Calculates a base-64 encoded, URL-safe sha-256 hmac.
*
* @param string $data
* String to be validated with the hmac.
* @param string $key
* A secret string key.
*
* @return string
* A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and
* any = padding characters removed.
*/
function drupal_hmac_base64($data, $key) {
// Casting $data and $key to strings here is necessary to avoid empty string
// results of the hash function if they are not scalar values. As this
// function is used in security-critical contexts like token validation it is
// important that it never returns an empty string.
$hmac = base64_encode(hash_hmac('sha256', (string) $data, (string) $key, TRUE));
// Modify the hmac so it's safe to use in URLs.
return strtr($hmac, array('+' => '-', '/' => '_', '=' => ''));
}

/**
* Calculates a base-64 encoded, URL-safe sha-256 hash.
*
* @param $data
* String to be hashed.
*
* @return
* A base-64 encoded sha-256 hash, with + replaced with -, / with _ and
* any = padding characters removed.
*/
function drupal_hash_base64($data) {
$hash = base64_encode(hash('sha256', $data, TRUE));
// Modify the hash so it's safe to use in URLs.
return strtr($hash, array('+' => '-', '/' => '_', '=' => ''));
}

/**
* Merges multiple arrays, recursively, and returns the merged array.
*
* This function is similar to PHP's array_merge_recursive() function, but it
* handles non-array values differently. When merging values that are not both
* arrays, the latter value replaces the former rather than merging with it.
*
* Example:
* @code
* $link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => t('X'), 'class' => array('a', 'b')));
* $link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('c', 'd')));
*
* // This results in array('fragment' => array('x', 'y'), 'attributes' => array('title' => array(t('X'), t('Y')), 'class' => array('a', 'b', 'c', 'd'))).
* $incorrect = array_merge_recursive($link_options_1, $link_options_2);
*
* // This results in array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('a', 'b', 'c', 'd'))).
* $correct = drupal_array_merge_deep($link_options_1, $link_options_2);
* @endcode
*
* @param ...
* Arrays to merge.
*
* @return
* The merged array.
*
* @see drupal_array_merge_deep_array()
*/
function drupal_array_merge_deep() {
$args = func_get_args();
return drupal_array_merge_deep_array($args);
}

/**
* Merges multiple arrays, recursively, and returns the merged array.
*
* This function is equivalent to drupal_array_merge_deep(), except the
* input arrays are passed as a single array parameter rather than a variable
* parameter list.
*
* The following are equivalent:
* - drupal_array_merge_deep($a, $b);
* - drupal_array_merge_deep_array(array($a, $b));
*
* The following are also equivalent:
* - call_user_func_array('drupal_array_merge_deep', $arrays_to_merge);
* - drupal_array_merge_deep_array($arrays_to_merge);
*
* @see drupal_array_merge_deep()
*/
function drupal_array_merge_deep_array($arrays) {
$result = array();

foreach ($arrays as $array) {
foreach ($array as $key => $value) {
// Renumber integer keys as array_merge_recursive() does. Note that PHP
// automatically converts array keys that are integer strings (e.g., '1')
// to integers.
if (is_integer($key)) {
$result[] = $value;
}
// Recurse when both values are arrays.
elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
$result[$key] = drupal_array_merge_deep_array(array($result[$key], $value));
}
// Otherwise, use the latter value, overriding any previous value.
else {
$result[$key] = $value;
}
}
}

return $result;
}

/**
* Generates a default anonymous $user object.
*
* @return Object - the user object.
*/
function drupal_anonymous_user() {
$user = variable_get('drupal_anonymous_user_object', new stdClass);
$user->uid = 0;
$user->hostname = ip_address();
$user->roles = array();
$user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
$user->cache = 0;
return $user;
}

/**
* Ensures Drupal is bootstrapped to the specified phase.
*
* In order to bootstrap Drupal from another PHP script, you can use this code:
* @code
* define('DRUPAL_ROOT', '/path/to/drupal');
* require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
* drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
* @endcode
*
* @param int $phase
* A constant telling which phase to bootstrap to. When you bootstrap to a
* particular phase, all earlier phases are run automatically. Possible
* values:
* - DRUPAL_BOOTSTRAP_CONFIGURATION: Initializes configuration.
* - DRUPAL_BOOTSTRAP_PAGE_CACHE: Tries to serve a cached page.
* - DRUPAL_BOOTSTRAP_DATABASE: Initializes the database layer.
* - DRUPAL_BOOTSTRAP_VARIABLES: Initializes the variable system.
* - DRUPAL_BOOTSTRAP_SESSION: Initializes session handling.
* - DRUPAL_BOOTSTRAP_PAGE_HEADER: Sets up the page header.
* - DRUPAL_BOOTSTRAP_LANGUAGE: Finds out the language of the page.
* - DRUPAL_BOOTSTRAP_FULL: Fully loads Drupal. Validates and fixes input
* data.
* @param boolean $new_phase
* A boolean, set to FALSE if calling drupal_bootstrap from inside a
* function called from drupal_bootstrap (recursion).
*
* @return int
* The most recently completed phase.
*/
function drupal_bootstrap($phase = NULL, $new_phase = TRUE) {
// Not drupal_static(), because does not depend on any run-time information.
static $phases = array(
DRUPAL_BOOTSTRAP_CONFIGURATION,
DRUPAL_BOOTSTRAP_PAGE_CACHE,
DRUPAL_BOOTSTRAP_DATABASE,
DRUPAL_BOOTSTRAP_VARIABLES,
DRUPAL_BOOTSTRAP_SESSION,
DRUPAL_BOOTSTRAP_PAGE_HEADER,
DRUPAL_BOOTSTRAP_LANGUAGE,
DRUPAL_BOOTSTRAP_FULL,
);
// Not drupal_static(), because the only legitimate API to control this is to
// call drupal_bootstrap() with a new phase parameter.
static $final_phase;
// Not drupal_static(), because it's impossible to roll back to an earlier
// bootstrap state.
static $stored_phase = -1;

if (isset($phase)) {
// When not recursing, store the phase name so it's not forgotten while
// recursing but take care of not going backwards.
if ($new_phase && $phase >= $stored_phase) {
$final_phase = $phase;
}

// Call a phase if it has not been called before and is below the requested
// phase.
while ($phases && $phase > $stored_phase && $final_phase > $stored_phase) {
$current_phase = array_shift($phases);

// This function is re-entrant. Only update the completed phase when the
// current call actually resulted in a progress in the bootstrap process.
if ($current_phase > $stored_phase) {
$stored_phase = $current_phase;
}

switch ($current_phase) {
case DRUPAL_BOOTSTRAP_CONFIGURATION:
_drupal_bootstrap_configuration();
break;

case DRUPAL_BOOTSTRAP_PAGE_CACHE:
_drupal_bootstrap_page_cache();
break;

case DRUPAL_BOOTSTRAP_DATABASE:
_drupal_bootstrap_database();
break;

case DRUPAL_BOOTSTRAP_VARIABLES:
_drupal_bootstrap_variables();
break;

case DRUPAL_BOOTSTRAP_SESSION:
require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
drupal_session_initialize();
break;

case DRUPAL_BOOTSTRAP_PAGE_HEADER:
_drupal_bootstrap_page_header();
break;

case DRUPAL_BOOTSTRAP_LANGUAGE:
drupal_language_initialize();
break;

case DRUPAL_BOOTSTRAP_FULL:
require_once DRUPAL_ROOT . '/includes/common.inc';
_drupal_bootstrap_full();
break;
}
}
}
return $stored_phase;
}

/**
* Returns the time zone of the current user.
*/
function drupal_get_user_timezone() {
global $user;
if (variable_get('configurable_timezones', 1) && $user->uid && $user->timezone) {
return $user->timezone;
}
else {
// Ignore PHP strict notice if time zone has not yet been set in the php.ini
// configuration.
return variable_get('date_default_timezone', @date_default_timezone_get());
}
}

/**
* Gets a salt useful for hardening against SQL injection.
*
* @return
* A salt based on information in settings.php, not in the database.
*/
function drupal_get_hash_salt() {
global $drupal_hash_salt, $databases;
// If the $drupal_hash_salt variable is empty, a hash of the serialized
// database credentials is used as a fallback salt.
return empty($drupal_hash_salt) ? hash('sha256', serialize($databases)) : $drupal_hash_salt;
}

/**
* Provides custom PHP error handling.
*
* @param $error_level
* The level of the error raised.
* @param $message
* The error message.
* @param $filename
* The filename that the error was raised in.
* @param $line
* The line number the error was raised at.
* @param $context
* An array that points to the active symbol table at the point the error
* occurred.
*/
function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
require_once DRUPAL_ROOT . '/includes/errors.inc';
_drupal_error_handler_real($error_level, $message, $filename, $line, $context);
}

/**
* Provides custom PHP exception handling.
*
* Uncaught exceptions are those not enclosed in a try/catch block. They are
* always fatal: the execution of the script will stop as soon as the exception
* handler exits.
*
* @param $exception
* The exception object that was thrown.
*/
function _drupal_exception_handler($exception) {
require_once DRUPAL_ROOT . '/includes/errors.inc';

try {
// Log the message to the watchdog and return an error page to the user.
_drupal_log_error(_drupal_decode_exception($exception), TRUE);
}
catch (Exception $exception2) {
// Another uncaught exception was thrown while handling the first one.
// If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
if (error_displayable()) {
print '<h1>Additional uncaught exception thrown while handling exception.</h1>';
print '<h2>Original</h2><p>' . _drupal_render_exception_safe($exception) . '</p>';
print '<h2>Additional</h2><p>' . _drupal_render_exception_safe($exception2) . '</p><hr />';
}
}
}

/**
* Sets up the script environment and loads settings.php.
*/
function _drupal_bootstrap_configuration() {
// Set the Drupal custom error handler.
set_error_handler('_drupal_error_handler');
set_exception_handler('_drupal_exception_handler');

drupal_environment_initialize();
// Start a page timer:
timer_start('page');
// Initialize the configuration, including variables from settings.php.
drupal_settings_initialize();require_once DRUPAL_ROOT . '/includes/request-sanitizer.inc';DrupalRequestSanitizer::sanitize();
}

/**
* Attempts to serve a page from the cache.
*/
function _drupal_bootstrap_page_cache() {
global $user;

// Allow specifying special cache handlers in settings.php, like
// using memcached or files for storing cache information.
require_once DRUPAL_ROOT . '/includes/cache.inc';
foreach (variable_get('cache_backends', array()) as $include) {
require_once DRUPAL_ROOT . '/' . $include;
}
// Check for a cache mode force from settings.php.
if (variable_get('page_cache_without_database')) {
$cache_enabled = TRUE;
}
else {
drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE);
$cache_enabled = variable_get('cache');
}
drupal_block_denied(ip_address());
// If there is no session cookie and cache is enabled (or forced), try
// to serve a cached page.
if (!isset($_COOKIE[session_name()]) && $cache_enabled) {
// Make sure there is a user object because its timestamp will be
// checked, hook_boot might check for anonymous user etc.
$user = drupal_anonymous_user();
// Get the page from the cache.
$cache = drupal_page_get_cache();
// If there is a cached page, display it.
if (is_object($cache)) {
header('X-Drupal-Cache: HIT');
// Restore the metadata cached with the page.
$_GET['q'] = $cache->data['path'];
drupal_set_title($cache->data['title'], PASS_THROUGH);
date_default_timezone_set(drupal_get_user_timezone());
// If the skipping of the bootstrap hooks is not enforced, call
// hook_boot.
if (variable_get('page_cache_invoke_hooks', TRUE)) {
bootstrap_invoke_all('boot');
}
drupal_serve_page_from_cache($cache);
// If the skipping of the bootstrap hooks is not enforced, call
// hook_exit.
if (variable_get('page_cache_invoke_hooks', TRUE)) {
bootstrap_invoke_all('exit');
}
// We are done.
exit;
}
else {
header('X-Drupal-Cache: MISS');
}
}
}

/**
* Initializes the database system and registers autoload functions.
*/
function _drupal_bootstrap_database() {
// Redirect the user to the installation script if Drupal has not been
// installed yet (i.e., if no $databases array has been defined in the
// settings.php file) and we are not already installing.
if (empty($GLOBALS['databases']) && !drupal_installation_attempted()) {
include_once DRUPAL_ROOT . '/includes/install.inc';
install_goto('install.php');
}

// The user agent header is used to pass a database prefix in the request when
// running tests. However, for security reasons, it is imperative that we
// validate we ourselves made the request.
if ($test_prefix = drupal_valid_test_ua()) {
// Set the test run id for use in other parts of Drupal.
$test_info = &$GLOBALS['drupal_test_info'];
$test_info['test_run_id'] = $test_prefix;
$test_info['in_child_site'] = TRUE;

foreach ($GLOBALS['databases']['default'] as &$value) {
// Extract the current default database prefix.
if (!isset($value['prefix'])) {
$current_prefix = '';
}
elseif (is_array($value['prefix'])) {
$current_prefix = $value['prefix']['default'];
}
else {
$current_prefix = $value['prefix'];
}

// Remove the current database prefix and replace it by our own.
$value['prefix'] = array(
'default' => $current_prefix . $test_prefix,
);
}
}

// Initialize the database system. Note that the connection
// won't be initialized until it is actually requested.
require_once DRUPAL_ROOT . '/includes/database/database.inc';

// Register autoload functions so that we can access classes and interfaces.
// The database autoload routine comes first so that we can load the database
// system without hitting the database. That is especially important during
// the install or upgrade process.
spl_autoload_register('drupal_autoload_class');
spl_autoload_register('drupal_autoload_interface');
if (version_compare(PHP_VERSION, '5.4') >= 0) {
spl_autoload_register('drupal_autoload_trait');
}
}

/**
* Loads system variables and all enabled bootstrap modules.
*/
function _drupal_bootstrap_variables() {
global $conf;

// Initialize the lock system.
require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
lock_initialize();

// Load variables from the database, but do not overwrite variables set in settings.php.
$conf = variable_initialize(isset($conf) ? $conf : array());
// Load bootstrap modules.
require_once DRUPAL_ROOT . '/includes/module.inc';
module_load_all(TRUE);

// Sanitize the destination parameter (which is often used for redirects) to
// prevent open redirect attacks leading to other domains. Sanitize both
// $_GET['destination'] and $_REQUEST['destination'] to protect code that
// relies on either, but do not sanitize $_POST to avoid interfering with
// unrelated form submissions. The sanitization happens here because
// url_is_external() requires the variable system to be available.
if (isset($_GET['destination']) || isset($_REQUEST['destination'])) {
require_once DRUPAL_ROOT . '/includes/common.inc';
// If the destination is an external URL, remove it.
if (isset($_GET['destination']) && url_is_external($_GET['destination'])) {
unset($_GET['destination']);
unset($_REQUEST['destination']);
}

//by ugarte new patch

// Use the DrupalRequestSanitizer to ensure that the destination's query
// parameters are not dangerous.
if (isset($_GET['destination'])) {
DrupalRequestSanitizer::cleanDestination();
}


// If there's still something in $_REQUEST['destination'] that didn't come
// from $_GET, check it too.
if (isset($_REQUEST['destination']) && (!isset($_GET['destination']) || $_REQUEST['destination'] != $_GET['destination']) && url_is_external($_REQUEST['destination'])) {
unset($_REQUEST['destination']);
}
}
}

/**
* Invokes hook_boot(), initializes locking system, and sends HTTP headers.
*/
function _drupal_bootstrap_page_header() {
bootstrap_invoke_all('boot');

if (!drupal_is_cli()) {
ob_start();
drupal_page_header();
}
}

/**
* Returns the current bootstrap phase for this Drupal process.
*
* The current phase is the one most recently completed by drupal_bootstrap().
*
* @see drupal_bootstrap()
*/
function drupal_get_bootstrap_phase() {
return drupal_bootstrap(NULL, FALSE);
}

/**
* Returns the test prefix if this is an internal request from SimpleTest.
*
* @return
* Either the simpletest prefix (the string "simpletest" followed by any
* number of digits) or FALSE if the user agent does not contain a valid
* HMAC and timestamp.
*/
function drupal_valid_test_ua() {
// No reason to reset this.
static $test_prefix;

if (isset($test_prefix)) {
return $test_prefix;
}

if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/^(simpletest\d+);(.+);(.+);(.+)$/", $_SERVER['HTTP_USER_AGENT'], $matches)) {
list(, $prefix, $time, $salt, $hmac) = $matches;
$check_string = $prefix . ';' . $time . ';' . $salt;
// We use the salt from settings.php to make the HMAC key, since
// the database is not yet initialized and we can't access any Drupal variables.
// The file properties add more entropy not easily accessible to others.
$key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
$time_diff = REQUEST_TIME - $time;
// Since we are making a local request a 5 second time window is allowed,
// and the HMAC must match.
if ($time_diff >= 0 && $time_diff <= 5 && $hmac == drupal_hmac_base64($check_string, $key)) {
$test_prefix = $prefix;
return $test_prefix;
}
}

$test_prefix = FALSE;
return $test_prefix;
}

/**
* Generates a user agent string with a HMAC and timestamp for simpletest.
*/
function drupal_generate_test_ua($prefix) {
static $key;

if (!isset($key)) {
// We use the salt from settings.php to make the HMAC key, since
// the database is not yet initialized and we can't access any Drupal variables.
// The file properties add more entropy not easily accessible to others.
$key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
}
// Generate a moderately secure HMAC based on the database credentials.
$salt = uniqid('', TRUE);
$check_string = $prefix . ';' . time() . ';' . $salt;
return $check_string . ';' . drupal_hmac_base64($check_string, $key);
}

/**
* Enables use of the theme system without requiring database access.
*
* Loads and initializes the theme system for site installs, updates and when
* the site is in maintenance mode. This also applies when the database fails.
*
* @see _drupal_maintenance_theme()
*/
function drupal_maintenance_theme() {
require_once DRUPAL_ROOT . '/includes/theme.maintenance.inc';
_drupal_maintenance_theme();
}

/**
* Returns a simple 404 Not Found page.
*
* If fast 404 pages are enabled, and this is a matching page then print a
* simple 404 page and exit.
*
* This function is called from drupal_deliver_html_page() at the time when a
* a normal 404 page is generated, but it can also optionally be called directly
* from settings.php to prevent a Drupal bootstrap on these pages. See
* documentation in settings.php for the benefits and drawbacks of using this.
*
* Paths to dynamically-generated content, such as image styles, should also be
* accounted for in this function.
*/
function drupal_fast_404() {
$exclude_paths = variable_get('404_fast_paths_exclude', FALSE);
if ($exclude_paths && !preg_match($exclude_paths, $_GET['q'])) {
$fast_paths = variable_get('404_fast_paths', FALSE);
if ($fast_paths && preg_match($fast_paths, $_GET['q'])) {
drupal_add_http_header('Status', '404 Not Found');
$fast_404_html = variable_get('404_fast_html', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL "@path" was not found on this server.</p></body></html>');
// Replace @path in the variable with the page path.
print strtr($fast_404_html, array('@path' => check_plain(request_uri())));
exit;
}
}
}

/**
* Returns TRUE if a Drupal installation is currently being attempted.
*/
function drupal_installation_attempted() {
return defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'install';
}

/**
* Returns the name of the proper localization function.
*
* get_t() exists to support localization for code that might run during
* the installation phase, when some elements of the system might not have
* loaded.
*
* This would include implementations of hook_install(), which could run
* during the Drupal installation phase, and might also be run during
* non-installation time, such as while installing the module from the
* module administration page.
*
* Example usage:
* @code
* $t = get_t();
* $translated = $t('translate this');
* @endcode
*
* Use t() if your code will never run during the Drupal installation phase.
* Use st() if your code will only run during installation and never any other
* time. Use get_t() if your code could run in either circumstance.
*
* @see t()
* @see st()
* @ingroup sanitization
*/
function get_t() {
static $t;
// This is not converted to drupal_static because there is no point in
// resetting this as it can not change in the course of a request.
if (!isset($t)) {
$t = drupal_installation_attempted() ? 'st' : 't';
}
return $t;
}

/**
* Initializes all the defined language types.
*/
function drupal_language_initialize() {
$types = language_types();

// Ensure the language is correctly returned, even without multilanguage
// support. Also make sure we have a $language fallback, in case a language
// negotiation callback needs to do a full bootstrap.
// Useful for eg. XML/HTML 'lang' attributes.
$default = language_default();
foreach ($types as $type) {
$GLOBALS[$type] = $default;
}
if (drupal_multilingual()) {
include_once DRUPAL_ROOT . '/includes/language.inc';
foreach ($types as $type) {
$GLOBALS[$type] = language_initialize($type);
}
// Allow modules to react on language system initialization in multilingual
// environments.
bootstrap_invoke_all('language_init');
}
}

/**
* Returns a list of the built-in language types.
*
* @return
* An array of key-values pairs where the key is the language type and the
* value is its configurability.
*/
function drupal_language_types() {
return array(
LANGUAGE_TYPE_INTERFACE => TRUE,
LANGUAGE_TYPE_CONTENT => FALSE,
LANGUAGE_TYPE_URL => FALSE,
);
}

/**
* Returns TRUE if there is more than one language enabled.
*
* @return
* TRUE if more than one language is enabled.
*/
function drupal_multilingual() {
// The "language_count" variable stores the number of enabled languages to
// avoid unnecessarily querying the database when building the list of
// enabled languages on monolingual sites.
return variable_get('language_count', 1) > 1;
}

/**
* Returns an array of the available language types.
*
* @return
* An array of all language types where the keys of each are the language type
* name and its value is its configurability (TRUE/FALSE).
*/
function language_types() {
return array_keys(variable_get('language_types', drupal_language_types()));
}

/**
* Returns a list of installed languages, indexed by the specified key.
*
* @param $field
* (optional) The field to index the list with.
*
* @return
* An associative array, keyed on the values of $field.
* - If $field is 'weight' or 'enabled', the array is nested, with the outer
* array's values each being associative arrays with language codes as
* keys and language objects as values.
* - For all other values of $field, the array is only one level deep, and
* the array's values are language objects.
*/
function language_list($field = 'language') {
$languages = &drupal_static(__FUNCTION__);
// Init language list
if (!isset($languages)) {
if (drupal_multilingual() || module_exists('locale')) {
$languages['language'] = db_query('SELECT * FROM {languages} ORDER BY weight ASC, name ASC')->fetchAllAssoc('language');
// Users cannot uninstall the native English language. However, we allow
// it to be hidden from the installed languages. Therefore, at least one
// other language must be enabled then.
if (!$languages['language']['en']->enabled && !variable_get('language_native_enabled', TRUE)) {
unset($languages['language']['en']);
}
}
else {
// No locale module, so use the default language only.
$default = language_default();
$languages['language'][$default->language] = $default;
}
}

// Return the array indexed by the right field
if (!isset($languages[$field])) {
$languages[$field] = array();
foreach ($languages['language'] as $lang) {
// Some values should be collected into an array
if (in_array($field, array('enabled', 'weight'))) {
$languages[$field][$lang->$field][$lang->language] = $lang;
}
else {
$languages[$field][$lang->$field] = $lang;
}
}
}
return $languages[$field];
}

/**
* Returns the default language, as an object, or one of its properties.
*
* @param $property
* (optional) The property of the language object to return.
*
* @return
* Either the language object for the default language used on the site,
* or the property of that object named in the $property parameter.
*/
function language_default($property = NULL) {
$language = variable_get('language_default', (object) array('language' => 'en', 'name' => 'English', 'native' => 'English', 'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => ''));
return $property ? $language->$property : $language;
}

/**
* Returns the requested URL path of the page being viewed.
*
* Examples:
* - http://example.com/node/306 returns "node/306".
* - http://example.com/drupalfolder/node/306 returns "node/306" while
* base_path() returns "/drupalfolder/".
* - http://example.com/path/alias (which is a path alias for node/306) returns
* "path/alias" as opposed to the internal path.
* - http://example.com/index.php returns an empty string (meaning: front page).
* - http://example.com/index.php?page=1 returns an empty string.
*
* @return
* The requested Drupal URL path.
*
* @see current_path()
*/
function request_path() {
static $path;

if (isset($path)) {
return $path;
}

if (isset($_GET['q']) && is_string($_GET['q'])) {
// This is a request with a ?q=foo/bar query string. $_GET['q'] is
// overwritten in drupal_path_initialize(), but request_path() is called
// very early in the bootstrap process, so the original value is saved in
// $path and returned in later calls.
$path = $_GET['q'];
}
elseif (isset($_SERVER['REQUEST_URI'])) {
// This request is either a clean URL, or 'index.php', or nonsense.
// Extract the path from REQUEST_URI.
$request_path = strtok($_SERVER['REQUEST_URI'], '?');
$base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
// Unescape and strip $base_path prefix, leaving q without a leading slash.
$path = substr(urldecode($request_path), $base_path_len + 1);
// If the path equals the script filename, either because 'index.php' was
// explicitly provided in the URL, or because the server added it to
// $_SERVER['REQUEST_URI'] even when it wasn't provided in the URL (some
// versions of Microsoft IIS do this), the front page should be served.
if ($path == basename($_SERVER['PHP_SELF'])) {
$path = '';
}
}
else {
// This is the front page.
$path = '';
}

// Under certain conditions Apache's RewriteRule directive prepends the value
// assigned to $_GET['q'] with a slash. Moreover we can always have a trailing
// slash in place, hence we need to normalize $_GET['q'].
$path = trim($path, '/');

return $path;
}

/**
* Returns a component of the current Drupal path.
*
* When viewing a page at the path "admin/structure/types", for example, arg(0)
* returns "admin", arg(1) returns "structure", and arg(2) returns "types".
*
* Avoid use of this function where possible, as resulting code is hard to
* read. In menu callback functions, attempt to use named arguments. See the
* explanation in menu.inc for how to construct callbacks that take arguments.
* When attempting to use this function to load an element from the current
* path, e.g. loading the node on a node page, use menu_get_object() instead.
*
* @param $index
* The index of the component, where each component is separated by a '/'
* (forward-slash), and where the first component has an index of 0 (zero).
* @param $path
* A path to break into components. Defaults to the path of the current page.
*
* @return
* The component specified by $index, or NULL if the specified component was
* not found. If called without arguments, it returns an array containing all
* the components of the current path.
*/
function arg($index = NULL, $path = NULL) {
// Even though $arguments doesn't need to be resettable for any functional
// reasons (the result of explode() does not depend on any run-time
// information), it should be resettable anyway in case a module needs to
// free up the memory used by it.
// Use the advanced drupal_static() pattern, since this is called very often.
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
$drupal_static_fast['arguments'] = &drupal_static(__FUNCTION__);
}
$arguments = &$drupal_static_fast['arguments'];

if (!isset($path)) {
$path = $_GET['q'];
}
if (!isset($arguments[$path])) {
$arguments[$path] = explode('/', $path);
}
if (!isset($index)) {
return $arguments[$path];
}
if (isset($arguments[$path][$index])) {
return $arguments[$path][$index];
}
}

/**
* Returns the IP address of the client machine.
*
* If Drupal is behind a reverse proxy, we use the X-Forwarded-For header
* instead of $_SERVER['REMOTE_ADDR'], which would be the IP address of
* the proxy server, and not the client's. The actual header name can be
* configured by the reverse_proxy_header variable.
*
* @return
* IP address of client machine, adjusted for reverse proxy and/or cluster
* environments.
*/
function ip_address() {
$ip_address = &drupal_static(__FUNCTION__);

if (!isset($ip_address)) {
$ip_address = $_SERVER['REMOTE_ADDR'];

if (variable_get('reverse_proxy', 0)) {
$reverse_proxy_header = variable_get('reverse_proxy_header', 'HTTP_X_FORWARDED_FOR');
if (!empty($_SERVER[$reverse_proxy_header])) {
// If an array of known reverse proxy IPs is provided, then trust
// the XFF header if request really comes from one of them.
$reverse_proxy_addresses = variable_get('reverse_proxy_addresses', array());

// Turn XFF header into an array.
$forwarded = explode(',', $_SERVER[$reverse_proxy_header]);

// Trim the forwarded IPs; they may have been delimited by commas and spaces.
$forwarded = array_map('trim', $forwarded);

// Tack direct client IP onto end of forwarded array.
$forwarded[] = $ip_address;

// Eliminate all trusted IPs.
$untrusted = array_diff($forwarded, $reverse_proxy_addresses);

if (!empty($untrusted)) {
// The right-most IP is the most specific we can trust.
$ip_address = array_pop($untrusted);
}
else {
// All IP addresses in the forwarded array are configured proxy IPs
// (and thus trusted). We take the leftmost IP.
$ip_address = array_shift($forwarded);
}
}
}
}

return $ip_address;
}

/**
* @addtogroup schemaapi
* @{
*/

/**
* Gets the schema definition of a table, or the whole database schema.
*
* The returned schema will include any modifications made by any
* module that implements hook_schema_alter(). To get the schema without
* modifications, use drupal_get_schema_unprocessed().
*
*
* @param $table
* The name of the table. If not given, the schema of all tables is returned.
* @param $rebuild
* If true, the schema will be rebuilt instead of retrieved from the cache.
*/
function drupal_get_schema($table = NULL, $rebuild = FALSE) {
static $schema;

if ($rebuild || !isset($table)) {
$schema = drupal_get_complete_schema($rebuild);
}
elseif (!isset($schema)) {
$schema = new SchemaCache();
}

if (!isset($table)) {
return $schema;
}
if (isset($schema[$table])) {
return $schema[$table];
}
else {
return FALSE;
}
}

/**
* Extends DrupalCacheArray to allow for dynamic building of the schema cache.
*/
class SchemaCache extends DrupalCacheArray {

/**
* Constructs a SchemaCache object.
*/
public function __construct() {
// Cache by request method.
parent::__construct('schema:runtime:' . ($_SERVER['REQUEST_METHOD'] == 'GET'), 'cache');
}

/**
* Overrides DrupalCacheArray::resolveCacheMiss().
*/
protected function resolveCacheMiss($offset) {
$complete_schema = drupal_get_complete_schema();
$value = isset($complete_schema[$offset]) ? $complete_schema[$offset] : NULL;
$this->storage[$offset] = $value;
$this->persist($offset);
return $value;
}
}

/**
* Gets the whole database schema.
*
* The returned schema will include any modifications made by any
* module that implements hook_schema_alter().
*
* @param $rebuild
* If true, the schema will be rebuilt instead of retrieved from the cache.
*/
function drupal_get_complete_schema($rebuild = FALSE) {
static $schema = array();

if (empty($schema) || $rebuild) {
// Try to load the schema from cache.
if (!$rebuild && $cached = cache_get('schema')) {
$schema = $cached->data;
}
// Otherwise, rebuild the schema cache.
else {
$schema = array();
// Load the .install files to get hook_schema.
// On some databases this function may be called before bootstrap has
// been completed, so we force the functions we need to load just in case.
if (function_exists('module_load_all_includes')) {
// This function can be called very early in the bootstrap process, so
// we force the module_list() cache to be refreshed to ensure that it
// contains the complete list of modules before we go on to call
// module_load_all_includes().
module_list(TRUE);
module_load_all_includes('install');
}

require_once DRUPAL_ROOT . '/includes/common.inc';
// Invoke hook_schema for all modules.
foreach (module_implements('schema') as $module) {
// Cast the result of hook_schema() to an array, as a NULL return value
// would cause array_merge() to set the $schema variable to NULL as well.
// That would break modules which use $schema further down the line.
$current = (array) module_invoke($module, 'schema');
// Set 'module' and 'name' keys for each table, and remove descriptions,
// as they needlessly slow down cache_get() for every single request.
_drupal_schema_initialize($current, $module);
$schema = array_merge($schema, $current);
}

drupal_alter('schema', $schema);
// If the schema is empty, avoid saving it: some database engines require
// the schema to perform queries, and this could lead to infinite loops.
if (!empty($schema) && (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL)) {
cache_set('schema', $schema);
}
if ($rebuild) {
cache_clear_all('schema:', 'cache', TRUE);
}
}
}

return $schema;
}

/**
* @} End of "addtogroup schemaapi".
*/


/**
* @addtogroup registry
* @{
*/

/**
* Confirms that an interface is available.
*
* This function is rarely called directly. Instead, it is registered as an
* spl_autoload() handler, and PHP calls it for us when necessary.
*
* @param $interface
* The name of the interface to check or load.
*
* @return
* TRUE if the interface is currently available, FALSE otherwise.
*/
function drupal_autoload_interface($interface) {
return _registry_check_code('interface', $interface);
}

/**
* Confirms that a class is available.
*
* This function is rarely called directly. Instead, it is registered as an
* spl_autoload() handler, and PHP calls it for us when necessary.
*
* @param $class
* The name of the class to check or load.
*
* @return
* TRUE if the class is currently available, FALSE otherwise.
*/
function drupal_autoload_class($class) {
return _registry_check_code('class', $class);
}

/**
* Confirms that a trait is available.
*
* This function is rarely called directly. Instead, it is registered as an
* spl_autoload() handler, and PHP calls it for us when necessary.
*
* @param string $trait
* The name of the trait to check or load.
*
* @return bool
* TRUE if the trait is currently available, FALSE otherwise.
*/
function drupal_autoload_trait($trait) {
return _registry_check_code('trait', $trait);
}

/**
* Checks for a resource in the registry.
*
* @param $type
* The type of resource we are looking up, or one of the constants
* REGISTRY_RESET_LOOKUP_CACHE or REGISTRY_WRITE_LOOKUP_CACHE, which
* signal that we should reset or write the cache, respectively.
* @param $name
* The name of the resource, or NULL if either of the REGISTRY_* constants
* is passed in.
*
* @return
* TRUE if the resource was found, FALSE if not.
* NULL if either of the REGISTRY_* constants is passed in as $type.
*/
function _registry_check_code($type, $name = NULL) {
static $lookup_cache, $cache_update_needed;

if ($type == 'class' && class_exists($name) || $type == 'interface' && interface_exists($name) || $type == 'trait' && trait_exists($name)) {
return TRUE;
}

if (!isset($lookup_cache)) {
$lookup_cache = array();
if ($cache = cache_get('lookup_cache', 'cache_bootstrap')) {
$lookup_cache = $cache->data;
}
}

// When we rebuild the registry, we need to reset this cache so
// we don't keep lookups for resources that changed during the rebuild.
if ($type == REGISTRY_RESET_LOOKUP_CACHE) {
$cache_update_needed = TRUE;
$lookup_cache = NULL;
return;
}

// Called from drupal_page_footer, we write to permanent storage if there
// changes to the lookup cache for this request.
if ($type == REGISTRY_WRITE_LOOKUP_CACHE) {
if ($cache_update_needed) {
cache_set('lookup_cache', $lookup_cache, 'cache_bootstrap');
}
return;
}

// $type is either 'interface' or 'class', so we only need the first letter to
// keep the cache key unique.
$cache_key = $type[0] . $name;
if (isset($lookup_cache[$cache_key])) {
if ($lookup_cache[$cache_key]) {
include_once DRUPAL_ROOT . '/' . $lookup_cache[$cache_key];
}
return (bool) $lookup_cache[$cache_key];
}

// This function may get called when the default database is not active, but
// there is no reason we'd ever want to not use the default database for
// this query.
$file = Database::getConnection('default', 'default')
->select('registry', 'r', array('target' => 'default'))
->fields('r', array('filename'))
// Use LIKE here to make the query case-insensitive.
->condition('r.name', db_like($name), 'LIKE')
->condition('r.type', $type)
->execute()
->fetchField();

// Flag that we've run a lookup query and need to update the cache.
$cache_update_needed = TRUE;

// Misses are valuable information worth caching, so cache even if
// $file is FALSE.
$lookup_cache[$cache_key] = $file;

if ($file) {
include_once DRUPAL_ROOT . '/' . $file;
return TRUE;
}
else {
return FALSE;
}
}

/**
* Rescans all enabled modules and rebuilds the registry.
*
* Rescans all code in modules or includes directories, storing the location of
* each interface or class in the database.
*/
function registry_rebuild() {
system_rebuild_module_data();
registry_update();
}

/**
* Updates the registry based on the latest files listed in the database.
*
* This function should be used when system_rebuild_module_data() does not need
* to be called, because it is already known that the list of files in the
* {system} table matches those in the file system.
*
* @return
* TRUE if the registry was rebuilt, FALSE if another thread was rebuilding
* in parallel and the current thread just waited for completion.
*
* @see registry_rebuild()
*/
function registry_update() {
// install_system_module() calls module_enable() which calls into this
// function during initial system installation, so the lock system is neither
// loaded nor does its storage exist yet.
$in_installer = drupal_installation_attempted();
if (!$in_installer && !lock_acquire(__FUNCTION__)) {
// Another request got the lock, wait for it to finish.
lock_wait(__FUNCTION__);
return FALSE;
}

require_once DRUPAL_ROOT . '/includes/registry.inc';
_registry_update();

if (!$in_installer) {
lock_release(__FUNCTION__);
}
return TRUE;
}

/**
* @} End of "addtogroup registry".
*/

/**
* Provides central static variable storage.
*
* All functions requiring a static variable to persist or cache data within
* a single page request are encouraged to use this function unless it is
* absolutely certain that the static variable will not need to be reset during
* the page request. By centralizing static variable storage through this
* function, other functions can rely on a consistent API for resetting any
* other function's static variables.
*
* Example:
* @code
* function language_list($field = 'language') {
* $languages = &drupal_static(__FUNCTION__);
* if (!isset($languages)) {
* // If this function is being called for the first time after a reset,
* // query the database and execute any other code needed to retrieve
* // information about the supported languages.
* ...
* }
* if (!isset($languages[$field])) {
* // If this function is being called for the first time for a particular
* // index field, then execute code needed to index the information already
* // available in $languages by the desired field.
* ...
* }
* // Subsequent invocations of this function for a particular index field
* // skip the above two code blocks and quickly return the already indexed
* // information.
* return $languages[$field];
* }
* function locale_translate_overview_screen() {
* // When building the content for the translations overview page, make
* // sure to get completely fresh information about the supported languages.
* drupal_static_reset('language_list');
* ...
* }
* @endcode
*
* In a few cases, a function can have certainty that there is no legitimate
* use-case for resetting that function's static variable. This is rare,
* because when writing a function, it's hard to forecast all the situations in
* which it will be used. A guideline is that if a function's static variable
* does not depend on any information outside of the function that might change
* during a single page request, then it's ok to use the "static" keyword
* instead of the drupal_static() function.
*
* Example:
* @code
* function actions_do(...) {
* // $stack tracks the number of recursive calls.
* static $stack;
* $stack++;
* if ($stack > variable_get('actions_max_stack', 35)) {
* ...
* return;
* }
* ...
* $stack--;
* }
* @endcode
*
* In a few cases, a function needs a resettable static variable, but the
* function is called many times (100+) during a single page request, so
* every microsecond of execution time that can be removed from the function
* counts. These functions can use a more cumbersome, but faster variant of
* calling drupal_static(). It works by storing the reference returned by
* drupal_static() in the calling function's own static variable, thereby
* removing the need to call drupal_static() for each iteration of the function.
* Conceptually, it replaces:
* @code
* $foo = &drupal_static(__FUNCTION__);
* @endcode
* with:
* @code
* // Unfortunately, this does not work.
* static $foo = &drupal_static(__FUNCTION__);
* @endcode
* However, the above line of code does not work, because PHP only allows static
* variables to be initializied by literal values, and does not allow static
* variables to be assigned to references.
* - http://php.net/manual/language.variables.scope.php#language.variables.scope.static
* - http://php.net/manual/language.variables.scope.php#language.variables.scope.references
* The example below shows the syntax needed to work around both limitations.
* For benchmarks and more information, see http://drupal.org/node/619666.
*
* Example:
* @code
* function user_access($string, $account = NULL) {
* // Use the advanced drupal_static() pattern, since this is called very often.
* static $drupal_static_fast;
* if (!isset($drupal_static_fast)) {
* $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
* }
* $perm = &$drupal_static_fast['perm'];
* ...
* }
* @endcode
*
* @param $name
* Globally unique name for the variable. For a function with only one static,
* variable, the function name (e.g. via the PHP magic __FUNCTION__ constant)
* is recommended. For a function with multiple static variables add a
* distinguishing suffix to the function name for each one.
* @param $default_value
* Optional default value.
* @param $reset
* TRUE to reset one or all variables(s). This parameter is only used
* internally and should not be passed in; use drupal_static_reset() instead.
* (This function's return value should not be used when TRUE is passed in.)
*
* @return
* Returns a variable by reference.
*
* @see drupal_static_reset()
*/
function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
static $data = array(), $default = array();
// First check if dealing with a previously defined static variable.
if (isset($data[$name]) || array_key_exists($name, $data)) {
// Non-NULL $name and both $data[$name] and $default[$name] statics exist.
if ($reset) {
// Reset pre-existing static variable to its default value.
$data[$name] = $default[$name];
}
return $data[$name];
}
// Neither $data[$name] nor $default[$name] static variables exist.
if (isset($name)) {
if ($reset) {
// Reset was called before a default is set and yet a variable must be
// returned.
return $data;
}
// First call with new non-NULL $name. Initialize a new static variable.
$default[$name] = $data[$name] = $default_value;
return $data[$name];
}
// Reset all: ($name == NULL). This needs to be done one at a time so that
// references returned by earlier invocations of drupal_static() also get
// reset.
foreach ($default as $name => $value) {
$data[$name] = $value;
}
// As the function returns a reference, the return should always be a
// variable.
return $data;
}

/**
* Resets one or all centrally stored static variable(s).
*
* @param $name
* Name of the static variable to reset. Omit to reset all variables.
* Resetting all variables should only be used, for example, for running unit
* tests with a clean environment.
*/
function drupal_static_reset($name = NULL) {
drupal_static($name, NULL, TRUE);
}

/**
* Detects whether the current script is running in a command-line environment.
*/
function drupal_is_cli() {
return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
}

/**
* Formats text for emphasized display in a placeholder inside a sentence.
*
* Used automatically by format_string().
*
* @param $text
* The text to format (plain-text).
*
* @return
* The formatted text (html).
*/
function drupal_placeholder($text) {
return '<em class="placeholder">' . check_plain($text) . '</em>';
}

/**
* Registers a function for execution on shutdown.
*
* Wrapper for register_shutdown_function() that catches thrown exceptions to
* avoid "Exception thrown without a stack frame in Unknown".
*
* @param $callback
* The shutdown function to register.
* @param ...
* Additional arguments to pass to the shutdown function.
*
* @return
* Array of shutdown functions to be executed.
*
* @see register_shutdown_function()
* @ingroup php_wrappers
*/
function &drupal_register_shutdown_function($callback = NULL) {
// We cannot use drupal_static() here because the static cache is reset during
// batch processing, which breaks batch handling.
static $callbacks = array();

if (isset($callback)) {
// Only register the internal shutdown function once.
if (empty($callbacks)) {
register_shutdown_function('_drupal_shutdown_function');
}
$args = func_get_args();
array_shift($args);
// Save callback and arguments
$callbacks[] = array('callback' => $callback, 'arguments' => $args);
}
return $callbacks;
}

/**
* Executes registered shutdown functions.
*/
function _drupal_shutdown_function() {
$callbacks = &drupal_register_shutdown_function();

// Set the CWD to DRUPAL_ROOT as it is not guaranteed to be the same as it
// was in the normal context of execution.
chdir(DRUPAL_ROOT);

try {

/*
while (list($key, $callback) = each($callbacks)) {
call_user_func_array($callback['callback'], $callback['arguments']);
}
*/

// by ugarte the top code is old and was working ok
while ($callback = current($callbacks)) {
call_user_func_array($callback['callback'], $callback['arguments']);
next($callbacks);
}

}
catch (Exception $exception) {
// If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
require_once DRUPAL_ROOT . '/includes/errors.inc';
if (error_displayable()) {
print '<h1>Uncaught exception thrown in shutdown function.</h1>';
print '<p>' . _drupal_render_exception_safe($exception) . '</p><hr />';
}
}
}

/**
* Compares the memory required for an operation to the available memory.
*
* @param $required
* The memory required for the operation, expressed as a number of bytes with
* optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8bytes,
* 9mbytes).
* @param $memory_limit
* (optional) The memory limit for the operation, expressed as a number of
* bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G,
* 6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP
* memory_limit will be used. Defaults to NULL.
*
* @return
* TRUE if there is sufficient memory to allow the operation, or FALSE
* otherwise.
*/
function drupal_check_memory_limit($required, $memory_limit = NULL) {
if (!isset($memory_limit)) {
$memory_limit = ini_get('memory_limit');
}

// There is sufficient memory if:
// - No memory limit is set.
// - The memory limit is set to unlimited (-1).
// - The memory limit is greater than the memory required for the operation.
return ((!$memory_limit) || ($memory_limit == -1) || (parse_size($memory_limit) >= parse_size($required)));
}

/**
* Invalidates a PHP file from any active opcode caches.
*
* If the opcode cache does not support the invalidation of individual files,
* the entire cache will be flushed.
*
* @param string $filepath
* The absolute path of the PHP file to invalidate.
*/
function drupal_clear_opcode_cache($filepath) {
if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50300) {
// Below PHP 5.3, clearstatcache does not accept any function parameters.
clearstatcache();
}
else {
clearstatcache(TRUE, $filepath);
}

// Zend OPcache.
if (function_exists('opcache_invalidate')) {
opcache_invalidate($filepath, TRUE);
}
// APC.
if (function_exists('apc_delete_file')) {
// apc_delete_file() throws a PHP warning in case the specified file was
// not compiled yet.
// @see http://php.net/apc-delete-file
@apc_delete_file($filepath);
}
}



Folder [includes] file content different! File=(includes/common.inc)
<?php

/**
* @file
* Common functions that many Drupal modules will need to reference.
*
* The functions that are critical and need to be available even when serving
* a cached page are instead located in bootstrap.inc.
*/
/**
* @defgroup php_wrappers PHP wrapper functions
* @{
* Functions that are wrappers or custom implementations of PHP functions.
*
* Certain PHP functions should not be used in Drupal. Instead, Drupal's
* replacement functions should be used.
*
* For example, for improved or more secure UTF8-handling, or RFC-compliant
* handling of URLs in Drupal.
*
* For ease of use and memorizing, all these wrapper functions use the same name
* as the original PHP function, but prefixed with "drupal_". Beware, however,
* that not all wrapper functions support the same arguments as the original
* functions.
*
* You should always use these wrapper functions in your code.
*
* Wrong:
* @code
* $my_substring = substr($original_string, 0, 5);
* @endcode
*
* Correct:
* @code
* $my_substring = drupal_substr($original_string, 0, 5);
* @endcode
*
* @}
*/
/**
* Return status for saving which involved creating a new item.
*/
define('SAVED_NEW', 1);
/**
* Return status for saving which involved an update to an existing item.
*/
define('SAVED_UPDATED', 2);
/**
* Return status for saving which deleted an existing item.
*/
define('SAVED_DELETED', 3);

/**
* The default group for system CSS files added to the page.
*/
define('CSS_SYSTEM', -100);

/**
* The default group for module CSS files added to the page.
*/
define('CSS_DEFAULT', 0);

/**
* The default group for theme CSS files added to the page.
*/
define('CSS_THEME', 100);

/**
* The default group for JavaScript and jQuery libraries added to the page.
*/
define('JS_LIBRARY', -100);

/**
* The default group for module JavaScript code added to the page.
*/
define('JS_DEFAULT', 0);

/**
* The default group for theme JavaScript code added to the page.
*/
define('JS_THEME', 100);

/**
* Error code indicating that the request exceeded the specified timeout.
*
* @see drupal_http_request()
*/
define('HTTP_REQUEST_TIMEOUT', -1);

/**
* @defgroup block_caching Block Caching
* @{
* Constants that define each block's caching state.
*
* Modules specify how their blocks can be cached in their hook_block_info()
* implementations. Caching can be turned off (DRUPAL_NO_CACHE), managed by the
* module declaring the block (DRUPAL_CACHE_CUSTOM), or managed by the core
* Block module. If the Block module is managing the cache, you can specify that
* the block is the same for every page and user (DRUPAL_CACHE_GLOBAL), or that
* it can change depending on the page (DRUPAL_CACHE_PER_PAGE) or by user
* (DRUPAL_CACHE_PER_ROLE or DRUPAL_CACHE_PER_USER). Page and user settings can
* be combined with a bitwise-binary or operator; for example,
* DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE means that the block can change
* depending on the user role or page it is on.
*
* The block cache is cleared in cache_clear_all(), and uses the same clearing
* policy than page cache (node, comment, user, taxonomy added or updated...).
* Blocks requiring more fine-grained clearing might consider disabling the
* built-in block cache (DRUPAL_NO_CACHE) and roll their own.
*
* Note that user 1 is excluded from block caching.
*/
/**
* The block should not get cached.
*
* This setting should be used:
* - For simple blocks (notably those that do not perform any db query), where
* querying the db cache would be more expensive than directly generating the
* content.
* - For blocks that change too frequently.
*/
define('DRUPAL_NO_CACHE', -1);

/**
* The block is handling its own caching in its hook_block_view().
*
* This setting is useful when time based expiration is needed or a site uses a
* node access which invalidates standard block cache.
*/
define('DRUPAL_CACHE_CUSTOM', -2);

/**
* The block or element can change depending on the user's roles.
*
* This is the default setting for blocks, used when the block does not specify
* anything.
*/
define('DRUPAL_CACHE_PER_ROLE', 0x0001);

/**
* The block or element can change depending on the user.
*
* This setting can be resource-consuming for sites with large number of users,
* and thus should only be used when DRUPAL_CACHE_PER_ROLE is not sufficient.
*/
define('DRUPAL_CACHE_PER_USER', 0x0002);

/**
* The block or element can change depending on the page being viewed.
*/
define('DRUPAL_CACHE_PER_PAGE', 0x0004);

/**
* The block or element is the same for every user and page that it is visible.
*/
define('DRUPAL_CACHE_GLOBAL', 0x0008);

/**
* @} End of "defgroup block_caching".
*/

/**
* Adds content to a specified region.
*
* @param $region
* Page region the content is added to.
* @param $data
* Content to be added.
*/
function drupal_add_region_content($region = NULL, $data = NULL) {
static $content = array();

if (isset($region) && isset($data)) {
$content[$region][] = $data;
}
return $content;
}

/**
* Gets assigned content for a given region.
*
* @param $region
* A specified region to fetch content for. If NULL, all regions will be
* returned.
* @param $delimiter
* Content to be inserted between imploded array elements.
*/
function drupal_get_region_content($region = NULL, $delimiter = ' ') {
$content = drupal_add_region_content();
if (isset($region)) {
if (isset($content[$region]) && is_array($content[$region])) {
return implode($delimiter, $content[$region]);
}
} else {
foreach (array_keys($content) as $region) {
if (is_array($content[$region])) {
$content[$region] = implode($delimiter, $content[$region]);
}
}
return $content;
}
}

/**
* Gets the name of the currently active installation profile.
*
* When this function is called during Drupal's initial installation process,
* the name of the profile that's about to be installed is stored in the global
* installation state. At all other times, the standard Drupal systems variable
* table contains the name of the current profile, and we can call
* variable_get() to determine what one is active.
*
* @return $profile
* The name of the installation profile.
*/
function drupal_get_profile() {
global $install_state;

if (isset($install_state['parameters']['profile'])) {
$profile = $install_state['parameters']['profile'];
} else {
$profile = variable_get('install_profile', 'standard');
}

return $profile;
}

/**
* Sets the breadcrumb trail for the current page.
*
* @param $breadcrumb
* Array of links, starting with "home" and proceeding up to but not including
* the current page.
*/
function drupal_set_breadcrumb($breadcrumb = NULL) {
$stored_breadcrumb = &drupal_static(__FUNCTION__);

if (isset($breadcrumb)) {
$stored_breadcrumb = $breadcrumb;
}
return $stored_breadcrumb;
}

/**
* Gets the breadcrumb trail for the current page.
*/
function drupal_get_breadcrumb() {
$breadcrumb = drupal_set_breadcrumb();

if (!isset($breadcrumb)) {
$breadcrumb = menu_get_active_breadcrumb();
}

return $breadcrumb;
}

/**
* Returns a string containing RDF namespace declarations for use in XML and
* XHTML output.
*/
function drupal_get_rdf_namespaces() {
$xml_rdf_namespaces = array();

// Serializes the RDF namespaces in XML namespace syntax.
if (function_exists('rdf_get_namespaces')) {
foreach (rdf_get_namespaces() as $prefix => $uri) {
$xml_rdf_namespaces[] = 'xmlns:' . $prefix . '="' . $uri . '"';
}
}
return count($xml_rdf_namespaces) ? "\n " . implode("\n ", $xml_rdf_namespaces) : '';
}

/**
* Adds output to the HEAD tag of the HTML page.
*
* This function can be called as long as the headers aren't sent. Pass no
* arguments (or NULL for both) to retrieve the currently stored elements.
*
* @param $data
* A renderable array. If the '#type' key is not set then 'html_tag' will be
* added as the default '#type'.
* @param $key
* A unique string key to allow implementations of hook_html_head_alter() to
* identify the element in $data. Required if $data is not NULL.
*
* @return
* An array of all stored HEAD elements.
*
* @see theme_html_tag()
*/
function drupal_add_html_head($data = NULL, $key = NULL) {
$stored_head = &drupal_static(__FUNCTION__);

if (!isset($stored_head)) {
// Make sure the defaults, including Content-Type, come first.
$stored_head = _drupal_default_html_head();
}

if (isset($data) && isset($key)) {
if (!isset($data['#type'])) {
$data['#type'] = 'html_tag';
}
$stored_head[$key] = $data;
}
return $stored_head;
}

/**
* Returns elements that are always displayed in the HEAD tag of the HTML page.
*/
function _drupal_default_html_head() {
// Add default elements. Make sure the Content-Type comes first because the
// IE browser may be vulnerable to XSS via encoding attacks from any content
// that comes before this META tag, such as a TITLE tag.
$elements['system_meta_content_type'] = array(
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => array(
'http-equiv' => 'Content-Type',
'content' => 'text/html; charset=utf-8',
),
// Security: This always has to be output first.
'#weight' => -1000,
);
// Show Drupal and the major version number in the META GENERATOR tag.
// Get the major version.
list($version, ) = explode('.', VERSION);
$elements['system_meta_generator'] = array(
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => array(
'name' => 'Generator',
'content' => 'Drupal ' . $version . ' (http://drupal.org)',
),
);
// Also send the generator in the HTTP header.
$elements['system_meta_generator']['#attached']['drupal_add_http_header'][] = array('X-Generator', $elements['system_meta_generator']['#attributes']['content']);
return $elements;
}

/**
* Retrieves output to be displayed in the HEAD tag of the HTML page.
*/
function drupal_get_html_head() {
$elements = drupal_add_html_head();
drupal_alter('html_head', $elements);
return drupal_render($elements);
}

/**
* Adds a feed URL for the current page.
*
* This function can be called as long the HTML header hasn't been sent.
*
* @param $url
* An internal system path or a fully qualified external URL of the feed.
* @param $title
* The title of the feed.
*/
function drupal_add_feed($url = NULL, $title = '') {
$stored_feed_links = &drupal_static(__FUNCTION__, array());

if (isset($url)) {
$stored_feed_links[$url] = theme('feed_icon', array('url' => $url, 'title' => $title));

drupal_add_html_head_link(array(
'rel' => 'alternate',
'type' => 'application/rss+xml',
'title' => $title,
// Force the URL to be absolute, for consistency with other <link> tags
// output by Drupal.
'href' => url($url, array('absolute' => TRUE)),
));
}
return $stored_feed_links;
}

/**
* Gets the feed URLs for the current page.
*
* @param $delimiter
* A delimiter to split feeds by.
*/
function drupal_get_feeds($delimiter = "\n") {
$feeds = drupal_add_feed();
return implode($feeds, $delimiter);
}

/**
* @defgroup http_handling HTTP handling
* @{
* Functions to properly handle HTTP responses.
*/

/**
* Processes a URL query parameter array to remove unwanted elements.
*
* @param $query
* (optional) An array to be processed. Defaults to $_GET.
* @param $exclude
* (optional) A list of $query array keys to remove. Use "parent[child]" to
* exclude nested items. Defaults to array('q').
* @param $parent
* Internal use only. Used to build the $query array key for nested items.
*
* @return
* An array containing query parameters, which can be used for url().
*/
function drupal_get_query_parameters(array $query = NULL, array $exclude = array('q'), $parent = '') {
// Set defaults, if none given.
if (!isset($query)) {
$query = $_GET;
}
// If $exclude is empty, there is nothing to filter.
if (empty($exclude)) {
return $query;
} elseif (!$parent) {
$exclude = array_flip($exclude);
}

$params = array();
foreach ($query as $key => $value) {
$string_key = ($parent ? $parent . '[' . $key . ']' : $key);
if (isset($exclude[$string_key])) {
continue;
}

if (is_array($value)) {
$params[$key] = drupal_get_query_parameters($value, $exclude, $string_key);
} else {
$params[$key] = $value;
}
}

return $params;
}

/**
* Splits a URL-encoded query string into an array.
*
* @param $query
* The query string to split.
*
* @return
* An array of URL decoded couples $param_name => $value.
*/
function drupal_get_query_array($query) {
$result = array();
if (!empty($query)) {
foreach (explode('&', $query) as $param) {
$param = explode('=', $param, 2);
$result[$param[0]] = isset($param[1]) ? rawurldecode($param[1]) : '';
}
}
return $result;
}

/**
* Parses an array into a valid, rawurlencoded query string.
*
* This differs from http_build_query() as we need to rawurlencode() (instead of
* urlencode()) all query parameters.
*
* @param $query
* The query parameter array to be processed, e.g. $_GET.
* @param $parent
* Internal use only. Used to build the $query array key for nested items.
*
* @return
* A rawurlencoded string which can be used as or appended to the URL query
* string.
*
* @see drupal_get_query_parameters()
* @ingroup php_wrappers
*/
function drupal_http_build_query(array $query, $parent = '') {
$params = array();

foreach ($query as $key => $value) {
$key = $parent ? $parent . rawurlencode('[' . $key . ']') : rawurlencode($key);

// Recurse into children.
if (is_array($value)) {
$params[] = drupal_http_build_query($value, $key);
}
// If a query parameter value is NULL, only append its key.
elseif (!isset($value)) {
$params[] = $key;
} else {
// For better readability of paths in query strings, we decode slashes.
$params[] = $key . '=' . str_replace('%2F', '/', rawurlencode($value));
}
}

return implode('&', $params);
}

/**
* Prepares a 'destination' URL query parameter for use with drupal_goto().
*
* Used to direct the user back to the referring page after completing a form.
* By default the current URL is returned. If a destination exists in the
* previous request, that destination is returned. As such, a destination can
* persist across multiple pages.
*
* @return
* An associative array containing the key:
* - destination: The path provided via the destination query string or, if
* not available, the current path.
*
* @see current_path()
* @see drupal_goto()
*/
function drupal_get_destination() {
$destination = &drupal_static(__FUNCTION__);

if (isset($destination)) {
return $destination;
}

if (isset($_GET['destination'])) {
$destination = array('destination' => $_GET['destination']);
} else {
$path = $_GET['q'];
$query = drupal_http_build_query(drupal_get_query_parameters());
if ($query != '') {
$path .= '?' . $query;
}
$destination = array('destination' => $path);
}
return $destination;
}

/**
* Parses a URL string into its path, query, and fragment components.
*
* This function splits both internal paths like @code node?b=c#d @endcode and
* external URLs like @code https://example.com/a?b=c#d @endcode into their
* component parts. See
* @link http://tools.ietf.org/html/rfc3986#section-3 RFC 3986 @endlink for an
* explanation of what the component parts are.
*
* Note that, unlike the RFC, when passed an external URL, this function
* groups the scheme, authority, and path together into the path component.
*
* @param string $url
* The internal path or external URL string to parse.
*
* @return array
* An associative array containing:
* - path: The path component of $url. If $url is an external URL, this
* includes the scheme, authority, and path.
* - query: An array of query parameters from $url, if they exist.
* - fragment: The fragment component from $url, if it exists.
*
* @see drupal_goto()
* @see l()
* @see url()
* @see http://tools.ietf.org/html/rfc3986
*
* @ingroup php_wrappers
*/
function drupal_parse_url($url) {
$options = array(
'path' => NULL,
'query' => array(),
'fragment' => '',
);

// External URLs: not using parse_url() here, so we do not have to rebuild
// the scheme, host, and path without having any use for it.
if (strpos($url, '://') !== FALSE) {
// Split off everything before the query string into 'path'.
$parts = explode('?', $url);
$options['path'] = $parts[0];
// If there is a query string, transform it into keyed query parameters.
if (isset($parts[1])) {
$query_parts = explode('#', $parts[1]);
parse_str($query_parts[0], $options['query']);
// Take over the fragment, if there is any.
if (isset($query_parts[1])) {
$options['fragment'] = $query_parts[1];
}
}
}
// Internal URLs.
else {
// parse_url() does not support relative URLs, so make it absolute. E.g. the
// relative URL "foo/bar:1" isn't properly parsed.
$parts = parse_url('http://example.com/' . $url);
// Strip the leading slash that was just added.
$options['path'] = substr($parts['path'], 1);
if (isset($parts['query'])) {
parse_str($parts['query'], $options['query']);
}
if (isset($parts['fragment'])) {
$options['fragment'] = $parts['fragment'];
}
}
// The 'q' parameter contains the path of the current page if clean URLs are
// disabled. It overrides the 'path' of the URL when present, even if clean
// URLs are enabled, due to how Apache rewriting rules work.
#if (isset($options['query']['q'])) {
// by ugarte patch just the if condition before was the line on top
if (isset($options['query']['q']) && is_string($options['query']['q'])) {
$options['path'] = $options['query']['q'];
unset($options['query']['q']);
}

return $options;
}

/**
* Encodes a Drupal path for use in a URL.
*
* For aesthetic reasons slashes are not escaped.
*
* Note that url() takes care of calling this function, so a path passed to that
* function should not be encoded in advance.
*
* @param $path
* The Drupal path to encode.
*/
function drupal_encode_path($path) {
return str_replace('%2F', '/', rawurlencode($path));
}

/**
* Sends the user to a different page.
*
* This issues an on-site HTTP redirect. The function makes sure the redirected
* URL is formatted correctly.
*
* Usually the redirected URL is constructed from this function's input
* parameters. However you may override that behavior by setting a
* destination in either the $_REQUEST-array (i.e. by using
* the query string of an URI) This is used to direct the user back to
* the proper page after completing a form. For example, after editing
* a post on the 'admin/content'-page or after having logged on using the
* 'user login'-block in a sidebar. The function drupal_get_destination()
* can be used to help set the destination URL.
*
* Drupal will ensure that messages set by drupal_set_message() and other
* session data are written to the database before the user is redirected.
*
* This function ends the request; use it instead of a return in your menu
* callback.
*
* @param $path
* (optional) A Drupal path or a full URL, which will be passed to url() to
* compute the redirect for the URL.
* @param $options
* (optional) An associative array of additional URL options to pass to url().
* @param $http_response_code
* (optional) The HTTP status code to use for the redirection, defaults to
* 302. The valid values for 3xx redirection status codes are defined in
* @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3 RFC 2616 @endlink
* and the
* @link http://tools.ietf.org/html/draft-reschke-http-status-308-07 draft for the new HTTP status codes: @endlink
* - 301: Moved Permanently (the recommended value for most redirects).
* - 302: Found (default in Drupal and PHP, sometimes used for spamming search
* engines).
* - 303: See Other.
* - 304: Not Modified.
* - 305: Use Proxy.
* - 307: Temporary Redirect.
*
* @see drupal_get_destination()
* @see url()
*/
function drupal_goto($path = '', array $options = array(), $http_response_code = 302) {
// A destination in $_GET always overrides the function arguments.
// We do not allow absolute URLs to be passed via $_GET, as this can be an attack vector.
if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
$destination = drupal_parse_url($_GET['destination']);
$path = $destination['path'];
$options['query'] = $destination['query'];
$options['fragment'] = $destination['fragment'];
}

// In some cases modules call drupal_goto(current_path()). We need to ensure
// that such a redirect is not to an external URL.
if ($path === current_path() && empty($options['external']) && url_is_external($path)) {
// Force url() to generate a non-external URL.
$options['external'] = FALSE;
}

drupal_alter('drupal_goto', $path, $options, $http_response_code);

// The 'Location' HTTP header must be absolute.
$options['absolute'] = TRUE;

$url = url($path, $options);

header('Location: ' . $url, TRUE, $http_response_code);

// The "Location" header sends a redirect status code to the HTTP daemon. In
// some cases this can be wrong, so we make sure none of the code below the
// drupal_goto() call gets executed upon redirection.
drupal_exit($url);
}

/**
* Delivers a "site is under maintenance" message to the browser.
*
* Page callback functions wanting to report a "site offline" message should
* return MENU_SITE_OFFLINE instead of calling drupal_site_offline(). However,
* functions that are invoked in contexts where that return value might not
* bubble up to menu_execute_active_handler() should call drupal_site_offline().
*/
function drupal_site_offline() {
drupal_deliver_page(MENU_SITE_OFFLINE);
}

/**
* Delivers a "page not found" error to the browser.
*
* Page callback functions wanting to report a "page not found" message should
* return MENU_NOT_FOUND instead of calling drupal_not_found(). However,
* functions that are invoked in contexts where that return value might not
* bubble up to menu_execute_active_handler() should call drupal_not_found().
*/
function drupal_not_found() {
core_log('Page Not Found.', false, 'E');
drupal_deliver_page(MENU_NOT_FOUND);
}

/**
* Delivers an "access denied" error to the browser.
*
* Page callback functions wanting to report an "access denied" message should
* return MENU_ACCESS_DENIED instead of calling drupal_access_denied(). However,
* functions that are invoked in contexts where that return value might not
* bubble up to menu_execute_active_handler() should call
* drupal_access_denied().
*/
function drupal_access_denied() {
core_log('Access Denied.', false, 'E');
drupal_deliver_page(MENU_ACCESS_DENIED);
}

/**
* Performs an HTTP request.
*
* This is a flexible and powerful HTTP client implementation. Correctly
* handles GET, POST, PUT or any other HTTP requests. Handles redirects.
*
* @param $url
* A string containing a fully qualified URI.
* @param array $options
* (optional) An array that can have one or more of the following elements:
* - headers: An array containing request headers to send as name/value pairs.
* - method: A string containing the request method. Defaults to 'GET'.
* - data: A string containing the request body, formatted as
* 'param=value&param=value&...'; to generate this, use http_build_query().
* Defaults to NULL.
* - max_redirects: An integer representing how many times a redirect
* may be followed. Defaults to 3.
* - timeout: A float representing the maximum number of seconds the function
* call may take. The default is 30 seconds. If a timeout occurs, the error
* code is set to the HTTP_REQUEST_TIMEOUT constant.
* - context: A context resource created with stream_context_create().
*
* @return object
* An object that can have one or more of the following components:
* - request: A string containing the request body that was sent.
* - code: An integer containing the response status code, or the error code
* if an error occurred.
* - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
* - status_message: The status message from the response, if a response was
* received.
* - redirect_code: If redirected, an integer containing the initial response
* status code.
* - redirect_url: If redirected, a string containing the URL of the redirect
* target.
* - error: If an error occurred, the error message. Otherwise not set.
* - headers: An array containing the response headers as name/value pairs.
* HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
* easy access the array keys are returned in lower case.
* - data: A string containing the response body that was received.
*
* @see http_build_query()
*/
function drupal_http_request($url, array $options = array()) {
// Allow an alternate HTTP client library to replace Drupal's default
// implementation.
$override_function = variable_get('drupal_http_request_function', FALSE);
if (!empty($override_function) && function_exists($override_function)) {
return $override_function($url, $options);
}

$result = new stdClass();

// Parse the URL and make sure we can handle the schema.
$uri = @parse_url($url);

if ($uri == FALSE) {
$result->error = 'unable to parse URL';
$result->code = -1001;
return $result;
}

if (!isset($uri['scheme'])) {
$result->error = 'missing schema';
$result->code = -1002;
return $result;
}

timer_start(__FUNCTION__);

// Merge the default options.
$options += array(
'headers' => array(),
'method' => 'GET',
'data' => NULL,
'max_redirects' => 3,
'timeout' => 30.0,
'context' => NULL,
);

// Merge the default headers.
$options['headers'] += array(
'User-Agent' => 'Drupal (+http://drupal.org/)',
);

// stream_socket_client() requires timeout to be a float.
$options['timeout'] = (float) $options['timeout'];

// Use a proxy if one is defined and the host is not on the excluded list.
$proxy_server = variable_get('proxy_server', '');
if ($proxy_server && _drupal_http_use_proxy($uri['host'])) {
// Set the scheme so we open a socket to the proxy server.
$uri['scheme'] = 'proxy';
// Set the path to be the full URL.
$uri['path'] = $url;
// Since the URL is passed as the path, we won't use the parsed query.
unset($uri['query']);

// Add in username and password to Proxy-Authorization header if needed.
if ($proxy_username = variable_get('proxy_username', '')) {
$proxy_password = variable_get('proxy_password', '');
$options['headers']['Proxy-Authorization'] = 'Basic ' . base64_encode($proxy_username . (!empty($proxy_password) ? ":" . $proxy_password : ''));
}
// Some proxies reject requests with any User-Agent headers, while others
// require a specific one.
$proxy_user_agent = variable_get('proxy_user_agent', '');
// The default value matches neither condition.
if ($proxy_user_agent === NULL) {
unset($options['headers']['User-Agent']);
} elseif ($proxy_user_agent) {
$options['headers']['User-Agent'] = $proxy_user_agent;
}
}

switch ($uri['scheme']) {
case 'proxy':
// Make the socket connection to a proxy server.
$socket = 'tcp://' . $proxy_server . ':' . variable_get('proxy_port', 8080);
// The Host header still needs to match the real request.
$options['headers']['Host'] = $uri['host'];
$options['headers']['Host'] .= isset($uri['port']) && $uri['port'] != 80 ? ':' . $uri['port'] : '';
break;

case 'http':
case 'feed':
$port = isset($uri['port']) ? $uri['port'] : 80;
$socket = 'tcp://' . $uri['host'] . ':' . $port;
// RFC 2616: "non-standard ports MUST, default ports MAY be included".
// We don't add the standard port to prevent from breaking rewrite rules
// checking the host that do not take into account the port number.
$options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
break;

case 'https':
// Note: Only works when PHP is compiled with OpenSSL support.
$port = isset($uri['port']) ? $uri['port'] : 443;
$socket = 'ssl://' . $uri['host'] . ':' . $port;
$options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
break;

default:
$result->error = 'invalid schema ' . $uri['scheme'];
$result->code = -1003;
return $result;
}

if (empty($options['context'])) {
$fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
} else {
// Create a stream with context. Allows verification of a SSL certificate.
$fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
}

// Make sure the socket opened properly.
if (!$fp) {
// When a network error occurs, we use a negative number so it does not
// clash with the HTTP status codes.
$result->code = -$errno;
$result->error = trim($errstr) ? trim($errstr) : t('Error opening socket @socket', array('@socket' => $socket));

// Mark that this request failed. This will trigger a check of the web
// server's ability to make outgoing HTTP requests the next time that
// requirements checking is performed.
// See system_requirements().
variable_set('drupal_http_request_fails', TRUE);

return $result;
}

// Construct the path to act on.
$path = isset($uri['path']) ? $uri['path'] : '/';
if (isset($uri['query'])) {
$path .= '?' . $uri['query'];
}

// Only add Content-Length if we actually have any content or if it is a POST
// or PUT request. Some non-standard servers get confused by Content-Length in
// at least HEAD/GET requests, and Squid always requires Content-Length in
// POST/PUT requests.
$content_length = strlen($options['data']);
if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
$options['headers']['Content-Length'] = $content_length;
}

// If the server URL has a user then attempt to use basic authentication.
if (isset($uri['user'])) {
$options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
}

// If the database prefix is being used by SimpleTest to run the tests in a copied
// database then set the user-agent header to the database prefix so that any
// calls to other Drupal pages will run the SimpleTest prefixed database. The
// user-agent is used to ensure that multiple testing sessions running at the
// same time won't interfere with each other as they would if the database
// prefix were stored statically in a file or database variable.
$test_info = &$GLOBALS['drupal_test_info'];
if (!empty($test_info['test_run_id'])) {
$options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
}

$request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
foreach ($options['headers'] as $name => $value) {
$request .= $name . ': ' . trim($value) . "\r\n";
}
$request .= "\r\n" . $options['data'];
$result->request = $request;
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
if ($timeout > 0) {
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
fwrite($fp, $request);
}

// Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
// and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
// instead must invoke stream_get_meta_data() each iteration.
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'];
$response = '';

while ($alive) {
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
if ($timeout <= 0) {
$info['timed_out'] = TRUE;
break;
}
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
$chunk = fread($fp, 1024);
$response .= $chunk;
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'] && $chunk;
}
fclose($fp);

if ($info['timed_out']) {
$result->code = HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
return $result;
}
// Parse response headers from the response body.
// Be tolerant of malformed HTTP responses that separate header and body with
// \n\n or \r\r instead of \r\n\r\n.
list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$response = preg_split("/\r\n|\n|\r/", $response);

// Parse the response status line.
$response_status_array = _drupal_parse_response_status(trim(array_shift($response)));
$result->protocol = $response_status_array['http_version'];
$result->status_message = $response_status_array['reason_phrase'];
$code = $response_status_array['response_code'];

$result->headers = array();

// Parse the response headers.
while ($line = trim(array_shift($response))) {
list($name, $value) = explode(':', $line, 2);
$name = strtolower($name);
if (isset($result->headers[$name]) && $name == 'set-cookie') {
// RFC 2109: the Set-Cookie response header comprises the token Set-
// Cookie:, followed by a comma-separated list of one or more cookies.
$result->headers[$name] .= ',' . trim($value);
} else {
$result->headers[$name] = trim($value);
}
}

$responses = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
);
// RFC 2616 states that all unknown HTTP codes must be treated the same as the
// base code in their class.
if (!isset($responses[$code])) {
$code = floor($code / 100) * 100;
}
$result->code = $code;

switch ($code) {
case 200: // OK
case 201: // Created
case 202: // Accepted
case 203: // Non-Authoritative Information
case 204: // No Content
case 205: // Reset Content
case 206: // Partial Content
case 304: // Not modified
break;
case 301: // Moved permanently
case 302: // Moved temporarily
case 307: // Moved temporarily
$location = $result->headers['location'];
$options['timeout'] -= timer_read(__FUNCTION__) / 1000;
if ($options['timeout'] <= 0) {
$result->code = HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
} elseif ($options['max_redirects']) {
// Redirect to the new location.
$options['max_redirects'] --;
$result = drupal_http_request($location, $options);
$result->redirect_code = $code;
}
if (!isset($result->redirect_url)) {
$result->redirect_url = $location;
}
break;
default:
$result->error = $result->status_message;
}

return $result;
}

/**
* Splits an HTTP response status line into components.
*
* See the @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html status line definition @endlink
* in RFC 2616.
*
* @param string $respone
* The response status line, for example 'HTTP/1.1 500 Internal Server Error'.
*
* @return array
* Keyed array containing the component parts. If the response is malformed,
* all possible parts will be extracted. 'reason_phrase' could be empty.
* Possible keys:
* - 'http_version'
* - 'response_code'
* - 'reason_phrase'
*/
function _drupal_parse_response_status($response) {
$response_array = explode(' ', trim($response), 3);
// Set up empty values.
$result = array(
'reason_phrase' => '',
);
$result['http_version'] = $response_array[0];
$result['response_code'] = $response_array[1];
if (isset($response_array[2])) {
$result['reason_phrase'] = $response_array[2];
}
return $result;
}

/**
* Helper function for determining hosts excluded from needing a proxy.
*
* @return
* TRUE if a proxy should be used for this host.
*/
function _drupal_http_use_proxy($host) {
$proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
return !in_array(strtolower($host), $proxy_exceptions, TRUE);
}

/**
* @} End of "HTTP handling".
*/

/**
* Strips slashes from a string or array of strings.
*
* Callback for array_walk() within fix_gpx_magic().
*
* @param $item
* An individual string or array of strings from superglobals.
*/
function _fix_gpc_magic(&$item) {
if (is_array($item)) {
array_walk($item, '_fix_gpc_magic');
} else {
$item = stripslashes($item);
}
}

/**
* Strips slashes from $_FILES items.
*
* Callback for array_walk() within fix_gpc_magic().
*
* The tmp_name key is skipped keys since PHP generates single backslashes for
* file paths on Windows systems.
*
* @param $item
* An item from $_FILES.
* @param $key
* The key for the item within $_FILES.
*
* @see http://php.net/manual/features.file-upload.php#42280
*/
function _fix_gpc_magic_files(&$item, $key) {
if ($key != 'tmp_name') {
if (is_array($item)) {
array_walk($item, '_fix_gpc_magic_files');
} else {
$item = stripslashes($item);
}
}
}

/**
* Fixes double-escaping caused by "magic quotes" in some PHP installations.
*
* @see _fix_gpc_magic()
* @see _fix_gpc_magic_files()
*/
function fix_gpc_magic() {
static $fixed = FALSE;
if (!$fixed && ini_get('magic_quotes_gpc')) {
array_walk($_GET, '_fix_gpc_magic');
array_walk($_POST, '_fix_gpc_magic');
array_walk($_COOKIE, '_fix_gpc_magic');
array_walk($_REQUEST, '_fix_gpc_magic');
array_walk($_FILES, '_fix_gpc_magic_files');
}
$fixed = TRUE;
}

/**
* @defgroup validation Input validation
* @{
* Functions to validate user input.
*/

/**
* Verifies the syntax of the given e-mail address.
*
* This uses the
* @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
*
* @param $mail
* A string containing an e-mail address.
*
* @return
* TRUE if the address is in a valid format.
*/
function valid_email_address($mail) {
return (bool) filter_var($mail, FILTER_VALIDATE_EMAIL);
}

/**
* Verifies the syntax of the given URL.
*
* This function should only be used on actual URLs. It should not be used for
* Drupal menu paths, which can contain arbitrary characters.
* Valid values per RFC 3986.
* @param $url
* The URL to verify.
* @param $absolute
* Whether the URL is absolute (beginning with a scheme such as "http:").
*
* @return
* TRUE if the URL is in a valid format.
*/
function valid_url($url, $absolute = FALSE) {
if ($absolute) {
return (bool) preg_match("
/^ # Start at the beginning of the text
(?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
(?: # Userinfo (optional) which is typically
(?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
(?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
)?
(?:
(?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
|(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
)
(?::[0-9]+)? # Server port number (optional)
(?:[\/|\?]
(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
*)?
$/xi", $url);
} else {
return (bool) preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
}
}

/**
* @} End of "defgroup validation".
*/

/**
* Registers an event for the current visitor to the flood control mechanism.
*
* @param $name
* The name of an event.
* @param $window
* Optional number of seconds before this event expires. Defaults to 3600 (1
* hour). Typically uses the same value as the flood_is_allowed() $window
* parameter. Expired events are purged on cron run to prevent the flood table
* from growing indefinitely.
* @param $identifier
* Optional identifier (defaults to the current user's IP address).
*/
function flood_register_event($name, $window = 3600, $identifier = NULL) {
if (!isset($identifier)) {
$identifier = ip_address();
}
db_insert('flood')
->fields(array(
'event' => $name,
'identifier' => $identifier,
'timestamp' => REQUEST_TIME,
'expiration' => REQUEST_TIME + $window,
))
->execute();
}

/**
* Makes the flood control mechanism forget an event for the current visitor.
*
* @param $name
* The name of an event.
* @param $identifier
* Optional identifier (defaults to the current user's IP address).
*/
function flood_clear_event($name, $identifier = NULL) {
if (!isset($identifier)) {
$identifier = ip_address();
}
db_delete('flood')
->condition('event', $name)
->condition('identifier', $identifier)
->execute();
}

/**
* Checks whether a user is allowed to proceed with the specified event.
*
* Events can have thresholds saying that each user can only do that event
* a certain number of times in a time window. This function verifies that the
* current user has not exceeded this threshold.
*
* @param $name
* The unique name of the event.
* @param $threshold
* The maximum number of times each user can do this event per time window.
* @param $window
* Number of seconds in the time window for this event (default is 3600
* seconds, or 1 hour).
* @param $identifier
* Unique identifier of the current user. Defaults to their IP address.
*
* @return
* TRUE if the user is allowed to proceed. FALSE if they have exceeded the
* threshold and should not be allowed to proceed.
*/
function flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) {
if (!isset($identifier)) {
$identifier = ip_address();
}
$number = db_query("SELECT COUNT(*) FROM {flood} WHERE event = :event AND identifier = :identifier AND timestamp > :timestamp", array(
':event' => $name,
':identifier' => $identifier,
':timestamp' => REQUEST_TIME - $window))
->fetchField();
return ($number < $threshold);
}

/**
* @defgroup sanitization Sanitization functions
* @{
* Functions to sanitize values.
*
* See http://drupal.org/writing-secure-code for information
* on writing secure code.
*/

/**
* Strips dangerous protocols (e.g. 'javascript:') from a URI.
*
* This function must be called for all URIs within user-entered input prior
* to being output to an HTML attribute value. It is often called as part of
* check_url() or filter_xss(), but those functions return an HTML-encoded
* string, so this function can be called independently when the output needs to
* be a plain-text string for passing to t(), l(), drupal_attributes(), or
* another function that will call check_plain() separately.
*
* @param $uri
* A plain-text URI that might contain dangerous protocols.
*
* @return
* A plain-text URI stripped of dangerous protocols. As with all plain-text
* strings, this return value must not be output to an HTML page without
* check_plain() being called on it. However, it can be passed to functions
* expecting plain-text strings.
*
* @see check_url()
*/
function drupal_strip_dangerous_protocols($uri) {
static $allowed_protocols;

if (!isset($allowed_protocols)) {
$allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal')));
}

// Iteratively remove any invalid protocol found.
do {
$before = $uri;
$colonpos = strpos($uri, ':');
if ($colonpos > 0) {
// We found a colon, possibly a protocol. Verify.
$protocol = substr($uri, 0, $colonpos);
// If a colon is preceded by a slash, question mark or hash, it cannot
// possibly be part of the URL scheme. This must be a relative URL, which
// inherits the (safe) protocol of the base document.
if (preg_match('![/?#]!', $protocol)) {
break;
}
// Check if this is a disallowed protocol. Per RFC2616, section 3.2.3
// (URI Comparison) scheme comparison must be case-insensitive.
if (!isset($allowed_protocols[strtolower($protocol)])) {
$uri = substr($uri, $colonpos + 1);
}
}
} while ($before != $uri);

return $uri;
}

/**
* Strips dangerous protocols from a URI and encodes it for output to HTML.
*
* @param $uri
* A plain-text URI that might contain dangerous protocols.
*
* @return
* A URI stripped of dangerous protocols and encoded for output to an HTML
* attribute value. Because it is already encoded, it should not be set as a
* value within a $attributes array passed to drupal_attributes(), because
* drupal_attributes() expects those values to be plain-text strings. To pass
* a filtered URI to drupal_attributes(), call
* drupal_strip_dangerous_protocols() instead.
*
* @see drupal_strip_dangerous_protocols()
*/
function check_url($uri) {
return check_plain(drupal_strip_dangerous_protocols($uri));
}

/**
* Applies a very permissive XSS/HTML filter for admin-only use.
*
* Use only for fields where it is impractical to use the
* whole filter system, but where some (mainly inline) mark-up
* is desired (so check_plain() is not acceptable).
*
* Allows all tags that can be used inside an HTML body, save
* for scripts and styles.
*/
function filter_xss_admin($string) {
return filter_xss($string, array('a', 'abbr', 'acronym', 'address', 'article', 'aside', 'b', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'command', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'menu', 'meter', 'nav', 'ol', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'tt', 'u', 'ul', 'var', 'wbr'));
}

/**
* Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities.
*
* Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses.
* For examples of various XSS attacks, see: http://ha.ckers.org/xss.html.
*
* This code does four things:
* - Removes characters and constructs that can trick browsers.
* - Makes sure all HTML entities are well-formed.
* - Makes sure all HTML tags and attributes are well-formed.
* - Makes sure no HTML tags contain URLs with a disallowed protocol (e.g.
* javascript:).
*
* @param $string
* The string with raw HTML in it. It will be stripped of everything that can
* cause an XSS attack.
* @param $allowed_tags
* An array of allowed tags.
*
* @return
* An XSS safe version of $string, or an empty string if $string is not
* valid UTF-8.
*
* @see drupal_validate_utf8()
*/
function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')) {
// Only operate on valid UTF-8 strings. This is necessary to prevent cross
// site scripting issues on Internet Explorer 6.
if (!drupal_validate_utf8($string)) {
return '';
}
// Store the text format.
_filter_xss_split($allowed_tags, TRUE);
// Remove NULL characters (ignored by some browsers).
$string = str_replace(chr(0), '', $string);
// Remove Netscape 4 JS entities.
$string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);

// Defuse all HTML entities.
$string = str_replace('&', '&amp;', $string);
// Change back only well-formed entities in our whitelist:
// Decimal numeric entities.
$string = preg_replace('/&amp;#([0-9]+;)/', '&#\1', $string);
// Hexadecimal numeric entities.
$string = preg_replace('/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);
// Named entities.
$string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);

return preg_replace_callback('%
(
<(?=[^a-zA-Z!/]) # a lone <
| # or
<!--.*?--> # a comment
| # or
<[^>]*(>|$) # a string that starts with a <, up until the > or the end of the string
| # or
> # just a >
)%x', '_filter_xss_split', $string);
}

/**
* Processes an HTML tag.
*
* @param $m
* An array with various meaning depending on the value of $store.
* If $store is TRUE then the array contains the allowed tags.
* If $store is FALSE then the array has one element, the HTML tag to process.
* @param $store
* Whether to store $m.
*
* @return
* If the element isn't allowed, an empty string. Otherwise, the cleaned up
* version of the HTML element.
*/
function _filter_xss_split($m, $store = FALSE) {
static $allowed_html;

if ($store) {
$allowed_html = array_flip($m);
return;
}

$string = $m[1];

if (substr($string, 0, 1) != '<') {
// We matched a lone ">" character.
return '&gt;';
} elseif (strlen($string) == 1) {
// We matched a lone "<" character.
return '&lt;';
}

if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
// Seriously malformed.
return '';
}

$slash = trim($matches[1]);
$elem = &$matches[2];
$attrlist = &$matches[3];
$comment = &$matches[4];

if ($comment) {
$elem = '!--';
}

if (!isset($allowed_html[strtolower($elem)])) {
// Disallowed HTML element.
return '';
}

if ($comment) {
return $comment;
}

if ($slash != '') {
return "</$elem>";
}

// Is there a closing XHTML slash at the end of the attributes?
$attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
$xhtml_slash = $count ? ' /' : '';

// Clean up attributes.
$attr2 = implode(' ', _filter_xss_attributes($attrlist));
$attr2 = preg_replace('/[<>]/', '', $attr2);
$attr2 = strlen($attr2) ? ' ' . $attr2 : '';

return "<$elem$attr2$xhtml_slash>";
}

/**
* Processes a string of HTML attributes.
*
* @return
* Cleaned up version of the HTML attributes.
*/
function _filter_xss_attributes($attr) {
$attrarr = array();
$mode = 0;
$attrname = '';

while (strlen($attr) != 0) {
// Was the last operation successful?
$working = 0;

switch ($mode) {
case 0:
// Attribute name, href for instance.
if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
$attrname = strtolower($match[1]);
$skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
$working = $mode = 1;
$attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
}
break;

case 1:
// Equals sign or valueless ("selected").
if (preg_match('/^\s*=\s*/', $attr)) {
$working = 1;
$mode = 2;
$attr = preg_replace('/^\s*=\s*/', '', $attr);
break;
}

if (preg_match('/^\s+/', $attr)) {
$working = 1;
$mode = 0;
if (!$skip) {
$attrarr[] = $attrname;
}
$attr = preg_replace('/^\s+/', '', $attr);
}
break;

case 2:
// Attribute value, a URL after href= for instance.
if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
$thisval = filter_xss_bad_protocol($match[1]);

if (!$skip) {
$attrarr[] = "$attrname=\"$thisval\"";
}
$working = 1;
$mode = 0;
$attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
break;
}

if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) {
$thisval = filter_xss_bad_protocol($match[1]);

if (!$skip) {
$attrarr[] = "$attrname='$thisval'";
}
$working = 1;
$mode = 0;
$attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
break;
}

if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) {
$thisval = filter_xss_bad_protocol($match[1]);

if (!$skip) {
$attrarr[] = "$attrname=\"$thisval\"";
}
$working = 1;
$mode = 0;
$attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
}
break;
}

if ($working == 0) {
// Not well formed; remove and try again.
$attr = preg_replace('/
^
(
"[^"]*("|$) # - a string that starts with a double quote, up until the next double quote or the end of the string
| # or
\'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
| # or
\S # - a non-whitespace character
)* # any number of the above three
\s* # any number of whitespaces
/x', '', $attr);
$mode = 0;
}
}

// The attribute list ends with a valueless attribute like "selected".
if ($mode == 1 && !$skip) {
$attrarr[] = $attrname;
}
return $attrarr;
}

/**
* Processes an HTML attribute value and strips dangerous protocols from URLs.
*
* @param $string
* The string with the attribute value.
* @param $decode
* (deprecated) Whether to decode entities in the $string. Set to FALSE if the
* $string is in plain text, TRUE otherwise. Defaults to TRUE. This parameter
* is deprecated and will be removed in Drupal 8. To process a plain-text URI,
* call drupal_strip_dangerous_protocols() or check_url() instead.
*
* @return
* Cleaned up and HTML-escaped version of $string.
*/
function filter_xss_bad_protocol($string, $decode = TRUE) {
// Get the plain text representation of the attribute value (i.e. its meaning).
// @todo Remove the $decode parameter in Drupal 8, and always assume an HTML
// string that needs decoding.
if ($decode) {
if (!function_exists('decode_entities')) {
require_once DRUPAL_ROOT . '/includes/unicode.inc';
}

$string = decode_entities($string);
}
return check_plain(drupal_strip_dangerous_protocols($string));
}

/**
* @} End of "defgroup sanitization".
*/
/**
* @defgroup format Formatting
* @{
* Functions to format numbers, strings, dates, etc.
*/

/**
* Formats an RSS channel.
*
* Arbitrary elements may be added using the $args associative array.
*/
function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
global $language_content;
$langcode = $langcode ? $langcode : $language_content->language;

$output = "<channel>\n";
$output .= ' <title>' . check_plain($title) . "</title>\n";
$output .= ' <link>' . check_url($link) . "</link>\n";

// The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
// We strip all HTML tags, but need to prevent double encoding from properly
// escaped source data (such as &amp becoming &amp;amp;).
$output .= ' <description>' . check_plain(decode_entities(strip_tags($description))) . "</description>\n";
$output .= ' <language>' . check_plain($langcode) . "</language>\n";
$output .= format_xml_elements($args);
$output .= $items;
$output .= "</channel>\n";

return $output;
}

/**
* Formats a single RSS item.
*
* Arbitrary elements may be added using the $args associative array.
*/
function format_rss_item($title, $link, $description, $args = array()) {
$output = "<item>\n";
$output .= ' <title>' . check_plain($title) . "</title>\n";
$output .= ' <link>' . check_url($link) . "</link>\n";
$output .= ' <description>' . check_plain($description) . "</description>\n";
$output .= format_xml_elements($args);
$output .= "</item>\n";

return $output;
}

/**
* Formats XML elements.
*
* @param $array
* An array where each item represents an element and is either a:
* - (key => value) pair (<key>value</key>)
* - Associative array with fields:
* - 'key': element name
* - 'value': element contents
* - 'attributes': associative array of element attributes
* - 'encoded': TRUE if 'value' is already encoded
*
* In both cases, 'value' can be a simple string, or it can be another array
* with the same format as $array itself for nesting.
*
* If 'encoded' is TRUE it is up to the caller to ensure that 'value' is either
* entity-encoded or CDATA-escaped. Using this option is not recommended when
* working with untrusted user input, since failing to escape the data
* correctly has security implications.
*/
function format_xml_elements($array) {
$output = '';
foreach ($array as $key => $value) {
if (is_numeric($key)) {
if ($value['key']) {
$output .= ' <' . $value['key'];
if (isset($value['attributes']) && is_array($value['attributes'])) {
$output .= drupal_attributes($value['attributes']);
}

if (isset($value['value']) && $value['value'] != '') {
$output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : (!empty($value['encoded']) ? $value['value'] : check_plain($value['value']))) . '</' . $value['key'] . ">\n";
} else {
$output .= " />\n";
}
}
} else {
$output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
}
}
return $output;
}

/**
* Formats a string containing a count of items.
*
* This function ensures that the string is pluralized correctly. Since t() is
* called by this function, make sure not to pass already-localized strings to
* it.
*
* For example:
* @code
* $output = format_plural($node->comment_count, '1 comment', '@count comments');
* @endcode
*
* Example with additional replacements:
* @code
* $output = format_plural($update_count,
* 'Changed the content type of 1 post from %old-type to %new-type.',
* 'Changed the content type of @count posts from %old-type to %new-type.',
* array('%old-type' => $info->old_type, '%new-type' => $info->new_type));
* @endcode
*
* @param $count
* The item count to display.
* @param $singular
* The string for the singular case. Make sure it is clear this is singular,
* to ease translation (e.g. use "1 new comment" instead of "1 new"). Do not
* use @count in the singular string.
* @param $plural
* The string for the plural case. Make sure it is clear this is plural, to
* ease translation. Use @count in place of the item count, as in
* "@count new comments".
* @param $args
* An associative array of replacements to make after translation. Instances
* of any key in this array are replaced with the corresponding value.
* Based on the first character of the key, the value is escaped and/or
* themed. See format_string(). Note that you do not need to include @count
* in this array; this replacement is done automatically for the plural case.
* @param $options
* An associative array of additional options. See t() for allowed keys.
*
* @return
* A translated string.
*
* @see t()
* @see format_string()
*/
function format_plural($count, $singular, $plural, array $args = array(), array $options = array()) {
$args['@count'] = $count;
if ($count == 1) {
return t($singular, $args, $options);
}

// Get the plural index through the gettext formula.
$index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
// If the index cannot be computed, use the plural as a fallback (which
// allows for most flexiblity with the replaceable @count value).
if ($index < 0) {
return t($plural, $args, $options);
} else {
switch ($index) {
case "0":
return t($singular, $args, $options);
case "1":
return t($plural, $args, $options);
default:
unset($args['@count']);
$args['@count[' . $index . ']'] = $count;
return t(strtr($plural, array('@count' => '@count[' . $index . ']')), $args, $options);
}
}
}

/**
* Parses a given byte count.
*
* @param $size
* A size expressed as a number of bytes with optional SI or IEC binary unit
* prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
*
* @return
* An integer representation of the size in bytes.
*/
function parse_size($size) {
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
$size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
if ($unit) {
// Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
return round($size * pow(DRUPAL_KILOBYTE, stripos('bkmgtpezy', $unit[0])));
} else {
return round($size);
}
}

/**
* Generates a string representation for the given byte count.
*
* @param $size
* A size in bytes.
* @param $langcode
* Optional language code to translate to a language other than what is used
* to display the page.
*
* @return
* A translated string representation of the size.
*/
function format_size($size, $langcode = NULL) {
if ($size < DRUPAL_KILOBYTE) {
return format_plural($size, '1 byte', '@count bytes', array(), array('langcode' => $langcode));
} else {
$size = $size / DRUPAL_KILOBYTE; // Convert bytes to kilobytes.
$units = array(
t('@size KB', array(), array('langcode' => $langcode)),
t('@size MB', array(), array('langcode' => $langcode)),
t('@size GB', array(), array('langcode' => $langcode)),
t('@size TB', array(), array('langcode' => $langcode)),
t('@size PB', array(), array('langcode' => $langcode)),
t('@size EB', array(), array('langcode' => $langcode)),
t('@size ZB', array(), array('langcode' => $langcode)),
t('@size YB', array(), array('langcode' => $langcode)),
);
foreach ($units as $unit) {
if (round($size, 2) >= DRUPAL_KILOBYTE) {
$size = $size / DRUPAL_KILOBYTE;
} else {
break;
}
}
return str_replace('@size', round($size, 2), $unit);
}
}

/**
* Formats a time interval with the requested granularity.
*
* @param $interval
* The length of the interval in seconds.
* @param $granularity
* How many different units to display in the string.
* @param $langcode
* Optional language code to translate to a language other than
* what is used to display the page.
*
* @return
* A translated string representation of the interval.
*/
function format_interval($interval, $granularity = 2, $langcode = NULL) {
$units = array(
'1 year|@count years' => 31536000,
'1 month|@count months' => 2592000,
'1 week|@count weeks' => 604800,
'1 day|@count days' => 86400,
'1 hour|@count hours' => 3600,
'1 min|@count min' => 60,
'1 sec|@count sec' => 1
);
$output = '';
foreach ($units as $key => $value) {
$key = explode('|', $key);
if ($interval >= $value) {
$output .= ($output ? ' ' : '') . format_plural(floor($interval / $value), $key[0], $key[1], array(), array('langcode' => $langcode));
$interval %= $value;
$granularity--;
}

if ($granularity == 0) {
break;
}
}
return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
}

/**
* Formats a date, using a date type or a custom date format string.
*
* @param $timestamp
* A UNIX timestamp to format.
* @param $type
* (optional) The format to use, one of:
* - 'short', 'medium', or 'long' (the corresponding built-in date formats).
* - The name of a date type defined by a module in hook_date_format_types(),
* if it's been assigned a format.
* - The machine name of an administrator-defined date format.
* - 'custom', to use $format.
* Defaults to 'medium'.
* @param $format
* (optional) If $type is 'custom', a PHP date format string suitable for
* input to date(). Use a backslash to escape ordinary text, so it does not
* get interpreted as date format characters.
* @param $timezone
* (optional) Time zone identifier, as described at
* http://php.net/manual/timezones.php Defaults to the time zone used to
* display the page.
* @param $langcode
* (optional) Language code to translate to. Defaults to the language used to
* display the page.
*
* @return
* A translated date string in the requested format.
*/
function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
// Use the advanced drupal_static() pattern, since this is called very often.
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
$drupal_static_fast['timezones'] = &drupal_static(__FUNCTION__);
}
$timezones = &$drupal_static_fast['timezones'];

if (!isset($timezone)) {
$timezone = date_default_timezone_get();
}
// Store DateTimeZone objects in an array rather than repeatedly
// constructing identical objects over the life of a request.
if (!isset($timezones[$timezone])) {
$timezones[$timezone] = timezone_open($timezone);
}

// Use the default langcode if none is set.
global $language;
if (empty($langcode)) {
$langcode = isset($language->language) ? $language->language : 'en';
}

switch ($type) {
case 'short':
$format = variable_get('date_format_short', 'm/d/Y - H:i');
break;

case 'long':
$format = variable_get('date_format_long', 'l, F j, Y - H:i');
break;

case 'custom':
// No change to format.
break;

case 'medium':
default:
// Retrieve the format of the custom $type passed.
if ($type != 'medium') {
$format = variable_get('date_format_' . $type, '');
}
// Fall back to 'medium'.
if ($format === '') {
$format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
}
break;
}

// Create a DateTime object from the timestamp.
$date_time = date_create('@' . $timestamp);
// Set the time zone for the DateTime object.
date_timezone_set($date_time, $timezones[$timezone]);

// Encode markers that should be translated. 'A' becomes '\xEF\AA\xFF'.
// xEF and xFF are invalid UTF-8 sequences, and we assume they are not in the
// input string.
// Paired backslashes are isolated to prevent errors in read-ahead evaluation.
// The read-ahead expression ensures that A matches, but not \A.
$format = preg_replace(array('/\\\\\\\\/', '/(?<!\\\\)([AaeDlMTF])/'), array("\xEF\\\\\\\\\xFF", "\xEF\\\\\$1\$1\xFF"), $format);

// Call date_format().
$format = date_format($date_time, $format);

// Pass the langcode to _format_date_callback().
_format_date_callback(NULL, $langcode);

// Translate the marked sequences.
return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
}

/**
* Returns an ISO8601 formatted date based on the given date.
*
* Callback for use within hook_rdf_mapping() implementations.
*
* @param $date
* A UNIX timestamp.
*
* @return string
* An ISO8601 formatted date.
*/
function date_iso8601($date) {
// The DATE_ISO8601 constant cannot be used here because it does not match
// date('c') and produces invalid RDF markup.
return date('c', $date);
}

/**
* Translates a formatted date string.
*
* Callback for preg_replace_callback() within format_date().
*/
function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
// We cache translations to avoid redundant and rather costly calls to t().
static $cache, $langcode;

if (!isset($matches)) {
$langcode = $new_langcode;
return;
}

$code = $matches[1];
$string = $matches[2];

if (!isset($cache[$langcode][$code][$string])) {
$options = array(
'langcode' => $langcode,
);

if ($code == 'F') {
$options['context'] = 'Long month name';
}

if ($code == '') {
$cache[$langcode][$code][$string] = $string;
} else {
$cache[$langcode][$code][$string] = t($string, array(), $options);
}
}
return $cache[$langcode][$code][$string];
}

/**
* Format a username.
*
* This is also the label callback implementation of
* callback_entity_info_label() for user_entity_info().
*
* By default, the passed-in object's 'name' property is used if it exists, or
* else, the site-defined value for the 'anonymous' variable. However, a module
* may override this by implementing hook_username_alter(&$name, $account).
*
* @see hook_username_alter()
*
* @param $account
* The account object for the user whose name is to be formatted.
*
* @return
* An unsanitized string with the username to display. The code receiving
* this result must ensure that check_plain() is called on it before it is
* printed to the page.
*/
function format_username($account) {
$name = !empty($account->name) ? $account->name : variable_get('anonymous', t('Anonymous'));
drupal_alter('username', $name, $account);
return $name;
}

/**
* @} End of "defgroup format".
*/

/**
* Generates an internal or external URL.
*
* When creating links in modules, consider whether l() could be a better
* alternative than url().
*
* @param $path
* (optional) The internal path or external URL being linked to, such as
* "node/34" or "http://example.com/foo". The default value is equivalent to
* passing in '<front>'. A few notes:
* - If you provide a full URL, it will be considered an external URL.
* - If you provide only the path (e.g. "node/34"), it will be
* considered an internal link. In this case, it should be a system URL,
* and it will be replaced with the alias, if one exists. Additional query
* arguments for internal paths must be supplied in $options['query'], not
* included in $path.
* - If you provide an internal path and $options['alias'] is set to TRUE, the
* path is assumed already to be the correct path alias, and the alias is
* not looked up.
* - The special string '<front>' generates a link to the site's base URL.
* - If your external URL contains a query (e.g. http://example.com/foo?a=b),
* then you can either URL encode the query keys and values yourself and
* include them in $path, or use $options['query'] to let this function
* URL encode them.
* @param $options
* (optional) An associative array of additional options, with the following
* elements:
* - 'query': An array of query key/value-pairs (without any URL-encoding) to
* append to the URL.
* - 'fragment': A fragment identifier (named anchor) to append to the URL.
* Do not include the leading '#' character.
* - 'absolute': Defaults to FALSE. Whether to force the output to be an
* absolute link (beginning with http:). Useful for links that will be
* displayed outside the site, such as in an RSS feed.
* - 'alias': Defaults to FALSE. Whether the given path is a URL alias
* already.
* - 'external': Whether the given path is an external URL.
* - 'language': An optional language object. If the path being linked to is
* internal to the site, $options['language'] is used to look up the alias
* for the URL. If $options['language'] is omitted, the global $language_url
* will be used.
* - 'https': Whether this URL should point to a secure location. If not
* defined, the current scheme is used, so the user stays on HTTP or HTTPS
* respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can
* only be enforced when the variable 'https' is set to TRUE.
* - 'base_url': Only used internally, to modify the base URL when a language
* dependent URL requires so.
* - 'prefix': Only used internally, to modify the path when a language
* dependent URL requires so.
* - 'script': The script filename in Drupal's root directory to use when
* clean URLs are disabled, such as 'index.php'. Defaults to an empty
* string, as most modern web servers automatically find 'index.php'. If
* clean URLs are disabled, the value of $path is appended as query
* parameter 'q' to $options['script'] in the returned URL. When deploying
* Drupal on a web server that cannot be configured to automatically find
* index.php, then hook_url_outbound_alter() can be implemented to force
* this value to 'index.php'.
* - 'entity_type': The entity type of the object that called url(). Only
* set if url() is invoked by entity_uri().
* - 'entity': The entity object (such as a node) for which the URL is being
* generated. Only set if url() is invoked by entity_uri().
*
* @return
* A string containing a URL to the given path.
*/
function url($path = NULL, array $options = array()) {
// Merge in defaults.
$options += array(
'fragment' => '',
'query' => array(),
'absolute' => FALSE,
'alias' => FALSE,
'prefix' => ''
);
<?php

/**
* @file
* Common functions that many Drupal modules will need to reference.
*
* The functions that are critical and need to be available even when serving
* a cached page are instead located in bootstrap.inc.
*/
/**
* @defgroup php_wrappers PHP wrapper functions
* @{
* Functions that are wrappers or custom implementations of PHP functions.
*
* Certain PHP functions should not be used in Drupal. Instead, Drupal's
* replacement functions should be used.
*
* For example, for improved or more secure UTF8-handling, or RFC-compliant
* handling of URLs in Drupal.
*
* For ease of use and memorizing, all these wrapper functions use the same name
* as the original PHP function, but prefixed with "drupal_". Beware, however,
* that not all wrapper functions support the same arguments as the original
* functions.
*
* You should always use these wrapper functions in your code.
*
* Wrong:
* @code
* $my_substring = substr($original_string, 0, 5);
* @endcode
*
* Correct:
* @code
* $my_substring = drupal_substr($original_string, 0, 5);
* @endcode
*
* @}
*/
/**
* Return status for saving which involved creating a new item.
*/
define('SAVED_NEW', 1);
/**
* Return status for saving which involved an update to an existing item.
*/
define('SAVED_UPDATED', 2);
/**
* Return status for saving which deleted an existing item.
*/
define('SAVED_DELETED', 3);

/**
* The default group for system CSS files added to the page.
*/
define('CSS_SYSTEM', -100);

/**
* The default group for module CSS files added to the page.
*/
define('CSS_DEFAULT', 0);

/**
* The default group for theme CSS files added to the page.
*/
define('CSS_THEME', 100);

/**
* The default group for JavaScript and jQuery libraries added to the page.
*/
define('JS_LIBRARY', -100);

/**
* The default group for module JavaScript code added to the page.
*/
define('JS_DEFAULT', 0);

/**
* The default group for theme JavaScript code added to the page.
*/
define('JS_THEME', 100);

/**
* Error code indicating that the request exceeded the specified timeout.
*
* @see drupal_http_request()
*/
define('HTTP_REQUEST_TIMEOUT', -1);

/**
* @defgroup block_caching Block Caching
* @{
* Constants that define each block's caching state.
*
* Modules specify how their blocks can be cached in their hook_block_info()
* implementations. Caching can be turned off (DRUPAL_NO_CACHE), managed by the
* module declaring the block (DRUPAL_CACHE_CUSTOM), or managed by the core
* Block module. If the Block module is managing the cache, you can specify that
* the block is the same for every page and user (DRUPAL_CACHE_GLOBAL), or that
* it can change depending on the page (DRUPAL_CACHE_PER_PAGE) or by user
* (DRUPAL_CACHE_PER_ROLE or DRUPAL_CACHE_PER_USER). Page and user settings can
* be combined with a bitwise-binary or operator; for example,
* DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE means that the block can change
* depending on the user role or page it is on.
*
* The block cache is cleared in cache_clear_all(), and uses the same clearing
* policy than page cache (node, comment, user, taxonomy added or updated...).
* Blocks requiring more fine-grained clearing might consider disabling the
* built-in block cache (DRUPAL_NO_CACHE) and roll their own.
*
* Note that user 1 is excluded from block caching.
*/
/**
* The block should not get cached.
*
* This setting should be used:
* - For simple blocks (notably those that do not perform any db query), where
* querying the db cache would be more expensive than directly generating the
* content.
* - For blocks that change too frequently.
*/
define('DRUPAL_NO_CACHE', -1);

/**
* The block is handling its own caching in its hook_block_view().
*
* This setting is useful when time based expiration is needed or a site uses a
* node access which invalidates standard block cache.
*/
define('DRUPAL_CACHE_CUSTOM', -2);

/**
* The block or element can change depending on the user's roles.
*
* This is the default setting for blocks, used when the block does not specify
* anything.
*/
define('DRUPAL_CACHE_PER_ROLE', 0x0001);

/**
* The block or element can change depending on the user.
*
* This setting can be resource-consuming for sites with large number of users,
* and thus should only be used when DRUPAL_CACHE_PER_ROLE is not sufficient.
*/
define('DRUPAL_CACHE_PER_USER', 0x0002);

/**
* The block or element can change depending on the page being viewed.
*/
define('DRUPAL_CACHE_PER_PAGE', 0x0004);

/**
* The block or element is the same for every user and page that it is visible.
*/
define('DRUPAL_CACHE_GLOBAL', 0x0008);

/**
* @} End of "defgroup block_caching".
*/

/**
* Adds content to a specified region.
*
* @param $region
* Page region the content is added to.
* @param $data
* Content to be added.
*/
function drupal_add_region_content($region = NULL, $data = NULL) {
static $content = array();

if (isset($region) && isset($data)) {
$content[$region][] = $data;
}
return $content;
}

/**
* Gets assigned content for a given region.
*
* @param $region
* A specified region to fetch content for. If NULL, all regions will be
* returned.
* @param $delimiter
* Content to be inserted between imploded array elements.
*/
function drupal_get_region_content($region = NULL, $delimiter = ' ') {
$content = drupal_add_region_content();
if (isset($region)) {
if (isset($content[$region]) && is_array($content[$region])) {
return implode($delimiter, $content[$region]);
}
} else {
foreach (array_keys($content) as $region) {
if (is_array($content[$region])) {
$content[$region] = implode($delimiter, $content[$region]);
}
}
return $content;
}
}

/**
* Gets the name of the currently active installation profile.
*
* When this function is called during Drupal's initial installation process,
* the name of the profile that's about to be installed is stored in the global
* installation state. At all other times, the standard Drupal systems variable
* table contains the name of the current profile, and we can call
* variable_get() to determine what one is active.
*
* @return $profile
* The name of the installation profile.
*/
function drupal_get_profile() {
global $install_state;

if (isset($install_state['parameters']['profile'])) {
$profile = $install_state['parameters']['profile'];
} else {
$profile = variable_get('install_profile', 'standard');
}

return $profile;
}

/**
* Sets the breadcrumb trail for the current page.
*
* @param $breadcrumb
* Array of links, starting with "home" and proceeding up to but not including
* the current page.
*/
function drupal_set_breadcrumb($breadcrumb = NULL) {
$stored_breadcrumb = &drupal_static(__FUNCTION__);

if (isset($breadcrumb)) {
$stored_breadcrumb = $breadcrumb;
}
return $stored_breadcrumb;
}

/**
* Gets the breadcrumb trail for the current page.
*/
function drupal_get_breadcrumb() {
$breadcrumb = drupal_set_breadcrumb();

if (!isset($breadcrumb)) {
$breadcrumb = menu_get_active_breadcrumb();
}

return $breadcrumb;
}

/**
* Returns a string containing RDF namespace declarations for use in XML and
* XHTML output.
*/
function drupal_get_rdf_namespaces() {
$xml_rdf_namespaces = array();

// Serializes the RDF namespaces in XML namespace syntax.
if (function_exists('rdf_get_namespaces')) {
foreach (rdf_get_namespaces() as $prefix => $uri) {
$xml_rdf_namespaces[] = 'xmlns:' . $prefix . '="' . $uri . '"';
}
}
return count($xml_rdf_namespaces) ? "\n " . implode("\n ", $xml_rdf_namespaces) : '';
}

/**
* Adds output to the HEAD tag of the HTML page.
*
* This function can be called as long as the headers aren't sent. Pass no
* arguments (or NULL for both) to retrieve the currently stored elements.
*
* @param $data
* A renderable array. If the '#type' key is not set then 'html_tag' will be
* added as the default '#type'.
* @param $key
* A unique string key to allow implementations of hook_html_head_alter() to
* identify the element in $data. Required if $data is not NULL.
*
* @return
* An array of all stored HEAD elements.
*
* @see theme_html_tag()
*/
function drupal_add_html_head($data = NULL, $key = NULL) {
$stored_head = &drupal_static(__FUNCTION__);

if (!isset($stored_head)) {
// Make sure the defaults, including Content-Type, come first.
$stored_head = _drupal_default_html_head();
}

if (isset($data) && isset($key)) {
if (!isset($data['#type'])) {
$data['#type'] = 'html_tag';
}
$stored_head[$key] = $data;
}
return $stored_head;
}

/**
* Returns elements that are always displayed in the HEAD tag of the HTML page.
*/
function _drupal_default_html_head() {
// Add default elements. Make sure the Content-Type comes first because the
// IE browser may be vulnerable to XSS via encoding attacks from any content
// that comes before this META tag, such as a TITLE tag.
$elements['system_meta_content_type'] = array(
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => array(
'http-equiv' => 'Content-Type',
'content' => 'text/html; charset=utf-8',
),
// Security: This always has to be output first.
'#weight' => -1000,
);
// Show Drupal and the major version number in the META GENERATOR tag.
// Get the major version.
list($version, ) = explode('.', VERSION);
$elements['system_meta_generator'] = array(
'#type' => 'html_tag',
'#tag' => 'meta',
'#attributes' => array(
'name' => 'Generator',
'content' => 'Drupal ' . $version . ' (http://drupal.org)',
),
);
// Also send the generator in the HTTP header.
$elements['system_meta_generator']['#attached']['drupal_add_http_header'][] = array('X-Generator', $elements['system_meta_generator']['#attributes']['content']);
return $elements;
}

/**
* Retrieves output to be displayed in the HEAD tag of the HTML page.
*/
function drupal_get_html_head() {
$elements = drupal_add_html_head();
drupal_alter('html_head', $elements);
return drupal_render($elements);
}

/**
* Adds a feed URL for the current page.
*
* This function can be called as long the HTML header hasn't been sent.
*
* @param $url
* An internal system path or a fully qualified external URL of the feed.
* @param $title
* The title of the feed.
*/
function drupal_add_feed($url = NULL, $title = '') {
$stored_feed_links = &drupal_static(__FUNCTION__, array());

if (isset($url)) {
$stored_feed_links[$url] = theme('feed_icon', array('url' => $url, 'title' => $title));

drupal_add_html_head_link(array(
'rel' => 'alternate',
'type' => 'application/rss+xml',
'title' => $title,
// Force the URL to be absolute, for consistency with other <link> tags
// output by Drupal.
'href' => url($url, array('absolute' => TRUE)),
));
}
return $stored_feed_links;
}

/**
* Gets the feed URLs for the current page.
*
* @param $delimiter
* A delimiter to split feeds by.
*/
function drupal_get_feeds($delimiter = "\n") {
$feeds = drupal_add_feed();
return implode($feeds, $delimiter);
}

/**
* @defgroup http_handling HTTP handling
* @{
* Functions to properly handle HTTP responses.
*/

/**
* Processes a URL query parameter array to remove unwanted elements.
*
* @param $query
* (optional) An array to be processed. Defaults to $_GET.
* @param $exclude
* (optional) A list of $query array keys to remove. Use "parent[child]" to
* exclude nested items. Defaults to array('q').
* @param $parent
* Internal use only. Used to build the $query array key for nested items.
*
* @return
* An array containing query parameters, which can be used for url().
*/
function drupal_get_query_parameters(array $query = NULL, array $exclude = array('q'), $parent = '') {
// Set defaults, if none given.
if (!isset($query)) {
$query = $_GET;
}
// If $exclude is empty, there is nothing to filter.
if (empty($exclude)) {
return $query;
} elseif (!$parent) {
$exclude = array_flip($exclude);
}

$params = array();
foreach ($query as $key => $value) {
$string_key = ($parent ? $parent . '[' . $key . ']' : $key);
if (isset($exclude[$string_key])) {
continue;
}

if (is_array($value)) {
$params[$key] = drupal_get_query_parameters($value, $exclude, $string_key);
} else {
$params[$key] = $value;
}
}

return $params;
}

/**
* Splits a URL-encoded query string into an array.
*
* @param $query
* The query string to split.
*
* @return
* An array of URL decoded couples $param_name => $value.
*/
function drupal_get_query_array($query) {
$result = array();
if (!empty($query)) {
foreach (explode('&', $query) as $param) {
$param = explode('=', $param, 2);
$result[$param[0]] = isset($param[1]) ? rawurldecode($param[1]) : '';
}
}
return $result;
}

/**
* Parses an array into a valid, rawurlencoded query string.
*
* This differs from http_build_query() as we need to rawurlencode() (instead of
* urlencode()) all query parameters.
*
* @param $query
* The query parameter array to be processed, e.g. $_GET.
* @param $parent
* Internal use only. Used to build the $query array key for nested items.
*
* @return
* A rawurlencoded string which can be used as or appended to the URL query
* string.
*
* @see drupal_get_query_parameters()
* @ingroup php_wrappers
*/
function drupal_http_build_query(array $query, $parent = '') {
$params = array();

foreach ($query as $key => $value) {
$key = $parent ? $parent . rawurlencode('[' . $key . ']') : rawurlencode($key);

// Recurse into children.
if (is_array($value)) {
$params[] = drupal_http_build_query($value, $key);
}
// If a query parameter value is NULL, only append its key.
elseif (!isset($value)) {
$params[] = $key;
} else {
// For better readability of paths in query strings, we decode slashes.
$params[] = $key . '=' . str_replace('%2F', '/', rawurlencode($value));
}
}

return implode('&', $params);
}

/**
* Prepares a 'destination' URL query parameter for use with drupal_goto().
*
* Used to direct the user back to the referring page after completing a form.
* By default the current URL is returned. If a destination exists in the
* previous request, that destination is returned. As such, a destination can
* persist across multiple pages.
*
* @return
* An associative array containing the key:
* - destination: The path provided via the destination query string or, if
* not available, the current path.
*
* @see current_path()
* @see drupal_goto()
*/
function drupal_get_destination() {
$destination = &drupal_static(__FUNCTION__);

if (isset($destination)) {
return $destination;
}

if (isset($_GET['destination'])) {
$destination = array('destination' => $_GET['destination']);
} else {
$path = $_GET['q'];
$query = drupal_http_build_query(drupal_get_query_parameters());
if ($query != '') {
$path .= '?' . $query;
}
$destination = array('destination' => $path);
}
return $destination;
}

/**
* Parses a URL string into its path, query, and fragment components.
*
* This function splits both internal paths like @code node?b=c#d @endcode and
* external URLs like @code https://example.com/a?b=c#d @endcode into their
* component parts. See
* @link http://tools.ietf.org/html/rfc3986#section-3 RFC 3986 @endlink for an
* explanation of what the component parts are.
*
* Note that, unlike the RFC, when passed an external URL, this function
* groups the scheme, authority, and path together into the path component.
*
* @param string $url
* The internal path or external URL string to parse.
*
* @return array
* An associative array containing:
* - path: The path component of $url. If $url is an external URL, this
* includes the scheme, authority, and path.
* - query: An array of query parameters from $url, if they exist.
* - fragment: The fragment component from $url, if it exists.
*
* @see drupal_goto()
* @see l()
* @see url()
* @see http://tools.ietf.org/html/rfc3986
*
* @ingroup php_wrappers
*/
function drupal_parse_url($url) {
$options = array(
'path' => NULL,
'query' => array(),
'fragment' => '',
);

// External URLs: not using parse_url() here, so we do not have to rebuild
// the scheme, host, and path without having any use for it.
if (strpos($url, '://') !== FALSE) {
// Split off everything before the query string into 'path'.
$parts = explode('?', $url);
$options['path'] = $parts[0];
// If there is a query string, transform it into keyed query parameters.
if (isset($parts[1])) {
$query_parts = explode('#', $parts[1]);
parse_str($query_parts[0], $options['query']);
// Take over the fragment, if there is any.
if (isset($query_parts[1])) {
$options['fragment'] = $query_parts[1];
}
}
}
// Internal URLs.
else {
// parse_url() does not support relative URLs, so make it absolute. E.g. the
// relative URL "foo/bar:1" isn't properly parsed.
$parts = parse_url('http://example.com/' . $url);
// Strip the leading slash that was just added.
$options['path'] = substr($parts['path'], 1);
if (isset($parts['query'])) {
parse_str($parts['query'], $options['query']);
}
if (isset($parts['fragment'])) {
$options['fragment'] = $parts['fragment'];
}
}
// The 'q' parameter contains the path of the current page if clean URLs are
// disabled. It overrides the 'path' of the URL when present, even if clean
// URLs are enabled, due to how Apache rewriting rules work.
#if (isset($options['query']['q'])) {
// by ugarte patch just the if condition before was the line on top
if (isset($options['query']['q']) && is_string($options['query']['q'])) {
$options['path'] = $options['query']['q'];
unset($options['query']['q']);
}

return $options;
}

/**
* Encodes a Drupal path for use in a URL.
*
* For aesthetic reasons slashes are not escaped.
*
* Note that url() takes care of calling this function, so a path passed to that
* function should not be encoded in advance.
*
* @param $path
* The Drupal path to encode.
*/
function drupal_encode_path($path) {
return str_replace('%2F', '/', rawurlencode($path));
}

/**
* Sends the user to a different page.
*
* This issues an on-site HTTP redirect. The function makes sure the redirected
* URL is formatted correctly.
*
* Usually the redirected URL is constructed from this function's input
* parameters. However you may override that behavior by setting a
* destination in either the $_REQUEST-array (i.e. by using
* the query string of an URI) This is used to direct the user back to
* the proper page after completing a form. For example, after editing
* a post on the 'admin/content'-page or after having logged on using the
* 'user login'-block in a sidebar. The function drupal_get_destination()
* can be used to help set the destination URL.
*
* Drupal will ensure that messages set by drupal_set_message() and other
* session data are written to the database before the user is redirected.
*
* This function ends the request; use it instead of a return in your menu
* callback.
*
* @param $path
* (optional) A Drupal path or a full URL, which will be passed to url() to
* compute the redirect for the URL.
* @param $options
* (optional) An associative array of additional URL options to pass to url().
* @param $http_response_code
* (optional) The HTTP status code to use for the redirection, defaults to
* 302. The valid values for 3xx redirection status codes are defined in
* @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3 RFC 2616 @endlink
* and the
* @link http://tools.ietf.org/html/draft-reschke-http-status-308-07 draft for the new HTTP status codes: @endlink
* - 301: Moved Permanently (the recommended value for most redirects).
* - 302: Found (default in Drupal and PHP, sometimes used for spamming search
* engines).
* - 303: See Other.
* - 304: Not Modified.
* - 305: Use Proxy.
* - 307: Temporary Redirect.
*
* @see drupal_get_destination()
* @see url()
*/
function drupal_goto($path = '', array $options = array(), $http_response_code = 302) {
// A destination in $_GET always overrides the function arguments.
// We do not allow absolute URLs to be passed via $_GET, as this can be an attack vector.
if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
$destination = drupal_parse_url($_GET['destination']);
$path = $destination['path'];
$options['query'] = $destination['query'];
$options['fragment'] = $destination['fragment'];
}

// In some cases modules call drupal_goto(current_path()). We need to ensure
// that such a redirect is not to an external URL.
if ($path === current_path() && empty($options['external']) && url_is_external($path)) {
// Force url() to generate a non-external URL.
$options['external'] = FALSE;
}

drupal_alter('drupal_goto', $path, $options, $http_response_code);

// The 'Location' HTTP header must be absolute.
$options['absolute'] = TRUE;

$url = url($path, $options);

header('Location: ' . $url, TRUE, $http_response_code);

// The "Location" header sends a redirect status code to the HTTP daemon. In
// some cases this can be wrong, so we make sure none of the code below the
// drupal_goto() call gets executed upon redirection.
drupal_exit($url);
}

/**
* Delivers a "site is under maintenance" message to the browser.
*
* Page callback functions wanting to report a "site offline" message should
* return MENU_SITE_OFFLINE instead of calling drupal_site_offline(). However,
* functions that are invoked in contexts where that return value might not
* bubble up to menu_execute_active_handler() should call drupal_site_offline().
*/
function drupal_site_offline() {
drupal_deliver_page(MENU_SITE_OFFLINE);
}

/**
* Delivers a "page not found" error to the browser.
*
* Page callback functions wanting to report a "page not found" message should
* return MENU_NOT_FOUND instead of calling drupal_not_found(). However,
* functions that are invoked in contexts where that return value might not
* bubble up to menu_execute_active_handler() should call drupal_not_found().
*/
function drupal_not_found() {
core_log('Page Not Found.', false, 'E');
drupal_deliver_page(MENU_NOT_FOUND);
}

/**
* Delivers an "access denied" error to the browser.
*
* Page callback functions wanting to report an "access denied" message should
* return MENU_ACCESS_DENIED instead of calling drupal_access_denied(). However,
* functions that are invoked in contexts where that return value might not
* bubble up to menu_execute_active_handler() should call
* drupal_access_denied().
*/
function drupal_access_denied() {
core_log('Access Denied.', false, 'E');
drupal_deliver_page(MENU_ACCESS_DENIED);
}

/**
* Performs an HTTP request.
*
* This is a flexible and powerful HTTP client implementation. Correctly
* handles GET, POST, PUT or any other HTTP requests. Handles redirects.
*
* @param $url
* A string containing a fully qualified URI.
* @param array $options
* (optional) An array that can have one or more of the following elements:
* - headers: An array containing request headers to send as name/value pairs.
* - method: A string containing the request method. Defaults to 'GET'.
* - data: A string containing the request body, formatted as
* 'param=value&param=value&...'; to generate this, use http_build_query().
* Defaults to NULL.
* - max_redirects: An integer representing how many times a redirect
* may be followed. Defaults to 3.
* - timeout: A float representing the maximum number of seconds the function
* call may take. The default is 30 seconds. If a timeout occurs, the error
* code is set to the HTTP_REQUEST_TIMEOUT constant.
* - context: A context resource created with stream_context_create().
*
* @return object
* An object that can have one or more of the following components:
* - request: A string containing the request body that was sent.
* - code: An integer containing the response status code, or the error code
* if an error occurred.
* - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
* - status_message: The status message from the response, if a response was
* received.
* - redirect_code: If redirected, an integer containing the initial response
* status code.
* - redirect_url: If redirected, a string containing the URL of the redirect
* target.
* - error: If an error occurred, the error message. Otherwise not set.
* - headers: An array containing the response headers as name/value pairs.
* HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
* easy access the array keys are returned in lower case.
* - data: A string containing the response body that was received.
*
* @see http_build_query()
*/
function drupal_http_request($url, array $options = array()) {
// Allow an alternate HTTP client library to replace Drupal's default
// implementation.
$override_function = variable_get('drupal_http_request_function', FALSE);
if (!empty($override_function) && function_exists($override_function)) {
return $override_function($url, $options);
}

$result = new stdClass();

// Parse the URL and make sure we can handle the schema.
$uri = @parse_url($url);

if ($uri == FALSE) {
$result->error = 'unable to parse URL';
$result->code = -1001;
return $result;
}

if (!isset($uri['scheme'])) {
$result->error = 'missing schema';
$result->code = -1002;
return $result;
}

timer_start(__FUNCTION__);

// Merge the default options.
$options += array(
'headers' => array(),
'method' => 'GET',
'data' => NULL,
'max_redirects' => 3,
'timeout' => 30.0,
'context' => NULL,
);

// Merge the default headers.
$options['headers'] += array(
'User-Agent' => 'Drupal (+http://drupal.org/)',
);

// stream_socket_client() requires timeout to be a float.
$options['timeout'] = (float) $options['timeout'];

// Use a proxy if one is defined and the host is not on the excluded list.
$proxy_server = variable_get('proxy_server', '');
if ($proxy_server && _drupal_http_use_proxy($uri['host'])) {
// Set the scheme so we open a socket to the proxy server.
$uri['scheme'] = 'proxy';
// Set the path to be the full URL.
$uri['path'] = $url;
// Since the URL is passed as the path, we won't use the parsed query.
unset($uri['query']);

// Add in username and password to Proxy-Authorization header if needed.
if ($proxy_username = variable_get('proxy_username', '')) {
$proxy_password = variable_get('proxy_password', '');
$options['headers']['Proxy-Authorization'] = 'Basic ' . base64_encode($proxy_username . (!empty($proxy_password) ? ":" . $proxy_password : ''));
}
// Some proxies reject requests with any User-Agent headers, while others
// require a specific one.
$proxy_user_agent = variable_get('proxy_user_agent', '');
// The default value matches neither condition.
if ($proxy_user_agent === NULL) {
unset($options['headers']['User-Agent']);
} elseif ($proxy_user_agent) {
$options['headers']['User-Agent'] = $proxy_user_agent;
}
}

switch ($uri['scheme']) {
case 'proxy':
// Make the socket connection to a proxy server.
$socket = 'tcp://' . $proxy_server . ':' . variable_get('proxy_port', 8080);
// The Host header still needs to match the real request.
$options['headers']['Host'] = $uri['host'];
$options['headers']['Host'] .= isset($uri['port']) && $uri['port'] != 80 ? ':' . $uri['port'] : '';
break;

case 'http':
case 'feed':
$port = isset($uri['port']) ? $uri['port'] : 80;
$socket = 'tcp://' . $uri['host'] . ':' . $port;
// RFC 2616: "non-standard ports MUST, default ports MAY be included".
// We don't add the standard port to prevent from breaking rewrite rules
// checking the host that do not take into account the port number.
$options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
break;

case 'https':
// Note: Only works when PHP is compiled with OpenSSL support.
$port = isset($uri['port']) ? $uri['port'] : 443;
$socket = 'ssl://' . $uri['host'] . ':' . $port;
$options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
break;

default:
$result->error = 'invalid schema ' . $uri['scheme'];
$result->code = -1003;
return $result;
}

if (empty($options['context'])) {
$fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
} else {
// Create a stream with context. Allows verification of a SSL certificate.
$fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
}

// Make sure the socket opened properly.
if (!$fp) {
// When a network error occurs, we use a negative number so it does not
// clash with the HTTP status codes.
$result->code = -$errno;
$result->error = trim($errstr) ? trim($errstr) : t('Error opening socket @socket', array('@socket' => $socket));

// Mark that this request failed. This will trigger a check of the web
// server's ability to make outgoing HTTP requests the next time that
// requirements checking is performed.
// See system_requirements().
variable_set('drupal_http_request_fails', TRUE);

return $result;
}

// Construct the path to act on.
$path = isset($uri['path']) ? $uri['path'] : '/';
if (isset($uri['query'])) {
$path .= '?' . $uri['query'];
}

// Only add Content-Length if we actually have any content or if it is a POST
// or PUT request. Some non-standard servers get confused by Content-Length in
// at least HEAD/GET requests, and Squid always requires Content-Length in
// POST/PUT requests.
$content_length = strlen($options['data']);
if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
$options['headers']['Content-Length'] = $content_length;
}

// If the server URL has a user then attempt to use basic authentication.
if (isset($uri['user'])) {
$options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
}

// If the database prefix is being used by SimpleTest to run the tests in a copied
// database then set the user-agent header to the database prefix so that any
// calls to other Drupal pages will run the SimpleTest prefixed database. The
// user-agent is used to ensure that multiple testing sessions running at the
// same time won't interfere with each other as they would if the database
// prefix were stored statically in a file or database variable.
$test_info = &$GLOBALS['drupal_test_info'];
if (!empty($test_info['test_run_id'])) {
$options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
}

$request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
foreach ($options['headers'] as $name => $value) {
$request .= $name . ': ' . trim($value) . "\r\n";
}
$request .= "\r\n" . $options['data'];
$result->request = $request;
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
if ($timeout > 0) {
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
fwrite($fp, $request);
}

// Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
// and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
// instead must invoke stream_get_meta_data() each iteration.
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'];
$response = '';

while ($alive) {
// Calculate how much time is left of the original timeout value.
$timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
if ($timeout <= 0) {
$info['timed_out'] = TRUE;
break;
}
stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
$chunk = fread($fp, 1024);
$response .= $chunk;
$info = stream_get_meta_data($fp);
$alive = !$info['eof'] && !$info['timed_out'] && $chunk;
}
fclose($fp);

if ($info['timed_out']) {
$result->code = HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
return $result;
}
// Parse response headers from the response body.
// Be tolerant of malformed HTTP responses that separate header and body with
// \n\n or \r\r instead of \r\n\r\n.
list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
$response = preg_split("/\r\n|\n|\r/", $response);

// Parse the response status line.
$response_status_array = _drupal_parse_response_status(trim(array_shift($response)));
$result->protocol = $response_status_array['http_version'];
$result->status_message = $response_status_array['reason_phrase'];
$code = $response_status_array['response_code'];

$result->headers = array();

// Parse the response headers.
while ($line = trim(array_shift($response))) {
list($name, $value) = explode(':', $line, 2);
$name = strtolower($name);
if (isset($result->headers[$name]) && $name == 'set-cookie') {
// RFC 2109: the Set-Cookie response header comprises the token Set-
// Cookie:, followed by a comma-separated list of one or more cookies.
$result->headers[$name] .= ',' . trim($value);
} else {
$result->headers[$name] = trim($value);
}
}

$responses = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
);
// RFC 2616 states that all unknown HTTP codes must be treated the same as the
// base code in their class.
if (!isset($responses[$code])) {
$code = floor($code / 100) * 100;
}
$result->code = $code;

switch ($code) {
case 200: // OK
case 201: // Created
case 202: // Accepted
case 203: // Non-Authoritative Information
case 204: // No Content
case 205: // Reset Content
case 206: // Partial Content
case 304: // Not modified
break;
case 301: // Moved permanently
case 302: // Moved temporarily
case 307: // Moved temporarily
$location = $result->headers['location'];
$options['timeout'] -= timer_read(__FUNCTION__) / 1000;
if ($options['timeout'] <= 0) {
$result->code = HTTP_REQUEST_TIMEOUT;
$result->error = 'request timed out';
} elseif ($options['max_redirects']) {
// Redirect to the new location.
$options['max_redirects'] --;
$result = drupal_http_request($location, $options);
$result->redirect_code = $code;
}
if (!isset($result->redirect_url)) {
$result->redirect_url = $location;
}
break;
default:
$result->error = $result->status_message;
}

return $result;
}

/**
* Splits an HTTP response status line into components.
*
* See the @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html status line definition @endlink
* in RFC 2616.
*
* @param string $respone
* The response status line, for example 'HTTP/1.1 500 Internal Server Error'.
*
* @return array
* Keyed array containing the component parts. If the response is malformed,
* all possible parts will be extracted. 'reason_phrase' could be empty.
* Possible keys:
* - 'http_version'
* - 'response_code'
* - 'reason_phrase'
*/
function _drupal_parse_response_status($response) {
$response_array = explode(' ', trim($response), 3);
// Set up empty values.
$result = array(
'reason_phrase' => '',
);
$result['http_version'] = $response_array[0];
$result['response_code'] = $response_array[1];
if (isset($response_array[2])) {
$result['reason_phrase'] = $response_array[2];
}
return $result;
}

/**
* Helper function for determining hosts excluded from needing a proxy.
*
* @return
* TRUE if a proxy should be used for this host.
*/
function _drupal_http_use_proxy($host) {
$proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
return !in_array(strtolower($host), $proxy_exceptions, TRUE);
}

/**
* @} End of "HTTP handling".
*/

/**
* Strips slashes from a string or array of strings.
*
* Callback for array_walk() within fix_gpx_magic().
*
* @param $item
* An individual string or array of strings from superglobals.
*/
function _fix_gpc_magic(&$item) {
if (is_array($item)) {
array_walk($item, '_fix_gpc_magic');
} else {
$item = stripslashes($item);
}
}

/**
* Strips slashes from $_FILES items.
*
* Callback for array_walk() within fix_gpc_magic().
*
* The tmp_name key is skipped keys since PHP generates single backslashes for
* file paths on Windows systems.
*
* @param $item
* An item from $_FILES.
* @param $key
* The key for the item within $_FILES.
*
* @see http://php.net/manual/features.file-upload.php#42280
*/
function _fix_gpc_magic_files(&$item, $key) {
if ($key != 'tmp_name') {
if (is_array($item)) {
array_walk($item, '_fix_gpc_magic_files');
} else {
$item = stripslashes($item);
}
}
}

/**
* Fixes double-escaping caused by "magic quotes" in some PHP installations.
*
* @see _fix_gpc_magic()
* @see _fix_gpc_magic_files()
*/
function fix_gpc_magic() {
static $fixed = FALSE;
if (!$fixed && ini_get('magic_quotes_gpc')) {
array_walk($_GET, '_fix_gpc_magic');
array_walk($_POST, '_fix_gpc_magic');
array_walk($_COOKIE, '_fix_gpc_magic');
array_walk($_REQUEST, '_fix_gpc_magic');
array_walk($_FILES, '_fix_gpc_magic_files');
}
$fixed = TRUE;
}

/**
* @defgroup validation Input validation
* @{
* Functions to validate user input.
*/

/**
* Verifies the syntax of the given e-mail address.
*
* This uses the
* @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
*
* @param $mail
* A string containing an e-mail address.
*
* @return
* TRUE if the address is in a valid format.
*/
function valid_email_address($mail) {
return (bool) filter_var($mail, FILTER_VALIDATE_EMAIL);
}

/**
* Verifies the syntax of the given URL.
*
* This function should only be used on actual URLs. It should not be used for
* Drupal menu paths, which can contain arbitrary characters.
* Valid values per RFC 3986.
* @param $url
* The URL to verify.
* @param $absolute
* Whether the URL is absolute (beginning with a scheme such as "http:").
*
* @return
* TRUE if the URL is in a valid format.
*/
function valid_url($url, $absolute = FALSE) {
if ($absolute) {
return (bool) preg_match("
/^ # Start at the beginning of the text
(?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
(?: # Userinfo (optional) which is typically
(?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
(?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
)?
(?:
(?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
|(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
)
(?::[0-9]+)? # Server port number (optional)
(?:[\/|\?]
(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
*)?
$/xi", $url);
} else {
return (bool) preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
}
}

/**
* @} End of "defgroup validation".
*/

/**
* Registers an event for the current visitor to the flood control mechanism.
*
* @param $name
* The name of an event.
* @param $window
* Optional number of seconds before this event expires. Defaults to 3600 (1
* hour). Typically uses the same value as the flood_is_allowed() $window
* parameter. Expired events are purged on cron run to prevent the flood table
* from growing indefinitely.
* @param $identifier
* Optional identifier (defaults to the current user's IP address).
*/
function flood_register_event($name, $window = 3600, $identifier = NULL) {
if (!isset($identifier)) {
$identifier = ip_address();
}
db_insert('flood')
->fields(array(
'event' => $name,
'identifier' => $identifier,
'timestamp' => REQUEST_TIME,
'expiration' => REQUEST_TIME + $window,
))
->execute();
}

/**
* Makes the flood control mechanism forget an event for the current visitor.
*
* @param $name
* The name of an event.
* @param $identifier
* Optional identifier (defaults to the current user's IP address).
*/
function flood_clear_event($name, $identifier = NULL) {
if (!isset($identifier)) {
$identifier = ip_address();
}
db_delete('flood')
->condition('event', $name)
->condition('identifier', $identifier)
->execute();
}

/**
* Checks whether a user is allowed to proceed with the specified event.
*
* Events can have thresholds saying that each user can only do that event
* a certain number of times in a time window. This function verifies that the
* current user has not exceeded this threshold.
*
* @param $name
* The unique name of the event.
* @param $threshold
* The maximum number of times each user can do this event per time window.
* @param $window
* Number of seconds in the time window for this event (default is 3600
* seconds, or 1 hour).
* @param $identifier
* Unique identifier of the current user. Defaults to their IP address.
*
* @return
* TRUE if the user is allowed to proceed. FALSE if they have exceeded the
* threshold and should not be allowed to proceed.
*/
function flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) {
if (!isset($identifier)) {
$identifier = ip_address();
}
$number = db_query("SELECT COUNT(*) FROM {flood} WHERE event = :event AND identifier = :identifier AND timestamp > :timestamp", array(
':event' => $name,
':identifier' => $identifier,
':timestamp' => REQUEST_TIME - $window))
->fetchField();
return ($number < $threshold);
}

/**
* @defgroup sanitization Sanitization functions
* @{
* Functions to sanitize values.
*
* See http://drupal.org/writing-secure-code for information
* on writing secure code.
*/

/**
* Strips dangerous protocols (e.g. 'javascript:') from a URI.
*
* This function must be called for all URIs within user-entered input prior
* to being output to an HTML attribute value. It is often called as part of
* check_url() or filter_xss(), but those functions return an HTML-encoded
* string, so this function can be called independently when the output needs to
* be a plain-text string for passing to t(), l(), drupal_attributes(), or
* another function that will call check_plain() separately.
*
* @param $uri
* A plain-text URI that might contain dangerous protocols.
*
* @return
* A plain-text URI stripped of dangerous protocols. As with all plain-text
* strings, this return value must not be output to an HTML page without
* check_plain() being called on it. However, it can be passed to functions
* expecting plain-text strings.
*
* @see check_url()
*/
function drupal_strip_dangerous_protocols($uri) {
static $allowed_protocols;

if (!isset($allowed_protocols)) {
$allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal')));
}

// Iteratively remove any invalid protocol found.
do {
$before = $uri;
$colonpos = strpos($uri, ':');
if ($colonpos > 0) {
// We found a colon, possibly a protocol. Verify.
$protocol = substr($uri, 0, $colonpos);
// If a colon is preceded by a slash, question mark or hash, it cannot
// possibly be part of the URL scheme. This must be a relative URL, which
// inherits the (safe) protocol of the base document.
if (preg_match('![/?#]!', $protocol)) {
break;
}
// Check if this is a disallowed protocol. Per RFC2616, section 3.2.3
// (URI Comparison) scheme comparison must be case-insensitive.
if (!isset($allowed_protocols[strtolower($protocol)])) {
$uri = substr($uri, $colonpos + 1);
}
}
} while ($before != $uri);

return $uri;
}

/**
* Strips dangerous protocols from a URI and encodes it for output to HTML.
*
* @param $uri
* A plain-text URI that might contain dangerous protocols.
*
* @return
* A URI stripped of dangerous protocols and encoded for output to an HTML
* attribute value. Because it is already encoded, it should not be set as a
* value within a $attributes array passed to drupal_attributes(), because
* drupal_attributes() expects those values to be plain-text strings. To pass
* a filtered URI to drupal_attributes(), call
* drupal_strip_dangerous_protocols() instead.
*
* @see drupal_strip_dangerous_protocols()
*/
function check_url($uri) {
return check_plain(drupal_strip_dangerous_protocols($uri));
}

/**
* Applies a very permissive XSS/HTML filter for admin-only use.
*
* Use only for fields where it is impractical to use the
* whole filter system, but where some (mainly inline) mark-up
* is desired (so check_plain() is not acceptable).
*
* Allows all tags that can be used inside an HTML body, save
* for scripts and styles.
*/
function filter_xss_admin($string) {
return filter_xss($string, array('a', 'abbr', 'acronym', 'address', 'article', 'aside', 'b', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'command', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'menu', 'meter', 'nav', 'ol', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'tt', 'u', 'ul', 'var', 'wbr'));
}

/**
* Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities.
*
* Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses.
* For examples of various XSS attacks, see: http://ha.ckers.org/xss.html.
*
* This code does four things:
* - Removes characters and constructs that can trick browsers.
* - Makes sure all HTML entities are well-formed.
* - Makes sure all HTML tags and attributes are well-formed.
* - Makes sure no HTML tags contain URLs with a disallowed protocol (e.g.
* javascript:).
*
* @param $string
* The string with raw HTML in it. It will be stripped of everything that can
* cause an XSS attack.
* @param $allowed_tags
* An array of allowed tags.
*
* @return
* An XSS safe version of $string, or an empty string if $string is not
* valid UTF-8.
*
* @see drupal_validate_utf8()
*/
function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')) {
// Only operate on valid UTF-8 strings. This is necessary to prevent cross
// site scripting issues on Internet Explorer 6.
if (!drupal_validate_utf8($string)) {
return '';
}
// Store the text format.
_filter_xss_split($allowed_tags, TRUE);
// Remove NULL characters (ignored by some browsers).
$string = str_replace(chr(0), '', $string);
// Remove Netscape 4 JS entities.
$string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);

// Defuse all HTML entities.
$string = str_replace('&', '&amp;', $string);
// Change back only well-formed entities in our whitelist:
// Decimal numeric entities.
$string = preg_replace('/&amp;#([0-9]+;)/', '&#\1', $string);
// Hexadecimal numeric entities.
$string = preg_replace('/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);
// Named entities.
$string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);

return preg_replace_callback('%
(
<(?=[^a-zA-Z!/]) # a lone <
| # or
<!--.*?--> # a comment
| # or
<[^>]*(>|$) # a string that starts with a <, up until the > or the end of the string
| # or
> # just a >
)%x', '_filter_xss_split', $string);
}

/**
* Processes an HTML tag.
*
* @param $m
* An array with various meaning depending on the value of $store.
* If $store is TRUE then the array contains the allowed tags.
* If $store is FALSE then the array has one element, the HTML tag to process.
* @param $store
* Whether to store $m.
*
* @return
* If the element isn't allowed, an empty string. Otherwise, the cleaned up
* version of the HTML element.
*/
function _filter_xss_split($m, $store = FALSE) {
static $allowed_html;

if ($store) {
$allowed_html = array_flip($m);
return;
}

$string = $m[1];

if (substr($string, 0, 1) != '<') {
// We matched a lone ">" character.
return '&gt;';
} elseif (strlen($string) == 1) {
// We matched a lone "<" character.
return '&lt;';
}

if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9\-]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
// Seriously malformed.
return '';
}

$slash = trim($matches[1]);
$elem = &$matches[2];
$attrlist = &$matches[3];
$comment = &$matches[4];

if ($comment) {
$elem = '!--';
}

if (!isset($allowed_html[strtolower($elem)])) {
// Disallowed HTML element.
return '';
}

if ($comment) {
return $comment;
}

if ($slash != '') {
return "</$elem>";
}

// Is there a closing XHTML slash at the end of the attributes?
$attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
$xhtml_slash = $count ? ' /' : '';

// Clean up attributes.
$attr2 = implode(' ', _filter_xss_attributes($attrlist));
$attr2 = preg_replace('/[<>]/', '', $attr2);
$attr2 = strlen($attr2) ? ' ' . $attr2 : '';

return "<$elem$attr2$xhtml_slash>";
}

/**
* Processes a string of HTML attributes.
*
* @return
* Cleaned up version of the HTML attributes.
*/
function _filter_xss_attributes($attr) {
$attrarr = array();
$mode = 0;
$attrname = '';

while (strlen($attr) != 0) {
// Was the last operation successful?
$working = 0;

switch ($mode) {
case 0:
// Attribute name, href for instance.
if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
$attrname = strtolower($match[1]);
$skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
$working = $mode = 1;
$attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
}
break;

case 1:
// Equals sign or valueless ("selected").
if (preg_match('/^\s*=\s*/', $attr)) {
$working = 1;
$mode = 2;
$attr = preg_replace('/^\s*=\s*/', '', $attr);
break;
}

if (preg_match('/^\s+/', $attr)) {
$working = 1;
$mode = 0;
if (!$skip) {
$attrarr[] = $attrname;
}
$attr = preg_replace('/^\s+/', '', $attr);
}
break;

case 2:
// Attribute value, a URL after href= for instance.
if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
$thisval = filter_xss_bad_protocol($match[1]);

if (!$skip) {
$attrarr[] = "$attrname=\"$thisval\"";
}
$working = 1;
$mode = 0;
$attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
break;
}

if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) {
$thisval = filter_xss_bad_protocol($match[1]);

if (!$skip) {
$attrarr[] = "$attrname='$thisval'";
}
$working = 1;
$mode = 0;
$attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
break;
}

if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) {
$thisval = filter_xss_bad_protocol($match[1]);

if (!$skip) {
$attrarr[] = "$attrname=\"$thisval\"";
}
$working = 1;
$mode = 0;
$attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
}
break;
}

if ($working == 0) {
// Not well formed; remove and try again.
$attr = preg_replace('/
^
(
"[^"]*("|$) # - a string that starts with a double quote, up until the next double quote or the end of the string
| # or
\'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
| # or
\S # - a non-whitespace character
)* # any number of the above three
\s* # any number of whitespaces
/x', '', $attr);
$mode = 0;
}
}

// The attribute list ends with a valueless attribute like "selected".
if ($mode == 1 && !$skip) {
$attrarr[] = $attrname;
}
return $attrarr;
}

/**
* Processes an HTML attribute value and strips dangerous protocols from URLs.
*
* @param $string
* The string with the attribute value.
* @param $decode
* (deprecated) Whether to decode entities in the $string. Set to FALSE if the
* $string is in plain text, TRUE otherwise. Defaults to TRUE. This parameter
* is deprecated and will be removed in Drupal 8. To process a plain-text URI,
* call drupal_strip_dangerous_protocols() or check_url() instead.
*
* @return
* Cleaned up and HTML-escaped version of $string.
*/
function filter_xss_bad_protocol($string, $decode = TRUE) {
// Get the plain text representation of the attribute value (i.e. its meaning).
// @todo Remove the $decode parameter in Drupal 8, and always assume an HTML
// string that needs decoding.
if ($decode) {
if (!function_exists('decode_entities')) {
require_once DRUPAL_ROOT . '/includes/unicode.inc';
}

$string = decode_entities($string);
}
return check_plain(drupal_strip_dangerous_protocols($string));
}

/**
* @} End of "defgroup sanitization".
*/
/**
* @defgroup format Formatting
* @{
* Functions to format numbers, strings, dates, etc.
*/

/**
* Formats an RSS channel.
*
* Arbitrary elements may be added using the $args associative array.
*/
function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
global $language_content;
$langcode = $langcode ? $langcode : $language_content->language;

$output = "<channel>\n";
$output .= ' <title>' . check_plain($title) . "</title>\n";
$output .= ' <link>' . check_url($link) . "</link>\n";

// The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
// We strip all HTML tags, but need to prevent double encoding from properly
// escaped source data (such as &amp becoming &amp;amp;).
$output .= ' <description>' . check_plain(decode_entities(strip_tags($description))) . "</description>\n";
$output .= ' <language>' . check_plain($langcode) . "</language>\n";
$output .= format_xml_elements($args);
$output .= $items;
$output .= "</channel>\n";

return $output;
}

/**
* Formats a single RSS item.
*
* Arbitrary elements may be added using the $args associative array.
*/
function format_rss_item($title, $link, $description, $args = array()) {
$output = "<item>\n";
$output .= ' <title>' . check_plain($title) . "</title>\n";
$output .= ' <link>' . check_url($link) . "</link>\n";
$output .= ' <description>' . check_plain($description) . "</description>\n";
$output .= format_xml_elements($args);
$output .= "</item>\n";

return $output;
}

/**
* Formats XML elements.
*
* @param $array
* An array where each item represents an element and is either a:
* - (key => value) pair (<key>value</key>)
* - Associative array with fields:
* - 'key': element name
* - 'value': element contents
* - 'attributes': associative array of element attributes
* - 'encoded': TRUE if 'value' is already encoded
*
* In both cases, 'value' can be a simple string, or it can be another array
* with the same format as $array itself for nesting.
*
* If 'encoded' is TRUE it is up to the caller to ensure that 'value' is either
* entity-encoded or CDATA-escaped. Using this option is not recommended when
* working with untrusted user input, since failing to escape the data
* correctly has security implications.
*/
function format_xml_elements($array) {
$output = '';
foreach ($array as $key => $value) {
if (is_numeric($key)) {
if ($value['key']) {
$output .= ' <' . $value['key'];
if (isset($value['attributes']) && is_array($value['attributes'])) {
$output .= drupal_attributes($value['attributes']);
}

if (isset($value['value']) && $value['value'] != '') {
$output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : (!empty($value['encoded']) ? $value['value'] : check_plain($value['value']))) . '</' . $value['key'] . ">\n";
} else {
$output .= " />\n";
}
}
} else {
$output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
}
}
return $output;
}

/**
* Formats a string containing a count of items.
*
* This function ensures that the string is pluralized correctly. Since t() is
* called by this function, make sure not to pass already-localized strings to
* it.
*
* For example:
* @code
* $output = format_plural($node->comment_count, '1 comment', '@count comments');
* @endcode
*
* Example with additional replacements:
* @code
* $output = format_plural($update_count,
* 'Changed the content type of 1 post from %old-type to %new-type.',
* 'Changed the content type of @count posts from %old-type to %new-type.',
* array('%old-type' => $info->old_type, '%new-type' => $info->new_type));
* @endcode
*
* @param $count
* The item count to display.
* @param $singular
* The string for the singular case. Make sure it is clear this is singular,
* to ease translation (e.g. use "1 new comment" instead of "1 new"). Do not
* use @count in the singular string.
* @param $plural
* The string for the plural case. Make sure it is clear this is plural, to
* ease translation. Use @count in place of the item count, as in
* "@count new comments".
* @param $args
* An associative array of replacements to make after translation. Instances
* of any key in this array are replaced with the corresponding value.
* Based on the first character of the key, the value is escaped and/or
* themed. See format_string(). Note that you do not need to include @count
* in this array; this replacement is done automatically for the plural case.
* @param $options
* An associative array of additional options. See t() for allowed keys.
*
* @return
* A translated string.
*
* @see t()
* @see format_string()
*/
function format_plural($count, $singular, $plural, array $args = array(), array $options = array()) {
$args['@count'] = $count;
if ($count == 1) {
return t($singular, $args, $options);
}

// Get the plural index through the gettext formula.
$index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
// If the index cannot be computed, use the plural as a fallback (which
// allows for most flexiblity with the replaceable @count value).
if ($index < 0) {
return t($plural, $args, $options);
} else {
switch ($index) {
case "0":
return t($singular, $args, $options);
case "1":
return t($plural, $args, $options);
default:
unset($args['@count']);
$args['@count[' . $index . ']'] = $count;
return t(strtr($plural, array('@count' => '@count[' . $index . ']')), $args, $options);
}
}
}

/**
* Parses a given byte count.
*
* @param $size
* A size expressed as a number of bytes with optional SI or IEC binary unit
* prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
*
* @return
* An integer representation of the size in bytes.
*/
function parse_size($size) {
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
$size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
if ($unit) {
// Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
return round($size * pow(DRUPAL_KILOBYTE, stripos('bkmgtpezy', $unit[0])));
} else {
return round($size);
}
}

/**
* Generates a string representation for the given byte count.
*
* @param $size
* A size in bytes.
* @param $langcode
* Optional language code to translate to a language other than what is used
* to display the page.
*
* @return
* A translated string representation of the size.
*/
function format_size($size, $langcode = NULL) {
if ($size < DRUPAL_KILOBYTE) {
return format_plural($size, '1 byte', '@count bytes', array(), array('langcode' => $langcode));
} else {
$size = $size / DRUPAL_KILOBYTE; // Convert bytes to kilobytes.
$units = array(
t('@size KB', array(), array('langcode' => $langcode)),
t('@size MB', array(), array('langcode' => $langcode)),
t('@size GB', array(), array('langcode' => $langcode)),
t('@size TB', array(), array('langcode' => $langcode)),
t('@size PB', array(), array('langcode' => $langcode)),
t('@size EB', array(), array('langcode' => $langcode)),
t('@size ZB', array(), array('langcode' => $langcode)),
t('@size YB', array(), array('langcode' => $langcode)),
);
foreach ($units as $unit) {
if (round($size, 2) >= DRUPAL_KILOBYTE) {
$size = $size / DRUPAL_KILOBYTE;
} else {
break;
}
}
return str_replace('@size', round($size, 2), $unit);
}
}

/**
* Formats a time interval with the requested granularity.
*
* @param $interval
* The length of the interval in seconds.
* @param $granularity
* How many different units to display in the string.
* @param $langcode
* Optional language code to translate to a language other than
* what is used to display the page.
*
* @return
* A translated string representation of the interval.
*/
function format_interval($interval, $granularity = 2, $langcode = NULL) {
$units = array(
'1 year|@count years' => 31536000,
'1 month|@count months' => 2592000,
'1 week|@count weeks' => 604800,
'1 day|@count days' => 86400,
'1 hour|@count hours' => 3600,
'1 min|@count min' => 60,
'1 sec|@count sec' => 1
);
$output = '';
foreach ($units as $key => $value) {
$key = explode('|', $key);
if ($interval >= $value) {
$output .= ($output ? ' ' : '') . format_plural(floor($interval / $value), $key[0], $key[1], array(), array('langcode' => $langcode));
$interval %= $value;
$granularity--;
}

if ($granularity == 0) {
break;
}
}
return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
}

/**
* Formats a date, using a date type or a custom date format string.
*
* @param $timestamp
* A UNIX timestamp to format.
* @param $type
* (optional) The format to use, one of:
* - 'short', 'medium', or 'long' (the corresponding built-in date formats).
* - The name of a date type defined by a module in hook_date_format_types(),
* if it's been assigned a format.
* - The machine name of an administrator-defined date format.
* - 'custom', to use $format.
* Defaults to 'medium'.
* @param $format
* (optional) If $type is 'custom', a PHP date format string suitable for
* input to date(). Use a backslash to escape ordinary text, so it does not
* get interpreted as date format characters.
* @param $timezone
* (optional) Time zone identifier, as described at
* http://php.net/manual/timezones.php Defaults to the time zone used to
* display the page.
* @param $langcode
* (optional) Language code to translate to. Defaults to the language used to
* display the page.
*
* @return
* A translated date string in the requested format.
*/
function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
// Use the advanced drupal_static() pattern, since this is called very often.
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
$drupal_static_fast['timezones'] = &drupal_static(__FUNCTION__);
}
$timezones = &$drupal_static_fast['timezones'];

if (!isset($timezone)) {
$timezone = date_default_timezone_get();
}
// Store DateTimeZone objects in an array rather than repeatedly
// constructing identical objects over the life of a request.
if (!isset($timezones[$timezone])) {
$timezones[$timezone] = timezone_open($timezone);
}

// Use the default langcode if none is set.
global $language;
if (empty($langcode)) {
$langcode = isset($language->language) ? $language->language : 'en';
}

switch ($type) {
case 'short':
$format = variable_get('date_format_short', 'm/d/Y - H:i');
break;

case 'long':
$format = variable_get('date_format_long', 'l, F j, Y - H:i');
break;

case 'custom':
// No change to format.
break;

case 'medium':
default:
// Retrieve the format of the custom $type passed.
if ($type != 'medium') {
$format = variable_get('date_format_' . $type, '');
}
// Fall back to 'medium'.
if ($format === '') {
$format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
}
break;
}

// Create a DateTime object from the timestamp.
$date_time = date_create('@' . $timestamp);
// Set the time zone for the DateTime object.
date_timezone_set($date_time, $timezones[$timezone]);

// Encode markers that should be translated. 'A' becomes '\xEF\AA\xFF'.
// xEF and xFF are invalid UTF-8 sequences, and we assume they are not in the
// input string.
// Paired backslashes are isolated to prevent errors in read-ahead evaluation.
// The read-ahead expression ensures that A matches, but not \A.
$format = preg_replace(array('/\\\\\\\\/', '/(?<!\\\\)([AaeDlMTF])/'), array("\xEF\\\\\\\\\xFF", "\xEF\\\\\$1\$1\xFF"), $format);

// Call date_format().
$format = date_format($date_time, $format);

// Pass the langcode to _format_date_callback().
_format_date_callback(NULL, $langcode);

// Translate the marked sequences.
return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
}

/**
* Returns an ISO8601 formatted date based on the given date.
*
* Callback for use within hook_rdf_mapping() implementations.
*
* @param $date
* A UNIX timestamp.
*
* @return string
* An ISO8601 formatted date.
*/
function date_iso8601($date) {
// The DATE_ISO8601 constant cannot be used here because it does not match
// date('c') and produces invalid RDF markup.
return date('c', $date);
}

/**
* Translates a formatted date string.
*
* Callback for preg_replace_callback() within format_date().
*/
function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
// We cache translations to avoid redundant and rather costly calls to t().
static $cache, $langcode;

if (!isset($matches)) {
$langcode = $new_langcode;
return;
}

$code = $matches[1];
$string = $matches[2];

if (!isset($cache[$langcode][$code][$string])) {
$options = array(
'langcode' => $langcode,
);

if ($code == 'F') {
$options['context'] = 'Long month name';
}

if ($code == '') {
$cache[$langcode][$code][$string] = $string;
} else {
$cache[$langcode][$code][$string] = t($string, array(), $options);
}
}
return $cache[$langcode][$code][$string];
}

/**
* Format a username.
*
* This is also the label callback implementation of
* callback_entity_info_label() for user_entity_info().
*
* By default, the passed-in object's 'name' property is used if it exists, or
* else, the site-defined value for the 'anonymous' variable. However, a module
* may override this by implementing hook_username_alter(&$name, $account).
*
* @see hook_username_alter()
*
* @param $account
* The account object for the user whose name is to be formatted.
*
* @return
* An unsanitized string with the username to display. The code receiving
* this result must ensure that check_plain() is called on it before it is
* printed to the page.
*/
function format_username($account) {
$name = !empty($account->name) ? $account->name : variable_get('anonymous', t('Anonymous'));
drupal_alter('username', $name, $account);
return $name;
}

/**
* @} End of "defgroup format".
*/

/**
* Generates an internal or external URL.
*
* When creating links in modules, consider whether l() could be a better
* alternative than url().
*
* @param $path
* (optional) The internal path or external URL being linked to, such as
* "node/34" or "http://example.com/foo". The default value is equivalent to
* passing in '<front>'. A few notes:
* - If you provide a full URL, it will be considered an external URL.
* - If you provide only the path (e.g. "node/34"), it will be
* considered an internal link. In this case, it should be a system URL,
* and it will be replaced with the alias, if one exists. Additional query
* arguments for internal paths must be supplied in $options['query'], not
* included in $path.
* - If you provide an internal path and $options['alias'] is set to TRUE, the
* path is assumed already to be the correct path alias, and the alias is
* not looked up.
* - The special string '<front>' generates a link to the site's base URL.
* - If your external URL contains a query (e.g. http://example.com/foo?a=b),
* then you can either URL encode the query keys and values yourself and
* include them in $path, or use $options['query'] to let this function
* URL encode them.
* @param $options
* (optional) An associative array of additional options, with the following
* elements:
* - 'query': An array of query key/value-pairs (without any URL-encoding) to
* append to the URL.
* - 'fragment': A fragment identifier (named anchor) to append to the URL.
* Do not include the leading '#' character.
* - 'absolute': Defaults to FALSE. Whether to force the output to be an
* absolute link (beginning with http:). Useful for links that will be
* displayed outside the site, such as in an RSS feed.
* - 'alias': Defaults to FALSE. Whether the given path is a URL alias
* already.
* - 'external': Whether the given path is an external URL.
* - 'language': An optional language object. If the path being linked to is
* internal to the site, $options['language'] is used to look up the alias
* for the URL. If $options['language'] is omitted, the global $language_url
* will be used.
* - 'https': Whether this URL should point to a secure location. If not
* defined, the current scheme is used, so the user stays on HTTP or HTTPS
* respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can
* only be enforced when the variable 'https' is set to TRUE.
* - 'base_url': Only used internally, to modify the base URL when a language
* dependent URL requires so.
* - 'prefix': Only used internally, to modify the path when a language
* dependent URL requires so.
* - 'script': The script filename in Drupal's root directory to use when
* clean URLs are disabled, such as 'index.php'. Defaults to an empty
* string, as most modern web servers automatically find 'index.php'. If
* clean URLs are disabled, the value of $path is appended as query
* parameter 'q' to $options['script'] in the returned URL. When deploying
* Drupal on a web server that cannot be configured to automatically find
* index.php, then hook_url_outbound_alter() can be implemented to force
* this value to 'index.php'.
* - 'entity_type': The entity type of the object that called url(). Only
* set if url() is invoked by entity_uri().
* - 'entity': The entity object (such as a node) for which the URL is being
* generated. Only set if url() is invoked by entity_uri().
*
* @return
* A string containing a URL to the given path.
*/
function url($path = NULL, array $options = array()) {
// Merge in defaults.
$options += array(
'fragment' => '',
'query' => array(),
'absolute' => FALSE,
'alias' => FALSE,
'prefix' => ''
);


if (!isset($options['external'])) {
$options['external'] = url_is_external($path);
}

// Preserve the original path before altering or aliasing.
$original_path = $path;

// Allow other modules to alter the outbound URL and options.
drupal_alter('url_outbound', $path, $options, $original_path);

if (isset($options['fragment']) && $options['fragment'] !== '') {
$options['fragment'] = '#' . $options['fragment'];
}

if ($options['external']) {
// Split off the fragment.
if (strpos($path, '#') !== FALSE) {
list($path, $old_fragment) = explode('#', $path, 2);
// If $options contains no fragment, take it over from the path.
if (isset($old_fragment) && !$options['fragment']) {
$options['fragment'] = '#' . $old_fragment;
}
}
// Append the query.
if ($options['query']) {
$path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']);
}
if (isset($options['https']) && variable_get('https', FALSE)) {
if ($options['https'] === TRUE) {
$path = str_replace('http://', 'https://', $path);
} elseif ($options['https'] === FALSE) {
$path = str_replace('https://', 'http://', $path);
}
}
// Reassemble.
return $path . $options['fragment'];
}

// Strip leading slashes from internal paths to prevent them becoming external
// URLs without protocol. /example.com should not be turned into
// //example.com.
$path = ltrim($path, '/');

global $base_url, $base_secure_url, $base_insecure_url;

// The base_url might be rewritten from the language rewrite in domain mode.
if (!isset($options['base_url'])) {
if (isset($options['https']) && variable_get('https', FALSE)) {
if ($options['https'] === TRUE) {
$options['base_url'] = $base_secure_url;
$options['absolute'] = TRUE;
} elseif ($options['https'] === FALSE) {
$options['base_url'] = $base_insecure_url;
$options['absolute'] = TRUE;
}
} else {
$options['base_url'] = $base_url;
}
}

// The special path '<front>' links ault front page.
if ($path == '<front>') {
$path = '';
} elseif (!empty($path) && !$options['alias']) {
$language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
$alias = drupal_get_path_alias($original_path, $language);
if ($alias != $original_path) {
$path = $alias;
}
}
$base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
$prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
if (!isset($options['external'])) {
$options['external'] = url_is_external($path);
}

// Preserve the original path before altering or aliasing.
$original_path = $path;

// Allow other modules to alter the outbound URL and options.
drupal_alter('url_outbound', $path, $options, $original_path);

if (isset($options['fragment']) && $options['fragment'] !== '') {
$options['fragment'] = '#' . $options['fragment'];
}

if ($options['external']) {
// Split off the fragment.
if (strpos($path, '#') !== FALSE) {
list($path, $old_fragment) = explode('#', $path, 2);
// If $options contains no fragment, take it over from the path.
if (isset($old_fragment) && !$options['fragment']) {
$options['fragment'] = '#' . $old_fragment;
}
}
// Append the query.
if ($options['query']) {
$path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']);
}
if (isset($options['https']) && variable_get('https', FALSE)) {
if ($options['https'] === TRUE) {
$path = str_replace('http://', 'https://', $path);
} elseif ($options['https'] === FALSE) {
$path = str_replace('https://', 'http://', $path);
}
}
// Reassemble.
return $path . $options['fragment'];
}

// Strip leading slashes from internal paths to prevent them becoming external
// URLs without protocol. /example.com should not be turned into
// //example.com.
$path = ltrim($path, '/');

global $base_url, $base_secure_url, $base_insecure_url;

// The base_url might be rewritten from the language rewrite in domain mode.
if (!isset($options['base_url'])) {
if (isset($options['https']) && variable_get('https', FALSE)) {
if ($options['https'] === TRUE) {
$options['base_url'] = $base_secure_url;
$options['absolute'] = TRUE;
} elseif ($options['https'] === FALSE) {
$options['base_url'] = $base_insecure_url;
$options['absolute'] = TRUE;
}
} else {
$options['base_url'] = $base_url;
}
}

// The special path '<front>' links ault front page.
if ($path == '<front>') {
$path = '';
} elseif (!empty($path) && !$options['alias']) {
$language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
$alias = drupal_get_path_alias($original_path, $language);
if ($alias != $original_path) {
$path = $alias;
}
}
$base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
$prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];


// With Clean URLs.
if (!empty($GLOBALS['conf']['clean_url'])) {

$path = drupal_encode_path($prefix . $path);

//by ugarte menu with option <none>
if ($path == '%3Cnone%3E') {
return '#';
}

if ($options['query']) {
return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
} else {
return $base . $path . $options['fragment'];
}
}

// Without Clean URLs.
else {

$path = $prefix . $path;
$query = array();
if (!empty($path)) {
$query['q'] = $path;
}
if ($options['query']) {
// We do not use array_merge() here to prevent overriding $path via query
// parameters.
$query += $options['query'];
}
$query = $query ? ('?' . drupal_http_build_query($query)) : '';
$script = isset($options['script']) ? $options['script'] : '';
return $base . $script . $query . $options['fragment'];
}
}

/**
* Returns TRUE if a path is external to Drupal (e.g. http://example.com).
*
* If a path cannot be assessed by Drupal's menu handler, then we must
* treat it as potentially insecure.
*
* @param $path
* The internal path or external URL being linked to, such as "node/34" or
* "http://example.com/foo".
*
* @return
* Boolean TRUE or FALSE, where TRUE indicates an external path.
*/
function url_is_external($path) {
$colonpos = strpos($path, ':');
// Some browsers treat \ as / so normalize to forward slashes.
$path = str_replace('\\', '/', $path);
// If the path starts with 2 slashes then it is always considered an external
// URL without an explicit protocol part.
return (strpos($path, '//') === 0)
// Leading control characters may be ignored or mishandled by browsers, so
// assume such a path may lead to an external location. The \p{C} character
// class matches all UTF-8 control, unassigned, and private characters.
|| (preg_match('/^\p{C}/u', $path) !== 0)
// Avoid calling drupal_strip_dangerous_protocols() if there is any slash
// (/), hash (#) or question_mark (?) before the colon (:) occurrence - if
// any - as this would clearly mean it is not a URL.
|| ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && drupal_strip_dangerous_protocols($path) == $path);
}

/**
* Formats an attribute string for an HTTP header.
*
* @param $attributes
* An associative array of attributes such as 'rel'.
*
* @return
* A ; separated string ready for insertion in a HTTP header. No escaping is
* performed for HTML entities, so this string is not safe to be printed.
*
* @see drupal_add_http_header()
*/
function drupal_http_header_attributes(array $attributes = array()) {
foreach ($attributes as $attribute => &$data) {
if (is_array($data)) {
$data = implode(' ', $data);
}
$data = $attribute . '="' . $data . '"';
}
return $attributes ? ' ' . implode('; ', $attributes) : '';
}

/**
* Converts an associative array to an XML/HTML tag attribute string.
*
* Each array key and its value will be formatted into an attribute string.
* If a value is itself an array, then its elements are concatenated to a single
* space-delimited string (for example, a class attribute with multiple values).
*
* Attribute values are sanitized by running them through check_plain().
* Attribute names are not automatically sanitized. When using user-supplied
* attribute names, it is strongly recommended to allow only white-listed names,
* since certain attributes carry security risks and can be abused.
*
* Examples of security aspects when using drupal_attributes:
* @code
* // By running the value in the following statement through check_plain,
* // the malicious script is neutralized.
* drupal_attributes(array('title' => t('<script>steal_cookie();</script>')));
*
* // The statement below demonstrates dangerous use of drupal_attributes, and
* // will return an onmouseout attribute with JavaScript code that, when used
* // as attribute in a tag, will cause users to be redirected to another site.
* //
* // In this case, the 'onmouseout' attribute should not be whitelisted --
* // you don't want users to have the ability to add this attribute or others
* // that take JavaScript commands.
* drupal_attributes(array('onmouseout' => 'window.location="http://malicious.com/";')));
* @endcode
*
* @param $attributes
* An associative array of key-value pairs to be converted to attributes.
*
* @return
* A string ready for insertion in a tag (starts with a space).
*
* @ingroup sanitization
*/
function drupal_attributes(array $attributes = array()) {
foreach ($attributes as $attribute => &$data) {
$data = implode(' ', (array) $data);
$data = $attribute . '="' . check_plain($data) . '"';
}
return $attributes ? ' ' . implode(' ', $attributes) : '';
}

/**
* Formats an internal or external URL link as an HTML anchor tag.
*
* This function correctly handles aliased paths and adds an 'active' class
* attribute to links that point to the current page (for theming), so all
* internal links output by modules should be generated by this function if
* possible.
*
* However, for links enclosed in translatable text you should use t() and
* embed the HTML anchor tag directly in the translated string. For example:
* @code
* t('Visit the <a href="@url">settings</a> page', array('@url' => url('admin')));
* @endcode
* This keeps the context of the link title ('settings' in the example) for
* translators.
*
* @param string $text
* The translated link text for the anchor tag.
* @param string $path
* The internal path or external URL being linked to, such as "node/34" or
* "http://example.com/foo". After the url() function is called to construct
* the URL from $path and $options, the resulting URL is passed through
* check_plain() before it is inserted into the HTML anchor tag, to ensure
* well-formed HTML. See url() for more information and notes.
* @param array $options
* An associative array of additional options. Defaults to an empty array. It
* may contain the following elements.
* - 'attributes': An associative array of HTML attributes to apply to the
* anchor tag. If element 'class' is included, it must be an array; 'title'
* must be a string; other elements are more flexible, as they just need
* to work in a call to drupal_attributes($options['attributes']).
* - 'html' (default FALSE): Whether $text is HTML or just plain-text. For
* example, to make an image tag into a link, this must be set to TRUE, or
* you will see the escaped HTML image tag. $text is not sanitized if
* 'html' is TRUE. The calling function must ensure that $text is already
* safe.
* - 'language': An optional language object. If the path being linked to is
* internal to the site, $options['language'] is used to determine whether
* the link is "active", or pointing to the current page (the language as
* well as the path must match). This element is also used by url().
* - Additional $options elements used by the url() function.
*
* @return string
* An HTML string containing a link to the given path.
*
* @see url()
*/
function l($text, $path, array $options = array()) {
global $language_url;
static $use_theme = NULL;

// Merge in defaults.
$options += array(
'attributes' => array(),
'html' => FALSE,
);

// Append active class.
if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
(empty($options['language']) || $options['language']->language == $language_url->language)) {
$options['attributes']['class'][] = 'active';
}

// Remove all HTML and PHP tags from a tooltip. For best performance, we act only
// if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
$options['attributes']['title'] = strip_tags($options['attributes']['title']);
}

// Determine if rendering of the link is to be done with a theme function
// or the inline default. Inline is faster, but if the theme system has been
// loaded and a module or theme implements a preprocess or process function
// or overrides the theme_link() function, then invoke theme(). Preliminary
// benchmarks indicate that invoking theme() can slow down the l() function
// by 20% or more, and that some of the link-heavy Drupal pages spend more
// than 10% of the total page request time in the l() function.
if (!isset($use_theme) && function_exists('theme')) {
// Allow edge cases to prevent theme initialization and force inline link
// rendering.
if (variable_get('theme_link', TRUE)) {
drupal_theme_initialize();
$registry = theme_get_registry(FALSE);
// We don't want to duplicate functionality that's in theme(), so any
// hint of a module or theme doing anything at all special with the 'link'
// theme hook should simply result in theme() being called. This includes
// the overriding of theme_link() with an alternate function or template,
// the presence of preprocess or process functions, or the presence of
// include files.
$use_theme = !isset($registry['link']['function']) || ($registry['link']['function'] != 'theme_link');
$use_theme = $use_theme || !empty($registry['link']['preprocess functions']) || !empty($registry['link']['process functions']) || !empty($registry['link']['includes']);
} else {
$use_theme = FALSE;
}
}
if ($use_theme) {
return theme('link', array('text' => $text, 'path' => $path, 'options' => $options));
}
// The result of url() is a plain-text URL. Because we are using it here
// in an HTML argument context, we need to encode it properly.
return '<a href="' . check_plain(url($path, $options)) . '"' . drupal_attributes($options['attributes']) . '>' . ($options['html'] ? $text : check_plain($text)) . '</a>';
}

/**
* Delivers a page callback result to the browser in the appropriate format.
*
* This function is most commonly called by menu_execute_active_handler(), but
* can also be called by error conditions such as drupal_not_found(),
* drupal_access_denied(), and drupal_site_offline().
*
* When a user requests a page, index.php calls menu_execute_active_handler(),
* which calls the 'page callback' function registered in hook_menu(). The page
* callback function can return one of:
* - NULL: to indicate no content.
* - An integer menu status constant: to indicate an error condition.
* - A string of HTML content.
* - A renderable array of content.
* Returning a renderable array rather than a string of HTML is preferred,
* because that provides modules with more flexibility in customizing the final
* result.
*
* When the page callback returns its constructed content to
* menu_execute_active_handler(), this function gets called. The purpose of
* this function is to determine the most appropriate 'delivery callback'
* function to route the content to. The delivery callback function then
* sends the content to the browser in the needed format. The default delivery
* callback is drupal_deliver_html_page(), which delivers the content as an HTML
* page, complete with blocks in addition to the content. This default can be
* overridden on a per menu router item basis by setting 'delivery callback' in
* hook_menu() or hook_menu_alter(), and can also be overridden on a per request
* basis in hook_page_delivery_callback_alter().
*
* For example, the same page callback function can be used for an HTML
* version of the page and an Ajax version of the page. The page callback
* function just needs to decide what content is to be returned and the
* delivery callback function will send it as an HTML page or an Ajax
* response, as appropriate.
*
* In order for page callbacks to be reusable in different delivery formats,
* they should not issue any "print" or "echo" statements, but instead just
* return content.
*
* Also note that this function does not perform access checks. The delivery
* callback function specified in hook_menu(), hook_menu_alter(), or
* hook_page_delivery_callback_alter() will be called even if the router item
* access checks fail. This is intentional (it is needed for JSON and other
* purposes), but it has security implications. Do not call this function
* directly unless you understand the security implications, and be careful in
* writing delivery callbacks, so that they do not violate security. See
* drupal_deliver_html_page() for an example of a delivery callback that
* respects security.
*
* @param $page_callback_result
* The result of a page callback. Can be one of:
* - NULL: to indicate no content.
* - An integer menu status constant: to indicate an error condition.
* - A string of HTML content.
* - A renderable array of content.
* @param $default_delivery_callback
* (Optional) If given, it is the name of a delivery function most likely
* to be appropriate for the page request as determined by the calling
* function (e.g., menu_execute_active_handler()). If not given, it is
* determined from the menu router information of the current page.
*
* @see menu_execute_active_handler()
* @see hook_menu()
* @see hook_menu_alter()
* @see hook_page_delivery_callback_alter()
*/
function drupal_deliver_page($page_callback_result, $default_delivery_callback = NULL) {
if (!isset($default_delivery_callback) && ($router_item = menu_get_item())) {
$default_delivery_callback = $router_item['delivery_callback'];
}
$delivery_callback = !empty($default_delivery_callback) ? $default_delivery_callback : 'drupal_deliver_html_page';
// Give modules a chance to alter the delivery callback used, based on
// request-time context (e.g., HTTP request headers).
drupal_alter('page_delivery_callback', $delivery_callback);
if (function_exists($delivery_callback)) {
$delivery_callback($page_callback_result);
} else {
// If a delivery callback is specified, but doesn't exist as a function,
// something is wrong, but don't print anything, since it's not known
// what format the response needs to be in.
watchdog('delivery callback not found', 'callback %callback not found: %q.', array('%callback' => $delivery_callback, '%q' => $_GET['q']), WATCHDOG_ERROR);
}
}

/**
* Packages and sends the result of a page callback to the browser as HTML.
*
* @param $page_callback_result
* The result of a page callback. Can be one of:
* - NULL: to indicate no content.
* - An integer menu status constant: to indicate an error condition.
* - A string of HTML content.
* - A renderable array of content.
*
* @see drupal_deliver_page()
*/
function drupal_deliver_html_page($page_callback_result) {
// Emit the correct charset HTTP header, but not if the page callback
// result is NULL, since that likely indicates that it printed something
// in which case, no further headers may be sent, and not if code running
// for this page request has already set the content type header.
if (isset($page_callback_result) && is_null(drupal_get_http_header('Content-Type'))) {
drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
}

// Send appropriate HTTP-Header for browsers and search engines.
global $language;
drupal_add_http_header('Content-Language', $language->language);

// By default, do not allow the site to be rendered in an iframe on another
// domain, but provide a variable to override this. If the code running for
// this page request already set the X-Frame-Options header earlier, don't
// overwrite it here.
$frame_options = variable_get('x_frame_options', 'SAMEORIGIN');
if ($frame_options && is_null(drupal_get_http_header('X-Frame-Options'))) {
drupal_add_http_header('X-Frame-Options', $frame_options);
}

// Menu status constants are integers; page content is a string or array.
if (is_int($page_callback_result)) {
// @todo: Break these up into separate functions?
switch ($page_callback_result) {
case MENU_NOT_FOUND:
// Print a 404 page.
drupal_add_http_header('Status', '404 Not Found');

watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);

// Check for and return a fast 404 page if configured.
drupal_fast_404();

// Keep old path for reference, and to allow forms to redirect to it.
if (!isset($_GET['destination'])) {
// Make sure that the current path is not interpreted as external URL.
if (!url_is_external($_GET['q'])) {
$_GET['destination'] = $_GET['q'];
}
}

$path = drupal_get_normal_path(variable_get('site_404', ''));
if ($path && $path != $_GET['q']) {
// Custom 404 handler. Set the active item in case there are tabs to
// display, or other dependencies on the path.
menu_set_active_item($path);
$return = menu_execute_active_handler($path, FALSE);
}

if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
// Standard 404 handler.
drupal_set_title(t('Page not found'));
$return = t('The requested page "@path" could not be found.', array('@path' => request_uri()));
}

drupal_set_page_content($return);
$page = element_info('page');
print drupal_render_page($page);
break;

case MENU_ACCESS_DENIED:
// Print a 403 page.
drupal_add_http_header('Status', '403 Forbidden');
watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);

// Keep old path for reference, and to allow forms to redirect to it.
if (!isset($_GET['destination'])) {
// Make sure that the current path is not interpreted as external URL.
if (!url_is_external($_GET['q'])) {
$_GET['destination'] = $_GET['q'];
}
}

$path = drupal_get_normal_path(variable_get('site_403', ''));
if ($path && $path != $_GET['q']) {
// Custom 403 handler. Set the active item in case there are tabs to
// display or other dependencies on the path.
menu_set_active_item($path);
$return = menu_execute_active_handler($path, FALSE);
}

if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
// Standard 403 handler.
drupal_set_title(t('Access denied'));
$return = t('You are not authorized to access this page.');
}

print drupal_render_page($return);
break;

case MENU_SITE_OFFLINE:
// Print a 503 page.
drupal_maintenance_theme();
drupal_add_http_header('Status', '503 Service unavailable');
drupal_set_title(t('Site under maintenance'));
print theme('maintenance_page', array('content' => filter_xss_admin(variable_get('maintenance_mode_message', t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))))));
break;
}
} elseif (isset($page_callback_result)) {
// Print anything besides a menu constant, assuming it's not NULL or
// undefined.
print drupal_render_page($page_callback_result);
}

// Perform end-of-request tasks.
drupal_page_footer();
}

/**
* Performs end-of-request tasks.
*
* This function sets the page cache if appropriate, and allows modules to
* react to the closing of the page by calling hook_exit().
*/
function drupal_page_footer() {
global $user;

module_invoke_all('exit');

// Commit the user session, if needed.
drupal_session_commit();

if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
drupal_serve_page_from_cache($cache);
} else {
ob_flush();
}

_registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
drupal_cache_system_paths();
module_implements_write_cache();
drupal_file_scan_write_cache();
system_run_automated_cron();
}

/**
* Performs end-of-request tasks.
*
* In some cases page requests need to end without calling drupal_page_footer().
* In these cases, call drupal_exit() instead. There should rarely be a reason
* to call exit instead of drupal_exit();
*
* @param $destination
* If this function is called from drupal_goto(), then this argument
* will be a fully-qualified URL that is the destination of the redirect.
* This should be passed along to hook_exit() implementations.
*/
function drupal_exit($destination = NULL) {
if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
module_invoke_all('exit', $destination);
}
drupal_session_commit();
}
exit;
}

/**
* Forms an associative array from a linear array.
*
* This function walks through the provided array and constructs an associative
* array out of it. The keys of the resulting array will be the values of the
* input array. The values will be the same as the keys unless a function is
* specified, in which case the output of the function is used for the values
* instead.
*
* @param $array
* A linear array.
* @param $function
* A name of a function to apply to all values before output.
*
* @return
* An associative array.
*/
function drupal_map_assoc($array, $function = NULL) {
// array_combine() fails with empty arrays:
// http://bugs.php.net/bug.php?id=34857.
$array = !empty($array) ? array_combine($array, $array) : array();
if (is_callable($function)) {
$array = array_map($function, $array);
}
return $array;
}

/**
* Attempts to set the PHP maximum execution time.
*
* This function is a wrapper around the PHP function set_time_limit().
* When called, set_time_limit() restarts the timeout counter from zero.
* In other words, if the timeout is the default 30 seconds, and 25 seconds
* into script execution a call such as set_time_limit(20) is made, the
* script will run for a total of 45 seconds before timing out.
*
* If the current time limit is not unlimited it is possible to decrease the
* total time limit if the sum of the new time limit and the current time spent
* running the script is inferior to the original time limit. It is inherent to
* the way set_time_limit() works, it should rather be called with an
* appropriate value every time you need to allocate a certain amount of time
* to execute a task than only once at the beginning of the script.
*
* Before calling set_time_limit(), we check if this function is available
* because it could be disabled by the server administrator. We also hide all
* the errors that could occur when calling set_time_limit(), because it is
* not possible to reliably ensure that PHP or a security extension will
* not issue a warning/error if they prevent the use of this function.
*
* @param $time_limit
* An integer specifying the new time limit, in seconds. A value of 0
* indicates unlimited execution time.
*
* @ingroup php_wrappers
*/
function drupal_set_time_limit($time_limit) {
if (function_exists('set_time_limit')) {
$current = ini_get('max_execution_time');
// Do not set time limit if it is currently unlimited.
if ($current != 0) {
@set_time_limit($time_limit);
}
}
}

/**
* Returns the path to a system item (module, theme, etc.).
*
* @param $type
* The type of the item (i.e. theme, theme_engine, module, profile).
* @param $name
* The name of the item for which the path is requested.
*
* @return
* The path to the requested item or an empty string if the item is not found.
*/
function drupal_get_path($type, $name) {
return dirname(drupal_get_filename($type, $name));
}

/**
* Returns the base URL path (i.e., directory) of the Drupal installation.
*
* base_path() adds a "/" to the beginning and end of the returned path if the
* path is not empty. At the very least, this will return "/".
*
* Examples:
* - http://example.com returns "/" because the path is empty.
* - http://example.com/drupal/folder returns "/drupal/folder/".
*/
function base_path() {
return $GLOBALS['base_path'];
}

/**
* Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
*
* This function can be called as long the HTML header hasn't been sent, which
* on normal pages is up through the preprocess step of theme('html'). Adding
* a link will overwrite a prior link with the exact same 'rel' and 'href'
* attributes.
*
* @param $attributes
* Associative array of element attributes including 'href' and 'rel'.
* @param $header
* Optional flag to determine if a HTTP 'Link:' header should be sent.
*/
function drupal_add_html_head_link($attributes, $header = FALSE) {
$element = array(
'#tag' => 'link',
'#attributes' => $attributes,
);
$href = $attributes['href'];

if ($header) {
// Also add a HTTP header "Link:".
$href = '<' . check_plain($attributes['href']) . '>;';
unset($attributes['href']);
$element['#attached']['drupal_add_http_header'][] = array('Link', $href . drupal_http_header_attributes($attributes), TRUE);
}

drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
}

/**
* Adds a cascading stylesheet to the stylesheet queue.
*
* Calling drupal_static_reset('drupal_add_css') will clear all cascading
* stylesheets added so far.
*
* If CSS aggregation/compression is enabled, all cascading style sheets added
* with $options['preprocess'] set to TRUE will be merged into one aggregate
* file and compressed by removing all extraneous white space.
* Preprocessed inline stylesheets will not be aggregated into this single file;
* instead, they are just compressed upon output on the page. Externally hosted
* stylesheets are never aggregated or compressed.
*
* The reason for aggregating the files is outlined quite thoroughly here:
* http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
* to request overhead, one bigger file just loads faster than two smaller ones
* half its size."
*
* $options['preprocess'] should be only set to TRUE when a file is required for
* all typical visitors and most pages of a site. It is critical that all
* preprocessed files are added unconditionally on every page, even if the
* files do not happen to be needed on a page. This is normally done by calling
* drupal_add_css() in a hook_init() implementation.
*
* Non-preprocessed files should only be added to the page when they are
* actually needed.
*
* @param $data
* (optional) The stylesheet data to be added, depending on what is passed
* through to the $options['type'] parameter:
* - 'file': The path to the CSS file relative to the base_path(), or a
* stream wrapper URI. For example: "modules/devel/devel.css" or
* "public://generated_css/stylesheet_1.css". Note that Modules should
* always prefix the names of their CSS files with the module name; for
* example, system-menus.css rather than simply menus.css. Themes can
* override module-supplied CSS files based on their filenames, and this
* prefixing helps prevent confusing name collisions for theme developers.
* See drupal_get_css() where the overrides are performed. Also, if the
* direction of the current language is right-to-left (Hebrew, Arabic,
* etc.), the function will also look for an RTL CSS file and append it to
* the list. The name of this file should have an '-rtl.css' suffix. For
* example, a CSS file called 'mymodule-name.css' will have a
* 'mymodule-name-rtl.css' file added to the list, if exists in the same
* directory. This CSS file should contain overrides for properties which
* should be reversed or otherwise different in a right-to-left display.
* - 'inline': A string of CSS that should be placed in the given scope. Note
* that it is better practice to use 'file' stylesheets, rather than
* 'inline', as the CSS would then be aggregated and cached.
* - 'external': The absolute path to an external CSS file that is not hosted
* on the local server. These files will not be aggregated if CSS
* aggregation is enabled.
* @param $options
* (optional) A string defining the 'type' of CSS that is being added in the
* $data parameter ('file', 'inline', or 'external'), or an array which can
* have any or all of the following keys:
* - 'type': The type of stylesheet being added. Available options are 'file',
* 'inline' or 'external'. Defaults to 'file'.
* - 'basename': Force a basename for the file being added. Modules are
* expected to use stylesheets with unique filenames, but integration of
* external libraries may make this impossible. The basename of
* 'modules/node/node.css' is 'node.css'. If the external library "node.js"
* ships with a 'node.css', then a different, unique basename would be
* 'node.js.css'.
* - 'group': A number identifying the group in which to add the stylesheet.
* Available constants are:
* - CSS_SYSTEM: Any system-layer CSS.
* - CSS_DEFAULT: (default) Any module-layer CSS.
* - CSS_THEME: Any theme-layer CSS.
* The group number serves as a weight: the markup for loading a stylesheet
* within a lower weight group is output to the page before the markup for
* loading a stylesheet within a higher weight group, so CSS within higher
* weight groups take precendence over CSS within lower weight groups.
* - 'every_page': For optimal front-end performance when aggregation is
* enabled, this should be set to TRUE if the stylesheet is present on every
* page of the website for users for whom it is present at all. This
* defaults to FALSE. It is set to TRUE for stylesheets added via module and
* theme .info files. Modules that add stylesheets within hook_init()
* implementations, or from other code that ensures that the stylesheet is
* added to all website pages, should also set this flag to TRUE. All
* stylesheets within the same group that have the 'every_page' flag set to
* TRUE and do not have 'preprocess' set to FALSE are aggregated together
* into a single aggregate file, and that aggregate file can be reused
* across a user's entire site visit, leading to faster navigation between
* pages. However, stylesheets that are only needed on pages less frequently
* visited, can be added by code that only runs for those particular pages,
* and that code should not set the 'every_page' flag. This minimizes the
* size of the aggregate file that the user needs to download when first
* visiting the website. Stylesheets without the 'every_page' flag are
* aggregated into a separate aggregate file. This other aggregate file is
* likely to change from page to page, and each new aggregate file needs to
* be downloaded when first encountered, so it should be kept relatively
* small by ensuring that most commonly needed stylesheets are added to
* every page.
* - 'weight': The weight of the stylesheet specifies the order in which the
* CSS will appear relative to other stylesheets with the same group and
* 'every_page' flag. The exact ordering of stylesheets is as follows:
* - First by group.
* - Then by the 'every_page' flag, with TRUE coming before FALSE.
* - Then by weight.
* - Then by the order in which the CSS was added. For example, all else
* being the same, a stylesheet added by a call to drupal_add_css() that
* happened later in the page request gets added to the page after one for
* which drupal_add_css() happened earlier in the page request.
* - 'media': The media type for the stylesheet, e.g., all, print, screen.
* Defaults to 'all'.
* - 'preprocess': If TRUE and CSS aggregation/compression is enabled, the
* styles will be aggregated and compressed. Defaults to TRUE.
* - 'browsers': An array containing information specifying which browsers
* should load the CSS item. See drupal_pre_render_conditional_comments()
* for details.
*
* @return
* An array of queued cascading stylesheets.
*
* @see drupal_get_css()
*/
function drupal_add_css($data = NULL, $options = NULL) {
$css = &drupal_static(__FUNCTION__, array());
$count = &drupal_static(__FUNCTION__ . '_count', 0);

// If the $css variable has been reset with drupal_static_reset(), there is
// no longer any CSS being tracked, so set the counter back to 0 also.
if (count($css) === 0) {
$count = 0;
}

// Construct the options, taking the defaults into consideration.
if (isset($options)) {
if (!is_array($options)) {
$options = array('type' => $options);
}
} else {
$options = array();
}

// Create an array of CSS files for each media type first, since each type needs to be served
// to the browser differently.
if (isset($data)) {
$options += array(
'type' => 'file',
'group' => CSS_DEFAULT,
'weight' => 0,
'every_page' => FALSE,
'media' => 'all',
'preprocess' => TRUE,
'data' => $data,
'browsers' => array(),
);
$options['browsers'] += array(
'IE' => TRUE,
'!IE' => TRUE,
);

// Files with a query string cannot be preprocessed.
if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
$options['preprocess'] = FALSE;
}

// Always add a tiny value to the weight, to conserve the insertion order.
$options['weight'] += $count / 1000;
$count++;

// Add the data to the CSS array depending on the type.
switch ($options['type']) {
case 'inline':
// For inline stylesheets, we don't want to use the $data as the array
// key as $data could be a very long string of CSS.
$css[] = $options;
break;
default:
// Local and external files must keep their name as the associative key
// so the same CSS file is not be added twice.
$css[$data] = $options;
}
}

return $css;
}

/**
* Returns a themed representation of all stylesheets to attach to the page.
*
* It loads the CSS in order, with 'module' first, then 'theme' afterwards.
* This ensures proper cascading of styles so themes can easily override
* module styles through CSS selectors.
*
* Themes may replace module-defined CSS files by adding a stylesheet with the
* same filename. For example, themes/bartik/system-menus.css would replace
* modules/system/system-menus.css. This allows themes to override complete
* CSS files, rather than specific selectors, when necessary.
*
* If the original CSS file is being overridden by a theme, the theme is
* responsible for supplying an accompanying RTL CSS file to replace the
* module's.
*
* @param $css
* (optional) An array of CSS files. If no array is provided, the default
* stylesheets array is used instead.
* @param $skip_alter
* (optional) If set to TRUE, this function skips calling drupal_alter() on
* $css, useful when the calling function passes a $css array that has already
* been altered.
*
* @return
* A string of XHTML CSS tags.
*
* @see drupal_add_css()
*/
function drupal_get_css($css = NULL, $skip_alter = FALSE) {
if (!isset($css)) {
$css = drupal_add_css();
}

// Allow modules and themes to alter the CSS items.
if (!$skip_alter) {
drupal_alter('css', $css);
}

// Sort CSS items, so that they appear in the correct order.
uasort($css, 'drupal_sort_css_js');

// Provide the page with information about the individual CSS files used,
// information not otherwise available when CSS aggregation is enabled. The
// setting is attached later in this function, but is set here, so that CSS
// files removed below are still considered "used" and prevented from being
// added in a later AJAX request.
// Skip if no files were added to the page or jQuery.extend() will overwrite
// the Drupal.settings.ajaxPageState.css object with an empty array.
if (!empty($css)) {
// Cast the array to an object to be on the safe side even if not empty.
$setting['ajaxPageState']['css'] = (object) array_fill_keys(array_keys($css), 1);
}

// Remove the overridden CSS files. Later CSS files override former ones.
$previous_item = array();
foreach ($css as $key => $item) {
if ($item['type'] == 'file') {
// If defined, force a unique basename for this file.
$basename = isset($item['basename']) ? $item['basename'] : drupal_basename($item['data']);
if (isset($previous_item[$basename])) {
// Remove the previous item that shared the same base name.
unset($css[$previous_item[$basename]]);
}
$previous_item[$basename] = $key;
}
}

// Render the HTML needed to load the CSS.
$styles = array(
'#type' => 'styles',
'#items' => $css,
);

if (!empty($setting)) {
$styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
}

return drupal_render($styles);
}

/**
* Sorts CSS and JavaScript resources.
*
* Callback for uasort() within:
* - drupal_get_css()
* - drupal_get_js()
*
* This sort order helps optimize front-end performance while providing modules
* and themes with the necessary control for ordering the CSS and JavaScript
* appearing on a page.
*
* @param $a
* First item for comparison. The compared items should be associative arrays
* of member items from drupal_add_css() or drupal_add_js().
* @param $b
* Second item for comparison.
*
* @see drupal_add_css()
* @see drupal_add_js()
*/
function drupal_sort_css_js($a, $b) {
// First order by group, so that, for example, all items in the CSS_SYSTEM
// group appear before items in the CSS_DEFAULT group, which appear before
// all items in the CSS_THEME group. Modules may create additional groups by
// defining their own constants.
if ($a['group'] < $b['group']) {
return -1;
} elseif ($a['group'] > $b['group']) {
return 1;
}
// Within a group, order all infrequently needed, page-specific files after
// common files needed throughout the website. Separating this way allows for
// the aggregate file generated for all of the common files to be reused
// across a site visit without being cut by a page using a less common file.
elseif ($a['every_page'] && !$b['every_page']) {
return -1;
} elseif (!$a['every_page'] && $b['every_page']) {
return 1;
}
// Finally, order by weight.
elseif ($a['weight'] < $b['weight']) {
return -1;
} elseif ($a['weight'] > $b['weight']) {
return 1;
} else {
return 0;
}
}

/**
* Default callback to group CSS items.
*
* This function arranges the CSS items that are in the #items property of the
* styles element into groups. Arranging the CSS items into groups serves two
* purposes. When aggregation is enabled, files within a group are aggregated
* into a single file, significantly improving page loading performance by
* minimizing network traffic overhead. When aggregation is disabled, grouping
* allows multiple files to be loaded from a single STYLE tag, enabling sites
* with many modules enabled or a complex theme being used to stay within IE's
* 31 CSS inclusion tag limit: http://drupal.org/node/228818.
*
* This function puts multiple items into the same group if they are groupable
* and if they are for the same 'media' and 'browsers'. Items of the 'file' type
* are groupable if their 'preprocess' flag is TRUE, items of the 'inline' type
* are always groupable, and items of the 'external' type are never groupable.
* This function also ensures that the process of grouping items does not change
* their relative order. This requirement may result in multiple groups for the
* same type, media, and browsers, if needed to accommodate other items in
* between.
*
* @param $css
* An array of CSS items, as returned by drupal_add_css(), but after
* alteration performed by drupal_get_css().
*
* @return
* An array of CSS groups. Each group contains the same keys (e.g., 'media',
* 'data', etc.) as a CSS item from the $css parameter, with the value of
* each key applying to the group as a whole. Each group also contains an
* 'items' key, which is the subset of items from $css that are in the group.
*
* @see drupal_pre_render_styles()
* @see system_element_info()
*/
function drupal_group_css($css) {
$groups = array();
// If a group can contain multiple items, we track the information that must
// be the same for each item in the group, so that when we iterate the next
// item, we can determine if it can be put into the current group, or if a
// new group needs to be made for it.
$current_group_keys = NULL;
// When creating a new group, we pre-increment $i, so by initializing it to
// -1, the first group will have index 0.
$i = -1;
foreach ($css as $item) {
// The browsers for which the CSS item needs to be loaded is part of the
// information that determines when a new group is needed, but the order of
// keys in the array doesn't matter, and we don't want a new group if all
// that's different is that order.
ksort($item['browsers']);

// If the item can be grouped with other items, set $group_keys to an array
// of information that must be the same for all items in its group. If the
// item can't be grouped with other items, set $group_keys to FALSE. We
// put items into a group that can be aggregated together: whether they will
// be aggregated is up to the _drupal_css_aggregate() function or an
// override of that function specified in hook_css_alter(), but regardless
// of the details of that function, a group represents items that can be
// aggregated. Since a group may be rendered with a single HTML tag, all
// items in the group must share the same information that would need to be
// part of that HTML tag.
switch ($item['type']) {
case 'file':
// Group file items if their 'preprocess' flag is TRUE.
// Help ensure maximum reuse of aggregate files by only grouping
// together items that share the same 'group' value and 'every_page'
// flag. See drupal_add_css() for details about that.
$group_keys = $item['preprocess'] ? array($item['type'], $item['group'], $item['every_page'], $item['media'], $item['browsers']) : FALSE;
break;
case 'inline':
// Always group inline items.
$group_keys = array($item['type'], $item['media'], $item['browsers']);
break;
case 'external':
// Do not group external items.
$group_keys = FALSE;
break;
}

// If the group keys don't match the most recent group we're working with,
// then a new group must be made.
if ($group_keys !== $current_group_keys) {
$i++;
// Initialize the new group with the same properties as the first item
// being placed into it. The item's 'data' and 'weight' properties are
// unique to the item and should not be carried over to the group.
$groups[$i] = $item;
unset($groups[$i]['data'], $groups[$i]['weight']);
$groups[$i]['items'] = array();
$current_group_keys = $group_keys ? $group_keys : NULL;
}

// Add the item to the current group.
$groups[$i]['items'][] = $item;
}
return $groups;
}

/**
* Default callback to aggregate CSS files and inline content.
*
* Having the browser load fewer CSS files results in much faster page loads
* than when it loads many small files. This function aggregates files within
* the same group into a single file unless the site-wide setting to do so is
* disabled (commonly the case during site development). To optimize download,
* it also compresses the aggregate files by removing comments, whitespace, and
* other unnecessary content. Additionally, this functions aggregates inline
* content together, regardless of the site-wide aggregation setting.
*
* @param $css_groups
* An array of CSS groups as returned by drupal_group_css(). This function
* modifies the group's 'data' property for each group that is aggregated.
*
* @see drupal_group_css()
* @see drupal_pre_render_styles()
* @see system_element_info()
*/
function drupal_aggregate_css(&$css_groups) {
$preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));

// For each group that needs aggregation, aggregate its items.
foreach ($css_groups as $key => $group) {
switch ($group['type']) {
// If a file group can be aggregated into a single file, do so, and set
// the group's data property to the file path of the aggregate file.
case 'file':
if ($group['preprocess'] && $preprocess_css) {
$css_groups[$key]['data'] = drupal_build_css_cache($group['items']);
}
break;
// Aggregate all inline CSS content into the group's data property.
case 'inline':
$css_groups[$key]['data'] = '';
foreach ($group['items'] as $item) {
$css_groups[$key]['data'] .= drupal_load_stylesheet_content($item['data'], $item['preprocess']);
}
break;
}
}
}

/**
* #pre_render callback to add the elements needed for CSS tags to be rendered.
*
* For production websites, LINK tags are preferable to STYLE tags with @import
* statements, because:
* - They are the standard tag intended for linking to a resource.
* - On Firefox 2 and perhaps other browsers, CSS files included with @import
* statements don't get saved when saving the complete web page for offline
* use: http://drupal.org/node/145218.
* - On IE, if only LINK tags and no @import statements are used, all the CSS
* files are downloaded in parallel, resulting in faster page load, but if
* @import statements are used and span across multiple STYLE tags, all the
* ones from one STYLE tag must be downloaded before downloading begins for
* the next STYLE tag. Furthermore, IE7 does not support media declaration on
* the @import statement, so multiple STYLE tags must be used when different
* files are for different media types. Non-IE browsers always download in
* parallel, so this is an IE-specific performance quirk:
* http://www.stevesouders.com/blog/2009/04/09/dont-use-import/.
*
* However, IE has an annoying limit of 31 total CSS inclusion tags
* (http://drupal.org/node/228818) and LINK tags are limited to one file per
* tag, whereas STYLE tags can contain multiple @import statements allowing
* multiple files to be loaded per tag. When CSS aggregation is disabled, a
* Drupal site can easily have more than 31 CSS files that need to be loaded, so
* using LINK tags exclusively would result in a site that would display
* incorrectly in IE. Depending on different needs, different strategies can be
* employed to decide when to use LINK tags and when to use STYLE tags.
*
* The strategy employed by this function is to use LINK tags for all aggregate
* files and for all files that cannot be aggregated (e.g., if 'preprocess' is
* set to FALSE or the type is 'external'), and to use STYLE tags for groups
* of files that could be aggregated together but aren't (e.g., if the site-wide
* aggregation setting is disabled). This results in all LINK tags when
* aggregation is enabled, a guarantee that as many or only slightly more tags
* are used with aggregation disabled than enabled (so that if the limit were to
* be crossed with aggregation enabled, the site developer would also notice the
* problem while aggregation is disabled), and an easy way for a developer to
* view HTML source while aggregation is disabled and know what files will be
* aggregated together when aggregation becomes enabled.
*
* This function evaluates the aggregation enabled/disabled condition on a group
* by group basis by testing whether an aggregate file has been made for the
* group rather than by testing the site-wide aggregation setting. This allows
* this function to work correctly even if modules have implemented custom
* logic for grouping and aggregating files.
*
* @param $element
* A render array containing:
* - '#items': The CSS items as returned by drupal_add_css() and altered by
* drupal_get_css().
* - '#group_callback': A function to call to group #items to enable the use
* of fewer tags by aggregating files and/or using multiple @import
* statements within a single tag.
* - '#aggregate_callback': A function to call to aggregate the items within
* the groups arranged by the #group_callback function.
*
* @return
* A render array that will render to a string of XHTML CSS tags.
*
* @see drupal_get_css()
*/
function drupal_pre_render_styles($elements) {
// Group and aggregate the items.
if (isset($elements['#group_callback'])) {
$elements['#groups'] = $elements['#group_callback']($elements['#items']);
}
if (isset($elements['#aggregate_callback'])) {
$elements['#aggregate_callback']($elements['#groups']);
}

// A dummy query-string is added to filenames, to gain control over
// browser-caching. The string changes on every update or full cache
// flush, forcing browsers to load a new copy of the files, as the
// URL changed.
$query_string = variable_get('css_js_query_string', '0');

// For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
// wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
// comment out the CDATA-tag.
$embed_prefix = "\n<!--/*--><![CDATA[/*><!--*/\n";
$embed_suffix = "\n/*]]>*/-->\n";

// Defaults for LINK and STYLE elements.
$link_element_defaults = array(
'#type' => 'html_tag',
'#tag' => 'link',
'#attributes' => array(
'type' => 'text/css',
'rel' => 'stylesheet',
),
);
$style_element_defaults = array(
'#type' => 'html_tag',
'#tag' => 'style',
'#attributes' => array(
'type' => 'text/css',
),
);

// Loop through each group.
foreach ($elements['#groups'] as $group) {
switch ($group['type']) {
// For file items, there are three possibilites.
// - The group has been aggregated: in this case, output a LINK tag for
// the aggregate file.
// - The group can be aggregated but has not been (most likely because
// the site administrator disabled the site-wide setting): in this case,
// output as few STYLE tags for the group as possible, using @import
// statement for each file in the group. This enables us to stay within
// IE's limit of 31 total CSS inclusion tags.
// - The group contains items not eligible for aggregation (their
// 'preprocess' flag has been set to FALSE): in this case, output a LINK
// tag for each file.
case 'file':
// The group has been aggregated into a single file: output a LINK tag
// for the aggregate file.
if (isset($group['data'])) {
$element = $link_element_defaults;
$element['#attributes']['href'] = file_create_url($group['data']);
$element['#attributes']['media'] = $group['media'];
$element['#browsers'] = $group['browsers'];
$elements[] = $element;
}
// The group can be aggregated, but hasn't been: combine multiple items
// into as few STYLE tags as possible.
elseif ($group['preprocess']) {
$import = array();
foreach ($group['items'] as $item) {
// A theme's .info file may have an entry for a file that doesn't
// exist as a way of overriding a module or base theme CSS file from
// being added to the page. Normally, file_exists() calls that need
// to run for every page request should be minimized, but this one
// is okay, because it only runs when CSS aggregation is disabled.
// On a server under heavy enough load that file_exists() calls need
// to be minimized, CSS aggregation should be enabled, in which case
// this code is not run. When aggregation is enabled,
// drupal_load_stylesheet() checks file_exists(), but only when
// building the aggregate file, which is then reused for many page
// requests.
if (file_exists($item['data'])) {
// The dummy query string needs to be added to the URL to control
// browser-caching. IE7 does not support a media type on the
// @import statement, so we instead specify the media for the
// group on the STYLE tag.
$import[] = '@import url("' . check_plain(file_create_url($item['data']) . '?' . $query_string) . '");';
}
}
// In addition to IE's limit of 31 total CSS inclusion tags, it also
// has a limit of 31 @import statements per STYLE tag.
while (!empty($import)) {
$import_batch = array_slice($import, 0, 31);
$import = array_slice($import, 31);
$element = $style_element_defaults;
// This simplifies the JavaScript regex, allowing each line
// (separated by \n) to be treated as a completely different string.
// This means that we can use ^ and $ on one line at a time, and not
// worry about style tags since they'll never match the regex.
$element['#value'] = "\n" . implode("\n", $import_batch) . "\n";
$element['#attributes']['media'] = $group['media'];
$element['#browsers'] = $group['browsers'];
$elements[] = $element;
}
}
// The group contains items ineligible for aggregation: output a LINK
// tag for each file.
else {
foreach ($group['items'] as $item) {
$element = $link_element_defaults;
// We do not check file_exists() here, because this code runs for
// files whose 'preprocess' is set to FALSE, and therefore, even
// when aggregation is enabled, and we want to avoid needlessly
// taxing a server that may be under heavy load. The file_exists()
// performed above for files whose 'preprocess' is TRUE is done for
// the benefit of theme .info files, but code that deals with files
// whose 'preprocess' is FALSE is responsible for ensuring the file
// exists.
// The dummy query string needs to be added to the URL to control
// browser-caching.
$query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
$element['#attributes']['href'] = file_create_url($item['data']) . $query_string_separator . $query_string;
$element['#attributes']['media'] = $item['media'];
$element['#browsers'] = $group['browsers'];
$elements[] = $element;
}
}
break;
// For inline content, the 'data' property contains the CSS content. If
// the group's 'data' property is set, then output it in a single STYLE
// tag. Otherwise, output a separate STYLE tag for each item.
case 'inline':
if (isset($group['data'])) {
$element = $style_element_defaults;
$element['#value'] = $group['data'];
$element['#value_prefix'] = $embed_prefix;
$element['#value_suffix'] = $embed_suffix;
$element['#attributes']['media'] = $group['media'];
$element['#browsers'] = $group['browsers'];
$elements[] = $element;
} else {
foreach ($group['items'] as $item) {
$element = $style_element_defaults;
$element['#value'] = $item['data'];
$element['#value_prefix'] = $embed_prefix;
$element['#value_suffix'] = $embed_suffix;
$element['#attributes']['media'] = $item['media'];
$element['#browsers'] = $group['browsers'];
$elements[] = $element;
}
}
break;
// Output a LINK tag for each external item. The item's 'data' property
// contains the full URL.
case 'external':
foreach ($group['items'] as $item) {
$element = $link_element_defaults;
$element['#attributes']['href'] = $item['data'];
$element['#attributes']['media'] = $item['media'];
$element['#browsers'] = $group['browsers'];
$elements[] = $element;
}
break;
}
}

return $elements;
}

/**
* Aggregates and optimizes CSS files into a cache file in the files directory.
*
* The file name for the CSS cache file is generated from the hash of the
* aggregated contents of the files in $css. This forces proxies and browsers
* to download new CSS when the CSS changes.
*
* The cache file name is retrieved on a page load via a lookup variable that
* contains an associative array. The array key is the hash of the file names
* in $css while the value is the cache file name. The cache file is generated
* in two cases. First, if there is no file name value for the key, which will
* happen if a new file name has been added to $css or after the lookup
* variable is emptied to force a rebuild of the cache. Second, the cache file
* is generated if it is missing on disk. Old cache files are not deleted
* immediately when the lookup variable is emptied, but are deleted after a set
* period by drupal_delete_file_if_stale(). This ensures that files referenced
* by a cached page will still be available.
*
* @param $css
* An array of CSS files to aggregate and compress into one file.
*
* @return
* The URI of the CSS cache file, or FALSE if the file could not be saved.
*/
function drupal_build_css_cache($css) {
$data = '';
$uri = '';
$map = variable_get('drupal_css_cache_files', array());
// Create a new array so that only the file names are used to create the hash.
// This prevents new aggregates from being created unnecessarily.
$css_data = array();
foreach ($css as $css_file) {
$css_data[] = $css_file['data'];
}
$key = hash('sha256', serialize($css_data));
if (isset($map[$key])) {
$uri = $map[$key];
}

if (empty($uri) || !file_exists($uri)) {
// Build aggregate CSS file.
foreach ($css as $stylesheet) {
// Only 'file' stylesheets can be aggregated.
if ($stylesheet['type'] == 'file') {
$contents = drupal_load_stylesheet($stylesheet['data'], TRUE);

// Build the base URL of this CSS file: start with the full URL.
$css_base_url = file_create_url($stylesheet['data']);
// Move to the parent.
$css_base_url = substr($css_base_url, 0, strrpos($css_base_url, '/'));
// Simplify to a relative URL if the stylesheet URL starts with the
// base URL of the website.
if (substr($css_base_url, 0, strlen($GLOBALS['base_root'])) == $GLOBALS['base_root']) {
$css_base_url = substr($css_base_url, strlen($GLOBALS['base_root']));
}

_drupal_build_css_path(NULL, $css_base_url . '/');
// Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
$data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
}
}

// Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
// @import rules must proceed any other style, so we move those to the top.
$regexp = '/@import[^;]+;/i';
preg_match_all($regexp, $data, $matches);
$data = preg_replace($regexp, '', $data);
$data = implode('', $matches[0]) . $data;

// Prefix filename to prevent blocking by firewalls which reject files
// starting with "ad*".
$filename = 'css_' . drupal_hash_base64($data) . '.css';
// Create the css/ within the files folder.
$csspath = 'public://css';
$uri = $csspath . '/' . $filename;
// Create the CSS file.
file_prepare_directory($csspath, FILE_CREATE_DIRECTORY);
if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
return FALSE;
}
// If CSS gzip compression is enabled, clean URLs are enabled (which means
// that rewrite rules are working) and the zlib extension is available then
// create a gzipped version of this file. This file is served conditionally
// to browsers that accept gzip using .htaccess rules.
if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
return FALSE;
}
}
// Save the updated map.
$map[$key] = $uri;
variable_set('drupal_css_cache_files', $map);
}
return $uri;
}

/**
* Prefixes all paths within a CSS file for drupal_build_css_cache().
*/
function _drupal_build_css_path($matches, $base = NULL) {
$_base = &drupal_static(__FUNCTION__);
// Store base path for preg_replace_callback.
if (isset($base)) {
$_base = $base;
}

// Prefix with base and remove '../' segments where possible.
$path = $_base . $matches[1];
$last = '';
while ($path != $last) {
$last = $path;
$path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
}
return 'url(' . $path . ')';
}

/**
* Loads the stylesheet and resolves all @import commands.
*
* Loads a stylesheet and replaces @import commands with the contents of the
* imported file. Use this instead of file_get_contents when processing
* stylesheets.
*
* The returned contents are compressed removing white space and comments only
* when CSS aggregation is enabled. This optimization will not apply for
* color.module enabled themes with CSS aggregation turned off.
*
* @param $file
* Name of the stylesheet to be processed.
* @param $optimize
* Defines if CSS contents should be compressed or not.
* @param $reset_basepath
* Used internally to facilitate recursive resolution of @import commands.
*
* @return
* Contents of the stylesheet, including any resolved @import commands.
*/
function drupal_load_stylesheet($file, $optimize = NULL, $reset_basepath = TRUE) {
// These statics are not cache variables, so we don't use drupal_static().
static $_optimize, $basepath;
if ($reset_basepath) {
$basepath = '';
}
// Store the value of $optimize for preg_replace_callback with nested
// @import loops.
if (isset($optimize)) {
$_optimize = $optimize;
}

// Stylesheets are relative one to each other. Start by adding a base path
// prefix provided by the parent stylesheet (if necessary).
if ($basepath && !file_uri_scheme($file)) {
$file = $basepath . '/' . $file;
}
// Store the parent base path to restore it later.
$parent_base_path = $basepath;
// Set the current base path to process possible child imports.
$basepath = dirname($file);

// Load the CSS stylesheet. We suppress errors because themes may specify
// stylesheets in their .info file that don't exist in the theme's path,
// but are merely there to disable certain module CSS files.
$content = '';
if ($contents = @file_get_contents($file)) {
// Return the processed stylesheet.
$content = drupal_load_stylesheet_content($contents, $_optimize);
}

// Restore the parent base path as the file and its childen are processed.
$basepath = $parent_base_path;
return $content;
}

/**
* Processes the contents of a stylesheet for aggregation.
*
* @param $contents
* The contents of the stylesheet.
* @param $optimize
* (optional) Boolean whether CSS contents should be minified. Defaults to
* FALSE.
*
* @return
* Contents of the stylesheet including the imported stylesheets.
*/
function drupal_load_stylesheet_content($contents, $optimize = FALSE) {
// Remove multiple charset declarations for standards compliance (and fixing Safari problems).
$contents = preg_replace('/^@charset\s+[\'"](\S*?)\b[\'"];/i', '', $contents);

if ($optimize) {
// Perform some safe CSS optimizations.
// Regexp to match comment blocks.
$comment = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
// Regexp to match double quoted strings.
$double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
// Regexp to match single quoted strings.
$single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
// Strip all comment blocks, but keep double/single quoted strings.
$contents = preg_replace(
"<($double_quot|$single_quot)|$comment>Ss", "$1", $contents
);
// Remove certain whitespace.
// There are different conditions for removing leading and trailing
// whitespace.
// @see http://php.net/manual/regexp.reference.subpatterns.php
$contents = preg_replace('<
# Strip leading and trailing whitespace.
\s*([@{};,])\s*
# Strip only leading whitespace from:
# - Closing parenthesis: Retain "@media (bar) and foo".
| \s+([\)])
# Strip only trailing whitespace from:
# - Opening parenthesis: Retain "@media (bar) and foo".
# - Colon: Retain :pseudo-selectors.
| ([\(:])\s+
>xS',
// Only one of the three capturing groups will match, so its reference
// will contain the wanted value and the references for the
// two non-matching groups will be replaced with empty strings.
'$1$2$3', $contents
);
// End the file with a new line.
$contents = trim($contents);
$contents .= "\n";
}

// Replaces @import commands with the actual stylesheet content.
// This happens recursively but omits external files.
$contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)(?!\/\/)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
return $contents;
}

/**
* Loads stylesheets recursively and returns contents with corrected paths.
*
* This function is used for recursive loading of stylesheets and
* returns the stylesheet content with all url() paths corrected.
*/
function _drupal_load_stylesheet($matches) {
$filename = $matches[1];
// Load the imported stylesheet and replace @import commands in there as well.
$file = drupal_load_stylesheet($filename, NULL, FALSE);

// Determine the file's directory.
$directory = dirname($filename);
// If the file is in the current directory, make sure '.' doesn't appear in
// the url() path.
$directory = $directory == '.' ? '' : $directory . '/';

// Alter all internal url() paths. Leave external paths alone. We don't need
// to normalize absolute paths here (i.e. remove folder/... segments) because
// that will be done later.
return preg_replace('/url\(\s*([\'"]?)(?![a-z]+:|\/+)([^\'")]+)([\'"]?)\s*\)/i', 'url(\1' . $directory . '\2\3)', $file);
}

/**
* Deletes old cached CSS files.
*/
function drupal_clear_css_cache() {
variable_del('drupal_css_cache_files');
file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
}

/**
* Callback to delete files modified more than a set time ago.
*/
function drupal_delete_file_if_stale($uri) {
// Default stale file threshold is 30 days.
if (REQUEST_TIME - filemtime($uri) > variable_get('drupal_stale_file_threshold', 2592000)) {
file_unmanaged_delete($uri);
}
}

/**
* Prepares a string for use as a CSS identifier (element, class, or ID name).
*
* http://www.w3.org/TR/CSS21/syndata.html#characters shows the syntax for valid
* CSS identifiers (including element names, classes, and IDs in selectors.)
*
* @param $identifier
* The identifier to clean.
* @param $filter
* An array of string replacements to use on the identifier.
*
* @return
* The cleaned identifier.
*/
function drupal_clean_css_identifier($identifier, $filter = array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '')) {
// Use the advanced drupal_static() pattern, since this is called very often.
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
$drupal_static_fast['allow_css_double_underscores'] = &drupal_static(__FUNCTION__ . ':allow_css_double_underscores');
}
$allow_css_double_underscores = &$drupal_static_fast['allow_css_double_underscores'];
if (!isset($allow_css_double_underscores)) {
$allow_css_double_underscores = variable_get('allow_css_double_underscores', FALSE);
}

// Preserve BEM-style double-underscores depending on custom setting.
if ($allow_css_double_underscores) {
$filter['__'] = '__';
}

// By default, we filter using Drupal's coding standards.
$identifier = strtr($identifier, $filter);

// Valid characters in a CSS identifier are:
// - the hyphen (U+002D)
// - a-z (U+0030 - U+0039)
// - A-Z (U+0041 - U+005A)
// - the underscore (U+005F)
// - 0-9 (U+0061 - U+007A)
// - ISO 10646 characters U+00A1 and higher
// We strip out any character not in the above list.
$identifier = preg_replace('/[^\x{002D}\x{0030}-\x{0039}\x{0041}-\x{005A}\x{005F}\x{0061}-\x{007A}\x{00A1}-\x{FFFF}]/u', '', $identifier);

return $identifier;
}

/**
* Prepares a string for use as a valid class name.
*
* Do not pass one string containing multiple classes as they will be
* incorrectly concatenated with dashes, i.e. "one two" will become "one-two".
*
* @param $class
* The class name to clean.
*
* @return
* The cleaned class name.
*/
function drupal_html_class($class) {
// The output of this function will never change, so this uses a normal
// static instead of drupal_static().
static $classes = array();

if (!isset($classes[$class])) {
$classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
}
return $classes[$class];
}

/**
* Prepares a string for use as a valid HTML ID and guarantees uniqueness.
*
* This function ensures that each passed HTML ID value only exists once on the
* page. By tracking the already returned ids, this function enables forms,
* blocks, and other content to be output multiple times on the same page,
* without breaking (X)HTML validation.
*
* For already existing IDs, a counter is appended to the ID string. Therefore,
* JavaScript and CSS code should not rely on any value that was generated by
* this function and instead should rely on manually added CSS classes or
* similarly reliable constructs.
*
* Two consecutive hyphens separate the counter from the original ID. To manage
* uniqueness across multiple Ajax requests on the same page, Ajax requests
* POST an array of all IDs currently present on the page, which are used to
* prime this function's cache upon first invocation.
*
* To allow reverse-parsing of IDs submitted via Ajax, any multiple consecutive
* hyphens in the originally passed $id are replaced with a single hyphen.
*
* @param $id
* The ID to clean.
*
* @return
* The cleaned ID.
*/
function drupal_html_id($id) {
// If this is an Ajax request, then content returned by this page request will
// be merged with content already on the base page. The HTML IDs must be
// unique for the fully merged content. Therefore, initialize $seen_ids to
// take into account IDs that are already in use on the base page.
static $drupal_static_fast;
if (!isset($drupal_static_fast['seen_ids_init'])) {
$drupal_static_fast['seen_ids_init'] = &drupal_static(__FUNCTION__ . ':init');
}
$seen_ids_init = &$drupal_static_fast['seen_ids_init'];
if (!isset($seen_ids_init)) {
// Ideally, Drupal would provide an API to persist state information about
// prior page requests in the database, and we'd be able to add this
// function's $seen_ids static variable to that state information in order
// to have it properly initialized for this page request. However, no such
// page state API exists, so instead, ajax.js adds all of the in-use HTML
// IDs to the POST data of Ajax submissions. Direct use of $_POST is
// normally not recommended as it could open up security risks, but because
// the raw POST data is cast to a number before being returned by this
// function, this usage is safe.
if (empty($_POST['ajax_html_ids'])) {
$seen_ids_init = array();
} else {
// This function ensures uniqueness by appending a counter to the base id
// requested by the calling function after the first occurrence of that
// requested id. $_POST['ajax_html_ids'] contains the ids as they were
// returned by this function, potentially with the appended counter, so
// we parse that to reconstruct the $seen_ids array.
if (isset($_POST['ajax_html_ids'][0]) && strpos($_POST['ajax_html_ids'][0], ',') === FALSE) {
$ajax_html_ids = $_POST['ajax_html_ids'];
} else {
// jquery.form.js may send the server a comma-separated string as the
// first element of an array (see http://drupal.org/node/1575060), so
// we need to convert it to an array in that case.
$ajax_html_ids = explode(',', $_POST['ajax_html_ids'][0]);
}
foreach ($ajax_html_ids as $seen_id) {
// We rely on '--' being used solely for separating a base id from the
// counter, which this function ensures when returning an id.
$parts = explode('--', $seen_id, 2);
if (!empty($parts[1]) && is_numeric($parts[1])) {
list($seen_id, $i) = $parts;
} else {
$i = 1;
}
if (!isset($seen_ids_init[$seen_id]) || ($i > $seen_ids_init[$seen_id])) {
$seen_ids_init[$seen_id] = $i;
}
}
}
}
if (!isset($drupal_static_fast['seen_ids'])) {
$drupal_static_fast['seen_ids'] = &drupal_static(__FUNCTION__, $seen_ids_init);
}
$seen_ids = &$drupal_static_fast['seen_ids'];

$id = strtr(drupal_strtolower($id), array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));

// As defined in http://www.w3.org/TR/html4/types.html#type-name, HTML IDs can
// only contain letters, digits ([0-9]), hyphens ("-"), underscores ("_"),
// colons (":"), and periods ("."). We strip out any character not in that
// list. Note that the CSS spec doesn't allow colons or periods in identifiers
// (http://www.w3.org/TR/CSS21/syndata.html#characters), so we strip those two
// characters as well.
$id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id);

// Removing multiple consecutive hyphens.
$id = preg_replace('/\-+/', '-', $id);
// Ensure IDs are unique by appending a counter after the first occurrence.
// The counter needs to be appended with a delimiter that does not exist in
// the base ID. Requiring a unique delimiter helps ensure that we really do
// return unique IDs and also helps us re-create the $seen_ids array during
// Ajax requests.
if (isset($seen_ids[$id])) {
$id = $id . '--' . ++$seen_ids[$id];
} else {
$seen_ids[$id] = 1;
}

return $id;
}

/**
* Provides a standard HTML class name that identifies a page region.
*
* It is recommended that template preprocess functions apply this class to any
* page region that is output by the theme (Drupal core already handles this in
* the standard template preprocess implementation). Standardizing the class
* names in this way allows modules to implement certain features, such as
* drag-and-drop or dynamic Ajax loading, in a theme-independent way.
*
* @param $region
* The name of the page region (for example, 'page_top' or 'content').
*
* @return
* An HTML class that identifies the region (for example, 'region-page-top'
* or 'region-content').
*
* @see template_preprocess_region()
*/
function drupal_region_class($region) {
return drupal_html_class("region-$region");
}

/**
* Adds a JavaScript file, setting, or inline code to the page.
*
* The behavior of this function depends on the parameters it is called with.
* Generally, it handles the addition of JavaScript to the page, either as
* reference to an existing file or as inline code. The following actions can be
* performed using this function:
* - Add a file ('file'): Adds a reference to a JavaScript file to the page.
* - Add inline JavaScript code ('inline'): Executes a piece of JavaScript code
* on the current page by placing the code directly in the page (for example,
* to tell the user that a new message arrived, by opening a pop up, alert
* box, etc.). This should only be used for JavaScript that cannot be executed
* from a file. When adding inline code, make sure that you are not relying on
* $() being the jQuery function. Wrap your code in
* @code (function ($) {... })(jQuery); @endcode
* or use jQuery() instead of $().
* - Add external JavaScript ('external'): Allows the inclusion of external
* JavaScript files that are not hosted on the local server. Note that these
* external JavaScript references do not get aggregated when preprocessing is
* on.
* - Add settings ('setting'): Adds settings to Drupal's global storage of
* JavaScript settings. Per-page settings are required by some modules to
* function properly. All settings will be accessible at Drupal.settings.
*
* Examples:
* @code
* drupal_add_js('misc/collapse.js');
* drupal_add_js('misc/collapse.js', 'file');
* drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
* drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
* array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
* );
* drupal_add_js('http://example.com/example.js', 'external');
* drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
* @endcode
*
* Calling drupal_static_reset('drupal_add_js') will clear all JavaScript added
* so far.
*
* If JavaScript aggregation is enabled, all JavaScript files added with
* $options['preprocess'] set to TRUE will be merged into one aggregate file.
* Preprocessed inline JavaScript will not be aggregated into this single file.
* Externally hosted JavaScripts are never aggregated.
*
* The reason for aggregating the files is outlined quite thoroughly here:
* http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
* to request overhead, one bigger file just loads faster than two smaller ones
* half its size."
*
* $options['preprocess'] should be only set to TRUE when a file is required for
* all typical visitors and most pages of a site. It is critical that all
* preprocessed files are added unconditionally on every page, even if the
* files are not needed on a page. This is normally done by calling
* drupal_add_js() in a hook_init() implementation.
*
* Non-preprocessed files should only be added to the page when they are
* actually needed.
*
* @param $data
* (optional) If given, the value depends on the $options parameter, or
* $options['type'] if $options is passed as an associative array:
* - 'file': Path to the file relative to base_path().
* - 'inline': The JavaScript code that should be placed in the given scope.
* - 'external': The absolute path to an external JavaScript file that is not
* hosted on the local server. These files will not be aggregated if
* JavaScript aggregation is enabled.
* - 'setting': An associative array with configuration options. The array is
* merged directly into Drupal.settings. All modules should wrap their
* actual configuration settings in another variable to prevent conflicts in
* the Drupal.settings namespace. Items added with a string key will replace
* existing settings with that key; items with numeric array keys will be
* added to the existing settings array.
* @param $options
* (optional) A string defining the type of JavaScript that is being added in
* the $data parameter ('file'/'setting'/'inline'/'external'), or an
* associative array. JavaScript settings should always pass the string
* 'setting' only. Other types can have the following elements in the array:
* - type: The type of JavaScript that is to be added to the page. Allowed
* values are 'file', 'inline', 'external' or 'setting'. Defaults
* to 'file'.
* - scope: The location in which you want to place the script. Possible
* values are 'header' or 'footer'. If your theme implements different
* regions, you can also use these. Defaults to 'header'.
* - group: A number identifying the group in which to add the JavaScript.
* Available constants are:
* - JS_LIBRARY: Any libraries, settings, or jQuery plugins.
* - JS_DEFAULT: Any module-layer JavaScript.
* - JS_THEME: Any theme-layer JavaScript.
* The group number serves as a weight: JavaScript within a lower weight
* group is presented on the page before JavaScript within a higher weight
* group.
* - every_page: For optimal front-end performance when aggregation is
* enabled, this should be set to TRUE if the JavaScript is present on every
* page of the website for users for whom it is present at all. This
* defaults to FALSE. It is set to TRUE for JavaScript files that are added
* via module and theme .info files. Modules that add JavaScript within
* hook_init() implementations, or from other code that ensures that the
* JavaScript is added to all website pages, should also set this flag to
* TRUE. All JavaScript files within the same group and that have the
* 'every_page' flag set to TRUE and do not have 'preprocess' set to FALSE
* are aggregated together into a single aggregate file, and that aggregate
* file can be reused across a user's entire site visit, leading to faster
* navigation between pages. However, JavaScript that is only needed on
* pages less frequently visited, can be added by code that only runs for
* those particular pages, and that code should not set the 'every_page'
* flag. This minimizes the size of the aggregate file that the user needs
* to download when first visiting the website. JavaScript without the
* 'every_page' flag is aggregated into a separate aggregate file. This
* other aggregate file is likely to change from page to page, and each new
* aggregate file needs to be downloaded when first encountered, so it
* should be kept relatively small by ensuring that most commonly needed
* JavaScript is added to every page.
* - weight: A number defining the order in which the JavaScript is added to
* the page relative to other JavaScript with the same 'scope', 'group',
* and 'every_page' value. In some cases, the order in which the JavaScript
* is presented on the page is very important. jQuery, for example, must be
* added to the page before any jQuery code is run, so jquery.js uses the
* JS_LIBRARY group and a weight of -20, jquery.once.js (a library drupal.js
* depends on) uses the JS_LIBRARY group and a weight of -19, drupal.js uses
* the JS_LIBRARY group and a weight of -1, other libraries use the
* JS_LIBRARY group and a weight of 0 or higher, and all other scripts use
* one of the other group constants. The exact ordering of JavaScript is as
* follows:
* - First by scope, with 'header' first, 'footer' last, and any other
* scopes provided by a custom theme coming in between, as determined by
* the theme.
* - Then by group.
* - Then by the 'every_page' flag, with TRUE coming before FALSE.
* - Then by weight.
* - Then by the order in which the JavaScript was added. For example, all
* else being the same, JavaScript added by a call to drupal_add_js() that
* happened later in the page request gets added to the page after one for
* which drupal_add_js() happened earlier in the page request.
* - requires_jquery: Set this to FALSE if the JavaScript you are adding does
* not have a dependency on jQuery. Defaults to TRUE, except for JavaScript
* settings where it defaults to FALSE. This is used on sites that have the
* 'javascript_always_use_jquery' variable set to FALSE; on those sites, if
* all the JavaScript added to the page by drupal_add_js() does not have a
* dependency on jQuery, then for improved front-end performance Drupal
* will not add jQuery and related libraries and settings to the page.
* - defer: If set to TRUE, the defer attribute is set on the <script>
* tag. Defaults to FALSE.
* - cache: If set to FALSE, the JavaScript file is loaded anew on every page
* call; in other words, it is not cached. Used only when 'type' references
* a JavaScript file. Defaults to TRUE.
* - preprocess: If TRUE and JavaScript aggregation is enabled, the script
* file will be aggregated. Defaults to TRUE.
*
* @return
* The current array of JavaScript files, settings, and in-line code,
* including Drupal defaults, anything previously added with calls to
* drupal_add_js(), and this function call's additions.
*
* @see drupal_get_js()
*/
function drupal_add_js($data = NULL, $options = NULL) {
$javascript = &drupal_static(__FUNCTION__, array());
$jquery_added = &drupal_static(__FUNCTION__ . ':jquery_added', FALSE);

// If the $javascript variable has been reset with drupal_static_reset(),
// jQuery and related files will have been removed from the list, so set the
// variable back to FALSE to indicate they have not yet been added.
if (empty($javascript)) {
$jquery_added = FALSE;
}

// Construct the options, taking the defaults into consideration.
if (isset($options)) {
if (!is_array($options)) {
$options = array('type' => $options);
}
} else {
$options = array();
}
if (isset($options['type']) && $options['type'] == 'setting') {
$options += array('requires_jquery' => FALSE);
}
$options += drupal_js_defaults($data);

// Preprocess can only be set if caching is enabled.
$options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;

// Tweak the weight so that files of the same weight are included in the
// order of the calls to drupal_add_js().
$options['weight'] += count($javascript) / 1000;

if (isset($data)) {
// Add jquery.js, drupal.js, and related files and settings if they have
// not been added yet. However, if the 'javascript_always_use_jquery'
// variable is set to FALSE (indicating that the site does not want jQuery
// automatically added on all pages) then only add it if a file or setting
// that requires jQuery is being added also.
if (!$jquery_added && (variable_get('javascript_always_use_jquery', TRUE) || $options['requires_jquery'])) {
$jquery_added = TRUE;
// url() generates the prefix using hook_url_outbound_alter(). Instead of
// running the hook_url_outbound_alter() again here, extract the prefix
// from url().
url('', array('prefix' => &$prefix));
$default_javascript = array(
'settings' => array(
'data' => array(
array('basePath' => base_path()),
array('pathPrefix' => empty($prefix) ? '' : $prefix),
),
'type' => 'setting',
'scope' => 'header',
'group' => JS_LIBRARY,
'every_page' => TRUE,
'weight' => 0,
),
'misc/drupal.js' => array(
'data' => 'misc/drupal.js',
'type' => 'file',
'scope' => 'header',
'group' => JS_LIBRARY,
'every_page' => TRUE,
'weight' => -1,
'requires_jquery' => TRUE,
'preprocess' => TRUE,
'cache' => TRUE,
'defer' => FALSE,
),
);
$javascript = drupal_array_merge_deep($javascript, $default_javascript);
// Register all required libraries.
drupal_add_library('system', 'jquery', TRUE);
drupal_add_library('system', 'jquery.once', TRUE);
}

switch ($options['type']) {
case 'setting':
// All JavaScript settings are placed in the header of the page with
// the library weight so that inline scripts appear afterwards.
$javascript['settings']['data'][] = $data;
break;

case 'inline':
$javascript[] = $options;
break;

default: // 'file' and 'external'
// Local and external files must keep their name as the associative key
// so the same JavaScript file is not added twice.
$javascript[$options['data']] = $options;
}
}
return $javascript;
}

/**
* Constructs an array of the defaults that are used for JavaScript items.
*
* @param $data
* (optional) The default data parameter for the JavaScript item array.
*
* @see drupal_get_js()
* @see drupal_add_js()
*/
function drupal_js_defaults($data = NULL) {
return array(
'type' => 'file',
'group' => JS_DEFAULT,
'every_page' => FALSE,
'weight' => 0,
'requires_jquery' => TRUE,
'scope' => 'header',
'cache' => TRUE,
'defer' => FALSE,
'preprocess' => TRUE,
'version' => NULL,
'data' => $data,
);
}

/**
* Returns a themed presentation of all JavaScript code for the current page.
*
* References to JavaScript files are placed in a certain order: first, all
* 'core' files, then all 'module' and finally all 'theme' JavaScript files
* are added to the page. Then, all settings are output, followed by 'inline'
* JavaScript code. If running update.php, all preprocessing is disabled.
*
* Note that hook_js_alter(&$javascript) is called during this function call
* to allow alterations of the JavaScript during its presentation. Calls to
* drupal_add_js() from hook_js_alter() will not be added to the output
* presentation. The correct way to add JavaScript during hook_js_alter()
* is to add another element to the $javascript array, deriving from
* drupal_js_defaults(). See locale_js_alter() for an example of this.
*
* @param $scope
* (optional) The scope for which the JavaScript rules should be returned.
* Defaults to 'header'.
* @param $javascript
* (optional) An array with all JavaScript code. Defaults to the default
* JavaScript array for the given scope.
* @param $skip_alter
* (optional) If set to TRUE, this function skips calling drupal_alter() on
* $javascript, useful when the calling function passes a $javascript array
* that has already been altered.
*
* @return
* All JavaScript code segments and includes for the scope as HTML tags.
*
* @see drupal_add_js()
* @see locale_js_alter()
* @see drupal_js_defaults()
*/
function drupal_get_js($scope = 'header', $javascript = NULL, $skip_alter = FALSE) {
if (!isset($javascript)) {
$javascript = drupal_add_js();
}

// If no JavaScript items have been added, or if the only JavaScript items
// that have been added are JavaScript settings (which don't do anything
// without any JavaScript code to use them), then no JavaScript code should
// be added to the page.
if (empty($javascript) || (isset($javascript['settings']) && count($javascript) == 1)) {
return '';
}

// Allow modules to alter the JavaScript.
if (!$skip_alter) {
drupal_alter('js', $javascript);
}

// Filter out elements of the given scope.
$items = array();
foreach ($javascript as $key => $item) {
if ($item['scope'] == $scope) {
$items[$key] = $item;
}
}

$output = '';
// The index counter is used to keep aggregated and non-aggregated files in
// order by weight.
$index = 1;
$processed = array();
$files = array();
$preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));

// A dummy query-string is added to filenames, to gain control over
// browser-caching. The string changes on every update or full cache
// flush, forcing browsers to load a new copy of the files, as the
// URL changed. Files that should not be cached (see drupal_add_js())
// get REQUEST_TIME as query-string instead, to enforce reload on every
// page request.
$default_query_string = variable_get('css_js_query_string', '0');

// For inline JavaScript to validate as XHTML, all JavaScript containing
// XHTML needs to be wrapped in CDATA. To make that backwards compatible
// with HTML 4, we need to comment out the CDATA-tag.
$embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
$embed_suffix = "\n//--><!]]>\n";

// Since JavaScript may look for arguments in the URL and act on them, some
// third-party code might require the use of a different query string.
$js_version_string = variable_get('drupal_js_version_query_string', 'v=');

// Sort the JavaScript so that it appears in the correct order.
uasort($items, 'drupal_sort_css_js');

// Provide the page with information about the individual JavaScript files
// used, information not otherwise available when aggregation is enabled.
$setting['ajaxPageState']['js'] = array_fill_keys(array_keys($items), 1);
unset($setting['ajaxPageState']['js']['settings']);
drupal_add_js($setting, 'setting');

// If we're outputting the header scope, then this might be the final time
// that drupal_get_js() is running, so add the setting to this output as well
// as to the drupal_add_js() cache. If $items['settings'] doesn't exist, it's
// because drupal_get_js() was intentionally passed a $javascript argument
// stripped off settings, potentially in order to override how settings get
// output, so in this case, do not add the setting to this output.
if ($scope == 'header' && isset($items['settings'])) {
$items['settings']['data'][] = $setting;
}

// Loop through the JavaScript to construct the rendered output.
$element = array(
'#tag' => 'script',
'#value' => '',
'#attributes' => array(
'type' => 'text/javascript',
),
);
foreach ($items as $item) {
$query_string = empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];

switch ($item['type']) {
case 'setting':
$js_element = $element;
$js_element['#value_prefix'] = $embed_prefix;
$js_element['#value'] = 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($item['data'])) . ");";
$js_element['#value_suffix'] = $embed_suffix;
$output .= theme('html_tag', array('element' => $js_element));
break;

case 'inline':
$js_element = $element;
if ($item['defer']) {
$js_element['#attributes']['defer'] = 'defer';
}
$js_element['#value_prefix'] = $embed_prefix;
$js_element['#value'] = $item['data'];
$js_element['#value_suffix'] = $embed_suffix;
$processed[$index++] = theme('html_tag', array('element' => $js_element));
break;

case 'file':
$js_element = $element;
if (!$item['preprocess'] || !$preprocess_js) {
if ($item['defer']) {
$js_element['#attributes']['defer'] = 'defer';
}
$query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
$js_element['#attributes']['src'] = file_create_url($item['data']) . $query_string_separator . ($item['cache'] ? $query_string : REQUEST_TIME);
$processed[$index++] = theme('html_tag', array('element' => $js_element));
} else {
// By increasing the index for each aggregated file, we maintain
// the relative ordering of JS by weight. We also set the key such
// that groups are split by items sharing the same 'group' value and
// 'every_page' flag. While this potentially results in more aggregate
// files, it helps make each one more reusable across a site visit,
// leading to better front-end performance of a website as a whole.
// See drupal_add_js() for details.
$key = 'aggregate_' . $item['group'] . '_' . $item['every_page'] . '_' . $index;
$processed[$key] = '';
$files[$key][$item['data']] = $item;
}
break;

case 'external':
$js_element = $element;
// Preprocessing for external JavaScript files is ignored.
if ($item['defer']) {
$js_element['#attributes']['defer'] = 'defer';
}
$js_element['#attributes']['src'] = $item['data'];
$processed[$index++] = theme('html_tag', array('element' => $js_element));
break;
}
}

// Aggregate any remaining JS files that haven't already been output.
if ($preprocess_js && count($files) > 0) {
foreach ($files as $key => $file_set) {
$uri = drupal_build_js_cache($file_set);
// Only include the file if was written successfully. Errors are logged
// using watchdog.
if ($uri) {
$preprocess_file = file_create_url($uri);
$js_element = $element;
$js_element['#attributes']['src'] = $preprocess_file;
$processed[$key] = theme('html_tag', array('element' => $js_element));
}
}
}

// Keep the order of JS files consistent as some are preprocessed and others are not.
// Make sure any inline or JS setting variables appear last after libraries have loaded.
return implode('', $processed) . $output;
}

/**
* Adds attachments to a render() structure.
*
* Libraries, JavaScript, CSS and other types of custom structures are attached
* to elements using the #attached property. The #attached property is an
* associative array, where the keys are the attachment types and the values are
* the attached data. For example:
* @code
* $build['#attached'] = array(
* 'js' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.js'),
* 'css' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.css'),
* );
* @endcode
*
* 'js', 'css', and 'library' are types that get special handling. For any
* other kind of attached data, the array key must be the full name of the
* callback function and each value an array of arguments. For example:
* @code
* $build['#attached']['drupal_add_http_header'] = array(
* array('Content-Type', 'application/rss+xml; charset=utf-8'),
* );
* @endcode
*
* External 'js' and 'css' files can also be loaded. For example:
* @code
* $build['#attached']['js'] = array(
* 'http://code.jquery.com/jquery-1.4.2.min.js' => array(
* 'type' => 'external',
* ),
* );
* @endcode
*
* @param $elements
* The structured array describing the data being rendered.
* @param $group
* The default group of JavaScript and CSS being added. This is only applied
* to the stylesheets and JavaScript items that don't have an explicit group
* assigned to them.
* @param $dependency_check
* When TRUE, will exit if a given library's dependencies are missing. When
* set to FALSE, will continue to add the libraries, even though one or more
* dependencies are missing. Defaults to FALSE.
* @param $every_page
* Set to TRUE to indicate that the attachments are added to every page on the
* site. Only attachments with the every_page flag set to TRUE can participate
* in JavaScript/CSS aggregation.
*
* @return
* FALSE if there were any missing library dependencies; TRUE if all library
* dependencies were met.
*
* @see drupal_add_library()
* @see drupal_add_js()
* @see drupal_add_css()
* @see drupal_render()
*/
function drupal_process_attached($elements, $group = JS_DEFAULT, $dependency_check = FALSE, $every_page = NULL) {
// Add defaults to the special attached structures that should be processed differently.
$elements['#attached'] += array(
'library' => array(),
'js' => array(),
'css' => array(),
);

// Add the libraries first.
$success = TRUE;
foreach ($elements['#attached']['library'] as $library) {
if (drupal_add_library($library[0], $library[1], $every_page) === FALSE) {
$success = FALSE;
// Exit if the dependency is missing.
if ($dependency_check) {
return $success;
}
}
}
unset($elements['#attached']['library']);

// Add both the JavaScript and the CSS.
// The parameters for drupal_add_js() and drupal_add_css() require special
// handling.
foreach (array('js', 'css') as $type) {
foreach ($elements['#attached'][$type] as $data => $options) {
// If the value is not an array, it's a filename and passed as first
// (and only) argument.
if (!is_array($options)) {
$data = $options;
$options = NULL;
}
// In some cases, the first parameter ($data) is an array. Arrays can't be
// passed as keys in PHP, so we have to get $data from the value array.
if (is_numeric($data)) {
$data = $options['data'];
unset($options['data']);
}
// Apply the default group if it isn't explicitly given.
if (!isset($options['group'])) {
$options['group'] = $group;
}
// Set the every_page flag if one was passed.
if (isset($every_page)) {
$options['every_page'] = $every_page;
}
call_user_func('drupal_add_' . $type, $data, $options);
}
unset($elements['#attached'][$type]);
}

// Add additional types of attachments specified in the render() structure.
// Libraries, JavaScript and CSS have been added already, as they require
// special handling.
foreach ($elements['#attached'] as $callback => $options) {
if (function_exists($callback)) {
foreach ($elements['#attached'][$callback] as $args) {
call_user_func_array($callback, $args);
}
}
}

return $success;
}

/**
* Adds JavaScript to change the state of an element based on another element.
*
* A "state" means a certain property on a DOM element, such as "visible" or
* "checked". A state can be applied to an element, depending on the state of
* another element on the page. In general, states depend on HTML attributes and
* DOM element properties, which change due to user interaction.
*
* Since states are driven by JavaScript only, it is important to understand
* that all states are applied on presentation only, none of the states force
* any server-side logic, and that they will not be applied for site visitors
* without JavaScript support. All modules implementing states have to make
* sure that the intended logic also works without JavaScript being enabled.
*
* #states is an associative array in the form of:
* @code
* array(
* STATE1 => CONDITIONS_ARRAY1,
* STATE2 => CONDITIONS_ARRAY2,
* ...
* )
* @endcode
* Each key is the name of a state to apply to the element, such as 'visible'.
* Each value is a list of conditions that denote when the state should be
* applied.
*
* Multiple different states may be specified to act on complex conditions:
* @code
* array(
* 'visible' => CONDITIONS,
* 'checked' => OTHER_CONDITIONS,
* )
* @endcode
*
* Every condition is a key/value pair, whose key is a jQuery selector that
* denotes another element on the page, and whose value is an array of
* conditions, which must bet met on that element:
* @code
* array(
* 'visible' => array(
* JQUERY_SELECTOR => REMOTE_CONDITIONS,
* JQUERY_SELECTOR => REMOTE_CONDITIONS,
* ...
* ),
* )
* @endcode
* All conditions must be met for the state to be applied.
*
* Each remote condition is a key/value pair specifying conditions on the other
* element that need to be met to apply the state to the element:
* @code
* array(
* 'visible' => array(
* ':input[name="remote_checkbox"]' => array('checked' => TRUE),
* ),
* )
* @endcode
*
* For example, to show a textfield only when a checkbox is checked:
* @code
* $form['toggle_me'] = array(
* '#type' => 'checkbox',
* '#title' => t('Tick this box to type'),
* );
* $form['settings'] = array(
* '#type' => 'textfield',
* '#states' => array(
* // Only show this field when the 'toggle_me' checkbox is enabled.
* 'visible' => array(
* ':input[name="toggle_me"]' => array('checked' => TRUE),
* ),
* ),
* );
* @endcode
*
* The following states may be applied to an element:
* - enabled
* - disabled
* - required
* - optional
* - visible
* - invisible
* - checked
* - unchecked
* - expanded
* - collapsed
*
* The following states may be used in remote conditions:
* - empty
* - filled
* - checked
* - unchecked
* - expanded
* - collapsed
* - value
*
* The following states exist for both elements and remote conditions, but are
* not fully implemented and may not change anything on the element:
* - relevant
* - irrelevant
* - valid
* - invalid
* - touched
* - untouched
* - readwrite
* - readonly
*
* When referencing select lists and radio buttons in remote conditions, a
* 'value' condition must be used:
* @code
* '#states' => array(
* // Show the settings if 'bar' has been selected for 'foo'.
* 'visible' => array(
* ':input[name="foo"]' => array('value' => 'bar'),
* ),
* ),
* @endcode
*
* @param $elements
* A renderable array element having a #states property as described above.
*
* @see form_example_states_form()
*/
function drupal_process_states(&$elements) {
$elements['#attached']['library'][] = array('system', 'drupal.states');
$elements['#attached']['js'][] = array(
'type' => 'setting',
'data' => array('states' => array('#' . $elements['#id'] => $elements['#states'])),
);
}

/**
* Adds multiple JavaScript or CSS files at the same time.
*
* A library defines a set of JavaScript and/or CSS files, optionally using
* settings, and optionally requiring another library. For example, a library
* can be a jQuery plugin, a JavaScript framework, or a CSS framework. This
* function allows modules to load a library defined/shipped by itself or a
* depending module, without having to add all files of the library separately.
* Each library is only loaded once.
*
* @param $module
* The name of the module that registered the library.
* @param $name
* The name of the library to add.
* @param $every_page
* Set to TRUE if this library is added to every page on the site. Only items
* with the every_page flag set to TRUE can participate in aggregation.
*
* @return
* TRUE if the library was successfully added; FALSE if the library or one of
* its dependencies could not be added.
*
* @see drupal_get_library()
* @see hook_library()
* @see hook_library_alter()
*/
function drupal_add_library($module, $name, $every_page = NULL) {
$added = &drupal_static(__FUNCTION__, array());

// Only process the library if it exists and it was not added already.
if (!isset($added[$module][$name])) {
if ($library = drupal_get_library($module, $name)) {
// Add all components within the library.
$elements['#attached'] = array(
'library' => $library['dependencies'],
'js' => $library['js'],
'css' => $library['css'],
);
$added[$module][$name] = drupal_process_attached($elements, JS_LIBRARY, TRUE, $every_page);
} else {
// Requested library does not exist.
$added[$module][$name] = FALSE;
}
}

return $added[$module][$name];
}

/**
* Retrieves information for a JavaScript/CSS library.
*
* Library information is statically cached. Libraries are keyed by module for
* several reasons:
* - Libraries are not unique. Multiple modules might ship with the same library
* in a different version or variant. This registry cannot (and does not
* attempt to) prevent library conflicts.
* - Modules implementing and thereby depending on a library that is registered
* by another module can only rely on that module's library.
* - Two (or more) modules can still register the same library and use it
* without conflicts in case the libraries are loaded on certain pages only.
*
* @param $module
* The name of a module that registered a library.
* @param $name
* (optional) The name of a registered library to retrieve. By default, all
* libraries registered by $module are returned.
*
* @return
* The definition of the requested library, if $name was passed and it exists,
* or FALSE if it does not exist. If no $name was passed, an associative array
* of libraries registered by $module is returned (which may be empty).
*
* @see drupal_add_library()
* @see hook_library()
* @see hook_library_alter()
*
* @todo The purpose of drupal_get_*() is completely different to other page
* requisite API functions; find and use a different name.
*/
function drupal_get_library($module, $name = NULL) {
$libraries = &drupal_static(__FUNCTION__, array());

if (!isset($libraries[$module])) {
// Retrieve all libraries associated with the module.
$module_libraries = module_invoke($module, 'library');
if (empty($module_libraries)) {
$module_libraries = array();
}
// Allow modules to alter the module's registered libraries.
drupal_alter('library', $module_libraries, $module);

foreach ($module_libraries as $key => $data) {
if (is_array($data)) {
// Add default elements to allow for easier processing.
$module_libraries[$key] += array('dependencies' => array(), 'js' => array(), 'css' => array());
foreach ($module_libraries[$key]['js'] as $file => $options) {
$module_libraries[$key]['js'][$file]['version'] = $module_libraries[$key]['version'];
}
}
}
$libraries[$module] = $module_libraries;
}
if (isset($name)) {
if (!isset($libraries[$module][$name])) {
$libraries[$module][$name] = FALSE;
}
return $libraries[$module][$name];
}
return $libraries[$module];
}

/**
* Assists in adding the tableDrag JavaScript behavior to a themed table.
*
* Draggable tables should be used wherever an outline or list of sortable items
* needs to be arranged by an end-user. Draggable tables are very flexible and
* can manipulate the value of form elements placed within individual columns.
*
* To set up a table to use drag and drop in place of weight select-lists or in
* place of a form that contains parent relationships, the form must be themed
* into a table. The table must have an ID attribute set. If using
* theme_table(), the ID may be set as follows:
* @code
* $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'my-module-table')));
* return $output;
* @endcode
*
* In the theme function for the form, a special class must be added to each
* form element within the same column, "grouping" them together.
*
* In a situation where a single weight column is being sorted in the table, the
* classes could be added like this (in the theme function):
* @code
* $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
* @endcode
*
* Each row of the table must also have a class of "draggable" in order to
* enable the drag handles:
* @code
* $row = array(...);
* $rows[] = array(
* 'data' => $row,
* 'class' => array('draggable'),
* );
* @endcode
*
* When tree relationships are present, the two additional classes
* 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
* - Rows with the 'tabledrag-leaf' class cannot have child rows.
* - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
*
* Calling drupal_add_tabledrag() would then be written as such:
* @code
* drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
* @endcode
*
* In a more complex case where there are several groups in one column (such as
* the block regions on the admin/structure/block page), a separate subgroup
* class must also be added to differentiate the groups.
* @code
* $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
* @endcode
*
* $group is still 'my-element-weight', and the additional $subgroup variable
* will be passed in as 'my-elements-weight-' . $region. This also means that
* you'll need to call drupal_add_tabledrag() once for every region added.
*
* @code
* foreach ($regions as $region) {
* drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-' . $region);
* }
* @endcode
*
* In a situation where tree relationships are present, adding multiple
* subgroups is not necessary, because the table will contain indentations that
* provide enough information about the sibling and parent relationships. See
* theme_menu_overview_form() for an example creating a table containing parent
* relationships.
*
* Note that this function should be called from the theme layer, such as in a
* .tpl.php file, theme_ function, or in a template_preprocess function, not in
* a form declaration. Though the same JavaScript could be added to the page
* using drupal_add_js() directly, this function helps keep template files
* clean and readable. It also prevents tabledrag.js from being added twice
* accidentally.
*
* @param $table_id
* String containing the target table's id attribute. If the table does not
* have an id, one will need to be set, such as <table id="my-module-table">.
* @param $action
* String describing the action to be done on the form item. Either 'match'
* 'depth', or 'order'. Match is typically used for parent relationships.
* Order is typically used to set weights on other form elements with the same
* group. Depth updates the target element with the current indentation.
* @param $relationship
* String describing where the $action variable should be performed. Either
* 'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
* up the tree. Sibling will look for fields in the same group in rows above
* and below it. Self affects the dragged row itself. Group affects the
* dragged row, plus any children below it (the entire dragged group).
* @param $group
* A class name applied on all related form elements for this action.
* @param $subgroup
* (optional) If the group has several subgroups within it, this string should
* contain the class name identifying fields in the same subgroup.
* @param $source
* (optional) If the $action is 'match', this string should contain the class
* name identifying what field will be used as the source value when matching
* the value in $subgroup.
* @param $hidden
* (optional) The column containing the field elements may be entirely hidden
* from view dynamically when the JavaScript is loaded. Set to FALSE if the
* column should not be hidden.
* @param $limit
* (optional) Limit the maximum amount of parenting in this table.
* @see block-admin-display-form.tpl.php
* @see theme_menu_overview_form()
*/
function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
$js_added = &drupal_static(__FUNCTION__, FALSE);
if (!$js_added) {
// Add the table drag JavaScript to the page before the module JavaScript
// to ensure that table drag behaviors are registered before any module
// uses it.
drupal_add_library('system', 'jquery.cookie');
drupal_add_js('misc/tabledrag.js', array('weight' => -1));
$js_added = TRUE;
}

// If a subgroup or source isn't set, assume it is the same as the group.
$target = isset($subgroup) ? $subgroup : $group;
$source = isset($source) ? $source : $target;
$settings['tableDrag'][$table_id][$group][] = array(
'target' => $target,
'source' => $source,
'relationship' => $relationship,
'action' => $action,
'hidden' => $hidden,
'limit' => $limit,
);
drupal_add_js($settings, 'setting');
}

/**
* Aggregates JavaScript files into a cache file in the files directory.
*
* The file name for the JavaScript cache file is generated from the hash of
* the aggregated contents of the files in $files. This forces proxies and
* browsers to download new JavaScript when the JavaScript changes.
*
* The cache file name is retrieved on a page load via a lookup variable that
* contains an associative array. The array key is the hash of the names in
* $files while the value is the cache file name. The cache file is generated
* in two cases. First, if there is no file name value for the key, which will
* happen if a new file name has been added to $files or after the lookup
* variable is emptied to force a rebuild of the cache. Second, the cache file
* is generated if it is missing on disk. Old cache files are not deleted
* immediately when the lookup variable is emptied, but are deleted after a set
* period by drupal_delete_file_if_stale(). This ensures that files referenced
* by a cached page will still be available.
*
* @param $files
* An array of JavaScript files to aggregate and compress into one file.
*
* @return
* The URI of the cache file, or FALSE if the file could not be saved.
*/
function drupal_build_js_cache($files) {
$contents = '';
$uri = '';
$map = variable_get('drupal_js_cache_files', array());
// Create a new array so that only the file names are used to create the hash.
// This prevents new aggregates from being created unnecessarily.
$js_data = array();
foreach ($files as $file) {
$js_data[] = $file['data'];
}
$key = hash('sha256', serialize($js_data));
if (isset($map[$key])) {
$uri = $map[$key];
}

if (empty($uri) || !file_exists($uri)) {
// Build aggregate JS file.
foreach ($files as $path => $info) {
if ($info['preprocess']) {
// Append a ';' and a newline after each JS file to prevent them from running together.
$contents .= file_get_contents($path) . ";\n";
}
}
// Prefix filename to prevent blocking by firewalls which reject files
// starting with "ad*".
$filename = 'js_' . drupal_hash_base64($contents) . '.js';
// Create the js/ within the files folder.
$jspath = 'public://js';
$uri = $jspath . '/' . $filename;
// Create the JS file.
file_prepare_directory($jspath, FILE_CREATE_DIRECTORY);
if (!file_exists($uri) && !file_unmanaged_save_data($contents, $uri, FILE_EXISTS_REPLACE)) {
return FALSE;
}
// If JS gzip compression is enabled, clean URLs are enabled (which means
// that rewrite rules are working) and the zlib extension is available then
// create a gzipped version of this file. This file is served conditionally
// to browsers that accept gzip using .htaccess rules.
if (variable_get('js_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($contents, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
return FALSE;
}
}
$map[$key] = $uri;
variable_set('drupal_js_cache_files', $map);
}
return $uri;
}

/**
* Deletes old cached JavaScript files and variables.
*/
function drupal_clear_js_cache() {
variable_del('javascript_parsed');
variable_del('drupal_js_cache_files');
file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
}

/**
* Converts a PHP variable into its JavaScript equivalent.
*
* We use HTML-safe strings, with several characters escaped.
*
* @see drupal_json_decode()
* @see drupal_json_encode_helper()
* @ingroup php_wrappers
*/
function drupal_json_encode($var) {
// The PHP version cannot change within a request.
static $php530;

if (!isset($php530)) {
$php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
}

if ($php530) {
// Encode <, >, ', &, and " using the json_encode() options parameter.
return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
}

// json_encode() escapes <, >, ', &, and " using its options parameter, but
// does not support this parameter prior to PHP 5.3.0. Use a helper instead.
include_once DRUPAL_ROOT . '/includes/json-encode.inc';
return drupal_json_encode_helper($var);
}

/**
* Converts an HTML-safe JSON string into its PHP equivalent.
*
* @see drupal_json_encode()
* @ingroup php_wrappers
*/
function drupal_json_decode($var) {
return json_decode($var, TRUE);
}

/**
* Returns data in JSON format.
*
* This function should be used for JavaScript callback functions returning
* data in JSON format. It sets the header for JavaScript output.
*
* @param $var
* (optional) If set, the variable will be converted to JSON and output.
*/
function drupal_json_output($var = NULL) {
// We are returning JSON, so tell the browser.
drupal_add_http_header('Content-Type', 'application/json');

if (isset($var)) {
echo drupal_json_encode($var);
}
}

/**
* Ensures the private key variable used to generate tokens is set.
*
* @return
* The private key.
*/
function drupal_get_private_key() {
if (!($key = variable_get('drupal_private_key', 0))) {
$key = drupal_random_key();
variable_set('drupal_private_key', $key);
}
return $key;
}

/**
* Generates a token based on $value, the user session, and the private key.
*
* @param $value
* An additional value to base the token on.
*
* The generated token is based on the session ID of the current user. Normally,
* anonymous users do not have a session, so the generated token will be
* different on every page request. To generate a token for users without a
* session, manually start a session prior to calling this function.
*
* @return string
* A 43-character URL-safe token for validation, based on the user session ID,
* the hash salt provided from drupal_get_hash_salt(), and the
* 'drupal_private_key' configuration variable.
*
* @see drupal_get_hash_salt()
*/
function drupal_get_token($value = '') {
return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
}

/**
* Validates a token based on $value, the user session, and the private key.
*
* @param $token
* The token to be validated.
* @param $value
* An additional value to base the token on.
* @param $skip_anonymous
* Set to true to skip token validation for anonymous users.
*
* @return
* True for a valid token, false for an invalid token. When $skip_anonymous
* is true, the return value will always be true for anonymous users.
*/
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
global $user;
return (($skip_anonymous && $user->uid == 0) || ($token === drupal_get_token($value)));
}

function _drupal_bootstrap_full() {
static $called = FALSE;

if ($called) {
return;
}
$called = TRUE;
require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
require_once DRUPAL_ROOT . '/includes/theme.inc';
require_once DRUPAL_ROOT . '/includes/pager.inc';
require_once DRUPAL_ROOT . '/' . variable_get('menu_inc', 'includes/menu.inc');
require_once DRUPAL_ROOT . '/includes/tablesort.inc';
require_once DRUPAL_ROOT . '/includes/file.inc';
require_once DRUPAL_ROOT . '/includes/unicode.inc';
require_once DRUPAL_ROOT . '/includes/image.inc';
require_once DRUPAL_ROOT . '/includes/form.inc';
require_once DRUPAL_ROOT . '/includes/mail.inc';
require_once DRUPAL_ROOT . '/includes/actions.inc';
require_once DRUPAL_ROOT . '/includes/ajax.inc';
require_once DRUPAL_ROOT . '/includes/token.inc';
require_once DRUPAL_ROOT . '/includes/errors.inc';

// Detect string handling method
unicode_check();
// Undo magic quotes
fix_gpc_magic();
// Load all enabled modules
module_load_all();
// Reset drupal_alter() and module_implements() static caches as these
// include implementations for vital modules only when called early on
// in the bootstrap.
drupal_static_reset('drupal_alter');
drupal_static_reset('module_implements');
// Make sure all stream wrappers are registered.
file_get_stream_wrappers();
// Ensure mt_rand is reseeded, to prevent random values from one page load
// being exploited to predict random values in subsequent page loads.
$seed = unpack("L", drupal_random_bytes(4));
mt_srand($seed[1]);

$test_info = &$GLOBALS['drupal_test_info'];
if (!empty($test_info['in_child_site'])) {
// Running inside the simpletest child site, log fatal errors to test
// specific file directory.
ini_set('log_errors', 1);
ini_set('error_log', 'public://error.log');
}

// Initialize $_GET['q'] prior to invoking hook_init().
drupal_path_initialize();

// Let all modules take action before the menu system handles the request.
// We do not want this while running update.php.
if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
// Prior to invoking hook_init(), initialize the theme (potentially a custom
// one for this page), so that:
// - Modules with hook_init() implementations that call theme() or
// theme_get_registry() don't initialize the incorrect theme.
// - The theme can have hook_*_alter() implementations affect page building
// (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
// ahead of when rendering starts.
menu_set_custom_theme();
drupal_theme_initialize();
module_invoke_all('init');
}
}

/**
* Stores the current page in the cache.
*
* If page_compression is enabled, a gzipped version of the page is stored in
* the cache to avoid compressing the output on each request. The cache entry
* is unzipped in the relatively rare event that the page is requested by a
* client without gzip support.
*
* Page compression requires the PHP zlib extension
* (http://php.net/manual/ref.zlib.php).
*
* @see drupal_page_header()
*/
function drupal_page_set_cache() {
global $base_root;

if (drupal_page_is_cacheable()) {

// Check whether the current page might be compressed.
$page_compressed = variable_get('page_compression', TRUE) && extension_loaded('zlib');

$cache = (object) array(
'cid' => $base_root . request_uri(),
'data' => array(
'path' => $_GET['q'],
'body' => ob_get_clean(),
'title' => drupal_get_title(),
'headers' => array(),
// We need to store whether page was compressed or not,
// because by the time it is read, the configuration might change.
'page_compressed' => $page_compressed,
),
'expire' => CACHE_TEMPORARY,
'created' => REQUEST_TIME,
);

// Restore preferred header names based on the lower-case names returned
// by drupal_get_http_header().
$header_names = _drupal_set_preferred_header_name();
foreach (drupal_get_http_header() as $name_lower => $value) {
$cache->data['headers'][$header_names[$name_lower]] = $value;
if ($name_lower == 'expires') {
// Use the actual timestamp from an Expires header if available.
$cache->expire = strtotime($value);
}
}

if ($cache->data['body']) {
if ($page_compressed) {
$cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
}
cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
}
return $cache;
}
}

/**
* Executes a cron run when called.
*
* Do not call this function from a test. Use $this->cronRun() instead.
*
* @return bool
* TRUE if cron ran successfully and FALSE if cron is already running.
*/
function drupal_cron_run() {
// Allow execution to continue even if the request gets canceled.
@ignore_user_abort(TRUE);

// Prevent session information from being saved while cron is running.
$original_session_saving = drupal_save_session();
drupal_save_session(FALSE);

// Force the current user to anonymous to ensure consistent permissions on
// cron runs.
$original_user = $GLOBALS['user'];
$GLOBALS['user'] = drupal_anonymous_user();

// Try to allocate enough time to run all the hook_cron implementations.
drupal_set_time_limit(240);

$return = FALSE;
// Grab the defined cron queues.
$queues = module_invoke_all('cron_queue_info');
drupal_alter('cron_queue_info', $queues);

// Try to acquire cron lock.
if (!lock_acquire('cron', 240.0)) {
// Cron is still running normally.
watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
} else {
// Make sure every queue exists. There is no harm in trying to recreate an
// existing queue.
foreach ($queues as $queue_name => $info) {
DrupalQueue::get($queue_name)->createQueue();
}

// Iterate through the modules calling their cron handlers (if any):
foreach (module_implements('cron') as $module) {
// Do not let an exception thrown by one module disturb another.
try {
module_invoke($module, 'cron');
} catch (Exception $e) {
watchdog_exception('cron', $e);
}
}

// Record cron time.
variable_set('cron_last', REQUEST_TIME);
watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);

// Release cron lock.
lock_release('cron');

// Return TRUE so other functions can check if it did run successfully
$return = TRUE;
}

foreach ($queues as $queue_name => $info) {
if (!empty($info['skip on cron'])) {
// Do not run if queue wants to skip.
continue;
}
$callback = $info['worker callback'];
$end = time() + (isset($info['time']) ? $info['time'] : 15);
$queue = DrupalQueue::get($queue_name);
while (time() < $end && ($item = $queue->claimItem())) {
try {
call_user_func($callback, $item->data);
$queue->deleteItem($item);
} catch (Exception $e) {
// In case of exception log it and leave the item in the queue
// to be processed again later.
watchdog_exception('cron', $e);
}
}
}
// Restore the user.
$GLOBALS['user'] = $original_user;
drupal_save_session($original_session_saving);

return $return;
}

/**
* DEPRECATED: Shutdown function: Performs cron cleanup.
*
* This function is deprecated because the 'cron_semaphore' variable it
* references no longer exists. It is therefore no longer used as a shutdown
* function by Drupal core.
*
* @deprecated
*/
function drupal_cron_cleanup() {
// See if the semaphore is still locked.
if (variable_get('cron_semaphore', FALSE)) {
watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);

// Release cron semaphore.
variable_del('cron_semaphore');
}
}

/**
* Returns information about system object files (modules, themes, etc.).
*
* This function is used to find all or some system object files (module files,
* theme files, etc.) that exist on the site. It searches in several locations,
* depending on what type of object you are looking for. For instance, if you
* are looking for modules and call:
* @code
* drupal_system_listing("/\.module$/", "modules", 'name', 0);
* @endcode
* this function will search the site-wide modules directory (i.e., /modules/),
* your installation profile's directory (i.e.,
* /profiles/your_site_profile/modules/), the all-sites directory (i.e.,
* /sites/all/modules/), and your site-specific directory (i.e.,
* /sites/your_site_dir/modules/), in that order, and return information about
* all of the files ending in .module in those directories.
*
* The information is returned in an associative array, which can be keyed on
* the file name ($key = 'filename'), the file name without the extension ($key
* = 'name'), or the full file stream URI ($key = 'uri'). If you use a key of
* 'filename' or 'name', files found later in the search will take precedence
* over files found earlier (unless they belong to a module or theme not
* compatible with Drupal core); if you choose a key of 'uri', you will get all
* files found.
*
* @param string $mask
* The preg_match() regular expression for the files to find.
* @param string $directory
* The subdirectory name in which the files are found. For example,
* 'modules' will search in sub-directories of the top-level /modules
* directory, sub-directories of /sites/all/modules/, etc.
* @param string $key
* The key to be used for the associative array returned. Possible values are
* 'uri', for the file's URI; 'filename', for the basename of the file; and
* 'name' for the name of the file without the extension. If you choose 'name'
* or 'filename', only the highest-precedence file will be returned.
* @param int $min_depth
* Minimum depth of directories to return files from, relative to each
* directory searched. For instance, a minimum depth of 2 would find modules
* inside /modules/node/tests, but not modules directly in /modules/node.
*
* @return array
* An associative array of file objects, keyed on the chosen key. Each element
* in the array is an object containing file information, with properties:
* - 'uri': Full URI of the file.
* - 'filename': File name.
* - 'name': Name of file without the extension.
*/
function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
$config = conf_path();

$searchdir = array($directory);
$files = array();

// The 'profiles' directory contains pristine collections of modules and
// themes as organized by a distribution. It is pristine in the same way
// that /modules is pristine for core; users should avoid changing anything
// there in favor of sites/all or sites/<domain> directories.
$profiles = array();
$profile = drupal_get_profile();
// For SimpleTest to be able to test modules packaged together with a
// distribution we need to include the profile of the parent site (in which
// test runs are triggered).
if (drupal_valid_test_ua()) {
$testing_profile = variable_get('simpletest_parent_profile', FALSE);
if ($testing_profile && $testing_profile != $profile) {
$profiles[] = $testing_profile;
}
}
// In case both profile directories contain the same extension, the actual
// profile always has precedence.
$profiles[] = $profile;
foreach ($profiles as $profile) {
if (file_exists("profiles/$profile/$directory")) {
$searchdir[] = "profiles/$profile/$directory";
}
}

// Always search sites/all/* as well as the global directories.
$searchdir[] = 'sites/all/' . $directory;

if (file_exists("$config/$directory")) {
$searchdir[] = "$config/$directory";
}

// Get current list of items.
if (!function_exists('file_scan_directory')) {
require_once DRUPAL_ROOT . '/includes/file.inc';
}
foreach ($searchdir as $dir) {
$files_to_add = file_scan_directory($dir, $mask, array('key' => $key, 'min_depth' => $min_depth));

// Duplicate files found in later search directories take precedence over
// earlier ones, so we want them to overwrite keys in our resulting
// $files array.
// The exception to this is if the later file is from a module or theme not
// compatible with Drupal core. This may occur during upgrades of Drupal
// core when new modules exist in core while older contrib modules with the
// same name exist in a directory such as sites/all/modules/.
foreach (array_intersect_key($files_to_add, $files) as $file_key => $file) {
// If it has no info file, then we just behave liberally and accept the
// new resource on the list for merging.
if (file_exists($info_file = dirname($file->uri) . '/' . $file->name . '.info')) {
// Get the .info file for the module or theme this file belongs to.
$info = drupal_parse_info_file($info_file);

// If the module or theme is incompatible with Drupal core, remove it
// from the array for the current search directory, so it is not
// overwritten when merged with the $files array.
if (isset($info['core']) && $info['core'] != DRUPAL_CORE_COMPATIBILITY) {
unset($files_to_add[$file_key]);
}
}
}
$files = array_merge($files, $files_to_add);
}

return $files;
}

/**
* Sets the main page content value for later use.
*
* Given the nature of the Drupal page handling, this will be called once with
* a string or array. We store that and return it later as the block is being
* displayed.
*
* @param $content
* A string or renderable array representing the body of the page.
*
* @return
* If called without $content, a renderable array representing the body of
* the page.
*/
function drupal_set_page_content($content = NULL) {
$content_block = &drupal_static(__FUNCTION__, NULL);
$main_content_display = &drupal_static('system_main_content_added', FALSE);

if (!empty($content)) {
$content_block = (is_array($content) ? $content : array('main' => array('#markup' => $content)));
} else {
// Indicate that the main content has been requested. We assume that
// the module requesting the content will be adding it to the page.
// A module can indicate that it does not handle the content by setting
// the static variable back to FALSE after calling this function.
$main_content_display = TRUE;
return $content_block;
}
}

/**
* #pre_render callback to render #browsers into #prefix and #suffix.
*
* @param $elements
* A render array with a '#browsers' property. The '#browsers' property can
* contain any or all of the following keys:
* - 'IE': If FALSE, the element is not rendered by Internet Explorer. If
* TRUE, the element is rendered by Internet Explorer. Can also be a string
* containing an expression for Internet Explorer to evaluate as part of a
* conditional comment. For example, this can be set to 'lt IE 7' for the
* element to be rendered in Internet Explorer 6, but not in Internet
* Explorer 7 or higher. Defaults to TRUE.
* - '!IE': If FALSE, the element is not rendered by browsers other than
* Internet Explorer. If TRUE, the element is rendered by those browsers.
* Defaults to TRUE.
* Examples:
* - To render an element in all browsers, '#browsers' can be left out or set
* to array('IE' => TRUE, '!IE' => TRUE).
* - To render an element in Internet Explorer only, '#browsers' can be set
* to array('!IE' => FALSE).
* - To render an element in Internet Explorer 6 only, '#browsers' can be set
* to array('IE' => 'lt IE 7', '!IE' => FALSE).
* - To render an element in Internet Explorer 8 and higher and in all other
* browsers, '#browsers' can be set to array('IE' => 'gte IE 8').
*
* @return
* The passed-in element with markup for conditional comments potentially
* added to '#prefix' and '#suffix'.
*/
function drupal_pre_render_conditional_comments($elements) {
$browsers = isset($elements['#browsers']) ? $elements['#browsers'] : array();
$browsers += array(
'IE' => TRUE,
'!IE' => TRUE,
);

// If rendering in all browsers, no need for conditional comments.
if ($browsers['IE'] === TRUE && $browsers['!IE']) {
return $elements;
}

// Determine the conditional comment expression for Internet Explorer to
// evaluate.
if ($browsers['IE'] === TRUE) {
$expression = 'IE';
} elseif ($browsers['IE'] === FALSE) {
$expression = '!IE';
} else {
$expression = $browsers['IE'];
}

// Wrap the element's potentially existing #prefix and #suffix properties with
// conditional comment markup. The conditional comment expression is evaluated
// by Internet Explorer only. To control the rendering by other browsers,
// either the "downlevel-hidden" or "downlevel-revealed" technique must be
// used. See http://en.wikipedia.org/wiki/Conditional_comment for details.
$elements += array(
'#prefix' => '',
'#suffix' => '',
);
if (!$browsers['!IE']) {
// "downlevel-hidden".
$elements['#prefix'] = "\n<!--[if $expression]>\n" . $elements['#prefix'];
$elements['#suffix'] .= "<![endif]-->\n";
} else {
// "downlevel-revealed".
$elements['#prefix'] = "\n<!--[if $expression]><!-->\n" . $elements['#prefix'];
$elements['#suffix'] .= "<!--<![endif]-->\n";
}