expire.module 14.3 KB
Newer Older
Mike Carper's avatar
Mike Carper committed
1 2 3 4 5 6 7 8
<?php
// $Id$

/**
 * @file
 * Provides logic for page cache expiration
 */

9
// Defaults used if variable_get is not set.
Mike Carper's avatar
Mike Carper committed
10 11 12
define('EXPIRE_FLUSH_NODE_TERMS', TRUE);
define('EXPIRE_FLUSH_MENU_ITEMS', 1);
define('EXPIRE_FLUSH_CCK_REFERENCES', TRUE);
13
define('EXPIRE_FLUSH_FRONT', TRUE);
14
define('EXPIRE_INCLUDE_BASE_URL', TRUE);
Mike Carper's avatar
Mike Carper committed
15 16 17 18 19

/**
 * Implementation of hook_comment(). Acts on comment modification.
 */
function expire_comment($comment, $op) {
20 21 22 23 24 25
  // Convert array to object
  if (is_array($comment)) {
    $comment = (object)$comment;
  }

  // Expire the relevant node page from the static page cache to prevent serving stale content:
Mike Carper's avatar
Mike Carper committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
  switch ($op) {
    case 'insert':
    case 'update':
    case 'publish':
    case 'unpublish':
    case 'delete':
      if (!empty($comment->nid)) {
        $node = node_load($comment->nid);
        $node->nid = $comment->nid;
        expire_node($node);
      }
      break;
  }
}

/**
 * Implementation of hook_nodeapi(). Acts on nodes defined by other modules.
 */
function expire_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  switch ($op) {
    case 'insert':
      expire_node($node);
      break;
    case 'update':
      expire_node($node);
      break;
    case 'delete':
      expire_node($node);
      break;
  }
}

/**
 * Implementation of hook_votingapi_insert().
 *
 * @param $votes
 *  array of votes
 */
function expire_votingapi_insert($votes) {
65
  _expire_votingapi($votes);
Mike Carper's avatar
Mike Carper committed
66 67 68 69 70 71 72 73 74
}

/**
 * Implementation of hook_votingapi_delete().
 *
 * @param $votes
 *  array of votes
 */
function expire_votingapi_delete($votes) {
75 76 77 78 79 80 81
  _expire_votingapi($votes);
}

/**
 * Common expiry logic for votingapi.
 */
function _expire_votingapi($votes) {
Mike Carper's avatar
Mike Carper committed
82
  foreach ($votes as $vote) {
83 84 85 86 87 88 89 90 91
    if ($vote['content_type'] == 'comment') {
      $nid = db_result(db_query('SELECT nid FROM {comments} WHERE cid = %d', $vote['content_id']));
      $node = node_load($nid);
      expire_node($node);
    }
    if ($vote['content_type'] == 'node') {
      $node = node_load($vote['content_id']);
      expire_node($node);
    }
Mike Carper's avatar
Mike Carper committed
92 93 94 95 96 97 98 99 100 101 102 103
  }
}

/**
 * Implementation of hook_user(). Acts on user account actions.
 */
function expire_user($op, &$edit, &$account, $category = NULL) {
  switch ($op) {
    case 'delete':
      // Expire the relevant user page from the static page cache to prevent serving stale content:
      if (!empty($account->uid)) {
        $paths[] = 'user/' . $account->uid;
104
        $flushed = expire_cache_derivative($account, $paths);
105 106 107 108
        watchdog('expire', 'User !uid was deleted resulting in !flushed pages being expired from the cache',  array(
          '!uid' => $account->uid,
          '!flushed' => $flushed,
        ));
Mike Carper's avatar
Mike Carper committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
      }
      break;
  }
}

/**
 * Expires a node from the cache; including related pages.
 *
 * Expires front page if promoted, taxonomy terms,
 *
 * @param $node
 *  node object
 */
