Projet

Général

Profil

Paste
Télécharger (119 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / bootstrap.inc @ bceb9b7a

1
<?php
2

    
3
/**
4
 * @file
5
 * Functions that need to be loaded on every Drupal request.
6
 */
7

    
8
/**
9
 * The current system version.
10
 */
11
define('VERSION', '7.35');
12

    
13
/**
14
 * Core API compatibility.
15
 */
16
define('DRUPAL_CORE_COMPATIBILITY', '7.x');
17

    
18
/**
19
 * Minimum supported version of PHP.
20
 */
21
define('DRUPAL_MINIMUM_PHP', '5.2.4');
22

    
23
/**
24
 * Minimum recommended value of PHP memory_limit.
25
 */
26
define('DRUPAL_MINIMUM_PHP_MEMORY_LIMIT', '32M');
27

    
28
/**
29
 * Error reporting level: display no errors.
30
 */
31
define('ERROR_REPORTING_HIDE', 0);
32

    
33
/**
34
 * Error reporting level: display errors and warnings.
35
 */
36
define('ERROR_REPORTING_DISPLAY_SOME', 1);
37

    
38
/**
39
 * Error reporting level: display all messages.
40
 */
41
define('ERROR_REPORTING_DISPLAY_ALL', 2);
42

    
43
/**
44
 * Indicates that the item should never be removed unless explicitly selected.
45
 *
46
 * The item may be removed using cache_clear_all() with a cache ID.
47
 */
48
define('CACHE_PERMANENT', 0);
49

    
50
/**
51
 * Indicates that the item should be removed at the next general cache wipe.
52
 */
53
define('CACHE_TEMPORARY', -1);
54

    
55
/**
56
 * @defgroup logging_severity_levels Logging severity levels
57
 * @{
58
 * Logging severity levels as defined in RFC 3164.
59
 *
60
 * The WATCHDOG_* constant definitions correspond to the logging severity levels
61
 * defined in RFC 3164, section 4.1.1. PHP supplies predefined LOG_* constants
62
 * for use in the syslog() function, but their values on Windows builds do not
63
 * correspond to RFC 3164. The associated PHP bug report was closed with the
64
 * comment, "And it's also not a bug, as Windows just have less log levels,"
65
 * and "So the behavior you're seeing is perfectly normal."
66
 *
67
 * @see http://www.faqs.org/rfcs/rfc3164.html
68
 * @see http://bugs.php.net/bug.php?id=18090
69
 * @see http://php.net/manual/function.syslog.php
70
 * @see http://php.net/manual/network.constants.php
71
 * @see watchdog()
72
 * @see watchdog_severity_levels()
73
 */
74

    
75
/**
76
 * Log message severity -- Emergency: system is unusable.
77
 */
78
define('WATCHDOG_EMERGENCY', 0);
79

    
80
/**
81
 * Log message severity -- Alert: action must be taken immediately.
82
 */
83
define('WATCHDOG_ALERT', 1);
84

    
85
/**
86
 * Log message severity -- Critical conditions.
87
 */
88
define('WATCHDOG_CRITICAL', 2);
89

    
90
/**
91
 * Log message severity -- Error conditions.
92
 */
93
define('WATCHDOG_ERROR', 3);
94

    
95
/**
96
 * Log message severity -- Warning conditions.
97
 */
98
define('WATCHDOG_WARNING', 4);
99

    
100
/**
101
 * Log message severity -- Normal but significant conditions.
102
 */
103
define('WATCHDOG_NOTICE', 5);
104

    
105
/**
106
 * Log message severity -- Informational messages.
107
 */
108
define('WATCHDOG_INFO', 6);
109

    
110
/**
111
 * Log message severity -- Debug-level messages.
112
 */
113
define('WATCHDOG_DEBUG', 7);
114

    
115
/**
116
 * @} End of "defgroup logging_severity_levels".
117
 */
118

    
119
/**
120
 * First bootstrap phase: initialize configuration.
121
 */
122
define('DRUPAL_BOOTSTRAP_CONFIGURATION', 0);
123

    
124
/**
125
 * Second bootstrap phase: try to serve a cached page.
126
 */
127
define('DRUPAL_BOOTSTRAP_PAGE_CACHE', 1);
128

    
129
/**
130
 * Third bootstrap phase: initialize database layer.
131
 */
132
define('DRUPAL_BOOTSTRAP_DATABASE', 2);
133

    
134
/**
135
 * Fourth bootstrap phase: initialize the variable system.
136
 */
137
define('DRUPAL_BOOTSTRAP_VARIABLES', 3);
138

    
139
/**
140
 * Fifth bootstrap phase: initialize session handling.
141
 */
142
define('DRUPAL_BOOTSTRAP_SESSION', 4);
143

    
144
/**
145
 * Sixth bootstrap phase: set up the page header.
146
 */
147
define('DRUPAL_BOOTSTRAP_PAGE_HEADER', 5);
148

    
149
/**
150
 * Seventh bootstrap phase: find out language of the page.
151
 */
152
define('DRUPAL_BOOTSTRAP_LANGUAGE', 6);
153

    
154
/**
155
 * Final bootstrap phase: Drupal is fully loaded; validate and fix input data.
156
 */
157
define('DRUPAL_BOOTSTRAP_FULL', 7);
158

    
159
/**
160
 * Role ID for anonymous users; should match what's in the "role" table.
161
 */
162
define('DRUPAL_ANONYMOUS_RID', 1);
163

    
164
/**
165
 * Role ID for authenticated users; should match what's in the "role" table.
166
 */
167
define('DRUPAL_AUTHENTICATED_RID', 2);
168

    
169
/**
170
 * The number of bytes in a kilobyte.
171
 *
172
 * For more information, visit http://en.wikipedia.org/wiki/Kilobyte.
173
 */
174
define('DRUPAL_KILOBYTE', 1024);
175

    
176
/**
177
 * The language code used when no language is explicitly assigned.
178
 *
179
 * Defined by ISO639-2 for "Undetermined".
180
 */
181
define('LANGUAGE_NONE', 'und');
182

    
183
/**
184
 * The type of language used to define the content language.
185
 */
186
define('LANGUAGE_TYPE_CONTENT', 'language_content');
187

    
188
/**
189
 * The type of language used to select the user interface.
190
 */
191
define('LANGUAGE_TYPE_INTERFACE', 'language');
192

    
193
/**
194
 * The type of language used for URLs.
195
 */
196
define('LANGUAGE_TYPE_URL', 'language_url');
197

    
198
/**
199
 * Language written left to right. Possible value of $language->direction.
200
 */
201
define('LANGUAGE_LTR', 0);
202

    
203
/**
204
 * Language written right to left. Possible value of $language->direction.
205
 */
206
define('LANGUAGE_RTL', 1);
207

    
208
/**
209
 * Time of the current request in seconds elapsed since the Unix Epoch.
210
 *
211
 * This differs from $_SERVER['REQUEST_TIME'], which is stored as a float
212
 * since PHP 5.4.0. Float timestamps confuse most PHP functions
213
 * (including date_create()).
214
 *
215
 * @see http://php.net/manual/reserved.variables.server.php
216
 * @see http://php.net/manual/function.time.php
217
 */
218
define('REQUEST_TIME', (int) $_SERVER['REQUEST_TIME']);
219

    
220
/**
221
 * Flag used to indicate that text is not sanitized, so run check_plain().
222
 *
223
 * @see drupal_set_title()
224
 */
225
define('CHECK_PLAIN', 0);
226

    
227
/**
228
 * Flag used to indicate that text has already been sanitized.
229
 *
230
 * @see drupal_set_title()
231
 */
232
define('PASS_THROUGH', -1);
233

    
234
/**
235
 * Signals that the registry lookup cache should be reset.
236
 */
237
define('REGISTRY_RESET_LOOKUP_CACHE', 1);
238

    
239
/**
240
 * Signals that the registry lookup cache should be written to storage.
241
 */
242
define('REGISTRY_WRITE_LOOKUP_CACHE', 2);
243

    
244
/**
245
 * Regular expression to match PHP function names.
246
 *
247
 * @see http://php.net/manual/language.functions.php
248
 */
249
define('DRUPAL_PHP_FUNCTION_PATTERN', '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*');
250

    
251
/**
252
 * A RFC7231 Compliant date.
253
 *
254
 * http://tools.ietf.org/html/rfc7231#section-7.1.1.1
255
 *
256
 * Example: Sun, 06 Nov 1994 08:49:37 GMT
257
 */
258
define('DATE_RFC7231', 'D, d M Y H:i:s \G\M\T');
259

    
260
/**
261
 * Provides a caching wrapper to be used in place of large array structures.
262
 *
263
 * This class should be extended by systems that need to cache large amounts
264
 * of data and have it represented as an array to calling functions. These
265
 * arrays can become very large, so ArrayAccess is used to allow different
266
 * strategies to be used for caching internally (lazy loading, building caches
267
 * over time etc.). This can dramatically reduce the amount of data that needs
268
 * to be loaded from cache backends on each request, and memory usage from
269
 * static caches of that same data.
270
 *
271
 * Note that array_* functions do not work with ArrayAccess. Systems using
272
 * DrupalCacheArray should use this only internally. If providing API functions
273
 * that return the full array, this can be cached separately or returned
274
 * directly. However since DrupalCacheArray holds partial content by design, it
275
 * should be a normal PHP array or otherwise contain the full structure.
276
 *
277
 * Note also that due to limitations in PHP prior to 5.3.4, it is impossible to
278
 * write directly to the contents of nested arrays contained in this object.
279
 * Only writes to the top-level array elements are possible. So if you
280
 * previously had set $object['foo'] = array(1, 2, 'bar' => 'baz'), but later
281
 * want to change the value of 'bar' from 'baz' to 'foobar', you cannot do so
282
 * a targeted write like $object['foo']['bar'] = 'foobar'. Instead, you must
283
 * overwrite the entire top-level 'foo' array with the entire set of new
284
 * values: $object['foo'] = array(1, 2, 'bar' => 'foobar'). Due to this same
285
 * limitation, attempts to create references to any contained data, nested or
286
 * otherwise, will fail silently. So $var = &$object['foo'] will not throw an
287
 * error, and $var will be populated with the contents of $object['foo'], but
288
 * that data will be passed by value, not reference. For more information on
289
 * the PHP limitation, see the note in the official PHP documentation at·
290
 * http://php.net/manual/arrayaccess.offsetget.php on
291
 * ArrayAccess::offsetGet().
292
 *
293
 * By default, the class accounts for caches where calling functions might
294
 * request keys in the array that won't exist even after a cache rebuild. This
295
 * prevents situations where a cache rebuild would be triggered over and over
296
 * due to a 'missing' item. These cases are stored internally as a value of
297
 * NULL. This means that the offsetGet() and offsetExists() methods
298
 * must be overridden if caching an array where the top level values can
299
 * legitimately be NULL, and where $object->offsetExists() needs to correctly
300
 * return (equivalent to array_key_exists() vs. isset()). This should not
301
 * be necessary in the majority of cases.
302
 *
303
 * Classes extending this class must override at least the
304
 * resolveCacheMiss() method to have a working implementation.
305
 *
306
 * offsetSet() is not overridden by this class by default. In practice this
307
 * means that assigning an offset via arrayAccess will only apply while the
308
 * object is in scope and will not be written back to the persistent cache.
309
 * This follows a similar pattern to static vs. persistent caching in
310
 * procedural code. Extending classes may wish to alter this behavior, for
311
 * example by overriding offsetSet() and adding an automatic call to persist().
312
 *
313
 * @see SchemaCache
314
 */
315
abstract class DrupalCacheArray implements ArrayAccess {
316

    
317
  /**
318
   * A cid to pass to cache_set() and cache_get().
319
   */
320
  protected $cid;
321

    
322
  /**
323
   * A bin to pass to cache_set() and cache_get().
324
   */
325
  protected $bin;
326

    
327
  /**
328
   * An array of keys to add to the cache at the end of the request.
329
   */
330
  protected $keysToPersist = array();
331

    
332
  /**
333
   * Storage for the data itself.
334
   */
335
  protected $storage = array();
336

    
337
  /**
338
   * Constructs a DrupalCacheArray object.
339
   *
340
   * @param $cid
341
   *   The cid for the array being cached.
342
   * @param $bin
343
   *   The bin to cache the array.
344
   */
345
  public function __construct($cid, $bin) {
346
    $this->cid = $cid;
347
    $this->bin = $bin;
348

    
349
    if ($cached = cache_get($this->cid, $this->bin)) {
350
     $this->storage = $cached->data;
351
    }
352
  }
353

    
354
  /**
355
   * Implements ArrayAccess::offsetExists().
356
   */
357
  public function offsetExists($offset) {
358
    return $this->offsetGet($offset) !== NULL;
359
  }
360

    
361
  /**
362
   * Implements ArrayAccess::offsetGet().
363
   */
364
  public function offsetGet($offset) {
365
    if (isset($this->storage[$offset]) || array_key_exists($offset, $this->storage)) {
366
      return $this->storage[$offset];
367
    }
368
    else {
369
      return $this->resolveCacheMiss($offset);
370
    }
371
  }
372

    
373
  /**
374
   * Implements ArrayAccess::offsetSet().
375
   */
376
  public function offsetSet($offset, $value) {
377
    $this->storage[$offset] = $value;
378
  }
379

    
380
  /**
381
   * Implements ArrayAccess::offsetUnset().
382
   */
383
  public function offsetUnset($offset) {
384
    unset($this->storage[$offset]);
385
  }
386

    
387
  /**
388
   * Flags an offset value to be written to the persistent cache.
389
   *
390
   * If a value is assigned to a cache object with offsetSet(), by default it
391
   * will not be written to the persistent cache unless it is flagged with this
392
   * method. This allows items to be cached for the duration of a request,
393
   * without necessarily writing back to the persistent cache at the end.
394
   *
395
   * @param $offset
396
   *   The array offset that was requested.
397
   * @param $persist
398
   *   Optional boolean to specify whether the offset should be persisted or
399
   *   not, defaults to TRUE. When called with $persist = FALSE the offset will
400
   *   be unflagged so that it will not be written at the end of the request.
401
   */
402
  protected function persist($offset, $persist = TRUE) {
403
    $this->keysToPersist[$offset] = $persist;
404
  }
405

    
406
  /**
407
   * Resolves a cache miss.
408
   *
409
   * When an offset is not found in the object, this is treated as a cache
410
   * miss. This method allows classes implementing the interface to look up
411
   * the actual value and allow it to be cached.
412
   *
413
   * @param $offset
414
   *   The offset that was requested.
415
   *
416
   * @return
417
   *   The value of the offset, or NULL if no value was found.
418
   */
419
  abstract protected function resolveCacheMiss($offset);
420

    
421
  /**
422
   * Writes a value to the persistent cache immediately.
423
   *
424
   * @param $data
425
   *   The data to write to the persistent cache.
426
   * @param $lock
427
   *   Whether to acquire a lock before writing to cache.
428
   */
429
  protected function set($data, $lock = TRUE) {
430
    // Lock cache writes to help avoid stampedes.
431
    // To implement locking for cache misses, override __construct().
432
    $lock_name = $this->cid . ':' . $this->bin;
433
    if (!$lock || lock_acquire($lock_name)) {
434
      if ($cached = cache_get($this->cid, $this->bin)) {
435
        $data = $cached->data + $data;
436
      }
437
      cache_set($this->cid, $data, $this->bin);
438
      if ($lock) {
439
        lock_release($lock_name);
440
      }
441
    }
442
  }
443

    
444
  /**
445
   * Destructs the DrupalCacheArray object.
446
   */
447
  public function __destruct() {
448
    $data = array();
449
    foreach ($this->keysToPersist as $offset => $persist) {
450
      if ($persist) {
451
        $data[$offset] = $this->storage[$offset];
452
      }
453
    }
454
    if (!empty($data)) {
455
      $this->set($data);
456
    }
457
  }
458
}
459

    
460
/**
461
 * Starts the timer with the specified name.
462
 *
463
 * If you start and stop the same timer multiple times, the measured intervals
464
 * will be accumulated.
465
 *
466
 * @param $name
467
 *   The name of the timer.
468
 */
469
function timer_start($name) {
470
  global $timers;
471

    
472
  $timers[$name]['start'] = microtime(TRUE);
473
  $timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
474
}
475

    
476
/**
477
 * Reads the current timer value without stopping the timer.
478
 *
479
 * @param $name
480
 *   The name of the timer.
481
 *
482
 * @return
483
 *   The current timer value in ms.
484
 */
485
function timer_read($name) {
486
  global $timers;
487

    
488
  if (isset($timers[$name]['start'])) {
489
    $stop = microtime(TRUE);
490
    $diff = round(($stop - $timers[$name]['start']) * 1000, 2);
491

    
492
    if (isset($timers[$name]['time'])) {
493
      $diff += $timers[$name]['time'];
494
    }
495
    return $diff;
496
  }
497
  return $timers[$name]['time'];
498
}
499

    
500
/**
501
 * Stops the timer with the specified name.
502
 *
503
 * @param $name
504
 *   The name of the timer.
505
 *
506
 * @return
507
 *   A timer array. The array contains the number of times the timer has been
508
 *   started and stopped (count) and the accumulated timer value in ms (time).
509
 */
510
function timer_stop($name) {
511
  global $timers;
512

    
513
  if (isset($timers[$name]['start'])) {
514
    $stop = microtime(TRUE);
515
    $diff = round(($stop - $timers[$name]['start']) * 1000, 2);
516
    if (isset($timers[$name]['time'])) {
517
      $timers[$name]['time'] += $diff;
518
    }
519
    else {
520
      $timers[$name]['time'] = $diff;
521
    }
522
    unset($timers[$name]['start']);
523
  }
524

    
525
  return $timers[$name];
526
}
527

    
528
/**
529
 * Returns the appropriate configuration directory.
530
 *
531
 * Returns the configuration path based on the site's hostname, port, and
532
 * pathname. Uses find_conf_path() to find the current configuration directory.
533
 * See default.settings.php for examples on how the URL is converted to a
534
 * directory.
535
 *
536
 * @param bool $require_settings
537
 *   Only configuration directories with an existing settings.php file
538
 *   will be recognized. Defaults to TRUE. During initial installation,
539
 *   this is set to FALSE so that Drupal can detect a matching directory,
540
 *   then create a new settings.php file in it.
541
 * @param bool $reset
542
 *   Force a full search for matching directories even if one had been
543
 *   found previously. Defaults to FALSE.
544
 *
545
 * @return
546
 *   The path of the matching directory.
547
 *
548
 * @see default.settings.php
549
 */
550
function conf_path($require_settings = TRUE, $reset = FALSE) {
551
  $conf = &drupal_static(__FUNCTION__, '');
552

    
553
  if ($conf && !$reset) {
554
    return $conf;
555
  }
556

    
557
  $confdir = 'sites';
558

    
559
  $sites = array();
560
  if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/sites.php')) {
561
    // This will overwrite $sites with the desired mappings.
562
    include(DRUPAL_ROOT . '/' . $confdir . '/sites.php');
563
  }
564

    
565
  $uri = explode('/', $_SERVER['SCRIPT_NAME'] ? $_SERVER['SCRIPT_NAME'] : $_SERVER['SCRIPT_FILENAME']);
566
  $server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
567
  for ($i = count($uri) - 1; $i > 0; $i--) {
568
    for ($j = count($server); $j > 0; $j--) {
569
      $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
570
      if (isset($sites[$dir]) && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $sites[$dir])) {
571
        $dir = $sites[$dir];
572
      }
573
      if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir . '/settings.php') || (!$require_settings && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir))) {
574
        $conf = "$confdir/$dir";
575
        return $conf;
576
      }
