boost.module 45.7 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5 6
 * Caches generated output as a static file to be served directly from the
 * webserver.
7 8
 */

9 10 11
/**
 * Default cacheablily setting.
 */
mikeytown2's avatar
mikeytown2 committed
12
define('BOOST_CACHEABILITY_PAGES', '');
13

14 15 16 17 18
/**
 * Whether the host supports gzip
 */
define('BOOST_GZIP', function_exists('gzencode'));

19 20 21
/**
 * Default cookie name.
 */
mikeytown2's avatar
mikeytown2 committed
22
define('BOOST_COOKIE', 'DRUPAL_UID');
23

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
/**
 * Default value for sending out debugging info via a message.
 */
define('BOOST_MESSAGE_DEBUG', FALSE);

/**
 * Default value for the root cache dir.
 */
define('BOOST_ROOT_CACHE_DIR', 'cache');

/**
 * Default value for the normal cache dir.
 */
define('BOOST_NORMAL_DIR', 'normal');

/**
 * Default value for the character replacement of ? in the URL.
 */
define('BOOST_CHAR', '_');

/**
45
 * Default value for ignoring cron cache flush requests.
46
 */
47
define('BOOST_IGNORE_FLUSH', TRUE);
48 49

/**
50
 * Default value for ignoring cron cache flush requests.
51
 */
52
define('BOOST_EXPIRE_CRON', TRUE);
53

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
/**
 * Default etag settings.
 */
define('BOOST_APACHE_ETAG', 3);

/**
 * Default header setttings.
 */
define('BOOST_APACHE_XHEADER', 1);

/**
 * Default setting for forcing all content to be the charset defined below.
 */
define('BOOST_ADD_DEFAULT_CHARSET', TRUE);

/**
 * Default for content charset.
 */
define('BOOST_CHARSET_TYPE', 'utf-8');

74 75
/**
 * Shows this block on every page except the listed pages.
76
 * (do not depend on block.module, see #1612448)
77 78 79 80 81 82 83 84 85 86 87 88
 */
define('BOOST_VISIBILITY_NOTLISTED', 0);

/**
 * Shows this block on only the listed pages.
 */
define('BOOST_VISIBILITY_LISTED', 1);

/**
 * Shows this block if the associated PHP code returns TRUE.
 */
define('BOOST_VISIBILITY_PHP', 2);
89

90 91 92 93 94 95
/**
 * Default Setting for .htaccess files +FollowSymLinks, some ISP's require
 * +SymlinksIfOwnerMatch to avoid http 500 error.
 */
define('BOOST_MATCH_SYMLINKS_OPTIONS', 1);

mikeytown2's avatar
mikeytown2 committed
96
/**
97
 * Implements hook_menu().
mikeytown2's avatar
mikeytown2 committed
98 99
 */
function boost_menu() {
100 101
  $items = array();
  $path = drupal_get_path('module', 'boost');
mikeytown2's avatar
mikeytown2 committed
102

103 104
  $items['admin/config/system/boost'] = array(
    'title' => 'Boost',
mikeytown2's avatar
mikeytown2 committed
105 106 107 108
    'description' => 'Configuration for Boost.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('boost_admin_settings'),
    'access arguments' => array('administer site configuration'),
109
    'type' => MENU_NORMAL_ITEM,
mikeytown2's avatar
mikeytown2 committed
110
    'file' => 'boost.admin.inc',
111
    'file path' => $path,
112
  );
113 114 115 116 117 118
  $items['admin/config/system/boost/default'] = array(
    'title' => 'Boost Settings',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/config/system/boost/debug'] = array(
    'title' => 'Debug',
119 120 121 122 123 124
    'description' => 'Debug configuration for Boost.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('boost_admin_debug_settings'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'boost.admin.debug.inc',
125
    'file path' => $path,
126
  );
127 128
  $items['admin/config/system/boost/filesystem'] = array(
    'title' => 'File System',
129 130 131 132 133 134
    'description' => 'File system configuration for Boost.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('boost_admin_filesystem_settings'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'boost.admin.filesystem.inc',
135
    'file path' => $path,
136
  );
137 138
  $items['admin/config/system/boost/htaccess'] = array(
    'title' => '.htaccess',
139 140 141 142 143 144
    'description' => '.htaccess configuration for Boost.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('boost_admin_htaccess_settings'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'boost.admin.htaccess.inc',
145
    'file path' => $path,
146
  );
147 148 149 150 151 152
  $items['admin/config/system/boost/htaccess/default'] = array(
    'title' => '.htaccess Settings',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/config/system/boost/htaccess/generator'] = array(
    'title' => '.htaccess Generation',
153 154 155 156 157 158
    'description' => '.htaccess generation for Boost.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('boost_admin_htaccess_generation'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'boost.admin.htaccess.inc',
159 160 161 162 163 164 165 166 167 168 169
    'file path' => $path,
  );
  $items['admin/config/system/boost/expiration'] = array(
    'title' => 'Cache Expiration',
    'description' => 'Cache expiration configuration for Boost.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('boost_admin_expiration_settings'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'boost.admin.expiration.inc',
    'file path' => $path,
mikeytown2's avatar
mikeytown2 committed
170
  );
171 172 173 174 175 176 177 178 179 180
  $items['admin/config/system/boost/listmodules'] = array(
    'title' => 'Boost Modules',
    'description' => ' Compatible Modules that add features to Boost.',
    'page callback' => 'boost_admin_modules_theme',
    'page callback' => 'boost_compatible_output',
    'access arguments' => array('administer site configuration'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'boost.admin.modules.inc',
    'weight' => 100,
  );
181

mikeytown2's avatar
mikeytown2 committed
182 183
  return $items;
}
184

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
/**
 * Implements hook_permissions().
 */
function boost_permission() {
  return array(
    'boost flush pages' => array(
      'title' => t('Flush pages from Boost cache'), 
      'description' => t('Allow users to flush individual pages from the Boost cache using the Boost status block.'),
    ),
  );
}

/**
 * Implements hook_block_info().
 */
function boost_block_info() {
  $blocks['status'] = array(
    'info' => t('Boost: Pages cache status'), 
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function boost_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'status':
      module_load_include('inc', 'boost', 'boost.blocks');
      return boost_block_view_status();
  }

  return $block;
}

mikeytown2's avatar
mikeytown2 committed
224
/**
225 226 227
 * Implements hook_init().
 *
 * Performs page setup tasks.
mikeytown2's avatar
mikeytown2 committed
228 229
 */
function boost_init() {
230
  global $_boost;
231

232 233
  $_boost = array();

234
  // Make sure the page is/should be cached according to our current configuration.
235
  // Start with the quick checks
mikeytown2's avatar
mikeytown2 committed
236 237
  if (   strpos($_SERVER['SCRIPT_FILENAME'], 'index.php') === FALSE
      || $_SERVER['SERVER_SOFTWARE'] === 'PHP CLI'
238
      || ($_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['REQUEST_METHOD'] != 'HEAD')
mikeytown2's avatar
mikeytown2 committed
239
      || isset($_GET['nocache'])
240 241
      || variable_get('maintenance_mode', 0)
      || defined('MAINTENANCE_MODE')
242
      || !empty($_SESSION['messages']) // do not cache pages with messages
243
  ) {
mikeytown2's avatar
mikeytown2 committed
244 245
    $_boost['cache_this'] = FALSE;
  }
246 247 248 249 250 251 252
  else {
    // More advanced checks
    $_boost = boost_transform_url();
    if (empty($_boost['menu_item']['status']) || $_boost['menu_item']['status'] != 200) {
      $_boost['cache_this'] = FALSE;
    }
  }
253 254 255 256 257 258 259 260

  // Give modules a chance to alter the cookie handler callback used.
  // hook_boost_cookie_handler_callback_alter
  $cookie_handler_callback = 'boost_cookie_handler';
  drupal_alter('boost_cookie_handler_callback', $cookie_handler_callback);
  if (function_exists($cookie_handler_callback)) {
    $cookie_handler_callback();
  }
mikeytown2's avatar
mikeytown2 committed
261
}
262

263 264 265 266 267 268 269 270 271
/**
 * Implements hook_drupal_goto_alter().
 */
function boost_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  global $_boost;
  // Bypass caching on redirects (issue #1176534).
  $_boost['is_cacheable'] = FALSE;
}

