xmlsitemap.module 29 KB
Newer Older
Darren Oh's avatar
Darren Oh committed
1 2 3 4 5 6 7 8 9 10
<?php
// $Id$

/**
 * @file Creates a site map compatible with the sitemaps.org schema.
 */

/**
 * Implementation of hook_help().
 */
11 12
function xmlsitemap_help($path, $arg) {
  switch ($path) {
Darren Oh's avatar
Darren Oh committed
13 14
    case 'admin/settings/xmlsitemap':
    case 'admin/settings/xmlsitemap/settings':
15
      return t('Configure the site map. Your site map is at !url.', array('!url' => '<a href="'. xmlsitemap_url('sitemap.xml', drupal_lookup_path('alias', 'sitemap.xml') ? drupal_lookup_path('alias', 'sitemap.xml') : NULL, NULL, NULL, TRUE) .'">'. xmlsitemap_url('sitemap.xml', drupal_lookup_path('alias', 'sitemap.xml') ? drupal_lookup_path('alias', 'sitemap.xml') : NULL, NULL, NULL, TRUE) .'</a>'));
Darren Oh's avatar
Darren Oh committed
16 17 18 19 20 21 22 23 24 25
    case 'admin/settings/xmlsitemap/engines':
      return t('Configure behavior for search engines.');
    case 'admin/settings/xmlsitemap/additional':
      return t('Set up additional links for your site map.');
  }
}

/**
 * Implementation of hook_menu().
 */
26
function xmlsitemap_menu() {
Darren Oh's avatar
Darren Oh committed
27
  $items = array();
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
  $access_config = array('administer site configuration');
  $access_content = array('access content');
  $items['admin/settings/xmlsitemap'] = array(
    'title' => 'XML Sitemap',
    'description' => 'Configure site map.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('xmlsitemap_settings_sitemap'),
    'access arguments' => $access_config,
  );
  $items['admin/settings/xmlsitemap/settings'] = array(
    'title' => 'Site map',
    'description' => 'Configure site map.',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -1,
  );
  $items['admin/settings/xmlsitemap/engines'] = array(
    'title' => 'Search engines',
    'description' => 'Configure search engines.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('xmlsitemap_settings_engines'),
    'type' => MENU_LOCAL_TASK,
    'access arguments' => $access_config,
  );
  $items['admin/settings/xmlsitemap/additional'] = array(
    'title' => 'Additional',
    'description' => 'Configure additional links.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('xmlsitemap_settings_additional'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
    'access arguments' => $access_config,

  );
  $items['sitemap.xml'] = array(
    'title' => 'Site map index',
    'page callback' => '_xmlsitemap_output',
    'type' => MENU_CALLBACK,
    'access arguments' => $access_content
  );
  $chunk_count = variable_get('xmlsitemap_chunk_count', 0);
  for ($chunk = 0; $chunk < $chunk_count; ++$chunk) {
    $items["sitemap$chunk.xml"] = array(
70 71
      'title' => 'Site map !number',
      'title arguments' => array('!number' => $chunk),
72
      'page callback' => '_xmlsitemap_output',
73
      'page arguments' => array((string)$chunk),
Darren Oh's avatar
Darren Oh committed
74
      'type' => MENU_CALLBACK,
75
      'access arguments' => $access_content
Darren Oh's avatar
Darren Oh committed
76 77
    );
  }
78

Darren Oh's avatar
Darren Oh committed
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
  return $items;
}

/**
 * Menu callback; return site map settings form.
 */
function xmlsitemap_settings_sitemap() {
  $form['xmlsitemap_chunk_size'] = array(
    '#type' => 'textfield',
    '#title' => t('Chunk size'),
    '#default_value' => variable_get('xmlsitemap_chunk_size', 50000),
    '#size' => 10,
    '#maxlength' => 5,
    '#description' => t('This is the number of links to include in one site map. Values can range between 1 and 50,000. If the total number of links exceeds the chunk size, multiple site maps will be generated.'),
    '#weight' => -1,
  );
  $form['xmlsitemap_front_page_priority'] = array(
    '#type' => 'select',
    '#title' => t('Front page priority'),
    '#default_value' => variable_get('xmlsitemap_front_page_priority', 1),
    '#options' => xmlsitemap_priority_options(),
    '#description' => t('This is the absolute priority for the front page.'),
    '#weight' => -1,
  );
  return system_settings_form($form);
}

/**
 * Validate site map settings form.
 */
