A Drupal-CiviCRM setup
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3852 lines
132KB

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