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

Functions that need to be loaded on every Drupal request.

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

Functions

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

Constants

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

Classes

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

Comments

Though drupal has a function to get user IP address but still it would not work for us.
So I have written a small function to get actual client IP from end user machine and can be used in DRUPAL 6 / 7.
How can I add it in the drupal bootstrap.inc file ?

Patched can be submitted to the Drupal Issue queue:

https://www.drupal.org/project/issues/drupal