Skip navigation
Help

bootstrap.inc

  1. drupal
    1. 6 drupal/includes/bootstrap.inc
    2. 7 drupal/includes/bootstrap.inc

Functions that need to be loaded on every Drupal request.

Functions & methods

NameDescription
argReturn a component of the current Drupal path.
bootstrap_hooksDefine the critical hooks that force modules to always be loaded.
bootstrap_invoke_allInvoke a bootstrap hook in all bootstrap modules that implement it.
check_plainEncode special characters in a plain-text string for display as HTML.
conf_pathFinds the appropriate configuration directory.
drupal_add_http_headerSet an HTTP response header for the current page.
drupal_anonymous_userGenerates a default anonymous $user object.
drupal_array_merge_deepMerges multiple arrays, recursively, and returns the merged array.
drupal_array_merge_deep_arrayMerges multiple arrays, recursively, and returns the merged array.
drupal_autoload_classConfirm that a class is available.
drupal_autoload_interfaceConfirm that an interface is available.
drupal_block_deniedHandle denied users.
drupal_bootstrapA string describing a phase of Drupal to load. Each phase adds to the previous one, so invoking a later phase automatically runs the earlier phases too. The most important usage is that if you want to access the Drupal database from a script without…
drupal_environment_initializeInitialize PHP environment.
drupal_generate_test_uaGenerate a user agent string with a HMAC and timestamp for simpletest.
drupal_get_bootstrap_phaseReturns the current bootstrap phase for this Drupal process.
drupal_get_filenameReturns and optionally sets the filename for a system item (module, theme, etc.). The filename, whether provided, cached, or retrieved from the database, is only returned if the file exists.
drupal_get_http_headerGet the HTTP response headers for the current page.
drupal_get_messagesReturn all messages that have been set.
drupal_get_schemaGet the schema definition of a table, or the whole database schema.
drupal_get_titleGet the title of the current page, for display on the page and in the title bar.
drupal_get_user_timezoneReturn the time zone of the current user.
drupal_hash_base64Calculate a base-64 encoded, URL-safe sha-256 hash.
drupal_hmac_base64Calculate a base-64 encoded, URL-safe sha-256 hmac.
drupal_installation_attemptedReturn TRUE if a Drupal installation is currently being attempted.
drupal_is_cliDetect whether the current script is running in a command-line environment.
drupal_is_deniedCheck to see if an IP address has been blocked.
drupal_language_initializeInitialize all the defined language types.
drupal_language_typesThe built-in language types.
drupal_loadIncludes a file with the provided type and name. This prevents including a theme, engine, module, etc., more than once.
drupal_maintenance_themeEnables use of the theme system without requiring database access.
drupal_multilingualReturn true if there is more than one language enabled.
drupal_override_server_variablesSet appropriate server variables needed for command line scripts to work.
drupal_page_get_cacheRetrieve the current page from the cache.
drupal_page_headerSet HTTP headers in preparation for a page response.
drupal_page_is_cacheableDetermine the cacheability of the current page.
drupal_placeholderFormats text for emphasized display in a placeholder inside a sentence. Used automatically by t().
drupal_random_bytesReturns a string of highly randomized bytes (over the full 8-bit range).
drupal_register_shutdown_functionRegister a function for execution on shutdown.
drupal_send_headersSend the HTTP response headers previously set using drupal_add_http_header(). Add default headers, unless they have been replaced or unset using drupal_add_http_header().
drupal_serve_page_from_cacheSet HTTP headers in preparation for a cached page response.
drupal_settings_initializeLoads the configuration and sets the base URL, cookie domain, and session name correctly.
drupal_set_messageSet a message which reflects the status of the performed operation.
drupal_set_titleSet the title of the current page, for display on the page and in the title bar.
drupal_staticCentral static variable storage.
drupal_static_resetReset one or all centrally stored static variable(s).
drupal_unpackUnserializes and appends elements from a serialized string.
drupal_validate_utf8Checks whether a string is valid UTF-8.
drupal_valid_http_hostValidate that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
drupal_valid_test_uaChecks the current User-Agent string to see if this is an internal request from SimpleTest. If so, returns the test prefix for this test.
get_tReturns the name of the proper localization function.
ip_addressIf Drupal is behind a reverse proxy, we use the X-Forwarded-For header instead of $_SERVER['REMOTE_ADDR'], which would be the IP address of the proxy server, and not the client's. The actual header name can be configured by the…
language_defaultDefault language used on the site
language_listGet a list of languages set up indexed by the specified key
language_typesReturn an array of the available language types.
registry_rebuildRescan all enabled modules and rebuild the registry.
registry_updateUpdate the registry based on the latest files listed in the database.
request_pathReturns the requested URL path of the page being viewed.
request_uriSince $_SERVER['REQUEST_URI'] is only available on Apache, we generate an equivalent using other environment variables.
tTranslates a string to the current language or to a given language.
timer_readRead the current timer value without stopping the timer.
timer_startStart the timer with the specified name. If you start and stop the same timer multiple times, the measured intervals will be accumulated.
timer_stopStop the timer with the specified name.
variable_delUnsets a persistent variable.
variable_getReturns a persistent variable.
variable_initializeLoad the persistent variable table.
variable_setSets a persistent variable.
watchdogLog a system message.
watchdog_exceptionLog an exception.
_drupal_bootstrap_configurationBootstrap configuration: Setup script environment and load settings.php.
_drupal_bootstrap_databaseBootstrap database: Initialize database system and register autoload functions.
_drupal_bootstrap_page_cacheBootstrap page cache: Try to serve a page from cache.
_drupal_bootstrap_page_headerBootstrap page header: Invoke hook_boot(), initialize locking system, and send default HTTP headers.
_drupal_bootstrap_variablesBootstrap variables: Load system variables and all enabled bootstrap modules.
_drupal_error_handlerCustom PHP error handler.
_drupal_exception_handlerCustom PHP exception handler.
_drupal_set_preferred_header_nameHeader names are case-insensitive, but for maximum compatibility they should follow "common form" (see RFC 2617, section 4.2).
_drupal_shutdown_functionInternal function used to execute registered shutdown functions.
_registry_check_codeHelper to check for a resource in the registry.

