Projet

Général

Profil

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

root / drupal7 / includes / bootstrap.inc @ d719f12f

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.41');
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. See default.settings.php for examples on how the URL is converted
533
 * to a directory.
534
 *
535
 * @param bool $require_settings
536
 *   Only configuration directories with an existing settings.php file
537
 *   will be recognized. Defaults to TRUE. During initial installation,
538
 *   this is set to FALSE so that Drupal can detect a matching directory,
539
 *   then create a new settings.php file in it.
540
 * @param bool $reset
541
 *   Force a full search for matching directories even if one had been
542
 *   found previously. Defaults to FALSE.
543
 *
544
 * @return
545
 *   The path of the matching directory.
546
 *
547
 * @see default.settings.php
548
 */
549
function conf_path($require_settings = TRUE, $reset = FALSE) {
550
  $conf = &drupal_static(__FUNCTION__, '');
551

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

    
556
  $confdir = 'sites';
557

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
751
    $base_url = $base_root;
752

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

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

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

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

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

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

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

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

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

    
945
  return $variables;
946
}
947

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1123
    return TRUE;
1124
  }
1125

    
1126
  return FALSE;
1127
}
1128

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

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

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

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

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

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

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

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

    
1241
/**
1242
 * Sets HTTP headers in preparation for a page response.
1243
 *
1244
 * Authenticated users are always given a 'no-cache' header, and will fetch a
1245
 * fresh page on every request. This prevents authenticated users from seeing
1246
 * locally cached pages.
1247
 *
1248
 * ETag and Last-Modified headers are not set per default for authenticated
1249
 * users so that browsers do not send If-Modified-Since headers from
1250
 * authenticated user pages. drupal_serve_page_from_cache() will set appropriate
1251
 * ETag and Last-Modified headers for cached pages.
1252
 *
1253
 * @see drupal_page_set_cache()
1254
 */
1255
function drupal_page_header() {
1256
  $headers_sent = &drupal_static(__FUNCTION__, FALSE);
1257
  if ($headers_sent) {
1258
    return TRUE;
1259
  }
1260
  $headers_sent = TRUE;
1261

    
1262
  $default_headers = array(
1263
    'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
1264
    'Cache-Control' => 'no-cache, must-revalidate, post-check=0, pre-check=0',
1265
    // Prevent browsers from sniffing a response and picking a MIME type
1266
    // different from the declared content-type, since that can lead to
1267
    // XSS and other vulnerabilities.
1268
    'X-Content-Type-Options' => 'nosniff',
1269
  );
1270
  drupal_send_headers($default_headers);
1271
}
1272

    
1273
/**
1274
 * Sets HTTP headers in preparation for a cached page response.
1275
 *
1276
 * The headers allow as much as possible in proxies and browsers without any
1277
 * particular knowledge about the pages. Modules can override these headers
1278
 * using drupal_add_http_header().
1279
 *
1280
 * If the request is conditional (using If-Modified-Since and If-None-Match),
1281
 * and the conditions match those currently in the cache, a 304 Not Modified
1282
 * response is sent.
1283
 */
1284
function drupal_serve_page_from_cache(stdClass $cache) {
1285
  // Negotiate whether to use compression.
1286
  $page_compression = !empty($cache->data['page_compressed']);
1287
  $return_compressed = $page_compression && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE;
1288

    
1289
  // Get headers set in hook_boot(). Keys are lower-case.
1290
  $hook_boot_headers = drupal_get_http_header();
1291

    
1292
  // Headers generated in this function, that may be replaced or unset using
1293
  // drupal_add_http_headers(). Keys are mixed-case.
1294
  $default_headers = array();
1295

    
1296
  foreach ($cache->data['headers'] as $name => $value) {
1297
    // In the case of a 304 response, certain headers must be sent, and the
1298
    // remaining may not (see RFC 2616, section 10.3.5). Do not override
1299
    // headers set in hook_boot().
1300
    $name_lower = strtolower($name);
1301
    if (in_array($name_lower, array('content-location', 'expires', 'cache-control', 'vary')) && !isset($hook_boot_headers[$name_lower])) {
1302
      drupal_add_http_header($name, $value);
1303
      unset($cache->data['headers'][$name]);
1304
    }
1305
  }
1306

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

    
1315
  // Entity tag should change if the output changes.
1316
  $etag = '"' . $cache->created . '-' . intval($return_compressed) . '"';
1317
  header('Etag: ' . $etag);
1318

    
1319
  // See if the client has provided the required HTTP headers.
1320
  $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : FALSE;
1321
  $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : FALSE;
1322

    
1323
  if ($if_modified_since && $if_none_match
1324
      && $if_none_match == $etag // etag must match
1325
      && $if_modified_since == $cache->created) {  // if-modified-since must match
1326
    header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
1327
    drupal_send_headers($default_headers);
1328
    return;
1329
  }
1330

    
1331
  // Send the remaining headers.
1332
  foreach ($cache->data['headers'] as $name => $value) {
1333
    drupal_add_http_header($name, $value);
1334
  }
1335

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

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

    
1344
  drupal_send_headers($default_headers);
1345

    
1346
  // Allow HTTP proxies to cache pages for anonymous users without a session
1347
  // cookie. The Vary header is used to indicates the set of request-header
1348
  // fields that fully determines whether a cache is permitted to use the
1349
  // response to reply to a subsequent request for a given URL without
1350
  // revalidation. If a Vary header has been set in hook_boot(), it is assumed
1351
  // that the module knows how to cache the page.
1352
  if (!isset($hook_boot_headers['vary']) && !variable_get('omit_vary_cookie')) {
1353
    header('Vary: Cookie');
1354
  }
1355

    
1356
  if ($page_compression) {
1357
    header('Vary: Accept-Encoding', FALSE);
1358
    // If page_compression is enabled, the cache contains gzipped data.
1359
    if ($return_compressed) {
1360
      // $cache->data['body'] is already gzip'ed, so make sure
1361
      // zlib.output_compression does not compress it once more.
1362
      ini_set('zlib.output_compression', '0');
1363
      header('Content-Encoding: gzip');
1364
    }
1365
    else {
1366
      // The client does not support compression, so unzip the data in the
1367
      // cache. Strip the gzip header and run uncompress.
1368
      $cache->data['body'] = gzinflate(substr(substr($cache->data['body'], 10), 0, -8));
1369
    }
1370
  }
1371

    
1372
  // Print the page.
1373
  print $cache->data['body'];
1374
}
1375

    
1376
/**
1377
 * Defines the critical hooks that force modules to always be loaded.
1378
 */