109 110
function xmlsitemap_settings_sitemap_validate($form, &$form_state) {
  if ($form_state['values']['xmlsitemap_chunk_size'] > 50000) {
Darren Oh's avatar
Darren Oh committed
111 112 113 114 115 116 117
    form_set_error('xmlsitemap_chunk_size', t('Cannot send more than 50,000 links at one time.'));
  }
}

/**
 * Submit site map settings form.
 */
118 119
function xmlsitemap_settings_sitemap_submit($form, &$form_state) {
  system_settings_form_submit($form, $form_state);
Darren Oh's avatar
Darren Oh committed
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
  xmlsitemap_update_sitemap();
}

/**
 * Menu callback; return search engine settings form.
 */
function xmlsitemap_settings_engines() {
  $form['submission'] = array(
    '#type' => 'fieldset',
    '#title' => t('Submission settings'),
  );
  $form['submission']['xmlsitemap_submit'] = array(
    '#type' => 'checkbox',
    '#title' => t('Submit site map when updated.'),
    '#default_value' => variable_get('xmlsitemap_submit', FALSE),
    '#description' => t('If enabled, search engines will be notified of changes to the site map each time it is updated.'),
  );
  $form['submission']['xmlsitemap_cron_submit'] = array(
    '#type' => 'checkbox',
    '#title' => t('Submit site map on cron run.'),
    '#default_value' => variable_get('xmlsitemap_cron_submit', FALSE),
    '#description' => t('If enabled, search engines will be notified of changes to the site map each time cron is run.'),
  );
  $form['submission']['xmlsitemap_log_access'] = array(
    '#type' => 'checkbox',
    '#title' => t('Log access.'),
    '#default_value' => variable_get('xmlsitemap_log_access', FALSE),
    '#description' => t('If enabled, a watchdog entry will be made each time the site map is accessed, containing information about the requestor.'),
  );
  $form = array_merge($form, module_invoke_all('xmlsitemap_engines', 'form'));
  menu_rebuild();
  return system_settings_form($form);
}

/**
 * Submit search engine settings form.
 */
157 158 159 160
function xmlsitemap_settings_engines_submit($form, &$form_state) {
  if ($form_state['values']['xmlsitemap_root']) {
    $form_state['values']['xmlsitemap_submit'] = FALSE;
    $form_state['values']['xmlsitemap_log_access'] = FALSE;
Darren Oh's avatar
Darren Oh committed
161
  }
162
  system_settings_form_submit($form, $form_state);
Darren Oh's avatar
Darren Oh committed
163 164 165 166 167 168 169 170 171
}

/**
 * Menu callback; return additional links form.
 */
function xmlsitemap_settings_additional() {
  $form['xmlsitemap_additional_links_priority'] = array(
    '#type' => 'select',
    '#title' => t('Link priority'),
172
    '#default_value' => variable_get('xmlsitemap_additional_links_priority', 0.5),
Darren Oh's avatar
Darren Oh committed
173 174 175 176 177 178 179 180 181 182
    '#options' => xmlsitemap_priority_options(),
    '#description' => t('This is the default priority for additional links.'),
  );
  $form['delete']['#tree'] = TRUE;
  $form['path']['#tree'] = TRUE;
  $form['link']['#tree'] = TRUE;
  $form['link']['new'] = array(
    '#type' => 'textfield',
    '#size' => 40,
    '#description' => t('Enter a Drupal path to add to the site map.'),
183
    '#attributes' => array('tabindex' => 1),
Darren Oh's avatar
Darren Oh committed
184
  );
185 186
  $form['old_priority']['#tree'] = TRUE;
  $form['priority']['#tree'] = TRUE;
Darren Oh's avatar
Darren Oh committed
187 188 189 190
  $form['priority']['new'] = array(
    '#type' => 'select',
    '#default_value' => 'NULL',
    '#options' => xmlsitemap_priority_options('default'),
191
    '#attributes' => array('tabindex' => 2),
Darren Oh's avatar
Darren Oh committed
192
  );
193 194
  $result = pager_query("SELECT path, priority FROM {xmlsitemap_additional} ORDER BY last_changed DESC", 50);
  while ($link = db_fetch_object($result)) {
195 196 197 198
    $id = $link->path == 'new' ? '_new' : str_replace(array('_', '%'), array('__', '_'), urlencode($link->path));
    $form['delete'][$id] = array('#type' => 'checkbox', '#default_value' => FALSE);
    $form['path'][$id] = array('#type' => 'value', '#value' => $link->path);
    $form['link'][$id] = array('#value' => '<a href="'. xmlsitemap_url($link->path, drupal_lookup_path('alias', $link->path) ? drupal_lookup_path('alias', $link->path) : NULL) .'">'. $link->path .'</a>');
199
    $priority = isset($link->priority) ? $link->priority : 'NULL';
200 201
    $form['old_priority'][$id] = array('#type' => 'value', '#value' => $priority);
    $form['priority'][$id] = array('#type' => 'select', '#default_value' => $priority, '#options' => xmlsitemap_priority_options('default'));
202 203
  }
  $form['pager'] = array('#value' => theme('pager', NULL, 50));
Darren Oh's avatar
Darren Oh committed
204 205 206
  return system_settings_form($form);
}