577
    }
578
  }
579
  $conf = "$confdir/default";
580
  return $conf;
581
}
582

    
583
/**
584
 * Sets appropriate server variables needed for command line scripts to work.
585
 *
586
 * This function can be called by command line scripts before bootstrapping
587
 * Drupal, to ensure that the page loads with the desired server parameters.
588
 * This is because many parts of Drupal assume that they are running in a web
589
 * browser and therefore use information from the global PHP $_SERVER variable
590
 * that does not get set when Drupal is run from the command line.
591
 *
592
 * In many cases, the default way in which this function populates the $_SERVER
593
 * variable is sufficient, and it can therefore be called without passing in
594
 * any input. However, command line scripts running on a multisite installation
595
 * (or on any installation that has settings.php stored somewhere other than
596
 * the sites/default folder) need to pass in the URL of the site to allow
597
 * Drupal to detect the correct location of the settings.php file. Passing in
598
 * the 'url' parameter is also required for functions like request_uri() to
599
 * return the expected values.
600
 *
601
 * Most other parameters do not need to be passed in, but may be necessary in
602
 * some cases; for example, if Drupal's ip_address() function needs to return
603
 * anything but the standard localhost value ('127.0.0.1'), the command line
604
 * script should pass in the desired value via the 'REMOTE_ADDR' key.
605
 *
606
 * @param $variables
607
 *   (optional) An associative array of variables within $_SERVER that should
608
 *   be replaced. If the special element 'url' is provided in this array, it
609
 *   will be used to populate some of the server defaults; it should be set to
610
 *   the URL of the current page request, excluding any $_GET request but
611
 *   including the script name (e.g., http://www.example.com/mysite/index.php).
612
 *
613
 * @see conf_path()
614
 * @see request_uri()
615
 * @see ip_address()
616
 */
617
function drupal_override_server_variables($variables = array()) {
618
  // Allow the provided URL to override any existing values in $_SERVER.
619
  if (isset($variables['url'])) {
620
    $url = parse_url($variables['url']);
621
    if (isset($url['host'])) {
622
      $_SERVER['HTTP_HOST'] = $url['host'];
623
    }
624
    if (isset($url['path'])) {
625
      $_SERVER['SCRIPT_NAME'] = $url['path'];
626
    }
627
    unset($variables['url']);
628
  }
629
  // Define default values for $_SERVER keys. These will be used if $_SERVER
630
  // does not already define them and no other values are passed in to this
631
  // function.
632
  $defaults = array(
633
    'HTTP_HOST' => 'localhost',
634
    'SCRIPT_NAME' => NULL,
635
    'REMOTE_ADDR' => '127.0.0.1',
636
    'REQUEST_METHOD' => 'GET',
637
    'SERVER_NAME' => NULL,
638
    'SERVER_SOFTWARE' => NULL,
639
    'HTTP_USER_AGENT' => NULL,
640
  );
641
  // Replace elements of the $_SERVER array, as appropriate.
642
  $_SERVER = $variables + $_SERVER + $defaults;
643
}
644

    
645
/**
646
 * Initializes the PHP environment.
647
 */
648
function drupal_environment_initialize() {
649
  if (!isset($_SERVER['HTTP_REFERER'])) {
650
    $_SERVER['HTTP_REFERER'] = '';
651
  }
652
  if (!isset($_SERVER['SERVER_PROTOCOL']) || ($_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.0' && $_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.1')) {
653
    $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
654
  }
655

    
656
  if (isset($_SERVER['HTTP_HOST'])) {
657
    // As HTTP_HOST is user input, ensure it only contains characters allowed
658
    // in hostnames. See RFC 952 (and RFC 2181).
659
    // $_SERVER['HTTP_HOST'] is lowercased here per specifications.
660
    $_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']);
661
    if (!drupal_valid_http_host($_SERVER['HTTP_HOST'])) {
662
      // HTTP_HOST is invalid, e.g. if containing slashes it may be an attack.
663
      header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
664
      exit;
665
    }
666
  }
667
  else {
668
    // Some pre-HTTP/1.1 clients will not send a Host header. Ensure the key is
669
    // defined for E_ALL compliance.
670
    $_SERVER['HTTP_HOST'] = '';
671
  }
672

    
673
  // When clean URLs are enabled, emulate ?q=foo/bar using REQUEST_URI. It is
674
  // not possible to append the query string using mod_rewrite without the B
675
  // flag (this was added in Apache 2.2.8), because mod_rewrite unescapes the
676
  // path before passing it on to PHP. This is a problem when the path contains
677
  // e.g. "&" or "%" that have special meanings in URLs and must be encoded.
678
  $_GET['q'] = request_path();
679

    
680
  // Enforce E_ALL, but allow users to set levels not part of E_ALL.
681
  error_reporting(E_ALL | error_reporting());
682

    
683
  // Override PHP settings required for Drupal to work properly.
684
  // sites/default/default.settings.php contains more runtime settings.
685
  // The .htaccess file contains settings that cannot be changed at runtime.
686

    
687
  // Don't escape quotes when reading files from the database, disk, etc.
688
  ini_set('magic_quotes_runtime', '0');
689
  // Use session cookies, not transparent sessions that puts the session id in
690
  // the query string.
691
  ini_set('session.use_cookies', '1');
692
  ini_set('session.use_only_cookies', '1');
693
  ini_set('session.use_trans_sid', '0');
694
  // Don't send HTTP headers using PHP's session handler.
695
  // An empty string is used here to disable the cache limiter.
696
  ini_set('session.cache_limiter', '');
697
  // Use httponly session cookies.
698
  ini_set('session.cookie_httponly', '1');
699

    
700
  // Set sane locale settings, to ensure consistent string, dates, times and
701
  // numbers handling.
702
  setlocale(LC_ALL, 'C');
703
}
704

    
705
/**
706
 * Validates that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
707
 *
708
 * @return
709
 *  TRUE if only containing valid characters, or FALSE otherwise.
710
 */
711
function drupal_valid_http_host($host) {
712
  // Limit the length of the host name to 1000 bytes to prevent DoS attacks with
713
  // long host names.
714
  return strlen($host) <= 1000
715
    // Limit the number of subdomains and port separators to prevent DoS attacks
716
    // in conf_path().
717
    && substr_count($host, '.') <= 100
718
    && substr_count($host, ':') <= 100
719
    && preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host);
720
}
721

    
722
/**
723
 * Sets the base URL, cookie domain, and session name from configuration.
724
 */
725
function drupal_settings_initialize() {
726
  global $base_url, $base_path, $base_root;
727

    
728
  // Export these settings.php variables to the global namespace.
729
  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;
730
  $conf = array();
731

    
732
  if (file_exists(DRUPAL_ROOT . '/' . conf_path() . '/settings.php')) {
733
    include_once DRUPAL_ROOT . '/' . conf_path() . '/settings.php';
734
  }
735
  $is_https = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
736

    
737
  if (isset($base_url)) {
738
    // Parse fixed base URL from settings.php.
739
    $parts = parse_url($base_url);
740
    if (!isset($parts['path'])) {
741
      $parts['path'] = '';
742
    }
743
    $base_path = $parts['path'] . '/';
744
    // Build $base_root (everything until first slash after "scheme://").
745
    $base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
746
  }
747
  else {
748
    // Create base URL.
749
    $http_protocol = $is_https ? 'https' : 'http';
750
    $base_root = $http_protocol . '://' . $_SERVER['HTTP_HOST'];
751

    
752
    $base_url = $base_root;
753

    
754
    // $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
755
    // be modified by a visitor.
756
    if ($dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/')) {
757
      $base_path = $dir;
758
      $base_url .= $base_path;
759
      $base_path .= '/';
760
    }
761
    else {
762
      $base_path = '/';
763
    }
764
  }
765
  $base_secure_url = str_replace('http://', 'https://', $base_url);
766
  $base_insecure_url = str_replace('https://', 'http://', $base_url);
767

    
768
  if ($cookie_domain) {
769
    // If the user specifies the cookie domain, also use it for session name.
770
    $session_name = $cookie_domain;
771
  }
772
  else {
773
    // Otherwise use $base_url as session name, without the protocol
774
    // to use the same session identifiers across HTTP and HTTPS.
775
    list( , $session_name) = explode('://', $base_url, 2);
776
    // HTTP_HOST can be modified by a visitor, but we already sanitized it
777
    // in drupal_settings_initialize().
778
    if (!empty($_SERVER['HTTP_HOST'])) {
779
      $cookie_domain = $_SERVER['HTTP_HOST'];
780
      // Strip leading periods, www., and port numbers from cookie domain.
781
      $cookie_domain = ltrim($cookie_domain, '.');
782
      if (strpos($cookie_domain, 'www.') === 0) {
783
        $cookie_domain = substr($cookie_domain, 4);
784
      }
785
      $cookie_domain = explode(':', $cookie_domain);
786
      $cookie_domain = '.' . $cookie_domain[0];
787
    }
788
  }
789
  // Per RFC 2109, cookie domains must contain at least one dot other than the
790
  // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
791
  if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
792
    ini_set('session.cookie_domain', $cookie_domain);
793
  }
794
  // To prevent session cookies from being hijacked, a user can configure the
795
  // SSL version of their website to only transfer session cookies via SSL by
796
  // using PHP's session.cookie_secure setting. The browser will then use two
797
  // separate session cookies for the HTTPS and HTTP versions of the site. So we
798
  // must use different session identifiers for HTTPS and HTTP to prevent a
799
  // cookie collision.
800
  if ($is_https) {
801
    ini_set('session.cookie_secure', TRUE);
802
  }
803
  $prefix = ini_get('session.cookie_secure') ? 'SSESS' : 'SESS';
804
  session_name($prefix . substr(hash('sha256', $session_name), 0, 32));
805
}
806

    
807
/**
808
 * Returns and optionally sets the filename for a system resource.
809
 *
810
 * The filename, whether provided, cached, or retrieved from the database, is
811
 * only returned if the file exists.
812
 *
813
 * This function plays a key role in allowing Drupal's resources (modules
814
 * and themes) to be located in different places depending on a site's
815
 * configuration. For example, a module 'foo' may legally be located
816
 * in any of these three places:
817
 *
818
 * modules/foo/foo.module
819
 * sites/all/modules/foo/foo.module
820
 * sites/example.com/modules/foo/foo.module
821
 *
822
 * Calling drupal_get_filename('module', 'foo') will give you one of
823
 * the above, depending on where the module is located.
824
 *
825
 * @param $type
826
 *   The type of the item (theme, theme_engine, module, profile).
827
 * @param $name
828
 *   The name of the item for which the filename is requested.
829
 * @param $filename
830
 *   The filename of the item if it is to be set explicitly rather
831
 *   than by consulting the database.
832
 *
833
 * @return
834
 *   The filename of the requested item or NULL if the item is not found.
835
 */