1379
function bootstrap_hooks() {
1380
  return array('boot', 'exit', 'watchdog', 'language_init');
1381
}
1382

    
1383
/**
1384
 * Unserializes and appends elements from a serialized string.
1385
 *
1386
 * @param $obj
1387
 *   The object to which the elements are appended.
1388
 * @param $field
1389
 *   The attribute of $obj whose value should be unserialized.
1390
 */
1391
function drupal_unpack($obj, $field = 'data') {
1392
  if ($obj->$field && $data = unserialize($obj->$field)) {
1393
    foreach ($data as $key => $value) {
1394
      if (!empty($key) && !isset($obj->$key)) {
1395
        $obj->$key = $value;
1396
      }
1397
    }
1398
  }
1399
  return $obj;
1400
}
1401

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

    
1467
  // Merge in default.
1468
  if (empty($options['langcode'])) {
1469
    $options['langcode'] = isset($language->language) ? $language->language : 'en';
1470
  }
1471
  if (empty($options['context'])) {
1472
    $options['context'] = '';
1473
  }
1474

    
1475
  // First, check for an array of customized strings. If present, use the array
1476
  // *instead of* database lookups. This is a high performance way to provide a
1477
  // handful of string replacements. See settings.php for examples.
1478
  // Cache the $custom_strings variable to improve performance.
1479
  if (!isset($custom_strings[$options['langcode']])) {
1480
    $custom_strings[$options['langcode']] = variable_get('locale_custom_strings_' . $options['langcode'], array());
1481
  }
1482
  // Custom strings work for English too, even if locale module is disabled.
1483
  if (isset($custom_strings[$options['langcode']][$options['context']][$string])) {
1484
    $string = $custom_strings[$options['langcode']][$options['context']][$string];
1485
  }
1486
  // Translate with locale module if enabled.
1487
  elseif ($options['langcode'] != 'en' && function_exists('locale')) {
1488
    $string = locale($string, $options['context'], $options['langcode']);
1489
  }
1490
  if (empty($args)) {
1491
    return $string;
1492
  }
1493
  else {
1494
    return format_string($string, $args);
1495
  }
1496
}
1497

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

    
1540
      case '%':
1541
      default:
1542
        // Escaped and placeholder.
1543
        $args[$key] = drupal_placeholder($value);
1544
        break;
1545

    
1546
      case '!':
1547
        // Pass-through.
1548
    }
1549
  }
1550
  return strtr($string, $args);
1551
}
1552

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

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

    
1608
/**
1609
 * Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
1610
 *
1611
 * Because $_SERVER['REQUEST_URI'] is only available on Apache, we generate an
1612
 * equivalent using other environment variables.
1613
 */
1614
function request_uri() {
1615
  if (isset($_SERVER['REQUEST_URI'])) {
1616
    $uri = $_SERVER['REQUEST_URI'];
1617
  }
1618
  else {
1619
    if (isset($_SERVER['argv'])) {
1620
      $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
1621
    }
1622
    elseif (isset($_SERVER['QUERY_STRING'])) {
1623
      $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
1624
    }
1625
    else {
1626
      $uri = $_SERVER['SCRIPT_NAME'];
1627
    }
1628
  }
1629
  // Prevent multiple slashes to avoid cross site requests via the Form API.
1630
  $uri = '/' . ltrim($uri, '/');
1631

    
1632
  return $uri;
1633
}
1634

    
1635
/**
1636
 * Logs an exception.
1637
 *
1638
 * This is a wrapper function for watchdog() which automatically decodes an
1639
 * exception.
1640
 *
1641
 * @param $type
1642
 *   The category to which this message belongs.
1643
 * @param $exception
1644
 *   The exception that is going to be logged.
1645
 * @param $message
1646
 *   The message to store in the log. If empty, a text that contains all useful
1647
 *   information about the passed-in exception is used.
1648
 * @param $variables
1649
 *   Array of variables to replace in the message on display. Defaults to the
1650
 *   return value of _drupal_decode_exception().
1651
 * @param $severity
1652
 *   The severity of the message, as per RFC 3164.
1653
 * @param $link
1654
 *   A link to associate with the message.
1655
 *
1656
 * @see watchdog()
1657
 * @see _drupal_decode_exception()
1658
 */
1659
function watchdog_exception($type, Exception $exception, $message = NULL, $variables = array(), $severity = WATCHDOG_ERROR, $link = NULL) {
1660

    
1661
   // Use a default value if $message is not set.
1662
   if (empty($message)) {
1663
     // The exception message is run through check_plain() by _drupal_decode_exception().
1664
     $message = '%type: !message in %function (line %line of %file).';
1665
   }
1666
   // $variables must be an array so that we can add the exception information.
1667
   if (!is_array($variables)) {
1668
     $variables = array();
1669
   }
1670

    
1671
   require_once DRUPAL_ROOT . '/includes/errors.inc';
1672
   $variables += _drupal_decode_exception($exception);
1673
   watchdog($type, $message, $variables, $severity, $link);
1674
}
1675

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

    
1712
  static $in_error_state = FALSE;
1713

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

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

    
1722
    // Prepare the fields to be logged
1723
    $log_entry = array(
1724
      'type'        => $type,
1725
      'message'     => $message,
1726
      'variables'   => $variables,
1727
      'severity'    => $severity,
1728
      'link'        => $link,
1729
      'user'        => $user,
1730
      'uid'         => $user_uid,
1731
      'request_uri' => $base_root . request_uri(),
1732
      'referer'     => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
1733
      'ip'          => ip_address(),
1734
      // Request time isn't accurate for long processes, use time() instead.
1735
      'timestamp'   => time(),
1736
    );
1737

    
1738
    // Call the logging hooks to log/process the message
1739
    foreach (module_implements('watchdog') as $module) {
1740
      module_invoke($module, 'watchdog', $log_entry);
1741
    }
1742

    
1743
    // It is critical that the semaphore is only cleared here, in the parent
1744
    // watchdog() call (not outside the loop), to prevent recursive execution.
1745
    $in_error_state = FALSE;
1746
  }
1747
}
1748

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

    
1788
    if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
1789
      $_SESSION['messages'][$type][] = $message;
1790
    }
1791

    
1792
    // Mark this page as being uncacheable.
1793
    drupal_page_is_cacheable(FALSE);
1794
  }
1795

    
1796
  // Messages not set when DB connection fails.
1797
  return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
1798
}
1799

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

    
1845
/**
1846
 * Gets the title of the current page.
1847
 *
1848
 * The title is displayed on the page and in the title bar.
1849
 *
1850
 * @return
1851
 *   The current page's title.
1852
 */