207 208 209 210 211 212 213 214 215
/**
 * Implementation of hook_theme().
 */
function xmlsitemap_theme() {
  return array(
    'xmlsitemap_settings_additional' => array('form'),
  );
}

Darren Oh's avatar
Darren Oh committed
216 217 218 219 220 221 222 223
/**
 * Theme additional links form.
 * @ingroup themeable
 */
function theme_xmlsitemap_settings_additional($form) {
  $output = '';
  $output .= drupal_render($form['xmlsitemap_additional_links_priority']);
  $header = array(t('Delete'), t('Path'), t('Priority'));
224
  foreach (element_children($form['link']) as $id) {
Darren Oh's avatar
Darren Oh committed
225
    $row = array();
226 227 228 229
    $row[] = isset($form['delete'][$id]) ? drupal_render($form['delete'][$id]) : array_merge(array('header' => TRUE, 'valign' => 'bottom'), theme('table_select_header_cell'));
    $row[] = drupal_render($form['link'][$id]);
    $row[] = drupal_render($form['priority'][$id]);
    $rows[$id] = array('data' => $row, 'valign' => 'top');
Darren Oh's avatar
Darren Oh committed
230 231 232 233 234
  }
  if (!empty($rows)) {
    $output .= theme('table', $header, $rows);
  }
  $output .= drupal_render($form);
235
  drupal_add_js('document.getElementById("edit-link-new").focus()', 'inline', 'footer');
Darren Oh's avatar
Darren Oh committed
236 237 238
  return $output;
}

239

Darren Oh's avatar
Darren Oh committed
240 241 242
/**
 * Submit additional links form.
 */
