expire.module 10.2 KB
Newer Older
Mike Carper's avatar
Mike Carper committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 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 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 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 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 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 327 328 329 330 331 332 333 334 335 336 337 338
<?php

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

define('EXPIRE_FLUSH_NODE_TERMS', TRUE);
define('EXPIRE_FLUSH_MENU_ITEMS', 1);
define('EXPIRE_FLUSH_CCK_REFERENCES', TRUE);


/**
 * Implementation of hook_comment(). Acts on comment modification.
 */
function expire_comment($comment, $op) {

  switch ($op) {
    case 'insert':
    case 'update':
      // Expire the relevant node page from the static page cache to prevent serving stale content:
      if (!empty($comment['nid'])) {
        $node = node_load($comment['nid']);
        $node->nid = $comment['nid'];
        expire_node($node);
      }
      break;
    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) {
  if (!BOOST_ENABLED) return;

  foreach ($votes as $vote) {
    $node = node_load($vote['content_id']);
    $node->nid = $vote['content_id'];
    expire_node($node);
  }
}

/**
 * Implementation of hook_votingapi_delete().
 *
 * @param $votes
 *  array of votes
 */
function expire_votingapi_delete($votes) {
  if (!BOOST_ENABLED) return;

  foreach ($votes as $vote) {
    $node = node_load($vote['content_id']);
    $node->nid = $vote['content_id'];
    boost_expire_node($node);
  }
}

/**
 * Implementation of hook_user(). Acts on user account actions.
 */
function expire_user($op, &$edit, &$account, $category = NULL) {

  global $user;
  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;
        $flushed = expire_cache_derivative($paths, TRUE, TRUE);
        watchdog('boost', 'expire_user() <br />User !uid was deleted resulting in !flushed pages being expired from the cache',  array('!uid' => $account->uid, '!flushed' => $flushed));
      }
      break;
  }
}

/**
 * Expires a node from the cache; including related pages.
 *
 * Expires front page if promoted, taxonomy terms,
 *
 * @param $node
 *  node object
 * @param $nid
 *  node id
 */
function expire_node($node) {
  $data = array();
  $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
  if ($node->promote == 1) {
    $paths['front'] = '<front>';
  }

  // Get taxonomy terms and flush
  if (module_exists('taxonomy') && EXPIRE_FLUSH_NODE_TERMS) {
    $tids = boost_taxonomy_node_get_tids($node->nid);
    $filenames = array();
    foreach ($tids as $tid) {
      if (is_int($tid)) {
        $paths['term' . $tid] = 'taxonomy/term/' . $tid;
      }
    }
  }

  // Get menu and flush related items in the menu.
  if (EXPIRE_FLUSH_MENU_ITEMS !=0) {
    if (!isset($node->menu['menu_name'])) {
      menu_nodeapi($node, 'prepare');
    }
    $menu = menu_tree_all_data($node->menu['menu_name']);
    if (EXPIRE_FLUSH_MENU_ITEMS == 1) {
      $links = expire_get_menu_structure($menu, FALSE, 'node/' . $node->nid);
    }
    elseif (EXPIRE_FLUSH_MENU_ITEMS == 2) {
      $links = expire_get_menu_structure($menu);
    }
    $paths = array_merge($links, $paths);
  }

  // Get CCK References and flush.
  if (EXPIRE_FLUSH_CCK_REFERENCES && module_exists('nodereference')) {
    $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) {
            $nids[$item['nid']] = $item['nid'];
          }
        }
      }
      foreach ($nids as $nid) {
        if (is_int($nid)) {
          $paths['reference' . $nid] = 'node/' . $nid;
        }
      }
    }

    // Get CCK references pointing to this node and flush.
    if (module_exists('nodereferrer')) {
      $nids = nodereferrer_referrers($node->nid);
      foreach ($nids as $nid) {
        if (is_int($nid['nid'])) {
          $paths['referrer' . $nid['nid']] = 'node/' . $nid['nid'];
        }
      }
    }
  }

  // Flush array of paths
  if (!empty($paths)) {
    $flushed = expire_cache_derivative($paths, TRUE);
    watchdog('expire', 'expire_node() <br />Node !nid was flushed resulting in !flushed pages being expired from the cache',  array('!nid' => $node->nid, '!flushed' => $flushed));
  }
}

/**
 * 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
 *
 * TODO: Use page_callback and page_arguments instead of link_path.
 *  Can use boost_cache_expire_router() then.
 */
function expire_get_menu_structure($menu, $found = TRUE, $needle = '', $first = TRUE, &$found_global = FALSE, &$menu_out = array()) {
  $found_global = FALSE;
  // 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
  if (is_array($structure)) {
    $structure = array_unique($structure);
  }
  $found_global = $found;
  if ($first) {
    $menu_out = array_unique($menu_out);
    sort($menu_out);
    return $menu_out;
  }
  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.
 *
 * @param $paths
 *   Array of current URLs
 * @param $both
 *   Expire database & file
 * @param $force_flush
 *   Override the settings and kill the file
 */
function expire_cache_derivative($paths, $both = FALSE, $force_flush = FALSE) {
  global $base_path;
  $expire = array();

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

    // Special front page feed handling
    if ($path == '' || $path == '<front>') {
      $expire[] = 'rss.xml';
    }

    // Path alias
    $path_alias = url($path, array('absolute' => FALSE));
    if ($base_path != '/') {
      $path_alias = implode('/', array_diff_assoc(array_filter(explode('/', $path_alias)), array_filter(explode('/', $base_path))));
    }
    $expire[] = $path_alias;

    // 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'];
        }
      }
    }
  }

  // Expire cached files
  if (empty($expire)) {
    return FALSE;
  }
  $expire = array_unique($expire);
339
  watchdog('expire','<pre><tt>' .  print_r($expire, TRUE) . '</tt></pre>');
Mike Carper's avatar
Mike Carper committed
340 341
  // hook_expire_cache
  foreach (module_implements('expire_cache') as $module) {
342
    module_invoke($module, 'expire_cache', $expire);
Mike Carper's avatar
Mike Carper committed
343
  }
344
  return count($expire);
Mike Carper's avatar
Mike Carper committed
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
}

/**
 * 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;
  }
}