1853
function drupal_get_title() {
1854
  $title = drupal_set_title();
1855

    
1856
  // During a bootstrap, menu.inc is not included and thus we cannot provide a title.
1857
  if (!isset($title) && function_exists('menu_get_active_title')) {
1858
    $title = check_plain(menu_get_active_title());
1859
  }
1860

    
1861
  return $title;
1862
}
1863

    
1864
/**
1865
 * Sets the title of the current page.
1866
 *
1867
 * The title is displayed on the page and in the title bar.
1868
 *
1869
 * @param $title
1870
 *   Optional string value to assign to the page title; or if set to NULL
1871
 *   (default), leaves the current title unchanged.
1872
 * @param $output
1873
 *   Optional flag - normally should be left as CHECK_PLAIN. Only set to
1874
 *   PASS_THROUGH if you have already removed any possibly dangerous code
1875
 *   from $title using a function like check_plain() or filter_xss(). With this
1876
 *   flag the string will be passed through unchanged.
1877
 *
1878
 * @return
1879
 *   The updated title of the current page.
1880
 */
1881
function drupal_set_title($title = NULL, $output = CHECK_PLAIN) {
1882
  $stored_title = &drupal_static(__FUNCTION__);
1883

    
1884
  if (isset($title)) {
1885
    $stored_title = ($output == PASS_THROUGH) ? $title : check_plain($title);
1886
  }
1887

    
1888
  return $stored_title;
1889
}
1890

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

    
1926
/**
1927
 * Handles denied users.
1928
 *
1929
 * @param $ip
1930
 *   IP address to check. Prints a message and exits if access is denied.
1931
 */
1932
function drupal_block_denied($ip) {
1933
  // Deny access to blocked IP addresses - t() is not yet available.
1934
  if (drupal_is_denied($ip)) {
1935
    header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
1936
    print 'Sorry, ' . check_plain(ip_address()) . ' has been banned.';
1937
    exit();
1938
  }
1939
}
1940

    
1941
/**
1942
 * Returns a URL-safe, base64 encoded string of highly randomized bytes (over the full 8-bit range).
1943
 *
1944
 * @param $byte_count
1945
 *   The number of random bytes to fetch and base64 encode.
1946
 *
1947
 * @return string
1948
 *   The base64 encoded result will have a length of up to 4 * $byte_count.
1949
 */
1950
function drupal_random_key($byte_count = 32) {
1951
  return drupal_base64_encode(drupal_random_bytes($byte_count));
1952
}
1953

    
1954
/**
1955
 * Returns a URL-safe, base64 encoded version of the supplied string.
1956
 *
1957
 * @param $string
1958
 *   The string to convert to base64.
1959
 *
1960
 * @return string
1961
 */
1962
function drupal_base64_encode($string) {
1963
  $data = base64_encode($string);
1964
  // Modify the output so it's safe to use in URLs.
1965
  return strtr($data, array('+' => '-', '/' => '_', '=' => ''));
1966
}
1967

    
1968
/**
1969
 * Returns a string of highly randomized bytes (over the full 8-bit range).
1970
 *
1971
 * This function is better than simply calling mt_rand() or any other built-in
1972
 * PHP function because it can return a long string of bytes (compared to < 4
1973
 * bytes normally from mt_rand()) and uses the best available pseudo-random
1974
 * source.
1975
 *
1976
 * @param $count
1977
 *   The number of characters (bytes) to return in the string.
1978
 */
1979
function drupal_random_bytes($count)  {
1980
  // $random_state does not use drupal_static as it stores random bytes.
1981
  static $random_state, $bytes, $has_openssl;
1982

    
1983
  $missing_bytes = $count - strlen($bytes);
1984

    
1985
  if ($missing_bytes > 0) {
1986
    // PHP versions prior 5.3.4 experienced openssl_random_pseudo_bytes()
1987
    // locking on Windows and rendered it unusable.
1988
    if (!isset($has_openssl)) {
1989
      $has_openssl = version_compare(PHP_VERSION, '5.3.4', '>=') && function_exists('openssl_random_pseudo_bytes');
1990
    }
1991

    
1992
    // openssl_random_pseudo_bytes() will find entropy in a system-dependent
1993
    // way.
1994
    if ($has_openssl) {
1995
      $bytes .= openssl_random_pseudo_bytes($missing_bytes);
1996
    }
1997

    
1998
    // Else, read directly from /dev/urandom, which is available on many *nix
1999
    // systems and is considered cryptographically secure.
2000
    elseif ($fh = @fopen('/dev/urandom', 'rb')) {
2001
      // PHP only performs buffered reads, so in reality it will always read
2002
      // at least 4096 bytes. Thus, it costs nothing extra to read and store
2003
      // that much so as to speed any additional invocations.
2004
      $bytes .= fread($fh, max(4096, $missing_bytes));
2005
      fclose($fh);
2006
    }
2007

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

    
2028
      do {
2029
        $random_state = hash('sha256', microtime() . mt_rand() . $random_state);
2030
        $bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
2031
      }
2032
      while (strlen($bytes) < $count);
2033
    }
2034
  }
2035
  $output = substr($bytes, 0, $count);
2036
  $bytes = substr($bytes, $count);
2037
  return $output;
2038
}
2039

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

    
2062
/**
2063
 * Calculates a base-64 encoded, URL-safe sha-256 hash.
2064
 *
2065
 * @param $data
2066
 *   String to be hashed.
2067
 *
2068
 * @return
2069
 *   A base-64 encoded sha-256 hash, with + replaced with -, / with _ and
2070
 *   any = padding characters removed.
2071
 */
2072
function drupal_hash_base64($data) {
2073
  $hash = base64_encode(hash('sha256', $data, TRUE));
2074
  // Modify the hash so it's safe to use in URLs.
2075
  return strtr($hash, array('+' => '-', '/' => '_', '=' => ''));
2076
}
2077

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

    
2110
/**
2111
 * Merges multiple arrays, recursively, and returns the merged array.
2112
 *
2113
 * This function is equivalent to drupal_array_merge_deep(), except the
2114
 * input arrays are passed as a single array parameter rather than a variable
2115
 * parameter list.
2116
 *
2117
 * The following are equivalent:
2118
 * - drupal_array_merge_deep($a, $b);
2119
 * - drupal_array_merge_deep_array(array($a, $b));
2120
 *
2121
 * The following are also equivalent:
2122
 * - call_user_func_array('drupal_array_merge_deep', $arrays_to_merge);
2123
 * - drupal_array_merge_deep_array($arrays_to_merge);
2124
 *
2125
 * @see drupal_array_merge_deep()
2126
 */