243
function xmlsitemap_settings_additional_submit($form, &$form_state) {
Darren Oh's avatar
Darren Oh committed
244
  $update = FALSE;
245 246
  if ($form_state['values']['op'] == t('Save configuration')) {
    if ($form_state['values']['xmlsitemap_additional_links_priority'] != variable_get('xmlsitemap_additional_links_priority', 0.1)) {
Darren Oh's avatar
Darren Oh committed
247 248
      $update = TRUE;
    }
249 250 251 252 253
    if (!empty($form_state['values']['delete'])) {
      foreach ($form_state['values']['delete'] as $id => $delete) {
        if ($delete || $form_state['values']['path'][$id] == trim($form_state['values']['link']['new'])) {
          db_query("DELETE FROM {xmlsitemap_additional} WHERE path = '%s'", $form_state['values']['path'][$id]);
          unset($form_state['values']['priority'][$id]);
Darren Oh's avatar
Darren Oh committed
254 255 256
          $update = TRUE;
        }
      }
257
      unset($form_state['values']['delete']);
Darren Oh's avatar
Darren Oh committed
258
    }
259
    $path = trim($form_state['values']['link']['new']);
Darren Oh's avatar
Darren Oh committed
260 261 262 263
    $pid = db_result(db_query("SELECT pid FROM {url_alias} WHERE src = '%s'", $path));
    if (!empty($path)) {
      db_query("
        INSERT INTO {xmlsitemap_additional} (path, pid, last_changed, priority) VALUES ('%s', %s, %d, %s)
264 265
      ", $path, empty($pid) ? 'NULL' : $pid, time(), $form_state['values']['priority']['new']);
      unset($form_state['values']['link'], $form_state['values']['priority']['new']);
Darren Oh's avatar
Darren Oh committed
266 267
      $update = TRUE;
    }
268 269 270 271
    if (!empty($form_state['values']['priority'])) {
      foreach ($form_state['values']['priority'] as $id => $priority) {
        if ($priority != $form_state['values']['old_priority'][$id]) {
          $pid = db_result(db_query("SELECT pid FROM {url_alias} WHERE src = '%s'", $form_state['values']['path'][$id]));
Darren Oh's avatar
Darren Oh committed
272 273 274 275
          db_query("
            UPDATE {xmlsitemap_additional}
            SET pid = %s, previously_changed = last_changed, last_changed = %d, priority = %s
            WHERE path = '%s'
276
          ", empty($pid) ? 'NULL' : $pid, time(), $priority, $form_state['values']['path'][$id]);
Darren Oh's avatar
Darren Oh committed
277 278 279
          $update = TRUE;
        }
      }
280
      unset($form_state['values']['path'], $form_state['values']['priority'], $form_state['values']['old_priority']);
Darren Oh's avatar
Darren Oh committed
281 282 283
    }
  }
  elseif (variable_get('xmlsitemap_additional_links_priority', 0.1) != 0.1) {
284
    if (in_array('NULL', $form_state['values']['old_priority'])) {
Darren Oh's avatar
Darren Oh committed
285 286
      $update = TRUE;
    }
287
    unset($form_state['values']['delete'], $form_state['values']['path'], $form_state['values']['link'], $form_state['values']['old_priority'], $form_state['values']['priority']);
Darren Oh's avatar
Darren Oh committed
288
  }
289
  system_settings_form_submit($form, $form_state);
Darren Oh's avatar
Darren Oh committed
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
  if ($update) {
    xmlsitemap_update_sitemap();
  }
}

/**
 * Get an array of site map priority options.
 * @param $option:
 * If not given, the array will include priority values from 0.0 to 1.0.
 * - exclude: Add option to exclude item from site map.
 * - default: Add option to use default priority. Only for cases where a
 *   default priority exists.
 * - both: Add both the default and exclude options.
 * @return An array of priority options.
 */
function xmlsitemap_priority_options($option = NULL) {
  if ($option == 'default' || $option == 'both') {
    $options['NULL'] = t('Default');
  }
  $options['1'] = '1.0';
  $values = array('0.9', '0.8', '0.7', '0.6', '0.5', '0.4', '0.3', '0.2', '0.1');
  foreach ($values as $value) {
    $options[$value] = $value;
  }
  $options['0'] = '0.0';
315
  if ($option == 'exclude' || $option == 'both') {
Darren Oh's avatar
Darren Oh committed
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    $options['-1'] = t('Not in site map');
  }
  return $options;
}

/**
 * Implementation of hook_robotstxt().
 */
function xmlsitemap_robotstxt() {
  return array("Sitemap: ". xmlsitemap_url('sitemap.xml', drupal_lookup_path('alias', 'sitemap.xml') ? drupal_lookup_path('alias', 'sitemap.xml') : NULL, NULL, NULL, TRUE));
}

/**
 * Menu callback; display the site map.
 * @param $chunk:
 * An integer specifying which chunk of the site map is being requested. If
 * not set and there is more than one chunk, display the site map index.
333
 * @return None
Darren Oh's avatar
Darren Oh committed
334 335 336 337 338
 */
function _xmlsitemap_output($chunk = NULL) {
  drupal_set_header('Content-type: text/xml; charset=utf-8');
  global $user;
  $dest = file_directory_path() .'/xmlsitemap';
339
  file_check_directory($dest, FILE_CREATE_DIRECTORY);
Darren Oh's avatar
Darren Oh committed
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
  if (isset($chunk)) {
    $dest .= "/sitemap$chunk.xml.gz";
    $type = t('Site map @chunk', array('@chunk' => $chunk));
  }
  else {
    $dest .= '/sitemap.xml.gz';
    $link_count = _xmlsitemap_link_count();
    $chunk_size = variable_get('xmlsitemap_chunk_size', 50000);
    $type = $link_count > $chunk_size ? t('Site map index') : t('Site map');
  }
  $status = TRUE;
  if (!file_exists($dest) || variable_get('xmlsitemap_update', FALSE)) {
    $page = isset($chunk) ? $chunk : 'index';
    $status = _xmlsitemap_update_cache($page);
  }
  if ($status) {
    if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === FALSE || zlib_get_coding_type() !== FALSE || extension_loaded('eAccelerator') || (variable_get('cache', CACHE_DISABLED) != CACHE_DISABLED && empty($user->uid))) {
      readgzfile($dest);
    }
    else {
      drupal_set_header('Content-Encoding: gzip');
      print file_get_contents($dest);
    }
    if (variable_get('xmlsitemap_log_access', FALSE)) {
      $message = array_shift(module_invoke_all('xmlsitemap_engines', 'access', $type));
365 366 367 368 369 370 371 372 373 374
      if (isset($message)) {
        watchdog('xmlsitemap', $message);
      }
      else {
        watchdog('xmlsitemap', '!sitemap downloaded by @user-agent at @address.', array(
          '!sitemap' => $type,
          '@user-agent' => $_SERVER['HTTP_USER_AGENT'],
          '@address' => ip_address(),
        ));
      }
Darren Oh's avatar
Darren Oh committed
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
    }
  }
  else {
    drupal_not_found();
  }
}

/**
 * Count the total number of links in the site.
 * @return An integer containing the total number of links
 */
function _xmlsitemap_link_count() {
  static $count;
  $count = isset($count) ? $count : count(_xmlsitemap_links());
  return $count;
}

/**
 * Update the cached site map files.
 * @return TRUE if the update was successful, FALSE otherwise.
 */
function _xmlsitemap_update_cache($page = NULL) {
  global $user;
  $current_user = $user;
  $user = user_load(array('uid' => 0));
  $path = file_directory_path() .'/xmlsitemap';
401
  file_check_directory($path, FILE_CREATE_DIRECTORY);
Darren Oh's avatar
Darren Oh committed
402 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
  $node_count = db_result(db_query("SELECT COUNT(*) FROM {node}"));
  $dest = $path .'/sitemap.xml.gz';
  $link_count = _xmlsitemap_link_count();
  $chunk_size = variable_get('xmlsitemap_chunk_size', 50000);
  $status = TRUE;
  if ($link_count > $chunk_size) {
    $data = gzencode(_xmlsitemap_output_index($link_count));
    if (file_save_data($data, $dest, FILE_EXISTS_REPLACE) === 0 && ($page == 'index' || !isset($page))) {
      $status = FALSE;
    }
    for ($chunk = 0; $chunk < $link_count / $chunk_size; ++$chunk) {
      $dest = $path ."/sitemap$chunk.xml.gz";
      $data = gzencode(_xmlsitemap_output_chunk($chunk));
      if (file_save_data($data, $dest, FILE_EXISTS_REPLACE) === 0 && ($page == $chunk || !isset($page))) {
        $status = FALSE;
      }
    }
  }
  else {
    $chunk = 0;
    $data = gzencode(_xmlsitemap_output_chunk($chunk));
    if (file_save_data($data, $dest, FILE_EXISTS_REPLACE) === 0 && ($page == 'index' || !isset($page))) {
      $status = FALSE;
    }
  }
  variable_set('xmlsitemap_chunk_count', $chunk);
  variable_set('xmlsitemap_update', FALSE);
  if (!$status) {
430
    drupal_set_message(t('Unable to load site map. Make sure that there is an xmlsitemap directory in your files directory and that it is writable by Drupal.'), 'error');
Darren Oh's avatar
Darren Oh committed
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
  }
  $user = $current_user;
  return $status;
}

/**
 * Generate the site map index.
 * @param $link_count:
 * An integer containing the total number of links in the site
 * @return A string containing the site map index
 */
function _xmlsitemap_output_index($link_count) {
  $output = '';
  global $base_path;
  $xsl_path = file_directory_path() .'/xmlsitemap/gss.xsl';
446
  $xsl_path = file_exists($xsl_path) ? _xmlsitemap_file_create_url($xsl_path) : $base_path . drupal_get_path('module', 'xmlsitemap') .'/gss/gss.xsl';
Darren Oh's avatar
Darren Oh committed
447 448
  $output .= '<?xml version="1.0" encoding="UTF-8"?>'."\n";
  $output .= '<?xml-stylesheet type="text/xsl" href="'. $xsl_path .'" ?>'."\n";
449 450 451 452
  $output .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"'."\n";
  $output .= '              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'."\n";
  $output .= '              xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9'."\n";
  $output .= '                                  http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd">'."\n";
Darren Oh's avatar
Darren Oh committed
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 484 485 486 487 488 489 490 491 492
  $chunk_size = variable_get('xmlsitemap_chunk_size', 50000);
  for ($chunk = 0; $chunk < $link_count / $chunk_size; ++$chunk) {
    $output .= '<sitemap><loc>'. xmlsitemap_url("sitemap$chunk.xml", NULL, NULL, NULL, TRUE) .'</loc>';
    $previous = $chunk * $chunk_size;
    $links = array_slice(_xmlsitemap_links(), $previous, $chunk_size);
    $output .= '<lastmod>'. gmdate('Y-m-d\TH:i:s+00:00', array_reduce($links, '_xmlsitemap_chunk_last_change')) .'</lastmod>';
    $output .= "</sitemap>\n";
  }
  $output .= '</sitemapindex>';
  return $output;
}

/**
 * Compare link modification time to modification time of previous link.
 * @param $time:
 * Modification time of previous link
 * @param $value:
 * Link array
 * @return Most recent time
 */
function _xmlsitemap_chunk_last_change($time, $value) {
  if ($time < $value['#lastmod']) {
    $time = $value['#lastmod'];
  }
  return $time;
}

/**
 * Generate a chunk of the site map.
 * @param $chunk:
 * An integer specifying which chunk of the site map to display
 * @return A string containing a chunk of the site map
 */
function _xmlsitemap_output_chunk($chunk) {
  $output = '';
  global $base_path;
  if (!ini_get('safe_mode')) {
    set_time_limit(240);
  }
  $xsl_path = file_directory_path() .'/xmlsitemap/gss.xsl';
493
  $xsl_path = file_exists($xsl_path) ? _xmlsitemap_file_create_url($xsl_path) : $base_path . drupal_get_path('module', 'xmlsitemap') .'/gss/gss.xsl';
Darren Oh's avatar
Darren Oh committed
494 495
  $output .= '<?xml version="1.0" encoding="UTF-8"?>'."\n";
  $output .= '<?xml-stylesheet type="text/xsl" href="'. $xsl_path .'" ?>'."\n";
496 497 498 499
  $output .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"'."\n";
  $output .= '        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'."\n";
  $output .= '        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9'."\n";
  $output .= '                            http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">'."\n";
Darren Oh's avatar
Darren Oh committed
500 501 502 503 504 505 506
  $chunk_size = variable_get('xmlsitemap_chunk_size', 50000);
  $previous = $chunk * $chunk_size;
  $output .= implode("\n", _xmlsitemap_format(array_slice(_xmlsitemap_links(), $previous, $chunk_size)));
  $output .= "\n</urlset>";
  return $output;
}

507 508 509 510 511 512 513 514 515 516 517 518
/**
 * Modified version of file_create_url(). Allows us to remove language
 * prefixes.
 * @param $path: the path to the file
 * @return A URL to the file
 */
function _xmlsitemap_file_create_url($path) {
  $path = trim(substr($path, strlen(file_directory_path())), '\\/');
  switch (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC)) {
    case FILE_DOWNLOADS_PUBLIC:
      return $GLOBALS['base_url'] .'/'. file_directory_path() .'/'. str_replace('\\', '/', $path);
    case FILE_DOWNLOADS_PRIVATE:
Darren Oh's avatar
Darren Oh committed
519
      return xmlsitemap_url('system/files/'. $path, NULL, NULL, NULL, TRUE);
520 521 522
  }
}

