You are here

class GISController in Google Image Sitemap 8

Same name and namespace in other branches
  1. 2.0.x src/Controller/GISController.php \Drupal\google_image_sitemap\Controller\GISController
  2. 1.0.x src/Controller/GISController.php \Drupal\google_image_sitemap\Controller\GISController

Default controller for the google_image_sitemap module.

Hierarchy

Expanded class hierarchy of GISController

File

src/Controller/GISController.php, line 16

Namespace

Drupal\google_image_sitemap\Controller
View source
class GISController extends ControllerBase {
  const GOOGLE_IMAGE_SITEMAP_ADMIN_PATH = '/admin/config/search/google_image_sitemap';
  protected $db;

  /**
   * {@inheritdoc}
   */
  public function __construct(Connection $database) {
    $this->db = $database;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('database'));
  }

  /**
   * Function to get available image sitemap.
   */
  public function getList() {
    $output = '';
    $header = [
      $this
        ->t('S.NO.'),
      $this
        ->t('SITEMAP URL'),
      $this
        ->t('CONTENT TYPE'),
      $this
        ->t('LAST UPDATED'),
      $this
        ->t('Edit'),
      $this
        ->t('Sitemap'),
    ];
    $query = $this->db
      ->select('google_image_sitemap', 'g')
      ->fields('g');
    $result = $query
      ->execute();
    $counter = 0;
    $rows = [];
    while ($gis_obj = $result
      ->fetchObject()) {
      $is_exist = file_exists(\Drupal::service('file_system')
        ->realpath(file_default_scheme() . "://") . '/google_image_sitemap/sitemap_' . $gis_obj->node_type . '.xml');
      $build_url = 'admin/config/search/google_image_sitemap/' . $gis_obj->sid . '/build';
      $generate_text = $this
        ->t('Generate Sitemap');
      if ($is_exist) {
        $access_url = 'sites/default/files/google_image_sitemap/sitemap_' . $gis_obj->node_type . '.xml';
        $url = Url::fromUri('internal:/' . $access_url);
        $link_options = [
          'attributes' => [
            'title' => $this
              ->t('Open sitemap'),
          ],
        ];
        $url
          ->setOptions($link_options);
        $generate_text = $this
          ->t('Re Generate Sitemap');
      }
      $build_link = Link::fromTextAndUrl($generate_text, url::fromUri('internal:/' . $build_url));
      $edit = 'admin/config/search/google_image_sitemap/' . $gis_obj->sid . '/edit';

      // Rows of table.
      $rows[] = [
        ++$counter,
        $build_link,
        $gis_obj->node_type,
        empty($gis_obj->last_updated) ? '-' : date('d-M-Y ', $gis_obj->last_updated),
        Link::fromTextAndUrl($this
          ->t('Edit'), Url::fromUri('internal:/' . $edit))
          ->toString(),
        $is_exist ? Link::fromTextAndUrl($this
          ->t('Url'), $url)
          ->toString() : $this
          ->t('Url'),
      ];
    }
    $output = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#caption' => Link::fromTextAndUrl($this
        ->t('Add a new sitemap'), Url::fromUserInput(static::GOOGLE_IMAGE_SITEMAP_ADMIN_PATH . '/add')),
      '#empty' => $this
        ->t('No sitemap available.'),
    ];
    return $output;
  }

  /**
   * Function to generate image sitemap.
   */
  public function googleImageSitemapBuild($sitemap_id) {
    $query = $this->db
      ->select('google_image_sitemap', 'g')
      ->fields('g')
      ->condition('sid', $sitemap_id);
    $result = $query
      ->execute()
      ->fetchObject();
    $filename = 'google_image_sitemap.xml';
    if (!empty($result)) {
      $query = $this->db
        ->select('node_field_data', 'nfd');
      $query
        ->fields('nfd', [
        'nid',
        'title',
      ]);
      $query
        ->fields('f', [
        'uri',
      ]);
      $query
        ->innerJoin('file_usage', 'fu', "nfd.nid = fu.id");
      $query
        ->innerJoin('file_managed', 'f', "fu.fid = f.fid");
      $query
        ->condition('f.filemime', [
        'image/png',
        'image/jpg',
        'image/gif',
        'image/jpeg',
      ], 'IN');
      if ($result->node_type != 'all') {
        $query
          ->condition('nfd.type', $result->node_type);
        $filename = 'google_image_sitemap_' . $result->node_type . '.xml';
      }
      $query
        ->orderBy('nfd.nid', 'DESC');
      $nodes = $query
        ->execute()
        ->fetchAll();
      if (!empty($nodes)) {
        $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 ($nodes as $node) {
          $output .= '<url><loc>' . Url::fromUri('internal:/node/' . $node->nid, [
            'absolute' => TRUE,
          ])
            ->toString() . '</loc>
                     <image:image>
                       <image:loc>' . file_create_url($node->uri) . '</image:loc>
                       <image:title>' . $node->title . '</image:title>
                       <image:caption>' . $node->title . '</image:caption>
                       <image:license>' . $result->license . '</image:license>
                     </image:image></url>';
        }
        $output .= '</urlset>';

        // File build path.
        $path = \Drupal::service('file_system')
          ->realpath(file_default_scheme() . "://") . '/google_image_sitemap';
        if (!is_dir($path)) {
          \Drupal::service('file_system')
            ->mkdir($path);
        }
        if ($file = file_unmanaged_save_data($output, $path . '/' . $filename, FILE_EXISTS_REPLACE)) {
          $this->db
            ->update('google_image_sitemap')
            ->fields([
            'last_updated' => \Drupal::time()
              ->getRequestTime(),
          ])
            ->condition('sid', $sitemap_id, '=')
            ->execute();
          drupal_set_message($this
            ->t("Sitemap created successfully!"));
        }
      }
      else {
        drupal_set_message($this
          ->t("No Images found!"));
      }
      global $base_url;
      $redirect = new RedirectResponse($base_url . '/' . GISController::GOOGLE_IMAGE_SITEMAP_ADMIN_PATH);
      $redirect
        ->send();
    }
  }

  /**
   * Function to edit image sitemap.
   */
  public function editSitemap($sitemap_id) {
    $query = $this->db
      ->select('google_image_sitemap', 'g')
      ->fields('g', [
      'sid',
      'node_type',
      'license',
    ])
      ->condition('sid', $sitemap_id, '=');
    $result = $query
      ->execute()
      ->fetchObject();
    if (!empty($result)) {
      $form = \Drupal::formBuilder()
        ->getForm('Drupal\\google_image_sitemap\\Form\\GoogleImageSitemapCreateForm', $result);
      return $form;
    }
    else {
      throw new NotFoundHttpException();
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
GISController::$db protected property
GISController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
GISController::editSitemap public function Function to edit image sitemap.
GISController::getList public function Function to get available image sitemap.
GISController::googleImageSitemapBuild public function Function to generate image sitemap.
GISController::GOOGLE_IMAGE_SITEMAP_ADMIN_PATH constant
GISController::__construct public function
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.