Constants

NameDescription
CACHE_PERMANENTIndicates that the item should never be removed unless explicitly selected.
CACHE_TEMPORARYIndicates that the item should be removed at the next general cache wipe.
CHECK_PLAINFlag for drupal_set_title(); text is not sanitized, so run check_plain().
DRUPAL_ANONYMOUS_RIDRole ID for anonymous users; should match what's in the "role" table.
DRUPAL_AUTHENTICATED_RIDRole ID for authenticated users; should match what's in the "role" table.
DRUPAL_BOOTSTRAP_CONFIGURATIONFirst bootstrap phase: initialize configuration.
DRUPAL_BOOTSTRAP_DATABASEThird bootstrap phase: initialize database layer.
DRUPAL_BOOTSTRAP_FULLFinal bootstrap phase: Drupal is fully loaded; validate and fix input data.
DRUPAL_BOOTSTRAP_LANGUAGESeventh bootstrap phase: find out language of the page.
DRUPAL_BOOTSTRAP_PAGE_CACHESecond bootstrap phase: try to serve a cached page.
DRUPAL_BOOTSTRAP_PAGE_HEADERSixth bootstrap phase: set up the page header.
DRUPAL_BOOTSTRAP_SESSIONFifth bootstrap phase: initialize session handling.
DRUPAL_BOOTSTRAP_VARIABLESFourth bootstrap phase: initialize the variable system.
DRUPAL_CORE_COMPATIBILITYCore API compatibility.
DRUPAL_KILOBYTEThe number of bytes in a kilobyte. For more information, visit http://en.wikipedia.org/wiki/Kilobyte.
DRUPAL_MINIMUM_PHPMinimum supported version of PHP.
DRUPAL_MINIMUM_PHP_MEMORY_LIMITMinimum recommended value of PHP memory_limit.
DRUPAL_PHP_FUNCTION_PATTERNRegular expression to match PHP function names.
LANGUAGE_LTRLanguage written left to right. Possible value of $language->direction.
LANGUAGE_NONEThe language code used when no language is explicitly assigned.
LANGUAGE_RTLLanguage written right to left. Possible value of $language->direction.
LANGUAGE_TYPE_CONTENTThe type of language used to define the content language.
LANGUAGE_TYPE_INTERFACEThe type of language used to select the user interface.
LANGUAGE_TYPE_URLThe type of language used for URLs.
PASS_THROUGHFlag for drupal_set_title(); text has already been sanitized.
REGISTRY_RESET_LOOKUP_CACHESignals that the registry lookup cache should be reset.
REGISTRY_WRITE_LOOKUP_CACHESignals that the registry lookup cache should be written to storage.
REQUEST_TIMEFor convenience, define a short form of the request time global.
VERSIONThe current system version.
WATCHDOG_ALERTLog message severity -- Alert: action must be taken immediately.
WATCHDOG_CRITICALLog message severity -- Critical: critical conditions.
WATCHDOG_DEBUGLog message severity -- Debug: debug-level messages.
WATCHDOG_EMERGENCYLog message severity -- Emergency: system is unusable.
WATCHDOG_ERRORLog message severity -- Error: error conditions.
WATCHDOG_INFOLog message severity -- Informational: informational messages.
WATCHDOG_NOTICELog message severity -- Notice: normal but significant condition.
WATCHDOG_WARNINGLog message severity -- Warning: warning conditions.

File

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