836
function drupal_get_filename($type, $name, $filename = NULL) {
837
  // The location of files will not change during the request, so do not use
838
  // drupal_static().
839
  static $files = array(), $dirs = array();
840

    
841
  // Profiles are a special case: they have a fixed location and naming.
842
  if ($type == 'profile') {
843
    $profile_filename = "profiles/$name/$name.profile";
844
    $files[$type][$name] = file_exists($profile_filename) ? $profile_filename : FALSE;
845
  }
846
  if (!isset($files[$type])) {
847
    $files[$type] = array();
848
  }
849

    
850
  if (!empty($filename) && file_exists($filename)) {
851
    $files[$type][$name] = $filename;
852
  }
853
  elseif (isset($files[$type][$name])) {
854
    // nothing
855
  }
856
  // Verify that we have an active database connection, before querying
857
  // the database. This is required because this function is called both
858
  // before we have a database connection (i.e. during installation) and
859
  // when a database connection fails.
860
  else {
861
    try {
862
      if (function_exists('db_query')) {
863
        $file = db_query("SELECT filename FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
864
        if ($file !== FALSE && file_exists(DRUPAL_ROOT . '/' . $file)) {
865
          $files[$type][$name] = $file;
866
        }
867
      }
868
    }
869
    catch (Exception $e) {
870
      // The database table may not exist because Drupal is not yet installed,
871
      // or the database might be down. We have a fallback for this case so we
872
      // hide the error completely.
873
    }
874
    // Fallback to searching the filesystem if the database could not find the
875
    // file or the file returned by the database is not found.
876
    if (!isset($files[$type][$name])) {
877
      // We have a consistent directory naming: modules, themes...
878
      $dir = $type . 's';
879
      if ($type == 'theme_engine') {
880
        $dir = 'themes/engines';
881
        $extension = 'engine';
882
      }
883
      elseif ($type == 'theme') {
884
        $extension = 'info';
885
      }
886
      else {
887
        $extension = $type;
888
      }
889

    
890
      if (!isset($dirs[$dir][$extension])) {
891
        $dirs[$dir][$extension] = TRUE;
892
        if (!function_exists('drupal_system_listing')) {
893
          require_once DRUPAL_ROOT . '/includes/common.inc';
894
        }
895
        // Scan the appropriate directories for all files with the requested
896
        // extension, not just the file we are currently looking for. This
897
        // prevents unnecessary scans from being repeated when this function is
898
        // called more than once in the same page request.
899
        $matches = drupal_system_listing("/^" . DRUPAL_PHP_FUNCTION_PATTERN . "\.$extension$/", $dir, 'name', 0);
900
        foreach ($matches as $matched_name => $file) {
901
          $files[$type][$matched_name] = $file->uri;
902
        }
903
      }
904
    }
905
  }
906

    
907
  if (isset($files[$type][$name])) {
908
    return $files[$type][$name];
909
  }
910
}
911

    
912
/**
913
 * Loads the persistent variable table.
914
 *
915
 * The variable table is composed of values that have been saved in the table
916
 * with variable_set() as well as those explicitly specified in the
917
 * configuration file.
918
 */
919
function variable_initialize($conf = array()) {
920
  // NOTE: caching the variables improves performance by 20% when serving
921
  // cached pages.
922
  if ($cached = cache_get('variables', 'cache_bootstrap')) {
923
    $variables = $cached->data;
924
  }
925
  else {
926
    // Cache miss. Avoid a stampede.
927
    $name = 'variable_init';
928
    if (!lock_acquire($name, 1)) {
929
      // Another request is building the variable cache.
930
      // Wait, then re-run this function.
931
      lock_wait($name);
932
      return variable_initialize($conf);
933
    }
934
    else {
935
      // Proceed with variable rebuild.
936
      $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
937
      cache_set('variables', $variables, 'cache_bootstrap');
938
      lock_release($name);
939
    }
940
  }
941

    
942
  foreach ($conf as $name => $value) {
943
    $variables[$name] = $value;
944
  }
945

    
946
  return $variables;
947
}
948

    
949
/**
950
 * Returns a persistent variable.
951
 *
952
 * Case-sensitivity of the variable_* functions depends on the database
953
 * collation used. To avoid problems, always use lower case for persistent
954
 * variable names.
955
 *
956
 * @param $name
957
 *   The name of the variable to return.
958
 * @param $default
959
 *   The default value to use if this variable has never been set.
960
 *
961
 * @return
962
 *   The value of the variable. Unserialization is taken care of as necessary.
963
 *
964
 * @see variable_del()
965
 * @see variable_set()
966
 */
967
function variable_get($name, $default = NULL) {
968
  global $conf;
969

    
970
  return isset($conf[$name]) ? $conf[$name] : $default;
971
}
972

    
973
/**
974
 * Sets a persistent variable.
975
 *
976
 * Case-sensitivity of the variable_* functions depends on the database
977
 * collation used. To avoid problems, always use lower case for persistent
978
 * variable names.
979
 *
980
 * @param $name
981
 *   The name of the variable to set.
982
 * @param $value
983
 *   The value to set. This can be any PHP data type; these functions take care
984
 *   of serialization as necessary.
985
 *
986
 * @see variable_del()
987
 * @see variable_get()
988
 */
989
function variable_set($name, $value) {
990
  global $conf;
991

    
992
  db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();
993

    
994
  cache_clear_all('variables', 'cache_bootstrap');
995

    
996
  $conf[$name] = $value;
997
}
998

    
999
/**
1000
 * Unsets a persistent variable.
1001
 *
1002
 * Case-sensitivity of the variable_* functions depends on the database
1003
 * collation used. To avoid problems, always use lower case for persistent
1004
 * variable names.
1005
 *
1006
 * @param $name
1007
 *   The name of the variable to undefine.
1008
 *
1009
 * @see variable_get()
1010
 * @see variable_set()
1011
 */
1012
function variable_del($name) {
1013
  global $conf;
1014

    
1015
  db_delete('variable')
1016
    ->condition('name', $name)
1017
    ->execute();
1018
  cache_clear_all('variables', 'cache_bootstrap');
1019

    
1020
  unset($conf[$name]);
1021
}
1022

    
1023
/**
1024
 * Retrieves the current page from the cache.
1025
 *
1026
 * Note: we do not serve cached pages to authenticated users, or to anonymous
1027
 * users when $_SESSION is non-empty. $_SESSION may contain status messages
1028
 * from a form submission, the contents of a shopping cart, or other user-
1029
 * specific content that should not be cached and displayed to other users.
1030
 *
1031
 * @param $check_only
1032
 *   (optional) Set to TRUE to only return whether a previous call found a
1033
 *   cache entry.
1034
 *
1035
 * @return
1036
 *   The cache object, if the page was found in the cache, NULL otherwise.
1037
 */
1038
function drupal_page_get_cache($check_only = FALSE) {
1039
  global $base_root;
1040
  static $cache_hit = FALSE;
1041

    
1042
  if ($check_only) {
1043
    return $cache_hit;
1044
  }
1045

    
1046
  if (drupal_page_is_cacheable()) {
1047
    $cache = cache_get($base_root . request_uri(), 'cache_page');
1048
    if ($cache !== FALSE) {
1049
      $cache_hit = TRUE;
1050
    }
1051
    return $cache;
1052
  }
1053
}
1054

    
1055
/**
1056
 * Determines the cacheability of the current page.
1057
 *
1058
 * @param $allow_caching
1059
 *   Set to FALSE if you want to prevent this page to get cached.
1060
 *
1061
 * @return
1062
 *   TRUE if the current page can be cached, FALSE otherwise.
1063
 */
1064
function drupal_page_is_cacheable($allow_caching = NULL) {
1065
  $allow_caching_static = &drupal_static(__FUNCTION__, TRUE);
1066
  if (isset($allow_caching)) {
1067
    $allow_caching_static = $allow_caching;
1068
  }
1069

    
1070
  return $allow_caching_static && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')
1071
    && !drupal_is_cli();
1072
}
1073

    
1074
/**
1075
 * Invokes a bootstrap hook in all bootstrap modules that implement it.
1076
 *
1077
 * @param $hook
1078
 *   The name of the bootstrap hook to invoke.
1079
 *
1080
 * @see bootstrap_hooks()
1081
 */
1082
function bootstrap_invoke_all($hook) {
1083
  // Bootstrap modules should have been loaded when this function is called, so
1084
  // we don't need to tell module_list() to reset its internal list (and we
1085
  // therefore leave the first parameter at its default value of FALSE). We
1086
  // still pass in TRUE for the second parameter, though; in case this is the
1087
  // first time during the bootstrap that module_list() is called, we want to
1088
  // make sure that its internal cache is primed with the bootstrap modules
1089
  // only.
1090
  foreach (module_list(FALSE, TRUE) as $module) {
1091
    drupal_load('module', $module);
1092
    module_invoke($module, $hook);
1093
  }
1094
}
1095

    
1096
/**
1097
 * Includes a file with the provided type and name.
1098
 *
1099
 * This prevents including a theme, engine, module, etc., more than once.
1100
 *
1101
 * @param $type
1102
 *   The type of item to load (i.e. theme, theme_engine, module).
1103
 * @param $name
1104
 *   The name of the item to load.
1105
 *
1106
 * @return
1107
 *   TRUE if the item is loaded or has already been loaded.
1108
 */
1109
function drupal_load($type, $name) {
1110
  // Once a file is included this can't be reversed during a request so do not
1111
  // use drupal_static() here.
1112
  static $files = array();
1113

    
1114
  if (isset($files[$type][$name])) {
1115
    return TRUE;
1116
  }
1117

    
1118
  $filename = drupal_get_filename($type, $name);
1119

    
1120
  if ($filename) {
1121
    include_once DRUPAL_ROOT . '/' . $filename;
1122
    $files[$type][$name] = TRUE;
1123

    
1124
    return TRUE;
1125
  }
1126

    
1127
  return FALSE;
1128
}
1129

    
1130
/**
1131
 * Sets an HTTP response header for the current page.
1132
 *
1133
 * Note: When sending a Content-Type header, always include a 'charset' type,
1134
 * too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
1135
 *
1136
 * @param $name
1137
 *   The HTTP header name, or the special 'Status' header name.
1138
 * @param $value
1139
 *   The HTTP header value; if equal to FALSE, the specified header is unset.
1140
 *   If $name is 'Status', this is expected to be a status code followed by a
1141
 *   reason phrase, e.g. "404 Not Found".
1142
 * @param $append
1143
 *   Whether to append the value to an existing header or to replace it.
1144
 */
1145
function drupal_add_http_header($name, $value, $append = FALSE) {
1146
  // The headers as name/value pairs.
1147
  $headers = &drupal_static('drupal_http_headers', array());
1148

    
1149
  $name_lower = strtolower($name);
1150
  _drupal_set_preferred_header_name($name);
1151

    
1152
  if ($value === FALSE) {
1153
    $headers[$name_lower] = FALSE;
1154
  }
1155
  elseif (isset($headers[$name_lower]) && $append) {
1156
    // Multiple headers with identical names may be combined using comma (RFC
1157
    // 2616, section 4.2).
1158
    $headers[$name_lower] .= ',' . $value;
1159
  }
1160
  else {
1161
    $headers[$name_lower] = $value;
1162
  }
1163
  drupal_send_headers(array($name => $headers[$name_lower]), TRUE);
1164
}
1165

    
1166
/**
1167
 * Gets the HTTP response headers for the current page.
1168
 *
1169
 * @param $name
1170
 *   An HTTP header name. If omitted, all headers are returned as name/value
1171
 *   pairs. If an array value is FALSE, the header has been unset.
1172
 *
1173
 * @return
1174
 *   A string containing the header value, or FALSE if the header has been set,
1175
 *   or NULL if the header has not been set.
1176
 */
1177
function drupal_get_http_header($name = NULL) {
1178
  $headers = &drupal_static('drupal_http_headers', array());
1179
  if (isset($name)) {
1180
    $name = strtolower($name);
1181
    return isset($headers[$name]) ? $headers[$name] : NULL;
1182
  }
1183
  else {
1184
    return $headers;
1185
  }
1186
}
1187

    
1188
/**
1189
 * Sets the preferred name for the HTTP header.
1190
 *
1191
 * Header names are case-insensitive, but for maximum compatibility they should
1192
 * follow "common form" (see RFC 2617, section 4.2).
1193
 */
1194
function _drupal_set_preferred_header_name($name = NULL) {
1195
  static $header_names = array();
1196

    
1197
  if (!isset($name)) {
1198
    return $header_names;
1199
  }
1200
  $header_names[strtolower($name)] = $name;
1201
}
1202

    
1203
/**
1204
 * Sends the HTTP response headers that were previously set, adding defaults.
1205
 *
1206
 * Headers are set in drupal_add_http_header(). Default headers are not set
1207
 * if they have been replaced or unset using drupal_add_http_header().
1208
 *
1209
 * @param array $default_headers
1210
 *   (optional) An array of headers as name/value pairs.
1211
 * @param bool $only_default
1212
 *   (optional) If TRUE and headers have already been sent, send only the
1213
 *   specified headers.
1214
 */
1215
function drupal_send_headers($default_headers = array(), $only_default = FALSE) {
1216
  $headers_sent = &drupal_static(__FUNCTION__, FALSE);
1217
  $headers = drupal_get_http_header();
1218
  if ($only_default && $headers_sent) {
1219
    $headers = array();
1220
  }
1221
  $headers_sent = TRUE;
1222

    
1223
  $header_names = _drupal_set_preferred_header_name();
1224
  foreach ($default_headers as $name => $value) {
1225
    $name_lower = strtolower($name);
1226
    if (!isset($headers[$name_lower])) {
1227
      $headers[$name_lower] = $value;
1228
      $header_names[$name_lower] = $name;
1229
    }
1230
  }
1231
  foreach ($headers as $name_lower => $value) {
1232
    if ($name_lower == 'status') {
1233
      header($_SERVER['SERVER_PROTOCOL'] . ' ' . $value);
1234
    }
1235
    // Skip headers that have been unset.
1236
    elseif ($value !== FALSE) {
1237
      header($header_names[$name_lower] . ': ' . $value);
1238
    }
1239
  }
1240
}
1241

    
1242
/**
1243
 * Sets HTTP headers in preparation for a page response.
1244
 *
1245
 * Authenticated users are always given a 'no-cache' header, and will fetch a
1246
 * fresh page on every request. This prevents authenticated users from seeing
1247
 * locally cached pages.
1248
 *
1249
 * Also give each page a unique ETag. This will force clients to include both
1250
 * an If-Modified-Since header and an If-None-Match header when doing
1251
 * conditional requests for the page (required by RFC 2616, section 13.3.4),
1252
 * making the validation more robust. This is a workaround for a bug in Mozilla
1253
 * Firefox that is triggered when Drupal's caching is enabled and the user
1254
 * accesses Drupal via an HTTP proxy (see
1255
 * https://bugzilla.mozilla.org/show_bug.cgi?id=269303): When an authenticated
1256
 * user requests a page, and then logs out and requests the same page again,
1257
 * Firefox may send a conditional request based on the page that was cached
1258
 * locally when the user was logged in. If this page did not have an ETag
1259
 * header, the request only contains an If-Modified-Since header. The date will
1260
 * be recent, because with authenticated users the Last-Modified header always
1261
 * refers to the time of the request. If the user accesses Drupal via a proxy
1262
 * server, and the proxy already has a cached copy of the anonymous page with an
1263
 * older Last-Modified date, the proxy may respond with 304 Not Modified, making
1264
 * the client think that the anonymous and authenticated pageviews are
1265
 * identical.
1266
 *
1267
 * @see drupal_page_set_cache()
1268
 */
1269
function drupal_page_header() {
1270
  $headers_sent = &drupal_static(__FUNCTION__, FALSE);
1271
  if ($headers_sent) {
1272
    return TRUE;
1273
  }
1274
  $headers_sent = TRUE;
1275

    
1276
  $default_headers = array(
1277
    'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
1278
    'Last-Modified' => gmdate(DATE_RFC7231, REQUEST_TIME),
1279
    'Cache-Control' => 'no-cache, must-revalidate, post-check=0, pre-check=0',
1280
    'ETag' => '"' . REQUEST_TIME . '"',
1281
  );
1282
  drupal_send_headers($default_headers);
1283
}
1284

    
1285
/**
1286
 * Sets HTTP headers in preparation for a cached page response.
1287
 *
1288
 * The headers allow as much as possible in proxies and browsers without any
1289
 * particular knowledge about the pages. Modules can override these headers
1290
 * using drupal_add_http_header().
1291
 *
1292
 * If the request is conditional (using If-Modified-Since and If-None-Match),
1293
 * and the conditions match those currently in the cache, a 304 Not Modified
1294
 * response is sent.
1295
 */
1296
function drupal_serve_page_from_cache(stdClass $cache) {
1297
  // Negotiate whether to use compression.
1298
  $page_compression = !empty($cache->data['page_compressed']);
1299
  $return_compressed = $page_compression && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE;
1300

    
1301
  // Get headers set in hook_boot(). Keys are lower-case.
1302
  $hook_boot_headers = drupal_get_http_header();
1303

    
1304
  // Headers generated in this function, that may be replaced or unset using
1305
  // drupal_add_http_headers(). Keys are mixed-case.
1306
  $default_headers = array();
1307

    
1308
  foreach ($cache->data['headers'] as $name => $value) {
1309
    // In the case of a 304 response, certain headers must be sent, and the
1310
    // remaining may not (see RFC 2616, section 10.3.5). Do not override
1311
    // headers set in hook_boot().
1312
    $name_lower = strtolower($name);
1313
    if (in_array($name_lower, array('content-location', 'expires', 'cache-control', 'vary')) && !isset($hook_boot_headers[$name_lower])) {
1314
      drupal_add_http_header($name, $value);
1315
      unset($cache->data['headers'][$name]);
1316
    }
1317
  }
1318

    
1319
  // If the client sent a session cookie, a cached copy will only be served
1320
  // to that one particular client due to Vary: Cookie. Thus, do not set
1321
  // max-age > 0, allowing the page to be cached by external proxies, when a
1322
  // session cookie is present unless the Vary header has been replaced or
1323
  // unset in hook_boot().
1324
  $max_age = !isset($_COOKIE[session_name()]) || isset($hook_boot_headers['vary']) ? variable_get('page_cache_maximum_age', 0) : 0;
1325
  $default_headers['Cache-Control'] = 'public, max-age=' . $max_age;
1326

    
1327
  // Entity tag should change if the output changes.
1328
  $etag = '"' . $cache->created . '-' . intval($return_compressed) . '"';
1329
  header('Etag: ' . $etag);
1330

    
1331
  // See if the client has provided the required HTTP headers.
1332
  $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : FALSE;
1333
  $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : FALSE;
1334

    
1335
  if ($if_modified_since && $if_none_match
1336
      && $if_none_match == $etag // etag must match
1337
      && $if_modified_since == $cache->created) {  // if-modified-since must match
1338
    header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
1339
    drupal_send_headers($default_headers);
1340
    return;
1341
  }
1342

    
1343
  // Send the remaining headers.
1344
  foreach ($cache->data['headers'] as $name => $value) {
1345
    drupal_add_http_header($name, $value);
1346
  }
1347

    
1348
  $default_headers['Last-Modified'] = gmdate(DATE_RFC7231, $cache->created);
1349

    
1350
  // HTTP/1.0 proxies does not support the Vary header, so prevent any caching
1351
  // by sending an Expires date in the past. HTTP/1.1 clients ignores the
1352
  // Expires header if a Cache-Control: max-age= directive is specified (see RFC
1353
  // 2616, section 14.9.3).
1354
  $default_headers['Expires'] = 'Sun, 19 Nov 1978 05:00:00 GMT';
1355

    
1356
  drupal_send_headers($default_headers);
1357

    
1358
  // Allow HTTP proxies to cache pages for anonymous users without a session
1359
  // cookie. The Vary header is used to indicates the set of request-header
1360
  // fields that fully determines whether a cache is permitted to use the
1361
  // response to reply to a subsequent request for a given URL without
1362
  // revalidation. If a Vary header has been set in hook_boot(), it is assumed
1363
  // that the module knows how to cache the page.
1364
  if (!isset($hook_boot_headers['vary']) && !variable_get('omit_vary_cookie')) {
1365
    header('Vary: Cookie');
1366
  }
1367

    
1368
  if ($page_compression) {
1369
    header('Vary: Accept-Encoding', FALSE);
1370
    // If page_compression is enabled, the cache contains gzipped data.
1371
    if ($return_compressed) {
1372
      // $cache->data['body'] is already gzip'ed, so make sure
1373
      // zlib.output_compression does not compress it once more.
1374
      ini_set('zlib.output_compression', '0');
1375
      header('Content-Encoding: gzip');
1376
    }
1377
    else {
1378
      // The client does not support compression, so unzip the data in the
1379
      // cache. Strip the gzip header and run uncompress.
1380
      $cache->data['body'] = gzinflate(substr(substr($cache->data['body'], 10), 0, -8));
1381
    }
1382
  }
1383

    
1384
  // Print the page.
1385
  print $cache->data['body'];
1386
}
1387

    
1388
/**
1389
 * Defines the critical hooks that force modules to always be loaded.
1390
 */
1391
function bootstrap_hooks() {
1392
  return array('boot', 'exit', 'watchdog', 'language_init');
1393
}
1394

    
1395
/**
1396
 * Unserializes and appends elements from a serialized string.
1397
 *
1398
 * @param $obj
1399
 *   The object to which the elements are appended.
1400
 * @param $field
1401
 *   The attribute of $obj whose value should be unserialized.
1402
 */
1403
function drupal_unpack($obj, $field = 'data') {
1404
  if ($obj->$field && $data = unserialize($obj->$field)) {
1405
    foreach ($data as $key => $value) {
1406
      if (!empty($key) && !isset($obj->$key)) {
1407
        $obj->$key = $value;
1408
      }
1409
    }
1410
  }
1411
  return $obj;
1412
}
1413

    
1414
/**
1415
 * Translates a string to the current language or to a given language.
1416
 *
1417
 * The t() function serves two purposes. First, at run-time it translates
1418
 * user-visible text into the appropriate language. Second, various mechanisms
1419
 * that figure out what text needs to be translated work off t() -- the text
1420
 * inside t() calls is added to the database of strings to be translated.
1421
 * These strings are expected to be in English, so the first argument should
1422
 * always be in English. To enable a fully-translatable site, it is important
1423
 * that all human-readable text that will be displayed on the site or sent to
1424
 * a user is passed through the t() function, or a related function. See the
1425
 * @link http://drupal.org/node/322729 Localization API @endlink pages for
1426
 * more information, including recommendations on how to break up or not
1427
 * break up strings for translation.
1428
 *
1429
 * @section sec_translating_vars Translating Variables
1430
 * You should never use t() to translate variables, such as calling
1431
 * @code t($text); @endcode, unless the text that the variable holds has been
1432
 * passed through t() elsewhere (e.g., $text is one of several translated
1433
 * literal strings in an array). It is especially important never to call
1434
 * @code t($user_text); @endcode, where $user_text is some text that a user
1435
 * entered - doing that can lead to cross-site scripting and other security
1436
 * problems. However, you can use variable substitution in your string, to put
1437
 * variable text such as user names or link URLs into translated text. Variable
1438
 * substitution looks like this:
1439
 * @code
1440
 * $text = t("@name's blog", array('@name' => format_username($account)));
1441
 * @endcode
1442
 * Basically, you can put variables like @name into your string, and t() will
1443
 * substitute their sanitized values at translation time. (See the
1444
 * Localization API pages referenced above and the documentation of
1445
 * format_string() for details about how to define variables in your string.)
1446
 * Translators can then rearrange the string as necessary for the language
1447
 * (e.g., in Spanish, it might be "blog de @name").
1448
 *
1449
 * @section sec_alt_funcs_install Use During Installation Phase
1450
 * During the Drupal installation phase, some resources used by t() wil not be
1451
 * available to code that needs localization. See st() and get_t() for
1452
 * alternatives.
1453
 *
1454
 * @param $string
1455
 *   A string containing the English string to translate.
1456
 * @param $args
1457
 *   An associative array of replacements to make after translation. Based
1458
 *   on the first character of the key, the value is escaped and/or themed.
1459
 *   See format_string() for details.
1460
 * @param $options
1461
 *   An associative array of additional options, with the following elements:
1462
 *   - 'langcode' (defaults to the current language): The language code to
1463
 *     translate to a language other than what is used to display the page.
1464
 *   - 'context' (defaults to the empty context): The context the source string
1465
 *     belongs to.
1466
 *
1467
 * @return
1468
 *   The translated string.
1469
 *
1470
 * @see st()
1471
 * @see get_t()
1472
 * @see format_string()
1473
 * @ingroup sanitization
1474
 */
1475
function t($string, array $args = array(), array $options = array()) {
1476
  global $language;
1477
  static $custom_strings;
1478

    
1479
  // Merge in default.
1480
  if (empty($options['langcode'])) {
1481
    $options['langcode'] = isset($language->language) ? $language->language : 'en';
1482
  }
1483
  if (empty($options['context'])) {
1484
    $options['context'] = '';
1485
  }
1486

    
1487
  // First, check for an array of customized strings. If present, use the array
1488
  // *instead of* database lookups. This is a high performance way to provide a
1489
  // handful of string replacements. See settings.php for examples.
1490
  // Cache the $custom_strings variable to improve performance.
1491
  if (!isset($custom_strings[$options['langcode']])) {
1492
    $custom_strings[$options['langcode']] = variable_get('locale_custom_strings_' . $options['langcode'], array());
1493
  }
1494
  // Custom strings work for English too, even if locale module is disabled.
1495
  if (isset($custom_strings[$options['langcode']][$options['context']][$string])) {
1496
    $string = $custom_strings[$options['langcode']][$options['context']][$string];
1497
  }
1498
  // Translate with locale module if enabled.
1499
  elseif ($options['langcode'] != 'en' && function_exists('locale')) {
1500
    $string = locale($string, $options['context'], $options['langcode']);
1501
  }
1502
  if (empty($args)) {
1503
    return $string;
1504
  }
1505
  else {
1506
    return format_string($string, $args);
1507
  }
1508
}
1509

    
1510
/**
1511
 * Formats a string for HTML display by replacing variable placeholders.
1512
 *
1513
 * This function replaces variable placeholders in a string with the requested
1514
 * values and escapes the values so they can be safely displayed as HTML. It
1515
 * should be used on any unknown text that is intended to be printed to an HTML
1516
 * page (especially text that may have come from untrusted users, since in that
1517
 * case it prevents cross-site scripting and other security problems).
1518
 *
1519
 * In most cases, you should use t() rather than calling this function
1520
 * directly, since it will translate the text (on non-English-only sites) in
1521
 * addition to formatting it.
1522
 *
1523
 * @param $string
1524
 *   A string containing placeholders.
1525
 * @param $args
1526
 *   An associative array of replacements to make. Occurrences in $string of
1527
 *   any key in $args are replaced with the corresponding value, after optional
1528
 *   sanitization and formatting. The type of sanitization and formatting
1529
 *   depends on the first character of the key:
1530
 *   - @variable: Escaped to HTML using check_plain(). Use this as the default
1531
 *     choice for anything displayed on a page on the site.
1532
 *   - %variable: Escaped to HTML and formatted using drupal_placeholder(),
1533
 *     which makes it display as <em>emphasized</em> text.
1534
 *   - !variable: Inserted as is, with no sanitization or formatting. Only use
1535
 *     this for text that has already been prepared for HTML display (for
1536
 *     example, user-supplied text that has already been run through
1537
 *     check_plain() previously, or is expected to contain some limited HTML
1538
 *     tags and has already been run through filter_xss() previously).
1539
 *
1540
 * @see t()
1541
 * @ingroup sanitization
1542
 */
1543
function format_string($string, array $args = array()) {
1544
  // Transform arguments before inserting them.
1545
  foreach ($args as $key => $value) {
1546
    switch ($key[0]) {
1547
      case '@':
1548
        // Escaped only.
1549
        $args[$key] = check_plain($value);
1550
        break;
1551

    
1552
      case '%':
1553
      default:
1554
        // Escaped and placeholder.
1555
        $args[$key] = drupal_placeholder($value);
1556
        break;
1557

    
1558
      case '!':
1559
        // Pass-through.
1560
    }
1561
  }
1562
  return strtr($string, $args);
1563
}
1564

    
1565
/**
1566
 * Encodes special characters in a plain-text string for display as HTML.
1567
 *
1568
 * Also validates strings as UTF-8 to prevent cross site scripting attacks on
1569
 * Internet Explorer 6.
1570
 *
1571
 * @param string $text
1572
 *   The text to be checked or processed.
1573
 *
1574
 * @return string
1575
 *   An HTML safe version of $text. If $text is not valid UTF-8, an empty string
1576
 *   is returned and, on PHP < 5.4, a warning may be issued depending on server
1577
 *   configuration (see @link https://bugs.php.net/bug.php?id=47494 @endlink).
1578
 *
1579
 * @see drupal_validate_utf8()
1580
 * @ingroup sanitization
1581
 */
1582
function check_plain($text) {
1583
  return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
1584
}
1585

    
1586
/**
1587
 * Checks whether a string is valid UTF-8.
1588
 *
1589
 * All functions designed to filter input should use drupal_validate_utf8
1590
 * to ensure they operate on valid UTF-8 strings to prevent bypass of the
1591
 * filter.
1592
 *
1593
 * When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
1594
 * as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
1595
 * bytes. When these subsequent bytes are HTML control characters such as
1596
 * quotes or angle brackets, parts of the text that were deemed safe by filters
1597
 * end up in locations that are potentially unsafe; An onerror attribute that
1598
 * is outside of a tag, and thus deemed safe by a filter, can be interpreted
1599
 * by the browser as if it were inside the tag.
1600
 *
1601
 * The function does not return FALSE for strings containing character codes
1602
 * above U+10FFFF, even though these are prohibited by RFC 3629.
1603
 *
1604
 * @param $text
1605
 *   The text to check.
1606
 *
1607
 * @return
1608
 *   TRUE if the text is valid UTF-8, FALSE if not.
1609
 */
1610
function drupal_validate_utf8($text) {
1611
  if (strlen($text) == 0) {
1612
    return TRUE;
1613
  }
1614
  // With the PCRE_UTF8 modifier 'u', preg_match() fails silently on strings
1615
  // containing invalid UTF-8 byte sequences. It does not reject character
1616
  // codes above U+10FFFF (represented by 4 or more octets), though.
1617
  return (preg_match('/^./us', $text) == 1);
1618
}
1619

    
1620
/**
1621
 * Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
1622
 *
1623
 * Because $_SERVER['REQUEST_URI'] is only available on Apache, we generate an
1624
 * equivalent using other environment variables.
1625
 */
1626
function request_uri() {
1627
  if (isset($_SERVER['REQUEST_URI'])) {
1628
    $uri = $_SERVER['REQUEST_URI'];
1629
  }
1630
  else {
1631
    if (isset($_SERVER['argv'])) {
1632
      $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
1633
    }
1634
    elseif (isset($_SERVER['QUERY_STRING'])) {
1635
      $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
1636
    }
1637
    else {
1638
      $uri = $_SERVER['SCRIPT_NAME'];
1639
    }
1640
  }
1641
  // Prevent multiple slashes to avoid cross site requests via the Form API.
1642
  $uri = '/' . ltrim($uri, '/');
1643

    
1644
  return $uri;
1645
}
1646

    
1647
/**
1648
 * Logs an exception.
1649
 *
1650
 * This is a wrapper function for watchdog() which automatically decodes an
1651
 * exception.
1652
 *
1653
 * @param $type
1654
 *   The category to which this message belongs.
1655
 * @param $exception
1656
 *   The exception that is going to be logged.
1657
 * @param $message
1658
 *   The message to store in the log. If empty, a text that contains all useful
1659
 *   information about the passed-in exception is used.
1660
 * @param $variables
1661
 *   Array of variables to replace in the message on display. Defaults to the
1662
 *   return value of drupal_decode_exception().
1663
 * @param $severity
1664
 *   The severity of the message, as per RFC 3164.
1665
 * @param $link
1666
 *   A link to associate with the message.
1667
 *
1668
 * @see watchdog()
1669
 * @see drupal_decode_exception()
1670
 */
1671
function watchdog_exception($type, Exception $exception, $message = NULL, $variables = array(), $severity = WATCHDOG_ERROR, $link = NULL) {
1672

    
1673
   // Use a default value if $message is not set.
1674
   if (empty($message)) {
1675
     // The exception message is run through check_plain() by _drupal_decode_exception().
1676
     $message = '%type: !message in %function (line %line of %file).';
1677
   }
1678
   // $variables must be an array so that we can add the exception information.
1679
   if (!is_array($variables)) {
1680
     $variables = array();
1681
   }
1682

    
1683
   require_once DRUPAL_ROOT . '/includes/errors.inc';
1684
   $variables += _drupal_decode_exception($exception);
1685
   watchdog($type, $message, $variables, $severity, $link);
1686
}
1687

    
1688
/**
1689
 * Logs a system message.
1690
 *
1691
 * @param $type
1692
 *   The category to which this message belongs. Can be any string, but the
1693
 *   general practice is to use the name of the module calling watchdog().
1694
 * @param $message
1695
 *   The message to store in the log. Keep $message translatable
1696
 *   by not concatenating dynamic values into it! Variables in the
1697
 *   message should be added by using placeholder strings alongside
1698
 *   the variables argument to declare the value of the placeholders.
1699
 *   See t() for documentation on how $message and $variables interact.
1700
 * @param $variables
1701
 *   Array of variables to replace in the message on display or
1702
 *   NULL if message is already translated or not possible to
1703
 *   translate.
1704
 * @param $severity
1705
 *   The severity of the message; one of the following values as defined in
1706
 *   @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
1707
 *   - WATCHDOG_EMERGENCY: Emergency, system is unusable.
1708
 *   - WATCHDOG_ALERT: Alert, action must be taken immediately.
1709
 *   - WATCHDOG_CRITICAL: Critical conditions.
1710
 *   - WATCHDOG_ERROR: Error conditions.
1711
 *   - WATCHDOG_WARNING: Warning conditions.
1712
 *   - WATCHDOG_NOTICE: (default) Normal but significant conditions.
1713
 *   - WATCHDOG_INFO: Informational messages.
1714
 *   - WATCHDOG_DEBUG: Debug-level messages.
1715
 * @param $link
1716
 *   A link to associate with the message.
1717
 *
1718
 * @see watchdog_severity_levels()
1719
 * @see hook_watchdog()
1720
 */
1721
function watchdog($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL) {
1722
  global $user, $base_root;
1723

    
1724
  static $in_error_state = FALSE;
1725

    
1726
  // It is possible that the error handling will itself trigger an error. In that case, we could
1727
  // end up in an infinite loop. To avoid that, we implement a simple static semaphore.
1728
  if (!$in_error_state && function_exists('module_implements')) {
1729
    $in_error_state = TRUE;
1730

    
1731
    // The user object may not exist in all conditions, so 0 is substituted if needed.
1732
    $user_uid = isset($user->uid) ? $user->uid : 0;
1733

    
1734
    // Prepare the fields to be logged
1735
    $log_entry = array(
1736
      'type'        => $type,
1737
      'message'     => $message,
1738
      'variables'   => $variables,
1739
      'severity'    => $severity,
1740
      'link'        => $link,
1741
      'user'        => $user,
1742
      'uid'         => $user_uid,
1743
      'request_uri' => $base_root . request_uri(),
1744
      'referer'     => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
1745
      'ip'          => ip_address(),
1746
      // Request time isn't accurate for long processes, use time() instead.
1747
      'timestamp'   => time(),
1748
    );
1749

    
1750
    // Call the logging hooks to log/process the message
1751
    foreach (module_implements('watchdog') as $module) {
1752
      module_invoke($module, 'watchdog', $log_entry);
1753
    }
1754

    
1755
    // It is critical that the semaphore is only cleared here, in the parent
1756
    // watchdog() call (not outside the loop), to prevent recursive execution.
1757
    $in_error_state = FALSE;
1758
  }
1759
}
1760

    
1761
/**
1762
 * Sets a message to display to the user.
1763
 *
1764
 * Messages are stored in a session variable and displayed in page.tpl.php via
1765
 * the $messages theme variable.
1766
 *
1767
 * Example usage:
1768
 * @code
1769
 * drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
1770
 * @endcode
1771
 *
1772
 * @param string $message
1773
 *   (optional) The translated message to be displayed to the user. For
1774
 *   consistency with other messages, it should begin with a capital letter and
1775
 *   end with a period.
1776
 * @param string $type
1777
 *   (optional) The message's type. Defaults to 'status'. These values are
1778
 *   supported:
1779
 *   - 'status'
1780
 *   - 'warning'
1781
 *   - 'error'
1782
 * @param bool $repeat
1783
 *   (optional) If this is FALSE and the message is already set, then the
1784
 *   message won't be repeated. Defaults to TRUE.
1785
 *
1786
 * @return array|null
1787
 *   A multidimensional array with keys corresponding to the set message types.
1788
 *   The indexed array values of each contain the set messages for that type.
1789
 *   Or, if there are no messages set, the function returns NULL.
1790
 *
1791
 * @see drupal_get_messages()
1792
 * @see theme_status_messages()
1793
 */
1794
function drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE) {
1795
  if ($message) {
1796
    if (!isset($_SESSION['messages'][$type])) {
1797
      $_SESSION['messages'][$type] = array();
1798
    }
1799

    
1800
    if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
1801
      $_SESSION['messages'][$type][] = $message;
1802
    }
1803

    
1804
    // Mark this page as being uncacheable.
1805
    drupal_page_is_cacheable(FALSE);
1806
  }
