SimplesitemapController.php 2.12 KB
Newer Older
Pawel G's avatar
Pawel G 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
<?php
/**
 * @file
 * Contains \Drupal\simplesitemap\Controller\SimplesitemapController.
 */

namespace Drupal\simplesitemap\Controller;

use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Url;

/**
 * SimplesitemapController.
 */
class SimplesitemapController {

  /**
   * Generates an example page.
   */
  public function generate_sitemap() {

    $config = \Drupal::config('simplesitemap.settings');

    $output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
    <urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";

    global $base_url;

    $home = $config->get('home');
Pawel G's avatar
Pawel G committed
30
    if ($home['index'])
Pawel G's avatar
Pawel G committed
31 32 33 34
      $output .= "<url><loc>" . $base_url . "</loc><priority>" . $home['priority'] .  "</priority></url>";

    $custom = $config->get('custom');
    foreach($custom as $page) {
Pawel G's avatar
Pawel G committed
35
      if ($page['index'])
Pawel G's avatar
Pawel G committed
36 37
        $output .= "<url><loc>" . $base_url . '/' . $page['path'] . "</loc><priority>" . $page['priority'] . "</priority></url>";
    }
Pawel G's avatar
Pawel G committed
38

39
    $content_types = $config->get('content_types');
Pawel G's avatar
Pawel G committed
40
    if (count($content_types) > 0) {
Pawel G's avatar
Pawel G committed
41

Pawel G's avatar
Pawel G committed
42 43 44 45 46 47 48 49 50 51
      //todo: D8 entityQuery doesn't seem to take multiple OR conditions, that's why that ugly db_select.
  /*    $query = \Drupal::entityQuery('node')
        ->condition('status', 1)
        ->condition('type', array_keys($content_types));
      $nids = $query->execute();*/
      $query = db_select('node_field_data', 'n')
        ->fields('n', array('nid', 'type'))
        ->condition('status', 1);
      $db_or = db_or();
      foreach($content_types as $machine_name => $options) {
52 53
        if ($options['index'])
          $db_or->condition('type', $machine_name);
Pawel G's avatar
Pawel G committed
54 55 56
      }
      $query->condition($db_or);
      $nids = $query->execute()->fetchAllAssoc('nid');
Pawel G's avatar
Pawel G committed
57

Pawel G's avatar
Pawel G committed
58 59 60 61
      foreach($nids as $nid => $node) {
        $link_url = Url::fromRoute('entity.node.canonical', array('node' => $nid), array('absolute' => TRUE));
        $output .= "<url><loc>" . $link_url->toString() . "</loc><priority>" . $content_types[$node->type]['priority'] .  "</priority></url>";
      }
Pawel G's avatar
Pawel G committed
62 63 64 65 66 67 68
    }

    $output .= "</urlset>";

    return new Response($output, Response::HTTP_OK, array('content-type' => 'application/xml'));
  }
}