bootstrap.inc

Functions that need to be loaded on every Drupal request.

Functions

Namesort descending Description
arg Returns a component of the current Drupal path.
bootstrap_hooks Defines the critical hooks that force modules to always be loaded.
bootstrap_invoke_all Invokes a bootstrap hook in all bootstrap modules that implement it.
check_plain Encodes special characters in a plain-text string for display as HTML.
conf_path Returns the appropriate configuration directory.
drupal_add_http_header Sets an HTTP response header for the current page.
drupal_anonymous_user Generates a default anonymous $user object.
drupal_array_merge_deep Merges multiple arrays, recursively, and returns the merged array.
drupal_array_merge_deep_array Merges multiple arrays, recursively, and returns the merged array.
drupal_autoload_class Confirms that a class is available.
drupal_autoload_interface Confirms that an interface is available.
drupal_block_denied Handles denied users.
drupal_bootstrap Ensures Drupal is bootstrapped to the specified phase.
drupal_environment_initialize Initializes the PHP environment.
drupal_fast_404 Returns a simple 404 Not Found page.
drupal_generate_test_ua Generates a user agent string with a HMAC and timestamp for simpletest.
drupal_get_bootstrap_phase Returns the current bootstrap phase for this Drupal process.
drupal_get_complete_schema Gets the whole database schema.
drupal_get_filename Returns and optionally sets the filename for a system resource.
drupal_get_http_header Gets the HTTP response headers for the current page.
drupal_get_messages Returns all messages that have been set with drupal_set_message().
drupal_get_schema Gets the schema definition of a table, or the whole database schema.
drupal_get_title Gets the title of the current page.
drupal_get_user_timezone Returns the time zone of the current user.
drupal_hash_base64 Calculates a base-64 encoded, URL-safe sha-256 hash.
drupal_hmac_base64 Calculates a base-64 encoded, URL-safe sha-256 hmac.
drupal_installation_attempted Returns TRUE if a Drupal installation is currently being attempted.
drupal_is_cli Detects whether the current script is running in a command-line environment.
drupal_is_denied Checks to see if an IP address has been blocked.
drupal_language_initialize Initializes all the defined language types.
drupal_language_types Returns a list of the built-in language types.
drupal_load Includes a file with the provided type and name.
drupal_maintenance_theme Enables use of the theme system without requiring database access.
drupal_multilingual Returns TRUE if there is more than one language enabled.
drupal_override_server_variables Sets appropriate server variables needed for command line scripts to work.
drupal_page_get_cache Retrieves the current page from the cache.
drupal_page_header Sets HTTP headers in preparation for a page response.
drupal_page_is_cacheable Determines the cacheability of the current page.
drupal_placeholder Formats text for emphasized display in a placeholder inside a sentence.
drupal_random_bytes Returns a string of highly randomized bytes (over the full 8-bit range).
drupal_register_shutdown_function Registers a function for execution on shutdown.
drupal_send_headers Sends the HTTP response headers that were previously set, adding defaults.
drupal_serve_page_from_cache Sets HTTP headers in preparation for a cached page response.
drupal_settings_initialize Sets the base URL, cookie domain, and session name from configuration.
drupal_set_message Sets a message to display to the user.
drupal_set_title Sets the title of the current page.
drupal_static Provides central static variable storage.
drupal_static_reset Resets one or all centrally stored static variable(s).
drupal_unpack Unserializes and appends elements from a serialized string.
drupal_validate_utf8 Checks whether a string is valid UTF-8.
drupal_valid_http_host Validates that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
drupal_valid_test_ua Returns the test prefix if this is an internal request from SimpleTest.
format_string Replaces placeholders with sanitized values in a string.
get_t Returns the name of the proper localization function.
ip_address Returns the IP address of the client machine.
language_default Returns the default language used on the site
language_list Returns a list of installed languages, indexed by the specified key.
language_types Returns an array of the available language types.
registry_rebuild Rescans all enabled modules and rebuilds the registry.
registry_update Updates the registry based on the latest files listed in the database.
request_path Returns the requested URL path of the page being viewed.
request_uri Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
t Translates a string to the current language or to a given language.
timer_read Reads the current timer value without stopping the timer.
timer_start Starts the timer with the specified name.
timer_stop Stops the timer with the specified name.
variable_del Unsets a persistent variable.
variable_get Returns a persistent variable.
variable_initialize Loads the persistent variable table.
variable_set Sets a persistent variable.
watchdog Logs a system message.
watchdog_exception Logs an exception.
_drupal_bootstrap_configuration Sets up the script environment and loads settings.php.
_drupal_bootstrap_database Initializes the database system and registers autoload functions.
_drupal_bootstrap_page_cache Attempts to serve a page from the cache.
_drupal_bootstrap_page_header Invokes hook_boot(), initializes locking system, and sends HTTP headers.
_drupal_bootstrap_variables Loads system variables and all enabled bootstrap modules.
_drupal_error_handler Provides custom PHP error handling.
_drupal_exception_handler Provides custom PHP exception handling.
_drupal_set_preferred_header_name Sets the preferred name for the HTTP header.
_drupal_shutdown_function Executes registered shutdown functions.
_registry_check_code Checks for a resource in the registry.

Constants

Namesort descending Description
CACHE_PERMANENT Indicates that the item should never be removed unless explicitly selected.
CACHE_TEMPORARY Indicates that the item should be removed at the next general cache wipe.
CHECK_PLAIN Flag for drupal_set_title(); text is not sanitized, so run check_plain().
DRUPAL_ANONYMOUS_RID Role ID for anonymous users; should match what's in the "role" table.
DRUPAL_AUTHENTICATED_RID Role ID for authenticated users; should match what's in the "role" table.
DRUPAL_BOOTSTRAP_CONFIGURATION First bootstrap phase: initialize configuration.
DRUPAL_BOOTSTRAP_DATABASE Third bootstrap phase: initialize database layer.
DRUPAL_BOOTSTRAP_FULL Final bootstrap phase: Drupal is fully loaded; validate and fix input data.
DRUPAL_BOOTSTRAP_LANGUAGE Seventh bootstrap phase: find out language of the page.
DRUPAL_BOOTSTRAP_PAGE_CACHE Second bootstrap phase: try to serve a cached page.
DRUPAL_BOOTSTRAP_PAGE_HEADER Sixth bootstrap phase: set up the page header.
DRUPAL_BOOTSTRAP_SESSION Fifth bootstrap phase: initialize session handling.
DRUPAL_BOOTSTRAP_VARIABLES Fourth bootstrap phase: initialize the variable system.
DRUPAL_CORE_COMPATIBILITY Core API compatibility.
DRUPAL_KILOBYTE The number of bytes in a kilobyte.
DRUPAL_MINIMUM_PHP Minimum supported version of PHP.
DRUPAL_MINIMUM_PHP_MEMORY_LIMIT Minimum recommended value of PHP memory_limit.
DRUPAL_PHP_FUNCTION_PATTERN Regular expression to match PHP function names.
ERROR_REPORTING_DISPLAY_ALL Error reporting level: display all messages.
ERROR_REPORTING_DISPLAY_SOME Error reporting level: display errors and warnings.
ERROR_REPORTING_HIDE Error reporting level: display no errors.
LANGUAGE_LTR Language written left to right. Possible value of $language->direction.
LANGUAGE_NONE The language code used when no language is explicitly assigned.
LANGUAGE_RTL Language written right to left. Possible value of $language->direction.
LANGUAGE_TYPE_CONTENT The type of language used to define the content language.
LANGUAGE_TYPE_INTERFACE The type of language used to select the user interface.
LANGUAGE_TYPE_URL The type of language used for URLs.
PASS_THROUGH Flag for drupal_set_title(); text has already been sanitized.
REGISTRY_RESET_LOOKUP_CACHE Signals that the registry lookup cache should be reset.
REGISTRY_WRITE_LOOKUP_CACHE Signals that the registry lookup cache should be written to storage.
REQUEST_TIME Time of the current request in seconds elapsed since the Unix Epoch.
VERSION The current system version.
WATCHDOG_ALERT Log message severity -- Alert: action must be taken immediately.
WATCHDOG_CRITICAL Log message severity -- Critical conditions.
WATCHDOG_DEBUG Log message severity -- Debug-level messages.
WATCHDOG_EMERGENCY Log message severity -- Emergency: system is unusable.
WATCHDOG_ERROR Log message severity -- Error conditions.
WATCHDOG_INFO Log message severity -- Informational messages.
WATCHDOG_NOTICE Log message severity -- Normal but significant conditions.
WATCHDOG_WARNING Log message severity -- Warning conditions.

Classes

Namesort descending Description
DrupalCacheArray Provides a caching wrapper to be used in place of large array structures.
SchemaCache Extends DrupalCacheArray to allow for dynamic building of the schema cache.

File

