source: sipes/cord/includes/bootstrap.inc @ 52861f4

stableversion-3.0
Last change on this file since 52861f4 was d7a822e, checked in by José Gregorio Puentes <jpuentes@…>, 8 años ago

se agrego el directorio del cord

  • Propiedad mode establecida a 100755
File size: 45.4 KB
Línea 
1<?php
2
3/**
4 * @file
5 * Functions that need to be loaded on every Drupal request.
6 */
7
8/**
9 * Indicates that the item should never be removed unless explicitly told to
10 * using cache_clear_all() with a cache ID.
11 */
12define('CACHE_PERMANENT', 0);
13
14/**
15 * Indicates that the item should be removed at the next general cache wipe.
16 */
17define('CACHE_TEMPORARY', -1);
18
19/**
20 * Indicates that page caching is disabled.
21 */
22define('CACHE_DISABLED', 0);
23
24/**
25 * Indicates that page caching is enabled, using "normal" mode.
26 */
27define('CACHE_NORMAL', 1);
28
29/**
30 * Indicates that page caching is using "aggressive" mode. This bypasses
31 * loading any modules for additional speed, which may break functionality in
32 * modules that expect to be run on each page load.
33 */
34define('CACHE_AGGRESSIVE', 2);
35
36/**
37 * Log message severity -- Emergency: system is unusable.
38 *
39 * The WATCHDOG_* constant definitions correspond to the logging severity levels
40 * defined in RFC 3164, section 4.1.1: http://www.faqs.org/rfcs/rfc3164.html
41 *
42 * @see watchdog()
43 * @see watchdog_severity_levels()
44 */
45define('WATCHDOG_EMERG', 0);
46
47/**
48 * Log message severity -- Alert: action must be taken immediately.
49 *
50 * The WATCHDOG_* constant definitions correspond to the logging severity levels
51 * defined in RFC 3164, section 4.1.1: http://www.faqs.org/rfcs/rfc3164.html
52 *
53 * @see watchdog()
54 * @see watchdog_severity_levels()
55 */
56define('WATCHDOG_ALERT', 1);
57
58/**
59 * Log message severity -- Critical: critical conditions.
60 *
61 * The WATCHDOG_* constant definitions correspond to the logging severity levels
62 * defined in RFC 3164, section 4.1.1: http://www.faqs.org/rfcs/rfc3164.html
63 *
64 * @see watchdog()
65 * @see watchdog_severity_levels()
66 */
67define('WATCHDOG_CRITICAL', 2);
68
69/**
70 * Log message severity -- Error: error conditions.
71 *
72 * The WATCHDOG_* constant definitions correspond to the logging severity levels
73 * defined in RFC 3164, section 4.1.1: http://www.faqs.org/rfcs/rfc3164.html
74 *
75 * @see watchdog()
76 * @see watchdog_severity_levels()
77 */
78define('WATCHDOG_ERROR', 3);
79
80/**
81 * Log message severity -- Warning: warning conditions.
82 *
83 * The WATCHDOG_* constant definitions correspond to the logging severity levels
84 * defined in RFC 3164, section 4.1.1: http://www.faqs.org/rfcs/rfc3164.html
85 *
86 * @see watchdog()
87 * @see watchdog_severity_levels()
88 */
89define('WATCHDOG_WARNING', 4);
90
91/**
92 * Log message severity -- Notice: normal but significant condition.
93 *
94 * The WATCHDOG_* constant definitions correspond to the logging severity levels
95 * defined in RFC 3164, section 4.1.1: http://www.faqs.org/rfcs/rfc3164.html
96 *
97 * @see watchdog()
98 * @see watchdog_severity_levels()
99 */
100define('WATCHDOG_NOTICE', 5);
101
102/**
103 * Log message severity -- Informational: informational messages.
104 *
105 * The WATCHDOG_* constant definitions correspond to the logging severity levels
106 * defined in RFC 3164, section 4.1.1: http://www.faqs.org/rfcs/rfc3164.html
107 *
108 * @see watchdog()
109 * @see watchdog_severity_levels()
110 */
111define('WATCHDOG_INFO', 6);
112
113/**
114 * Log message severity -- Debug: debug-level messages.
115 *
116 * The WATCHDOG_* constant definitions correspond to the logging severity levels
117 * defined in RFC 3164, section 4.1.1: http://www.faqs.org/rfcs/rfc3164.html
118 *
119 * @see watchdog()
120 * @see watchdog_severity_levels()
121 */
122define('WATCHDOG_DEBUG', 7);
123
124/**
125 * First bootstrap phase: initialize configuration.
126 */
127define('DRUPAL_BOOTSTRAP_CONFIGURATION', 0);
128
129/**
130 * Second bootstrap phase: try to call a non-database cache
131 * fetch routine.
132 */
133define('DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE', 1);
134
135/**
136 * Third bootstrap phase: initialize database layer.
137 */
138define('DRUPAL_BOOTSTRAP_DATABASE', 2);
139
140/**
141 * Fourth bootstrap phase: identify and reject banned hosts.
142 */
143define('DRUPAL_BOOTSTRAP_ACCESS', 3);
144
145/**
146 * Fifth bootstrap phase: initialize session handling.
147 */
148define('DRUPAL_BOOTSTRAP_SESSION', 4);
149
150/**
151 * Sixth bootstrap phase: load bootstrap.inc and module.inc, start
152 * the variable system and try to serve a page from the cache.
153 */
154define('DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE', 5);
155
156/**
157 * Seventh bootstrap phase: find out language of the page.
158 */
159define('DRUPAL_BOOTSTRAP_LANGUAGE', 6);
160
161/**
162 * Eighth bootstrap phase: set $_GET['q'] to Drupal path of request.
163 */
164define('DRUPAL_BOOTSTRAP_PATH', 7);
165
166/**
167 * Final bootstrap phase: Drupal is fully loaded; validate and fix
168 * input data.
169 */
170define('DRUPAL_BOOTSTRAP_FULL', 8);
171
172/**
173 * Role ID for anonymous users; should match what's in the "role" table.
174 */
175define('DRUPAL_ANONYMOUS_RID', 1);
176
177/**
178 * Role ID for authenticated users; should match what's in the "role" table.
179 */
180define('DRUPAL_AUTHENTICATED_RID', 2);
181
182/**
183 * No language negotiation. The default language is used.
184 */
185define('LANGUAGE_NEGOTIATION_NONE', 0);
186
187/**
188 * Path based negotiation with fallback to default language
189 * if no defined path prefix identified.
190 */
191define('LANGUAGE_NEGOTIATION_PATH_DEFAULT', 1);
192
193/**
194 * Path based negotiation with fallback to user preferences
195 * and browser language detection if no defined path prefix
196 * identified.
197 */
198define('LANGUAGE_NEGOTIATION_PATH', 2);
199
200/**
201 * Domain based negotiation with fallback to default language
202 * if no language identified by domain.
203 */
204define('LANGUAGE_NEGOTIATION_DOMAIN', 3);
205
206/**
207 * Language written left to right. Possible value of $language->direction.
208 */
209define('LANGUAGE_LTR', 0);
210
211/**
212 * Language written right to left. Possible value of $language->direction.
213 */
214define('LANGUAGE_RTL', 1);
215
216// Hide E_DEPRECATED messages.
217if (defined('E_DEPRECATED')) {
218  error_reporting(error_reporting() & ~E_DEPRECATED);
219}
220
221/**
222 * Start the timer with the specified name. If you start and stop
223 * the same timer multiple times, the measured intervals will be
224 * accumulated.
225 *
226 * @param name
227 *   The name of the timer.
228 */
229function timer_start($name) {
230  global $timers;
231
232  list($usec, $sec) = explode(' ', microtime());
233  $timers[$name]['start'] = (float)$usec + (float)$sec;
234  $timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
235}
236
237/**
238 * Read the current timer value without stopping the timer.
239 *
240 * @param name
241 *   The name of the timer.
242 * @return
243 *   The current timer value in ms.
244 */
245function timer_read($name) {
246  global $timers;
247
248  if (isset($timers[$name]['start'])) {
249    list($usec, $sec) = explode(' ', microtime());
250    $stop = (float)$usec + (float)$sec;
251    $diff = round(($stop - $timers[$name]['start']) * 1000, 2);
252
253    if (isset($timers[$name]['time'])) {
254      $diff += $timers[$name]['time'];
255    }
256    return $diff;
257  }
258}
259
260/**
261 * Stop the timer with the specified name.
262 *
263 * @param name
264 *   The name of the timer.
265 * @return
266 *   A timer array. The array contains the number of times the
267 *   timer has been started and stopped (count) and the accumulated
268 *   timer value in ms (time).
269 */
270function timer_stop($name) {
271  global $timers;
272
273  $timers[$name]['time'] = timer_read($name);
274  unset($timers[$name]['start']);
275
276  return $timers[$name];
277}
278
279/**
280 * Find the appropriate configuration directory.
281 *
282 * Try finding a matching configuration directory by stripping the website's
283 * hostname from left to right and pathname from right to left. The first
284 * configuration file found will be used; the remaining will ignored. If no
285 * configuration file is found, return a default value '$confdir/default'.
286 *
287 * Example for a fictitious site installed at
288 * http://www.drupal.org:8080/mysite/test/ the 'settings.php' is searched in
289 * the following directories:
290 *
291 *  1. $confdir/8080.www.drupal.org.mysite.test
292 *  2. $confdir/www.drupal.org.mysite.test
293 *  3. $confdir/drupal.org.mysite.test
294 *  4. $confdir/org.mysite.test
295 *
296 *  5. $confdir/8080.www.drupal.org.mysite
297 *  6. $confdir/www.drupal.org.mysite
298 *  7. $confdir/drupal.org.mysite
299 *  8. $confdir/org.mysite
300 *
301 *  9. $confdir/8080.www.drupal.org
302 * 10. $confdir/www.drupal.org
303 * 11. $confdir/drupal.org
304 * 12. $confdir/org
305 *
306 * 13. $confdir/default
307 *
308 * @param $require_settings
309 *   Only configuration directories with an existing settings.php file
310 *   will be recognized. Defaults to TRUE. During initial installation,
311 *   this is set to FALSE so that Drupal can detect a matching directory,
312 *   then create a new settings.php file in it.
313 * @param reset
314 *   Force a full search for matching directories even if one had been
315 *   found previously.
316 * @return
317 *   The path of the matching directory.
318 */
319function conf_path($require_settings = TRUE, $reset = FALSE) {
320  static $conf = '';
321
322  if ($conf && !$reset) {
323    return $conf;
324  }
325
326  $confdir = 'sites';
327  $uri = explode('/', $_SERVER['SCRIPT_NAME'] ? $_SERVER['SCRIPT_NAME'] : $_SERVER['SCRIPT_FILENAME']);
328  $server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
329  for ($i = count($uri) - 1; $i > 0; $i--) {
330    for ($j = count($server); $j > 0; $j--) {
331      $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
332      if (file_exists("$confdir/$dir/settings.php") || (!$require_settings && file_exists("$confdir/$dir"))) {
333        $conf = "$confdir/$dir";
334        return $conf;
335      }
336    }
337  }
338  $conf = "$confdir/default";
339  return $conf;
340}
341
342/**
343 * Unsets all disallowed global variables. See $allowed for what's allowed.
344 */
345function drupal_unset_globals() {
346  if (ini_get('register_globals')) {
347    $allowed = array('_ENV' => 1, '_GET' => 1, '_POST' => 1, '_COOKIE' => 1, '_FILES' => 1, '_SERVER' => 1, '_REQUEST' => 1, 'GLOBALS' => 1);
348    foreach ($GLOBALS as $key => $value) {
349      if (!isset($allowed[$key])) {
350        unset($GLOBALS[$key]);
351      }
352    }
353  }
354}
355
356/**
357 * Validate that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
358 *
359 * As $_SERVER['HTTP_HOST'] is user input, ensure it only contains characters
360 * allowed in hostnames.  See RFC 952 (and RFC 2181). $_SERVER['HTTP_HOST'] is
361 * lowercased.
362 *
363 * @return
364 *  TRUE if only containing valid characters, or FALSE otherwise.
365 */
366function drupal_valid_http_host($host) {
367  return preg_match('/^\[?(?:[a-z0-9-:\]_]+\.?)+$/', $host);
368}
369
370/**
371 * Loads the configuration and sets the base URL, cookie domain, and
372 * session name correctly.
373 */
374function conf_init() {
375  global $base_url, $base_path, $base_root;
376
377  // Export the following settings.php variables to the global namespace
378  global $db_url, $db_prefix, $db_collation, $cookie_domain, $conf, $installed_profile, $update_free_access;
379  $conf = array();
380
381  if (!isset($_SERVER['SERVER_PROTOCOL']) || ($_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.0' && $_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.1')) {
382    $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
383  }
384
385  if (isset($_SERVER['HTTP_HOST'])) {
386    // As HTTP_HOST is user input, ensure it only contains characters allowed
387    // in hostnames. See RFC 952 (and RFC 2181).
388    // $_SERVER['HTTP_HOST'] is lowercased here per specifications.
389    $_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']);
390    if (!drupal_valid_http_host($_SERVER['HTTP_HOST'])) {
391      // HTTP_HOST is invalid, e.g. if containing slashes it may be an attack.
392      header($_SERVER['SERVER_PROTOCOL'] .' 400 Bad Request');
393      exit;
394    }
395  }
396  else {
397    // Some pre-HTTP/1.1 clients will not send a Host header. Ensure the key is
398    // defined for E_ALL compliance.
399    $_SERVER['HTTP_HOST'] = '';
400  }
401
402  if (file_exists('./'. conf_path() .'/settings.php')) {
403    include_once './'. conf_path() .'/settings.php';
404  }
405
406  // Ignore the placeholder URL from default.settings.php.
407  if (isset($db_url) && $db_url == 'mysql://username:password@localhost/databasename') {
408    $db_url = '';
409  }
410
411  if (isset($base_url)) {
412    // Parse fixed base URL from settings.php.
413    $parts = parse_url($base_url);
414    if (!isset($parts['path'])) {
415      $parts['path'] = '';
416    }
417    $base_path = $parts['path'] .'/';
418    // Build $base_root (everything until first slash after "scheme://").
419    $base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
420  }
421  else {
422    // Create base URL
423    $base_root = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
424
425    $base_url = $base_root .= '://'. $_SERVER['HTTP_HOST'];
426
427    // $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
428    // be modified by a visitor.
429    if ($dir = trim(dirname($_SERVER['SCRIPT_NAME']), '\,/')) {
430      $base_path = "/$dir";
431      $base_url .= $base_path;
432      $base_path .= '/';
433    }
434    else {
435      $base_path = '/';
436    }
437  }
438
439  if ($cookie_domain) {
440    // If the user specifies the cookie domain, also use it for session name.
441    $session_name = $cookie_domain;
442  }
443  else {
444    // Otherwise use $base_url as session name, without the protocol
445    // to use the same session identifiers across HTTP and HTTPS.
446    list( , $session_name) = explode('://', $base_url, 2);
447    // We escape the hostname because it can be modified by a visitor.
448    if (!empty($_SERVER['HTTP_HOST'])) {
449      $cookie_domain = check_plain($_SERVER['HTTP_HOST']);
450      // Strip leading periods, www., and port numbers from cookie domain.
451      $cookie_domain = ltrim($cookie_domain, '.');
452      if (strpos($cookie_domain, 'www.') === 0) {
453        $cookie_domain = substr($cookie_domain, 4);
454      }
455      $cookie_domain = explode(':', $cookie_domain);
456      $cookie_domain = '.'. $cookie_domain[0];
457    }
458  }
459  // To prevent session cookies from being hijacked, a user can configure the
460  // SSL version of their website to only transfer session cookies via SSL by
461  // using PHP's session.cookie_secure setting. The browser will then use two
462  // separate session cookies for the HTTPS and HTTP versions of the site. So we
463  // must use different session identifiers for HTTPS and HTTP to prevent a
464  // cookie collision.
465  if (ini_get('session.cookie_secure')) {
466    $session_name .= 'SSL';
467  }
468  // Per RFC 2109, cookie domains must contain at least one dot other than the
469  // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
470  if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
471    ini_set('session.cookie_domain', $cookie_domain);
472  }
473  session_name('SESS'. md5($session_name));
474}
475
476/**
477 * Returns and optionally sets the filename for a system item (module,
478 * theme, etc.). The filename, whether provided, cached, or retrieved
479 * from the database, is only returned if the file exists.
480 *
481 * This function plays a key role in allowing Drupal's resources (modules
482 * and themes) to be located in different places depending on a site's
483 * configuration. For example, a module 'foo' may legally be be located
484 * in any of these three places:
485 *
486 * modules/foo/foo.module
487 * sites/all/modules/foo/foo.module
488 * sites/example.com/modules/foo/foo.module
489 *
490 * Calling drupal_get_filename('module', 'foo') will give you one of
491 * the above, depending on where the module is located.
492 *
493 * @param $type
494 *   The type of the item (i.e. theme, theme_engine, module, profile).
495 * @param $name
496 *   The name of the item for which the filename is requested.
497 * @param $filename
498 *   The filename of the item if it is to be set explicitly rather
499 *   than by consulting the database.
500 *
501 * @return
502 *   The filename of the requested item.
503 */
504function drupal_get_filename($type, $name, $filename = NULL) {
505  static $files = array();
506
507  if (!isset($files[$type])) {
508    $files[$type] = array();
509  }
510
511  if (!empty($filename) && file_exists($filename)) {
512    $files[$type][$name] = $filename;
513  }
514  elseif (isset($files[$type][$name])) {
515    // nothing
516  }
517  // Verify that we have an active database connection, before querying
518  // the database.  This is required because this function is called both
519  // before we have a database connection (i.e. during installation) and
520  // when a database connection fails.
521  elseif (db_is_active() && (($file = db_result(db_query("SELECT filename FROM {system} WHERE name = '%s' AND type = '%s'", $name, $type))) && file_exists($file))) {
522    $files[$type][$name] = $file;
523  }
524  else {
525    // Fallback to searching the filesystem if the database connection is
526    // not established or the requested file is not found.
527    $config = conf_path();
528    $dir = (($type == 'theme_engine') ? 'themes/engines' : "${type}s");
529    $file = (($type == 'theme_engine') ? "$name.engine" : "$name.$type");
530
531    foreach (array("$config/$dir/$file", "$config/$dir/$name/$file", "$dir/$file", "$dir/$name/$file") as $file) {
532      if (file_exists($file)) {
533        $files[$type][$name] = $file;
534        break;
535      }
536    }
537  }
538
539  if (isset($files[$type][$name])) {
540    return $files[$type][$name];
541  }
542}
543
544/**
545 * Load the persistent variable table.
546 *
547 * The variable table is composed of values that have been saved in the table
548 * with variable_set() as well as those explicitly specified in the configuration
549 * file.
550 */
551function variable_init($conf = array()) {
552  // NOTE: caching the variables improves performance by 20% when serving cached pages.
553  if ($cached = cache_get('variables', 'cache')) {
554    $variables = $cached->data;
555  }
556  else {
557    $result = db_query('SELECT * FROM {variable}');
558    while ($variable = db_fetch_object($result)) {
559      $variables[$variable->name] = unserialize($variable->value);
560    }
561    cache_set('variables', $variables);
562  }
563
564  foreach ($conf as $name => $value) {
565    $variables[$name] = $value;
566  }
567
568  return $variables;
569}
570
571/**
572 * Returns a persistent variable.
573 *
574 * Case-sensitivity of the variable_* functions depends on the database
575 * collation used. To avoid problems, always use lower case for persistent
576 * variable names.
577 *
578 * @param $name
579 *   The name of the variable to return.
580 * @param $default
581 *   The default value to use if this variable has never been set.
582 * @return
583 *   The value of the variable.
584 *
585 * @see variable_del(), variable_set()
586 */
587function variable_get($name, $default) {
588  global $conf;
589
590  return isset($conf[$name]) ? $conf[$name] : $default;
591}
592
593/**
594 * Sets a persistent variable.
595 *
596 * Case-sensitivity of the variable_* functions depends on the database
597 * collation used. To avoid problems, always use lower case for persistent
598 * variable names.
599 *
600 * @param $name
601 *   The name of the variable to set.
602 * @param $value
603 *   The value to set. This can be any PHP data type; these functions take care
604 *   of serialization as necessary.
605 *
606 * @see variable_del(), variable_get()
607 */
608function variable_set($name, $value) {
609  global $conf;
610
611  $serialized_value = serialize($value);
612  db_query("UPDATE {variable} SET value = '%s' WHERE name = '%s'", $serialized_value, $name);
613  if (!db_affected_rows()) {
614    @db_query("INSERT INTO {variable} (name, value) VALUES ('%s', '%s')", $name, $serialized_value);
615  }
616
617  cache_clear_all('variables', 'cache');
618
619  $conf[$name] = $value;
620}
621
622/**
623 * Unsets a persistent variable.
624 *
625 * Case-sensitivity of the variable_* functions depends on the database
626 * collation used. To avoid problems, always use lower case for persistent
627 * variable names.
628 *
629 * @param $name
630 *   The name of the variable to undefine.
631 *
632 * @see variable_get(), variable_set()
633 */
634function variable_del($name) {
635  global $conf;
636
637  db_query("DELETE FROM {variable} WHERE name = '%s'", $name);
638  cache_clear_all('variables', 'cache');
639
640  unset($conf[$name]);
641}
642
643
644/**
645 * Retrieve the current page from the cache.
646 *
647 * Note: we do not serve cached pages when status messages are waiting (from
648 * a redirected form submission which was completed).
649 *
650 * @param $status_only
651 *   When set to TRUE, retrieve the status of the page cache only
652 *   (whether it was started in this request or not).
653 */
654function page_get_cache($status_only = FALSE) {
655  static $status = FALSE;
656  global $user, $base_root;
657
658  if ($status_only) {
659    return $status;
660  }
661  $cache = NULL;
662
663  if (!$user->uid && $_SERVER['REQUEST_METHOD'] == 'GET' && count(drupal_set_message()) == 0 && $_SERVER['SERVER_SOFTWARE'] !== 'PHP CLI') {
664    $cache = cache_get($base_root . request_uri(), 'cache_page');
665
666    if (empty($cache)) {
667      ob_start();
668      $status = TRUE;
669    }
670  }
671
672  return $cache;
673}
674
675/**
676 * Call all init or exit hooks without including all modules.
677 *
678 * @param $hook
679 *   The name of the bootstrap hook we wish to invoke.
680 */
681function bootstrap_invoke_all($hook) {
682  foreach (module_list(TRUE, TRUE) as $module) {
683    drupal_load('module', $module);
684    module_invoke($module, $hook);
685  }
686}
687
688/**
689 * Includes a file with the provided type and name. This prevents
690 * including a theme, engine, module, etc., more than once.
691 *
692 * @param $type
693 *   The type of item to load (i.e. theme, theme_engine, module, profile).
694 * @param $name
695 *   The name of the item to load.
696 *
697 * @return
698 *   TRUE if the item is loaded or has already been loaded.
699 */
700function drupal_load($type, $name) {
701  static $files = array();
702
703  if (isset($files[$type][$name])) {
704    return TRUE;
705  }
706
707  $filename = drupal_get_filename($type, $name);
708
709  if ($filename) {
710    include_once "./$filename";
711    $files[$type][$name] = TRUE;
712
713    return TRUE;
714  }
715
716  return FALSE;
717}
718
719/**
720 * Set HTTP headers in preparation for a page response.
721 *
722 * Authenticated users are always given a 'no-cache' header, and will
723 * fetch a fresh page on every request.  This prevents authenticated
724 * users seeing locally cached pages that show them as logged out.
725 *
726 * @see page_set_cache()
727 */
728function drupal_page_header() {
729  header("Expires: Sun, 19 Nov 1978 05:00:00 GMT");
730  header("Last-Modified: ". gmdate("D, d M Y H:i:s") ." GMT");
731  header("Cache-Control: store, no-cache, must-revalidate");
732  header("Cache-Control: post-check=0, pre-check=0", FALSE);
733}
734
735/**
736 * Set HTTP headers in preparation for a cached page response.
737 *
738 * The general approach here is that anonymous users can keep a local
739 * cache of the page, but must revalidate it on every request.  Then,
740 * they are given a '304 Not Modified' response as long as they stay
741 * logged out and the page has not been modified.
742 *
743 */
744function drupal_page_cache_header($cache) {
745  // Set default values:
746  $last_modified = gmdate('D, d M Y H:i:s', $cache->created) .' GMT';
747  $etag = '"'. md5($last_modified) .'"';
748
749  // See if the client has provided the required HTTP headers:
750  $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']) : FALSE;
751  $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : FALSE;
752
753  if ($if_modified_since && $if_none_match
754      && $if_none_match == $etag // etag must match
755      && $if_modified_since == $last_modified) {  // if-modified-since must match
756    header($_SERVER['SERVER_PROTOCOL'] .' 304 Not Modified');
757    // All 304 responses must send an etag if the 200 response for the same object contained an etag
758    header("Etag: $etag");
759    return;
760  }
761
762  // Send appropriate response:
763  header("Last-Modified: $last_modified");
764  header("ETag: $etag");
765
766  // The following headers force validation of cache:
767  header("Expires: Sun, 19 Nov 1978 05:00:00 GMT");
768  header("Cache-Control: must-revalidate");
769
770  if (variable_get('page_compression', TRUE) && extension_loaded('zlib')) {
771    // Determine if the browser accepts gzipped data.
772    if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE) {
773      // $cache->data is already gzip'ed, so make sure zlib.output_compression
774      // does not compress it once more.
775      ini_set('zlib.output_compression', '0');
776      header('Content-Encoding: gzip');
777    }
778    else {
779      // The client does not support compression, so unzip the data in the
780      // cache. Strip the gzip header and run uncompress.
781      $cache->data = gzinflate(substr(substr($cache->data, 10), 0, -8));
782    }
783  }
784
785  // Send the original request's headers. We send them one after
786  // another so PHP's header() function can deal with duplicate
787  // headers.
788  $headers = explode("\n", $cache->headers);
789  foreach ($headers as $header) {
790    header($header);
791  }
792
793  print $cache->data;
794}
795
796/**
797 * Define the critical hooks that force modules to always be loaded.
798 */
799function bootstrap_hooks() {
800  return array('boot', 'exit');
801}
802
803/**
804 * Unserializes and appends elements from a serialized string.
805 *
806 * @param $obj
807 *   The object to which the elements are appended.
808 * @param $field
809 *   The attribute of $obj whose value should be unserialized.
810 */
811function drupal_unpack($obj, $field = 'data') {
812  if ($obj->$field && $data = unserialize($obj->$field)) {
813    foreach ($data as $key => $value) {
814      if (!empty($key) && !isset($obj->$key)) {
815        $obj->$key = $value;
816      }
817    }
818  }
819  return $obj;
820}
821
822/**
823 * Return the URI of the referring page.
824 */
825function referer_uri() {
826  if (isset($_SERVER['HTTP_REFERER'])) {
827    return $_SERVER['HTTP_REFERER'];
828  }
829}
830
831/**
832 * Encode special characters in a plain-text string for display as HTML.
833 *
834 * Also validates strings as UTF-8 to prevent cross site scripting attacks on
835 * Internet Explorer 6.
836 *
837 * @param $text
838 *   The text to be checked or processed.
839 * @return
840 *   An HTML safe version of $text, or an empty string if $text is not
841 *   valid UTF-8.
842 *
843 * @see drupal_validate_utf8().
844 */
845function check_plain($text) {
846  static $php525;
847
848  if (!isset($php525)) {
849    $php525 = version_compare(PHP_VERSION, '5.2.5', '>=');
850  }
851  // We duplicate the preg_match() to validate strings as UTF-8 from
852  // drupal_validate_utf8() here. This avoids the overhead of an additional
853  // function call, since check_plain() may be called hundreds of times during
854  // a request. For PHP 5.2.5+, this check for valid UTF-8 should be handled
855  // internally by PHP in htmlspecialchars().
856  // @see http://www.php.net/releases/5_2_5.php
857  // @todo remove this when support for either IE6 or PHP < 5.2.5 is dropped.
858
859  if ($php525) {
860    return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
861  }
862  return (preg_match('/^./us', $text) == 1) ? htmlspecialchars($text, ENT_QUOTES, 'UTF-8') : '';
863}
864
865/**
866 * Checks whether a string is valid UTF-8.
867 *
868 * All functions designed to filter input should use drupal_validate_utf8
869 * to ensure they operate on valid UTF-8 strings to prevent bypass of the
870 * filter.
871 *
872 * When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
873 * as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
874 * bytes. When these subsequent bytes are HTML control characters such as
875 * quotes or angle brackets, parts of the text that were deemed safe by filters
876 * end up in locations that are potentially unsafe; An onerror attribute that
877 * is outside of a tag, and thus deemed safe by a filter, can be interpreted
878 * by the browser as if it were inside the tag.
879 *
880 * This function exploits preg_match behaviour (since PHP 4.3.5) when used
881 * with the u modifier, as a fast way to find invalid UTF-8. When the matched
882 * string contains an invalid byte sequence, it will fail silently.
883 *
884 * preg_match may not fail on 4 and 5 octet sequences, even though they
885 * are not supported by the specification.
886 *
887 * The specific preg_match behaviour is present since PHP 4.3.5.
888 *
889 * @param $text
890 *   The text to check.
891 * @return
892 *   TRUE if the text is valid UTF-8, FALSE if not.
893 */
894function drupal_validate_utf8($text) {
895  if (strlen($text) == 0) {
896    return TRUE;
897  }
898  // For performance reasons this logic is duplicated in check_plain().
899  return (preg_match('/^./us', $text) == 1);
900}
901
902/**
903 * Since $_SERVER['REQUEST_URI'] is only available on Apache, we
904 * generate an equivalent using other environment variables.
905 */
906function request_uri() {
907
908  if (isset($_SERVER['REQUEST_URI'])) {
909    $uri = $_SERVER['REQUEST_URI'];
910  }
911  else {
912    if (isset($_SERVER['argv'])) {
913      $uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['argv'][0];
914    }
915    elseif (isset($_SERVER['QUERY_STRING'])) {
916      $uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
917    }
918    else {
919      $uri = $_SERVER['SCRIPT_NAME'];
920    }
921  }
922  // Prevent multiple slashes to avoid cross site requests via the FAPI.
923  $uri = '/'. ltrim($uri, '/');
924
925  return $uri;
926}
927
928/**
929 * Log a system message.
930 *
931 * @param $type
932 *   The category to which this message belongs. Can be any string, but the
933 *   general practice is to use the name of the module calling watchdog().
934 * @param $message
935 *   The message to store in the log. See t() for documentation
936 *   on how $message and $variables interact. Keep $message
937 *   translatable by not concatenating dynamic values into it!
938 * @param $variables
939 *   Array of variables to replace in the message on display or
940 *   NULL if message is already translated or not possible to
941 *   translate.
942 * @param $severity
943 *   The severity of the message, as per RFC 3164. Possible values are
944 *   WATCHDOG_ERROR, WATCHDOG_WARNING, etc.
945 * @param $link
946 *   A link to associate with the message.
947 *
948 * @see watchdog_severity_levels()
949 */
950function watchdog($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL) {
951  global $user, $base_root;
952
953  // Prepare the fields to be logged
954  $log_message = array(
955    'type'        => $type,
956    'message'     => $message,
957    'variables'   => $variables,
958    'severity'    => $severity,
959    'link'        => $link,
960    'user'        => $user,
961    'request_uri' => $base_root . request_uri(),
962    'referer'     => referer_uri(),
963    'ip'          => ip_address(),
964    'timestamp'   => time(),
965    );
966
967  // Call the logging hooks to log/process the message
968  foreach (module_implements('watchdog') as $module) {
969    module_invoke($module, 'watchdog', $log_message);
970  }
971}
972
973/**
974 * Set a message which reflects the status of the performed operation.
975 *
976 * If the function is called with no arguments, this function returns all set
977 * messages without clearing them.
978 *
979 * @param $message
980 *   The message should begin with a capital letter and always ends with a
981 *   period '.'.
982 * @param $type
983 *   The type of the message. One of the following values are possible:
984 *   - 'status'
985 *   - 'warning'
986 *   - 'error'
987 * @param $repeat
988 *   If this is FALSE and the message is already set, then the message won't
989 *   be repeated.
990 */
991function drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE) {
992  if ($message) {
993    if (!isset($_SESSION['messages'])) {
994      $_SESSION['messages'] = array();
995    }
996
997    if (!isset($_SESSION['messages'][$type])) {
998      $_SESSION['messages'][$type] = array();
999    }
1000
1001    if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
1002      $_SESSION['messages'][$type][] = $message;
1003    }
1004  }
1005
1006  // messages not set when DB connection fails
1007  return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
1008}
1009
1010/**
1011 * Return all messages that have been set.
1012 *
1013 * @param $type
1014 *   (optional) Only return messages of this type.
1015 * @param $clear_queue
1016 *   (optional) Set to FALSE if you do not want to clear the messages queue
1017 * @return
1018 *   An associative array, the key is the message type, the value an array
1019 *   of messages. If the $type parameter is passed, you get only that type,
1020 *   or an empty array if there are no such messages. If $type is not passed,
1021 *   all message types are returned, or an empty array if none exist.
1022 */
1023function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
1024  if ($messages = drupal_set_message()) {
1025    if ($type) {
1026      if ($clear_queue) {
1027        unset($_SESSION['messages'][$type]);
1028      }
1029      if (isset($messages[$type])) {
1030        return array($type => $messages[$type]);
1031      }
1032    }
1033    else {
1034      if ($clear_queue) {
1035        unset($_SESSION['messages']);
1036      }
1037      return $messages;
1038    }
1039  }
1040  return array();
1041}
1042
1043/**
1044 * Perform an access check for a given mask and rule type. Rules are usually
1045 * created via admin/user/rules page.
1046 *
1047 * If any allow rule matches, access is allowed. Otherwise, if any deny rule
1048 * matches, access is denied.  If no rule matches, access is allowed.
1049 *
1050 * @param $type string
1051 *   Type of access to check: Allowed values are:
1052 *     - 'host': host name or IP address
1053 *     - 'mail': e-mail address
1054 *     - 'user': username
1055 * @param $mask string
1056 *   String or mask to test: '_' matches any character, '%' matches any
1057 *   number of characters.
1058 * @return bool
1059 *   TRUE if access is denied, FALSE if access is allowed.
1060 */
1061function drupal_is_denied($type, $mask) {
1062  // Because this function is called for every page request, both cached
1063  // and non-cached pages, we tried to optimize it as much as possible.
1064  // We deny access if the only matching records in the {access} table have
1065  // status 0 (deny). If any have status 1 (allow), or if there are no
1066  // matching records, we allow access.
1067  $sql = "SELECT 1 FROM {access} WHERE type = '%s' AND LOWER('%s') LIKE LOWER(mask) AND status = %d";
1068  return db_result(db_query_range($sql, $type, $mask, 0, 0, 1)) && !db_result(db_query_range($sql, $type, $mask, 1, 0, 1));
1069}
1070
1071/**
1072 * Generates a default anonymous $user object.
1073 *
1074 * @return Object - the user object.
1075 */
1076function drupal_anonymous_user($session = '') {
1077  $user = new stdClass();
1078  $user->uid = 0;
1079  $user->hostname = ip_address();
1080  $user->roles = array();
1081  $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
1082  $user->session = $session;
1083  $user->cache = 0;
1084  return $user;
1085}
1086
1087/**
1088 * A string describing a phase of Drupal to load. Each phase adds to the
1089 * previous one, so invoking a later phase automatically runs the earlier
1090 * phases too. The most important usage is that if you want to access the
1091 * Drupal database from a script without loading anything else, you can
1092 * include bootstrap.inc, and call drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE).
1093 *
1094 * @param $phase
1095 *   A constant. Allowed values are:
1096 *     DRUPAL_BOOTSTRAP_CONFIGURATION: initialize configuration.
1097 *     DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE: try to call a non-database cache fetch routine.
1098 *     DRUPAL_BOOTSTRAP_DATABASE: initialize database layer.
1099 *     DRUPAL_BOOTSTRAP_ACCESS: identify and reject banned hosts.
1100 *     DRUPAL_BOOTSTRAP_SESSION: initialize session handling.
1101 *     DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE: load bootstrap.inc and module.inc, start
1102 *       the variable system and try to serve a page from the cache.
1103 *     DRUPAL_BOOTSTRAP_LANGUAGE: identify the language used on the page.
1104 *     DRUPAL_BOOTSTRAP_PATH: set $_GET['q'] to Drupal path of request.
1105 *     DRUPAL_BOOTSTRAP_FULL: Drupal is fully loaded, validate and fix input data.
1106 */
1107function drupal_bootstrap($phase) {
1108  static $phases = array(DRUPAL_BOOTSTRAP_CONFIGURATION, DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE, DRUPAL_BOOTSTRAP_DATABASE, DRUPAL_BOOTSTRAP_ACCESS, DRUPAL_BOOTSTRAP_SESSION, DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE, DRUPAL_BOOTSTRAP_LANGUAGE, DRUPAL_BOOTSTRAP_PATH, DRUPAL_BOOTSTRAP_FULL), $phase_index = 0;
1109
1110  while ($phase >= $phase_index && isset($phases[$phase_index])) {
1111    $current_phase = $phases[$phase_index];
1112    unset($phases[$phase_index++]);
1113    _drupal_bootstrap($current_phase);
1114  }
1115}
1116
1117function _drupal_bootstrap($phase) {
1118  global $conf;
1119
1120  switch ($phase) {
1121
1122    case DRUPAL_BOOTSTRAP_CONFIGURATION:
1123      drupal_unset_globals();
1124      // Start a page timer:
1125      timer_start('page');
1126      // Initialize the configuration
1127      conf_init();
1128      break;
1129
1130    case DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE:
1131      // Allow specifying special cache handlers in settings.php, like
1132      // using memcached or files for storing cache information.
1133      require_once variable_get('cache_inc', './includes/cache.inc');
1134      // If the page_cache_fastpath is set to TRUE in settings.php and
1135      // page_cache_fastpath (implemented in the special implementation of
1136      // cache.inc) printed the page and indicated this with a returned TRUE
1137      // then we are done.
1138      if (variable_get('page_cache_fastpath', FALSE) && page_cache_fastpath()) {
1139        exit;
1140      }
1141      break;
1142
1143    case DRUPAL_BOOTSTRAP_DATABASE:
1144      // Initialize the default database.
1145      require_once './includes/database.inc';
1146      db_set_active();
1147      // Allow specifying alternate lock implementations in settings.php, like
1148      // those using APC or memcached.
1149      require_once variable_get('lock_inc', './includes/lock.inc');
1150      lock_init();
1151      break;
1152
1153    case DRUPAL_BOOTSTRAP_ACCESS:
1154      // Deny access to hosts which were banned - t() is not yet available.
1155      if (drupal_is_denied('host', ip_address())) {
1156        header($_SERVER['SERVER_PROTOCOL'] .' 403 Forbidden');
1157        print 'Sorry, '. check_plain(ip_address()) .' has been banned.';
1158        exit();
1159      }
1160      break;
1161
1162    case DRUPAL_BOOTSTRAP_SESSION:
1163      require_once variable_get('session_inc', './includes/session.inc');
1164      session_set_save_handler('sess_open', 'sess_close', 'sess_read', 'sess_write', 'sess_destroy_sid', 'sess_gc');
1165      session_start();
1166      break;
1167
1168    case DRUPAL_BOOTSTRAP_LATE_PAGE_CACHE:
1169      // Initialize configuration variables, using values from settings.php if available.
1170      $conf = variable_init(isset($conf) ? $conf : array());
1171      $cache_mode = variable_get('cache', CACHE_DISABLED);
1172      // Get the page from the cache.
1173      $cache = $cache_mode == CACHE_DISABLED ? '' : page_get_cache();
1174      // If the skipping of the bootstrap hooks is not enforced, call hook_boot.
1175      if (!$cache || $cache_mode != CACHE_AGGRESSIVE) {
1176        // Load module handling.
1177        require_once './includes/module.inc';
1178        bootstrap_invoke_all('boot');
1179      }
1180      // If there is a cached page, display it.
1181      if ($cache) {
1182        drupal_page_cache_header($cache);
1183        // If the skipping of the bootstrap hooks is not enforced, call hook_exit.
1184        if ($cache_mode != CACHE_AGGRESSIVE) {
1185          bootstrap_invoke_all('exit');
1186        }
1187        // We are done.
1188        exit;
1189      }
1190      // Prepare for non-cached page workflow.
1191      drupal_page_header();
1192      break;
1193
1194    case DRUPAL_BOOTSTRAP_LANGUAGE:
1195      drupal_init_language();
1196      break;
1197
1198    case DRUPAL_BOOTSTRAP_PATH:
1199      require_once './includes/path.inc';
1200      // Initialize $_GET['q'] prior to loading modules and invoking hook_init().
1201      drupal_init_path();
1202      break;
1203
1204    case DRUPAL_BOOTSTRAP_FULL:
1205      require_once './includes/common.inc';
1206      _drupal_bootstrap_full();
1207      break;
1208  }
1209}
1210
1211/**
1212 * Enables use of the theme system without requiring database access.
1213 *
1214 * Loads and initializes the theme system for site installs, updates and when
1215 * the site is in off-line mode. This also applies when the database fails.
1216 *
1217 * @see _drupal_maintenance_theme()
1218 */
1219function drupal_maintenance_theme() {
1220  require_once './includes/theme.maintenance.inc';
1221  _drupal_maintenance_theme();
1222}
1223
1224/**
1225 * Return the name of the localisation function. Use in code that needs to
1226 * run both during installation and normal operation.
1227 */
1228function get_t() {
1229  static $t;
1230  if (is_null($t)) {
1231    $t = function_exists('install_main') ? 'st' : 't';
1232  }
1233  return $t;
1234}
1235
1236/**
1237 *  Choose a language for the current page, based on site and user preferences.
1238 */
1239function drupal_init_language() {
1240  global $language, $user;
1241
1242  // Ensure the language is correctly returned, even without multilanguage support.
1243  // Useful for eg. XML/HTML 'lang' attributes.
1244  if (variable_get('language_count', 1) == 1) {
1245    $language = language_default();
1246  }
1247  else {
1248    include_once './includes/language.inc';
1249    $language = language_initialize();
1250  }
1251}
1252
1253/**
1254 * Get a list of languages set up indexed by the specified key
1255 *
1256 * @param $field The field to index the list with.
1257 * @param $reset Boolean to request a reset of the list.
1258 */
1259function language_list($field = 'language', $reset = FALSE) {
1260  static $languages = NULL;
1261
1262  // Reset language list
1263  if ($reset) {
1264    $languages = NULL;
1265  }
1266
1267  // Init language list
1268  if (!isset($languages)) {
1269    if (variable_get('language_count', 1) > 1 || module_exists('locale')) {
1270      $result = db_query('SELECT * FROM {languages} ORDER BY weight ASC, name ASC');
1271      while ($row = db_fetch_object($result)) {
1272        $languages['language'][$row->language] = $row;
1273      }
1274    }
1275    else {
1276      // No locale module, so use the default language only.
1277      $default = language_default();
1278      $languages['language'][$default->language] = $default;
1279    }
1280  }
1281
1282  // Return the array indexed by the right field
1283  if (!isset($languages[$field])) {
1284    $languages[$field] = array();
1285    foreach ($languages['language'] as $lang) {
1286      // Some values should be collected into an array
1287      if (in_array($field, array('enabled', 'weight'))) {
1288        $languages[$field][$lang->$field][$lang->language] = $lang;
1289      }
1290      else {
1291        $languages[$field][$lang->$field] = $lang;
1292      }
1293    }
1294  }
1295  return $languages[$field];
1296}
1297
1298/**
1299 * Default language used on the site
1300 *
1301 * @param $property
1302 *   Optional property of the language object to return
1303 */
1304function language_default($property = NULL) {
1305  $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' => ''));
1306  return $property ? $language->$property : $language;
1307}
1308
1309/**
1310 * If Drupal is behind a reverse proxy, we use the X-Forwarded-For header
1311 * instead of $_SERVER['REMOTE_ADDR'], which would be the IP address
1312 * of the proxy server, and not the client's.
1313 *
1314 * @return
1315 *   IP address of client machine, adjusted for reverse proxy.
1316 */
1317function ip_address() {
1318  static $ip_address = NULL;
1319
1320  if (!isset($ip_address)) {
1321    $ip_address = $_SERVER['REMOTE_ADDR'];
1322    if (variable_get('reverse_proxy', 0) && array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
1323      // If an array of known reverse proxy IPs is provided, then trust
1324      // the XFF header if request really comes from one of them.
1325      $reverse_proxy_addresses = variable_get('reverse_proxy_addresses', array());
1326      if (!empty($reverse_proxy_addresses) && in_array($ip_address, $reverse_proxy_addresses, TRUE)) {
1327        // If there are several arguments, we need to check the most
1328        // recently added one, i.e. the last one.
1329        $ip_address_parts = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
1330        $ip_address = array_pop($ip_address_parts);
1331      }
1332    }
1333  }
1334
1335  return $ip_address;
1336}
1337
1338/**
1339 * Returns a URL-safe, base64 encoded string of highly randomized bytes (over the full 8-bit range).
1340 *
1341 * @param $byte_count
1342 *   The number of random bytes to fetch and base64 encode.
1343 *
1344 * @return string
1345 *   The base64 encoded result will have a length of up to 4 * $byte_count.
1346 */
1347function drupal_random_key($byte_count = 32) {
1348  return drupal_base64_encode(drupal_random_bytes($byte_count));
1349}
1350
1351/**
1352 * Returns a URL-safe, base64 encoded version of the supplied string.
1353 *
1354 * @param $string
1355 *   The string to convert to base64.
1356 *
1357 * @return string
1358 */
1359function drupal_base64_encode($string) {
1360  $data = base64_encode($string);
1361  // Modify the output so it's safe to use in URLs.
1362  return strtr($data, array('+' => '-', '/' => '_', '=' => ''));
1363}
1364
1365/**
1366 * Returns a string of highly randomized bytes (over the full 8-bit range).
1367 *
1368 * This function is better than simply calling mt_rand() or any other built-in
1369 * PHP function because it can return a long string of bytes (compared to < 4
1370 * bytes normally from mt_rand()) and uses the best available pseudo-random
1371 * source.
1372 *
1373 * @param $count
1374 *   The number of characters (bytes) to return in the string.
1375 */
1376function drupal_random_bytes($count) {
1377  // $random_state does not use drupal_static as it stores random bytes.
1378  static $random_state, $bytes, $has_openssl, $has_hash;
1379
1380  $missing_bytes = $count - strlen($bytes);
1381
1382  if ($missing_bytes > 0) {
1383    // PHP versions prior 5.3.4 experienced openssl_random_pseudo_bytes()
1384    // locking on Windows and rendered it unusable.
1385    if (!isset($has_openssl)) {
1386      $has_openssl = version_compare(PHP_VERSION, '5.3.4', '>=') && function_exists('openssl_random_pseudo_bytes');
1387    }
1388
1389    // openssl_random_pseudo_bytes() will find entropy in a system-dependent
1390    // way.
1391    if ($has_openssl) {
1392      $bytes .= openssl_random_pseudo_bytes($missing_bytes);
1393    }
1394
1395    // Else, read directly from /dev/urandom, which is available on many *nix
1396    // systems and is considered cryptographically secure.
1397    elseif ($fh = @fopen('/dev/urandom', 'rb')) {
1398      // PHP only performs buffered reads, so in reality it will always read
1399      // at least 4096 bytes. Thus, it costs nothing extra to read and store
1400      // that much so as to speed any additional invocations.
1401      $bytes .= fread($fh, max(4096, $missing_bytes));
1402      fclose($fh);
1403    }
1404
1405    // If we couldn't get enough entropy, this simple hash-based PRNG will
1406    // generate a good set of pseudo-random bytes on any system.
1407    // Note that it may be important that our $random_state is passed
1408    // through hash() prior to being rolled into $output, that the two hash()
1409    // invocations are different, and that the extra input into the first one -
1410    // the microtime() - is prepended rather than appended. This is to avoid
1411    // directly leaking $random_state via the $output stream, which could
1412    // allow for trivial prediction of further "random" numbers.
1413    if (strlen($bytes) < $count) {
1414      // Initialize on the first call. The contents of $_SERVER includes a mix of
1415      // user-specific and system information that varies a little with each page.
1416      if (!isset($random_state)) {
1417        $random_state = print_r($_SERVER, TRUE);
1418        if (function_exists('getmypid')) {
1419          // Further initialize with the somewhat random PHP process ID.
1420          $random_state .= getmypid();
1421        }
1422        // hash() is only available in PHP 5.1.2+ or via PECL.
1423        $has_hash = function_exists('hash') && in_array('sha256', hash_algos());
1424        $bytes = '';
1425      }
1426
1427      if ($has_hash) {
1428        do {
1429          $random_state = hash('sha256', microtime() . mt_rand() . $random_state);
1430          $bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
1431        } while (strlen($bytes) < $count);
1432      }
1433      else {
1434        do {
1435          $random_state = md5(microtime() . mt_rand() . $random_state);
1436          $bytes .= pack("H*", md5(mt_rand() . $random_state));
1437        } while (strlen($bytes) < $count);
1438      }
1439    }
1440  }
1441  $output = substr($bytes, 0, $count);
1442  $bytes = substr($bytes, $count);
1443  return $output;
1444}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.