function expire_node($node) {
  $paths = array();

  // Check node object
  if (empty($node->nid)) {
    return FALSE;
  }

  // Expire this node
  $paths['node'] = 'node/' . $node->nid;

  // If promoted to front page, expire front page
134
  if (variable_get('expire_flush_front', EXPIRE_FLUSH_FRONT) && $node->promote == 1) {
Mike Carper's avatar
Mike Carper committed
135 136 137 138
    $paths['front'] = '<front>';
  }

  // Get taxonomy terms and flush
139 140
  if (module_exists('taxonomy') && variable_get('expire_flush_node_terms', EXPIRE_FLUSH_NODE_TERMS)) {
    // Get old terms from DB
Mike Carper's avatar
updated  
Mike Carper committed
141
    $tids = expire_taxonomy_node_get_tids($node->nid);
142 143 144 145 146 147 148
    // Get old terms from static variable
    $terms = taxonomy_node_get_terms($node);
    if (!empty($terms)) {
      foreach ($terms as $term) {
        $tids[$term->tid] = $term->tid;
      }
    }
149 150 151 152 153 154 155 156 157 158
    // Get new terms from node object
    if (!empty($node->taxonomy)) {
      foreach ($node->taxonomy as $vocab) {
        if (is_array($vocab)) {
          foreach ($vocab as $term) {
            $tids[$term] = $term;
          }
        }
      }
    }
Mike Carper's avatar
Mike Carper committed
159 160
    $filenames = array();
    foreach ($tids as $tid) {
161
      if (is_numeric($tid)) {
162 163
        $term = taxonomy_get_term($tid);
        $paths['term' . $tid] = taxonomy_term_path($term);
Mike Carper's avatar
Mike Carper committed
164 165 166 167 168
      }
    }
  }

  // Get menu and flush related items in the menu.
169
  if (variable_get('expire_flush_menu_items', EXPIRE_FLUSH_MENU_ITEMS) !=0) {
Mike Carper's avatar
Mike Carper committed
170 171 172 173
    if (!isset($node->menu['menu_name'])) {
      menu_nodeapi($node, 'prepare');
    }
    $menu = menu_tree_all_data($node->menu['menu_name']);
174 175 176 177
    $tempa = NULL;
    $tempb = NULL;
    if (variable_get('expire_flush_menu_items', EXPIRE_FLUSH_MENU_ITEMS) == 1) {
      $links = expire_get_menu_structure($menu, FALSE, 'node/' . $node->nid, NULL, $tempa, $tempb);
Mike Carper's avatar
Mike Carper committed
178
    }
179 180
    elseif (variable_get('expire_flush_menu_items', EXPIRE_FLUSH_MENU_ITEMS) == 2) {
      $links = expire_get_menu_structure($menu, NULL, NULL, NULL, $tempa, $tempb);
Mike Carper's avatar
Mike Carper committed
181
    }
182 183
    unset($tempa);
    unset($tempb);
Mike Carper's avatar
Mike Carper committed
184 185 186 187
    $paths = array_merge($links, $paths);
  }

  // Get CCK References and flush.
188
  if (variable_get('expire_flush_cck_references', EXPIRE_FLUSH_CCK_REFERENCES) && module_exists('nodereference')) {
Mike Carper's avatar
Mike Carper committed
189 190 191 192 193 194 195 196 197
    $nids = array();
    $type = content_types($node->type);
    if ($type) {
      foreach ($type['fields'] as $field) {
        // Add referenced nodes to nids. This will clean up nodereferrer fields
        // when the referencing node is updated.
        if ($field['type'] == 'nodereference') {
          $node_field = isset($node->$field['field_name']) ? $node->$field['field_name'] : array();
          foreach ($node_field as $delta => $item) {
198
            if (is_numeric($item['nid'])) {
199 200
              $paths['reference' . $nid] = 'node/' . $item['nid'];
            }
Mike Carper's avatar
Mike Carper committed
201 202 203 204 205 206 207 208 209
          }
        }
      }
    }

    // Get CCK references pointing to this node and flush.
    if (module_exists('nodereferrer')) {
      $nids = nodereferrer_referrers($node->nid);
      foreach ($nids as $nid) {
210
        if (is_numeric($nid['nid'])) {
Mike Carper's avatar
Mike Carper committed
211 212 213 214 215 216 217 218
          $paths['referrer' . $nid['nid']] = 'node/' . $nid['nid'];
        }
      }
    }
  }

  // Flush array of paths
  if (!empty($paths)) {
219
    $flushed = expire_cache_derivative($node, $paths);
220 221 222 223
    watchdog('expire', 'Node !nid was flushed resulting in !flushed pages being expired from the cache',  array(
      '!nid' => $node->nid,
      '!flushed' => $flushed,
    ));
Mike Carper's avatar
Mike Carper committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
  }
}

/**
 * Finds parent, siblings and children of the menu item. UGLY CODE...
 *
 * @param array $menu
 *  Output from menu_tree_all_data()
 * @param bool $found
 *  Signal for when the needle was found in the menu array.
 *  Set TRUE to get entire menu
 * @param string $needle
 *  Name of menu link. Example 'node/21'
 * @param bool $first
 *  Keep track of the first call; this is a recursive function.
 * @param bool &$found_global
 *  Used to signal the parent item was found in one of it's children
 * @param bool &$menu_out
 *  Output array of parent, siblings and children menu links
 */
