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

/**
 * @file
5
 * Provides static file caching for Drupal text output. Pages, Feeds, ect...
6 7 8
 */

//////////////////////////////////////////////////////////////////////////////
9
// Module settings
10

11
define('BOOST_TIME',                 time());
mikeytown2's avatar
mikeytown2 committed
12
define('BOOST_MAX_TIMESTAMP',        variable_get('boost_max_timestamp', BOOST_TIME));
13
define('BOOST_ENABLED',              variable_get('boost_enabled', CACHE_NORMAL));
14
define('BOOST_GZIP',                 function_exists('gzencode') ? variable_get('page_compression', TRUE) : FALSE);
mikeytown2's avatar
mikeytown2 committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

// This cookie is set for all authenticated users, so that they can be
// excluded from caching (or in the future get a user-specific cached page):
define('BOOST_COOKIE',               variable_get('boost_cookie', 'DRUPAL_UID'));

// This line is appended to the generated static files; it is very useful
// for troubleshooting (e.g. determining whether one got the dynamic or
// static version):
define('BOOST_BANNER',               variable_get('boost_banner', "Page cached by Boost @ %cached_at, expires @ %expires_at"));

// Caching Options
define('BOOST_CACHE_LIFETIME',       variable_get('boost_cache_lifetime', 3600));
define('BOOST_CACHE_XML_LIFETIME',   variable_get('boost_cache_xml_lifetime', 3600));
define('BOOST_CACHE_JSON_LIFETIME',  variable_get('boost_cache_json_lifetime', 3600));
define('BOOST_CACHE_QUERY',          variable_get('boost_cache_query', TRUE));
define('BOOST_CACHE_HTML',           variable_get('boost_cache_html', TRUE));
define('BOOST_CACHE_XML',            variable_get('boost_cache_xml', FALSE));
define('BOOST_CACHE_JSON',           variable_get('boost_cache_json', FALSE));
define('BOOST_CACHE_CSS',            variable_get('boost_cache_css', TRUE));
define('BOOST_CACHE_JS',             variable_get('boost_cache_js', TRUE));
define('BOOST_CACHEABILITY_OPTION',  variable_get('boost_cacheability_option', 0));
define('BOOST_CACHEABILITY_PAGES',   variable_get('boost_cacheability_pages', ''));
37

38

39 40 41
// Views
define('BOOST_VIEWS_LIST_BEHAVIOR',  variable_get('boost_views_list_behavior', 0));

42
// Dir & File Structure
43
define('BOOST_ROOT_CACHE_DIR',       variable_get('boost_root_cache_dir', 'cache'));
44
define('BOOST_MULTISITE_SINGLE_DB',  variable_get('boost_multisite_single_db', TRUE));
45 46 47 48
define('BOOST_NORMAL_DIR',           variable_get('boost_normal_dir', 'normal'));
define('BOOST_GZIP_DIR',             variable_get('boost_gzip_dir', 'normal'));
define('BOOST_PERM_NORMAL_DIR',      variable_get('boost_perm_normal_dir', 'perm'));
define('BOOST_PERM_GZ_DIR',          variable_get('boost_perm_gz_dir', 'perm'));
49 50 51
define('BOOST_CHAR',                 variable_get('boost_char', '_'));
define('BOOST_PERM_CHAR',            variable_get('boost_perm_char', '_'));
define('BOOST_HOST',                 variable_get('boost_host', ''));
52
define('BOOST_FILE_EXTENSION',       variable_get('boost_file_extension', '.html'));
53
define('BOOST_XML_EXTENSION',        variable_get('boost_xml_extension', '.xml'));
mikeytown2's avatar
mikeytown2 committed
54
define('BOOST_JSON_EXTENSION',       variable_get('boost_json_extension', '.json'));
55 56
define('BOOST_CSS_EXTENSION',        variable_get('boost_css_extension', '.css'));
define('BOOST_JS_EXTENSION',         variable_get('boost_js_extension', '.js'));
57
define('BOOST_GZIP_EXTENSION',       variable_get('boost_gzip_extension', '.gz'));
58 59 60 61
define('BOOST_ROOT_FILE',            variable_get('boost_root_file', '.boost'));
define('BOOST_MAX_PATH_DEPTH',       10);

// Advanced Settings
mikeytown2's avatar
mikeytown2 committed
62
define('BOOST_CHECK_BEFORE_CRON_EXPIRE', variable_get('boost_check_before_cron_expire', FALSE));
63
define('BOOST_PRE_PROCESS_FUNCTION', variable_get('boost_pre_process_function', ''));
64
define('BOOST_EXIT_IN_HOOK_EXIT',    variable_get('boost_exit_in_hook_exit', TRUE));
65
define('BOOST_FLUSH_ALL_MULTISITE',  variable_get('boost_flush_all_multisite', TRUE));
66
define('BOOST_ONLY_ASCII_PATH',      variable_get('boost_only_ascii_path', TRUE));
67
define('BOOST_SET_FILE_ENCODING',    variable_get('boost_set_file_encoding', ''));
mikeytown2's avatar
mikeytown2 committed
68
define('BOOST_AGGRESSIVE_COOKIE',     variable_get('boost_aggressive_cookie', TRUE));
mikeytown2's avatar
mikeytown2 committed
69
define('BOOST_ASYNCHRONOUS_OUTPUT',  variable_get('boost_asynchronous_output', TRUE));
70
define('BOOST_PAGER_CLEAN',          variable_get('boost_pager_clean', FALSE));
71
define('BOOST_FLUSH_DIR',            variable_get('boost_flush_dir', FALSE));
mikeytown2's avatar
mikeytown2 committed
72
define('BOOST_FLUSH_CCK_REFERENCES', variable_get('boost_flush_cck_references', TRUE));
73
define('BOOST_FLUSH_FRONT',          variable_get('boost_flush_front', TRUE));
mikeytown2's avatar
mikeytown2 committed
74
define('BOOST_FLUSH_NODE_TERMS',     variable_get('boost_flush_node_terms', TRUE));
mikeytown2's avatar
mikeytown2 committed
75
define('BOOST_FLUSH_MENU_ITEMS',     variable_get('boost_flush_menu_items', 0));
76 77
define('BOOST_FLUSH_VIEWS',          variable_get('boost_flush_views', TRUE));
define('BOOST_FLUSH_VIEWS_INSERT',   variable_get('boost_flush_views_insert', TRUE));
78
define('BOOST_FLUSH_VIEWS_UPDATE',   variable_get('boost_flush_views_update', FALSE));
79
define('BOOST_CLEAR_CACHE_OFFLINE',  variable_get('boost_clear_cache_offline', FALSE));
mikeytown2's avatar
mikeytown2 committed
80
define('BOOST_OVERWRITE_FILE',       variable_get('boost_overwrite_file', FALSE));
81
define('BOOST_HALT_ON_ERRORS',       variable_get('boost_halt_on_errors', FALSE));
82
define('BOOST_HALT_ON_MESSAGES',     variable_get('boost_halt_on_messages', TRUE));
mikeytown2's avatar
mikeytown2 committed
83
define('BOOST_DISABLE_CLEAN_URL',    variable_get('boost_disable_clean_url', FALSE));
84
define('BOOST_AGGRESSIVE_GZIP',      BOOST_GZIP ? variable_get('boost_aggressive_gzip', TRUE) : FALSE);
85 86
define('BOOST_PERMISSIONS_FILE',     variable_get('boost_permissions_file', ''));
define('BOOST_PERMISSIONS_DIR',      variable_get('boost_permissions_dir', ''));
87
define('BOOST_EXPIRE_NO_FLUSH',      variable_get('boost_expire_no_flush', FALSE));
mikeytown2's avatar
mikeytown2 committed
88
define('BOOST_VERBOSE',              variable_get('boost_verbose', 5));
89
define('BOOST_IGNORE_SAFE_WARNING',  variable_get('boost_ignore_safe_warning', FALSE));
90
define('BOOST_IGNORE_SUBDIR_LIMIT',  variable_get('boost_ignore_subdir_limit', TRUE));
91
define('BOOST_IGNORE_HTACCESS_WARNING',  variable_get('boost_ignore_htaccess_warning', FALSE));
92
define('BOOST_NO_DATABASE',          variable_get('boost_no_database', FALSE));
93