2127
function drupal_array_merge_deep_array($arrays) {
2128
  $result = array();
2129

    
2130
  foreach ($arrays as $array) {
2131
    foreach ($array as $key => $value) {
2132
      // Renumber integer keys as array_merge_recursive() does. Note that PHP
2133
      // automatically converts array keys that are integer strings (e.g., '1')
2134
      // to integers.
2135
      if (is_integer($key)) {
2136
        $result[] = $value;
2137
      }
2138
      // Recurse when both values are arrays.
2139
      elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
2140
        $result[$key] = drupal_array_merge_deep_array(array($result[$key], $value));
2141
      }
2142
      // Otherwise, use the latter value, overriding any previous value.
2143
      else {
2144
        $result[$key] = $value;
2145
      }
2146
    }
2147
  }
2148

    
2149
  return $result;
2150
}
2151

    
2152
/**
2153
 * Generates a default anonymous $user object.
2154
 *
2155
 * @return Object - the user object.
2156
 */
2157
function drupal_anonymous_user() {
2158
  $user = variable_get('drupal_anonymous_user_object', new stdClass);
2159
  $user->uid = 0;
2160
  $user->hostname = ip_address();
2161
  $user->roles = array();
2162
  $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
2163
  $user->cache = 0;
2164
  return $user;
2165
}
2166

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

    
2216
  if (isset($phase)) {
2217
    // When not recursing, store the phase name so it's not forgotten while
2218
    // recursing but take care of not going backwards.
2219
    if ($new_phase && $phase >= $stored_phase) {
2220
      $final_phase = $phase;
2221
    }
2222

    
2223
    // Call a phase if it has not been called before and is below the requested
2224
    // phase.
2225
    while ($phases && $phase > $stored_phase && $final_phase > $stored_phase) {
2226
      $current_phase = array_shift($phases);
2227

    
2228
      // This function is re-entrant. Only update the completed phase when the
2229
      // current call actually resulted in a progress in the bootstrap process.
2230
      if ($current_phase > $stored_phase) {
2231
        $stored_phase = $current_phase;
2232
      }
2233

    
2234
      switch ($current_phase) {
2235
        case DRUPAL_BOOTSTRAP_CONFIGURATION:
2236
          _drupal_bootstrap_configuration();
2237
          break;
2238

    
2239
        case DRUPAL_BOOTSTRAP_PAGE_CACHE:
2240
          _drupal_bootstrap_page_cache();
2241
          break;
2242

    
2243
        case DRUPAL_BOOTSTRAP_DATABASE:
2244
          _drupal_bootstrap_database();
2245
          break;
2246

    
2247
        case DRUPAL_BOOTSTRAP_VARIABLES:
2248
          _drupal_bootstrap_variables();
2249
          break;
2250

    
2251
        case DRUPAL_BOOTSTRAP_SESSION:
2252
          require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
2253
          drupal_session_initialize();
2254
          break;
2255

    
2256
        case DRUPAL_BOOTSTRAP_PAGE_HEADER:
2257
          _drupal_bootstrap_page_header();
2258
          break;
2259

    
2260
        case DRUPAL_BOOTSTRAP_LANGUAGE:
2261
          drupal_language_initialize();
2262
          break;
2263

    
2264
        case DRUPAL_BOOTSTRAP_FULL:
2265
          require_once DRUPAL_ROOT . '/includes/common.inc';
2266
          _drupal_bootstrap_full();
2267
          break;
2268
      }
2269
    }
2270
  }
2271
  return $stored_phase;
2272
}
2273

    
2274
/**
2275
 * Returns the time zone of the current user.
2276
 */
2277
function drupal_get_user_timezone() {
2278
  global $user;
2279
  if (variable_get('configurable_timezones', 1) && $user->uid && $user->timezone) {
2280
    return $user->timezone;
2281
  }
2282
  else {
2283
    // Ignore PHP strict notice if time zone has not yet been set in the php.ini
2284
    // configuration.
2285
    return variable_get('date_default_timezone', @date_default_timezone_get());
2286
  }
2287
}
2288

    
2289
/**
2290
 * Gets a salt useful for hardening against SQL injection.
2291
 *
2292
 * @return
2293
 *   A salt based on information in settings.php, not in the database.
2294
 */
2295
function drupal_get_hash_salt() {
2296
  global $drupal_hash_salt, $databases;
2297
  // If the $drupal_hash_salt variable is empty, a hash of the serialized
2298
  // database credentials is used as a fallback salt.
2299
  return empty($drupal_hash_salt) ? hash('sha256', serialize($databases)) : $drupal_hash_salt;
2300
}
2301

    
2302
/**
2303
 * Provides custom PHP error handling.
2304
 *
2305
 * @param $error_level
2306
 *   The level of the error raised.
2307
 * @param $message
2308
 *   The error message.
2309
 * @param $filename
2310
 *   The filename that the error was raised in.
2311
 * @param $line
2312
 *   The line number the error was raised at.
2313
 * @param $context
2314
 *   An array that points to the active symbol table at the point the error
2315
 *   occurred.
2316
 */
2317
function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
2318
  require_once DRUPAL_ROOT . '/includes/errors.inc';
2319
  _drupal_error_handler_real($error_level, $message, $filename, $line, $context);
2320
}
2321

    
2322
/**
2323
 * Provides custom PHP exception handling.
2324
 *
2325
 * Uncaught exceptions are those not enclosed in a try/catch block. They are
2326
 * always fatal: the execution of the script will stop as soon as the exception
2327
 * handler exits.
2328
 *
2329
 * @param $exception
2330
 *   The exception object that was thrown.
2331
 */
2332
function _drupal_exception_handler($exception) {
2333
  require_once DRUPAL_ROOT . '/includes/errors.inc';
2334

    
2335
  try {
2336
    // Log the message to the watchdog and return an error page to the user.
2337
    _drupal_log_error(_drupal_decode_exception($exception), TRUE);
2338
  }
2339
  catch (Exception $exception2) {
2340
    // Another uncaught exception was thrown while handling the first one.
2341
    // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
2342
    if (error_displayable()) {
2343
      print '<h1>Additional uncaught exception thrown while handling exception.</h1>';
2344
      print '<h2>Original</h2><p>' . _drupal_render_exception_safe($exception) . '</p>';
2345
      print '<h2>Additional</h2><p>' . _drupal_render_exception_safe($exception2) . '</p><hr />';
2346
    }
2347
  }
2348
}
2349

    
2350
/**
2351
 * Sets up the script environment and loads settings.php.
2352
 */