Darren Oh's avatar
Darren Oh committed
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
/**
 * Implementation of hook_file_download().
 */
function xmlsitemap_file_download($file) {
  if ($file == 'xmlsitemap/gss.xsl') {
    return array('Content-Type:');
  }
}

/**
 * Get all site map links.
 * @return An array of links from hook_xmlsitemap_links().
 */
function _xmlsitemap_links() {
  static $links;
  if (!isset($links)) {
    $entries = module_invoke_all('xmlsitemap_links');
    if (!empty($entries)) {
      foreach ($entries as $key => $link) {
        $lastmod[$key] = $link['#lastmod'];
      }
      array_multisort($lastmod, $entries);
    }
    $links = $entries;
  }
  return $links;
}

/**
 * Process an array of links.
 * @param $entries: An array of links to process
 * @return A string of formatted links
 */
function _xmlsitemap_format($entries) {
  $links = array();
  foreach ($entries as $entry) {
    if (isset($entry['#loc'])) {
560 561
      $link = '  <url>'."\n";
      $link .= '    <loc>'. check_url($entry['#loc']) .'</loc>'."\n";
Darren Oh's avatar
Darren Oh committed
562
      if (isset($entry['#lastmod'])) {
563
        $link .= '    <lastmod>'. gmdate('Y-m-d\TH:i:s+00:00', $entry['#lastmod']) .'</lastmod>'."\n";
Darren Oh's avatar
Darren Oh committed
564 565
      }
      if (isset($entry['#changefreq'])) {
566
        $link .= '    <changefreq>'. _xmlsitemap_frequency($entry['#changefreq']) .'</changefreq>'."\n";
Darren Oh's avatar
Darren Oh committed
567 568
      }
      if (isset($entry['#priority']) && $entry['#priority'] <= 1 && $entry['#priority'] >= 0) {
569
        $link .= '    <priority>'. number_format($entry['#priority'], 1) .'</priority>'."\n";
Darren Oh's avatar
Darren Oh committed
570
      }
571
      $link .= '  </url>';
Darren Oh's avatar
Darren Oh committed
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
      $links[] = $link;
    }
  }
  return $links;
}