94 95 96 97 98 99
// Domain Whitelist/Blacklist Settings
define('BOOST_DOMAIN_NO_LISTS',      0);
define('BOOST_DOMAIN_WHITELIST_ONLY',1);
define('BOOST_DOMAIN_BLACKLIST_ONLY',2);
define('BOOST_DOMAIN_BOTH_LISTS',    3);

100
// Crawler Settings
101
define('BOOST_CRAWL_ON_CRON',        variable_get('boost_crawl_on_cron', FALSE));
102
define('BOOST_LOOPBACK_BYPASS',      BOOST_CRAWL_ON_CRON ? variable_get('boost_loopback_bypass', FALSE) : FALSE);
103 104 105
define('BOOST_PUSH_HTML',            variable_get('boost_push_html', TRUE));
define('BOOST_PUSH_XML',             variable_get('boost_push_xml', TRUE));
define('BOOST_PUSH_JSON',            variable_get('boost_push_json', TRUE));
106 107
define('BOOST_CRAWL_URL_ALIAS',      variable_get('boost_crawl_url_alias', FALSE));
define('BOOST_CRAWL_DB_IMPORT_SIZE', variable_get('boost_crawl_db_import_size', 10000));
108 109
define('BOOST_CRAWLER_THROTTLE',     variable_get('boost_crawler_throttle', 0));
define('BOOST_CRAWLER_THREADS',      variable_get('boost_crawler_threads', 2));
110
define('BOOST_MAX_THREADS',          8);
111

112 113 114 115 116 117 118
// Requires Boost Functions or global scope, Define These Last
global $base_url;
define('BOOST_CRAWLER_SELF',         $base_url . '/' . 'boost-crawler?nocache=1&key=' . variable_get('boost_crawler_key', FALSE));
define('BOOST_FILE_PATH',            BOOST_MULTISITE_SINGLE_DB ? boost_cache_directory(NULL, FALSE) : variable_get('boost_file_path', boost_cache_directory(BOOST_HOST, FALSE)));
define('BOOST_GZIP_FILE_PATH',       implode('/', array_filter(explode('/', str_replace(BOOST_ROOT_CACHE_DIR . '/' . BOOST_NORMAL_DIR, BOOST_ROOT_CACHE_DIR . '/' . BOOST_GZIP_DIR . '/', BOOST_FILE_PATH)))));
define('BOOST_PERM_GZIP_FILE_PATH',  implode('/', array_filter(explode('/', str_replace(BOOST_ROOT_CACHE_DIR . '/' . BOOST_NORMAL_DIR, BOOST_ROOT_CACHE_DIR . '/' . BOOST_PERM_GZ_DIR . '/', BOOST_FILE_PATH)))));
define('BOOST_PERM_FILE_PATH',       implode('/', array_filter(explode('/', str_replace(BOOST_ROOT_CACHE_DIR . '/' . BOOST_NORMAL_DIR, BOOST_ROOT_CACHE_DIR . '/' . BOOST_PERM_NORMAL_DIR . '/', BOOST_FILE_PATH)))));
119
define('BOOST_CRAWLER_BATCH_SIZE',   variable_get('boost_crawler_batch_size', min(15, (ini_get('max_execution_time') + 0.1)/(2 * boost_average_time()))));
120 121
define('BOOST_MAX_THREAD_TIME',      max(300, 2 * boost_average_time() * BOOST_CRAWLER_THREADS * BOOST_CRAWLER_BATCH_SIZE));

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
// define doesn't work with an array
$GLOBALS['_boost']['verbose_option_defaults'] = array(
  'boost_init_404',
  'boost_exit_headers',
  'boost_cron_expire',
  'boost_view_insert',
  'boost_expire_node',
  'boost_user_op',
  'boost_user_delete',
  'boost_block_flush_submit',
  'boost_block_settings_submit',
  'boost_block_rm_settings_submit',
  'boost_ob_handler_info',
  'boost_ob_handler_redirect',
  'boost_cache_clear_all',
  'boost_cache_flush_filename',
  'boost_cache_expire_router',
  'boost_cache_expire_all_db_list',
  'boost_cache_expire_all_db_count',
  'boost_cache_set_node_relationships',
  'boost_crawler_run_stop',
  'boost_crawler_run_rogue',
  'boost_crawler_run_sleep',
  'boost_crawler_run_shutdown',
  'boost_crawler_run_kill',
  'boost_crawler_run_startup',
  'boost_crawler_run_restart',
  'boost_crawler_run_done',
  'boost_crawler_run_start',
);
$GLOBALS['_boost']['verbose_option_selected'] = array_flip(variable_get('boost_verbose_refined', $GLOBALS['_boost']['verbose_option_defaults']));
153

154 155 156 157 158 159 160
//////////////////////////////////////////////////////////////////////////////
// Global variables

//$GLOBALS['_boost_path'] = '';
//$GLOBALS['_boost_query'] = '';
//$GLOBALS['_boost_message_count'] = '';
//$GLOBALS['_boost_cache_this'] = '';
161 162
//$GLOBALS['_boost_max_execution_time'] = '';
//$GLOBALS['_boost_output_buffering'] = '';
163
//$GLOBALS['_boost_default_socket_timeout'] = '';
164
//$GLOBALS['_boost_router_item'] = '';
165
//$GLOBALS['_boost_relationships'] = '';
mikeytown2's avatar
mikeytown2 committed
166
//$GLOBALS['_boost_nid'] = '';
167
//$_boost
168

169
//////////////////////////////////////////////////////////////////////////////
170
// Core API hooks
171 172 173 174

/**
 * Implementation of hook_help(). Provides online user help.
 */
175 176
function boost_help($path, $arg) {
  switch ($path) {
177
    case 'admin/help#boost':
178
      if (file_exists($file = drupal_get_path('module', 'boost') . '/README.txt')) {
179
        return '<pre>' . implode("\n", array_slice(explode("\n", @file_get_contents($file)), 2)) . '</pre>';
180
      }
181
      break;
182
    case 'admin/settings/performance/boost':
183
      return '<p>' . '' . '</p>'; // TODO: add help text.
184
  }
185 186
  //hack to get drupal_get_messages before they are destroyed.
  $GLOBALS['_boost_message_count'] = count(drupal_get_messages(NULL, FALSE));
187 188
}