2353
function _drupal_bootstrap_configuration() {
2354
  // Set the Drupal custom error handler.
2355
  set_error_handler('_drupal_error_handler');
2356
  set_exception_handler('_drupal_exception_handler');
2357

    
2358
  drupal_environment_initialize();
2359
  // Start a page timer:
2360
  timer_start('page');
2361
  // Initialize the configuration, including variables from settings.php.
2362
  drupal_settings_initialize();
2363
}
2364

    
2365
/**
2366
 * Attempts to serve a page from the cache.
2367
 */
2368
function _drupal_bootstrap_page_cache() {
2369
  global $user;
2370

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

    
2421
/**
2422
 * Initializes the database system and registers autoload functions.
2423
 */
2424
function _drupal_bootstrap_database() {
2425
  // Redirect the user to the installation script if Drupal has not been
2426
  // installed yet (i.e., if no $databases array has been defined in the
2427
  // settings.php file) and we are not already installing.
2428
  if (empty($GLOBALS['databases']) && !drupal_installation_attempted()) {
2429
    include_once DRUPAL_ROOT . '/includes/install.inc';
2430
    install_goto('install.php');
2431
  }
2432

    
2433
  // The user agent header is used to pass a database prefix in the request when
2434
  // running tests. However, for security reasons, it is imperative that we
2435
  // validate we ourselves made the request.
2436
  if ($test_prefix = drupal_valid_test_ua()) {
2437
    // Set the test run id for use in other parts of Drupal.
2438
    $test_info = &$GLOBALS['drupal_test_info'];
2439
    $test_info['test_run_id'] = $test_prefix;
2440
    $test_info['in_child_site'] = TRUE;
2441

    
2442
    foreach ($GLOBALS['databases']['default'] as &$value) {
2443
      // Extract the current default database prefix.
2444
      if (!isset($value['prefix'])) {
2445
        $current_prefix = '';
2446
      }
2447
      elseif (is_array($value['prefix'])) {
2448
        $current_prefix = $value['prefix']['default'];
2449
      }
2450
      else {
2451
        $current_prefix = $value['prefix'];
2452
      }
2453

    
2454
      // Remove the current database prefix and replace it by our own.
2455
      $value['prefix'] = array(
2456
        'default' => $current_prefix . $test_prefix,
2457
      );
2458
    }
2459
  }
2460

    
2461
  // Initialize the database system. Note that the connection
2462
  // won't be initialized until it is actually requested.
2463
  require_once DRUPAL_ROOT . '/includes/database/database.inc';
2464

    
2465
  // Register autoload functions so that we can access classes and interfaces.
2466
  // The database autoload routine comes first so that we can load the database
2467
  // system without hitting the database. That is especially important during
2468
  // the install or upgrade process.
2469
  spl_autoload_register('drupal_autoload_class');
2470
  spl_autoload_register('drupal_autoload_interface');
2471
  if (version_compare(PHP_VERSION, '5.4') >= 0) {
2472
    spl_autoload_register('drupal_autoload_trait');
2473
  }
2474
}
2475

    
2476
/**
2477
 * Loads system variables and all enabled bootstrap modules.
2478
 */
2479
function _drupal_bootstrap_variables() {
2480
  global $conf;
2481

    
2482
  // Initialize the lock system.
2483
  require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
2484
  lock_initialize();
2485

    
2486
  // Load variables from the database, but do not overwrite variables set in settings.php.
2487
  $conf = variable_initialize(isset($conf) ? $conf : array());
2488
  // Load bootstrap modules.
2489
  require_once DRUPAL_ROOT . '/includes/module.inc';
2490
  module_load_all(TRUE);
2491

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

    
2513
/**
2514
 * Invokes hook_boot(), initializes locking system, and sends HTTP headers.
2515
 */
2516
function _drupal_bootstrap_page_header() {
2517
  bootstrap_invoke_all('boot');
2518

    
2519
  if (!drupal_is_cli()) {
2520
    ob_start();
2521
    drupal_page_header();
2522
  }
2523
}
2524

    
2525
/**
2526
 * Returns the current bootstrap phase for this Drupal process.
2527
 *
2528
 * The current phase is the one most recently completed by drupal_bootstrap().
2529
 *
2530
 * @see drupal_bootstrap()
2531
 */
2532
function drupal_get_bootstrap_phase() {
2533
  return drupal_bootstrap(NULL, FALSE);
2534
}
2535

    
2536
/**
2537
 * Returns the test prefix if this is an internal request from SimpleTest.
2538
 *
2539
 * @return
2540
 *   Either the simpletest prefix (the string "simpletest" followed by any
2541
 *   number of digits) or FALSE if the user agent does not contain a valid
2542
 *   HMAC and timestamp.
2543
 */
2544
function drupal_valid_test_ua() {
2545
  // No reason to reset this.
2546
  static $test_prefix;
2547

    
2548
  if (isset($test_prefix)) {
2549
    return $test_prefix;
2550
  }
2551

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

    
2568
  $test_prefix = FALSE;
2569
  return $test_prefix;
2570
}
2571

    
2572
/**
2573
 * Generates a user agent string with a HMAC and timestamp for simpletest.
2574
 */
2575
function drupal_generate_test_ua($prefix) {
2576
  static $key;
2577

    
2578
  if (!isset($key)) {
2579
    // We use the salt from settings.php to make the HMAC key, since
2580
    // the database is not yet initialized and we can't access any Drupal variables.
2581
    // The file properties add more entropy not easily accessible to others.
2582
    $key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
2583
  }
2584
  // Generate a moderately secure HMAC based on the database credentials.
2585
  $salt = uniqid('', TRUE);
2586
  $check_string = $prefix . ';' . time() . ';' . $salt;
2587
  return $check_string . ';' . drupal_hmac_base64($check_string, $key);
2588
}
2589

    
2590
/**
2591
 * Enables use of the theme system without requiring database access.
2592
 *
2593
 * Loads and initializes the theme system for site installs, updates and when
2594
 * the site is in maintenance mode. This also applies when the database fails.
2595
 *
2596
 * @see _drupal_maintenance_theme()
2597
 */
2598
function drupal_maintenance_theme() {
2599
  require_once DRUPAL_ROOT . '/includes/theme.maintenance.inc';
2600
  _drupal_maintenance_theme();
2601
}
2602

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

    
2631
/**
2632
 * Returns TRUE if a Drupal installation is currently being attempted.
2633
 */
2634
function drupal_installation_attempted() {
2635
  return defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'install';
2636
}
2637

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

    
2674
/**
2675
 * Initializes all the defined language types.
2676
 */
2677
function drupal_language_initialize() {
2678
  $types = language_types();
2679

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

    
2699
/**
2700
 * Returns a list of the built-in language types.
2701
 *
2702
 * @return
2703
 *   An array of key-values pairs where the key is the language type and the
2704
 *   value is its configurability.
2705
 */
2706
function drupal_language_types() {
2707
  return array(
2708
    LANGUAGE_TYPE_INTERFACE => TRUE,
2709
    LANGUAGE_TYPE_CONTENT => FALSE,
2710
    LANGUAGE_TYPE_URL => FALSE,
2711
  );
2712
}
2713

    
2714
/**
2715
 * Returns TRUE if there is more than one language enabled.
2716
 *
2717
 * @return
2718
 *   TRUE if more than one language is enabled.
2719
 */
2720
function drupal_multilingual() {
2721
  // The "language_count" variable stores the number of enabled languages to
2722
  // avoid unnecessarily querying the database when building the list of
2723
  // enabled languages on monolingual sites.
2724
  return variable_get('language_count', 1) > 1;
2725
}
2726

    
2727
/**
2728
 * Returns an array of the available language types.
2729
 *
2730
 * @return
2731
 *   An array of all language types where the keys of each are the language type
2732
 *   name and its value is its configurability (TRUE/FALSE).
2733
 */
2734
function language_types() {
2735
  return array_keys(variable_get('language_types', drupal_language_types()));
2736
}
2737

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

    
2772
  // Return the array indexed by the right field
2773
  if (!isset($languages[$field])) {
2774
    $languages[$field] = array();
2775
    foreach ($languages['language'] as $lang) {
2776
      // Some values should be collected into an array
2777
      if (in_array($field, array('enabled', 'weight'))) {
2778
        $languages[$field][$lang->$field][$lang->language] = $lang;
2779
      }
2780
      else {
2781
        $languages[$field][$lang->$field] = $lang;
2782
      }
2783
    }
2784
  }
2785
  return $languages[$field];
2786
}
2787

    
2788
/**
2789
 * Returns the default language used on the site
2790
 *
2791
 * @param $property
2792
 *   Optional property of the language object to return
2793
 */
2794
function language_default($property = NULL) {
2795
  $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' => ''));
2796
  return $property ? $language->$property : $language;
2797
}
2798

    
2799
/**
2800
 * Returns the requested URL path of the page being viewed.
2801
 *
2802
 * Examples:
2803
 * - http://example.com/node/306 returns "node/306".
2804
 * - http://example.com/drupalfolder/node/306 returns "node/306" while
2805
 *   base_path() returns "/drupalfolder/".
2806
 * - http://example.com/path/alias (which is a path alias for node/306) returns
2807
 *   "path/alias" as opposed to the internal path.
2808
 * - http://example.com/index.php returns an empty string (meaning: front page).
2809
 * - http://example.com/index.php?page=1 returns an empty string.
2810
 *
2811
 * @return
2812
 *   The requested Drupal URL path.
2813
 *
2814
 * @see current_path()
2815
 */
2816
function request_path() {
2817
  static $path;
2818

    
2819
  if (isset($path)) {
2820
    return $path;
2821
  }
2822

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

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

    
2855
  return $path;
2856
}
2857

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

    
2893
  if (!isset($path)) {
2894
    $path = $_GET['q'];
2895
  }
2896
  if (!isset($arguments[$path])) {
2897
    $arguments[$path] = explode('/', $path);
2898
  }
2899
  if (!isset($index)) {
2900
    return $arguments[$path];
2901
  }
2902
  if (isset($arguments[$path][$index])) {
2903
    return $arguments[$path][$index];
2904
  }
2905
}
2906

    
2907
/**
2908
 * Returns the IP address of the client machine.
2909
 *
2910
 * If Drupal is behind a reverse proxy, we use the X-Forwarded-For header
2911
 * instead of $_SERVER['REMOTE_ADDR'], which would be the IP address of
2912
 * the proxy server, and not the client's. The actual header name can be
2913
 * configured by the reverse_proxy_header variable.
2914
 *
2915
 * @return
2916
 *   IP address of client machine, adjusted for reverse proxy and/or cluster
2917
 *   environments.
2918
 */
2919
function ip_address() {
2920
  $ip_address = &drupal_static(__FUNCTION__);
2921

    
2922
  if (!isset($ip_address)) {
2923
    $ip_address = $_SERVER['REMOTE_ADDR'];
2924

    
2925
    if (variable_get('reverse_proxy', 0)) {
2926
      $reverse_proxy_header = variable_get('reverse_proxy_header', 'HTTP_X_FORWARDED_FOR');
2927
      if (!empty($_SERVER[$reverse_proxy_header])) {
2928
        // If an array of known reverse proxy IPs is provided, then trust
2929
        // the XFF header if request really comes from one of them.
2930
        $reverse_proxy_addresses = variable_get('reverse_proxy_addresses', array());
2931

    
2932
        // Turn XFF header into an array.
2933
        $forwarded = explode(',', $_SERVER[$reverse_proxy_header]);
2934

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

    
2938
        // Tack direct client IP onto end of forwarded array.
2939
        $forwarded[] = $ip_address;
2940

    
2941
        // Eliminate all trusted IPs.
2942
        $untrusted = array_diff($forwarded, $reverse_proxy_addresses);
2943

    
2944
        // The right-most IP is the most specific we can trust.
2945
        $ip_address = array_pop($untrusted);
2946
      }
2947
    }
2948
  }
2949

    
2950
  return $ip_address;
2951
}
2952

    
2953
/**
2954
 * @addtogroup schemaapi
2955
 * @{
2956
 */
2957

    
2958
/**
2959
 * Gets the schema definition of a table, or the whole database schema.
2960
 *
2961
 * The returned schema will include any modifications made by any
2962
 * module that implements hook_schema_alter(). To get the schema without
2963
 * modifications, use drupal_get_schema_unprocessed().
2964
 *
2965
 *
2966
 * @param $table
2967
 *   The name of the table. If not given, the schema of all tables is returned.
2968
 * @param $rebuild
2969
 *   If true, the schema will be rebuilt instead of retrieved from the cache.
2970
 */
2971
function drupal_get_schema($table = NULL, $rebuild = FALSE) {
2972
  static $schema;
2973

    
2974
  if ($rebuild || !isset($table)) {
2975
    $schema = drupal_get_complete_schema($rebuild);
2976
  }
2977
  elseif (!isset($schema)) {
2978
    $schema = new SchemaCache();
2979
  }
2980

    
2981
  if (!isset($table)) {
2982
    return $schema;
2983
  }
2984
  if (isset($schema[$table])) {
2985
    return $schema[$table];
2986
  }
2987
  else {
2988
    return FALSE;
2989
  }
2990
}
2991

    
2992
/**
2993
 * Extends DrupalCacheArray to allow for dynamic building of the schema cache.
2994
 */
2995
class SchemaCache extends DrupalCacheArray {
2996

    
2997
  /**
2998
   * Constructs a SchemaCache object.
2999
   */
3000
  public function __construct() {
3001
    // Cache by request method.
3002
    parent::__construct('schema:runtime:' . ($_SERVER['REQUEST_METHOD'] == 'GET'), 'cache');
3003
  }
3004

    
3005
  /**
3006
   * Overrides DrupalCacheArray::resolveCacheMiss().
3007
   */
3008
  protected function resolveCacheMiss($offset) {
3009
    $complete_schema = drupal_get_complete_schema();
3010
    $value = isset($complete_schema[$offset]) ? $complete_schema[$offset] :  NULL;
3011
    $this->storage[$offset] = $value;
3012
    $this->persist($offset);
3013
    return $value;
3014
  }
3015
}
3016

    
3017
/**
3018
 * Gets the whole database schema.
3019
 *
3020
 * The returned schema will include any modifications made by any
3021
 * module that implements hook_schema_alter().
3022
 *
3023
 * @param $rebuild
3024
 *   If true, the schema will be rebuilt instead of retrieved from the cache.
3025
 */
3026
function drupal_get_complete_schema($rebuild = FALSE) {
3027
  static $schema = array();
3028

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

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

    
3062
      drupal_alter('schema', $schema);
3063
      // If the schema is empty, avoid saving it: some database engines require
3064
      // the schema to perform queries, and this could lead to infinite loops.
3065
      if (!empty($schema) && (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL)) {
3066
        cache_set('schema', $schema);
3067
      }
3068
      if ($rebuild) {
3069
        cache_clear_all('schema:', 'cache', TRUE);
3070
      }
3071
    }
3072
  }