mikeytown2's avatar
mikeytown2 committed
272
/**
bgm's avatar
bgm committed
273
 * Implements hook_exit().
mikeytown2's avatar
mikeytown2 committed
274
 */
275
function boost_exit($destination = NULL) {
mikeytown2's avatar
mikeytown2 committed
276
  global $_boost;
277
  // Bail out of caching.
mikeytown2's avatar
mikeytown2 committed
278 279 280 281 282 283 284 285
  if (!isset($_boost['cache_this'])) {
    if (!isset($_boost['is_cacheable'])) {
      return;
    }
    elseif (!$_boost['is_cacheable']) {
      return;
    }
  }
286

287
  if (isset($_boost['cache_this']) && $_boost['cache_this'] == FALSE) {
mikeytown2's avatar
mikeytown2 committed
288 289
    return;
  }
290
  elseif (!isset($_boost['is_cacheable']) || !$_boost['is_cacheable']) {
mikeytown2's avatar
mikeytown2 committed
291 292
    return;
  }
293 294 295
  elseif ($_boost['menu_item']['status'] != 200) {
    return;
  }
296 297 298 299
  elseif (!drupal_page_is_cacheable()) {
    $_boost['is_cacheable'] = FALSE;
    return;
  }
300

301
  // Get the data to cache.
mikeytown2's avatar
mikeytown2 committed
302
  $data = ob_get_contents();
303

304 305 306 307
  // Get header info.
  $_boost['header_info'] = boost_get_header_info();
  $_boost['matched_header_info'] = boost_match_header_attributes($_boost['header_info']);
  if ($_boost['matched_header_info']['enabled'] === FALSE) {
mikeytown2's avatar
mikeytown2 committed
308 309
    return;
  }
310

311
  // Add note to bottom of content if possible.
312
  if ($_boost['matched_header_info']['comment_start'] && $_boost['matched_header_info']['comment_end']) {
313
    $expire = $_boost['matched_header_info']['lifetime_max'];
mikeytown2's avatar
mikeytown2 committed
314 315
    $cached_at = date('Y-m-d H:i:s', REQUEST_TIME);
    $expires_at = date('Y-m-d H:i:s', REQUEST_TIME + $expire);
316
    $note = "\n" . $_boost['matched_header_info']['comment_start'] . 'Page cached by Boost @ ' . $cached_at . ', expires @ ' . $expires_at . ', lifetime ' . format_interval($expire) . $_boost['matched_header_info']['comment_end'];
mikeytown2's avatar
mikeytown2 committed
317 318
    $data .= $note;
  }
319 320 321 322 323 324

  // Write data to a file.
  if ($_boost['filename']) {
    // Attach extension to filename.
    $_boost['filename'] .= '.' . $_boost['matched_header_info']['extension'];
    // Write to file.
325
    boost_write_file($_boost['filename'], $data);
ruloweb's avatar
ruloweb committed
326 327

    // Gzip support.
328
    if (BOOST_GZIP && $_boost['matched_header_info']['gzip']) {
329 330
      // #1416214
      // boost_write_file($_boost['filename'] . '.gz', gzencode($data, 9));
ruloweb's avatar
ruloweb committed
331
    }
mikeytown2's avatar
mikeytown2 committed
332 333
  }
}
334 335

/**
336
 * Implements hook_cron(). Performs periodic actions.
337
 */
mikeytown2's avatar
mikeytown2 committed
338
function boost_cron() {
339
  // Remove expired files from the cache.
mikeytown2's avatar
mikeytown2 committed
340
  global $_boost;
341 342 343 344 345

  // This was not invoked in hook_init because of the quick check to
  // avoid caching requests from the CLI
  $_boost = boost_transform_url();

346
  if (isset($_boost['base_dir']) && variable_get('boost_expire_cron', BOOST_EXPIRE_CRON)) {
347 348
    $count = _boost_rmdir($_boost['base_dir'], FALSE);
    watchdog('boost', 'Expired %count stale files from static page cache.', array('%count' => $count), WATCHDOG_NOTICE);
349 350 351
  }
}

352
/**
353
 * Implements hook_flush_caches(). Deletes all static files.
354
 */
mikeytown2's avatar
mikeytown2 committed
355 356 357
function boost_flush_caches() {
  // Remove all files from the cache
  global $_boost;
358 359 360 361 362

  // This may not have been invoked in hook_init because of the quick
  // check to avoid caching requests from the CLI
  $_boost = boost_transform_url();

363 364
  // The lock_may_be_available() checks to see if the flush was requested by
  // the core cron, since we may want to ignore it (boost_ignore_flush)
365
  if (isset($_boost['base_dir']) && (lock_may_be_available('cron') || variable_get('boost_ignore_flush', BOOST_IGNORE_FLUSH) == FALSE)) {
366 367
    $count = _boost_rmdir($_boost['base_dir'], TRUE);
    watchdog('boost', 'Flushed all files (%count) from static page cache.', array('%count' => $count), WATCHDOG_NOTICE);
mikeytown2's avatar
mikeytown2 committed
368 369
  }
  return;
370 371
}

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
/**
 * Implements hook_expire_cache (from the 'expire' module)
 */
function boost_expire_cache($urls) {
  global $base_root;

  foreach ($urls as $url) {
    // Check if the URL to be flushed matches our base URL
    if (strpos($base_root, $url) == 0) {
      $boost = boost_transform_url($url);

      // We need the extention for the filename
      $boost['header_info'] = boost_get_header_info();
      $boost['matched_header_info'] = boost_match_header_attributes($boost['header_info']);

      $filename = (isset($boost['filename']) ? $boost['filename'] . '.' . $boost['matched_header_info']['extension'] : NULL);

      if ($filename && file_exists($filename)) {
        if (unlink($filename)) {
391
          boost_log('Removed !file from the boost cache.', array('!file' => $filename), WATCHDOG_DEBUG);
392 393
        }
        else {
394
          boost_log('Could not delete !file from the boost cache. Check file permissions.', array('!file' => $filename), WATCHDOG_WARNING);
395 396 397
        }
      }
      else {
398
        boost_log('Could not delete the cache for !url, file !file does not exist.', array('!url' => $url, '!file' => $filename), WATCHDOG_DEBUG);
399 400 401 402 403
      }
    }
  }
}

404
/**
405 406 407 408 409 410 411 412
 * Implements hook_page_delivery_callback_alter().
 */
function boost_page_delivery_callback_alter(&$callback, $set = FALSE) {
  if ($callback == 'drupal_deliver_html_page') {
    $callback = 'boost_deliver_html_page';
  }
}

413
/**
mikeytown2's avatar
mikeytown2 committed
414 415 416 417 418 419
 * Given a URL give back eveything we know
 *
 * @param $url
 *   Full URL
 * @param $b_path
 *   Base Path
420
 */