189 190 191 192 193 194 195 196 197 198 199
/**
 * Get some basic node attribues from the database given node id.
 *
 * @param $nid
 *  node ID
 * @return node object
 *  node->nid
 *  node->type
 *  node->language
 *  node->path
 *  node->domain
200
 *  node->tids
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
 */
function boost_node_get_basics($nid) {
  static $nodes = array();

  // Is the node statically cached?
  if (isset($nodes[$nid])) {
    return $nodes[$nid];
  }

  // Retrieve node nid, type, language.
  $op = 'load';
  $node = db_fetch_object(db_query("SELECT nid, type, language FROM {node} WHERE nid = %d", $nid));
  // Get path info
  if (module_exists('path')) {
    path_nodeapi($node, $op, NULL, NULL);
  }
  // Get domain access info
  if (module_exists('domain')) {
    domain_nodeapi($node, $op, NULL, NULL);
  }
221 222 223 224
  // Get taxonomy tid info
  if (module_exists('taxonomy')) {
    $node->tids = boost_taxonomy_node_get_tids($node->nid);
  }
225 226 227 228
  $nodes[$nid] = $node;
  return $nodes[$nid];
}

229 230 231 232 233 234
/**
 * Implementation of hook_ctools_render_alter().
 *
 * Needed to get the nodes that are inside of a panel's contex
 */
function boost_ctools_render_alter($info, $page, $args, $contexts, $task, $subtask, $handler) {
235 236 237 238 239
  // return if page not going to be cached or if database turned off
  if (!$GLOBALS['_boost_cache_this'] || BOOST_NO_DATABASE) {
    return;
  }

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
  foreach ($handler->conf['display']->context as $context) {
    if ($context->type == 'node') {
      $node = $context->data;
      // skip if node type is not set
      if (!isset($node->type)) {
        continue;
      }
      // set data
      $relationship = array(
        'child_page_callback' => 'node',
        'child_page_type' => $node->type,
        'child_page_id' => $node->nid,
      );
      if (BOOST_VERBOSE >= 9) {
        $relationship['debug'] = array(
          'panel-task' => $handler->task,
          'panel-subtask' => $handler->subtask,
          'node-path' => $node->path,
        );
      }
      // send to global
      $GLOBALS['_boost_relationships'][] = $relationship;
    }
  }
}

266 267 268 269 270 271 272 273 274 275
/**
 * Implementation of hook_views_pre_render().
 *
 * This is called right before the render process. Used to grab the NID's listed
 * in this view, and set the view node relationship in the database.
 *
 * @param &$view
 *  reference to the view being worked on
 */
function boost_views_pre_render(&$view) {
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
  // return if not a view, page not going to be cached, or if database turned off
  if (is_null($view) || !$GLOBALS['_boost_cache_this'] || BOOST_NO_DATABASE) {
    return;
  }

  // return if view doesn't belong in the set of views to search
  $views = boost_views_get_valid_array();
  $hash = $view->name . ' - ' . $view->current_display;
  if (!array_key_exists($hash, $views)) {
    return;
  }

  foreach ($view->result as $item) {
    // skip if nid is not a number
    if (!is_numeric($item->nid)) {
      continue;
    }

    $node = boost_node_get_basics($item->nid);
    // skip if node type is not set
    if (!isset($node->type)) {
      continue;
    }
    // set data
300
    $relationship = array(
301 302 303 304 305
      'child_page_callback' => 'node',
      'child_page_type' => $node->type,
      'child_page_id' => $item->nid,
    );
    if (BOOST_VERBOSE >= 9) {
306
      $relationship['debug'] = array(
307 308 309 310 311 312
        'view-name' => $view->name,
        'view-display' => $view->current_display,
        'node-path' => $node->path,
      );
    }
    // send to global
313
    $GLOBALS['_boost_relationships'][] = $relationship;
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
  }
}

/**
 * Genrate a list of views based off of defaults.
 *
 * Views that have a path, can be cached by boost & anonymous users can access
 *
 * @return array
 *    (view_name . ' - ' . display_name . ' - /' . path => Enabled/Disabled)
 */
function boost_views_generate_default_list() {
  $account = user_load(0);
  $views = views_get_all_views();
  $enabled = array();
  $disabled = array();
  foreach ($views as $view_name => $view) {
    // disabled views get nothing.
    if (!empty($view->disabled)) {
      unset($views[$view_name]);
      continue;
    }

    $view->init_display();
    foreach ($view->display as $display_id => $display) {
      // Anonymous users can access view
340 341 342 343 344 345 346 347 348 349 350
      if (!$view->access($display_id, $account)) {
        continue;
      }
      $hash = $view_name . ' - ' . $display_id;

      // Use the default view
      if (strcmp($display_id, 'default') == 0) {
        $enabled[$hash] = $hash;
      }
      // View with a path
      elseif (isset($display->display_options['path'])) {
351 352 353 354 355 356
        $path = $display->display_options['path'];
        $hash = $view_name . ' - ' . $display_id . ' - /' . $path;
        // Path is cacheable via boost & does not take arguments
        if (boost_is_cacheable($path) && !stristr($path, '%')) {
          $enabled[$hash] = $hash;
        }
357
        // Path is not cacheable via boost or view takes arguments
358 359
        else {
          $disabled[$hash] = 0;
360 361
        }
      }
362 363 364 365
      // All other displays mark as disabled
      else {
        $disabled[$hash] = 0;
      }
366 367
    }
  }
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
  ksort($disabled);
  natcasesort($enabled);
  $checkboxes = array_merge(array('line-break' => 0), $disabled, $enabled);
  return $checkboxes;
}

/**
 * Genrate a list of valid views that boost will search for new content.
 *
 * @return array
 */
function boost_views_get_valid_list($fresh = FALSE) {
  // Load saved default values; if not saved, save it.
  $defaults = variable_get('boost_views_list_default', FALSE);
  if (!$defaults || $fresh) {
    $defaults = boost_views_generate_default_list();
    variable_set('boost_views_list_default', $defaults);
  }

  // Load custom settings
  $list = variable_get('boost_views_list_custom', array());
  // Load defaults. http://php.net/operators.array
  $list += $defaults;


  return $list;
}

/**
 * Genrate a list of valid views that boost will search for new content.
 *
 * @return array
 */
function boost_views_get_valid_array() {
  $list = boost_views_get_valid_list();
  $views = array();
  foreach ($list as $hash => $enabled) {
    if ($enabled) {
      $info = explode(' - ', $hash);
      $page_type = $info[0];
      $page_id = $info[1];
      $key = $page_type . ' - ' . $page_id;
      $views[$key]['page_type'] = $page_type;
      $views[$key]['page_id'] = $page_id;
    }
  }
  return $views;
415 416
}

417 418 419 420 421 422 423 424
/**
 * Implementation of hook_views_pre_view().
 *
 * Hack due to this issue: http://drupal.org/node/619852
 */
function boost_views_pre_view(&$view) {
}

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
/**
* Send out a fast 404 and exit.
*/
function boost_fast404() {
  global $base_path;
  if (!headers_sent()) {
    header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
  }
  print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n";
  print '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">';
  print '<head><title>' . t('404 Not Found') . '</title></head>';
  print '<body><h1>' . t('Not Found') . '</h1>';
  print '<p>' . t('The requested URL was not found on this server.') . '</p>';
  print '<p><a href="' . $base_path . '">' . t('Home') . '</a></p>';
  print '</body></html>';
  exit();
}