includes/bootstrap.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Functions that need to be loaded on every Drupal request.
  5. */
  6. /**
  7. * The current system version.
  8. */
  9. define('VERSION', '7.18-dev');
  10. /**
  11. * Core API compatibility.
  12. */
  13. define('DRUPAL_CORE_COMPATIBILITY', '7.x');
  14. /**
  15. * Minimum supported version of PHP.
  16. */
  17. define('DRUPAL_MINIMUM_PHP', '5.2.4');
  18. /**
  19. * Minimum recommended value of PHP memory_limit.
  20. */
  21. define('DRUPAL_MINIMUM_PHP_MEMORY_LIMIT', '32M');
  22. /**
  23. * Error reporting level: display no errors.
  24. */
  25. define('ERROR_REPORTING_HIDE', 0);
  26. /**
  27. * Error reporting level: display errors and warnings.
  28. */
  29. define('ERROR_REPORTING_DISPLAY_SOME', 1);
  30. /**
  31. * Error reporting level: display all messages.
  32. */
  33. define('ERROR_REPORTING_DISPLAY_ALL', 2);
  34. /**
  35. * Indicates that the item should never be removed unless explicitly selected.
  36. *
  37. * The item may be removed using cache_clear_all() with a cache ID.
  38. */
  39. define('CACHE_PERMANENT', 0);
  40. /**
  41. * Indicates that the item should be removed at the next general cache wipe.
  42. */
  43. define('CACHE_TEMPORARY', -1);
  44. /**
  45. * @defgroup logging_severity_levels Logging severity levels
  46. * @{
  47. * Logging severity levels as defined in RFC 3164.
  48. *
  49. * The WATCHDOG_* constant definitions correspond to the logging severity levels
  50. * defined in RFC 3164, section 4.1.1. PHP supplies predefined LOG_* constants
  51. * for use in the syslog() function, but their values on Windows builds do not
  52. * correspond to RFC 3164. The associated PHP bug report was closed with the
  53. * comment, "And it's also not a bug, as Windows just have less log levels,"
  54. * and "So the behavior you're seeing is perfectly normal."
  55. *
  56. * @see http://www.faqs.org/rfcs/rfc3164.html
  57. * @see http://bugs.php.net/bug.php?id=18090
  58. * @see http://php.net/manual/function.syslog.php
  59. * @see http://php.net/manual/network.constants.php
  60. * @see watchdog()
  61. * @see watchdog_severity_levels()
  62. */
  63. /**
  64. * Log message severity -- Emergency: system is unusable.
  65. */
  66. define('WATCHDOG_EMERGENCY', 0);
  67. /**
  68. * Log message severity -- Alert: action must be taken immediately.
  69. */
  70. define('WATCHDOG_ALERT', 1);
  71. /**
  72. * Log message severity -- Critical conditions.
  73. */
  74. define('WATCHDOG_CRITICAL', 2);
  75. /**
  76. * Log message severity -- Error conditions.
  77. */
  78. define('WATCHDOG_ERROR', 3);
  79. /**
  80. * Log message severity -- Warning conditions.
  81. */
  82. define('WATCHDOG_WARNING', 4);
  83. /**
  84. * Log message severity -- Normal but significant conditions.
  85. */
  86. define('WATCHDOG_NOTICE', 5);
  87. /**
  88. * Log message severity -- Informational messages.
  89. */
  90. define('WATCHDOG_INFO', 6);
  91. /**
  92. * Log message severity -- Debug-level messages.
  93. */
  94. define('WATCHDOG_DEBUG', 7);
  95. /**
  96. * @} End of "defgroup logging_severity_levels".
  97. */
  98. /**
  99. * First bootstrap phase: initialize configuration.
  100. */
  101. define('DRUPAL_BOOTSTRAP_CONFIGURATION', 0);
  102. /**
  103. * Second bootstrap phase: try to serve a cached page.
  104. */
  105. define('DRUPAL_BOOTSTRAP_PAGE_CACHE', 1);
  106. /**
  107. * Third bootstrap phase: initialize database layer.
  108. */
  109. define('DRUPAL_BOOTSTRAP_DATABASE', 2);
  110. /**
  111. * Fourth bootstrap phase: initialize the variable system.
  112. */
  113. define('DRUPAL_BOOTSTRAP_VARIABLES', 3);
  114. /**
  115. * Fifth bootstrap phase: initialize session handling.
  116. */
  117. define('DRUPAL_BOOTSTRAP_SESSION', 4);
  118. /**
  119. * Sixth bootstrap phase: set up the page header.
  120. */
  121. define('DRUPAL_BOOTSTRAP_PAGE_HEADER', 5);
  122. /**
  123. * Seventh bootstrap phase: find out language of the page.
  124. */
  125. define('DRUPAL_BOOTSTRAP_LANGUAGE', 6);
  126. /**
  127. * Final bootstrap phase: Drupal is fully loaded; validate and fix input data.
  128. */
  129. define('DRUPAL_BOOTSTRAP_FULL', 7);
  130. /**
  131. * Role ID for anonymous users; should match what's in the "role" table.
  132. */
  133. define('DRUPAL_ANONYMOUS_RID', 1);
  134. /**
  135. * Role ID for authenticated users; should match what's in the "role" table.
  136. */
  137. define('DRUPAL_AUTHENTICATED_RID', 2);
  138. /**
  139. * The number of bytes in a kilobyte.
  140. *
  141. * For more information, visit http://en.wikipedia.org/wiki/Kilobyte.
  142. */
  143. define('DRUPAL_KILOBYTE', 1024);
  144. /**
  145. * The language code used when no language is explicitly assigned.
  146. *
  147. * Defined by ISO639-2 for "Undetermined".
  148. */
  149. define('LANGUAGE_NONE', 'und');
  150. /**
  151. * The type of language used to define the content language.
  152. */
  153. define('LANGUAGE_TYPE_CONTENT', 'language_content');
  154. /**
  155. * The type of language used to select the user interface.
  156. */
  157. define('LANGUAGE_TYPE_INTERFACE', 'language');
  158. /**
  159. * The type of language used for URLs.
  160. */
  161. define('LANGUAGE_TYPE_URL', 'language_url');
  162. /**
  163. * Language written left to right. Possible value of $language->direction.
  164. */
  165. define('LANGUAGE_LTR', 0);
  166. /**
  167. * Language written right to left. Possible value of $language->direction.
  168. */
  169. define('LANGUAGE_RTL', 1);
  170. /**
  171. * Time of the current request in seconds elapsed since the Unix Epoch.
  172. *
  173. * This differs from $_SERVER['REQUEST_TIME'], which is stored as a float
  174. * since PHP 5.4.0. Float timestamps confuse most PHP functions
  175. * (including date_create()).
  176. *
  177. * @see http://php.net/manual/reserved.variables.server.php
  178. * @see http://php.net/manual/function.time.php
  179. */
  180. define('REQUEST_TIME', (int) $_SERVER['REQUEST_TIME']);
  181. /**
  182. * Flag for drupal_set_title(); text is not sanitized, so run check_plain().
  183. */
  184. define('CHECK_PLAIN', 0);
  185. /**
  186. * Flag for drupal_set_title(); text has already been sanitized.
  187. */
  188. define('PASS_THROUGH', -1);
  189. /**
  190. * Signals that the registry lookup cache should be reset.
  191. */
  192. define('REGISTRY_RESET_LOOKUP_CACHE', 1);
  193. /**
  194. * Signals that the registry lookup cache should be written to storage.
  195. */
  196. define('REGISTRY_WRITE_LOOKUP_CACHE', 2);
  197. /**
  198. * Regular expression to match PHP function names.
  199. *
  200. * @see http://php.net/manual/en/language.functions.php
  201. */
  202. define('DRUPAL_PHP_FUNCTION_PATTERN', '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*');
  203. /**
  204. * Provides a caching wrapper to be used in place of large array structures.
  205. *
  206. * This class should be extended by systems that need to cache large amounts
  207. * of data and have it represented as an array to calling functions. These
  208. * arrays can become very large, so ArrayAccess is used to allow different
  209. * strategies to be used for caching internally (lazy loading, building caches
  210. * over time etc.). This can dramatically reduce the amount of data that needs
  211. * to be loaded from cache backends on each request, and memory usage from
  212. * static caches of that same data.
  213. *
  214. * Note that array_* functions do not work with ArrayAccess. Systems using
  215. * DrupalCacheArray should use this only internally. If providing API functions
  216. * that return the full array, this can be cached separately or returned
  217. * directly. However since DrupalCacheArray holds partial content by design, it
  218. * should be a normal PHP array or otherwise contain the full structure.
  219. *
  220. * Note also that due to limitations in PHP prior to 5.3.4, it is impossible to
  221. * write directly to the contents of nested arrays contained in this object.
  222. * Only writes to the top-level array elements are possible. So if you
  223. * previously had set $object['foo'] = array(1, 2, 'bar' => 'baz'), but later
  224. * want to change the value of 'bar' from 'baz' to 'foobar', you cannot do so
  225. * a targeted write like $object['foo']['bar'] = 'foobar'. Instead, you must
  226. * overwrite the entire top-level 'foo' array with the entire set of new
  227. * values: $object['foo'] = array(1, 2, 'bar' => 'foobar'). Due to this same
  228. * limitation, attempts to create references to any contained data, nested or
  229. * otherwise, will fail silently. So $var = &$object['foo'] will not throw an
  230. * error, and $var will be populated with the contents of $object['foo'], but
  231. * that data will be passed by value, not reference. For more information on
  232. * the PHP limitation, see the note in the official PHP documentation at·
  233. * http://php.net/manual/en/arrayaccess.offsetget.php on
  234. * ArrayAccess::offsetGet().
  235. *
  236. * By default, the class accounts for caches where calling functions might
  237. * request keys in the array that won't exist even after a cache rebuild. This
  238. * prevents situations where a cache rebuild would be triggered over and over
  239. * due to a 'missing' item. These cases are stored internally as a value of
  240. * NULL. This means that the offsetGet() and offsetExists() methods
  241. * must be overridden if caching an array where the top level values can
  242. * legitimately be NULL, and where $object->offsetExists() needs to correctly
  243. * return (equivalent to array_key_exists() vs. isset()). This should not
  244. * be necessary in the majority of cases.
  245. *
  246. * Classes extending this class must override at least the
  247. * resolveCacheMiss() method to have a working implementation.
  248. *
  249. * offsetSet() is not overridden by this class by default. In practice this
  250. * means that assigning an offset via arrayAccess will only apply while the
  251. * object is in scope and will not be written back to the persistent cache.
  252. * This follows a similar pattern to static vs. persistent caching in
  253. * procedural code. Extending classes may wish to alter this behavior, for
  254. * example by overriding offsetSet() and adding an automatic call to persist().
  255. *
  256. * @see SchemaCache
  257. */
  258. abstract class DrupalCacheArray implements ArrayAccess {
  259. /**
  260. * A cid to pass to cache_set() and cache_get().
  261. */
  262. protected $cid;
  263. /**
  264. * A bin to pass to cache_set() and cache_get().
  265. */
  266. protected $bin;
  267. /**
  268. * An array of keys to add to the cache at the end of the request.
  269. */
  270. protected $keysToPersist = array();
  271. /**
  272. * Storage for the data itself.
  273. */
  274. protected $storage = array();
  275. /**
  276. * Constructs a DrupalCacheArray object.
  277. *
  278. * @param $cid
  279. * The cid for the array being cached.
  280. * @param $bin
  281. * The bin to cache the array.
  282. */
  283. public function __construct($cid, $bin) {
  284. $this->cid = $cid;
  285. $this->bin = $bin;
  286. if ($cached = cache_get($this->cid, $this->bin)) {
  287. $this->storage = $cached->data;
  288. }
  289. }
  290. /**
  291. * Implements ArrayAccess::offsetExists().
  292. */
  293. public function offsetExists($offset) {
  294. return $this->offsetGet($offset) !== NULL;
  295. }
  296. /**
  297. * Implements ArrayAccess::offsetGet().
  298. */
  299. public function offsetGet($offset) {
  300. if (isset($this->storage[$offset]) || array_key_exists($offset, $this->storage)) {
  301. return $this->storage[$offset];
  302. }
  303. else {
  304. return $this->resolveCacheMiss($offset);
  305. }
  306. }
  307. /**
  308. * Implements ArrayAccess::offsetSet().
  309. */
  310. public function offsetSet($offset, $value) {
  311. $this->storage[$offset] = $value;
  312. }
  313. /**
  314. * Implements ArrayAccess::offsetUnset().
  315. */
  316. public function offsetUnset($offset) {
  317. unset($this->storage[$offset]);
  318. }
  319. /**
  320. * Flags an offset value to be written to the persistent cache.
  321. *
  322. * If a value is assigned to a cache object with offsetSet(), by default it
  323. * will not be written to the persistent cache unless it is flagged with this
  324. * method. This allows items to be cached for the duration of a request,
  325. * without necessarily writing back to the persistent cache at the end.
  326. *
  327. * @param $offset
  328. * The array offset that was request.
  329. * @param $persist
  330. * Optional boolean to specify whether the offset should be persisted or
  331. * not, defaults to TRUE. When called with $persist = FALSE the offset will
  332. * be unflagged so that it will not written at the end of the request.
  333. */
  334. protected function persist($offset, $persist = TRUE) {
  335. $this->keysToPersist[$offset] = $persist;
  336. }
  337. /**
  338. * Resolves a cache miss.
  339. *
  340. * When an offset is not found in the object, this is treated as a cache
  341. * miss. This method allows classes implementing the interface to look up
  342. * the actual value and allow it to be cached.
  343. *
  344. * @param $offset
  345. * The offset that was requested.
  346. *
  347. * @return
  348. * The value of the offset, or NULL if no value was found.
  349. */
  350. abstract protected function resolveCacheMiss($offset);
  351. /**
  352. * Writes a value to the persistent cache immediately.
  353. *
  354. * @param $data
  355. * The data to write to the persistent cache.
  356. * @param $lock
  357. * Whether to acquire a lock before writing to cache.
  358. */
  359. protected function set($data, $lock = TRUE) {
  360. // Lock cache writes to help avoid stampedes.
  361. // To implement locking for cache misses, override __construct().
  362. $lock_name = $this->cid . ':' . $this->bin;
  363. if (!$lock || lock_acquire($lock_name)) {
  364. if ($cached = cache_get($this->cid, $this->bin)) {
  365. $data = $cached->data + $data;
  366. }
  367. cache_set($this->cid, $data, $this->bin);
  368. if ($lock) {
  369. lock_release($lock_name);
  370. }
  371. }
  372. }
  373. /**
  374. * Destructs the DrupalCacheArray object.
  375. */
  376. public function __destruct() {
  377. $data = array();
  378. foreach ($this->keysToPersist as $offset => $persist) {
  379. if ($persist) {
  380. $data[$offset] = $this->storage[$offset];
  381. }
  382. }
  383. if (!empty($data)) {
  384. $this->set($data);
  385. }
  386. }
  387. }
  388. /**
  389. * Starts the timer with the specified name.
  390. *
  391. * If you start and stop the same timer multiple times, the measured intervals
  392. * will be accumulated.
  393. *
  394. * @param $name
  395. * The name of the timer.
  396. */
  397. function timer_start($name) {
  398. global $timers;
  399. $timers[$name]['start'] = microtime(TRUE);
  400. $timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
  401. }
  402. /**
  403. * Reads the current timer value without stopping the timer.
  404. *
  405. * @param $name
  406. * The name of the timer.
  407. *
  408. * @return
  409. * The current timer value in ms.
  410. */
  411. function timer_read($name) {
  412. global $timers;
  413. if (isset($timers[$name]['start'])) {
  414. $stop = microtime(TRUE);
  415. $diff = round(($stop - $timers[$name]['start']) * 1000, 2);
  416. if (isset($timers[$name]['time'])) {
  417. $diff += $timers[$name]['time'];
  418. }
  419. return $diff;
  420. }
  421. return $timers[$name]['time'];
  422. }
  423. /**
  424. * Stops the timer with the specified name.
  425. *
  426. * @param $name
  427. * The name of the timer.
  428. *
  429. * @return
  430. * A timer array. The array contains the number of times the timer has been
  431. * started and stopped (count) and the accumulated timer value in ms (time).
  432. */
  433. function timer_stop($name) {
  434. global $timers;
  435. if (isset($timers[$name]['start'])) {
  436. $stop = microtime(TRUE);
  437. $diff = round(($stop - $timers[$name]['start']) * 1000, 2);
  438. if (isset($timers[$name]['time'])) {
  439. $timers[$name]['time'] += $diff;
  440. }
  441. else {
  442. $timers[$name]['time'] = $diff;
  443. }
  444. unset($timers[$name]['start']);
  445. }
  446. return $timers[$name];
  447. }
  448. /**
  449. * Returns the appropriate configuration directory.
  450. *
  451. * Returns the configuration path based on the site's hostname, port, and
  452. * pathname. Uses find_conf_path() to find the current configuration directory.
  453. * See default.settings.php for examples on how the URL is converted to a
  454. * directory.
  455. *
  456. * @param bool $require_settings
  457. * Only configuration directories with an existing settings.php file
  458. * will be recognized. Defaults to TRUE. During initial installation,
  459. * this is set to FALSE so that Drupal can detect a matching directory,
  460. * then create a new settings.php file in it.
  461. * @param bool $reset
  462. * Force a full search for matching directories even if one had been
  463. * found previously. Defaults to FALSE.
  464. *
  465. * @return
  466. * The path of the matching directory.
  467. *
  468. * @see default.settings.php
  469. */
  470. function conf_path($require_settings = TRUE, $reset = FALSE) {
  471. $conf = &drupal_static(__FUNCTION__, '');
  472. if ($conf && !$reset) {
  473. return $conf;
  474. }
  475. $confdir = 'sites';
  476. $sites = array();
  477. if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/sites.php')) {
  478. // This will overwrite $sites with the desired mappings.
  479. include(DRUPAL_ROOT . '/' . $confdir . '/sites.php');
  480. }
  481. $uri = explode('/', $_SERVER['SCRIPT_NAME'] ? $_SERVER['SCRIPT_NAME'] : $_SERVER['SCRIPT_FILENAME']);
  482. $server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
  483. for ($i = count($uri) - 1; $i > 0; $i--) {
  484. for ($j = count($server); $j > 0; $j--) {
  485. $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
  486. if (isset($sites[$dir]) && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $sites[$dir])) {
  487. $dir = $sites[$dir];
  488. }
  489. if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir . '/settings.php') || (!$require_settings && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir))) {
  490. $conf = "$confdir/$dir";
  491. return $conf;
  492. }
  493. }
  494. }
  495. $conf = "$confdir/default";
  496. return $conf;
  497. }
  498. /**
  499. * Sets appropriate server variables needed for command line scripts to work.
  500. *
  501. * This function can be called by command line scripts before bootstrapping
  502. * Drupal, to ensure that the page loads with the desired server parameters.
  503. * This is because many parts of Drupal assume that they are running in a web
  504. * browser and therefore use information from the global PHP $_SERVER variable
  505. * that does not get set when Drupal is run from the command line.
  506. *
  507. * In many cases, the default way in which this function populates the $_SERVER
  508. * variable is sufficient, and it can therefore be called without passing in
  509. * any input. However, command line scripts running on a multisite installation
  510. * (or on any installation that has settings.php stored somewhere other than
  511. * the sites/default folder) need to pass in the URL of the site to allow
  512. * Drupal to detect the correct location of the settings.php file. Passing in
  513. * the 'url' parameter is also required for functions like request_uri() to
  514. * return the expected values.
  515. *
  516. * Most other parameters do not need to be passed in, but may be necessary in
  517. * some cases; for example, if Drupal's ip_address() function needs to return
  518. * anything but the standard localhost value ('127.0.0.1'), the command line
  519. * script should pass in the desired value via the 'REMOTE_ADDR' key.
  520. *
  521. * @param $variables
  522. * (optional) An associative array of variables within $_SERVER that should
  523. * be replaced. If the special element 'url' is provided in this array, it
  524. * will be used to populate some of the server defaults; it should be set to
  525. * the URL of the current page request, excluding any $_GET request but
  526. * including the script name (e.g., http://www.example.com/mysite/index.php).
  527. *
  528. * @see conf_path()
  529. * @see request_uri()
  530. * @see ip_address()
  531. */
  532. function drupal_override_server_variables($variables = array()) {
  533. // Allow the provided URL to override any existing values in $_SERVER.
  534. if (isset($variables['url'])) {
  535. $url = parse_url($variables['url']);
  536. if (isset($url['host'])) {
  537. $_SERVER['HTTP_HOST'] = $url['host'];
  538. }
  539. if (isset($url['path'])) {
  540. $_SERVER['SCRIPT_NAME'] = $url['path'];
  541. }
  542. unset($variables['url']);
  543. }
  544. // Define default values for $_SERVER keys. These will be used if $_SERVER
  545. // does not already define them and no other values are passed in to this
  546. // function.
  547. $defaults = array(
  548. 'HTTP_HOST' => 'localhost',
  549. 'SCRIPT_NAME' => NULL,
  550. 'REMOTE_ADDR' => '127.0.0.1',
  551. 'REQUEST_METHOD' => 'GET',
  552. 'SERVER_NAME' => NULL,
  553. 'SERVER_SOFTWARE' => NULL,
  554. 'HTTP_USER_AGENT' => NULL,
  555. );
  556. // Replace elements of the $_SERVER array, as appropriate.
  557. $_SERVER = $variables + $_SERVER + $defaults;
  558. }
  559. /**
  560. * Initializes the PHP environment.
  561. */
  562. function drupal_environment_initialize() {
  563. if (!isset($_SERVER['HTTP_REFERER'])) {
  564. $_SERVER['HTTP_REFERER'] = '';
  565. }
  566. if (!isset($_SERVER['SERVER_PROTOCOL']) || ($_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.0' && $_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.1')) {
  567. $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
  568. }
  569. if (isset($_SERVER['HTTP_HOST'])) {
  570. // As HTTP_HOST is user input, ensure it only contains characters allowed
  571. // in hostnames. See RFC 952 (and RFC 2181).
  572. // $_SERVER['HTTP_HOST'] is lowercased here per specifications.
  573. $_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']);
  574. if (!drupal_valid_http_host($_SERVER['HTTP_HOST'])) {
  575. // HTTP_HOST is invalid, e.g. if containing slashes it may be an attack.
  576. header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
  577. exit;
  578. }
  579. }
  580. else {
  581. // Some pre-HTTP/1.1 clients will not send a Host header. Ensure the key is
  582. // defined for E_ALL compliance.
  583. $_SERVER['HTTP_HOST'] = '';
  584. }
  585. // When clean URLs are enabled, emulate ?q=foo/bar using REQUEST_URI. It is
  586. // not possible to append the query string using mod_rewrite without the B
  587. // flag (this was added in Apache 2.2.8), because mod_rewrite unescapes the
  588. // path before passing it on to PHP. This is a problem when the path contains
  589. // e.g. "&" or "%" that have special meanings in URLs and must be encoded.
  590. $_GET['q'] = request_path();
  591. // Enforce E_ALL, but allow users to set levels not part of E_ALL.
  592. error_reporting(E_ALL | error_reporting());
  593. // Override PHP settings required for Drupal to work properly.
  594. // sites/default/default.settings.php contains more runtime settings.
  595. // The .htaccess file contains settings that cannot be changed at runtime.
  596. // Don't escape quotes when reading files from the database, disk, etc.
  597. ini_set('magic_quotes_runtime', '0');
  598. // Use session cookies, not transparent sessions that puts the session id in
  599. // the query string.
  600. ini_set('session.use_cookies', '1');
  601. ini_set('session.use_only_cookies', '1');
  602. ini_set('session.use_trans_sid', '0');
  603. // Don't send HTTP headers using PHP's session handler.
  604. ini_set('session.cache_limiter', 'none');
  605. // Use httponly session cookies.
  606. ini_set('session.cookie_httponly', '1');
  607. // Set sane locale settings, to ensure consistent string, dates, times and
  608. // numbers handling.
  609. setlocale(LC_ALL, 'C');
  610. }
  611. /**
  612. * Validates that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
  613. *
  614. * @return
  615. * TRUE if only containing valid characters, or FALSE otherwise.
  616. */
  617. function drupal_valid_http_host($host) {
  618. return preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host);
  619. }
  620. /**
  621. * Sets the base URL, cookie domain, and session name from configuration.
  622. */
  623. function drupal_settings_initialize() {
  624. global $base_url, $base_path, $base_root;
  625. // Export these settings.php variables to the global namespace.
  626. 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;
  627. $conf = array();
  628. if (file_exists(DRUPAL_ROOT . '/' . conf_path() . '/settings.php')) {
  629. include_once DRUPAL_ROOT . '/' . conf_path() . '/settings.php';
  630. }
  631. $is_https = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
  632. if (isset($base_url)) {
  633. // Parse fixed base URL from settings.php.
  634. $parts = parse_url($base_url);
  635. $http_protocol = $parts['scheme'];
  636. if (!isset($parts['path'])) {
  637. $parts['path'] = '';
  638. }
  639. $base_path = $parts['path'] . '/';
  640. // Build $base_root (everything until first slash after "scheme://").
  641. $base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
  642. }
  643. else {
  644. // Create base URL.
  645. $http_protocol = $is_https ? 'https' : 'http';
  646. $base_root = $http_protocol . '://' . $_SERVER['HTTP_HOST'];
  647. $base_url = $base_root;
  648. // $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
  649. // be modified by a visitor.
  650. if ($dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/')) {
  651. $base_path = $dir;
  652. $base_url .= $base_path;
  653. $base_path .= '/';
  654. }
  655. else {
  656. $base_path = '/';
  657. }
  658. }
  659. $base_secure_url = str_replace('http://', 'https://', $base_url);
  660. $base_insecure_url = str_replace('https://', 'http://', $base_url);
  661. if ($cookie_domain) {
  662. // If the user specifies the cookie domain, also use it for session name.
  663. $session_name = $cookie_domain;
  664. }
  665. else {
  666. // Otherwise use $base_url as session name, without the protocol
  667. // to use the same session identifiers across HTTP and HTTPS.
  668. list( , $session_name) = explode('://', $base_url, 2);
  669. // HTTP_HOST can be modified by a visitor, but we already sanitized it
  670. // in drupal_settings_initialize().
  671. if (!empty($_SERVER['HTTP_HOST'])) {
  672. $cookie_domain = $_SERVER['HTTP_HOST'];
  673. // Strip leading periods, www., and port numbers from cookie domain.
  674. $cookie_domain = ltrim($cookie_domain, '.');
  675. if (strpos($cookie_domain, 'www.') === 0) {
  676. $cookie_domain = substr($cookie_domain, 4);
  677. }
  678. $cookie_domain = explode(':', $cookie_domain);
  679. $cookie_domain = '.' . $cookie_domain[0];
  680. }
  681. }
  682. // Per RFC 2109, cookie domains must contain at least one dot other than the
  683. // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
  684. if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
  685. ini_set('session.cookie_domain', $cookie_domain);
  686. }
  687. // To prevent session cookies from being hijacked, a user can configure the
  688. // SSL version of their website to only transfer session cookies via SSL by
  689. // using PHP's session.cookie_secure setting. The browser will then use two
  690. // separate session cookies for the HTTPS and HTTP versions of the site. So we
  691. // must use different session identifiers for HTTPS and HTTP to prevent a
  692. // cookie collision.
  693. if ($is_https) {
  694. ini_set('session.cookie_secure', TRUE);
  695. }
  696. $prefix = ini_get('session.cookie_secure') ? 'SSESS' : 'SESS';
  697. session_name($prefix . substr(hash('sha256', $session_name), 0, 32));
  698. }
  699. /**
  700. * Returns and optionally sets the filename for a system resource.
  701. *
  702. * The filename, whether provided, cached, or retrieved from the database, is
  703. * only returned if the file exists.
  704. *
  705. * This function plays a key role in allowing Drupal's resources (modules
  706. * and themes) to be located in different places depending on a site's
  707. * configuration. For example, a module 'foo' may legally be be located
  708. * in any of these three places:
  709. *
  710. * modules/foo/foo.module
  711. * sites/all/modules/foo/foo.module
  712. * sites/example.com/modules/foo/foo.module
  713. *
  714. * Calling drupal_get_filename('module', 'foo') will give you one of
  715. * the above, depending on where the module is located.
  716. *
  717. * @param $type
  718. * The type of the item (i.e. theme, theme_engine, module, profile).
  719. * @param $name
  720. * The name of the item for which the filename is requested.
  721. * @param $filename
  722. * The filename of the item if it is to be set explicitly rather
  723. * than by consulting the database.
  724. *
  725. * @return
  726. * The filename of the requested item.
  727. */
  728. function drupal_get_filename($type, $name, $filename = NULL) {
  729. // The location of files will not change during the request, so do not use
  730. // drupal_static().
  731. static $files = array(), $dirs = array();
  732. // Profiles are a special case: they have a fixed location and naming.
  733. if ($type == 'profile') {
  734. $profile_filename = "profiles/$name/$name.profile";
  735. $files[$type][$name] = file_exists($profile_filename) ? $profile_filename : FALSE;
  736. }
  737. if (!isset($files[$type])) {
  738. $files[$type] = array();
  739. }
  740. if (!empty($filename) && file_exists($filename)) {
  741. $files[$type][$name] = $filename;
  742. }
  743. elseif (isset($files[$type][$name])) {
  744. // nothing
  745. }
  746. // Verify that we have an active database connection, before querying
  747. // the database. This is required because this function is called both
  748. // before we have a database connection (i.e. during installation) and
  749. // when a database connection fails.
  750. else {
  751. try {
  752. if (function_exists('db_query')) {
  753. $file = db_query("SELECT filename FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
  754. if (file_exists(DRUPAL_ROOT . '/' . $file)) {
  755. $files[$type][$name] = $file;
  756. }
  757. }
  758. }
  759. catch (Exception $e) {
  760. // The database table may not exist because Drupal is not yet installed,
  761. // or the database might be down. We have a fallback for this case so we
  762. // hide the error completely.
  763. }
  764. // Fallback to searching the filesystem if the database could not find the
  765. // file or the file returned by the database is not found.
  766. if (!isset($files[$type][$name])) {
  767. // We have a consistent directory naming: modules, themes...
  768. $dir = $type . 's';
  769. if ($type == 'theme_engine') {
  770. $dir = 'themes/engines';
  771. $extension = 'engine';
  772. }
  773. elseif ($type == 'theme') {
  774. $extension = 'info';
  775. }
  776. else {
  777. $extension = $type;
  778. }
  779. if (!isset($dirs[$dir][$extension])) {
  780. $dirs[$dir][$extension] = TRUE;
  781. if (!function_exists('drupal_system_listing')) {
  782. require_once DRUPAL_ROOT . '/includes/common.inc';
  783. }
  784. // Scan the appropriate directories for all files with the requested
  785. // extension, not just the file we are currently looking for. This
  786. // prevents unnecessary scans from being repeated when this function is
  787. // called more than once in the same page request.
  788. $matches = drupal_system_listing("/^" . DRUPAL_PHP_FUNCTION_PATTERN . "\.$extension$/", $dir, 'name', 0);
  789. foreach ($matches as $matched_name => $file) {
  790. $files[$type][$matched_name] = $file->uri;
  791. }
  792. }
  793. }
  794. }
  795. if (isset($files[$type][$name])) {
  796. return $files[$type][$name];
  797. }
  798. }
  799. /**
  800. * Loads the persistent variable table.
  801. *
  802. * The variable table is composed of values that have been saved in the table
  803. * with variable_set() as well as those explicitly specified in the
  804. * configuration file.
  805. */
  806. function variable_initialize($conf = array()) {
  807. // NOTE: caching the variables improves performance by 20% when serving
  808. // cached pages.
  809. if ($cached = cache_get('variables', 'cache_bootstrap')) {
  810. $variables = $cached->data;
  811. }
  812. else {
  813. // Cache miss. Avoid a stampede.
  814. $name = 'variable_init';
  815. if (!lock_acquire($name, 1)) {
  816. // Another request is building the variable cache.
  817. // Wait, then re-run this function.
  818. lock_wait($name);
  819. return variable_initialize($conf);
  820. }
  821. else {
  822. // Proceed with variable rebuild.
  823. $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
  824. cache_set('variables', $variables, 'cache_bootstrap');
  825. lock_release($name);
  826. }
  827. }
  828. foreach ($conf as $name => $value) {
  829. $variables[$name] = $value;
  830. }
  831. return $variables;
  832. }
  833. /**
  834. * Returns a persistent variable.
  835. *
  836. * Case-sensitivity of the variable_* functions depends on the database
  837. * collation used. To avoid problems, always use lower case for persistent
  838. * variable names.
  839. *
  840. * @param $name
  841. * The name of the variable to return.
  842. * @param $default
  843. * The default value to use if this variable has never been set.
  844. *
  845. * @return
  846. * The value of the variable. Unserialization is taken care of as necessary.
  847. *
  848. * @see variable_del()
  849. * @see variable_set()
  850. */
  851. function variable_get($name, $default = NULL) {
  852. global $conf;
  853. return isset($conf[$name]) ? $conf[$name] : $default;
  854. }
  855. /**
  856. * Sets a persistent variable.
  857. *
  858. * Case-sensitivity of the variable_* functions depends on the database
  859. * collation used. To avoid problems, always use lower case for persistent
  860. * variable names.
  861. *
  862. * @param $name
  863. * The name of the variable to set.
  864. * @param $value
  865. * The value to set. This can be any PHP data type; these functions take care
  866. * of serialization as necessary.
  867. *
  868. * @see variable_del()
  869. * @see variable_get()
  870. */
  871. function variable_set($name, $value) {
  872. global $conf;
  873. db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();
  874. cache_clear_all('variables', 'cache_bootstrap');
  875. $conf[$name] = $value;
  876. }
  877. /**
  878. * Unsets a persistent variable.
  879. *
  880. * Case-sensitivity of the variable_* functions depends on the database
  881. * collation used. To avoid problems, always use lower case for persistent
  882. * variable names.
  883. *
  884. * @param $name
  885. * The name of the variable to undefine.
  886. *
  887. * @see variable_get()
  888. * @see variable_set()
  889. */
  890. function variable_del($name) {
  891. global $conf;
  892. db_delete('variable')
  893. ->condition('name', $name)
  894. ->execute();
  895. cache_clear_all('variables', 'cache_bootstrap');
  896. unset($conf[$name]);
  897. }
  898. /**
  899. * Retrieves the current page from the cache.
  900. *
  901. * Note: we do not serve cached pages to authenticated users, or to anonymous
  902. * users when $_SESSION is non-empty. $_SESSION may contain status messages
  903. * from a form submission, the contents of a shopping cart, or other user-
  904. * specific content that should not be cached and displayed to other users.
  905. *
  906. * @param $check_only
  907. * (optional) Set to TRUE to only return whether a previous call found a
  908. * cache entry.
  909. *
  910. * @return
  911. * The cache object, if the page was found in the cache, NULL otherwise.
  912. */
  913. function drupal_page_get_cache($check_only = FALSE) {
  914. global $base_root;
  915. static $cache_hit = FALSE;
  916. if ($check_only) {
  917. return $cache_hit;
  918. }
  919. if (drupal_page_is_cacheable()) {
  920. $cache = cache_get($base_root . request_uri(), 'cache_page');
  921. if ($cache !== FALSE) {
  922. $cache_hit = TRUE;
  923. }
  924. return $cache;
  925. }
  926. }
  927. /**
  928. * Determines the cacheability of the current page.
  929. *
  930. * @param $allow_caching
  931. * Set to FALSE if you want to prevent this page to get cached.
  932. *
  933. * @return
  934. * TRUE if the current page can be cached, FALSE otherwise.
  935. */
  936. function drupal_page_is_cacheable($allow_caching = NULL) {
  937. $allow_caching_static = &drupal_static(__FUNCTION__, TRUE);
  938. if (isset($allow_caching)) {
  939. $allow_caching_static = $allow_caching;
  940. }
  941. return $allow_caching_static && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')
  942. && !drupal_is_cli();
  943. }
  944. /**
  945. * Invokes a bootstrap hook in all bootstrap modules that implement it.
  946. *
  947. * @param $hook
  948. * The name of the bootstrap hook to invoke.
  949. *
  950. * @see bootstrap_hooks()
  951. */
  952. function bootstrap_invoke_all($hook) {
  953. // Bootstrap modules should have been loaded when this function is called, so
  954. // we don't need to tell module_list() to reset its internal list (and we
  955. // therefore leave the first parameter at its default value of FALSE). We
  956. // still pass in TRUE for the second parameter, though; in case this is the
  957. // first time during the bootstrap that module_list() is called, we want to
  958. // make sure that its internal cache is primed with the bootstrap modules
  959. // only.
  960. foreach (module_list(FALSE, TRUE) as $module) {
  961. drupal_load('module', $module);
  962. module_invoke($module, $hook);
  963. }
  964. }
  965. /**
  966. * Includes a file with the provided type and name.
  967. *
  968. * This prevents including a theme, engine, module, etc., more than once.
  969. *
  970. * @param $type
  971. * The type of item to load (i.e. theme, theme_engine, module).
  972. * @param $name
  973. * The name of the item to load.
  974. *
  975. * @return
  976. * TRUE if the item is loaded or has already been loaded.
  977. */
  978. function drupal_load($type, $name) {
  979. // Once a file is included this can't be reversed during a request so do not
  980. // use drupal_static() here.
  981. static $files = array();
  982. if (isset($files[$type][$name])) {
  983. return TRUE;
  984. }
  985. $filename = drupal_get_filename($type, $name);
  986. if ($filename) {
  987. include_once DRUPAL_ROOT . '/' . $filename;
  988. $files[$type][$name] = TRUE;
  989. return TRUE;
  990. }
  991. return FALSE;
  992. }
  993. /**
  994. * Sets an HTTP response header for the current page.
  995. *
  996. * Note: When sending a Content-Type header, always include a 'charset' type,
  997. * too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
  998. *
  999. * @param $name
  1000. * The HTTP header name, or the special 'Status' header name.
  1001. * @param $value
  1002. * The HTTP header value; if equal to FALSE, the specified header is unset.
  1003. * If $name is 'Status', this is expected to be a status code followed by a
  1004. * reason phrase, e.g. "404 Not Found".
  1005. * @param $append
  1006. * Whether to append the value to an existing header or to replace it.
  1007. */
  1008. function drupal_add_http_header($name, $value, $append = FALSE) {
  1009. // The headers as name/value pairs.
  1010. $headers = &drupal_static('drupal_http_headers', array());
  1011. $name_lower = strtolower($name);
  1012. _drupal_set_preferred_header_name($name);
  1013. if ($value === FALSE) {
  1014. $headers[$name_lower] = FALSE;
  1015. }
  1016. elseif (isset($headers[$name_lower]) && $append) {
  1017. // Multiple headers with identical names may be combined using comma (RFC
  1018. // 2616, section 4.2).
  1019. $headers[$name_lower] .= ',' . $value;
  1020. }
  1021. else {
  1022. $headers[$name_lower] = $value;
  1023. }
  1024. drupal_send_headers(array($name => $headers[$name_lower]), TRUE);
  1025. }
  1026. /**
  1027. * Gets the HTTP response headers for the current page.
  1028. *
  1029. * @param $name
  1030. * An HTTP header name. If omitted, all headers are returned as name/value
  1031. * pairs. If an array value is FALSE, the header has been unset.
  1032. *
  1033. * @return
  1034. * A string containing the header value, or FALSE if the header has been set,
  1035. * or NULL if the header has not been set.
  1036. */
  1037. function drupal_get_http_header($name = NULL) {
  1038. $headers = &drupal_static('drupal_http_headers', array());
  1039. if (isset($name)) {
  1040. $name = strtolower($name);
  1041. return isset($headers[$name]) ? $headers[$name] : NULL;
  1042. }
  1043. else {
  1044. return $headers;
  1045. }
  1046. }
  1047. /**
  1048. * Sets the preferred name for the HTTP header.
  1049. *
  1050. * Header names are case-insensitive, but for maximum compatibility they should
  1051. * follow "common form" (see RFC 2617, section 4.2).
  1052. */
  1053. function _drupal_set_preferred_header_name($name = NULL) {
  1054. static $header_names = array();
  1055. if (!isset($name)) {
  1056. return $header_names;
  1057. }
  1058. $header_names[strtolower($name)] = $name;
  1059. }
  1060. /**
  1061. * Sends the HTTP response headers that were previously set, adding defaults.
  1062. *
  1063. * Headers are set in drupal_add_http_header(). Default headers are not set
  1064. * if they have been replaced or unset using drupal_add_http_header().
  1065. *
  1066. * @param $default_headers
  1067. * An array of headers as name/value pairs.
  1068. * @param $single
  1069. * If TRUE and headers have already be sent, send only the specified header.
  1070. */
  1071. function drupal_send_headers($default_headers = array(), $only_default = FALSE) {
  1072. $headers_sent = &drupal_static(__FUNCTION__, FALSE);
  1073. $headers = drupal_get_http_header();
  1074. if ($only_default && $headers_sent) {
  1075. $headers = array();
  1076. }
  1077. $headers_sent = TRUE;
  1078. $header_names = _drupal_set_preferred_header_name();
  1079. foreach ($default_headers as $name => $value) {
  1080. $name_lower = strtolower($name);
  1081. if (!isset($headers[$name_lower])) {
  1082. $headers[$name_lower] = $value;
  1083. $header_names[$name_lower] = $name;
  1084. }
  1085. }
  1086. foreach ($headers as $name_lower => $value) {
  1087. if ($name_lower == 'status') {
  1088. header($_SERVER['SERVER_PROTOCOL'] . ' ' . $value);
  1089. }
  1090. // Skip headers that have been unset.
  1091. elseif ($value) {
  1092. header($header_names[$name_lower] . ': ' . $value);
  1093. }
  1094. }
  1095. }
  1096. /**
  1097. * Sets HTTP headers in preparation for a page response.
  1098. *
  1099. * Authenticated users are always given a 'no-cache' header, and will fetch a
  1100. * fresh page on every request. This prevents authenticated users from seeing
  1101. * locally cached pages.
  1102. *
  1103. * Also give each page a unique ETag. This will force clients to include both
  1104. * an If-Modified-Since header and an If-None-Match header when doing
  1105. * conditional requests for the page (required by RFC 2616, section 13.3.4),
  1106. * making the validation more robust. This is a workaround for a bug in Mozilla
  1107. * Firefox that is triggered when Drupal's caching is enabled and the user
  1108. * accesses Drupal via an HTTP proxy (see
  1109. * https://bugzilla.mozilla.org/show_bug.cgi?id=269303): When an authenticated
  1110. * user requests a page, and then logs out and requests the same page again,
  1111. * Firefox may send a conditional request based on the page that was cached
  1112. * locally when the user was logged in. If this page did not have an ETag
  1113. * header, the request only contains an If-Modified-Since header. The date will
  1114. * be recent, because with authenticated users the Last-Modified header always
  1115. * refers to the time of the request. If the user accesses Drupal via a proxy
  1116. * server, and the proxy already has a cached copy of the anonymous page with an
  1117. * older Last-Modified date, the proxy may respond with 304 Not Modified, making
  1118. * the client think that the anonymous and authenticated pageviews are
  1119. * identical.
  1120. *
  1121. * @see drupal_page_set_cache()
  1122. */
  1123. function drupal_page_header() {
  1124. $headers_sent = &drupal_static(__FUNCTION__, FALSE);
  1125. if ($headers_sent) {
  1126. return TRUE;
  1127. }
  1128. $headers_sent = TRUE;
  1129. $default_headers = array(
  1130. 'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
  1131. 'Last-Modified' => gmdate(DATE_RFC1123, REQUEST_TIME),
  1132. 'Cache-Control' => 'no-cache, must-revalidate, post-check=0, pre-check=0',
  1133. 'ETag' => '"' . REQUEST_TIME . '"',
  1134. );
  1135. drupal_send_headers($default_headers);
  1136. }
  1137. /**
  1138. * Sets HTTP headers in preparation for a cached page response.
  1139. *
  1140. * The headers allow as much as possible in proxies and browsers without any
  1141. * particular knowledge about the pages. Modules can override these headers
  1142. * using drupal_add_http_header().
  1143. *
  1144. * If the request is conditional (using If-Modified-Since and If-None-Match),
  1145. * and the conditions match those currently in the cache, a 304 Not Modified
  1146. * response is sent.
  1147. */
  1148. function drupal_serve_page_from_cache(stdClass $cache) {
  1149. // Negotiate whether to use compression.
  1150. $page_compression = variable_get('page_compression', TRUE) && extension_loaded('zlib');
  1151. $return_compressed = $page_compression && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE;
  1152. // Get headers set in hook_boot(). Keys are lower-case.
  1153. $hook_boot_headers = drupal_get_http_header();
  1154. // Headers generated in this function, that may be replaced or unset using
  1155. // drupal_add_http_headers(). Keys are mixed-case.
  1156. $default_headers = array();
  1157. foreach ($cache->data['headers'] as $name => $value) {
  1158. // In the case of a 304 response, certain headers must be sent, and the
  1159. // remaining may not (see RFC 2616, section 10.3.5). Do not override
  1160. // headers set in hook_boot().
  1161. $name_lower = strtolower($name);
  1162. if (in_array($name_lower, array('content-location', 'expires', 'cache-control', 'vary')) && !isset($hook_boot_headers[$name_lower])) {
  1163. drupal_add_http_header($name, $value);
  1164. unset($cache->data['headers'][$name]);
  1165. }
  1166. }
  1167. // If the client sent a session cookie, a cached copy will only be served
  1168. // to that one particular client due to Vary: Cookie. Thus, do not set
  1169. // max-age > 0, allowing the page to be cached by external proxies, when a
  1170. // session cookie is present unless the Vary header has been replaced or
  1171. // unset in hook_boot().
  1172. $max_age = !isset($_COOKIE[session_name()]) || isset($hook_boot_headers['vary']) ? variable_get('page_cache_maximum_age', 0) : 0;
  1173. $default_headers['Cache-Control'] = 'public, max-age=' . $max_age;
  1174. // Entity tag should change if the output changes.
  1175. $etag = '"' . $cache->created . '-' . intval($return_compressed) . '"';
  1176. header('Etag: ' . $etag);
  1177. // See if the client has provided the required HTTP headers.
  1178. $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : FALSE;
  1179. $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : FALSE;
  1180. if ($if_modified_since && $if_none_match
  1181. && $if_none_match == $etag // etag must match
  1182. && $if_modified_since == $cache->created) { // if-modified-since must match
  1183. header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
  1184. drupal_send_headers($default_headers);
  1185. return;
  1186. }
  1187. // Send the remaining headers.
  1188. foreach ($cache->data['headers'] as $name => $value) {
  1189. drupal_add_http_header($name, $value);
  1190. }
  1191. $default_headers['Last-Modified'] = gmdate(DATE_RFC1123, $cache->created);
  1192. // HTTP/1.0 proxies does not support the Vary header, so prevent any caching
  1193. // by sending an Expires date in the past. HTTP/1.1 clients ignores the
  1194. // Expires header if a Cache-Control: max-age= directive is specified (see RFC
  1195. // 2616, section 14.9.3).
  1196. $default_headers['Expires'] = 'Sun, 19 Nov 1978 05:00:00 GMT';
  1197. drupal_send_headers($default_headers);
  1198. // Allow HTTP proxies to cache pages for anonymous users without a session
  1199. // cookie. The Vary header is used to indicates the set of request-header
  1200. // fields that fully determines whether a cache is permitted to use the
  1201. // response to reply to a subsequent request for a given URL without
  1202. // revalidation. If a Vary header has been set in hook_boot(), it is assumed
  1203. // that the module knows how to cache the page.
  1204. if (!isset($hook_boot_headers['vary']) && !variable_get('omit_vary_cookie')) {
  1205. header('Vary: Cookie');
  1206. }
  1207. if ($page_compression) {
  1208. header('Vary: Accept-Encoding', FALSE);
  1209. // If page_compression is enabled, the cache contains gzipped data.
  1210. if ($return_compressed) {
  1211. // $cache->data['body'] is already gzip'ed, so make sure
  1212. // zlib.output_compression does not compress it once more.
  1213. ini_set('zlib.output_compression', '0');
  1214. header('Content-Encoding: gzip');
  1215. }
  1216. else {
  1217. // The client does not support compression, so unzip the data in the
  1218. // cache. Strip the gzip header and run uncompress.
  1219. $cache->data['body'] = gzinflate(substr(substr($cache->data['body'], 10), 0, -8));
  1220. }
  1221. }
  1222. // Print the page.
  1223. print $cache->data['body'];
  1224. }
  1225. /**
  1226. * Defines the critical hooks that force modules to always be loaded.
  1227. */
  1228. function bootstrap_hooks() {
  1229. return array('boot', 'exit', 'watchdog', 'language_init');
  1230. }
  1231. /**
  1232. * Unserializes and appends elements from a serialized string.
  1233. *
  1234. * @param $obj
  1235. * The object to which the elements are appended.
  1236. * @param $field
  1237. * The attribute of $obj whose value should be unserialized.
  1238. */
  1239. function drupal_unpack($obj, $field = 'data') {
  1240. if ($obj->$field && $data = unserialize($obj->$field)) {
  1241. foreach ($data as $key => $value) {
  1242. if (!empty($key) && !isset($obj->$key)) {
  1243. $obj->$key = $value;
  1244. }
  1245. }
  1246. }
  1247. return $obj;
  1248. }
  1249. /**
  1250. * Translates a string to the current language or to a given language.
  1251. *
  1252. * The t() function serves two purposes. First, at run-time it translates
  1253. * user-visible text into the appropriate language. Second, various mechanisms
  1254. * that figure out what text needs to be translated work off t() -- the text
  1255. * inside t() calls is added to the database of strings to be translated.
  1256. * These strings are expected to be in English, so the first argument should
  1257. * always be in English. To enable a fully-translatable site, it is important
  1258. * that all human-readable text that will be displayed on the site or sent to
  1259. * a user is passed through the t() function, or a related function. See the
  1260. * @link http://drupal.org/node/322729 Localization API @endlink pages for
  1261. * more information, including recommendations on how to break up or not
  1262. * break up strings for translation.
  1263. *
  1264. * You should never use t() to translate variables, such as calling
  1265. * @code t($text); @endcode, unless the text that the variable holds has been
  1266. * passed through t() elsewhere (e.g., $text is one of several translated
  1267. * literal strings in an array). It is especially important never to call
  1268. * @code t($user_text); @endcode, where $user_text is some text that a user
  1269. * entered - doing that can lead to cross-site scripting and other security
  1270. * problems. However, you can use variable substitution in your string, to put
  1271. * variable text such as user names or link URLs into translated text. Variable
  1272. * substitution looks like this:
  1273. * @code
  1274. * $text = t("@name's blog", array('@name' => format_username($account)));
  1275. * @endcode
  1276. * Basically, you can put variables like @name into your string, and t() will
  1277. * substitute their sanitized values at translation time. (See the
  1278. * Localization API pages referenced above and the documentation of
  1279. * format_string() for details.) Translators can then rearrange the string as
  1280. * necessary for the language (e.g., in Spanish, it might be "blog de @name").
  1281. *
  1282. * During the Drupal installation phase, some resources used by t() wil not be
  1283. * available to code that needs localization. See st() and get_t() for
  1284. * alternatives.
  1285. *
  1286. * @param $string
  1287. * A string containing the English string to translate.
  1288. * @param $args
  1289. * An associative array of replacements to make after translation. Based
  1290. * on the first character of the key, the value is escaped and/or themed.
  1291. * See format_string() for details.
  1292. * @param $options
  1293. * An associative array of additional options, with the following elements:
  1294. * - 'langcode' (defaults to the current language): The language code to
  1295. * translate to a language other than what is used to display the page.
  1296. * - 'context' (defaults to the empty context): The context the source string
  1297. * belongs to.
  1298. *
  1299. * @return
  1300. * The translated string.
  1301. *
  1302. * @see st()
  1303. * @see get_t()
  1304. * @see format_string()
  1305. * @ingroup sanitization
  1306. */
  1307. function t($string, array $args = array(), array $options = array()) {
  1308. global $language;
  1309. static $custom_strings;
  1310. // Merge in default.
  1311. if (empty($options['langcode'])) {
  1312. $options['langcode'] = isset($language->language) ? $language->language : 'en';
  1313. }
  1314. if (empty($options['context'])) {
  1315. $options['context'] = '';
  1316. }
  1317. // First, check for an array of customized strings. If present, use the array
  1318. // *instead of* database lookups. This is a high performance way to provide a
  1319. // handful of string replacements. See settings.php for examples.
  1320. // Cache the $custom_strings variable to improve performance.
  1321. if (!isset($custom_strings[$options['langcode']])) {
  1322. $custom_strings[$options['langcode']] = variable_get('locale_custom_strings_' . $options['langcode'], array());
  1323. }
  1324. // Custom strings work for English too, even if locale module is disabled.
  1325. if (isset($custom_strings[$options['langcode']][$options['context']][$string])) {
  1326. $string = $custom_strings[$options['langcode']][$options['context']][$string];
  1327. }
  1328. // Translate with locale module if enabled.
  1329. elseif ($options['langcode'] != 'en' && function_exists('locale')) {
  1330. $string = locale($string, $options['context'], $options['langcode']);
  1331. }
  1332. if (empty($args)) {
  1333. return $string;
  1334. }
  1335. else {
  1336. return format_string($string, $args);
  1337. }
  1338. }
  1339. /**
  1340. * Replaces placeholders with sanitized values in a string.
  1341. *
  1342. * @param $string
  1343. * A string containing placeholders.
  1344. * @param $args
  1345. * An associative array of replacements to make. Occurrences in $string of
  1346. * any key in $args are replaced with the corresponding value, after
  1347. * sanitization. The sanitization function depends on the first character of
  1348. * the key:
  1349. * - !variable: Inserted as is. Use this for text that has already been
  1350. * sanitized.
  1351. * - @variable: Escaped to HTML using check_plain(). Use this for anything
  1352. * displayed on a page on the site.
  1353. * - %variable: Escaped as a placeholder for user-submitted content using
  1354. * drupal_placeholder(), which shows up as <em>emphasized</em> text.
  1355. *
  1356. * @see t()
  1357. * @ingroup sanitization
  1358. */
  1359. function format_string($string, array $args = array()) {
  1360. // Transform arguments before inserting them.
  1361. foreach ($args as $key => $value) {
  1362. switch ($key[0]) {
  1363. case '@':
  1364. // Escaped only.
  1365. $args[$key] = check_plain($value);
  1366. break;
  1367. case '%':
  1368. default:
  1369. // Escaped and placeholder.
  1370. $args[$key] = drupal_placeholder($value);
  1371. break;
  1372. case '!':
  1373. // Pass-through.
  1374. }
  1375. }
  1376. return strtr($string, $args);
  1377. }
  1378. /**
  1379. * Encodes special characters in a plain-text string for display as HTML.
  1380. *
  1381. * Also validates strings as UTF-8 to prevent cross site scripting attacks on
  1382. * Internet Explorer 6.
  1383. *
  1384. * @param $text
  1385. * The text to be checked or processed.
  1386. *
  1387. * @return
  1388. * An HTML safe version of $text, or an empty string if $text is not
  1389. * valid UTF-8.
  1390. *
  1391. * @see drupal_validate_utf8()
  1392. * @ingroup sanitization
  1393. */
  1394. function check_plain($text) {
  1395. return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
  1396. }
  1397. /**
  1398. * Checks whether a string is valid UTF-8.
  1399. *
  1400. * All functions designed to filter input should use drupal_validate_utf8
  1401. * to ensure they operate on valid UTF-8 strings to prevent bypass of the
  1402. * filter.
  1403. *
  1404. * When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
  1405. * as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
  1406. * bytes. When these subsequent bytes are HTML control characters such as
  1407. * quotes or angle brackets, parts of the text that were deemed safe by filters
  1408. * end up in locations that are potentially unsafe; An onerror attribute that
  1409. * is outside of a tag, and thus deemed safe by a filter, can be interpreted
  1410. * by the browser as if it were inside the tag.
  1411. *
  1412. * The function does not return FALSE for strings containing character codes
  1413. * above U+10FFFF, even though these are prohibited by RFC 3629.
  1414. *
  1415. * @param $text
  1416. * The text to check.
  1417. *
  1418. * @return
  1419. * TRUE if the text is valid UTF-8, FALSE if not.
  1420. */
  1421. function drupal_validate_utf8($text) {
  1422. if (strlen($text) == 0) {
  1423. return TRUE;
  1424. }
  1425. // With the PCRE_UTF8 modifier 'u', preg_match() fails silently on strings
  1426. // containing invalid UTF-8 byte sequences. It does not reject character
  1427. // codes above U+10FFFF (represented by 4 or more octets), though.
  1428. return (preg_match('/^./us', $text) == 1);
  1429. }
  1430. /**
  1431. * Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
  1432. *
  1433. * Because $_SERVER['REQUEST_URI'] is only available on Apache, we generate an
  1434. * equivalent using other environment variables.
  1435. */
  1436. function request_uri() {
  1437. if (isset($_SERVER['REQUEST_URI'])) {
  1438. $uri = $_SERVER['REQUEST_URI'];
  1439. }
  1440. else {
  1441. if (isset($_SERVER['argv'])) {
  1442. $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
  1443. }
  1444. elseif (isset($_SERVER['QUERY_STRING'])) {
  1445. $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
  1446. }
  1447. else {
  1448. $uri = $_SERVER['SCRIPT_NAME'];
  1449. }
  1450. }
  1451. // Prevent multiple slashes to avoid cross site requests via the Form API.
  1452. $uri = '/' . ltrim($uri, '/');
  1453. return $uri;
  1454. }
  1455. /**
  1456. * Logs an exception.
  1457. *
  1458. * This is a wrapper function for watchdog() which automatically decodes an
  1459. * exception.
  1460. *
  1461. * @param $type
  1462. * The category to which this message belongs.
  1463. * @param $exception
  1464. * The exception that is going to be logged.
  1465. * @param $message
  1466. * The message to store in the log. If empty, a text that contains all useful
  1467. * information about the passed-in exception is used.
  1468. * @param $variables
  1469. * Array of variables to replace in the message on display. Defaults to the
  1470. * return value of drupal_decode_exception().
  1471. * @param $severity
  1472. * The severity of the message, as per RFC 3164.
  1473. * @param $link
  1474. * A link to associate with the message.
  1475. *
  1476. * @see watchdog()
  1477. * @see drupal_decode_exception()
  1478. */
  1479. function watchdog_exception($type, Exception $exception, $message = NULL, $variables = array(), $severity = WATCHDOG_ERROR, $link = NULL) {
  1480. // Use a default value if $message is not set.
  1481. if (empty($message)) {
  1482. // The exception message is run through check_plain() by _drupal_decode_exception().
  1483. $message = '%type: !message in %function (line %line of %file).';
  1484. }
  1485. // $variables must be an array so that we can add the exception information.
  1486. if (!is_array($variables)) {
  1487. $variables = array();
  1488. }
  1489. require_once DRUPAL_ROOT . '/includes/errors.inc';
  1490. $variables += _drupal_decode_exception($exception);
  1491. watchdog($type, $message, $variables, $severity, $link);
  1492. }
  1493. /**
  1494. * Logs a system message.
  1495. *
  1496. * @param $type
  1497. * The category to which this message belongs. Can be any string, but the
  1498. * general practice is to use the name of the module calling watchdog().
  1499. * @param $message
  1500. * The message to store in the log. Keep $message translatable
  1501. * by not concatenating dynamic values into it! Variables in the
  1502. * message should be added by using placeholder strings alongside
  1503. * the variables argument to declare the value of the placeholders.
  1504. * See t() for documentation on how $message and $variables interact.
  1505. * @param $variables
  1506. * Array of variables to replace in the message on display or
  1507. * NULL if message is already translated or not possible to
  1508. * translate.
  1509. * @param $severity
  1510. * The severity of the message; one of the following values as defined in
  1511. * @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
  1512. * - WATCHDOG_EMERGENCY: Emergency, system is unusable.
  1513. * - WATCHDOG_ALERT: Alert, action must be taken immediately.
  1514. * - WATCHDOG_CRITICAL: Critical conditions.
  1515. * - WATCHDOG_ERROR: Error conditions.
  1516. * - WATCHDOG_WARNING: Warning conditions.
  1517. * - WATCHDOG_NOTICE: (default) Normal but significant conditions.
  1518. * - WATCHDOG_INFO: Informational messages.
  1519. * - WATCHDOG_DEBUG: Debug-level messages.
  1520. * @param $link
  1521. * A link to associate with the message.
  1522. *
  1523. * @see watchdog_severity_levels()
  1524. * @see hook_watchdog()
  1525. */
  1526. function watchdog($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL) {
  1527. global $user, $base_root;
  1528. static $in_error_state = FALSE;
  1529. // It is possible that the error handling will itself trigger an error. In that case, we could
  1530. // end up in an infinite loop. To avoid that, we implement a simple static semaphore.
  1531. if (!$in_error_state && function_exists('module_implements')) {
  1532. $in_error_state = TRUE;
  1533. // The user object may not exist in all conditions, so 0 is substituted if needed.
  1534. $user_uid = isset($user->uid) ? $user->uid : 0;
  1535. // Prepare the fields to be logged
  1536. $log_entry = array(
  1537. 'type' => $type,
  1538. 'message' => $message,
  1539. 'variables' => $variables,
  1540. 'severity' => $severity,
  1541. 'link' => $link,
  1542. 'user' => $user,
  1543. 'uid' => $user_uid,
  1544. 'request_uri' => $base_root . request_uri(),
  1545. 'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
  1546. 'ip' => ip_address(),
  1547. // Request time isn't accurate for long processes, use time() instead.
  1548. 'timestamp' => time(),
  1549. );
  1550. // Call the logging hooks to log/process the message
  1551. foreach (module_implements('watchdog') as $module) {
  1552. module_invoke($module, 'watchdog', $log_entry);
  1553. }
  1554. // It is critical that the semaphore is only cleared here, in the parent
  1555. // watchdog() call (not outside the loop), to prevent recursive execution.
  1556. $in_error_state = FALSE;
  1557. }
  1558. }
  1559. /**
  1560. * Sets a message to display to the user.
  1561. *
  1562. * Messages are stored in a session variable and displayed in page.tpl.php via
  1563. * the $messages theme variable.
  1564. *
  1565. * Example usage:
  1566. * @code
  1567. * drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
  1568. * @endcode
  1569. *
  1570. * @param string $message
  1571. * (optional) The translated message to be displayed to the user. For
  1572. * consistency with other messages, it should begin with a capital letter and
  1573. * end with a period.
  1574. * @param string $type
  1575. * (optional) The message's type. Defaults to 'status'. These values are
  1576. * supported:
  1577. * - 'status'
  1578. * - 'warning'
  1579. * - 'error'
  1580. * @param bool $repeat
  1581. * (optional) If this is FALSE and the message is already set, then the
  1582. * message won't be repeated. Defaults to TRUE.
  1583. *
  1584. * @return array|null
  1585. * A multidimensional array with keys corresponding to the set message types.
  1586. * The indexed array values of each contain the set messages for that type.
  1587. * Or, if there are no messages set, the function returns NULL.
  1588. *
  1589. * @see drupal_get_messages()
  1590. * @see theme_status_messages()
  1591. */
  1592. function drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE) {
  1593. if ($message) {
  1594. if (!isset($_SESSION['messages'][$type])) {
  1595. $_SESSION['messages'][$type] = array();
  1596. }
  1597. if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
  1598. $_SESSION['messages'][$type][] = $message;
  1599. }
  1600. // Mark this page as being uncacheable.
  1601. drupal_page_is_cacheable(FALSE);
  1602. }
  1603. // Messages not set when DB connection fails.
  1604. return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
  1605. }
  1606. /**
  1607. * Returns all messages that have been set with drupal_set_message().
  1608. *
  1609. * @param string $type
  1610. * (optional) Limit the messages returned by type. Defaults to NULL, meaning
  1611. * all types. These values are supported:
  1612. * - NULL
  1613. * - 'status'
  1614. * - 'warning'
  1615. * - 'error'
  1616. * @param bool $clear_queue
  1617. * (optional) If this is TRUE, the queue will be cleared of messages of the
  1618. * type specified in the $type parameter. Otherwise the queue will be left
  1619. * intact. Defaults to TRUE.
  1620. *
  1621. * @return array
  1622. * A multidimensional array with keys corresponding to the set message types.
  1623. * The indexed array values of each contain the set messages for that type.
  1624. * The messages returned are limited to the type specified in the $type
  1625. * parameter. If there are no messages of the specified type, an empty array
  1626. * is returned.
  1627. *
  1628. * @see drupal_set_message()
  1629. * @see theme_status_messages()
  1630. */
  1631. function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
  1632. if ($messages = drupal_set_message()) {
  1633. if ($type) {
  1634. if ($clear_queue) {
  1635. unset($_SESSION['messages'][$type]);
  1636. }
  1637. if (isset($messages[$type])) {
  1638. return array($type => $messages[$type]);
  1639. }
  1640. }
  1641. else {
  1642. if ($clear_queue) {
  1643. unset($_SESSION['messages']);
  1644. }
  1645. return $messages;
  1646. }
  1647. }
  1648. return array();
  1649. }
  1650. /**
  1651. * Gets the title of the current page.
  1652. *
  1653. * The title is displayed on the page and in the title bar.
  1654. *
  1655. * @return
  1656. * The current page's title.
  1657. */
  1658. function drupal_get_title() {
  1659. $title = drupal_set_title();
  1660. // During a bootstrap, menu.inc is not included and thus we cannot provide a title.
  1661. if (!isset($title) && function_exists('menu_get_active_title')) {
  1662. $title = check_plain(menu_get_active_title());
  1663. }
  1664. return $title;
  1665. }
  1666. /**
  1667. * Sets the title of the current page.
  1668. *
  1669. * The title is displayed on the page and in the title bar.
  1670. *
  1671. * @param $title
  1672. * Optional string value to assign to the page title; or if set to NULL
  1673. * (default), leaves the current title unchanged.
  1674. * @param $output
  1675. * Optional flag - normally should be left as CHECK_PLAIN. Only set to
  1676. * PASS_THROUGH if you have already removed any possibly dangerous code
  1677. * from $title using a function like check_plain() or filter_xss(). With this
  1678. * flag the string will be passed through unchanged.
  1679. *
  1680. * @return
  1681. * The updated title of the current page.
  1682. */
  1683. function drupal_set_title($title = NULL, $output = CHECK_PLAIN) {
  1684. $stored_title = &drupal_static(__FUNCTION__);
  1685. if (isset($title)) {
  1686. $stored_title = ($output == PASS_THROUGH) ? $title : check_plain($title);
  1687. }
  1688. return $stored_title;
  1689. }
  1690. /**
  1691. * Checks to see if an IP address has been blocked.
  1692. *
  1693. * Blocked IP addresses are stored in the database by default. However for
  1694. * performance reasons we allow an override in settings.php. This allows us
  1695. * to avoid querying the database at this critical stage of the bootstrap if
  1696. * an administrative interface for IP address blocking is not required.
  1697. *
  1698. * @param $ip
  1699. * IP address to check.
  1700. *
  1701. * @return bool
  1702. * TRUE if access is denied, FALSE if access is allowed.
  1703. */
  1704. function drupal_is_denied($ip) {
  1705. // Because this function is called on every page request, we first check
  1706. // for an array of IP addresses in settings.php before querying the
  1707. // database.
  1708. $blocked_ips = variable_get('blocked_ips');
  1709. $denied = FALSE;
  1710. if (isset($blocked_ips) && is_array($blocked_ips)) {
  1711. $denied = in_array($ip, $blocked_ips);
  1712. }
  1713. // Only check if database.inc is loaded already. If
  1714. // $conf['page_cache_without_database'] = TRUE; is set in settings.php,
  1715. // then the database won't be loaded here so the IPs in the database
  1716. // won't be denied. However the user asked explicitly not to use the
  1717. // database and also in this case it's quite likely that the user relies
  1718. // on higher performance solutions like a firewall.
  1719. elseif (class_exists('Database', FALSE)) {
  1720. $denied = (bool)db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();
  1721. }
  1722. return $denied;
  1723. }
  1724. /**
  1725. * Handles denied users.
  1726. *
  1727. * @param $ip
  1728. * IP address to check. Prints a message and exits if access is denied.
  1729. */
  1730. function drupal_block_denied($ip) {
  1731. // Deny access to blocked IP addresses - t() is not yet available.
  1732. if (drupal_is_denied($ip)) {
  1733. header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
  1734. print 'Sorry, ' . check_plain(ip_address()) . ' has been banned.';
  1735. exit();
  1736. }
  1737. }
  1738. /**
  1739. * Returns a string of highly randomized bytes (over the full 8-bit range).
  1740. *
  1741. * This function is better than simply calling mt_rand() or any other built-in
  1742. * PHP function because it can return a long string of bytes (compared to < 4
  1743. * bytes normally from mt_rand()) and uses the best available pseudo-random
  1744. * source.
  1745. *
  1746. * @param $count
  1747. * The number of characters (bytes) to return in the string.
  1748. */
  1749. function drupal_random_bytes($count) {
  1750. // $random_state does not use drupal_static as it stores random bytes.
  1751. static $random_state, $bytes, $php_compatible;
  1752. // Initialize on the first call. The contents of $_SERVER includes a mix of
  1753. // user-specific and system information that varies a little with each page.
  1754. if (!isset($random_state)) {
  1755. $random_state = print_r($_SERVER, TRUE);
  1756. if (function_exists('getmypid')) {
  1757. // Further initialize with the somewhat random PHP process ID.
  1758. $random_state .= getmypid();
  1759. }
  1760. $bytes = '';
  1761. }
  1762. if (strlen($bytes) < $count) {
  1763. // PHP versions prior 5.3.4 experienced openssl_random_pseudo_bytes()
  1764. // locking on Windows and rendered it unusable.
  1765. if (!isset($php_compatible)) {
  1766. $php_compatible = version_compare(PHP_VERSION, '5.3.4', '>=');
  1767. }
  1768. // /dev/urandom is available on many *nix systems and is considered the
  1769. // best commonly available pseudo-random source.
  1770. if ($fh = @fopen('/dev/urandom', 'rb')) {
  1771. // PHP only performs buffered reads, so in reality it will always read
  1772. // at least 4096 bytes. Thus, it costs nothing extra to read and store
  1773. // that much so as to speed any additional invocations.
  1774. $bytes .= fread($fh, max(4096, $count));
  1775. fclose($fh);
  1776. }
  1777. // openssl_random_pseudo_bytes() will find entropy in a system-dependent
  1778. // way.
  1779. elseif ($php_compatible && function_exists('openssl_random_pseudo_bytes')) {
  1780. $bytes .= openssl_random_pseudo_bytes($count - strlen($bytes));
  1781. }
  1782. // If /dev/urandom is not available or returns no bytes, this loop will
  1783. // generate a good set of pseudo-random bytes on any system.
  1784. // Note that it may be important that our $random_state is passed
  1785. // through hash() prior to being rolled into $output, that the two hash()
  1786. // invocations are different, and that the extra input into the first one -
  1787. // the microtime() - is prepended rather than appended. This is to avoid
  1788. // directly leaking $random_state via the $output stream, which could
  1789. // allow for trivial prediction of further "random" numbers.
  1790. while (strlen($bytes) < $count) {
  1791. $random_state = hash('sha256', microtime() . mt_rand() . $random_state);
  1792. $bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
  1793. }
  1794. }
  1795. $output = substr($bytes, 0, $count);
  1796. $bytes = substr($bytes, $count);
  1797. return $output;
  1798. }
  1799. /**
  1800. * Calculates a base-64 encoded, URL-safe sha-256 hmac.
  1801. *
  1802. * @param $data
  1803. * String to be validated with the hmac.
  1804. * @param $key
  1805. * A secret string key.
  1806. *
  1807. * @return
  1808. * A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and
  1809. * any = padding characters removed.
  1810. */
  1811. function drupal_hmac_base64($data, $key) {
  1812. $hmac = base64_encode(hash_hmac('sha256', $data, $key, TRUE));
  1813. // Modify the hmac so it's safe to use in URLs.
  1814. return strtr($hmac, array('+' => '-', '/' => '_', '=' => ''));
  1815. }
  1816. /**
  1817. * Calculates a base-64 encoded, URL-safe sha-256 hash.
  1818. *
  1819. * @param $data
  1820. * String to be hashed.
  1821. *
  1822. * @return
  1823. * A base-64 encoded sha-256 hash, with + replaced with -, / with _ and
  1824. * any = padding characters removed.
  1825. */
  1826. function drupal_hash_base64($data) {
  1827. $hash = base64_encode(hash('sha256', $data, TRUE));
  1828. // Modify the hash so it's safe to use in URLs.
  1829. return strtr($hash, array('+' => '-', '/' => '_', '=' => ''));
  1830. }
  1831. /**
  1832. * Merges multiple arrays, recursively, and returns the merged array.
  1833. *
  1834. * This function is similar to PHP's array_merge_recursive() function, but it
  1835. * handles non-array values differently. When merging values that are not both
  1836. * arrays, the latter value replaces the former rather than merging with it.
  1837. *
  1838. * Example:
  1839. * @code
  1840. * $link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => t('X'), 'class' => array('a', 'b')));
  1841. * $link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('c', 'd')));
  1842. *
  1843. * // This results in array('fragment' => array('x', 'y'), 'attributes' => array('title' => array(t('X'), t('Y')), 'class' => array('a', 'b', 'c', 'd'))).
  1844. * $incorrect = array_merge_recursive($link_options_1, $link_options_2);
  1845. *
  1846. * // This results in array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('a', 'b', 'c', 'd'))).
  1847. * $correct = drupal_array_merge_deep($link_options_1, $link_options_2);
  1848. * @endcode
  1849. *
  1850. * @param ...
  1851. * Arrays to merge.
  1852. *
  1853. * @return
  1854. * The merged array.
  1855. *
  1856. * @see drupal_array_merge_deep_array()
  1857. */
  1858. function drupal_array_merge_deep() {
  1859. $args = func_get_args();
  1860. return drupal_array_merge_deep_array($args);
  1861. }
  1862. /**
  1863. * Merges multiple arrays, recursively, and returns the merged array.
  1864. *
  1865. * This function is equivalent to drupal_array_merge_deep(), except the
  1866. * input arrays are passed as a single array parameter rather than a variable
  1867. * parameter list.
  1868. *
  1869. * The following are equivalent:
  1870. * - drupal_array_merge_deep($a, $b);
  1871. * - drupal_array_merge_deep_array(array($a, $b));
  1872. *
  1873. * The following are also equivalent:
  1874. * - call_user_func_array('drupal_array_merge_deep', $arrays_to_merge);
  1875. * - drupal_array_merge_deep_array($arrays_to_merge);
  1876. *
  1877. * @see drupal_array_merge_deep()
  1878. */
  1879. function drupal_array_merge_deep_array($arrays) {
  1880. $result = array();
  1881. foreach ($arrays as $array) {
  1882. foreach ($array as $key => $value) {
  1883. // Renumber integer keys as array_merge_recursive() does. Note that PHP
  1884. // automatically converts array keys that are integer strings (e.g., '1')
  1885. // to integers.
  1886. if (is_integer($key)) {
  1887. $result[] = $value;
  1888. }
  1889. // Recurse when both values are arrays.
  1890. elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
  1891. $result[$key] = drupal_array_merge_deep_array(array($result[$key], $value));
  1892. }
  1893. // Otherwise, use the latter value, overriding any previous value.
  1894. else {
  1895. $result[$key] = $value;
  1896. }
  1897. }
  1898. }
  1899. return $result;
  1900. }
  1901. /**
  1902. * Generates a default anonymous $user object.
  1903. *
  1904. * @return Object - the user object.
  1905. */
  1906. function drupal_anonymous_user() {
  1907. $user = new stdClass();
  1908. $user->uid = 0;
  1909. $user->hostname = ip_address();
  1910. $user->roles = array();
  1911. $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
  1912. $user->cache = 0;
  1913. return $user;
  1914. }
  1915. /**
  1916. * Ensures Drupal is bootstrapped to the specified phase.
  1917. *
  1918. * In order to bootstrap Drupal from another PHP script, you can use this code:
  1919. * @code
  1920. * define('DRUPAL_ROOT', '/path/to/drupal');
  1921. * require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
  1922. * drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
  1923. * @endcode
  1924. *
  1925. * @param $phase
  1926. * A constant telling which phase to bootstrap to. When you bootstrap to a
  1927. * particular phase, all earlier phases are run automatically. Possible
  1928. * values:
  1929. * - DRUPAL_BOOTSTRAP_CONFIGURATION: Initializes configuration.
  1930. * - DRUPAL_BOOTSTRAP_PAGE_CACHE: Tries to serve a cached page.
  1931. * - DRUPAL_BOOTSTRAP_DATABASE: Initializes the database layer.
  1932. * - DRUPAL_BOOTSTRAP_VARIABLES: Initializes the variable system.
  1933. * - DRUPAL_BOOTSTRAP_SESSION: Initializes session handling.
  1934. * - DRUPAL_BOOTSTRAP_PAGE_HEADER: Sets up the page header.
  1935. * - DRUPAL_BOOTSTRAP_LANGUAGE: Finds out the language of the page.
  1936. * - DRUPAL_BOOTSTRAP_FULL: Fully loads Drupal. Validates and fixes input
  1937. * data.
  1938. * @param $new_phase
  1939. * A boolean, set to FALSE if calling drupal_bootstrap from inside a
  1940. * function called from drupal_bootstrap (recursion).
  1941. *
  1942. * @return
  1943. * The most recently completed phase.
  1944. */
  1945. function drupal_bootstrap($phase = NULL, $new_phase = TRUE) {
  1946. // Not drupal_static(), because does not depend on any run-time information.
  1947. static $phases = array(
  1948. DRUPAL_BOOTSTRAP_CONFIGURATION,
  1949. DRUPAL_BOOTSTRAP_PAGE_CACHE,
  1950. DRUPAL_BOOTSTRAP_DATABASE,
  1951. DRUPAL_BOOTSTRAP_VARIABLES,
  1952. DRUPAL_BOOTSTRAP_SESSION,
  1953. DRUPAL_BOOTSTRAP_PAGE_HEADER,
  1954. DRUPAL_BOOTSTRAP_LANGUAGE,
  1955. DRUPAL_BOOTSTRAP_FULL,
  1956. );
  1957. // Not drupal_static(), because the only legitimate API to control this is to
  1958. // call drupal_bootstrap() with a new phase parameter.
  1959. static $final_phase;
  1960. // Not drupal_static(), because it's impossible to roll back to an earlier
  1961. // bootstrap state.
  1962. static $stored_phase = -1;
  1963. // When not recursing, store the phase name so it's not forgotten while
  1964. // recursing.
  1965. if ($new_phase) {
  1966. $final_phase = $phase;
  1967. }
  1968. if (isset($phase)) {
  1969. // Call a phase if it has not been called before and is below the requested
  1970. // phase.
  1971. while ($phases && $phase > $stored_phase && $final_phase > $stored_phase) {
  1972. $current_phase = array_shift($phases);
  1973. // This function is re-entrant. Only update the completed phase when the
  1974. // current call actually resulted in a progress in the bootstrap process.
  1975. if ($current_phase > $stored_phase) {
  1976. $stored_phase = $current_phase;
  1977. }
  1978. switch ($current_phase) {
  1979. case DRUPAL_BOOTSTRAP_CONFIGURATION:
  1980. _drupal_bootstrap_configuration();
  1981. break;
  1982. case DRUPAL_BOOTSTRAP_PAGE_CACHE:
  1983. _drupal_bootstrap_page_cache();
  1984. break;
  1985. case DRUPAL_BOOTSTRAP_DATABASE:
  1986. _drupal_bootstrap_database();
  1987. break;
  1988. case DRUPAL_BOOTSTRAP_VARIABLES:
  1989. _drupal_bootstrap_variables();
  1990. break;
  1991. case DRUPAL_BOOTSTRAP_SESSION:
  1992. require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
  1993. drupal_session_initialize();
  1994. break;
  1995. case DRUPAL_BOOTSTRAP_PAGE_HEADER:
  1996. _drupal_bootstrap_page_header();
  1997. break;
  1998. case DRUPAL_BOOTSTRAP_LANGUAGE:
  1999. drupal_language_initialize();
  2000. break;
  2001. case DRUPAL_BOOTSTRAP_FULL:
  2002. require_once DRUPAL_ROOT . '/includes/common.inc';
  2003. _drupal_bootstrap_full();
  2004. break;
  2005. }
  2006. }
  2007. }
  2008. return $stored_phase;
  2009. }
  2010. /**
  2011. * Returns the time zone of the current user.
  2012. */
  2013. function drupal_get_user_timezone() {
  2014. global $user;
  2015. if (variable_get('configurable_timezones', 1) && $user->uid && $user->timezone) {
  2016. return $user->timezone;
  2017. }
  2018. else {
  2019. // Ignore PHP strict notice if time zone has not yet been set in the php.ini
  2020. // configuration.
  2021. return variable_get('date_default_timezone', @date_default_timezone_get());
  2022. }
  2023. }
  2024. /**
  2025. * Provides custom PHP error handling.
  2026. *
  2027. * @param $error_level
  2028. * The level of the error raised.
  2029. * @param $message
  2030. * The error message.
  2031. * @param $filename
  2032. * The filename that the error was raised in.
  2033. * @param $line
  2034. * The line number the error was raised at.
  2035. * @param $context
  2036. * An array that points to the active symbol table at the point the error
  2037. * occurred.
  2038. */
  2039. function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
  2040. require_once DRUPAL_ROOT . '/includes/errors.inc';
  2041. _drupal_error_handler_real($error_level, $message, $filename, $line, $context);
  2042. }
  2043. /**
  2044. * Provides custom PHP exception handling.
  2045. *
  2046. * Uncaught exceptions are those not enclosed in a try/catch block. They are
  2047. * always fatal: the execution of the script will stop as soon as the exception
  2048. * handler exits.
  2049. *
  2050. * @param $exception
  2051. * The exception object that was thrown.
  2052. */
  2053. function _drupal_exception_handler($exception) {
  2054. require_once DRUPAL_ROOT . '/includes/errors.inc';
  2055. try {
  2056. // Log the message to the watchdog and return an error page to the user.
  2057. _drupal_log_error(_drupal_decode_exception($exception), TRUE);
  2058. }
  2059. catch (Exception $exception2) {
  2060. // Another uncaught exception was thrown while handling the first one.
  2061. // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
  2062. if (error_displayable()) {
  2063. print '<h1>Additional uncaught exception thrown while handling exception.</h1>';
  2064. print '<h2>Original</h2><p>' . _drupal_render_exception_safe($exception) . '</p>';
  2065. print '<h2>Additional</h2><p>' . _drupal_render_exception_safe($exception2) . '</p><hr />';
  2066. }
  2067. }
  2068. }
  2069. /**
  2070. * Sets up the script environment and loads settings.php.
  2071. */
  2072. function _drupal_bootstrap_configuration() {
  2073. // Set the Drupal custom error handler.
  2074. set_error_handler('_drupal_error_handler');
  2075. set_exception_handler('_drupal_exception_handler');
  2076. drupal_environment_initialize();
  2077. // Start a page timer:
  2078. timer_start('page');
  2079. // Initialize the configuration, including variables from settings.php.
  2080. drupal_settings_initialize();
  2081. }
  2082. /**
  2083. * Attempts to serve a page from the cache.
  2084. */
  2085. function _drupal_bootstrap_page_cache() {
  2086. global $user;
  2087. // Allow specifying special cache handlers in settings.php, like
  2088. // using memcached or files for storing cache information.
  2089. require_once DRUPAL_ROOT . '/includes/cache.inc';
  2090. foreach (variable_get('cache_backends', array()) as $include) {
  2091. require_once DRUPAL_ROOT . '/' . $include;
  2092. }
  2093. // Check for a cache mode force from settings.php.
  2094. if (variable_get('page_cache_without_database')) {
  2095. $cache_enabled = TRUE;
  2096. }
  2097. else {
  2098. drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE);
  2099. $cache_enabled = variable_get('cache');
  2100. }
  2101. drupal_block_denied(ip_address());
  2102. // If there is no session cookie and cache is enabled (or forced), try
  2103. // to serve a cached page.
  2104. if (!isset($_COOKIE[session_name()]) && $cache_enabled) {
  2105. // Make sure there is a user object because its timestamp will be
  2106. // checked, hook_boot might check for anonymous user etc.
  2107. $user = drupal_anonymous_user();
  2108. // Get the page from the cache.
  2109. $cache = drupal_page_get_cache();
  2110. // If there is a cached page, display it.
  2111. if (is_object($cache)) {
  2112. header('X-Drupal-Cache: HIT');
  2113. // Restore the metadata cached with the page.
  2114. $_GET['q'] = $cache->data['path'];
  2115. drupal_set_title($cache->data['title'], PASS_THROUGH);
  2116. date_default_timezone_set(drupal_get_user_timezone());
  2117. // If the skipping of the bootstrap hooks is not enforced, call
  2118. // hook_boot.
  2119. if (variable_get('page_cache_invoke_hooks', TRUE)) {
  2120. bootstrap_invoke_all('boot');
  2121. }
  2122. drupal_serve_page_from_cache($cache);
  2123. // If the skipping of the bootstrap hooks is not enforced, call
  2124. // hook_exit.
  2125. if (variable_get('page_cache_invoke_hooks', TRUE)) {
  2126. bootstrap_invoke_all('exit');
  2127. }
  2128. // We are done.
  2129. exit;
  2130. }
  2131. else {
  2132. header('X-Drupal-Cache: MISS');
  2133. }
  2134. }
  2135. }
  2136. /**
  2137. * Initializes the database system and registers autoload functions.
  2138. */
  2139. function _drupal_bootstrap_database() {
  2140. // Redirect the user to the installation script if Drupal has not been
  2141. // installed yet (i.e., if no $databases array has been defined in the
  2142. // settings.php file) and we are not already installing.
  2143. if (empty($GLOBALS['databases']) && !drupal_installation_attempted()) {
  2144. include_once DRUPAL_ROOT . '/includes/install.inc';
  2145. install_goto('install.php');
  2146. }
  2147. // The user agent header is used to pass a database prefix in the request when
  2148. // running tests. However, for security reasons, it is imperative that we
  2149. // validate we ourselves made the request.
  2150. if ($test_prefix = drupal_valid_test_ua()) {
  2151. // Set the test run id for use in other parts of Drupal.
  2152. $test_info = &$GLOBALS['drupal_test_info'];
  2153. $test_info['test_run_id'] = $test_prefix;
  2154. $test_info['in_child_site'] = TRUE;
  2155. foreach ($GLOBALS['databases']['default'] as &$value) {
  2156. // Extract the current default database prefix.
  2157. if (!isset($value['prefix'])) {
  2158. $current_prefix = '';
  2159. }
  2160. elseif (is_array($value['prefix'])) {
  2161. $current_prefix = $value['prefix']['default'];
  2162. }
  2163. else {
  2164. $current_prefix = $value['prefix'];
  2165. }
  2166. // Remove the current database prefix and replace it by our own.
  2167. $value['prefix'] = array(
  2168. 'default' => $current_prefix . $test_prefix,
  2169. );
  2170. }
  2171. }
  2172. // Initialize the database system. Note that the connection
  2173. // won't be initialized until it is actually requested.
  2174. require_once DRUPAL_ROOT . '/includes/database/database.inc';
  2175. // Register autoload functions so that we can access classes and interfaces.
  2176. // The database autoload routine comes first so that we can load the database
  2177. // system without hitting the database. That is especially important during
  2178. // the install or upgrade process.
  2179. spl_autoload_register('drupal_autoload_class');
  2180. spl_autoload_register('drupal_autoload_interface');
  2181. }
  2182. /**
  2183. * Loads system variables and all enabled bootstrap modules.
  2184. */
  2185. function _drupal_bootstrap_variables() {
  2186. global $conf;
  2187. // Initialize the lock system.
  2188. require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
  2189. lock_initialize();
  2190. // Load variables from the database, but do not overwrite variables set in settings.php.
  2191. $conf = variable_initialize(isset($conf) ? $conf : array());
  2192. // Load bootstrap modules.
  2193. require_once DRUPAL_ROOT . '/includes/module.inc';
  2194. module_load_all(TRUE);
  2195. }
  2196. /**
  2197. * Invokes hook_boot(), initializes locking system, and sends HTTP headers.
  2198. */
  2199. function _drupal_bootstrap_page_header() {
  2200. bootstrap_invoke_all('boot');
  2201. if (!drupal_is_cli()) {
  2202. ob_start();
  2203. drupal_page_header();
  2204. }
  2205. }
  2206. /**
  2207. * Returns the current bootstrap phase for this Drupal process.
  2208. *
  2209. * The current phase is the one most recently completed by drupal_bootstrap().
  2210. *
  2211. * @see drupal_bootstrap()
  2212. */
  2213. function drupal_get_bootstrap_phase() {
  2214. return drupal_bootstrap();
  2215. }
  2216. /**
  2217. * Returns the test prefix if this is an internal request from SimpleTest.
  2218. *
  2219. * @return
  2220. * Either the simpletest prefix (the string "simpletest" followed by any
  2221. * number of digits) or FALSE if the user agent does not contain a valid
  2222. * HMAC and timestamp.
  2223. */
  2224. function drupal_valid_test_ua() {
  2225. global $drupal_hash_salt;
  2226. // No reason to reset this.
  2227. static $test_prefix;
  2228. if (isset($test_prefix)) {
  2229. return $test_prefix;
  2230. }
  2231. if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/^(simpletest\d+);(.+);(.+);(.+)$/", $_SERVER['HTTP_USER_AGENT'], $matches)) {
  2232. list(, $prefix, $time, $salt, $hmac) = $matches;
  2233. $check_string = $prefix . ';' . $time . ';' . $salt;
  2234. // We use the salt from settings.php to make the HMAC key, since
  2235. // the database is not yet initialized and we can't access any Drupal variables.
  2236. // The file properties add more entropy not easily accessible to others.
  2237. $key = $drupal_hash_salt . filectime(__FILE__) . fileinode(__FILE__);
  2238. $time_diff = REQUEST_TIME - $time;
  2239. // Since we are making a local request a 5 second time window is allowed,
  2240. // and the HMAC must match.
  2241. if ($time_diff >= 0 && $time_diff <= 5 && $hmac == drupal_hmac_base64($check_string, $key)) {
  2242. $test_prefix = $prefix;
  2243. return $test_prefix;
  2244. }
  2245. }
  2246. $test_prefix = FALSE;
  2247. return $test_prefix;
  2248. }
  2249. /**
  2250. * Generates a user agent string with a HMAC and timestamp for simpletest.
  2251. */
  2252. function drupal_generate_test_ua($prefix) {
  2253. global $drupal_hash_salt;
  2254. static $key;
  2255. if (!isset($key)) {
  2256. // We use the salt from settings.php to make the HMAC key, since
  2257. // the database is not yet initialized and we can't access any Drupal variables.
  2258. // The file properties add more entropy not easily accessible to others.
  2259. $key = $drupal_hash_salt . filectime(__FILE__) . fileinode(__FILE__);
  2260. }
  2261. // Generate a moderately secure HMAC based on the database credentials.
  2262. $salt = uniqid('', TRUE);
  2263. $check_string = $prefix . ';' . time() . ';' . $salt;
  2264. return $check_string . ';' . drupal_hmac_base64($check_string, $key);
  2265. }
  2266. /**
  2267. * Enables use of the theme system without requiring database access.
  2268. *
  2269. * Loads and initializes the theme system for site installs, updates and when
  2270. * the site is in maintenance mode. This also applies when the database fails.
  2271. *
  2272. * @see _drupal_maintenance_theme()
  2273. */
  2274. function drupal_maintenance_theme() {
  2275. require_once DRUPAL_ROOT . '/includes/theme.maintenance.inc';
  2276. _drupal_maintenance_theme();
  2277. }
  2278. /**
  2279. * Returns a simple 404 Not Found page.
  2280. *
  2281. * If fast 404 pages are enabled, and this is a matching page then print a
  2282. * simple 404 page and exit.
  2283. *
  2284. * This function is called from drupal_deliver_html_page() at the time when a
  2285. * a normal 404 page is generated, but it can also optionally be called directly
  2286. * from settings.php to prevent a Drupal bootstrap on these pages. See
  2287. * documentation in settings.php for the benefits and drawbacks of using this.
  2288. *
  2289. * Paths to dynamically-generated content, such as image styles, should also be
  2290. * accounted for in this function.
  2291. */
  2292. function drupal_fast_404() {
  2293. $exclude_paths = variable_get('404_fast_paths_exclude', FALSE);
  2294. if ($exclude_paths && !preg_match($exclude_paths, $_GET['q'])) {
  2295. $fast_paths = variable_get('404_fast_paths', FALSE);
  2296. if ($fast_paths && preg_match($fast_paths, $_GET['q'])) {
  2297. drupal_add_http_header('Status', '404 Not Found');
  2298. $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>');
  2299. // Replace @path in the variable with the page path.
  2300. print strtr($fast_404_html, array('@path' => check_plain(request_uri())));
  2301. exit;
  2302. }
  2303. }
  2304. }
  2305. /**
  2306. * Returns TRUE if a Drupal installation is currently being attempted.
  2307. */
  2308. function drupal_installation_attempted() {
  2309. return defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'install';
  2310. }
  2311. /**
  2312. * Returns the name of the proper localization function.
  2313. *
  2314. * get_t() exists to support localization for code that might run during
  2315. * the installation phase, when some elements of the system might not have
  2316. * loaded.
  2317. *
  2318. * This would include implementations of hook_install(), which could run
  2319. * during the Drupal installation phase, and might also be run during
  2320. * non-installation time, such as while installing the module from the the
  2321. * module administration page.
  2322. *
  2323. * Example usage:
  2324. * @code
  2325. * $t = get_t();
  2326. * $translated = $t('translate this');
  2327. * @endcode
  2328. *
  2329. * Use t() if your code will never run during the Drupal installation phase.
  2330. * Use st() if your code will only run during installation and never any other
  2331. * time. Use get_t() if your code could run in either circumstance.
  2332. *
  2333. * @see t()
  2334. * @see st()
  2335. * @ingroup sanitization
  2336. */
  2337. function get_t() {
  2338. static $t;
  2339. // This is not converted to drupal_static because there is no point in
  2340. // resetting this as it can not change in the course of a request.
  2341. if (!isset($t)) {
  2342. $t = drupal_installation_attempted() ? 'st' : 't';
  2343. }
  2344. return $t;
  2345. }
  2346. /**
  2347. * Initializes all the defined language types.
  2348. */
  2349. function drupal_language_initialize() {
  2350. $types = language_types();
  2351. // Ensure the language is correctly returned, even without multilanguage
  2352. // support. Also make sure we have a $language fallback, in case a language
  2353. // negotiation callback needs to do a full bootstrap.
  2354. // Useful for eg. XML/HTML 'lang' attributes.
  2355. $default = language_default();
  2356. foreach ($types as $type) {
  2357. $GLOBALS[$type] = $default;
  2358. }
  2359. if (drupal_multilingual()) {
  2360. include_once DRUPAL_ROOT . '/includes/language.inc';
  2361. foreach ($types as $type) {
  2362. $GLOBALS[$type] = language_initialize($type);
  2363. }
  2364. // Allow modules to react on language system initialization in multilingual
  2365. // environments.
  2366. bootstrap_invoke_all('language_init');
  2367. }
  2368. }
  2369. /**
  2370. * Returns a list of the built-in language types.
  2371. *
  2372. * @return
  2373. * An array of key-values pairs where the key is the language type and the
  2374. * value is its configurability.
  2375. */
  2376. function drupal_language_types() {
  2377. return array(
  2378. LANGUAGE_TYPE_INTERFACE => TRUE,
  2379. LANGUAGE_TYPE_CONTENT => FALSE,
  2380. LANGUAGE_TYPE_URL => FALSE,
  2381. );
  2382. }
  2383. /**
  2384. * Returns TRUE if there is more than one language enabled.
  2385. *
  2386. * @return
  2387. * TRUE if more than one language is enabled.
  2388. */
  2389. function drupal_multilingual() {
  2390. // The "language_count" variable stores the number of enabled languages to
  2391. // avoid unnecessarily querying the database when building the list of
  2392. // enabled languages on monolingual sites.
  2393. return variable_get('language_count', 1) > 1;
  2394. }
  2395. /**
  2396. * Returns an array of the available language types.
  2397. *
  2398. * @return
  2399. * An array of all language types where the keys of each are the language type
  2400. * name and its value is its configurability (TRUE/FALSE).
  2401. */
  2402. function language_types() {
  2403. return array_keys(variable_get('language_types', drupal_language_types()));
  2404. }
  2405. /**
  2406. * Returns a list of installed languages, indexed by the specified key.
  2407. *
  2408. * @param $field
  2409. * (optional) The field to index the list with.
  2410. *
  2411. * @return
  2412. * An associative array, keyed on the values of $field.
  2413. * - If $field is 'weight' or 'enabled', the array is nested, with the outer
  2414. * array's values each being associative arrays with language codes as
  2415. * keys and language objects as values.
  2416. * - For all other values of $field, the array is only one level deep, and
  2417. * the array's values are language objects.
  2418. */
  2419. function language_list($field = 'language') {
  2420. $languages = &drupal_static(__FUNCTION__);
  2421. // Init language list
  2422. if (!isset($languages)) {
  2423. if (drupal_multilingual() || module_exists('locale')) {
  2424. $languages['language'] = db_query('SELECT * FROM {languages} ORDER BY weight ASC, name ASC')->fetchAllAssoc('language');
  2425. // Users cannot uninstall the native English language. However, we allow
  2426. // it to be hidden from the installed languages. Therefore, at least one
  2427. // other language must be enabled then.
  2428. if (!$languages['language']['en']->enabled && !variable_get('language_native_enabled', TRUE)) {
  2429. unset($languages['language']['en']);
  2430. }
  2431. }
  2432. else {
  2433. // No locale module, so use the default language only.
  2434. $default = language_default();
  2435. $languages['language'][$default->language] = $default;
  2436. }
  2437. }
  2438. // Return the array indexed by the right field
  2439. if (!isset($languages[$field])) {
  2440. $languages[$field] = array();
  2441. foreach ($languages['language'] as $lang) {
  2442. // Some values should be collected into an array
  2443. if (in_array($field, array('enabled', 'weight'))) {
  2444. $languages[$field][$lang->$field][$lang->language] = $lang;
  2445. }
  2446. else {
  2447. $languages[$field][$lang->$field] = $lang;
  2448. }
  2449. }
  2450. }
  2451. return $languages[$field];
  2452. }
  2453. /**
  2454. * Returns the default language used on the site
  2455. *
  2456. * @param $property
  2457. * Optional property of the language object to return
  2458. */
  2459. function language_default($property = NULL) {
  2460. $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' => ''));
  2461. return $property ? $language->$property : $language;
  2462. }
  2463. /**
  2464. * Returns the requested URL path of the page being viewed.
  2465. *
  2466. * Examples:
  2467. * - http://example.com/node/306 returns "node/306".
  2468. * - http://example.com/drupalfolder/node/306 returns "node/306" while
  2469. * base_path() returns "/drupalfolder/".
  2470. * - http://example.com/path/alias (which is a path alias for node/306) returns
  2471. * "path/alias" as opposed to the internal path.
  2472. * - http://example.com/index.php returns an empty string (meaning: front page).
  2473. * - http://example.com/index.php?page=1 returns an empty string.
  2474. *
  2475. * @return
  2476. * The requested Drupal URL path.
  2477. *
  2478. * @see current_path()
  2479. */
  2480. function request_path() {
  2481. static $path;
  2482. if (isset($path)) {
  2483. return $path;
  2484. }
  2485. if (isset($_GET['q']) && is_string($_GET['q'])) {
  2486. // This is a request with a ?q=foo/bar query string. $_GET['q'] is
  2487. // overwritten in drupal_path_initialize(), but request_path() is called
  2488. // very early in the bootstrap process, so the original value is saved in
  2489. // $path and returned in later calls.
  2490. $path = $_GET['q'];
  2491. }
  2492. elseif (isset($_SERVER['REQUEST_URI'])) {
  2493. // This request is either a clean URL, or 'index.php', or nonsense.
  2494. // Extract the path from REQUEST_URI.
  2495. $request_path = strtok($_SERVER['REQUEST_URI'], '?');
  2496. $base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
  2497. // Unescape and strip $base_path prefix, leaving q without a leading slash.
  2498. $path = substr(urldecode($request_path), $base_path_len + 1);
  2499. // If the path equals the script filename, either because 'index.php' was
  2500. // explicitly provided in the URL, or because the server added it to
  2501. // $_SERVER['REQUEST_URI'] even when it wasn't provided in the URL (some
  2502. // versions of Microsoft IIS do this), the front page should be served.
  2503. if ($path == basename($_SERVER['PHP_SELF'])) {
  2504. $path = '';
  2505. }
  2506. }
  2507. else {
  2508. // This is the front page.
  2509. $path = '';
  2510. }
  2511. // Under certain conditions Apache's RewriteRule directive prepends the value
  2512. // assigned to $_GET['q'] with a slash. Moreover we can always have a trailing
  2513. // slash in place, hence we need to normalize $_GET['q'].
  2514. $path = trim($path, '/');
  2515. return $path;
  2516. }
  2517. /**
  2518. * Returns a component of the current Drupal path.
  2519. *
  2520. * When viewing a page at the path "admin/structure/types", for example, arg(0)
  2521. * returns "admin", arg(1) returns "structure", and arg(2) returns "types".
  2522. *
  2523. * Avoid use of this function where possible, as resulting code is hard to
  2524. * read. In menu callback functions, attempt to use named arguments. See the
  2525. * explanation in menu.inc for how to construct callbacks that take arguments.
  2526. * When attempting to use this function to load an element from the current
  2527. * path, e.g. loading the node on a node page, use menu_get_object() instead.
  2528. *
  2529. * @param $index
  2530. * The index of the component, where each component is separated by a '/'
  2531. * (forward-slash), and where the first component has an index of 0 (zero).
  2532. * @param $path
  2533. * A path to break into components. Defaults to the path of the current page.
  2534. *
  2535. * @return
  2536. * The component specified by $index, or NULL if the specified component was
  2537. * not found. If called without arguments, it returns an array containing all
  2538. * the components of the current path.
  2539. */
  2540. function arg($index = NULL, $path = NULL) {
  2541. // Even though $arguments doesn't need to be resettable for any functional
  2542. // reasons (the result of explode() does not depend on any run-time
  2543. // information), it should be resettable anyway in case a module needs to
  2544. // free up the memory used by it.
  2545. // Use the advanced drupal_static() pattern, since this is called very often.
  2546. static $drupal_static_fast;
  2547. if (!isset($drupal_static_fast)) {
  2548. $drupal_static_fast['arguments'] = &drupal_static(__FUNCTION__);
  2549. }
  2550. $arguments = &$drupal_static_fast['arguments'];
  2551. if (!isset($path)) {
  2552. $path = $_GET['q'];
  2553. }
  2554. if (!isset($arguments[$path])) {
  2555. $arguments[$path] = explode('/', $path);
  2556. }
  2557. if (!isset($index)) {
  2558. return $arguments[$path];
  2559. }
  2560. if (isset($arguments[$path][$index])) {
  2561. return $arguments[$path][$index];
  2562. }
  2563. }
  2564. /**
  2565. * Returns the IP address of the client machine.
  2566. *
  2567. * If Drupal is behind a reverse proxy, we use the X-Forwarded-For header
  2568. * instead of $_SERVER['REMOTE_ADDR'], which would be the IP address of
  2569. * the proxy server, and not the client's. The actual header name can be
  2570. * configured by the reverse_proxy_header variable.
  2571. *
  2572. * @return
  2573. * IP address of client machine, adjusted for reverse proxy and/or cluster
  2574. * environments.
  2575. */
  2576. function ip_address() {
  2577. $ip_address = &drupal_static(__FUNCTION__);
  2578. if (!isset($ip_address)) {
  2579. $ip_address = $_SERVER['REMOTE_ADDR'];
  2580. if (variable_get('reverse_proxy', 0)) {
  2581. $reverse_proxy_header = variable_get('reverse_proxy_header', 'HTTP_X_FORWARDED_FOR');
  2582. if (!empty($_SERVER[$reverse_proxy_header])) {
  2583. // If an array of known reverse proxy IPs is provided, then trust
  2584. // the XFF header if request really comes from one of them.
  2585. $reverse_proxy_addresses = variable_get('reverse_proxy_addresses', array());
  2586. // Turn XFF header into an array.
  2587. $forwarded = explode(',', $_SERVER[$reverse_proxy_header]);
  2588. // Trim the forwarded IPs; they may have been delimited by commas and spaces.
  2589. $forwarded = array_map('trim', $forwarded);
  2590. // Tack direct client IP onto end of forwarded array.
  2591. $forwarded[] = $ip_address;
  2592. // Eliminate all trusted IPs.
  2593. $untrusted = array_diff($forwarded, $reverse_proxy_addresses);
  2594. // The right-most IP is the most specific we can trust.
  2595. $ip_address = array_pop($untrusted);
  2596. }
  2597. }
  2598. }
  2599. return $ip_address;
  2600. }
  2601. /**
  2602. * @addtogroup schemaapi
  2603. * @{
  2604. */
  2605. /**
  2606. * Gets the schema definition of a table, or the whole database schema.
  2607. *
  2608. * The returned schema will include any modifications made by any
  2609. * module that implements hook_schema_alter().
  2610. *
  2611. * @param $table
  2612. * The name of the table. If not given, the schema of all tables is returned.
  2613. * @param $rebuild
  2614. * If true, the schema will be rebuilt instead of retrieved from the cache.
  2615. */
  2616. function drupal_get_schema($table = NULL, $rebuild = FALSE) {
  2617. static $schema;
  2618. if ($rebuild || !isset($table)) {
  2619. $schema = drupal_get_complete_schema($rebuild);
  2620. }
  2621. elseif (!isset($schema)) {
  2622. $schema = new SchemaCache();
  2623. }
  2624. if (!isset($table)) {
  2625. return $schema;
  2626. }
  2627. if (isset($schema[$table])) {
  2628. return $schema[$table];
  2629. }
  2630. else {
  2631. return FALSE;
  2632. }
  2633. }
  2634. /**
  2635. * Extends DrupalCacheArray to allow for dynamic building of the schema cache.
  2636. */
  2637. class SchemaCache extends DrupalCacheArray {
  2638. /**
  2639. * Constructs a SchemaCache object.
  2640. */
  2641. public function __construct() {
  2642. // Cache by request method.
  2643. parent::__construct('schema:runtime:' . ($_SERVER['REQUEST_METHOD'] == 'GET'), 'cache');
  2644. }
  2645. /**
  2646. * Overrides DrupalCacheArray::resolveCacheMiss().
  2647. */
  2648. protected function resolveCacheMiss($offset) {
  2649. $complete_schema = drupal_get_complete_schema();
  2650. $value = isset($complete_schema[$offset]) ? $complete_schema[$offset] : NULL;
  2651. $this->storage[$offset] = $value;
  2652. $this->persist($offset);
  2653. return $value;
  2654. }
  2655. }
  2656. /**
  2657. * Gets the whole database schema.
  2658. *
  2659. * The returned schema will include any modifications made by any
  2660. * module that implements hook_schema_alter().
  2661. *
  2662. * @param $rebuild
  2663. * If true, the schema will be rebuilt instead of retrieved from the cache.
  2664. */
  2665. function drupal_get_complete_schema($rebuild = FALSE) {
  2666. static $schema = array();
  2667. if (empty($schema) || $rebuild) {
  2668. // Try to load the schema from cache.
  2669. if (!$rebuild && $cached = cache_get('schema')) {
  2670. $schema = $cached->data;
  2671. }
  2672. // Otherwise, rebuild the schema cache.
  2673. else {
  2674. $schema = array();
  2675. // Load the .install files to get hook_schema.
  2676. // On some databases this function may be called before bootstrap has
  2677. // been completed, so we force the functions we need to load just in case.
  2678. if (function_exists('module_load_all_includes')) {
  2679. // This function can be called very early in the bootstrap process, so
  2680. // we force the module_list() cache to be refreshed to ensure that it
  2681. // contains the complete list of modules before we go on to call
  2682. // module_load_all_includes().
  2683. module_list(TRUE);
  2684. module_load_all_includes('install');
  2685. }
  2686. require_once DRUPAL_ROOT . '/includes/common.inc';
  2687. // Invoke hook_schema for all modules.
  2688. foreach (module_implements('schema') as $module) {
  2689. // Cast the result of hook_schema() to an array, as a NULL return value
  2690. // would cause array_merge() to set the $schema variable to NULL as well.
  2691. // That would break modules which use $schema further down the line.
  2692. $current = (array) module_invoke($module, 'schema');
  2693. // Set 'module' and 'name' keys for each table, and remove descriptions,
  2694. // as they needlessly slow down cache_get() for every single request.
  2695. _drupal_schema_initialize($current, $module);
  2696. $schema = array_merge($schema, $current);
  2697. }
  2698. drupal_alter('schema', $schema);
  2699. // If the schema is empty, avoid saving it: some database engines require
  2700. // the schema to perform queries, and this could lead to infinite loops.
  2701. if (!empty($schema) && (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL)) {
  2702. cache_set('schema', $schema);
  2703. }
  2704. if ($rebuild) {
  2705. cache_clear_all('schema:', 'cache', TRUE);
  2706. }
  2707. }
  2708. }
  2709. return $schema;
  2710. }
  2711. /**
  2712. * @} End of "addtogroup schemaapi".
  2713. */
  2714. /**
  2715. * @addtogroup registry
  2716. * @{
  2717. */
  2718. /**
  2719. * Confirms that an interface is available.
  2720. *
  2721. * This function is rarely called directly. Instead, it is registered as an
  2722. * spl_autoload() handler, and PHP calls it for us when necessary.
  2723. *
  2724. * @param $interface
  2725. * The name of the interface to check or load.
  2726. *
  2727. * @return
  2728. * TRUE if the interface is currently available, FALSE otherwise.
  2729. */
  2730. function drupal_autoload_interface($interface) {
  2731. return _registry_check_code('interface', $interface);
  2732. }
  2733. /**
  2734. * Confirms that a class is available.
  2735. *
  2736. * This function is rarely called directly. Instead, it is registered as an
  2737. * spl_autoload() handler, and PHP calls it for us when necessary.
  2738. *
  2739. * @param $class
  2740. * The name of the class to check or load.
  2741. *
  2742. * @return
  2743. * TRUE if the class is currently available, FALSE otherwise.
  2744. */
  2745. function drupal_autoload_class($class) {
  2746. return _registry_check_code('class', $class);
  2747. }
  2748. /**
  2749. * Checks for a resource in the registry.
  2750. *
  2751. * @param $type
  2752. * The type of resource we are looking up, or one of the constants
  2753. * REGISTRY_RESET_LOOKUP_CACHE or REGISTRY_WRITE_LOOKUP_CACHE, which
  2754. * signal that we should reset or write the cache, respectively.
  2755. * @param $name
  2756. * The name of the resource, or NULL if either of the REGISTRY_* constants
  2757. * is passed in.
  2758. *
  2759. * @return
  2760. * TRUE if the resource was found, FALSE if not.
  2761. * NULL if either of the REGISTRY_* constants is passed in as $type.
  2762. */
  2763. function _registry_check_code($type, $name = NULL) {
  2764. static $lookup_cache, $cache_update_needed;
  2765. if ($type == 'class' && class_exists($name) || $type == 'interface' && interface_exists($name)) {
  2766. return TRUE;
  2767. }
  2768. if (!isset($lookup_cache)) {
  2769. $lookup_cache = array();
  2770. if ($cache = cache_get('lookup_cache', 'cache_bootstrap')) {
  2771. $lookup_cache = $cache->data;
  2772. }
  2773. }
  2774. // When we rebuild the registry, we need to reset this cache so
  2775. // we don't keep lookups for resources that changed during the rebuild.
  2776. if ($type == REGISTRY_RESET_LOOKUP_CACHE) {
  2777. $cache_update_needed = TRUE;
  2778. $lookup_cache = NULL;
  2779. return;
  2780. }
  2781. // Called from drupal_page_footer, we write to permanent storage if there
  2782. // changes to the lookup cache for this request.
  2783. if ($type == REGISTRY_WRITE_LOOKUP_CACHE) {
  2784. if ($cache_update_needed) {
  2785. cache_set('lookup_cache', $lookup_cache, 'cache_bootstrap');
  2786. }
  2787. return;
  2788. }
  2789. // $type is either 'interface' or 'class', so we only need the first letter to
  2790. // keep the cache key unique.
  2791. $cache_key = $type[0] . $name;
  2792. if (isset($lookup_cache[$cache_key])) {
  2793. if ($lookup_cache[$cache_key]) {
  2794. require_once DRUPAL_ROOT . '/' . $lookup_cache[$cache_key];
  2795. }
  2796. return (bool) $lookup_cache[$cache_key];
  2797. }
  2798. // This function may get called when the default database is not active, but
  2799. // there is no reason we'd ever want to not use the default database for
  2800. // this query.
  2801. $file = Database::getConnection('default', 'default')->query("SELECT filename FROM {registry} WHERE name = :name AND type = :type", array(
  2802. ':name' => $name,
  2803. ':type' => $type,
  2804. ))
  2805. ->fetchField();
  2806. // Flag that we've run a lookup query and need to update the cache.
  2807. $cache_update_needed = TRUE;
  2808. // Misses are valuable information worth caching, so cache even if
  2809. // $file is FALSE.
  2810. $lookup_cache[$cache_key] = $file;
  2811. if ($file) {
  2812. require_once DRUPAL_ROOT . '/' . $file;
  2813. return TRUE;
  2814. }
  2815. else {
  2816. return FALSE;
  2817. }
  2818. }
  2819. /**
  2820. * Rescans all enabled modules and rebuilds the registry.
  2821. *
  2822. * Rescans all code in modules or includes directories, storing the location of
  2823. * each interface or class in the database.
  2824. */
  2825. function registry_rebuild() {
  2826. system_rebuild_module_data();
  2827. registry_update();
  2828. }
  2829. /**
  2830. * Updates the registry based on the latest files listed in the database.
  2831. *
  2832. * This function should be used when system_rebuild_module_data() does not need
  2833. * to be called, because it is already known that the list of files in the
  2834. * {system} table matches those in the file system.
  2835. *
  2836. * @return
  2837. * TRUE if the registry was rebuilt, FALSE if another thread was rebuilding
  2838. * in parallel and the current thread just waited for completion.
  2839. *
  2840. * @see registry_rebuild()
  2841. */
  2842. function registry_update() {
  2843. // install_system_module() calls module_enable() which calls into this
  2844. // function during initial system installation, so the lock system is neither
  2845. // loaded nor does its storage exist yet.
  2846. $in_installer = drupal_installation_attempted();
  2847. if (!$in_installer && !lock_acquire(__FUNCTION__)) {
  2848. // Another request got the lock, wait for it to finish.
  2849. lock_wait(__FUNCTION__);
  2850. return FALSE;
  2851. }
  2852. require_once DRUPAL_ROOT . '/includes/registry.inc';
  2853. _registry_update();
  2854. if (!$in_installer) {
  2855. lock_release(__FUNCTION__);
  2856. }
  2857. return TRUE;
  2858. }
  2859. /**
  2860. * @} End of "addtogroup registry".
  2861. */
  2862. /**
  2863. * Provides central static variable storage.
  2864. *
  2865. * All functions requiring a static variable to persist or cache data within
  2866. * a single page request are encouraged to use this function unless it is
  2867. * absolutely certain that the static variable will not need to be reset during
  2868. * the page request. By centralizing static variable storage through this
  2869. * function, other functions can rely on a consistent API for resetting any
  2870. * other function's static variables.
  2871. *
  2872. * Example:
  2873. * @code
  2874. * function language_list($field = 'language') {
  2875. * $languages = &drupal_static(__FUNCTION__);
  2876. * if (!isset($languages)) {
  2877. * // If this function is being called for the first time after a reset,
  2878. * // query the database and execute any other code needed to retrieve
  2879. * // information about the supported languages.
  2880. * ...
  2881. * }
  2882. * if (!isset($languages[$field])) {
  2883. * // If this function is being called for the first time for a particular
  2884. * // index field, then execute code needed to index the information already
  2885. * // available in $languages by the desired field.
  2886. * ...
  2887. * }
  2888. * // Subsequent invocations of this function for a particular index field
  2889. * // skip the above two code blocks and quickly return the already indexed
  2890. * // information.
  2891. * return $languages[$field];
  2892. * }
  2893. * function locale_translate_overview_screen() {
  2894. * // When building the content for the translations overview page, make
  2895. * // sure to get completely fresh information about the supported languages.
  2896. * drupal_static_reset('language_list');
  2897. * ...
  2898. * }
  2899. * @endcode
  2900. *
  2901. * In a few cases, a function can have certainty that there is no legitimate
  2902. * use-case for resetting that function's static variable. This is rare,
  2903. * because when writing a function, it's hard to forecast all the situations in
  2904. * which it will be used. A guideline is that if a function's static variable
  2905. * does not depend on any information outside of the function that might change
  2906. * during a single page request, then it's ok to use the "static" keyword
  2907. * instead of the drupal_static() function.
  2908. *
  2909. * Example:
  2910. * @code
  2911. * function actions_do(...) {
  2912. * // $stack tracks the number of recursive calls.
  2913. * static $stack;
  2914. * $stack++;
  2915. * if ($stack > variable_get('actions_max_stack', 35)) {
  2916. * ...
  2917. * return;
  2918. * }
  2919. * ...
  2920. * $stack--;
  2921. * }
  2922. * @endcode
  2923. *
  2924. * In a few cases, a function needs a resettable static variable, but the
  2925. * function is called many times (100+) during a single page request, so
  2926. * every microsecond of execution time that can be removed from the function
  2927. * counts. These functions can use a more cumbersome, but faster variant of
  2928. * calling drupal_static(). It works by storing the reference returned by
  2929. * drupal_static() in the calling function's own static variable, thereby
  2930. * removing the need to call drupal_static() for each iteration of the function.
  2931. * Conceptually, it replaces:
  2932. * @code
  2933. * $foo = &drupal_static(__FUNCTION__);
  2934. * @endcode
  2935. * with:
  2936. * @code
  2937. * // Unfortunately, this does not work.
  2938. * static $foo = &drupal_static(__FUNCTION__);
  2939. * @endcode
  2940. * However, the above line of code does not work, because PHP only allows static
  2941. * variables to be initializied by literal values, and does not allow static
  2942. * variables to be assigned to references.
  2943. * - http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static
  2944. * - http://php.net/manual/en/language.variables.scope.php#language.variables.scope.references
  2945. * The example below shows the syntax needed to work around both limitations.
  2946. * For benchmarks and more information, see http://drupal.org/node/619666.
  2947. *
  2948. * Example:
  2949. * @code
  2950. * function user_access($string, $account = NULL) {
  2951. * // Use the advanced drupal_static() pattern, since this is called very often.
  2952. * static $drupal_static_fast;
  2953. * if (!isset($drupal_static_fast)) {
  2954. * $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
  2955. * }
  2956. * $perm = &$drupal_static_fast['perm'];
  2957. * ...
  2958. * }
  2959. * @endcode
  2960. *
  2961. * @param $name
  2962. * Globally unique name for the variable. For a function with only one static,
  2963. * variable, the function name (e.g. via the PHP magic __FUNCTION__ constant)
  2964. * is recommended. For a function with multiple static variables add a
  2965. * distinguishing suffix to the function name for each one.
  2966. * @param $default_value
  2967. * Optional default value.
  2968. * @param $reset
  2969. * TRUE to reset a specific named variable, or all variables if $name is NULL.
  2970. * Resetting every variable should only be used, for example, for running
  2971. * unit tests with a clean environment. Should be used only though via
  2972. * function drupal_static_reset() and the return value should not be used in
  2973. * this case.
  2974. *
  2975. * @return
  2976. * Returns a variable by reference.
  2977. *
  2978. * @see drupal_static_reset()
  2979. */
  2980. function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
  2981. static $data = array(), $default = array();
  2982. // First check if dealing with a previously defined static variable.
  2983. if (isset($data[$name]) || array_key_exists($name, $data)) {
  2984. // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
  2985. if ($reset) {
  2986. // Reset pre-existing static variable to its default value.
  2987. $data[$name] = $default[$name];
  2988. }
  2989. return $data[$name];
  2990. }
  2991. // Neither $data[$name] nor $default[$name] static variables exist.
  2992. if (isset($name)) {
  2993. if ($reset) {
  2994. // Reset was called before a default is set and yet a variable must be
  2995. // returned.
  2996. return $data;
  2997. }
  2998. // First call with new non-NULL $name. Initialize a new static variable.
  2999. $default[$name] = $data[$name] = $default_value;
  3000. return $data[$name];
  3001. }
  3002. // Reset all: ($name == NULL). This needs to be done one at a time so that
  3003. // references returned by earlier invocations of drupal_static() also get
  3004. // reset.
  3005. foreach ($default as $name => $value) {
  3006. $data[$name] = $value;
  3007. }
  3008. // As the function returns a reference, the return should always be a
  3009. // variable.
  3010. return $data;
  3011. }
  3012. /**
  3013. * Resets one or all centrally stored static variable(s).
  3014. *
  3015. * @param $name
  3016. * Name of the static variable to reset. Omit to reset all variables.
  3017. */
  3018. function drupal_static_reset($name = NULL) {
  3019. drupal_static($name, NULL, TRUE);
  3020. }
  3021. /**
  3022. * Detects whether the current script is running in a command-line environment.
  3023. */
  3024. function drupal_is_cli() {
  3025. return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
  3026. }
  3027. /**
  3028. * Formats text for emphasized display in a placeholder inside a sentence.
  3029. *
  3030. * Used automatically by format_string().
  3031. *
  3032. * @param $text
  3033. * The text to format (plain-text).
  3034. *
  3035. * @return
  3036. * The formatted text (html).
  3037. */
  3038. function drupal_placeholder($text) {
  3039. return '<em class="placeholder">' . check_plain($text) . '</em>';
  3040. }
  3041. /**
  3042. * Registers a function for execution on shutdown.
  3043. *
  3044. * Wrapper for register_shutdown_function() that catches thrown exceptions to
  3045. * avoid "Exception thrown without a stack frame in Unknown".
  3046. *
  3047. * @param $callback
  3048. * The shutdown function to register.
  3049. * @param ...
  3050. * Additional arguments to pass to the shutdown function.
  3051. *
  3052. * @return
  3053. * Array of shutdown functions to be executed.
  3054. *
  3055. * @see register_shutdown_function()
  3056. * @ingroup php_wrappers
  3057. */
  3058. function &drupal_register_shutdown_function($callback = NULL) {
  3059. // We cannot use drupal_static() here because the static cache is reset during
  3060. // batch processing, which breaks batch handling.
  3061. static $callbacks = array();
  3062. if (isset($callback)) {
  3063. // Only register the internal shutdown function once.
  3064. if (empty($callbacks)) {
  3065. register_shutdown_function('_drupal_shutdown_function');
  3066. }
  3067. $args = func_get_args();
  3068. array_shift($args);
  3069. // Save callback and arguments
  3070. $callbacks[] = array('callback' => $callback, 'arguments' => $args);
  3071. }
  3072. return $callbacks;
  3073. }
  3074. /**
  3075. * Executes registered shutdown functions.
  3076. */
  3077. function _drupal_shutdown_function() {
  3078. $callbacks = &drupal_register_shutdown_function();
  3079. // Set the CWD to DRUPAL_ROOT as it is not guaranteed to be the same as it
  3080. // was in the normal context of execution.
  3081. chdir(DRUPAL_ROOT);
  3082. try {
  3083. while (list($key, $callback) = each($callbacks)) {
  3084. call_user_func_array($callback['callback'], $callback['arguments']);
  3085. }
  3086. }
  3087. catch (Exception $exception) {
  3088. // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
  3089. require_once DRUPAL_ROOT . '/includes/errors.inc';
  3090. if (error_displayable()) {
  3091. print '<h1>Uncaught exception thrown in shutdown function.</h1>';
  3092. print '<p>' . _drupal_render_exception_safe($exception) . '</p><hr />';
  3093. }
  3094. }
  3095. }