244 245 246 247 248
function expire_get_menu_structure($menu, $found, $needle, $first, &$found_global, &$menu_out) {
  // Set Defaults
  $found = !is_null($found) ? $found : TRUE;
  $needle = !is_null($needle) ? $needle : '';
  $first = !is_null($first) ? $first : TRUE;
Mike Carper's avatar
Mike Carper committed
249
  $found_global = FALSE;
250 251
  $menu_out = !is_null($menu_out) ? $menu_out : array();

Mike Carper's avatar
Mike Carper committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
  // Get Siblings
  foreach ($menu as $item) {
    if ($item['link']['hidden'] == 0 && $item['link']['page_callback'] != '' && ($item['link']['link_path'] == $needle || $found)) {
      $menu_out[] = $item['link']['link_path'];
      $found = TRUE;
    }
  }
  // Get Children
  foreach ($menu as $item) {
    if ($item['link']['hidden'] != 0) {
      continue;
    }
    if ($item['link']['page_callback'] != '' && ($item['link']['link_path'] == $needle || $found)) {
      $menu_out[] = $item['link']['link_path'];
      $found = TRUE;
    }
    // Get Grandkids
    if (!empty($item['below'])) {
      $sub_menu = array();
      foreach ($item['below'] as $below) {
        if ($below['link']['hidden'] == 0) {
          $sub_menu[] = $below;
        }
      }
      expire_get_menu_structure($sub_menu, $needle, $found, FALSE, $found_global, $menu_out);
      $structure[$item['link']['link_path']][] = $sub;
      if ($item['link']['page_callback'] != '' && $found_global) {
        // Get Parent of kid
        $menu_out[] = $item['link']['link_path'];
      }
    }
    else {
      $structure[$item['link']['link_path']] = '';
    }
  }

  // Clean up
289
  if (isset($structure) && is_array($structure)) {
Mike Carper's avatar
Mike Carper committed
290 291 292 293
    $structure = array_unique($structure);
  }
  $found_global = $found;
  if ($first) {
294 295 296 297 298 299 300 301
    if (isset($menu_out) && is_array($menu_out)) {
      $menu_out = array_unique($menu_out);
      sort($menu_out);
      return $menu_out;
    }
    else {
      return array();
    }
Mike Carper's avatar
Mike Carper committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
  }
  else {
    return $structure;
  }
}

/**
 * Return taxonomy terms given a nid.
 *
 * Needed because of a weird bug with CCK & node_load()
 *  http://drupal.org/node/545922
 */
function expire_taxonomy_node_get_tids($nid) {
  $vid = db_result(db_query('SELECT vid FROM {node} WHERE nid = %d', $nid));
  $result = db_query(db_rewrite_sql('SELECT t.tid FROM {term_node} r INNER JOIN {term_data} t ON r.tid = t.tid INNER JOIN {vocabulary} v ON t.vid = v.vid WHERE r.vid = %d ORDER BY v.weight, t.weight, t.name', 't', 'tid'), $vid);
  $tids = array();
  while ($term = db_result($result)) {
    $tids[] = $term;
  }
  return $tids;
}

/**
 * Finds all possible paths/redirects/aliases given the root path.
 *
327 328
 * @param $node
 *   node object
Mike Carper's avatar
Mike Carper committed
329 330 331
 * @param $paths
 *   Array of current URLs
 */
332
function expire_cache_derivative(&$node, $paths) {
Mike Carper's avatar
Mike Carper committed
333 334 335 336 337 338 339 340 341 342
  global $base_path;
  $expire = array();

  if (empty($paths)) {
    return FALSE;
  }
  foreach ($paths as $path) {
    // Given path
    $expire[] = $path;

343 344 345 346 347 348
    // Add the empty front page path if this is the alias
    if ($path == variable_get('site_frontpage', 'node')) {
      $expire[] = '';
      $expire[] = 'rss.xml';
    }

Mike Carper's avatar
Mike Carper committed
349 350 351 352 353 354 355
    // Special front page feed handling
    if ($path == '' || $path == '<front>') {
      $expire[] = 'rss.xml';
    }

    // Path alias
    $path_alias = url($path, array('absolute' => FALSE));
356 357
    // Remove the base path
    $expire[] = substr($path_alias, strlen($base_path));
Mike Carper's avatar
Mike Carper committed
358 359 360 361 362 363 364 365 366 367 368 369

    // Path redirects
    if (module_exists('path_redirect')) {
      $path_redirects = expire_path_redirect_load(array('redirect' => $path));
      if (isset($path_redirects)) {
        foreach ($path_redirects as $path_redirect) {
          $expire[] = $path_redirect['path'];
        }
      }
    }
  }

370 371 372
  // Allow other modules to modify the list prior to expiring
  drupal_alter('expire_cache', $expire, $node, $paths);

Mike Carper's avatar
Mike Carper committed
373 374 375 376 377 378 379 380
  // Expire cached files
  if (empty($expire)) {
    return FALSE;
  }
  $expire = array_unique($expire);
  // Add on the url to these paths
  $urls = array();
  global $base_url;
381 382 383 384 385 386
  if (variable_get('expire_include_base_url', EXPIRE_INCLUDE_BASE_URL)) {
    foreach (expire_get_base_urls($node) as $domain_id) {
      foreach ($domain_id as $base) {
        foreach ($expire as $path) {
          $urls[] = $base . $path;
        }
387 388
      }
    }
Mike Carper's avatar
Mike Carper committed
389
  }
390 391 392
  else {
    $urls = $expire;
  }
Mike Carper's avatar
Mike Carper committed
393
  // hook_expire_cache
394 395
  $modules = module_implements('expire_cache');
  foreach ($modules as $module) {
Mike Carper's avatar
Mike Carper committed
396 397
    module_invoke($module, 'expire_cache', $urls);
  }
398 399 400 401 402
  watchdog('expire', 'Input: !paths <br /> Output: !urls <br /> Modules Using hook_expire_cache(): !modules', array(
    '!paths' => expire_print_r($paths),
    '!urls' => expire_print_r($urls),
    '!modules' => expire_print_r($modules),
  ));
Mike Carper's avatar
Mike Carper committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
  return count($urls);
}