1807

    
1808
  // Messages not set when DB connection fails.
1809
  return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
1810
}
1811

    
1812
/**
1813
 * Returns all messages that have been set with drupal_set_message().
1814
 *
1815
 * @param string $type
1816
 *   (optional) Limit the messages returned by type. Defaults to NULL, meaning
1817
 *   all types. These values are supported:
1818
 *   - NULL
1819
 *   - 'status'
1820
 *   - 'warning'
1821
 *   - 'error'
1822
 * @param bool $clear_queue
1823
 *   (optional) If this is TRUE, the queue will be cleared of messages of the
1824
 *   type specified in the $type parameter. Otherwise the queue will be left
1825
 *   intact. Defaults to TRUE.
1826
 *
1827
 * @return array
1828
 *   A multidimensional array with keys corresponding to the set message types.
1829
 *   The indexed array values of each contain the set messages for that type.
1830
 *   The messages returned are limited to the type specified in the $type
1831
 *   parameter. If there are no messages of the specified type, an empty array
1832
 *   is returned.
1833
 *
1834
 * @see drupal_set_message()
1835
 * @see theme_status_messages()
1836
 */
1837
function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
1838
  if ($messages = drupal_set_message()) {
1839
    if ($type) {
1840
      if ($clear_queue) {
1841
        unset($_SESSION['messages'][$type]);
1842
      }
1843
      if (isset($messages[$type])) {
1844
        return array($type => $messages[$type]);
1845
      }
1846
    }
1847
    else {
1848
      if ($clear_queue) {
1849
        unset($_SESSION['messages']);
1850
      }
1851
      return $messages;
1852
    }
1853
  }