443
/**
444
 * Implementation of hook_init(). Performs page setup tasks if page not cached.
445 446
 */
function boost_init() {
447 448 449 450 451 452 453
  global $user, $base_path, $base_root, $base_url;

  // Force lowercase host name
  $base_root = strtolower($base_root);
  $parts = parse_url($base_url);
  $parts['host'] = strtolower($parts['host']);
  $base_url = boost_glue_url($parts);
454

455 456 457 458 459 460 461 462
  // Make sure this is the correct domain
  // Only works if $base_url is set in settings.php
  if (strcmp($parts['host'], strtolower($_SERVER['HTTP_HOST'])) != 0) {
    $GLOBALS['conf']['cache'] = CACHE_DISABLED;
    $GLOBALS['_boost_cache_this'] = FALSE;
    return;
  }

463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
  // Check if Drupal is started from index.php - could cause problems with other
  // contrib modules like ad module.
  if (strpos($_SERVER['SCRIPT_FILENAME'], 'index.php') !== FALSE) {
    $uid = isset($user->uid) ? $user->uid : 0;
    // Remove Boost cookie at logout if it still exists
    if (BOOST_AGGRESSIVE_COOKIE && isset($_COOKIE[BOOST_COOKIE]) && $uid == 0) {
      boost_set_cookie($uid, BOOST_TIME - 86400);
    }
    // Remove Boost cookie if set to -1
    elseif (isset($_COOKIE[BOOST_COOKIE]) && $_COOKIE[BOOST_COOKIE] == '-1') {
      boost_set_cookie($uid, BOOST_TIME - 86400);
    }
    // Set Boost cookie if it doesn't exists and user is logged in
    elseif (BOOST_AGGRESSIVE_COOKIE && !isset($_COOKIE[BOOST_COOKIE]) && $uid != 0) {
      boost_set_cookie($uid);
    }
479
  }
480

481 482 483 484 485 486 487
  // Disable all caches when nocache is set
  if (isset($_GET['nocache'])) {
    $GLOBALS['conf']['cache'] = CACHE_DISABLED;
    $GLOBALS['_boost_cache_this'] = FALSE;
    return;
  }

488 489 490 491 492 493
  // Make sure this is not a 404 redirect from the htaccesss file
  $path = explode($base_path, request_uri());
  array_shift($path);
  $path = implode($base_path, $path);
  $path = explode('?', $path);
  $path = array_shift($path);
494
  if ($path != '' && empty($_REQUEST['q']) && !stristr($path, '.php') && isset($_SERVER['REDIRECT_STATUS']) && $_SERVER['REDIRECT_STATUS'] == 404) {
495 496
    $GLOBALS['conf']['cache'] = CACHE_DISABLED;
    $GLOBALS['_boost_cache_this'] = FALSE;
497 498 499


    if (BOOST_VERBOSE >= 7 && isset($_boost['verbose_option_selected']['boost_init_404'])) {
mikeytown2's avatar
mikeytown2 committed
500
      watchdog('boost', '404 received from server via redirect, going to send a 404. Info: !output', array('!output' => boost_print_r($_SERVER, TRUE, TRUE)));
501
    }
502
    boost_fast404();
503 504
  }

505
  //set variables
506
  if (empty($_REQUEST['q'])) {
507 508 509
    //front page
    $GLOBALS['_boost_path'] = '';
  }
510 511 512
  else {
    $GLOBALS['_boost_path'] = $_REQUEST['q'];
  }
513 514

  // Remove anchor tags from url.
515
  if (stristr($GLOBALS['_boost_path'], '#')) {
516 517 518
    $GLOBALS['_boost_path'] = array_shift(explode('#', $GLOBALS['_boost_path']));
  }

519
  // Make the proper filename for our query
520
  $GLOBALS['_boost_query'] = BOOST_CHAR;
521
  $query = array();
522
  foreach ($_GET as $key => $val) {
523 524 525 526
    if (BOOST_PAGER_CLEAN && $key == 'page') {
      $GLOBALS['_boost_path'] .= '/page/' . $val;
      continue;
    }
527
    if ($key != 'q' && $key != 'destination') {
528
      $query[$key] = $val;
529 530
    }
  }
531
  $GLOBALS['_boost_query'] .= str_replace('&amp;', '&', urldecode(http_build_query($query)));
532

533
  if (!empty($user->uid)) {
534
    boost_set_cookie($user->uid);
535 536
    if (BOOST_DISABLE_CLEAN_URL) {
      $GLOBALS['conf']['clean_url'] = 0;
537 538
      db_query('TRUNCATE {cache_filter}');
      db_query('TRUNCATE {cache_menu}');
539 540 541 542 543
      cache_clear_all('*', 'cache_menu');
      cache_clear_all('*', 'cache_filter');
    }
  }

544
  // Make sure the page is/should be cached according to our current configuration
545 546
  if (   strpos($_SERVER['SCRIPT_FILENAME'], 'index.php') === FALSE
      || variable_get('site_offline', 0)
547
      || ($_SERVER['REQUEST_METHOD'] != 'GET' && $_SERVER['REQUEST_METHOD'] != 'HEAD')
548
      || $_SERVER['SERVER_SOFTWARE'] === 'PHP CLI'
549
      || !variable_get('boost_enabled', CACHE_NORMAL)
550
      || !boost_is_cacheable($GLOBALS['_boost_path'])
551
      ) {
552
    $GLOBALS['_boost_cache_this'] = FALSE;
553 554
    return;
  }
555

556
  // We only generate cached pages for anonymous visitors.
557
  if (empty($user->uid)) {
558
    if (variable_get('boost_enabled', CACHE_NORMAL) != CACHE_AGGRESSIVE) {
559 560
      $GLOBALS['conf']['cache'] = CACHE_DISABLED;
    }
561
    $GLOBALS['_boost_cache_this'] = TRUE;
562 563
    register_shutdown_function('_boost_ob_handler');
    ob_start();
564
  }
565 566
}

567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
/**
 * Implementation of hook_domainupdate() - keeps domain whitelist variable
 * current
 */

function boost_domainupdate($op, $domain, $form_state = array()) {
  switch ($op) {
    case 'create':
      if (variable_get('boost_domain_whitelist_use_domain', FALSE)) {
        $whitelist = variable_get('boost_domain_whitelist', array());
        $whitelist[ $domain['subdomain'] ] = $domain['subdomain'];
        asort($whitelist);
        variable_set('boost_domain_whitelist', $whitelist);
      }
      break;

    case 'update':
      if (variable_get('boost_domain_whitelist_use_domain', FALSE)) {
        $whitelist = variable_get('boost_domain_whitelist', array());
        unset($whitelist[ $domain['subdomain'] ]);
        $new_name = $form_state['values']['subdomain'];
        $whitelist[ $new_name ] = $new_name;
        asort($whitelist);
        variable_set('boost_domain_whitelist', $whitelist);
      }
      break;

    case 'delete':
      if (variable_get('boost_domain_whitelist_use_domain', FALSE)) {
        $whitelist = variable_get('boost_domain_whitelist', array());
        unset($whitelist[ $domain['subdomain'] ]);
        variable_set('boost_domain_whitelist', $whitelist);
      }
      break;
  }
}

604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
/**
 * Grabs drupal_goto requests via boost_exit and looks for redirects.
 *
 * Looks at the current page and the destination, seeing if the internal name
 * is the same; node/8 == node/8.
 *
 * @param $destination
 *   URL that user will be sent to soon.
 */