mikeytown2's avatar
mikeytown2 committed
421 422 423 424
function boost_transform_url($url = NULL, $b_path = NULL) {
  global $base_root, $base_path;
  $items = &drupal_static(__FUNCTION__);

425
  // Set defaults if none passed in.
mikeytown2's avatar
mikeytown2 committed
426 427
  if ($url === NULL) {
    $url = $base_root . request_uri();
428
  }
mikeytown2's avatar
mikeytown2 committed
429 430 431 432 433 434 435 436 437 438 439
  if ($b_path == NULL) {
    $b_path = $base_path;
  }
  $hash = $url . ' ' . $b_path;

  if (!isset($items[$hash])) {
    $parts = boost_parse_url($url, $b_path);
    if (!$parts) {
      $items[$hash] = array('cache_this' => FALSE);
      return $items[$hash];
    }
440
    $parts['base_dir'] = boost_get_normal_cache_dir() . '/' . $parts['host'] . $b_path;
441
    $parts['filename'] = $parts['base_dir'] . $parts['full_path'] . variable_get('boost_char', BOOST_CHAR) . $parts['query'];
mikeytown2's avatar
mikeytown2 committed
442 443
    $parts['directory'] = dirname($parts['filename']);

444
    // Get the internal path (node/8).
mikeytown2's avatar
mikeytown2 committed
445 446 447 448 449 450
    if (drupal_is_front_page()) {
      $parts['normal_path'] = variable_get('site_frontpage', 'node');
    }
    else {
      $parts['normal_path'] = drupal_get_normal_path($parts['path']);
    }
451
    // Get the alias (content/about-us).
mikeytown2's avatar
mikeytown2 committed
452
    $parts['path_alias'] = drupal_get_path_alias($parts['normal_path']);
453
    // Get all args.
mikeytown2's avatar
mikeytown2 committed
454
    $args = arg(NULL, $parts['normal_path']);
455
    // Prevent array warnings.
mikeytown2's avatar
mikeytown2 committed
456 457 458 459 460
    $args[0] = empty($args[0]) ? '' : $args[0];
    $args[1] = empty($args[1]) ? '' : $args[1];
    $args[2] = empty($args[2]) ? '' : $args[2];
    $parts['args'] = $args;

461
    // Get content type.
462 463 464
    if (!empty($parts['normal_path'])) {
      $parts = _boost_get_menu_router($parts);
    }
465
    // See if url is cacheable.
mikeytown2's avatar
mikeytown2 committed
466 467 468 469 470
    $parts = boost_is_cacheable($parts);
    $items[$hash] = $parts;
  }

  return $items[$hash];
471 472
}

473 474 475 476 477 478 479
/**
 * Returns the relative normal cache dir. cache/normal.
 */
function boost_get_normal_cache_dir() {
  return variable_get('boost_root_cache_dir', BOOST_ROOT_CACHE_DIR) . '/' . variable_get('boost_normal_dir', BOOST_NORMAL_DIR);
}

480
/**
mikeytown2's avatar
mikeytown2 committed
481 482 483 484 485 486
 * parse_url that takes into account the base_path
 *
 * @param $url
 *   Full URL
 * @param $b_path
 *   Base Path
487
 */
mikeytown2's avatar
mikeytown2 committed
488 489
function boost_parse_url($url = NULL, $b_path = NULL) {
  global $base_root, $base_path;
490
  // Set defaults.
mikeytown2's avatar
mikeytown2 committed
491 492 493 494 495 496
  if ($url === NULL) {
    $url = $base_root . request_uri();
  }
  if ($b_path == NULL) {
    $b_path = $base_path;
  }
497

498
  // Parse url.
mikeytown2's avatar
mikeytown2 committed
499 500 501 502 503 504 505
  $parts = parse_url($url);
  if (empty($parts['host']) || empty($parts['path'])) {
    return FALSE;
  }
  if (!isset($parts['query'])) {
    $parts['query'] = '';
  }
Philip_Clarke's avatar
Philip_Clarke committed
506
  $parts['path'] = $parts['full_path'] = urldecode(preg_replace('/^' . preg_quote($b_path, '/') . '/i', '', $parts['path']));
mikeytown2's avatar
mikeytown2 committed
507 508 509 510
  $parts['base_path'] = $b_path;
  $parts['query_array'] = array();
  parse_str($parts['query'], $parts['query_array']);

511
  // Check if language prefix for urls is enabled.
512
  if (drupal_multilingual() && variable_get('locale_language_negotiation_url_part') == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
513 514 515 516 517 518
    // Get languages grouped by status and select only the enabled ones.
    $languages = language_list('enabled');
    $languages = $languages[1];
    list($language, $parts['path']) = language_url_split_prefix($parts['path'], $languages);
  }

519
  // Get page number and info from the query string.
mikeytown2's avatar
mikeytown2 committed
520 521 522 523 524 525 526 527 528
  if (!empty($parts['query_array'])) {
    $query = array();
    foreach ($parts['query_array'] as $key => $val) {
      if ($key != 'q' && $key != 'destination' && $key != 'page' && !empty($val)) {
        $query[$key] = $val;
      }
      if ($key == 'page' && is_numeric($val)) {
        $parts['page_number'] = $val;
      }
529
    }
mikeytown2's avatar
mikeytown2 committed
530
    ksort($query);
531
    $parts['query_extra'] = str_replace('&amp;', '&', urldecode(http_build_query($query)));
532 533
  }

534
  // Get fully decoded URL.
535
  $decoded1 = urldecode($parts['base_path'] . $parts['path'] . variable_get('boost_char', BOOST_CHAR) . $parts['query']);
mikeytown2's avatar
mikeytown2 committed
536 537 538 539 540 541 542 543 544
  $decoded2 = urldecode($decoded1);
  while ($decoded1 != $decoded2) {
    $decoded1 = urldecode($decoded2);
    $decoded2 = urldecode($decoded1);
  }
  $decoded = $decoded2;
  unset($decoded2);
  unset($decoded1);

545
  $parts['url_full'] = $parts['host'] . $parts['base_path'] . $parts['path'] . variable_get('boost_char', BOOST_CHAR) . $parts['query'];
mikeytown2's avatar
mikeytown2 committed
546 547 548 549
  $parts['url'] = $url;
  $parts['url_decoded'] = $decoded;
  return $parts;
}
550

mikeytown2's avatar
mikeytown2 committed
551 552 553 554 555 556 557
/**
 * Determines whether a given url can be cached or not by boost.
 *
 * TODO: Add in support for the menu_item
 *
 * @param $parts
 *   $parts
558 559 560 561 562 563
 * @param $request_type
 *   May be 'status' to skip some checks in order to show the status
 *   block on the admin interface (otherwise we will always mention
 *   that the page is non-cacheable, since user is logged in).
 *   Please don't rely on this parameter if you are extending boost,
 *   this is likely to change in the future. Contact us if you use it.
mikeytown2's avatar
mikeytown2 committed
564 565 566
 *
 * @return $parts
 */
