You are here

function _media_sitemap_generate in Media Sitemap 7

Custom function for generating the sitemap.

1 string reference to '_media_sitemap_generate'
_media_sitemap_generate_sitemap in ./media_sitemap.module
Creating batch for generating the sitemap.

File

./media_sitemap.module, line 68
This module is used for creating XML sitemap of Image/Video for Google.

Code

function _media_sitemap_generate(&$context) {
  $query = db_select('file_usage', 'fu');
  $query
    ->fields('fu', array(
    'id',
  ));
  $query
    ->join('node', 'n', 'n.nid = fu.id');
  $nids = $query
    ->distinct()
    ->execute()
    ->fetchAll();
  $output = '';
  $total_urls = 0;
  if (count($nids) > 0) {
    $output = '<?xml version="1.0" encoding="UTF-8"?>';
    $output .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
    xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">';
    foreach ($nids as $nid) {

      // fetch list of media files for each nid.
      $query = db_select('file_managed', 'fm');
      $query
        ->fields('fm', array(
        'fid',
        'filename',
        'uri',
      ));
      $query
        ->join('file_usage', 'fu', 'fu.fid = fm.fid');
      $query
        ->condition('fu.id', $nid->id);
      $query
        ->condition('fm.type', 'image');
      $files = $query
        ->execute()
        ->fetchAll();
      if (count($files) > 0) {
        $output .= '<url><loc>' . url('node/' . $nid->id, array(
          'absolute' => TRUE,
        )) . '</loc>';
        foreach ($files as $file) {
          $media_title = _media_sitemap_get_title($file->fid);
          if (!isset($media_title)) {
            $media_title = _media_sitemap_format_title($file->filename);
          }
          $output .= '<image:image><image:loc>' . file_create_url($file->uri) . '</image:loc><image:title>' . $media_title . '</image:title><image:caption>' . check_plain($media_title) . '</image:caption></image:image>';
        }
        $output .= '</url>';
        $total_urls++;
      }
    }
    $output .= '</urlset>';

    // File build path.
    $path = variable_get('file_public_path', 'sites/default/files') . '/media_sitemap';
    if (!is_dir($path)) {
      drupal_mkdir($path);
    }
  }
  $time = time();
  $filename = 'image_sitemap.xml';
  if ($file = file_unmanaged_save_data($output, $path . '/' . $filename, FILE_EXISTS_REPLACE)) {
    variable_set('image_sitemap_created', $time);
    variable_set('image_sitemap_number_of_urls', $total_urls);
  }
}