You are here

public function MediaSitemapGenerator::process in Media Sitemap 8

File

src/MediaSitemapGenerator.php, line 67
Contains \Drupal\media_sitemap\MediaSitemapGenerator.

Class

MediaSitemapGenerator
Class MediaSitemapGenerator.

Namespace

Drupal\media_sitemap

Code

public function process() {
  $query = $this->database
    ->select('file_usage', 'fu');
  $query
    ->fields('fu', array(
    'id',
  ));
  $query
    ->join('node', 'n', 'n.nid = fu.id');
  $nids = $query
    ->distinct()
    ->execute()
    ->fetchAll();
  $output = '';
  $path = '';
  $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 = \Drupal::database()
        ->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.filemime', 'image/%', 'LIKE');
      $files = $query
        ->execute()
        ->fetchAll();
      if (count($files) > 0) {
        $output .= '<url><loc>' . Url::fromRoute('entity.node.canonical', array(
          'node' => $nid->id,
        ), array(
          'absolute' => TRUE,
        ))
          ->toString() . '</loc>';
        foreach ($files as $file) {
          $output .= '<image:image><image:loc>' . file_create_url($file->uri) . '</image:loc><image:title>' . $file->filename . '</image:title></image:image>';
        }
        $output .= '</url>';
        $total_urls++;
      }
    }
    $output .= '</urlset>';

    // File build path.
    $path = file_create_url($this->fileSystem
      ->realpath($this->configFactory
      ->get('system.file')
      ->get('default_scheme') . "://media_sitemap"));
    if (!is_dir($path)) {
      \Drupal::service('file_system')
        ->mkdir($path);
    }
  }
  $time = time();
  $filename = 'image_sitemap.xml';
  if ($file = $this->fileSystem
    ->saveData($output, $path . '/' . $filename, FileSystemInterface::EXISTS_REPLACE)) {
    $this->configFactory
      ->getEditable('media_sitemap.settings')
      ->set('image_sitemap_created', $time)
      ->set('image_sitemap_number_of_urls', $total_urls)
      ->save();
  }
}