/**
 * Determine the frequency of updates to a link.
 * @param $interval: The number of seconds since last change
 * @return A string representing the update frequency according to the
 * sitemaps.org protocol
 */
function _xmlsitemap_frequency($interval) {
  $frequencies = array(
    'always' => 3600,
    'hourly' => 86400,
    'daily' => 604800,
    'weekly' => 2419200,
    'monthly' => 29030400,
    'yearly' => 100000000,
    'never' => 0,
  );
594
  $frequency = 'never';
Darren Oh's avatar
Darren Oh committed
595 596 597
  if (array_key_exists($interval, $frequencies)) {
    $frequency = $interval;
  }
598
  elseif (is_numeric($interval)) {
Darren Oh's avatar
Darren Oh committed
599
    foreach ($frequencies as $frequency => $value) {
600
      if ($interval < $value) {
Darren Oh's avatar
Darren Oh committed
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
        break;
      }
    }
  }
  return $frequency;
}

/**
 * Implementation of hook_xmlsitemap_links().
 */
function xmlsitemap_xmlsitemap_links($type = NULL, $excludes = array()) {
  $links = array();
  if (!isset($type)) {
    global $base_url;
    $links[] = array('#loc' => "$base_url/", '#changefreq' => 'always', '#priority' => variable_get('xmlsitemap_front_page_priority', 1));
    $links = array_merge($links, _xmlsitemap_additional_links());
617
    $links = array_merge($links, module_invoke_all('gsitemap'));
Darren Oh's avatar
Darren Oh committed
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
    $links = array_merge($links, _xmlsitemap_xml_links());
    if (!empty($links)) {
      foreach ($links as $key => $link) {
        $loc[$key] = $link['#loc'];
      }
      array_multisort($loc, $links);
    }
  }
  return $links;
}