function boost_redirect_handler($destination) {
  global $base_path, $base_root;
  if (empty($destination)) {
    return;
  }
  $source = $base_root . request_uri();

  // Parse the URLs
  $new_parts = parse_url($destination);
  $current_parts = parse_url($source);

  // Get paths
  $current_path = ltrim($current_parts['path'], $base_path);
  $current_path_system = $_GET['q'];
  $new_path = ltrim($new_parts['path'], $base_path);
  $new_path_system = drupal_get_normal_path($new_path);
629 630 631
  if (empty($new_path)) {
    $new_path_system = variable_get('site_frontpage', 'node');
  }
632 633 634 635 636 637 638

  // Build alt source url
  $alt_parts = $current_parts;
  $alt_parts['path'] = $current_path_system;
  $alt_src = boost_glue_url($alt_parts);
  $urls = array($alt_src, $source);

639 640 641 642 643 644 645 646 647 648
  $debug = array(
    'destination' => $destination,
    'source' => $source,
    'alt_src' => $alt_src,
    'current_path' => $current_path,
    'current_path_system' => $current_path_system,
    'new_path' => $new_path,
    'new_path_system' => $new_path_system,
  );

649 650 651 652
  // Handle domain alias redirects
  if (   module_exists('domain_alias')
      && isset($_domain['redirect'])
      && $_domain['redirect'] == TRUE
653
        ) {
654 655 656
    boost_cache_kill_url($urls);
    return;
  }
657
  // Redirect is not to the same domain
658
  elseif (strcmp($new_parts['host'], $current_parts['host']) != 0) {
659 660
    //watchdog('boost-redirect', 'redirect is not to the same domain' . str_replace('    ', '&nbsp;&nbsp;&nbsp;&nbsp;', nl2br(htmlentities(print_r(array($debug), TRUE)))));
    boost_cache_kill_url($urls);
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
    return;
  }

  // Check for globalredirect internal to alias redirect
  if (strcmp($current_path, $new_path_system) == 0) {
    boost_cache_kill_url($urls);
    return;
  }

  // Check for globalredirect alias to alias redirect (deslashing)
  // Also grabs not clean to clean redirects
  if (strcmp($current_path, $_REQUEST['q']) != 0) {
    if (strcmp($current_path_system, $new_path_system) == 0) {
      boost_cache_kill_url($urls);
      return;
    }
  }

  if (module_exists('path_redirect')) {
    // Check for normal path_redirect alias to alias redirect
    $path_redirects = boost_path_redirect_load(array('source' => $current_path));
    if (isset($path_redirects)) {
      foreach ($path_redirects as $path_redirect) {
        $current_path_system = $path_redirect['redirect'];
685
        $debug['new_current_path_system'] = $current_path_system;
686 687 688 689 690 691 692 693 694 695 696 697 698
        break;
      }
    }
    if (strcmp($current_path_system, $new_path_system) == 0) {
      boost_cache_kill_url($urls);
      return;
    }

    // Check for alt path_redirect alias to alias redirect
    $path_redirects = boost_path_redirect_load(array('source' => $current_path_system));
    if (isset($path_redirects)) {
      foreach ($path_redirects as $path_redirect) {
        $current_path_system = $path_redirect['redirect'];
699
        $debug['new_current_path_system'] = $current_path_system;
700 701 702 703 704 705 706 707 708 709 710
        break;
      }
    }
    if (strcmp($current_path_system, $new_path_system) == 0) {
      boost_cache_kill_url($urls);
      return;
    }
  }

  // Last attempt of getting a "match" for this redirect
  $result = db_query("SELECT page_callback, page_type, page_id FROM {boost_cache} WHERE expire = 0 AND (hash_url = '%s' OR hash_url = '%s')", md5($source),  md5($alt_src));
711
  while ($row = db_fetch_array($result)) {
712 713 714 715 716 717 718 719 720
    // Handle node redirects
    if ($row['page_callback'] == 'node') {
      $current_path_system = $row['page_callback'] . '/' . $row['page_id'];
      if (strcmp($current_path_system, $new_path_system) == 0) {
        boost_cache_kill_url($urls);
        return;
      }
    }
  }
721
  //watchdog('boost-redirect', 'Nothing Done' . str_replace('    ', '&nbsp;&nbsp;&nbsp;&nbsp;', nl2br(htmlentities(print_r($debug, TRUE)))));
722 723
}

724 725 726 727 728 729 730 731 732 733 734 735
/**
 * Implementation of hook_exit(). Performs cleanup tasks.
 *
 * For POST requests by anonymous visitors, this adds a dummy query string
 * to any URL being redirected to using drupal_goto().
 *
 * This is pretty much a hack that assumes a bit too much familiarity with
 * what happens under the hood of the Drupal core function drupal_goto().
 *
 * It's necessary, though, in order for any session messages set on form
 * submission to actually show up on the next page if that page has been
 * cached by Boost.
736 737 738
 *
 * @param $destination
 *   URL that user will be sent to soon.
739 740
 */
function boost_exit($destination = NULL) {
741
  global $_boost, $user;
742

743
  // Check for redirects.
744
  if (!empty($destination) && $_SERVER['REQUEST_METHOD'] != 'POST' && empty($_GET['destination'])) {
745 746
    // Make sure path functions are available.
    drupal_bootstrap(DRUPAL_BOOTSTRAP_PATH);
747 748
    boost_redirect_handler($destination);
  }
749

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
  // 404, 403 dection and removal from the boost cache.
  // Only run if user is anonymous.
  if (empty($user->uid)) {
    $status = boost_get_http_status();
    if ($status == 404 || $status == 403) {
      // Bail out of caching
      $GLOBALS['_boost_cache_this'] = FALSE;

      // Get content type
      $types = boost_get_content_type();
      $types = array_pop($types);

      // Match extension
      if (stristr($types, 'text/javascript')) {
        $extension = BOOST_JSON_EXTENSION;
      }
      elseif (   stristr($types, 'application/rss')
              || stristr($types, 'text/xml')
              || stristr($types, 'application/rss+xml')
                ) {
        $extension = BOOST_JSON_EXTENSION;
      }
      elseif (stristr($types, 'text/html') && BOOST_CACHE_HTML) {
        $extension = BOOST_FILE_EXTENSION;
      }

      // Get filename
      if (!empty($extension)) {
        $filename = boost_file_path($GLOBALS['_boost_path'], TRUE, $extension);
        // Remove dead item from the cache (file & db);
        if ($filename) {
          $files = array(array('filename' => $filename));
          boost_cache_kill($files, TRUE);
          boost_remove_db($files);
        }
      }
    }
  }

789 790 791 792 793 794 795 796 797 798 799
  // Check that hook_exit() was invoked by drupal_goto() for a POST request:
  // Check that we're dealing with an anonymous visitor. and that some
  // session messages have actually been set during this page request:
  if (   !empty($destination)
      && $_SERVER['REQUEST_METHOD'] == 'POST'
      && empty($user->uid)
      && $messages = drupal_set_message()
          ) {
    $query_parts = parse_url($destination);
    // Add a nocache parameter to query. Such pages will never be cached
    $query_parts['query'] .= (empty($query_parts['query']) ? '' : '&') . 'nocache=1';
800

801 802 803
    // Rebuild the URL with the new query string.  Do not use url() since
    // destination has presumably already been run through url().
    $destination = boost_glue_url($query_parts);
804

805 806 807 808 809 810 811
    // Do what drupal_goto() would do if we were to return to it:
    if (BOOST_EXIT_IN_HOOK_EXIT) {
      // FIXME: call any remaining exit hooks since we're about to terminate?
      exit(header('Location: ' . $destination));
    }
    else {
      header('Location: ' . $destination);
812
    }
813
  }
814
  // Set watchdog error if headers already sent
815 816 817 818 819 820
  if (   BOOST_ASYNCHRONOUS_OUTPUT
      && isset($GLOBALS['_boost_cache_this'])
      && $GLOBALS['_boost_cache_this']
      && headers_sent($filename, $linenum)
      && !boost_headers_contain('Location: ')
      && BOOST_VERBOSE >= 7
821
      && isset($_boost['verbose_option_selected']['boost_exit_headers'])
822
      ) {
823 824
    watchdog('boost', 'boost_exit() Debug: Headers already sent in @filename on line @linenum. Asynchronous Operation will not be used.', array('@filename' => $filename, '@linenum' => $linenum));
  }
825 826
}

