bootstrap.inc

  1. drupal
    1. 4.6 includes/bootstrap.inc
    2. 4.7 includes/bootstrap.inc
    3. 5 includes/bootstrap.inc
    4. 6 includes/bootstrap.inc
    5. 7 includes/bootstrap.inc
    6. 8 core/includes/bootstrap.inc

Functions that need to be loaded on every Drupal request.

Functions & methods

NameDescription
argReturns a component of the current Drupal path.
bootstrap_hooksDefines the critical hooks that force modules to always be loaded.
bootstrap_invoke_allInvokes a bootstrap hook in all bootstrap modules that implement it.
check_plainEncodes special characters in a plain-text string for display as HTML.
conf_pathFinds the appropriate configuration directory.
drupal_add_http_headerSets 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_classConfirms that a class is available.
drupal_autoload_interfaceConfirms that an interface is available.
drupal_block_deniedHandles denied users.
drupal_bootstrapEnsures Drupal is bootstrapped to the specified phase.
drupal_environment_initializeInitializes the PHP environment.
drupal_fast_404Returns a simple 404 Not Found page.
drupal_generate_test_uaGenerates 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_complete_schemaGets the whole database schema.
drupal_get_filenameReturns and optionally sets the filename for a system resource.
drupal_get_http_headerGets the HTTP response headers for the current page.
drupal_get_messagesReturns all messages that have been set.
drupal_get_schemaGets the schema definition of a table, or the whole database schema.
drupal_get_titleGets the title of the current page.
drupal_get_user_timezoneReturns the time zone of the current user.
drupal_hash_base64Calculates a base-64 encoded, URL-safe sha-256 hash.
drupal_hmac_base64Calculates a base-64 encoded, URL-safe sha-256 hmac.
drupal_installation_attemptedReturns TRUE if a Drupal installation is currently being attempted.
drupal_is_cliDetects whether the current script is running in a command-line environment.
drupal_is_deniedChecks to see if an IP address has been blocked.
drupal_language_initializeInitializes all the defined language types.
drupal_language_typesReturns a list of the built-in language types.
drupal_loadIncludes a file with the provided type and name.
drupal_maintenance_themeEnables use of the theme system without requiring database access.
drupal_multilingualReturns TRUE if there is more than one language enabled.
drupal_override_server_variablesSets appropriate server variables needed for command line scripts to work.
drupal_page_get_cacheRetrieves the current page from the cache.
drupal_page_headerSets HTTP headers in preparation for a page response.
drupal_page_is_cacheableDetermines the cacheability of the current page.
drupal_placeholderFormats text for emphasized display in a placeholder inside a sentence.
drupal_random_bytesReturns a string of highly randomized bytes (over the full 8-bit range).
drupal_register_shutdown_functionRegisters a function for execution on shutdown.
drupal_send_headersSends the HTTP response headers that were previously set, adding defaults.
drupal_serve_page_from_cacheSets HTTP headers in preparation for a cached page response.
drupal_settings_initializeSets the base URL, cookie domain, and session name from configuration.
drupal_set_messageSets a message which reflects the status of the performed operation.
drupal_set_titleSets the title of the current page.
drupal_staticProvides central static variable storage.
drupal_static_resetResets 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_hostValidates that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
drupal_valid_test_uaReturns the test prefix if this is an internal request from SimpleTest.
format_stringReplaces placeholders with sanitized values in a string.
get_tReturns the name of the proper localization function.
ip_addressReturns the IP address of the client machine.
language_defaultReturns the default language used on the site
language_listReturns a list of installed languages, indexed by the specified key.
language_typesReturns an array of the available language types.
registry_rebuildRescans all enabled modules and rebuilds the registry.
registry_updateUpdates the registry based on the latest files listed in the database.
request_pathReturns the requested URL path of the page being viewed.
request_uriReturns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
tTranslates a string to the current language or to a given language.
timer_readReads the current timer value without stopping the timer.
timer_startStarts the timer with the specified name.
timer_stopStops the timer with the specified name.
variable_delUnsets a persistent variable.
variable_getReturns a persistent variable.
variable_initializeLoads the persistent variable table.
variable_setSets a persistent variable.
watchdogLogs a system message.
watchdog_exceptionLogs an exception.
_drupal_bootstrap_configurationSets up the script environment and loads settings.php.
_drupal_bootstrap_databaseInitializes the database system and registers autoload functions.
_drupal_bootstrap_page_cacheAttempts to serve a page from the cache.
_drupal_bootstrap_page_headerInvokes hook_boot(), initializes locking system, and sends HTTP headers.
_drupal_bootstrap_variablesLoads system variables and all enabled bootstrap modules.
_drupal_error_handlerProvides custom PHP error handling.
_drupal_exception_handlerProvides custom PHP exception handling.
_drupal_set_preferred_header_nameSets the preferred name for the HTTP header.
_drupal_shutdown_functionExecutes registered shutdown functions.
_registry_check_codeChecks 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.
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_TIMETime of the current request in seconds elapsed since the Unix Epoch.
VERSIONThe current system version.
WATCHDOG_ALERTLog message severity -- Alert: action must be taken immediately.
WATCHDOG_CRITICALLog message severity -- Critical conditions.
WATCHDOG_DEBUGLog message severity -- Debug-level messages.
WATCHDOG_EMERGENCYLog message severity -- Emergency: system is unusable.
WATCHDOG_ERRORLog message severity -- Error conditions.
WATCHDOG_INFOLog message severity -- Informational messages.
WATCHDOG_NOTICELog message severity -- Normal but significant conditions.
WATCHDOG_WARNINGLog message severity -- Warning conditions.

Classes

NameDescription
DrupalCacheArrayProvides a caching wrapper to be used in place of large array structures.
SchemaCacheExtends DrupalCacheArray to allow for dynamic building of the schema cache.

File

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