1854
  return array();
1855
}
1856

    
1857
/**
1858
 * Gets the title of the current page.
1859
 *
1860
 * The title is displayed on the page and in the title bar.
1861
 *
1862
 * @return
1863
 *   The current page's title.
1864
 */
1865
function drupal_get_title() {
1866
  $title = drupal_set_title();
1867

    
1868
  // During a bootstrap, menu.inc is not included and thus we cannot provide a title.
1869
  if (!isset($title) && function_exists('menu_get_active_title')) {
1870
    $title = check_plain(menu_get_active_title());
1871
  }
1872

    
1873
  return $title;
1874
}
1875

    
1876
/**
1877
 * Sets the title of the current page.
1878
 *
1879
 * The title is displayed on the page and in the title bar.
1880
 *
1881
 * @param $title
1882
 *   Optional string value to assign to the page title; or if set to NULL
1883
 *   (default), leaves the current title unchanged.
1884
 * @param $output
1885
 *   Optional flag - normally should be left as CHECK_PLAIN. Only set to
1886
 *   PASS_THROUGH if you have already removed any possibly dangerous code
1887
 *   from $title using a function like check_plain() or filter_xss(). With this
1888
 *   flag the string will be passed through unchanged.
1889
 *
1890
 * @return
1891
 *   The updated title of the current page.
1892
 */
1893
function drupal_set_title($title = NULL, $output = CHECK_PLAIN) {
1894
  $stored_title = &drupal_static(__FUNCTION__);
1895

    
1896
  if (isset($title)) {
1897
    $stored_title = ($output == PASS_THROUGH) ? $title : check_plain($title);
1898
  }
1899

    
1900
  return $stored_title;
1901
}
1902

    
1903
/**
1904
 * Checks to see if an IP address has been blocked.
1905
 *
1906
 * Blocked IP addresses are stored in the database by default. However for
1907
 * performance reasons we allow an override in settings.php. This allows us
1908
 * to avoid querying the database at this critical stage of the bootstrap if
1909
 * an administrative interface for IP address blocking is not required.
1910
 *
1911
 * @param $ip
1912
 *   IP address to check.
1913
 *
1914
 * @return bool
1915
 *   TRUE if access is denied, FALSE if access is allowed.
1916
 */
1917
function drupal_is_denied($ip) {
1918
  // Because this function is called on every page request, we first check
1919
  // for an array of IP addresses in settings.php before querying the
1920
  // database.
1921
  $blocked_ips = variable_get('blocked_ips');
1922
  $denied = FALSE;
1923
  if (isset($blocked_ips) && is_array($blocked_ips)) {
1924
    $denied = in_array($ip, $blocked_ips);
1925
  }
1926
  // Only check if database.inc is loaded already. If
1927
  // $conf['page_cache_without_database'] = TRUE; is set in settings.php,
1928
  // then the database won't be loaded here so the IPs in the database
1929
  // won't be denied. However the user asked explicitly not to use the
1930
  // database and also in this case it's quite likely that the user relies
1931
  // on higher performance solutions like a firewall.
1932
  elseif (class_exists('Database', FALSE)) {
1933
    $denied = (bool)db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();
1934
  }
1935
  return $denied;
1936
}
1937

    
1938
/**
1939
 * Handles denied users.
1940
 *
1941
 * @param $ip
1942
 *   IP address to check. Prints a message and exits if access is denied.
1943
 */
1944
function drupal_block_denied($ip) {
1945
  // Deny access to blocked IP addresses - t() is not yet available.
1946
  if (drupal_is_denied($ip)) {
1947
    header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
1948
    print 'Sorry, ' . check_plain(ip_address()) . ' has been banned.';
1949
    exit();
1950
  }
1951
}
1952

    
1953
/**
1954
 * Returns a URL-safe, base64 encoded string of highly randomized bytes (over the full 8-bit range).
1955
 *
1956
 * @param $byte_count
1957
 *   The number of random bytes to fetch and base64 encode.
1958
 *
1959
 * @return string
1960
 *   The base64 encoded result will have a length of up to 4 * $byte_count.
1961
 */
1962
function drupal_random_key($byte_count = 32) {
1963
  return drupal_base64_encode(drupal_random_bytes($byte_count));
1964
}
1965

    
1966
/**
1967
 * Returns a URL-safe, base64 encoded version of the supplied string.
1968
 *
1969
 * @param $string
1970
 *   The string to convert to base64.
1971
 *
1972
 * @return string
1973
 */
1974
function drupal_base64_encode($string) {
1975
  $data = base64_encode($string);
1976
  // Modify the output so it's safe to use in URLs.
1977
  return strtr($data, array('+' => '-', '/' => '_', '=' => ''));
1978
}
1979

    
1980
/**
1981
 * Returns a string of highly randomized bytes (over the full 8-bit range).
1982
 *
1983
 * This function is better than simply calling mt_rand() or any other built-in
1984
 * PHP function because it can return a long string of bytes (compared to < 4
1985
 * bytes normally from mt_rand()) and uses the best available pseudo-random
1986
 * source.
1987
 *
1988
 * @param $count
1989
 *   The number of characters (bytes) to return in the string.
1990
 */
1991
function drupal_random_bytes($count)  {
1992
  // $random_state does not use drupal_static as it stores random bytes.
1993
  static $random_state, $bytes, $has_openssl;
1994

    
1995
  $missing_bytes = $count - strlen($bytes);
1996

    
1997
  if ($missing_bytes > 0) {
1998
    // PHP versions prior 5.3.4 experienced openssl_random_pseudo_bytes()
1999
    // locking on Windows and rendered it unusable.
2000
    if (!isset($has_openssl)) {
2001
      $has_openssl = version_compare(PHP_VERSION, '5.3.4', '>=') && function_exists('openssl_random_pseudo_bytes');
2002
    }
2003

    
2004
    // openssl_random_pseudo_bytes() will find entropy in a system-dependent
2005
    // way.
2006
    if ($has_openssl) {
2007
      $bytes .= openssl_random_pseudo_bytes($missing_bytes);
2008
    }
2009

    
2010
    // Else, read directly from /dev/urandom, which is available on many *nix
2011
    // systems and is considered cryptographically secure.
2012
    elseif ($fh = @fopen('/dev/urandom', 'rb')) {
2013
      // PHP only performs buffered reads, so in reality it will always read
2014
      // at least 4096 bytes. Thus, it costs nothing extra to read and store
2015
      // that much so as to speed any additional invocations.
2016
      $bytes .= fread($fh, max(4096, $missing_bytes));
2017
      fclose($fh);
2018
    }
2019

    
2020
    // If we couldn't get enough entropy, this simple hash-based PRNG will
2021
    // generate a good set of pseudo-random bytes on any system.
2022
    // Note that it may be important that our $random_state is passed
2023
    // through hash() prior to being rolled into $output, that the two hash()
2024
    // invocations are different, and that the extra input into the first one -
2025
    // the microtime() - is prepended rather than appended. This is to avoid
2026
    // directly leaking $random_state via the $output stream, which could
2027
    // allow for trivial prediction of further "random" numbers.
2028
    if (strlen($bytes) < $count) {
2029
      // Initialize on the first call. The contents of $_SERVER includes a mix of
2030
      // user-specific and system information that varies a little with each page.
2031
      if (!isset($random_state)) {
2032
        $random_state = print_r($_SERVER, TRUE);
2033
        if (function_exists('getmypid')) {
2034
          // Further initialize with the somewhat random PHP process ID.
2035
          $random_state .= getmypid();
2036
        }
2037
        $bytes = '';
2038
      }
2039

    
2040
      do {
2041
        $random_state = hash('sha256', microtime() . mt_rand() . $random_state);
2042
        $bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
2043
      }
2044
      while (strlen($bytes) < $count);
2045
    }
2046
  }
2047
  $output = substr($bytes, 0, $count);
2048
  $bytes = substr($bytes, $count);
2049
  return $output;
2050
}
2051

    
2052
/**
2053
 * Calculates a base-64 encoded, URL-safe sha-256 hmac.
2054
 *
2055
 * @param string $data
2056
 *   String to be validated with the hmac.
2057
 * @param string $key
2058
 *   A secret string key.
2059
 *
2060
 * @return string
2061
 *   A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and
2062
 *   any = padding characters removed.
2063
 */
2064
function drupal_hmac_base64($data, $key) {
2065
  // Casting $data and $key to strings here is necessary to avoid empty string
2066
  // results of the hash function if they are not scalar values. As this
2067
  // function is used in security-critical contexts like token validation it is
2068
  // important that it never returns an empty string.
2069
  $hmac = base64_encode(hash_hmac('sha256', (string) $data, (string) $key, TRUE));
2070
  // Modify the hmac so it's safe to use in URLs.
2071
  return strtr($hmac, array('+' => '-', '/' => '_', '=' => ''));
2072
}
2073

    
2074
/**
2075
 * Calculates a base-64 encoded, URL-safe sha-256 hash.
2076
 *
2077
 * @param $data
2078
 *   String to be hashed.
2079
 *
2080
 * @return
2081
 *   A base-64 encoded sha-256 hash, with + replaced with -, / with _ and
2082
 *   any = padding characters removed.
2083
 */
2084
function drupal_hash_base64($data) {
2085
  $hash = base64_encode(hash('sha256', $data, TRUE));
2086
  // Modify the hash so it's safe to use in URLs.
2087
  return strtr($hash, array('+' => '-', '/' => '_', '=' => ''));
2088
}
2089

    
2090
/**
2091
 * Merges multiple arrays, recursively, and returns the merged array.
2092
 *
2093
 * This function is similar to PHP's array_merge_recursive() function, but it
2094
 * handles non-array values differently. When merging values that are not both
2095
 * arrays, the latter value replaces the former rather than merging with it.
2096
 *
2097
 * Example:
2098
 * @code
2099
 * $link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => t('X'), 'class' => array('a', 'b')));
2100
 * $link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('c', 'd')));
2101
 *
2102
 * // This results in array('fragment' => array('x', 'y'), 'attributes' => array('title' => array(t('X'), t('Y')), 'class' => array('a', 'b', 'c', 'd'))).
2103
 * $incorrect = array_merge_recursive($link_options_1, $link_options_2);
2104
 *
2105
 * // This results in array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('a', 'b', 'c', 'd'))).
2106
 * $correct = drupal_array_merge_deep($link_options_1, $link_options_2);
2107
 * @endcode
2108
 *
2109
 * @param ...
2110
 *   Arrays to merge.
2111
 *
2112
 * @return
2113
 *   The merged array.
2114
 *
2115
 * @see drupal_array_merge_deep_array()
2116
 */
2117
function drupal_array_merge_deep() {
2118
  $args = func_get_args();
2119
  return drupal_array_merge_deep_array($args);
2120
}
2121

    
2122
/**
2123
 * Merges multiple arrays, recursively, and returns the merged array.
2124
 *
2125
 * This function is equivalent to drupal_array_merge_deep(), except the
2126
 * input arrays are passed as a single array parameter rather than a variable
2127
 * parameter list.
2128
 *
2129
 * The following are equivalent:
2130
 * - drupal_array_merge_deep($a, $b);
2131
 * - drupal_array_merge_deep_array(array($a, $b));
2132
 *
2133
 * The following are also equivalent:
2134
 * - call_user_func_array('drupal_array_merge_deep', $arrays_to_merge);
2135
 * - drupal_array_merge_deep_array($arrays_to_merge);
2136
 *
2137
 * @see drupal_array_merge_deep()
2138
 */
2139
function drupal_array_merge_deep_array($arrays) {
2140
  $result = array();
2141

    
2142
  foreach ($arrays as $array) {
2143
    foreach ($array as $key => $value) {
2144
      // Renumber integer keys as array_merge_recursive() does. Note that PHP
2145
      // automatically converts array keys that are integer strings (e.g., '1')
2146
      // to integers.
2147
      if (is_integer($key)) {
2148
        $result[] = $value;
2149
      }
2150
      // Recurse when both values are arrays.
2151
      elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
2152
        $result[$key] = drupal_array_merge_deep_array(array($result[$key], $value));
2153
      }
2154
      // Otherwise, use the latter value, overriding any previous value.
2155
      else {
2156
        $result[$key] = $value;
2157
      }
2158
    }
2159
  }
2160

    
2161
  return $result;
2162
}
2163

    
2164
/**
2165
 * Generates a default anonymous $user object.
2166
 *
2167
 * @return Object - the user object.
2168
 */
2169
function drupal_anonymous_user() {
2170
  $user = variable_get('drupal_anonymous_user_object', new stdClass);
2171
  $user->uid = 0;
2172
  $user->hostname = ip_address();
2173
  $user->roles = array();
2174
  $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
2175
  $user->cache = 0;
2176
  return $user;
2177
}
2178

    
2179
/**
2180
 * Ensures Drupal is bootstrapped to the specified phase.
2181
 *
2182
 * In order to bootstrap Drupal from another PHP script, you can use this code:
2183
 * @code
2184
 *   define('DRUPAL_ROOT', '/path/to/drupal');
2185
 *   require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
2186
 *   drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
2187
 * @endcode
2188
 *
2189
 * @param int $phase
2190
 *   A constant telling which phase to bootstrap to. When you bootstrap to a
2191
 *   particular phase, all earlier phases are run automatically. Possible
2192
 *   values:
2193
 *   - DRUPAL_BOOTSTRAP_CONFIGURATION: Initializes configuration.
2194
 *   - DRUPAL_BOOTSTRAP_PAGE_CACHE: Tries to serve a cached page.
2195
 *   - DRUPAL_BOOTSTRAP_DATABASE: Initializes the database layer.
2196
 *   - DRUPAL_BOOTSTRAP_VARIABLES: Initializes the variable system.
2197
 *   - DRUPAL_BOOTSTRAP_SESSION: Initializes session handling.
2198
 *   - DRUPAL_BOOTSTRAP_PAGE_HEADER: Sets up the page header.
2199
 *   - DRUPAL_BOOTSTRAP_LANGUAGE: Finds out the language of the page.
2200
 *   - DRUPAL_BOOTSTRAP_FULL: Fully loads Drupal. Validates and fixes input
2201
 *     data.
2202
 * @param boolean $new_phase
2203
 *   A boolean, set to FALSE if calling drupal_bootstrap from inside a
2204
 *   function called from drupal_bootstrap (recursion).
2205
 *
2206
 * @return int
2207
 *   The most recently completed phase.
2208
 */