827 828 829 830 831 832 833 834 835 836 837 838 839
/**
 * Implementation of hook_menu().
 */
function boost_menu() {
  $items['admin/settings/performance/default'] = array(
    'title' => 'Performance',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'file path' => drupal_get_path('module', 'system'),
  );
  $items['admin/settings/performance/boost'] = array(
    'title' => 'Boost Settings',
    'description' => 'Advanced boost configuration.',
    'page callback' => 'drupal_get_form',
mikeytown2's avatar
mikeytown2 committed
840
    'page arguments' => array('boost_admin_boost_performance_page'),
841 842 843 844 845
    'access arguments' => array('administer site configuration'),
    'weight' => 10,
    'type' => MENU_LOCAL_TASK,
    'file' => 'boost.admin.inc',
  );
mikeytown2's avatar
mikeytown2 committed
846 847 848 849 850 851 852 853 854 855
  $items['admin/settings/performance/boost-rules'] = array(
    'title' => 'Boost htaccess rules generation',
    'description' => 'htaccess boost rules.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('boost_admin_htaccess_page'),
    'access arguments' => array('administer site configuration'),
    'weight' => 12,
    'type' => MENU_LOCAL_TASK,
    'file' => 'boost.admin.inc',
  );
856
  $items['boost_stats.php'] = array(
mikeytown2's avatar
mikeytown2 committed
857 858
    'page callback' => 'boost_stats_ajax_callback',
    'type' => MENU_CALLBACK,
859
    'access callback' => 1,
860
    'access arguments' => array('access content'),
861
    'file path' => drupal_get_path('module', 'boost'),
mikeytown2's avatar
mikeytown2 committed
862 863
    'file' => 'stats/boost_stats.ajax.inc',
  );
864
  $items['boost-crawler'] = array(
865
    'page callback' => 'boost_crawler_run',
866 867
    'type' => MENU_CALLBACK,
    'access callback' => 1,
868
    'access arguments' => array('access content'),
869 870
    'file path' => drupal_get_path('module', 'boost'),
  );
871 872 873 874 875 876
  $items['boost_views.php'] = array(
    'page callback' => 'boost_views_async',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
    'file path' => drupal_get_path('module', 'boost'),
  );
877 878 879
  return $items;
}

880 881 882 883
/**
 * Implementation of hook_form_alter(). Performs alterations before a form
 * is rendered.
 */
884
function boost_form_alter(&$form, $form_state, $form_id) {
885 886 887 888 889 890 891
  switch ($form_id) {

    // Alter Drupal's system performance settings form by hiding the default
    // cache enabled/disabled control (which will now always default to
    // CACHE_DISABLED), and inject our own settings in its stead.
    case 'system_performance_settings':
      module_load_include('inc', 'boost', 'boost.admin');
892 893
      $form['page_cache'] = boost_admin_performance_page($form['page_cache']);
      $form['#submit'][] = 'boost_admin_performance_page_submit';
894 895 896 897 898 899 900 901 902 903
      $form['clear_cache']['clear']['#submit'][0] = 'boost_admin_clear_cache_submit';
      break;

    // Alter Drupal's site maintenance settings form in order to ensure that
    // the static page cache gets wiped if the administrator decides to take
    // the site offline.
    case 'system_site_maintenance_settings':
      module_load_include('inc', 'boost', 'boost.admin');
      $form['#submit'][] = 'boost_admin_site_offline_submit';
      break;
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918

    // Alter Drupal's modules build form in order to ensure that
    // the static page cache gets wiped if the administrator decides to
    // change enabled modules
    case 'system_modules':
      module_load_include('inc', 'boost', 'boost.admin');
      $form['#submit'][] = 'boost_admin_modules_submit';
      break;

    // Alter Drupal's theme build form in order to ensure that
    // the static page cache gets wiped if the administrator decides to
    // change theme
    case 'system_themes_form':
      module_load_include('inc', 'boost', 'boost.admin');
      $form['#submit'][] = 'boost_admin_themes_submit';
919 920

      // Added below due to this bug: http://drupal.org/node/276615
921
      if (   variable_get('preprocess_css', FALSE)==TRUE
922
          && version_compare(VERSION, 6.13, '<=')
923 924 925
          && boost_cache_clear_all()
          ) {
        drupal_set_message(t('Boost: Static page cache cleared. See <a href="http://drupal.org/node/276615">http://drupal.org/node/276615</a> for reason why (core bug that is fixed in 6.14+).'), 'warning');
926
      }
927
      break;
928 929 930 931 932 933 934
  }
}

/**
 * Implementation of hook_cron(). Performs periodic actions.
 */
function boost_cron() {
935
  if (!variable_get('boost_enabled', CACHE_NORMAL)) {
936 937
    return;
  }
938
  global $_boost;
939

940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
  // Remove old domains if they are now a redirect
  if (module_exists('domain_alias')) {
    $domains = domain_domains();
    $old_domains = array();
    foreach ($domains as $key => $value) {
      foreach ($value['aliases'] as $alias) {
        if ($alias['redirect'] == 1) {
          $old_domains[] = boost_cache_directory($alias['pattern'], FALSE);
        }
      }
    }
    if (!empty($old_domains)) {
      $result = boost_db_multi_select_in('boost_cache', 'base_dir', "'%s'", $old_domains);
      $files = array();
      while ($row = db_fetch_array($result)) {
        $files[] = array('filename' => $row['filename'], 'hash' => $row['hash']);
      }
      if (!empty($files)) {
        boost_cache_kill($files, TRUE);
        boost_remove_db($files);
      }
    }
  }

964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
  // Remove old domains if they are "inactive"
  if (module_exists('domain')) {
    $domains = domain_domains();
    $old_domains = array();
    foreach ($domains as $key => $value) {
      if ($value['valid'] == 0) {
        $old_domains[] = boost_cache_directory($value['subdomain'], FALSE);
      }
    }
    if (!empty($old_domains)) {
      $result = boost_db_multi_select_in('boost_cache', 'base_dir', "'%s'", $old_domains);
      $files = array();
      while ($row = db_fetch_array($result)) {
        $files[] = array('filename' => $row['filename'], 'hash' => $row['hash']);
      }
      if (!empty($files)) {
        boost_cache_kill($files, TRUE);
        boost_remove_db($files);
      }
    }
  }

986
  // Check for new views on cron
987
  if (module_exists('views') && BOOST_VIEWS_LIST_BEHAVIOR == 0) {
988 989 990 991
    $defaults = boost_views_generate_default_list();
    variable_set('boost_views_list_default', $defaults);
  }

992 993
  $expire = TRUE;
  if (BOOST_CHECK_BEFORE_CRON_EXPIRE) {
994
    $expire = boost_has_site_changed(TRUE);
995
  }
996
  // Expire old content
997
  if (!BOOST_LOOPBACK_BYPASS && variable_get('boost_expire_cron', TRUE) && $expire && boost_cache_expire_all()) {
998
    if (BOOST_VERBOSE >= 5 && isset($_boost['verbose_option_selected']['boost_cron_expire'])) {
999 1000
      watchdog('boost', 'Expired stale files from static page cache.', array(), WATCHDOG_NOTICE);
    }
1001
  }
1002 1003 1004 1005 1006 1007

  // Update Stats
  if (module_exists('statistics') && variable_get('boost_block_show_stats', FALSE)) {
    $block = module_invoke('statistics', 'block', 'view', 0);
    variable_set('boost_statistics_html', $block['content']);
  }
1008 1009

  // Crawl Site
1010
  if (BOOST_CRAWL_ON_CRON && !variable_get('site_offline', 0)) {
1011
    boost_crawler_run((int)$expire);
1012
  }
1013 1014
}