3073

    
3074
  return $schema;
3075
}
3076

    
3077
/**
3078
 * @} End of "addtogroup schemaapi".
3079
 */
3080

    
3081

    
3082
/**
3083
 * @addtogroup registry
3084
 * @{
3085
 */
3086

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

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

    
3119
/**
3120
 * Confirms that a trait is available.
3121
 *
3122
 * This function is rarely called directly. Instead, it is registered as an
3123
 * spl_autoload() handler, and PHP calls it for us when necessary.
3124
 *
3125
 * @param string $trait
3126
 *   The name of the trait to check or load.
3127
 *
3128
 * @return bool
3129
 *   TRUE if the trait is currently available, FALSE otherwise.
3130
 */
3131
function drupal_autoload_trait($trait) {
3132
  return _registry_check_code('trait', $trait);
3133
}
3134

    
3135
/**
3136
 * Checks for a resource in the registry.
3137
 *
3138
 * @param $type
3139
 *   The type of resource we are looking up, or one of the constants
3140
 *   REGISTRY_RESET_LOOKUP_CACHE or REGISTRY_WRITE_LOOKUP_CACHE, which
3141
 *   signal that we should reset or write the cache, respectively.
3142
 * @param $name
3143
 *   The name of the resource, or NULL if either of the REGISTRY_* constants
3144
 *   is passed in.
3145
 *
3146
 * @return
3147
 *   TRUE if the resource was found, FALSE if not.
3148
 *   NULL if either of the REGISTRY_* constants is passed in as $type.
3149
 */