2209
function drupal_bootstrap($phase = NULL, $new_phase = TRUE) {
2210
  // Not drupal_static(), because does not depend on any run-time information.
2211
  static $phases = array(
2212
    DRUPAL_BOOTSTRAP_CONFIGURATION,
2213
    DRUPAL_BOOTSTRAP_PAGE_CACHE,
2214
    DRUPAL_BOOTSTRAP_DATABASE,
2215
    DRUPAL_BOOTSTRAP_VARIABLES,
2216
    DRUPAL_BOOTSTRAP_SESSION,
2217
    DRUPAL_BOOTSTRAP_PAGE_HEADER,
2218
    DRUPAL_BOOTSTRAP_LANGUAGE,
2219
    DRUPAL_BOOTSTRAP_FULL,
2220
  );
2221
  // Not drupal_static(), because the only legitimate API to control this is to
2222
  // call drupal_bootstrap() with a new phase parameter.
2223
  static $final_phase;
2224
  // Not drupal_static(), because it's impossible to roll back to an earlier
2225
  // bootstrap state.
2226
  static $stored_phase = -1;
2227

    
2228
  if (isset($phase)) {
2229
    // When not recursing, store the phase name so it's not forgotten while
2230
    // recursing but take care of not going backwards.
2231
    if ($new_phase && $phase >= $stored_phase) {
2232
      $final_phase = $phase;
2233
    }
2234

    
2235
    // Call a phase if it has not been called before and is below the requested
2236
    // phase.
2237
    while ($phases && $phase > $stored_phase && $final_phase > $stored_phase) {
2238
      $current_phase = array_shift($phases);
2239

    
2240
      // This function is re-entrant. Only update the completed phase when the
2241
      // current call actually resulted in a progress in the bootstrap process.
2242
      if ($current_phase > $stored_phase) {
2243
        $stored_phase = $current_phase;
2244
      }
2245

    
2246
      switch ($current_phase) {
2247
        case DRUPAL_BOOTSTRAP_CONFIGURATION:
2248
          _drupal_bootstrap_configuration();
2249
          break;
2250

    
2251
        case DRUPAL_BOOTSTRAP_PAGE_CACHE:
2252
          _drupal_bootstrap_page_cache();
2253
          break;
2254

    
2255
        case DRUPAL_BOOTSTRAP_DATABASE:
2256
          _drupal_bootstrap_database();
2257
          break;
2258

    
2259
        case DRUPAL_BOOTSTRAP_VARIABLES:
2260
          _drupal_bootstrap_variables();
2261
          break;
2262

    
2263
        case DRUPAL_BOOTSTRAP_SESSION:
2264
          require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
2265
          drupal_session_initialize();
2266
          break;
2267

    
2268
        case DRUPAL_BOOTSTRAP_PAGE_HEADER:
2269
          _drupal_bootstrap_page_header();
2270
          break;
2271

    
2272
        case DRUPAL_BOOTSTRAP_LANGUAGE:
2273
          drupal_language_initialize();
2274
          break;
2275

    
2276
        case DRUPAL_BOOTSTRAP_FULL:
2277
          require_once DRUPAL_ROOT . '/includes/common.inc';
2278
          _drupal_bootstrap_full();
2279
          break;
2280
      }
2281
    }
2282
  }
2283
  return $stored_phase;
2284
}
2285

    
2286
/**
2287
 * Returns the time zone of the current user.
2288
 */
2289
function drupal_get_user_timezone() {
2290
  global $user;
2291
  if (variable_get('configurable_timezones', 1) && $user->uid && $user->timezone) {
2292
    return $user->timezone;
2293
  }
2294
  else {
2295
    // Ignore PHP strict notice if time zone has not yet been set in the php.ini
2296
    // configuration.
2297
    return variable_get('date_default_timezone', @date_default_timezone_get());
2298
  }
2299
}
2300

    
2301
/**
2302
 * Gets a salt useful for hardening against SQL injection.
2303
 *
2304
 * @return
2305
 *   A salt based on information in settings.php, not in the database.
2306
 */
2307
function drupal_get_hash_salt() {
2308
  global $drupal_hash_salt, $databases;
2309
  // If the $drupal_hash_salt variable is empty, a hash of the serialized
2310
  // database credentials is used as a fallback salt.
2311
  return empty($drupal_hash_salt) ? hash('sha256', serialize($databases)) : $drupal_hash_salt;
2312
}
2313

    
2314
/**
2315
 * Provides custom PHP error handling.
2316
 *
2317
 * @param $error_level
2318
 *   The level of the error raised.
2319
 * @param $message
2320
 *   The error message.
2321
 * @param $filename
2322
 *   The filename that the error was raised in.
2323
 * @param $line
2324
 *   The line number the error was raised at.
2325
 * @param $context
2326
 *   An array that points to the active symbol table at the point the error
2327
 *   occurred.
2328
 */
2329
function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
2330
  require_once DRUPAL_ROOT . '/includes/errors.inc';
2331
  _drupal_error_handler_real($error_level, $message, $filename, $line, $context);
2332
}
2333

    
2334
/**
2335
 * Provides custom PHP exception handling.
2336
 *
2337
 * Uncaught exceptions are those not enclosed in a try/catch block. They are
2338
 * always fatal: the execution of the script will stop as soon as the exception
2339
 * handler exits.
2340
 *
2341
 * @param $exception
2342
 *   The exception object that was thrown.
2343
 */
2344
function _drupal_exception_handler($exception) {
2345
  require_once DRUPAL_ROOT . '/includes/errors.inc';
2346

    
2347
  try {
2348
    // Log the message to the watchdog and return an error page to the user.
2349
    _drupal_log_error(_drupal_decode_exception($exception), TRUE);
2350
  }
2351
  catch (Exception $exception2) {
2352
    // Another uncaught exception was thrown while handling the first one.
2353
    // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
2354
    if (error_displayable()) {
2355
      print '<h1>Additional uncaught exception thrown while handling exception.</h1>';
2356
      print '<h2>Original</h2><p>' . _drupal_render_exception_safe($exception) . '</p>';
2357
      print '<h2>Additional</h2><p>' . _drupal_render_exception_safe($exception2) . '</p><hr />';
2358
    }
2359
  }
2360
}
2361

    
2362
/**
2363
 * Sets up the script environment and loads settings.php.
2364
 */
2365
function _drupal_bootstrap_configuration() {
2366
  // Set the Drupal custom error handler.
2367
  set_error_handler('_drupal_error_handler');
2368
  set_exception_handler('_drupal_exception_handler');
2369

    
2370
  drupal_environment_initialize();
2371
  // Start a page timer:
2372
  timer_start('page');
2373
  // Initialize the configuration, including variables from settings.php.
2374
  drupal_settings_initialize();
2375
}
2376

    
2377
/**
2378
 * Attempts to serve a page from the cache.
2379
 */
2380
function _drupal_bootstrap_page_cache() {
2381
  global $user;
2382

    
2383
  // Allow specifying special cache handlers in settings.php, like
2384
  // using memcached or files for storing cache information.
2385
  require_once DRUPAL_ROOT . '/includes/cache.inc';
2386
  foreach (variable_get('cache_backends', array()) as $include) {
2387
    require_once DRUPAL_ROOT . '/' . $include;
2388
  }
2389
  // Check for a cache mode force from settings.php.
2390
  if (variable_get('page_cache_without_database')) {
2391
    $cache_enabled = TRUE;
2392
  }
2393
  else {
2394
    drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE);
2395
    $cache_enabled = variable_get('cache');
2396
  }
2397
  drupal_block_denied(ip_address());
2398
  // If there is no session cookie and cache is enabled (or forced), try
2399
  // to serve a cached page.
2400
  if (!isset($_COOKIE[session_name()]) && $cache_enabled) {
2401
    // Make sure there is a user object because its timestamp will be
2402
    // checked, hook_boot might check for anonymous user etc.
2403
    $user = drupal_anonymous_user();
2404
    // Get the page from the cache.
2405
    $cache = drupal_page_get_cache();
2406
    // If there is a cached page, display it.
2407
    if (is_object($cache)) {
2408
      header('X-Drupal-Cache: HIT');
2409
      // Restore the metadata cached with the page.
2410
      $_GET['q'] = $cache->data['path'];
2411
      drupal_set_title($cache->data['title'], PASS_THROUGH);
2412
      date_default_timezone_set(drupal_get_user_timezone());
2413
      // If the skipping of the bootstrap hooks is not enforced, call
2414
      // hook_boot.
2415
      if (variable_get('page_cache_invoke_hooks', TRUE)) {
2416
        bootstrap_invoke_all('boot');
2417
      }
2418
      drupal_serve_page_from_cache($cache);
2419
      // If the skipping of the bootstrap hooks is not enforced, call
2420
      // hook_exit.
2421
      if (variable_get('page_cache_invoke_hooks', TRUE)) {
2422
        bootstrap_invoke_all('exit');
2423
      }
2424
      // We are done.
2425
      exit;
2426
    }
2427
    else {
2428
      header('X-Drupal-Cache: MISS');
2429
    }
2430
  }
2431
}
2432

    
2433
/**
2434
 * Initializes the database system and registers autoload functions.
2435
 */
2436
function _drupal_bootstrap_database() {
2437
  // Redirect the user to the installation script if Drupal has not been
2438
  // installed yet (i.e., if no $databases array has been defined in the
2439
  // settings.php file) and we are not already installing.
2440
  if (empty($GLOBALS['databases']) && !drupal_installation_attempted()) {
2441
    include_once DRUPAL_ROOT . '/includes/install.inc';
2442
    install_goto('install.php');
2443
  }
2444

    
2445
  // The user agent header is used to pass a database prefix in the request when
2446
  // running tests. However, for security reasons, it is imperative that we
2447
  // validate we ourselves made the request.
2448
  if ($test_prefix = drupal_valid_test_ua()) {
2449
    // Set the test run id for use in other parts of Drupal.
2450
    $test_info = &$GLOBALS['drupal_test_info'];
2451
    $test_info['test_run_id'] = $test_prefix;
2452
    $test_info['in_child_site'] = TRUE;
2453

    
2454
    foreach ($GLOBALS['databases']['default'] as &$value) {
2455
      // Extract the current default database prefix.
2456
      if (!isset($value['prefix'])) {
2457
        $current_prefix = '';
2458
      }
2459
      elseif (is_array($value['prefix'])) {
2460
        $current_prefix = $value['prefix']['default'];
2461
      }
2462
      else {
2463
        $current_prefix = $value['prefix'];
2464
      }
2465

    
2466
      // Remove the current database prefix and replace it by our own.
2467
      $value['prefix'] = array(
2468
        'default' => $current_prefix . $test_prefix,
2469
      );
2470
    }
2471
  }
2472

    
2473
  // Initialize the database system. Note that the connection
2474
  // won't be initialized until it is actually requested.
2475
  require_once DRUPAL_ROOT . '/includes/database/database.inc';
2476

    
2477
  // Register autoload functions so that we can access classes and interfaces.
2478
  // The database autoload routine comes first so that we can load the database
2479
  // system without hitting the database. That is especially important during
2480
  // the install or upgrade process.
2481
  spl_autoload_register('drupal_autoload_class');
2482
  spl_autoload_register('drupal_autoload_interface');
2483
}
2484

    
2485
/**
2486
 * Loads system variables and all enabled bootstrap modules.
2487
 */
2488
function _drupal_bootstrap_variables() {
2489
  global $conf;
2490

    
2491
  // Initialize the lock system.
2492
  require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
2493
  lock_initialize();
2494

    
2495
  // Load variables from the database, but do not overwrite variables set in settings.php.
2496
  $conf = variable_initialize(isset($conf) ? $conf : array());
2497
  // Load bootstrap modules.
2498
  require_once DRUPAL_ROOT . '/includes/module.inc';
2499
  module_load_all(TRUE);
2500

    
2501
  // Sanitize the destination parameter (which is often used for redirects) to
2502
  // prevent open redirect attacks leading to other domains. Sanitize both
2503
  // $_GET['destination'] and $_REQUEST['destination'] to protect code that
2504
  // relies on either, but do not sanitize $_POST to avoid interfering with
2505
  // unrelated form submissions. The sanitization happens here because
2506
  // url_is_external() requires the variable system to be available.
2507
  if (isset($_GET['destination']) || isset($_REQUEST['destination'])) {
2508
    require_once DRUPAL_ROOT . '/includes/common.inc';
2509
    // If the destination is an external URL, remove it.
2510
    if (isset($_GET['destination']) && url_is_external($_GET['destination'])) {
2511
      unset($_GET['destination']);
2512
      unset($_REQUEST['destination']);
2513
    }
2514
    // If there's still something in $_REQUEST['destination'] that didn't come
2515
    // from $_GET, check it too.
2516
    if (isset($_REQUEST['destination']) && (!isset($_GET['destination']) || $_REQUEST['destination'] != $_GET['destination']) && url_is_external($_REQUEST['destination'])) {
2517
      unset($_REQUEST['destination']);
2518
    }
2519
  }
2520
}
2521

    
2522
/**
2523
 * Invokes hook_boot(), initializes locking system, and sends HTTP headers.
2524
 */
2525
function _drupal_bootstrap_page_header() {
2526
  bootstrap_invoke_all('boot');
2527

    
2528
  if (!drupal_is_cli()) {
2529
    ob_start();
2530
    drupal_page_header();
2531
  }
2532
}
2533

    
2534
/**
2535
 * Returns the current bootstrap phase for this Drupal process.
2536
 *
2537
 * The current phase is the one most recently completed by drupal_bootstrap().
2538
 *
2539
 * @see drupal_bootstrap()
2540
 */
2541
function drupal_get_bootstrap_phase() {
2542
  return drupal_bootstrap(NULL, FALSE);
2543
}
2544

    
2545
/**
2546
 * Returns the test prefix if this is an internal request from SimpleTest.
2547
 *
2548
 * @return
2549
 *   Either the simpletest prefix (the string "simpletest" followed by any
2550
 *   number of digits) or FALSE if the user agent does not contain a valid
2551
 *   HMAC and timestamp.
2552
 */
2553
function drupal_valid_test_ua() {
2554
  // No reason to reset this.
2555
  static $test_prefix;
2556

    
2557
  if (isset($test_prefix)) {
2558
    return $test_prefix;
2559
  }
2560

    
2561
  if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/^(simpletest\d+);(.+);(.+);(.+)$/", $_SERVER['HTTP_USER_AGENT'], $matches)) {
2562
    list(, $prefix, $time, $salt, $hmac) = $matches;
2563
    $check_string =  $prefix . ';' . $time . ';' . $salt;
2564
    // We use the salt from settings.php to make the HMAC key, since
2565
    // the database is not yet initialized and we can't access any Drupal variables.
2566
    // The file properties add more entropy not easily accessible to others.
2567
    $key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
2568
    $time_diff = REQUEST_TIME - $time;
2569
    // Since we are making a local request a 5 second time window is allowed,
2570
    // and the HMAC must match.
2571
    if ($time_diff >= 0 && $time_diff <= 5 && $hmac == drupal_hmac_base64($check_string, $key)) {
2572
      $test_prefix = $prefix;
2573
      return $test_prefix;
2574
    }
2575
  }
2576

    
2577
  $test_prefix = FALSE;
2578
  return $test_prefix;
2579
}
2580

    
2581
/**
2582
 * Generates a user agent string with a HMAC and timestamp for simpletest.
2583
 */
2584
function drupal_generate_test_ua($prefix) {
2585
  static $key;
2586

    
2587
  if (!isset($key)) {
2588
    // We use the salt from settings.php to make the HMAC key, since
2589
    // the database is not yet initialized and we can't access any Drupal variables.
2590
    // The file properties add more entropy not easily accessible to others.
2591
    $key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
2592
  }
2593
  // Generate a moderately secure HMAC based on the database credentials.
2594
  $salt = uniqid('', TRUE);
2595
  $check_string = $prefix . ';' . time() . ';' . $salt;
2596
  return $check_string . ';' . drupal_hmac_base64($check_string, $key);
2597
}
2598

    
2599
/**
2600
 * Enables use of the theme system without requiring database access.
2601
 *
2602
 * Loads and initializes the theme system for site installs, updates and when
2603
 * the site is in maintenance mode. This also applies when the database fails.
2604
 *
2605
 * @see _drupal_maintenance_theme()
2606
 */
2607
function drupal_maintenance_theme() {
2608
  require_once DRUPAL_ROOT . '/includes/theme.maintenance.inc';
2609
  _drupal_maintenance_theme();
2610
}
2611

    
2612
/**
2613
 * Returns a simple 404 Not Found page.
2614
 *
2615
 * If fast 404 pages are enabled, and this is a matching page then print a
2616
 * simple 404 page and exit.
2617
 *
2618
 * This function is called from drupal_deliver_html_page() at the time when a
2619
 * a normal 404 page is generated, but it can also optionally be called directly
2620
 * from settings.php to prevent a Drupal bootstrap on these pages. See
2621
 * documentation in settings.php for the benefits and drawbacks of using this.
2622
 *
2623
 * Paths to dynamically-generated content, such as image styles, should also be
2624
 * accounted for in this function.
2625
 */