567
function boost_is_cacheable($parts, $request_type = 'normal') {
568
  // Set local variables.
mikeytown2's avatar
mikeytown2 committed
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
  $path = $parts['path'];
  $query = $parts['query'];
  $full = $parts['url_full'];
  $normal_path = $parts['normal_path'];
  $alias = $parts['path_alias'];
  $decoded = $parts['url_decoded'];

  // Never cache
  //  the user autocomplete/login/registration/password/reset/logout pages
  //  any admin pages
  //  comment reply pages
  //  node add page
  //  openid login page
  //  URL variables that contain / or \
  //  if incoming URL contains '..' or null bytes
  //  if decoded URL contains :// outside of the host portion of the url
  //  Limit the maximum directory nesting depth of the path
586
  //  Do not cache if destination is set.
mikeytown2's avatar
mikeytown2 committed
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
  if (   $normal_path == 'user'
      || preg_match('!^user/(autocomplete|login|register|password|reset|logout)!', $normal_path)
      || preg_match('!^admin!', $normal_path)
      || preg_match('!^comment/reply!', $normal_path)
      || preg_match('!^node/add!', $normal_path)
      || preg_match('!^openid/authenticate!', $normal_path)
      || strpos($query, '/') !== FALSE
      || strpos($query, "\\") !== FALSE
      || strpos($full, '..') !== FALSE
      || strpos($full, "\0") !== FALSE
      || count(explode('/', $path)) > 10
      || strpos($decoded, "://") !== FALSE
      || !empty($query_array['destination'])
    ) {
    $parts['is_cacheable'] = FALSE;
602
    $parts['is_cacheable_reason'] = 'Core Drupal dynamic pages';
mikeytown2's avatar
mikeytown2 committed
603 604 605
    return $parts;
  }

606
  // Check for reserved characters if on windows.
mikeytown2's avatar
mikeytown2 committed
607 608 609 610 611
  // http://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
  // " * : < > |
  $chars = '"*:<>|';
  if (stristr(PHP_OS, 'WIN') && preg_match("/[" . $chars . "]/", $full)) {
    $parts['is_cacheable'] = FALSE;
612
    $parts['is_cacheable_reason'] = 'Reserved characters on MS Windows';
mikeytown2's avatar
mikeytown2 committed
613 614
    return $parts;
  }
615

616
  // Match the user's cacheability settings against the path.
mikeytown2's avatar
mikeytown2 committed
617
  // See http://api.drupal.org/api/function/block_block_list_alter/7
618
  $visibility = variable_get('boost_cacheability_option', BOOST_VISIBILITY_NOTLISTED);
mikeytown2's avatar
mikeytown2 committed
619 620 621 622 623
  $pages_setting = variable_get('boost_cacheability_pages', BOOST_CACHEABILITY_PAGES);
  if ($pages_setting) {
    // Convert path string to lowercase. This allows comparison of the same path
    // with different case. Ex: /Page, /page, /PAGE.
    $pages = drupal_strtolower($pages_setting);
624
    if ($visibility < BOOST_VISIBILITY_PHP) {
625
      // Convert the alias to lowercase.
mikeytown2's avatar
mikeytown2 committed
626 627 628 629 630 631
      $path = drupal_strtolower($alias);
      // Compare the lowercase internal and lowercase path alias (if any).
      $page_match = drupal_match_path($path, $pages);
      if ($path != $normal_path) {
        $page_match = $page_match || drupal_match_path($normal_path, $pages);
      }
632
      // When 'boost_cacheability_option' has a value of 0 (BOOST_VISIBILITY_NOTLISTED),
mikeytown2's avatar
mikeytown2 committed
633
      // Boost will cache all pages except those listed in 'boost_cacheability_pages'.
634
      // When set to 1 (BOOST_VISIBILITY_LISTED), Boost will only cache those
mikeytown2's avatar
mikeytown2 committed
635 636 637 638 639
      // pages listed in 'boost_cacheability_pages'.
      $page_match = !($visibility xor $page_match);
    }
    elseif (module_exists('php')) {
      $page_match = php_eval($pages_setting);
640
    }
mikeytown2's avatar
mikeytown2 committed
641 642 643 644 645 646 647
    else {
      $page_match = FALSE;
    }
  }
  else {
    $page_match = TRUE;
  }
648

mikeytown2's avatar
mikeytown2 committed
649
  $parts['is_cacheable'] = $page_match;
650 651 652 653 654

  if (! $page_match) {
    $parts['is_cacheable_reason'] = 'Page excluded from cache by the include/exclude paths defined by site admin.';
  }

mikeytown2's avatar
mikeytown2 committed
655 656 657 658
  if (!$parts['is_cacheable']) {
    return $parts;
  }

659
  // Invoke hook_boost_is_cacheable($path).
mikeytown2's avatar
mikeytown2 committed
660 661
  $modules = boost_module_implements('boost_is_cacheable', 'boost');
  foreach ($modules as $module) {
662
    $result = module_invoke($module, 'boost_is_cacheable', $parts, $request_type);
663
    if ($result['is_cacheable'] === FALSE) {
664 665 666 667
      if (! isset($result['is_cacheable'])) {
        $result['is_cacheable_reason'] = 'Page excluded from cache by a third-party module.';
      }

mikeytown2's avatar
mikeytown2 committed
668
      return $result;
669 670
    }
  }
671 672

  return $result;
673 674
}

675
/**
676
 * Implements hook_boost_is_cacheable().
677
 *
mikeytown2's avatar
mikeytown2 committed
678
 * TODO support for node types, etc.
679
 *
mikeytown2's avatar
mikeytown2 committed
680 681
 * @param $parts
 *   info about this request
682 683 684 685
 * @param $request_type
 *   if the request_type is "status", we assume that this is being
 *   called from the admin status block. Since the user must be
 *   logged in to view this block, we do not return false.
686
 *
mikeytown2's avatar
mikeytown2 committed
687
 * @return $parts
688
 */
689
function boost_boost_is_cacheable($parts, $request_type = 'normal') {
690
  global $user;
691
  if ($user->uid != 0 && $request_type != 'status') {
692
    $parts['is_cacheable'] = FALSE;
693
    $parts['is_cacheable_reason'] = 'Boost only works for anonymous users.';
694 695 696 697
  }
  else {
    $parts['is_cacheable'] = TRUE;
  }
mikeytown2's avatar
mikeytown2 committed
698
  return $parts;
699 700
}

701
/**
mikeytown2's avatar
mikeytown2 committed
702 703 704 705 706 707 708
 * Sets a special cookie preventing authenticated users getting served pages
 * from the static page cache.
 *
 * @param $uid
 *   User ID Number
 * @param $expires
 *   Expiration time
709
 */