/**
 * Retrieve a specific URL redirect from the database.
 * http://drupal.org/node/451790
 *
 * @param $where
 *   Array containing 'redirect' => $path
 */
function expire_path_redirect_load($where = array(), $args = array(), $sort = array()) {
  $redirects = array();
  if (is_numeric($where)) {
    $where = array('rid' => $where);
  }

  foreach ($where as $key => $value) {
    if (is_string($key)) {
      $args[] = $value;
      $where[$key] = $key .' = '. (is_numeric($value) ? '%d' : "'%s'");
    }
  }

  if ($where && $args) {
    $sql = "SELECT * FROM {path_redirect} WHERE ". implode(' AND ', $where);
    if ($sort) {
      $sql .= ' ORDER BY '. implode(' ,', $sort);
    }
    $result = db_query($sql, $args);
    while ($redirect = db_fetch_array($result)) {
      $redirects[] = $redirect;
    }
    return $redirects;
  }
}
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483

/**
 * Simple print_r to html function
 *
 * @param $data
 *
 * @return string
 *   print_r contents in nicely formatted html
 */
function expire_print_r($data) {
  return str_replace('    ', '&nbsp;&nbsp;&nbsp;&nbsp;', nl2br(htmlentities(print_r($data, TRUE))));
}

/**
 * Get all base url's where this node can appear. Domain access support.
 *
 * @param $node
 *   node object
 * @return array
 *   array(0 => array($base_url . '/'))
 */
function expire_get_base_urls(&$node) {
  global $base_url, $base_path;

  // Get list of URL's if using domain access
  $base_urls = array();
  $domains = array();
  if (module_exists('domain') && isset($node->domains)) {
    // Get domains from node/user object
    foreach ($node->domains as $key => $domain_id) {
      if ($key != $domain_id) {
        continue;
      }
      $domains[$domain_id] = $domain_id;
    }
    // Get domains from database
    foreach (expire_get_domains($node) as $domain_id) {
      $domains[$domain_id] = $domain_id;
    }
    // Get aliases and set base url
    foreach ($domains as $domain_id) {
      $domain = domain_lookup($domain_id);
      if ($domain['valid'] == 1) {
        if (isset($domain['path'])) {
          $base_urls[$domain_id][] = $domain['path'];
        }
484 485 486 487 488 489
        if (is_array($domain['aliases'])) {
          foreach ($domain['aliases'] as $alias) {
            if ($alias['redirect'] != 1) {
              $temp_domain = array('scheme' => $domain['scheme'], 'subdomain' => $alias['pattern']);
              $base_urls[$domain_id][] = domain_get_path($temp_domain);
            }
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
          }
        }
      }
    }
  }
  else {
    $base_urls[0][] = $base_url . '/';
  }
  return $base_urls;
}

/**
 * Get domains the node is currently published to
 *
 * @param $node
 *   node object
 * @return array
 *   array('$gid' => $gid)
 */
function expire_get_domains(&$node) {
  $domains = array();
  if ($node->nid) {
    $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;
    }
  }
  elseif ($node->mail && $node->name) {
    $result = db_query("SELECT domain_id FROM {domain_editor} WHERE uid = %d", $node->uid);
    while ($row = db_fetch_array($result)) {
      $gid = $row['domain_id'];
      $domains[$gid] = $gid;
    }
  }
  return $domains;
}