3150
function _registry_check_code($type, $name = NULL) {
3151
  static $lookup_cache, $cache_update_needed;
3152

    
3153
  if ($type == 'class' && class_exists($name) || $type == 'interface' && interface_exists($name) || $type == 'trait' && trait_exists($name)) {
3154
    return TRUE;
3155
  }
3156

    
3157
  if (!isset($lookup_cache)) {
3158
    $lookup_cache = array();
3159
    if ($cache = cache_get('lookup_cache', 'cache_bootstrap')) {
3160
      $lookup_cache = $cache->data;
3161
    }
3162
  }
3163

    
3164
  // When we rebuild the registry, we need to reset this cache so
3165
  // we don't keep lookups for resources that changed during the rebuild.
3166
  if ($type == REGISTRY_RESET_LOOKUP_CACHE) {
3167
    $cache_update_needed = TRUE;
3168
    $lookup_cache = NULL;
3169
    return;
3170
  }
3171

    
3172
  // Called from drupal_page_footer, we write to permanent storage if there
3173
  // changes to the lookup cache for this request.
3174
  if ($type == REGISTRY_WRITE_LOOKUP_CACHE) {
3175
    if ($cache_update_needed) {
3176
      cache_set('lookup_cache', $lookup_cache, 'cache_bootstrap');
3177
    }
3178
    return;
3179
  }
3180

    
3181
  // $type is either 'interface' or 'class', so we only need the first letter to
3182
  // keep the cache key unique.
3183
  $cache_key = $type[0] . $name;
3184
  if (isset($lookup_cache[$cache_key])) {
3185
    if ($lookup_cache[$cache_key]) {
3186
      require_once DRUPAL_ROOT . '/' . $lookup_cache[$cache_key];
3187
    }
3188
    return (bool) $lookup_cache[$cache_key];
3189
  }
3190

    
3191
  // This function may get called when the default database is not active, but
3192
  // there is no reason we'd ever want to not use the default database for
3193
  // this query.
3194
  $file = Database::getConnection('default', 'default')
3195
    ->select('registry', 'r', array('target' => 'default'))
3196
    ->fields('r', array('filename'))
3197
    // Use LIKE here to make the query case-insensitive.
3198
    ->condition('r.name', db_like($name), 'LIKE')
3199
    ->condition('r.type', $type)
3200
    ->execute()
3201
    ->fetchField();
3202

    
3203
  // Flag that we've run a lookup query and need to update the cache.
3204
  $cache_update_needed = TRUE;
3205

    
3206
  // Misses are valuable information worth caching, so cache even if
3207
  // $file is FALSE.
3208
  $lookup_cache[$cache_key] = $file;
3209

    
3210
  if ($file) {
3211
    require_once DRUPAL_ROOT . '/' . $file;
3212
    return TRUE;
3213
  }
3214
  else {
3215
    return FALSE;
3216
  }
3217
}
3218

    
3219
/**
3220
 * Rescans all enabled modules and rebuilds the registry.
3221
 *
3222
 * Rescans all code in modules or includes directories, storing the location of
3223
 * each interface or class in the database.
3224
 */