1015 1016 1017 1018
/*
 * Implementation of hook_flush_caches(). Deletes all static files.
 */
function boost_flush_caches() {
1019
  if (variable_get('cron_semaphore', FALSE)==FALSE && (variable_get('preprocess_css', FALSE)==TRUE || variable_get('preprocess_js', FALSE)==TRUE)) {
1020 1021
    boost_cache_clear_all();
  }
1022 1023 1024
  return;
}

1025 1026 1027 1028
/**
 * Implementation of hook_comment(). Acts on comment modification.
 */
function boost_comment($comment, $op) {
1029
  if (!variable_get('boost_enabled', CACHE_NORMAL)) return;
1030

mikeytown2's avatar
mikeytown2 committed
1031 1032 1033 1034 1035
  if (is_array($comment)) {
    $comment = (object)$comment;
  }

  // Expire the relevant node page from the static page cache to prevent serving stale content:
1036 1037 1038
  switch ($op) {
    case 'insert':
    case 'update':
1039 1040 1041 1042
    case 'publish':
    case 'unpublish':
    case 'delete':
      if (!empty($comment->nid)) {
1043
        $node = node_load($comment->nid);
1044
        boost_expire_node($node, $comment->nid);
1045 1046
      }
      break;
1047 1048 1049
  }
}

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
/**
 * Sets the base_dir array key based on settings.
 *
 * @param array &$data
 *  array that might want to have the base_dir key added to it.
 */
function boost_set_base_dir_in_array(&$data) {
  if ($data) {
    foreach ($data as $key => $value) {
      if (!array_key_exists('base_dir', $data[$key]) && !BOOST_FLUSH_ALL_MULTISITE) {
        $data[$key]['base_dir'] = BOOST_FILE_PATH;
      }
      if (array_key_exists('base_dir', $data[$key]) && BOOST_FLUSH_ALL_MULTISITE) {
        unset($data[$key]['base_dir']);
      }
    }
  }
}

1069 1070 1071 1072
/**
 * Implementation of hook_nodeapi(). Acts on nodes defined by other modules.
 */
function boost_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
1073
  global $_boost;
1074
  if (!variable_get('boost_enabled', CACHE_NORMAL) || !isset($node->nid)) {
1075 1076
    return;
  }
1077 1078
  $data[] = array('page_callback' => 'node', 'page_id' => $node->nid);
  boost_set_base_dir_in_array($data);
1079 1080 1081

  switch ($op) {
    case 'insert':
1082
      boost_expire_node($node);
1083
      // Run all cached views, looking for this new node
1084
      if (BOOST_FLUSH_VIEWS_INSERT && module_exists('views')) {
mikeytown2's avatar
mikeytown2 committed
1085
        $GLOBALS['_boost_nid'] = $node->nid;
1086
        $_boost['new_nodes'][$node->nid] = $node->nid;
mikeytown2's avatar
mikeytown2 committed
1087 1088
        register_shutdown_function('_boost_view_insert');
      }
1089 1090 1091
      // Insert new node into boost_cache table
      if (variable_get('boost_insert_node_on_creation', FALSE)) {
        $GLOBALS['_boost_nid'] = $node->nid;
1092
        $_boost['new_nodes'][$node->nid] = $node->nid;
1093 1094
        register_shutdown_function('_boost_cache_insert');
      }
1095
      break;
1096

1097
    case 'update':
1098
      boost_expire_node($node);
1099 1100 1101
      // Run all cached views, looking for this new node
      if (BOOST_FLUSH_VIEWS_UPDATE && module_exists('views')) {
        $GLOBALS['_boost_nid'] = $node->nid;
1102
        $_boost['new_nodes'][$node->nid] = $node->nid;
1103 1104
        register_shutdown_function('_boost_view_insert');
      }
1105
      // if node is not published, delete it.
1106 1107 1108 1109
      if (!$node->status) {
        boost_cache_expire_router($data, TRUE, TRUE);
      }
      break;
1110

1111
    case 'delete':
1112
      boost_expire_node($node);
1113
      boost_cache_expire_router($data, TRUE, TRUE);
1114
      break;
1115

1116
    case 'presave':
1117
      // If path changes remove old path entry from database
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
      // Logic taken from path_redirect_node_presave()
      if (!empty($node->path)) {
        $node_path = 'node/'. $node->nid;
        $old_alias = drupal_get_path_alias($node_path, ($node->language ? $node->language : ''));
        if ($old_alias != $node_path && $node->path != $old_alias) {
          // If the user is manually changing the path alias, nuke the old files
          boost_cache_expire_router($data, TRUE, TRUE);
        }
      }
      break;
1128 1129 1130
  }
}

1131 1132 1133 1134 1135 1136 1137
/**
 * Shutdown function, gets called at the very end of node creation.
 *
 * Node is now created, thus we can get the node path and set the boost_cache
 * table.
 */
function _boost_cache_insert() {
1138 1139 1140 1141 1142
  static $processed = FALSE;
  if ($processed) {
    return;
  }

1143 1144
  global $_boost;
  if (empty($_boost['new_nodes'])) {
1145 1146 1147 1148 1149 1150
    return FALSE;
  }
  // Ensure we're in the correct working directory, since some web servers (e.g. Apache) mess this up here.
  chdir(dirname($_SERVER['SCRIPT_FILENAME']));

  // Load node
1151
  foreach ($_boost['new_nodes'] as $nid) {
1152
    $node = boost_node_get_basics($nid);
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
    if (!$node) {
      continue;
    }
    $router_item = array();
    $router_item['page_callback'] = 'node';
    $router_item['page_type'] = $node->type;
    $router_item['page_id'] = $node->nid;

    // Set DB defaults
    $expire = 0;
    $lifetime = -1;
    $push = -1;
    $timer = 0;
    $timer_average = 0;
    $extension = BOOST_FILE_EXTENSION;

    // Get list of base urls for this node
    $base_urls = array();
    foreach (boost_get_base_urls($node) as $domain_id) {
      foreach ($domain_id as $base) {
        $base_urls[] = $base . $node->path;
      }
1175 1176
    }

1177 1178 1179 1180 1181 1182 1183
    // Insert each url into the DB
    foreach ($base_urls as $url) {
      $parts = parse_url($url);
      $file_path = boost_cache_directory($parts['host'], FALSE);
      $filename = boost_file_path($node->path, FALSE, BOOST_FILE_EXTENSION, $file_path);
      boost_put_db($filename, $expire, $lifetime, $push, $router_item, $timer, $timer_average, $extension, $url, $file_path);
    }
1184
  }
1185
  $processed = TRUE;
1186 1187
}