/**
 * Get additional links.
 * @return An array of links. Each link is an array containing the XML
 * values for a site map URL.
 */
function _xmlsitemap_additional_links() {
  $links = array();
  $result = db_query("
    SELECT xa.*, ua.dst AS alias FROM {xmlsitemap_additional} xa
    LEFT JOIN {url_alias} ua ON xa.pid = ua.pid
  ");
  while ($link = db_fetch_object($result)) {
    $age = time() - $link->last_changed;
    if (!empty($link->previously_changed)) {
      $interval = $link->last_changed - $link->previously_changed;
    }
    else {
      $interval = 0;
    }
    $links[] = array(
      '#loc' => xmlsitemap_url($link->path, $link->alias, NULL, NULL, TRUE),
      '#lastmod' => $link->last_changed,
      '#changefreq' => max($age, $interval),
      '#priority' => isset($link->priority) ? $link->priority : variable_get('xmlsitemap_additional_links_priority', 0.1),
    );
  }
  return $links;
}

/**
 * Extract links from site maps returned by hook_xmlsitemap_links().
 * @return An array of links.
 */
function _xmlsitemap_xml_links() {
  $links = array();
  $xml = module_invoke_all('xmlsitemap_links', 'xml');
665
  $xml = array_merge($xml, module_invoke_all('gsitemap', 'xml'));
Darren Oh's avatar
Darren Oh committed
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
  foreach ($xml as $entries) {
    $start = strpos($entries, '<url>');
    if ($start !== FALSE) {
      $length = strpos($entries, '</urlset>') - $start;
      $entries = substr($entries, $start, $length);
      $entries = explode('<url>', $entries);
      foreach ($entries as $value) {
        if (($start = strpos($value, '<loc>')) !== FALSE) {
          $length = $start + strlen('<loc>');
          $link['#loc'] = substr($value, $length, strpos($value, '</loc>') - $length);
          if (($start = strpos($value, '<lastmod>')) !== FALSE) {
            $length = $start + strlen('<lastmod>');
            $t = array_shift(explode('+', substr($value, $length, strpos($value, '</lastmod>') - $length)));
            $t = explode('T', $t);
            $t = array_merge(explode('-', $t[0]), explode(':', $t[1]));
            $link['#lastmod'] = gmmktime($t[3], $t[4], $t[5], $t[1], $t[2], $t[0]);
          }
          if (($start = strpos($value, '<changefreq>')) !== FALSE) {
            $length = $start + strlen('<changefreq>');
            $link['#changefreq'] = substr($value, $length, strpos($value, '</changefreq>') - $length);
          }
          if (($start = strpos($value, '<priority>')) !== FALSE) {
            $length = $start + strlen('<priority>');
            $link['#priority'] = substr($value, $length, strpos($value, '</priority>') - $length);
          }
          $links[] = $link;
        }
      }
    }
  }
  return $links;
}

/**
 * Modified version of url(). We don't want to do a separate database query
 * for each url, so we pass the alias as an extra parameter.
 * @param $alias: The URL alias. Default is NULL.
 * @return The fully formatted URL
 */
function xmlsitemap_url($path = NULL, $alias = NULL, $query = NULL, $fragment = NULL, $absolute = FALSE) {
  if (isset($fragment)) {
    $fragment = "#$fragment";
  }
  $colonpos = strpos($path, ':');
  if ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && filter_xss_bad_protocol($path, FALSE) == check_plain($path)) {
    if (strpos($path, '#') !== FALSE) {
      list($path, $old_fragment) = explode('#', $path, 2);
      if (isset($old_fragment) && !isset($fragment)) {
        $fragment = "#$old_fragment";
      }
    }
    if (isset($query)) {
      $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . $query;
    }
    return $path . $fragment;
  }
  global $base_url;
  static $script;
  static $clean_url;
  $script = isset($script) ? $script : strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') === FALSE ? 'index.php' : '';
  $clean_url = isset($clean_url) ? $clean_url : variable_get('clean_url', FALSE);
Darren Oh's avatar
Darren Oh committed
727
  $base = ($absolute ? $base_url .'/' : base_path());
728

Darren Oh's avatar
Darren Oh committed
729 730 731
  if (!empty($path) && $path != '<front>') {
    $path = _xmlsitemap_get_path_alias($path, $alias);
    $path = drupal_urlencode($path);
732

Darren Oh's avatar
Darren Oh committed
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
    if (!$clean_url) {
      if (isset($query)) {
        return $base . $script .'?q='. $path .'&'. $query . $fragment;
      }
      else {
        return $base . $script .'?q='. $path . $fragment;
      }
    }
    else {
      if (isset($query)) {
        return $base . $path .'?'. $query . $fragment;
      }
      else {
        return $base . $path . $fragment;
      }
    }
  }
  else {
    if (isset($query)) {
      return $base . $script .'?'. $query . $fragment;
    }
    else {
      return $base . $fragment;
    }
  }
}