2626
function drupal_fast_404() {
2627
  $exclude_paths = variable_get('404_fast_paths_exclude', FALSE);
2628
  if ($exclude_paths && !preg_match($exclude_paths, $_GET['q'])) {
2629
    $fast_paths = variable_get('404_fast_paths', FALSE);
2630
    if ($fast_paths && preg_match($fast_paths, $_GET['q'])) {
2631
      drupal_add_http_header('Status', '404 Not Found');
2632
      $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>');
2633
      // Replace @path in the variable with the page path.
2634
      print strtr($fast_404_html, array('@path' => check_plain(request_uri())));
2635
      exit;
2636
    }
2637
  }
2638
}
2639

    
2640
/**
2641
 * Returns TRUE if a Drupal installation is currently being attempted.
2642
 */
2643
function drupal_installation_attempted() {
2644
  return defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'install';
2645
}
2646

    
2647
/**
2648
 * Returns the name of the proper localization function.
2649
 *
2650
 * get_t() exists to support localization for code that might run during
2651
 * the installation phase, when some elements of the system might not have
2652
 * loaded.
2653
 *
2654
 * This would include implementations of hook_install(), which could run
2655
 * during the Drupal installation phase, and might also be run during
2656
 * non-installation time, such as while installing the module from the the
2657
 * module administration page.
2658
 *
2659
 * Example usage:
2660
 * @code
2661
 *   $t = get_t();
2662
 *   $translated = $t('translate this');
2663
 * @endcode
2664
 *
2665
 * Use t() if your code will never run during the Drupal installation phase.
2666
 * Use st() if your code will only run during installation and never any other
2667
 * time. Use get_t() if your code could run in either circumstance.
2668
 *
2669
 * @see t()
2670
 * @see st()
2671
 * @ingroup sanitization
2672
 */
2673
function get_t() {
2674
  static $t;
2675
  // This is not converted to drupal_static because there is no point in
2676
  // resetting this as it can not change in the course of a request.
2677
  if (!isset($t)) {
2678
    $t = drupal_installation_attempted() ? 'st' : 't';
2679
  }
2680
  return $t;
2681
}
2682

    
2683
/**
2684
 * Initializes all the defined language types.
2685
 */
2686
function drupal_language_initialize() {
2687
  $types = language_types();
2688

    
2689
  // Ensure the language is correctly returned, even without multilanguage
2690
  // support. Also make sure we have a $language fallback, in case a language
2691
  // negotiation callback needs to do a full bootstrap.
2692
  // Useful for eg. XML/HTML 'lang' attributes.
2693
  $default = language_default();
2694
  foreach ($types as $type) {
2695
    $GLOBALS[$type] = $default;
2696
  }
2697
  if (drupal_multilingual()) {
2698
    include_once DRUPAL_ROOT . '/includes/language.inc';
2699
    foreach ($types as $type) {
2700
      $GLOBALS[$type] = language_initialize($type);
2701
    }
2702
    // Allow modules to react on language system initialization in multilingual
2703
    // environments.
2704
    bootstrap_invoke_all('language_init');
2705
  }
2706
}
2707

    
2708
/**
2709
 * Returns a list of the built-in language types.
2710
 *
2711
 * @return
2712
 *   An array of key-values pairs where the key is the language type and the
2713
 *   value is its configurability.
2714
 */
2715
function drupal_language_types() {
2716
  return array(
2717
    LANGUAGE_TYPE_INTERFACE => TRUE,
2718
    LANGUAGE_TYPE_CONTENT => FALSE,
2719
    LANGUAGE_TYPE_URL => FALSE,
2720
  );
2721
}
2722

    
2723
/**
2724
 * Returns TRUE if there is more than one language enabled.
2725
 *
2726
 * @return
2727
 *   TRUE if more than one language is enabled.
2728
 */
2729
function drupal_multilingual() {
2730
  // The "language_count" variable stores the number of enabled languages to
2731
  // avoid unnecessarily querying the database when building the list of
2732
  // enabled languages on monolingual sites.
2733
  return variable_get('language_count', 1) > 1;
2734
}
2735

    
2736
/**
2737
 * Returns an array of the available language types.
2738
 *
2739
 * @return
2740
 *   An array of all language types where the keys of each are the language type
2741
 *   name and its value is its configurability (TRUE/FALSE).
2742
 */
2743
function language_types() {
2744
  return array_keys(variable_get('language_types', drupal_language_types()));
2745
}
2746

    
2747
/**
2748
 * Returns a list of installed languages, indexed by the specified key.
2749
 *
2750
 * @param $field
2751
 *   (optional) The field to index the list with.
2752
 *
2753
 * @return
2754
 *   An associative array, keyed on the values of $field.
2755
 *   - If $field is 'weight' or 'enabled', the array is nested, with the outer
2756
 *     array's values each being associative arrays with language codes as
2757
 *     keys and language objects as values.
2758
 *   - For all other values of $field, the array is only one level deep, and
2759
 *     the array's values are language objects.
2760
 */
2761
function language_list($field = 'language') {
2762
  $languages = &drupal_static(__FUNCTION__);
2763
  // Init language list
2764
  if (!isset($languages)) {
2765
    if (drupal_multilingual() || module_exists('locale')) {
2766
      $languages['language'] = db_query('SELECT * FROM {languages} ORDER BY weight ASC, name ASC')->fetchAllAssoc('language');
2767
      // Users cannot uninstall the native English language. However, we allow
2768
      // it to be hidden from the installed languages. Therefore, at least one
2769
      // other language must be enabled then.
2770
      if (!$languages['language']['en']->enabled && !variable_get('language_native_enabled', TRUE)) {
2771
        unset($languages['language']['en']);
2772
      }
2773
    }
2774
    else {
2775
      // No locale module, so use the default language only.
2776
      $default = language_default();
2777
      $languages['language'][$default->language] = $default;
2778
    }
2779
  }
2780

    
2781
  // Return the array indexed by the right field
2782
  if (!isset($languages[$field])) {
2783
    $languages[$field] = array();
2784
    foreach ($languages['language'] as $lang) {
2785
      // Some values should be collected into an array
2786
      if (in_array($field, array('enabled', 'weight'))) {
2787
        $languages[$field][$lang->$field][$lang->language] = $lang;
2788
      }
2789
      else {
2790
        $languages[$field][$lang->$field] = $lang;
2791
      }
2792
    }
2793
  }
2794
  return $languages[$field];
2795
}
2796

    
2797
/**
2798
 * Returns the default language used on the site
2799
 *
2800
 * @param $property
2801
 *   Optional property of the language object to return
2802
 */
2803
function language_default($property = NULL) {
2804
  $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' => ''));
2805
  return $property ? $language->$property : $language;
2806
}
2807

    
2808
/**
2809
 * Returns the requested URL path of the page being viewed.
2810
 *
2811
 * Examples:
2812
 * - http://example.com/node/306 returns "node/306".
2813
 * - http://example.com/drupalfolder/node/306 returns "node/306" while
2814
 *   base_path() returns "/drupalfolder/".
2815
 * - http://example.com/path/alias (which is a path alias for node/306) returns
2816
 *   "path/alias" as opposed to the internal path.
2817
 * - http://example.com/index.php returns an empty string (meaning: front page).
2818
 * - http://example.com/index.php?page=1 returns an empty string.
2819
 *
2820
 * @return
2821
 *   The requested Drupal URL path.
2822
 *
2823
 * @see current_path()
2824
 */
2825
function request_path() {
2826
  static $path;
2827

    
2828
  if (isset($path)) {
2829
    return $path;
2830
  }
2831

    
2832
  if (isset($_GET['q']) && is_string($_GET['q'])) {
2833
    // This is a request with a ?q=foo/bar query string. $_GET['q'] is
2834
    // overwritten in drupal_path_initialize(), but request_path() is called
2835
    // very early in the bootstrap process, so the original value is saved in
2836
    // $path and returned in later calls.
2837
    $path = $_GET['q'];
2838
  }
2839
  elseif (isset($_SERVER['REQUEST_URI'])) {
2840
    // This request is either a clean URL, or 'index.php', or nonsense.
2841
    // Extract the path from REQUEST_URI.
2842
    $request_path = strtok($_SERVER['REQUEST_URI'], '?');
2843
    $base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
2844
    // Unescape and strip $base_path prefix, leaving q without a leading slash.
2845
    $path = substr(urldecode($request_path), $base_path_len + 1);
2846
    // If the path equals the script filename, either because 'index.php' was
2847
    // explicitly provided in the URL, or because the server added it to
2848
    // $_SERVER['REQUEST_URI'] even when it wasn't provided in the URL (some
2849
    // versions of Microsoft IIS do this), the front page should be served.
2850
    if ($path == basename($_SERVER['PHP_SELF'])) {
2851
      $path = '';
2852
    }
2853
  }
2854
  else {
2855
    // This is the front page.
2856
    $path = '';
2857
  }
2858

    
2859
  // Under certain conditions Apache's RewriteRule directive prepends the value
2860
  // assigned to $_GET['q'] with a slash. Moreover we can always have a trailing
2861
  // slash in place, hence we need to normalize $_GET['q'].
2862
  $path = trim($path, '/');
2863

    
2864
  return $path;
2865
}
2866

    
2867
/**
2868
 * Returns a component of the current Drupal path.
2869
 *
2870
 * When viewing a page at the path "admin/structure/types", for example, arg(0)
2871
 * returns "admin", arg(1) returns "structure", and arg(2) returns "types".
2872
 *
2873
 * Avoid use of this function where possible, as resulting code is hard to
2874
 * read. In menu callback functions, attempt to use named arguments. See the
2875
 * explanation in menu.inc for how to construct callbacks that take arguments.
2876
 * When attempting to use this function to load an element from the current
2877
 * path, e.g. loading the node on a node page, use menu_get_object() instead.
2878
 *
2879
 * @param $index
2880
 *   The index of the component, where each component is separated by a '/'
2881
 *   (forward-slash), and where the first component has an index of 0 (zero).
2882
 * @param $path
2883
 *   A path to break into components. Defaults to the path of the current page.
2884
 *
2885
 * @return
2886
 *   The component specified by $index, or NULL if the specified component was
2887
 *   not found. If called without arguments, it returns an array containing all
2888
 *   the components of the current path.
2889
 */