1188 1189 1190 1191 1192 1193 1194 1195 1196
/**
 * Get domains the node is currently published to
 *
 * @param $node
 *   node object
 * @return array
 *   array('$gid' => $gid)
 */
function boost_get_domains(&$node) {
1197 1198 1199
  if (empty($node->nid)) {
    return array();
  }
1200 1201 1202 1203 1204 1205 1206 1207 1208
  $domains = array();
  $result = db_query("SELECT gid FROM {domain_access} WHERE nid = %d", $node->nid);
  while ($row = db_fetch_array($result)) {
    $gid = $row['gid'];
    $domains[$gid] = $gid;
  }
  return $domains;
}

1209 1210 1211 1212 1213
/**
 * Get all base url's where this node can appear
 *
 * @param $node
 *   node object
1214 1215
 * @param $reset
 *  A boolean flag to clear the static variable if necessary.
1216
 * @return array
1217
 *   array(0 => array(0 => $base_url . '/'))
1218
 */
1219
function boost_get_base_urls(&$node, $reset = FALSE) {
1220 1221
  global $base_url, $base_path;

1222 1223
  // Get list of URL's if using domain access
  $base_urls = array();
1224
  $domains = array();
1225
  if (module_exists('domain') && isset($node->domains)) {
1226
    // Get domains from node object
1227 1228 1229 1230
    foreach ($node->domains as $key => $domain_id) {
      if ($key != $domain_id) {
        continue;
      }
1231 1232 1233
      $domains[$domain_id] = $domain_id;
    }
    // Get domains from database
1234
    foreach (boost_get_domains($node) as $domain_id) {
1235 1236 1237 1238
      $domains[$domain_id] = $domain_id;
    }
    // Get aliases and set base url
    foreach ($domains as $domain_id) {
1239
      $domain = domain_lookup($domain_id, NULL, $reset);
1240 1241
      if ($domain['valid'] == 1) {
        if (isset($domain['path'])) {
1242
          $base_urls[$domain_id][] = $domain['path'];
1243
        }
1244 1245
        if (is_array($domain['aliases'])) {
          foreach ($domain['aliases'] as $alias) {
1246 1247
            $alias['pattern'] = trim($alias['pattern']);
            if ($alias['redirect'] != 1 && !empty($alias['pattern'])) {
1248 1249 1250
              $temp_domain = array('scheme' => $domain['scheme'], 'subdomain' => $alias['pattern']);
              $base_urls[$domain_id][] = domain_get_path($temp_domain);
            }
1251 1252 1253 1254 1255 1256
          }
        }
      }
    }
  }
  else {
1257
    $base_urls[0][] = $base_url . '/';
1258
  }
1259
  return $base_urls;
1260 1261
}

1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
/**
 * Run views looking for new nodes.
 */
function boost_views_async() {

  // Exit if no nodes
  if (empty($_GET['new_nodes']) || !is_array($_GET['new_nodes'])) {
    return;
  }

  // Exit if key does not match.
  if (!empty($_GET['key'])) {
    $key = variable_get('boost_crawler_key', FALSE);
    if ($key == $_GET['key']) {
      // Break connection so processing is async. Return key.
      boost_async_opp($_GET['key']);
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290

      // Give us lots of ram
      $m_limit = ini_get('memory_limit');
      $m_limit_int = substr($m_limit, 0, -1);
      $m_limit_int = (int) $m_limit_int;
      $m_limit_scale = strtoupper(substr($m_limit, -1));
      if ($m_limit_scale == 'M') {
        @ini_set('memory_limit', $m_limit_int*4 . 'M');
      }

      // Give us lots of time
      $t_limit = ini_get('max_execution_time');
      @ini_set('max_execution_time', $t_limit*4);
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
    }
    else {
      return;
    }
  }
  else {
    return;
  }

  // Get list of nodes to process.
  global $_boost;
  $_boost['new_nodes'] = $_GET['new_nodes'];

  // Process list.
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
  $data = _boost_views_runit();

  // Set ini variables back
  if (isset($m_limit)) {
    @ini_set('memory_limit', $m_limit);
  }
  if (isset($t_limit)) {
    @ini_set('max_execution_time', $t_limit);
  }

  return $data;
1316 1317
}

mikeytown2's avatar
mikeytown2 committed
1318 1319 1320 1321
/**
 * Shutdown function, gets called at the very end of node creation.
 *
 * Node is now created, thus views has access to the new node. Searches all
mikeytown2's avatar
mikeytown2 committed
1322
 * cached views for newly created node. Expires the outdated views from the cache.
mikeytown2's avatar
mikeytown2 committed
1323
 */
1324 1325
function _boost_view_insert() {
  global $_boost, $base_url, $base_path;
1326
  static $processed = FALSE;
1327 1328

  // Only run once
1329 1330 1331 1332
  if ($processed) {
    return;
  }

1333 1334
  // Exit if no new nodes
  if (empty($_boost['new_nodes'])) {
1335 1336
    return FALSE;
  }
1337

1338 1339 1340 1341
  // Make sure node is numeric
  foreach ($_boost['new_nodes'] as $key => $value) {
    if (!is_numeric($value) || !is_numeric($key)) {
      unset($_boost['new_nodes'][$key]);
1342
    }
1343 1344 1345 1346
  }
  if (empty($_boost['new_nodes'])) {
    return;
  }
1347

1348 1349 1350 1351 1352
  // Prep for async
  // URL key.
  $key = variable_get('boost_crawler_key', FALSE);
  if ($key == FALSE) {
    variable_set('boost_crawler_key', mt_rand());
1353
    $key = variable_get('boost_crawler_key', FALSE);
1354
  }
1355

1356 1357 1358 1359 1360 1361 1362
  // Query string.
  $query = array(
    'new_nodes' => $_boost['new_nodes'],
    'rand' => mt_rand(),
    'key' => $key,
  );
  $query_string = str_replace('&amp;', '&', urldecode(http_build_query($query)));
1363

1364 1365 1366 1367 1368 1369 1370
  // Setup request URL and headers.
  $ip = variable_get('boost_server_addr', FALSE);
  if (empty($ip)) {
    $ip = $_SERVER['SERVER_ADDR'];
  }
  $url = 'http://' . $ip . $base_path . 'boost_views.php?' . $query_string;
  $headers['Host'] = $_SERVER['HTTP_HOST'];
1371

1372 1373 1374 1375
  // Send nodes to async processor
  $socket_timeout = ini_set('default_socket_timeout', 2);
  $results = drupal_http_request($url, $headers);
  ini_set('default_socket_timeout', $socket_timeout);
1376

1377 1378
  // Check response.
  $key_back = trim($results->data);