mikeytown2's avatar
mikeytown2 committed
710 711 712 713 714 715 716 717
function boost_set_cookie($uid, $expires = NULL) {
  if (!$expires) {
    $expires = ini_get('session.cookie_lifetime');
    $expires = (!empty($expires) && is_numeric($expires)) ? REQUEST_TIME + (int)$expires : 0;
    setcookie(BOOST_COOKIE, strval($uid), $expires, ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure') == '1');
  }
  else {
    setcookie(BOOST_COOKIE, '0', $expires, ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure') == '1');
718 719 720
  }
}

721 722 723 724 725 726 727 728
/**
 * Logic for the setting and removal of the boost cookie.
 */
function boost_cookie_handler() {
  global $user;

  // Check if Drupal is started from index.php - could cause problems with other
  // contrib modules like ad module.
729 730 731 732
  if (strpos($_SERVER['SCRIPT_FILENAME'], 'index.php') === FALSE) {
    return;
  }

733
  $uid = isset($user->uid) ? $user->uid : 0;
734 735 736 737
  // Remove Boost cookie at logout if it still exists.
  if (isset($_COOKIE[BOOST_COOKIE]) && $uid == 0) {
    boost_set_cookie($uid, REQUEST_TIME - 86400);
  }
738 739 740 741 742
  // Set Boost cookie if it doesn't exists (or is -1 likely because of a login POST) and user is logged in.
  // c.f. Issue #1616356 comment #7
  elseif ((!isset($_COOKIE[BOOST_COOKIE]) || $_COOKIE[BOOST_COOKIE] == '-1') && $uid != 0) {
    boost_set_cookie($uid);
  }
743 744 745 746 747 748 749 750 751 752 753 754
  // Remove Boost cookie if set to -1 & Request Method is a GET/HEAD.
  elseif (isset($_COOKIE[BOOST_COOKIE]) && $_COOKIE[BOOST_COOKIE] == '-1' && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')) {
    boost_set_cookie($uid, REQUEST_TIME - 86400);
  }

  // Issue #1242416: Set a nocache cookie on a POST, remove it immediately after
  // (on GET) Only necessary for anon users, since we already do not cache for
  // logged in users. Also note that if we are processing a GET, it means that
  // we have already been through the htaccess rules, so the cookie has done
  // its job and can be removed.
  if ($uid == 0 && $_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['REQUEST_METHOD'] != 'HEAD') {
    boost_set_cookie(-1);
755 756 757
  }
}

758
/**
759
 * Gets menu router contex.
mikeytown2's avatar
mikeytown2 committed
760
 *
761 762
 * Allows for any content type to have it's own cache expiration among
 * other things.
mikeytown2's avatar
mikeytown2 committed
763 764 765 766 767
 *
 * @param $parts
 *
 * @return $parts
 *
768
 */
mikeytown2's avatar
mikeytown2 committed
769
function _boost_get_menu_router($parts) {
770
  // Declare array keys.
mikeytown2's avatar
mikeytown2 committed
771 772 773
  $router_item = array();
  $router_item['page_type'] = '';
  $router_item['page_id'] = '';
774
  // Load the menu item.
mikeytown2's avatar
mikeytown2 committed
775 776 777
  $item = menu_get_item($parts['normal_path']);
  if (is_array($item)) {
    $router_item += $item;
778 779 780 781 782 783
    if ($router_item['access']) {
      $router_item['status'] = 200;
    }
    else {
      $router_item['status'] = 403;
    }
mikeytown2's avatar
mikeytown2 committed
784
  }
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
  else {
    $router_item['status'] = 404;
  }

  // Get any extra arguments.
  if (!empty($router_item['path'])) {
    $menu_args = arg(NULL, $router_item['path']);
    $diff = array();
    foreach ($parts['args'] as $key => $value) {
      if (!empty($value)) {
        if (isset($menu_args[$key])) {
          if ($value !== $menu_args[$key] && $menu_args[$key] !== '%') {
            $diff[] = $value;
          }
        }
        else {
          $diff[] = $value;
        }
      }
mikeytown2's avatar
mikeytown2 committed
804 805 806 807 808 809 810 811 812
    }
  }
  if (!empty($diff)) {
    $router_item['extra_arguments'] = implode('/', $diff);
  }
  else {
    $router_item['extra_arguments'] = '';
  }

813 814
  // Make sure function for menu callback is loaded.
  // See menu_execute_active_handler()
815
  if (!empty($router_item['include_file'])) {
816 817 818
    require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
  }

mikeytown2's avatar
mikeytown2 committed
819
  $parts['menu_item'] = $router_item;
820
  // Invoke hook_boost_menu_router($router_item).
mikeytown2's avatar
mikeytown2 committed
821 822 823
  $modules = boost_module_implements('boost_menu_router', 'boost');
  foreach ($modules as $module) {
    if (($result = module_invoke($module, 'boost_menu_router', $parts)) !== NULL) {
824
      break;
mikeytown2's avatar
mikeytown2 committed
825
    }
826
  }
827 828 829 830 831 832

  // Remove extra data from the load function
  unset($result['menu_item']['map']);
  unset($result['menu_item']['page_arguments']);

  return $result;
833 834 835
}

/**
836
 * Implements hook_boost_menu_router().
mikeytown2's avatar
mikeytown2 committed
837 838 839 840 841 842 843
 *
 * TODO Better support for arguments.
 *
 * @param $parts
 *   info about this request
 *
 * @return $parts
844
 */
mikeytown2's avatar
mikeytown2 committed
845
function boost_boost_menu_router($parts) {
846
  // Handle nodes.
mikeytown2's avatar
mikeytown2 committed
847 848 849 850 851 852 853 854 855
  if ($parts['args'][0] == 'node' && is_numeric($parts['args'][1])) {
    $node = node_load($parts['args'][1]);
    $parts['menu_item']['page_callback'] = 'node';
    $parts['menu_item']['page_id'] = $parts['args'][1];
    if ($node) {
      $parts['menu_item']['page_type'] = $node->type;
    }
    return $parts;
  }
856 857

  // Handle taxonomy.
mikeytown2's avatar
mikeytown2 committed
858 859 860 861 862 863 864 865 866 867
  if ($parts['args'][0] == 'taxonomy' && is_numeric($parts['args'][2])) {
    $term = taxonomy_term_load($parts['args'][2]);
    $parts['menu_item']['page_callback'] = 'taxonomy';
    $parts['menu_item']['page_id'] = $parts['args'][2];
    if ($term) {
      $vocab = taxonomy_vocabulary_load($term->vid);
      $parts['menu_item']['page_type'] = $vocab->name;
    }
    return $parts;
  }
868 869

  // Handle users.
mikeytown2's avatar
mikeytown2 committed
870 871 872 873 874 875 876 877 878
  if ($parts['args'][0] == 'user' && is_numeric($parts['args'][1])) {
    $user = user_load($parts['args'][1]);
    $parts['menu_item']['page_callback'] = 'user';
    $parts['menu_item']['page_id'] = $parts['args'][1];
    if ($user !== FALSE) {
      $parts['menu_item']['page_type'] = implode(', ', $user->roles);
    }
    return $parts;
  }
879 880 881

  // Handle views.
  if (isset($parts['menu_item']['page_callback']) && $parts['menu_item']['page_callback'] == 'views_page') {
882 883 884 885 886 887 888
    $page_arguments = $parts['menu_item']['page_arguments'];

    // Issue #1364090 : views with access control have serialized page arguments
    if (! is_array($page_arguments)) {
      $page_arguments = unserialize($page_arguments);
    }

mikeytown2's avatar
mikeytown2 committed
889
    $parts['menu_item']['page_callback'] = 'view';
890 891
    $parts['menu_item']['page_type'] = array_shift($page_arguments);
    $parts['menu_item']['page_id'] = array_shift($page_arguments);
mikeytown2's avatar
mikeytown2 committed
892 893 894 895 896 897 898
    // See http://drupal.org/node/651798 for the reason why this if is needed
    if (is_array($parts['menu_item']['page_id'])) {
      $parts['menu_item']['page_id'] = array_shift($parts['menu_item']['page_id']);
    }
    return $parts;
  }

899 900
  // Handle panels.
  if (isset($parts['menu_item']['page_callback']) && $parts['menu_item']['page_callback'] == 'page_manager_page_execute') {
901 902 903 904 905 906 907 908
    $page_arguments = $parts['menu_item']['page_arguments'];

    // Issue #1653206 : panels with access control have serialized page arguments
    if (! is_array($page_arguments)) {
      $page_arguments = unserialize($page_arguments);
    }

    $subtask_id = array_shift($page_arguments);
mikeytown2's avatar
mikeytown2 committed
909 910 911 912 913 914 915 916 917
    $page = page_manager_page_load($subtask_id);
    $task = page_manager_get_task($page->task);
    if ($function = ctools_plugin_get_function($task, 'page callback')) {
      $parts['menu_item']['page_callback'] = $function;
    }
    $parts['menu_item']['page_type'] = $page->task;
    $parts['menu_item']['page_id'] = $page->name;
    return $parts;
  }
918

919 920
  // Try to handle everything else.
  elseif (isset($parts['menu_item']['page_arguments']) && is_array($parts['menu_item']['page_arguments'])) {
mikeytown2's avatar
mikeytown2 committed
921 922 923 924 925 926 927 928
    foreach ($parts['menu_item']['page_arguments'] as $string) {
      if (is_string($string) && empty($parts['menu_item']['page_type'])) {
        $parts['menu_item']['page_type'] = $string;
      }
      elseif (is_string($string)) {
        $parts['menu_item']['page_id'] .= $string;
      }
    }
929
  }
930

mikeytown2's avatar
mikeytown2 committed
931 932 933 934 935 936 937 938
  // If router doesn't hold the the arguments, get them from the URL.
  if (empty($parts['menu_item']['page_type'])) {
    $parts['menu_item']['page_type'] = $parts['menu_item']['extra_arguments'];
  }
  elseif (empty($parts['menu_item']['page_id'])) {
    $parts['menu_item']['page_id'] = $parts['menu_item']['extra_arguments'];
  }

939 940 941
  // Try populating with the query string.
  if (empty($parts['menu_item']['page_type']) && !empty($parts['query_extra'])) {
    $parts['menu_item']['page_type'] = $parts['query_extra'];
mikeytown2's avatar
mikeytown2 committed
942
  }
943 944
  elseif (empty($parts['menu_item']['page_id']) && !empty($parts['query_extra'])) {
    $parts['menu_item']['page_id'] = $parts['query_extra'];
mikeytown2's avatar
mikeytown2 committed
945 946 947
  }

  return $parts;
948 949 950
}

/**
951
 * Alters module_implements to set a hook to fire at the end.
mikeytown2's avatar
mikeytown2 committed
952 953
 *
 * @param $hook
954
 *   Name of hook.
mikeytown2's avatar
mikeytown2 committed
955
 * @param $name
956
 *   Module name to shift to the end of the array.
mikeytown2's avatar
mikeytown2 committed
957 958
 *
 * @return array
959
 */
mikeytown2's avatar
mikeytown2 committed
960 961 962 963 964 965 966 967
function boost_module_implements($hook, $name) {
  $modules = module_implements($hook);
  // Make $names built in hook the last one.
  $pos = array_search($name, $modules);
  if ($pos !== FALSE) {
    $temp = $modules[$pos];
    unset($modules[$pos]);
    $modules[] = $temp;
968
  }
mikeytown2's avatar
mikeytown2 committed
969
  return $modules;
970 971 972
}

/**
mikeytown2's avatar
mikeytown2 committed
973 974 975 976 977
 * Gets and parses the header info.
 *
 * @see drupal_send_headers()
 *
 * @return array
978
 *   Contains info about the page that is about to be sent.
979
 */
mikeytown2's avatar
mikeytown2 committed
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
function boost_get_header_info() {
  $headers = drupal_get_http_header();
  $status = '200 OK';
  $status_number = '200';
  $content_type = 'text/html; charset=utf-8';
  $content_type_basic = 'text/html';
  $charset = 'utf-8';

  foreach ($headers as $name_lower => $value) {
    if ($name_lower == 'status') {
      $status = $value;
    }
    elseif ($name_lower == 'content-type') {
      $content_type = $value;
    }
  }
996

mikeytown2's avatar
mikeytown2 committed
997 998 999 1000 1001 1002 1003 1004
  preg_match('!^(\d+)!', $status, $matches);
  if (isset($matches[1])) {
    $status_number = (int) $matches[1];
  }
  $content_type_info = explode('; charset=', $content_type);
  $content_type_basic = array_shift($content_type_info);
  if (!empty($content_type_info)) {
    $charset = array_shift($content_type_info);
1005
  }
mikeytown2's avatar
mikeytown2 committed
1006 1007 1008 1009 1010 1011 1012 1013 1014

  return array(
    'status' => $status,
    'status-number' => $status_number,
    'content-type' => $content_type,
    'content-type-basic' => $content_type_basic,
    'charset' => $charset,
    'headers_sent' => headers_sent(),
  );
1015 1016 1017
}

/**
mikeytown2's avatar
mikeytown2 committed
1018 1019 1020 1021 1022 1023
 * Given header info, match it to a file extension
 *
 * @param $header_info
 *   array contains header info
 *
 * @return array
1024
 */
mikeytown2's avatar
mikeytown2 committed
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
function boost_match_header_attributes($header_info) {
  $type = $header_info['content-type-basic'];
  $enabled = variable_get('boost_enabled_' . $type, -1);
  if ($enabled === -1) {
    boost_get_storage_types();
    $enabled = variable_get('boost_enabled_' . $type, -1);
    if ($enabled === -1) {
      variable_set('boost_enabled_' . $type, FALSE);
      $enabled = FALSE;
    }
  }
  if (!$enabled) {
    return array('enabled' => FALSE);
1038
  }
mikeytown2's avatar
mikeytown2 committed
1039 1040 1041

  $keys = array(
    'enabled',
1042
    'gzip',
mikeytown2's avatar
mikeytown2 committed
1043 1044 1045
    'extension',
    'lifetime_max',
    'lifetime_min',
1046 1047
    'comment_start',
    'comment_end',
mikeytown2's avatar
mikeytown2 committed
1048 1049 1050 1051 1052 1053 1054 1055 1056
  );
  $info = array();
  foreach ($keys as $key) {
    $info[$key] = variable_get('boost_' . $key . '_' . $type, -1);
    if ($info[$key] === -1) {
      return array('enabled' => FALSE);
    }
  }
  return $info;
1057 1058 1059
}

/**
1060
 * Get the storage types for the boost cache.
1061
 *
mikeytown2's avatar
mikeytown2 committed
1062 1063
 * @return $types
 *   array('title' => array('content-type' => $values));
1064
 */
mikeytown2's avatar
mikeytown2 committed
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
function boost_get_storage_types() {
  $primary_types = array();
  $secondary_types = array();

  // Force boost to be last in the array
  $modules = boost_module_implements('boost_storage_types', 'boost');

  // Module with the lightest weight runs last. They will then be able to change
  // the defaults and modules that are heavier
  $modules = array_reverse($modules);
  foreach ($modules as $module) {
    // Invoke hook_boost_storage_types()
    if (($result = module_invoke($module, 'boost_storage_types')) !== NULL) {
      foreach ($result as $key => $values) {
        if (!empty($values['variants'])) {
          foreach ($values['variants'] as $type) {
            $secondary_types[$type] = $values;
            unset($secondary_types[$type]['variants']);
          }
        }
        unset($values['variants']);
        $primary_types[$key] = $values;
      }
    }
  }
1090

mikeytown2's avatar
mikeytown2 committed
1091
  // Merge it all back together
1092
  $merged = array_merge($primary_types, $secondary_types);
mikeytown2's avatar
mikeytown2 committed
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
  $types = array();
  foreach ($merged as $type => $values) {
    if ($values['title']) {
      $title = $values['title'];
      unset($values['title']);
      $types[$title][$type] = $values;
    }
  }

  // Apply what's saved in the database
  $keys = array(
    'enabled',
    'extension',
1106
    'gzip',
mikeytown2's avatar
mikeytown2 committed
1107 1108
    'lifetime_max',
    'lifetime_min',
1109 1110
    'comment_start',
    'comment_end',
1111

mikeytown2's avatar
mikeytown2 committed
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
  );
  foreach ($types as $title => $content_types) {
    foreach ($content_types as $type => $values) {
      foreach ($keys as $key) {
        $types[$title][$type][$key] = variable_get('boost_' . $key . '_' . $type, $values[$key]);
        // Set variable in DB if it has never been set before
        if (variable_get('boost_' . $key . '_' . $type, -1) === -1) {
          variable_set('boost_' . $key . '_' . $type, $values[$key]);
        }
      }
    }
  }

  return $types;
}
1127 1128

/**
1129
 * Implements hook_boost_storage_types().
1130
 *
mikeytown2's avatar
mikeytown2 committed
1131
 * @return $types
1132
 */
mikeytown2's avatar
mikeytown2 committed
1133 1134 1135 1136 1137 1138 1139 1140
function boost_boost_storage_types() {
  $types = array();

  $types['text/html'] = array(
    'title'           => t('HTML'),
    'description'     => t('HTML output, usually a webpage'),
    'extension'       => 'html',
    'enabled'         => TRUE,
1141
    'gzip'            => TRUE,
mikeytown2's avatar
mikeytown2 committed
1142 1143
    'lifetime_max'    => 3600,
    'lifetime_min'    => 0,
1144 1145
    'comment_start'  => '<!-- ',
    'comment_end'    => ' -->',
mikeytown2's avatar
mikeytown2 committed
1146 1147 1148 1149 1150 1151 1152
    'variants'        => array(),
  );
  $types['text/xml'] = array(
    'title'           => t('XML'),
    'description'     => t('XML output, usually a feed'),
    'extension'       => 'xml',
    'enabled'         => FALSE,
1153
    'gzip'            => TRUE,
mikeytown2's avatar
mikeytown2 committed
1154 1155
    'lifetime_max'    => 3600,
    'lifetime_min'    => 0,
1156 1157
    'comment_start'  => '<!-- ',
    'comment_end'    => ' -->',
mikeytown2's avatar
mikeytown2 committed
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
    'variants'        => array(
      'application/xml',
      'application/rss',
      'application/rss+xml',
    ),
  );
  $types['text/javascript'] = array(
    'title'           => t('AJAX/JSON'),
    'description'     => t('JSON output, usually a response to a AJAX request'),
    'extension'       => 'json',
    'enabled'         => FALSE,
1169
    'gzip'            => TRUE,
mikeytown2's avatar
mikeytown2 committed
1170 1171
    'lifetime_max'    => 3600,
    'lifetime_min'    => 0,
1172 1173
    'comment_start'  => '/* ',
    'comment_end'    => ' */',
mikeytown2's avatar
mikeytown2 committed
1174 1175 1176 1177
    'variants'        => array(),
  );
  return $types;
}
1178

mikeytown2's avatar
mikeytown2 committed
1179 1180 1181
/**
 * Recursive version of rmdir(); use with extreme caution.
 *
1182 1183
 * Function also checks file age and only removes expired files.
 *
mikeytown2's avatar
mikeytown2 committed
1184
 * @param $dir
1185
 *   The top-level directory that will be recursively removed.
1186 1187
 * @param $flush
 *   Instead of removing expired cached files, remove all files.
mikeytown2's avatar
mikeytown2 committed
1188 1189 1190
 */
function _boost_rmdir($dir, $flush = TRUE) {
  static $lifetimes = array();
1191 1192 1193 1194 1195 1196 1197 1198 1199
  static $counter = 0;
  if (is_dir($dir) == FALSE) {
    return FALSE;
  }

  if (!boost_in_cache_dir($dir)) {
    return FALSE;
  }

mikeytown2's avatar
mikeytown2 committed
1200 1201 1202 1203 1204 1205 1206
  // Map extensions to cache lifetimes
  if (empty($lifetimes)) {
    $types = boost_get_storage_types();
    foreach ($types as $title => $content_types) {
      foreach ($content_types as $type => $values) {
        $lifetimes[$values['extension']] = $values['lifetime_max'];
      }
1207
    }
1208 1209 1210

    // Be sure to recreate the htaccess file just in case.
    boost_form_submit_handler();
1211 1212
  }

1213 1214 1215
  $objects = scandir($dir);
  $empty_dir = TRUE;
  foreach ($objects as $object) {
1216 1217 1218 1219 1220
    if ($object == "." || $object == "..") {
      continue;
    }
    if ($object == ".htaccess") {
      $empty_dir = FALSE;
1221
      continue;
mikeytown2's avatar
mikeytown2 committed
1222
    }
1223 1224 1225 1226

    $file = $dir . "/" . $object;
    if (is_dir($file)) {
      _boost_rmdir($file, $flush);
mikeytown2's avatar
mikeytown2 committed
1227
    }
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
    elseif ($flush) {
      unlink($file);
      $counter++;
    }
    else {
      // Need to handle gzipped files.
      // Nice if  it supported multi level cache expiration per content type.
      $ext = substr(strrchr($file, '.'), 1);
      $age = boost_file_get_age($file);
      if (isset($lifetimes[$ext]) && $age > $lifetimes[$ext]) {
        unlink($file);
        $counter++;
      }
      else {
        $empty_dir = FALSE;
      }
    }
  }
1246 1247 1248
  if ($empty_dir && is_dir($dir)) {
    // #1138630 @ error suppression used due to rmdir being a race condition.
    @rmdir($dir);
mikeytown2's avatar
mikeytown2 committed
1249
  }
1250
  return $counter;
1251 1252 1253
}

/**
mikeytown2's avatar
mikeytown2 committed
1254 1255
 * Returns the age of a cached file, measured in seconds since it was last
 * updated.
1256
 *
mikeytown2's avatar
mikeytown2 committed
1257 1258 1259
 * @param $filename
 *   Name of cached file
 * @return int
1260
 */
mikeytown2's avatar
mikeytown2 committed
1261 1262
function boost_file_get_age($filename) {
  return REQUEST_TIME - filemtime($filename);
1263
}
1264

1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
/**
 * Returns a nice html formatted version of print_r
 *
 * @param $data
 *
 * @return string
 */
function boost_print_r($data) {
  return str_replace('    ', '&nbsp;&nbsp;&nbsp;&nbsp;', nl2br(htmlentities(print_r($data, TRUE))));
}

/**
1277
 * Write to a file. Ensures write is atomic via rename operation.
1278 1279 1280 1281 1282 1283
 *
 * @param $filename
 *  relative filename.
 * @param $data
 *  data to write to the file.
 */
1284
function boost_write_file($filename, $data) {
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
  // Create directory if it doesn't exist.
  $directory = dirname($filename);
  if (!boost_mkdir($directory)) {
    return FALSE;
  }

  // Save data to a temp file.
  // file_unmanaged_save_data does not use rename.
  $tempname = drupal_tempnam($directory, 'boost');
  if (file_put_contents($tempname, $data) === FALSE) {
    watchdog('boost', 'Could not create the file %file on your system', array('%file' => $tempname), WATCHDOG_ERROR);
    @unlink($tempname);
    return FALSE;
  }

  // Move temp file to real filename; windows can not do a rename replace.
  if (@rename($tempname, $filename) === FALSE) {
Philip_Clarke's avatar
Philip_Clarke committed
1302
    $oldname = $tempname . 'old';
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
    if (@rename($filename, $oldname) !== FALSE) {
      if (@rename($tempname, $filename) === FALSE) {
        watchdog('boost', 'Could not rename the file %file on your system', array('%file' => $filename), WATCHDOG_ERROR);
        @unlink($tempname);
        @rename($oldname, $filename);
        return FALSE;
      }
      else {
        @unlink($oldname);
      }
1313 1314
    }
  }
1315 1316 1317

  // chmod file so webserver can send it out.
  drupal_chmod($filename);
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
  return TRUE;
}

/**
 * Create a directory.
 *
 * @param $directory
 *  relative directory.
 */
function boost_mkdir($directory) {
  global $_boost;

1330
  // Only do something if it's not a dir.
1331
  if (!is_dir($directory)) {
1332
    if (!boost_in_cache_dir($directory)) {
1333 1334 1335 1336
      return FALSE;
    }

    // Try to create the directory.
1337 1338
    $mode = variable_get('file_chmod_directory', 0775);
    if (!mkdir($directory, $mode, TRUE)) {
1339 1340 1341
      watchdog('boost', 'Could not create the directory %dir on your system', array('%dir' => $directory), WATCHDOG_ERROR);
      return FALSE;
    }
1342
    drupal_chmod($directory);
1343 1344 1345 1346
  }
  return TRUE;
}

1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
/**
 * Verify that the operation is going to operate in the cache dir.
 *
 * @param $file
 *  relative directory or file.
 */
function boost_in_cache_dir($file) {
  global $_boost;

  $good = TRUE;
  $real_file = realpath($file);
  $cache_dir = variable_get('boost_root_cache_dir', BOOST_ROOT_CACHE_DIR);
  $real_cache_dir = realpath($cache_dir);

  // Only operate in the cache dir.
  // Check the real path.
  if (   strpos($file, $cache_dir) !== 0
      || ($real_file && $real_cache_dir && strpos($real_file, $real_cache_dir) !== 0)
        ) {
    $good = FALSE;
  }

  // Send error to watchdog.
  if (!$good) {
    watchdog('boost', 'An operation outside of the cache directory was attempted on your system. %file or %real_file is outside the cache directory %cache or %real_cache. Debug info below <br> !debug', array(
      '%file'       => $file,
      '%real_file'  => $real_file,
      '%cache'      => $cache_dir,
      '%real_cache' => $real_cache_dir,
      '!debug'      => boost_print_r($_boost),
      ),
    WATCHDOG_CRITICAL);
  }

  return $good;
}

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
/**
 * Capture error conditions.
 *
 * @param $page_callback_result
 *   The result of a page callback. Can be one of:
 *   - NULL: to indicate no content.
 *   - An integer menu status constant: to indicate an error condition.
 *   - A string of HTML content.
 *   - A renderable array of content.
 *
 * @see drupal_deliver_html_page()
 */
function boost_deliver_html_page($page_callback_result) {
  global $_boost;

  // Menu status constants are integers; page content is a string or array.
  if (is_int($page_callback_result)) {
    // @todo: Break these up into separate functions?
    switch ($page_callback_result) {
      case MENU_NOT_FOUND:
        // 404 page.
        $_boost['menu_item']['status'] = 404;
        break;

      case MENU_ACCESS_DENIED:
        // 403 page.
        $_boost['menu_item']['status'] = 403;
        break;

      case MENU_SITE_OFFLINE:
        // 503 page.
        $_boost['menu_item']['status'] = 503;
        break;
    }
  }

  // Call original function
  drupal_deliver_html_page($page_callback_result);
1422 1423 1424 1425 1426

  // Last possible place to send a watchdog message without a shutdown function.
  if (variable_get('boost_message_debug', BOOST_MESSAGE_DEBUG) && $_boost['args'][0] != 'admin') {
    watchdog('boost', boost_print_r($_boost), array(), WATCHDOG_DEBUG);
  }
1427
}
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439

/**
 * Always run these functions after a form submit from boost.
 */
function boost_form_submit_handler() {
  register_shutdown_function('boost_htaccess_cache_dir_put');
}

/**
 * Overwrite old htaccess rules with new ones.
 */
function boost_htaccess_cache_dir_put() {
1440
  global $_boost, $base_path, $base_root;
1441
  if (empty($_boost['base_dir'])) {
1442 1443 1444
    $url = $base_root . request_uri();
    $parts = parse_url($url);
    $_boost['base_dir'] = boost_get_normal_cache_dir() . '/' . $parts['host'] . $base_path;
1445
  }
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
  boost_write_file($_boost['base_dir'] . '.htaccess', boost_htaccess_cache_dir_generate());
}

/**
 * Generate htaccess rules for the cache directory.
 */
function boost_htaccess_cache_dir_generate() {
  $char_type = variable_get('boost_charset_type', BOOST_CHARSET_TYPE);
  $etag = variable_get('boost_apache_etag', BOOST_APACHE_ETAG);

  // Go through every storage type getting data needed to build htaccess file.
  $gzip = FALSE;
  $data = array();
  $files = array();
  $types = boost_get_storage_types();
  foreach ($types as $title => $content_types) {
    foreach ($content_types as $type => $values) {
      if ($values['enabled']) {
        $forcetype = '\.' . $values['extension'];
        if ($values['gzip']) {
1466
          $forcetype .= '(\.gz)?$';
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
          $gzip = TRUE;
        }
        else {
          $forcetype .= '$';
        }
        $files[$values['extension']] = $values['extension'];
        $data[$values['extension']] = array(
          'type' => $type,
          'forcetype' => $forcetype,
        );
      }
    }
  }
  if (empty($data) || empty($files)) {
    return FALSE;
  }

  // Add in default charset
  $string = '';
  if (variable_get('boost_add_default_charset', BOOST_ADD_DEFAULT_CHARSET)) {
    $string .= "AddDefaultCharset " . $char_type . "\n";
  }

  // Set FileETag
  if ($etag == 1) {
    $string .= "FileETag None\n";
  }
  elseif ($etag == 2) {
    $string .= "FileETag All\n";
  }
  elseif ($etag == 3) {
    $string .= "FileETag MTime Size\n";
  }

  // Set html expiration time to the past and put in boost header if desired.
1502
  $files = '(' . implode('|' , $files) . ')';
1503
  if ($gzip) {
1504
    $files .= '(\.gz)?';
1505
  }
1506
  $string .= "<FilesMatch \"\.$files$\">\n";
1507
  $string .= "  <IfModule mod_expires.c>\n";
1508
  $string .= "    ExpiresDefault A5\n";
1509 1510 1511
  $string .= "  </IfModule>\n";
  $string .= "  <IfModule mod_headers.c>\n";
  $string .= "    Header set Expires \"Sun, 19 Nov 1978 05:00:00 GMT\"\n";
1512 1513
  $string .= "    Header unset Last-Modified\n";
  $string .= "    Header append Vary Accept-Encoding\n";
1514 1515
  $string .= "    Header set Cache-Control \"no-store, no-cache, must-revalidate, post-check=0, pre-check=0\"\n";
  if (variable_get('boost_apache_xheader', BOOST_APACHE_XHEADER) > 0) {
1516
    $string .= "    Header set X-Cached-By \"Boost\"\n";
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
  }
  $string .= "  </IfModule>\n";
  $string .= "</FilesMatch>\n";

  // Set charset and content encoding.
  $string .= "<IfModule mod_mime.c>\n";
  foreach ($data as $extension => $values) {
    $string .= "  AddCharset " . $char_type . " ." . $extension . "\n";
  }
  $string .= $gzip ? "  AddEncoding gzip .gz\n" : '';
  $string .= "</IfModule>\n";

  // Fix for versions of apache that do not respect the T='' RewriteRule
  foreach ($data as $extension => $values) {
    $forcetype = $values['forcetype'];
    $type = $values['type'];
    $string .= "<FilesMatch \"$forcetype\">\n";
    $string .= "  ForceType " . $type . "\n";
    $string .= "</FilesMatch>\n";
  }

  // Make sure files can not execute in the cache dir.
  $string .= "\n";
  $string .= "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\n";
  $string .= "Options None\n";
1542
  $string .= "Options +" . ( variable_get('boost_match_symlinks_options', BOOST_MATCH_SYMLINKS_OPTIONS) ? "FollowSymLinks" : "SymLinksIfOwnerMatch" ) . "\n";
1543 1544 1545 1546
  $string .= "\n";

  return $string;
}
1547

1548 1549 1550
/**
 * Simple function to output log and debug messages
 */
1551
function boost_log($message, $variables, $severity = WATCHDOG_NOTICE) {
1552 1553 1554 1555 1556
  // Log debug info only if boost debugging is enabled
  if ($severity == WATCHDOG_DEBUG && ! variable_get('boost_message_debug', BOOST_MESSAGE_DEBUG)) {
    return;
  }