2890
function arg($index = NULL, $path = NULL) {
2891
  // Even though $arguments doesn't need to be resettable for any functional
2892
  // reasons (the result of explode() does not depend on any run-time
2893
  // information), it should be resettable anyway in case a module needs to
2894
  // free up the memory used by it.
2895
  // Use the advanced drupal_static() pattern, since this is called very often.
2896
  static $drupal_static_fast;
2897
  if (!isset($drupal_static_fast)) {
2898
    $drupal_static_fast['arguments'] = &drupal_static(__FUNCTION__);
2899
  }
2900
  $arguments = &$drupal_static_fast['arguments'];
2901

    
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
/**
2917
 * Returns the IP address of the client machine.
2918
 *
2919
 * If Drupal is behind a reverse proxy, we use the X-Forwarded-For header
2920
 * instead of $_SERVER['REMOTE_ADDR'], which would be the IP address of
2921
 * the proxy server, and not the client's. The actual header name can be
2922
 * configured by the reverse_proxy_header variable.
2923
 *
2924
 * @return
2925
 *   IP address of client machine, adjusted for reverse proxy and/or cluster
2926
 *   environments.
2927
 */
2928
function ip_address() {
2929
  $ip_address = &drupal_static(__FUNCTION__);
2930

    
2931
  if (!isset($ip_address)) {
2932
    $ip_address = $_SERVER['REMOTE_ADDR'];
2933

    
2934
    if (variable_get('reverse_proxy', 0)) {
2935
      $reverse_proxy_header = variable_get('reverse_proxy_header', 'HTTP_X_FORWARDED_FOR');
2936
      if (!empty($_SERVER[$reverse_proxy_header])) {
2937
        // If an array of known reverse proxy IPs is provided, then trust
2938
        // the XFF header if request really comes from one of them.
2939
        $reverse_proxy_addresses = variable_get('reverse_proxy_addresses', array());
2940

    
2941
        // Turn XFF header into an array.
2942
        $forwarded = explode(',', $_SERVER[$reverse_proxy_header]);
2943

    
2944
        // Trim the forwarded IPs; they may have been delimited by commas and spaces.
2945
        $forwarded = array_map('trim', $forwarded);
2946

    
2947
        // Tack direct client IP onto end of forwarded array.
2948
        $forwarded[] = $ip_address;
2949

    
2950
        // Eliminate all trusted IPs.
2951
        $untrusted = array_diff($forwarded, $reverse_proxy_addresses);
2952

    
2953
        // The right-most IP is the most specific we can trust.
2954
        $ip_address = array_pop($untrusted);
2955
      }
2956
    }
2957
  }
2958

    
2959
  return $ip_address;
2960
}
2961

    
2962
/**
2963
 * @addtogroup schemaapi
2964
 * @{
2965
 */
2966

    
2967
/**
2968
 * Gets the schema definition of a table, or the whole database schema.
2969
 *
2970
 * The returned schema will include any modifications made by any
2971
 * module that implements hook_schema_alter().
2972
 *
2973
 * @param $table
2974
 *   The name of the table. If not given, the schema of all tables is returned.
2975
 * @param $rebuild
2976
 *   If true, the schema will be rebuilt instead of retrieved from the cache.
2977
 */
2978
function drupal_get_schema($table = NULL, $rebuild = FALSE) {
2979
  static $schema;
2980

    
2981
  if ($rebuild || !isset($table)) {
2982
    $schema = drupal_get_complete_schema($rebuild);
2983
  }
2984
  elseif (!isset($schema)) {
2985
    $schema = new SchemaCache();
2986
  }
2987

    
2988
  if (!isset($table)) {
2989
    return $schema;
2990
  }
2991
  if (isset($schema[$table])) {
2992
    return $schema[$table];
2993
  }
2994
  else {
2995
    return FALSE;
2996
  }
2997
}
2998

    
2999
/**
3000
 * Extends DrupalCacheArray to allow for dynamic building of the schema cache.
3001
 */
3002
class SchemaCache extends DrupalCacheArray {
3003

    
3004
  /**
3005
   * Constructs a SchemaCache object.
3006
   */
3007
  public function __construct() {
3008
    // Cache by request method.
3009
    parent::__construct('schema:runtime:' . ($_SERVER['REQUEST_METHOD'] == 'GET'), 'cache');
3010
  }
3011

    
3012
  /**
3013
   * Overrides DrupalCacheArray::resolveCacheMiss().
3014
   */
3015
  protected function resolveCacheMiss($offset) {
3016
    $complete_schema = drupal_get_complete_schema();
3017
    $value = isset($complete_schema[$offset]) ? $complete_schema[$offset] :  NULL;
3018
    $this->storage[$offset] = $value;
3019
    $this->persist($offset);
3020
    return $value;
3021
  }
3022
}
3023

    
3024
/**
3025
 * Gets the whole database schema.
3026
 *
3027
 * The returned schema will include any modifications made by any
3028
 * module that implements hook_schema_alter().
3029
 *
3030
 * @param $rebuild
3031
 *   If true, the schema will be rebuilt instead of retrieved from the cache.
3032
 */
3033
function drupal_get_complete_schema($rebuild = FALSE) {
3034
  static $schema = array();
3035

    
3036
  if (empty($schema) || $rebuild) {
3037
    // Try to load the schema from cache.
3038
    if (!$rebuild && $cached = cache_get('schema')) {
3039
      $schema = $cached->data;
3040
    }
3041
    // Otherwise, rebuild the schema cache.
3042
    else {
3043
      $schema = array();
3044
      // Load the .install files to get hook_schema.
3045
      // On some databases this function may be called before bootstrap has
3046
      // been completed, so we force the functions we need to load just in case.
3047
      if (function_exists('module_load_all_includes')) {
3048
        // This function can be called very early in the bootstrap process, so
3049
        // we force the module_list() cache to be refreshed to ensure that it
3050
        // contains the complete list of modules before we go on to call
3051
        // module_load_all_includes().
3052
        module_list(TRUE);
3053
        module_load_all_includes('install');
3054
      }
3055

    
3056
      require_once DRUPAL_ROOT . '/includes/common.inc';
3057
      // Invoke hook_schema for all modules.
3058
      foreach (module_implements('schema') as $module) {
3059
        // Cast the result of hook_schema() to an array, as a NULL return value
3060
        // would cause array_merge() to set the $schema variable to NULL as well.
3061
        // That would break modules which use $schema further down the line.
3062
        $current = (array) module_invoke($module, 'schema');
3063
        // Set 'module' and 'name' keys for each table, and remove descriptions,
3064
        // as they needlessly slow down cache_get() for every single request.
3065
        _drupal_schema_initialize($current, $module);
3066
        $schema = array_merge($schema, $current);
3067
      }
3068

    
3069
      drupal_alter('schema', $schema);
3070
      // If the schema is empty, avoid saving it: some database engines require
3071
      // the schema to perform queries, and this could lead to infinite loops.
3072
      if (!empty($schema) && (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL)) {
3073
        cache_set('schema', $schema);
3074
      }
3075
      if ($rebuild) {
3076
        cache_clear_all('schema:', 'cache', TRUE);
3077
      }
3078
    }
3079
  }
3080

    
3081
  return $schema;
3082
}
3083

    
3084
/**
3085
 * @} End of "addtogroup schemaapi".
3086
 */
3087

    
3088

    
3089
/**
3090
 * @addtogroup registry
3091
 * @{
3092
 */
3093

    
3094
/**
3095
 * Confirms that an interface is available.
3096
 *
3097
 * This function is rarely called directly. Instead, it is registered as an
3098
 * spl_autoload()  handler, and PHP calls it for us when necessary.
3099
 *
3100
 * @param $interface
3101
 *   The name of the interface to check or load.
3102
 *
3103
 * @return
3104
 *   TRUE if the interface is currently available, FALSE otherwise.
3105
 */
3106
function drupal_autoload_interface($interface) {
3107
  return _registry_check_code('interface', $interface);
3108
}
3109

    
3110
/**
3111
 * Confirms that a class is available.
3112
 *
3113
 * This function is rarely called directly. Instead, it is registered as an
3114
 * spl_autoload()  handler, and PHP calls it for us when necessary.
3115
 *
3116
 * @param $class
3117
 *   The name of the class to check or load.
3118
 *
3119
 * @return
3120
 *   TRUE if the class is currently available, FALSE otherwise.
3121
 */
3122
function drupal_autoload_class($class) {
3123
  return _registry_check_code('class', $class);
3124
}
3125

    
3126
/**
3127
 * Checks for a resource in the registry.
3128
 *
3129
 * @param $type
3130
 *   The type of resource we are looking up, or one of the constants
3131
 *   REGISTRY_RESET_LOOKUP_CACHE or REGISTRY_WRITE_LOOKUP_CACHE, which
3132
 *   signal that we should reset or write the cache, respectively.
3133
 * @param $name
3134
 *   The name of the resource, or NULL if either of the REGISTRY_* constants
3135
 *   is passed in.
3136
 *
3137
 * @return
3138
 *   TRUE if the resource was found, FALSE if not.
3139
 *   NULL if either of the REGISTRY_* constants is passed in as $type.
3140
 */
3141
function _registry_check_code($type, $name = NULL) {
3142
  static $lookup_cache, $cache_update_needed;
3143

    
3144
  if ($type == 'class' && class_exists($name) || $type == 'interface' && interface_exists($name)) {
3145
    return TRUE;
3146
  }
3147

    
3148
  if (!isset($lookup_cache)) {
3149
    $lookup_cache = array();
3150
    if ($cache = cache_get('lookup_cache', 'cache_bootstrap')) {
3151
      $lookup_cache = $cache->data;
3152
    }
3153
  }
3154

    
3155
  // When we rebuild the registry, we need to reset this cache so
3156
  // we don't keep lookups for resources that changed during the rebuild.
3157
  if ($type == REGISTRY_RESET_LOOKUP_CACHE) {
3158
    $cache_update_needed = TRUE;
3159
    $lookup_cache = NULL;
3160
    return;
3161
  }
3162

    
3163
  // Called from drupal_page_footer, we write to permanent storage if there
3164
  // changes to the lookup cache for this request.
3165
  if ($type == REGISTRY_WRITE_LOOKUP_CACHE) {
3166
    if ($cache_update_needed) {
3167
      cache_set('lookup_cache', $lookup_cache, 'cache_bootstrap');
3168
    }
3169
    return;
3170
  }
3171

    
3172
  // $type is either 'interface' or 'class', so we only need the first letter to
3173
  // keep the cache key unique.
3174
  $cache_key = $type[0] . $name;
3175
  if (isset($lookup_cache[$cache_key])) {
3176
    if ($lookup_cache[$cache_key]) {
3177
      require_once DRUPAL_ROOT . '/' . $lookup_cache[$cache_key];
3178
    }
3179
    return (bool) $lookup_cache[$cache_key];
3180
  }
3181

    
3182
  // This function may get called when the default database is not active, but
3183
  // there is no reason we'd ever want to not use the default database for
3184
  // this query.
3185
  $file = Database::getConnection('default', 'default')->query("SELECT filename FROM {registry} WHERE name = :name AND type = :type", array(
3186
      ':name' => $name,
3187
      ':type' => $type,
3188
    ))
3189
    ->fetchField();
3190

    
3191
  // Flag that we've run a lookup query and need to update the cache.
3192
  $cache_update_needed = TRUE;
3193

    
3194
  // Misses are valuable information worth caching, so cache even if
3195
  // $file is FALSE.
3196
  $lookup_cache[$cache_key] = $file;
3197

    
3198
  if ($file) {
3199
    require_once DRUPAL_ROOT . '/' . $file;
3200
    return TRUE;
3201
  }
3202
  else {
3203
    return FALSE;
3204
  }
3205
}
3206

    
3207
/**
3208
 * Rescans all enabled modules and rebuilds the registry.
3209
 *
3210
 * Rescans all code in modules or includes directories, storing the location of
3211
 * each interface or class in the database.
3212
 */
3213
function registry_rebuild() {
3214
  system_rebuild_module_data();
3215
  registry_update();
3216
}
3217

    
3218
/**
3219
 * Updates the registry based on the latest files listed in the database.
3220
 *
3221
 * This function should be used when system_rebuild_module_data() does not need
3222
 * to be called, because it is already known that the list of files in the
3223
 * {system} table matches those in the file system.
3224
 *
3225
 * @return
3226
 *   TRUE if the registry was rebuilt, FALSE if another thread was rebuilding
3227
 *   in parallel and the current thread just waited for completion.
3228
 *
3229
 * @see registry_rebuild()
3230
 */
3231
function registry_update() {
3232
  // install_system_module() calls module_enable() which calls into this
3233
  // function during initial system installation, so the lock system is neither
3234
  // loaded nor does its storage exist yet.
3235
  $in_installer = drupal_installation_attempted();
3236
  if (!$in_installer && !lock_acquire(__FUNCTION__)) {
3237
    // Another request got the lock, wait for it to finish.
3238
    lock_wait(__FUNCTION__);
3239
    return FALSE;
3240
  }
3241

    
3242
  require_once DRUPAL_ROOT . '/includes/registry.inc';
3243
  _registry_update();
3244

    
3245
  if (!$in_installer) {
3246
    lock_release(__FUNCTION__);
3247
  }
3248
  return TRUE;
3249
}
3250

    
3251
/**
3252
 * @} End of "addtogroup registry".
3253
 */
3254

    
3255
/**
3256
 * Provides central static variable storage.
3257
 *
3258
 * All functions requiring a static variable to persist or cache data within
3259
 * a single page request are encouraged to use this function unless it is
3260
 * absolutely certain that the static variable will not need to be reset during
3261
 * the page request. By centralizing static variable storage through this
3262
 * function, other functions can rely on a consistent API for resetting any
3263
 * other function's static variables.
3264
 *
3265
 * Example:
3266
 * @code
3267
 * function language_list($field = 'language') {
3268
 *   $languages = &drupal_static(__FUNCTION__);
3269
 *   if (!isset($languages)) {
3270
 *     // If this function is being called for the first time after a reset,
3271
 *     // query the database and execute any other code needed to retrieve
3272
 *     // information about the supported languages.
3273
 *     ...
3274
 *   }
3275
 *   if (!isset($languages[$field])) {
3276
 *     // If this function is being called for the first time for a particular
3277
 *     // index field, then execute code needed to index the information already
3278
 *     // available in $languages by the desired field.
3279
 *     ...
3280
 *   }
3281
 *   // Subsequent invocations of this function for a particular index field
3282
 *   // skip the above two code blocks and quickly return the already indexed
3283
 *   // information.
3284
 *   return $languages[$field];
3285
 * }
3286
 * function locale_translate_overview_screen() {
3287
 *   // When building the content for the translations overview page, make
3288
 *   // sure to get completely fresh information about the supported languages.
3289
 *   drupal_static_reset('language_list');
3290
 *   ...
3291
 * }
3292
 * @endcode
3293
 *
3294
 * In a few cases, a function can have certainty that there is no legitimate
3295
 * use-case for resetting that function's static variable. This is rare,
3296
 * because when writing a function, it's hard to forecast all the situations in
3297
 * which it will be used. A guideline is that if a function's static variable
3298
 * does not depend on any information outside of the function that might change
3299
 * during a single page request, then it's ok to use the "static" keyword
3300
 * instead of the drupal_static() function.
3301
 *
3302
 * Example:
3303
 * @code
3304
 * function actions_do(...) {
3305
 *   // $stack tracks the number of recursive calls.
3306
 *   static $stack;
3307
 *   $stack++;
3308
 *   if ($stack > variable_get('actions_max_stack', 35)) {
3309
 *     ...
3310
 *     return;
3311
 *   }
3312
 *   ...
3313
 *   $stack--;
3314
 * }
3315
 * @endcode
3316
 *
3317
 * In a few cases, a function needs a resettable static variable, but the
3318
 * function is called many times (100+) during a single page request, so
3319
 * every microsecond of execution time that can be removed from the function
3320
 * counts. These functions can use a more cumbersome, but faster variant of
3321
 * calling drupal_static(). It works by storing the reference returned by
3322
 * drupal_static() in the calling function's own static variable, thereby
3323
 * removing the need to call drupal_static() for each iteration of the function.
3324
 * Conceptually, it replaces:
3325
 * @code
3326
 * $foo = &drupal_static(__FUNCTION__);
3327
 * @endcode
3328
 * with:
3329
 * @code
3330
 * // Unfortunately, this does not work.
3331
 * static $foo = &drupal_static(__FUNCTION__);
3332
 * @endcode
3333
 * However, the above line of code does not work, because PHP only allows static
3334
 * variables to be initializied by literal values, and does not allow static
3335
 * variables to be assigned to references.
3336
 * - http://php.net/manual/language.variables.scope.php#language.variables.scope.static
3337
 * - http://php.net/manual/language.variables.scope.php#language.variables.scope.references
3338
 * The example below shows the syntax needed to work around both limitations.
3339
 * For benchmarks and more information, see http://drupal.org/node/619666.
3340
 *
3341
 * Example:
3342
 * @code
3343
 * function user_access($string, $account = NULL) {
3344
 *   // Use the advanced drupal_static() pattern, since this is called very often.
3345
 *   static $drupal_static_fast;
3346
 *   if (!isset($drupal_static_fast)) {
3347
 *     $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
3348
 *   }
3349
 *   $perm = &$drupal_static_fast['perm'];
3350
 *   ...
3351
 * }
3352
 * @endcode
3353
 *
3354
 * @param $name
3355
 *   Globally unique name for the variable. For a function with only one static,
3356
 *   variable, the function name (e.g. via the PHP magic __FUNCTION__ constant)
3357
 *   is recommended. For a function with multiple static variables add a
3358
 *   distinguishing suffix to the function name for each one.
3359
 * @param $default_value
3360
 *   Optional default value.
3361
 * @param $reset
3362
 *   TRUE to reset one or all variables(s). This parameter is only used
3363
 *   internally and should not be passed in; use drupal_static_reset() instead.
3364
 *   (This function's return value should not be used when TRUE is passed in.)
3365
 *
3366
 * @return
3367
 *   Returns a variable by reference.
3368
 *
3369
 * @see drupal_static_reset()
3370
 */
3371
function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
3372
  static $data = array(), $default = array();
3373
  // First check if dealing with a previously defined static variable.
3374
  if (isset($data[$name]) || array_key_exists($name, $data)) {
3375
    // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
3376
    if ($reset) {
3377
      // Reset pre-existing static variable to its default value.
3378
      $data[$name] = $default[$name];
3379
    }
3380
    return $data[$name];
3381
  }
3382
  // Neither $data[$name] nor $default[$name] static variables exist.
3383
  if (isset($name)) {
3384
    if ($reset) {
3385
      // Reset was called before a default is set and yet a variable must be
3386
      // returned.
3387
      return $data;
3388
    }
3389
    // First call with new non-NULL $name. Initialize a new static variable.
3390
    $default[$name] = $data[$name] = $default_value;
3391
    return $data[$name];
3392
  }
3393
  // Reset all: ($name == NULL). This needs to be done one at a time so that
3394
  // references returned by earlier invocations of drupal_static() also get
3395
  // reset.
3396
  foreach ($default as $name => $value) {
3397
    $data[$name] = $value;
3398
  }
3399
  // As the function returns a reference, the return should always be a
3400
  // variable.
3401
  return $data;
3402
}
3403

    
3404
/**
3405
 * Resets one or all centrally stored static variable(s).
3406
 *
3407
 * @param $name
3408
 *   Name of the static variable to reset. Omit to reset all variables.
3409
 *   Resetting all variables should only be used, for example, for running unit
3410
 *   tests with a clean environment.
3411
 */
3412
function drupal_static_reset($name = NULL) {
3413
  drupal_static($name, NULL, TRUE);
3414
}
3415

    
3416
/**
3417
 * Detects whether the current script is running in a command-line environment.
3418
 */
3419
function drupal_is_cli() {
3420
  return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
3421
}
3422

    
3423
/**
3424
 * Formats text for emphasized display in a placeholder inside a sentence.
3425
 *
3426
 * Used automatically by format_string().
3427
 *
3428
 * @param $text
3429
 *   The text to format (plain-text).
3430
 *
3431
 * @return
3432
 *   The formatted text (html).
3433
 */
3434
function drupal_placeholder($text) {
3435
  return '<em class="placeholder">' . check_plain($text) . '</em>';
3436
}
3437

    
3438
/**
3439
 * Registers a function for execution on shutdown.
3440
 *
3441
 * Wrapper for register_shutdown_function() that catches thrown exceptions to
3442
 * avoid "Exception thrown without a stack frame in Unknown".
3443
 *
3444
 * @param $callback
3445
 *   The shutdown function to register.
3446
 * @param ...
3447
 *   Additional arguments to pass to the shutdown function.
3448
 *
3449
 * @return
3450
 *   Array of shutdown functions to be executed.
3451
 *
3452
 * @see register_shutdown_function()
3453
 * @ingroup php_wrappers
3454
 */
3455
function &drupal_register_shutdown_function($callback = NULL) {
3456
  // We cannot use drupal_static() here because the static cache is reset during
3457
  // batch processing, which breaks batch handling.
3458
  static $callbacks = array();
3459

    
3460
  if (isset($callback)) {
3461
    // Only register the internal shutdown function once.
3462
    if (empty($callbacks)) {
3463
      register_shutdown_function('_drupal_shutdown_function');
3464
    }
3465
    $args = func_get_args();
3466
    array_shift($args);
3467
    // Save callback and arguments
3468
    $callbacks[] = array('callback' => $callback, 'arguments' => $args);
3469
  }
3470
  return $callbacks;
3471
}
3472

    
3473
/**
3474
 * Executes registered shutdown functions.
3475
 */
3476
function _drupal_shutdown_function() {
3477
  $callbacks = &drupal_register_shutdown_function();
3478

    
3479
  // Set the CWD to DRUPAL_ROOT as it is not guaranteed to be the same as it
3480
  // was in the normal context of execution.
3481
  chdir(DRUPAL_ROOT);
3482

    
3483
  try {
3484
    while (list($key, $callback) = each($callbacks)) {
3485
      call_user_func_array($callback['callback'], $callback['arguments']);
3486
    }
3487
  }
3488
  catch (Exception $exception) {
3489
    // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
3490
   require_once DRUPAL_ROOT . '/includes/errors.inc';
3491
   if (error_displayable()) {
3492
      print '<h1>Uncaught exception thrown in shutdown function.</h1>';
3493
      print '<p>' . _drupal_render_exception_safe($exception) . '</p><hr />';
3494
    }
3495
  }
3496
}
3497

    
3498
/**
3499
 * Compares the memory required for an operation to the available memory.
3500
 *
3501
 * @param $required
3502
 *   The memory required for the operation, expressed as a number of bytes with
3503
 *   optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8bytes,
3504
 *   9mbytes).
3505
 * @param $memory_limit
3506
 *   (optional) The memory limit for the operation, expressed as a number of
3507
 *   bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G,
3508
 *   6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP
3509
 *   memory_limit will be used. Defaults to NULL.
3510
 *
3511
 * @return
3512
 *   TRUE if there is sufficient memory to allow the operation, or FALSE
3513
 *   otherwise.
3514
 */
3515
function drupal_check_memory_limit($required, $memory_limit = NULL) {
3516
  if (!isset($memory_limit)) {
3517
    $memory_limit = ini_get('memory_limit');
3518
  }
3519

    
3520
  // There is sufficient memory if:
3521
  // - No memory limit is set.
3522
  // - The memory limit is set to unlimited (-1).
3523
  // - The memory limit is greater than the memory required for the operation.
3524
  return ((!$memory_limit) || ($memory_limit == -1) || (parse_size($memory_limit) >= parse_size($required)));
3525
}