/**
 * Modified version of drupal_get_path_alias() for xmlsitemap_url().
 * @param $path: An internal Drupal path
 * @param $alias: The URL alias. Default is NULL.
 * @return A processed path
 */
function _xmlsitemap_get_path_alias($path, $alias = NULL) {
  $result = $path;
  if (!empty($alias)) {
    $result = $alias;
  }
771
  if (function_exists('custom_url_rewrite_outbound')) {
772
    custom_url_rewrite_outbound($result, $customarray = array('alias' => $alias), $path);
Darren Oh's avatar
Darren Oh committed
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
  }
  return $result;
}

/**
 * Implementation of hook_cron().
 */
function xmlsitemap_cron() {
  if (variable_get('xmlsitemap_cron_submit', FALSE) && variable_get('xmlsitemap_changed', FALSE)) {
    _xmlsitemap_ping();
  }
}

/**
 * Mark the site map as changed and the cache as needing update.
788
 * @return None
Darren Oh's avatar
Darren Oh committed
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
 */
function xmlsitemap_update_sitemap() {
  variable_set('xmlsitemap_changed', TRUE);
  variable_set('xmlsitemap_update', TRUE);
  if (variable_get('xmlsitemap_submit', FALSE)) {
    _xmlsitemap_submit_on_exit();
  }
}

/**
 * Schedule a call to _xmlsitemap_ping() to be run on exit. Use this
 * function instead of _xmlsitemap_ping() to avoid a delay in outputting
 * the page to the user.
 * @return TRUE if the function has been called previously, FALSE otherwise.
 */
function _xmlsitemap_submit_on_exit() {
  static $called = FALSE;
  $return = $called;
  $called = TRUE;
  return $return;
}

/**
 * Implementation of hook_exit().
 */
function xmlsitemap_exit() {
  if (_xmlsitemap_submit_on_exit()) {
    _xmlsitemap_ping();
  }
}

/**
 * Submit the site map to search engines.
822
 * @return None
Darren Oh's avatar
Darren Oh committed
823 824 825 826 827 828 829 830 831
 */
function _xmlsitemap_ping() {
  $status = _xmlsitemap_update_cache();
  if ($status) {
    module_invoke_all('xmlsitemap_engines', 'ping');
    variable_set('xmlsitemap_changed', FALSE);
  }
}