3225
function registry_rebuild() {
3226
  system_rebuild_module_data();
3227
  registry_update();
3228
}
3229

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

    
3254
  require_once DRUPAL_ROOT . '/includes/registry.inc';
3255
  _registry_update();
3256

    
3257
  if (!$in_installer) {
3258
    lock_release(__FUNCTION__);
3259
  }
3260
  return TRUE;
3261
}
3262

    
3263
/**
3264
 * @} End of "addtogroup registry".
3265
 */
3266

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

    
3416
/**
3417
 * Resets one or all centrally stored static variable(s).
3418
 *
3419
 * @param $name
3420
 *   Name of the static variable to reset. Omit to reset all variables.
3421
 *   Resetting all variables should only be used, for example, for running unit
3422
 *   tests with a clean environment.
3423
 */
3424
function drupal_static_reset($name = NULL) {
3425
  drupal_static($name, NULL, TRUE);
3426
}
3427

    
3428
/**
3429
 * Detects whether the current script is running in a command-line environment.
3430
 */
3431
function drupal_is_cli() {
3432
  return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
3433
}
3434

    
3435
/**
3436
 * Formats text for emphasized display in a placeholder inside a sentence.
3437
 *
3438
 * Used automatically by format_string().
3439
 *
3440
 * @param $text
3441
 *   The text to format (plain-text).
3442
 *
3443
 * @return
3444
 *   The formatted text (html).
3445
 */
3446
function drupal_placeholder($text) {
3447
  return '<em class="placeholder">' . check_plain($text) . '</em>';
3448
}
3449

    
3450
/**
3451
 * Registers a function for execution on shutdown.
3452
 *
3453
 * Wrapper for register_shutdown_function() that catches thrown exceptions to
3454
 * avoid "Exception thrown without a stack frame in Unknown".
3455
 *
3456
 * @param $callback
3457
 *   The shutdown function to register.
3458
 * @param ...
3459
 *   Additional arguments to pass to the shutdown function.
3460
 *
3461
 * @return
3462
 *   Array of shutdown functions to be executed.
3463
 *
3464
 * @see register_shutdown_function()
3465
 * @ingroup php_wrappers
3466
 */
3467
function &drupal_register_shutdown_function($callback = NULL) {
3468
  // We cannot use drupal_static() here because the static cache is reset during
3469
  // batch processing, which breaks batch handling.
3470
  static $callbacks = array();
3471

    
3472
  if (isset($callback)) {
3473
    // Only register the internal shutdown function once.
3474
    if (empty($callbacks)) {
3475
      register_shutdown_function('_drupal_shutdown_function');
3476
    }
3477
    $args = func_get_args();
3478
    array_shift($args);
3479
    // Save callback and arguments
3480
    $callbacks[] = array('callback' => $callback, 'arguments' => $args);
3481
  }
3482
  return $callbacks;
3483
}
3484

    
3485
/**
3486
 * Executes registered shutdown functions.
3487
 */
3488
function _drupal_shutdown_function() {
3489
  $callbacks = &drupal_register_shutdown_function();
3490

    
3491
  // Set the CWD to DRUPAL_ROOT as it is not guaranteed to be the same as it
3492
  // was in the normal context of execution.
3493
  chdir(DRUPAL_ROOT);
3494

    
3495
  try {
3496
    while (list($key, $callback) = each($callbacks)) {
3497
      call_user_func_array($callback['callback'], $callback['arguments']);
3498
    }
3499
  }
3500
  catch (Exception $exception) {
3501
    // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
3502
   require_once DRUPAL_ROOT . '/includes/errors.inc';
3503
   if (error_displayable()) {
3504
      print '<h1>Uncaught exception thrown in shutdown function.</h1>';
3505
      print '<p>' . _drupal_render_exception_safe($exception) . '</p><hr />';
3506
    }
3507
  }
3508
}
3509

    
3510
/**
3511
 * Compares the memory required for an operation to the available memory.
3512
 *
3513
 * @param $required
3514
 *   The memory required for the operation, expressed as a number of bytes with
3515
 *   optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8bytes,
3516
 *   9mbytes).
3517
 * @param $memory_limit
3518
 *   (optional) The memory limit for the operation, expressed as a number of
3519
 *   bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G,
3520
 *   6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP
3521
 *   memory_limit will be used. Defaults to NULL.
3522
 *
3523
 * @return
3524
 *   TRUE if there is sufficient memory to allow the operation, or FALSE
3525
 *   otherwise.
3526
 */
3527
function drupal_check_memory_limit($required, $memory_limit = NULL) {
3528
  if (!isset($memory_limit)) {
3529
    $memory_limit = ini_get('memory_limit');
3530
  }
3531

    
3532
  // There is sufficient memory if:
3533
  // - No memory limit is set.
3534
  // - The memory limit is set to unlimited (-1).
3535
  // - The memory limit is greater than the memory required for the operation.
3536
  return ((!$memory_limit) || ($memory_limit == -1) || (parse_size($memory_limit) >= parse_size($required)));
3537
}
3538

    
3539
/**
3540
 * Invalidates a PHP file from any active opcode caches.
3541
 *
3542
 * If the opcode cache does not support the invalidation of individual files,
3543
 * the entire cache will be flushed.
3544
 *
3545
 * @param string $filepath
3546
 *   The absolute path of the PHP file to invalidate.
3547
 */
3548
function drupal_clear_opcode_cache($filepath) {
3549
  if (!defined('PHP_VERSION_ID') || PHP_VERSION_ID < 50300) {
3550
    // Below PHP 5.3, clearstatcache does not accept any function parameters.
3551
    clearstatcache();
3552
  }
3553
  else {
3554
    clearstatcache(TRUE, $filepath);
3555
  }
3556

    
3557
  // Zend OPcache.
3558
  if (function_exists('opcache_invalidate')) {
3559
    opcache_invalidate($filepath, TRUE);
3560
  }
3561
  // APC.
3562
  if (function_exists('apc_delete_file')) {
3563
    // apc_delete_file() throws a PHP warning in case the specified file was
3564
    // not compiled yet.
3565
    // @see http://php.net/apc-delete-file
3566
    @apc_delete_file($filepath);
3567
  }
3568
}