SimplesitemapCustomLinksForm.php 6.76 KB
Newer Older
1 2
<?php

gbyte.co's avatar
gbyte.co committed
3
namespace Drupal\simple_sitemap\Form;
4 5 6 7

use Drupal\Core\Form\FormStateInterface;

/**
gbyte.co's avatar
gbyte.co committed
8
 * Class SimplesitemapCustomLinksForm
gbyte.co's avatar
gbyte.co committed
9
 * @package Drupal\simple_sitemap\Form
10
 */
gbyte.co's avatar
gbyte.co committed
11
class SimplesitemapCustomLinksForm extends SimplesitemapFormBase {
12 13 14 15

  /**
   * {@inheritdoc}
   */
gbyte.co's avatar
gbyte.co committed
16
  public function getFormId() {
gbyte.co's avatar
gbyte.co committed
17
    return 'simple_sitemap_custom_links_form';
18 19 20 21 22 23 24
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

gbyte.co's avatar
gbyte.co committed
25
    $form['simple_sitemap_custom'] = [
26
      '#title' => $this->t('Custom links'),
27
      '#type' => 'fieldset',
28
      '#markup' => '<p>' . $this->t('Add custom internal drupal paths to the XML sitemap.') . '</p>',
29
      '#prefix' => $this->getDonationText(),
gbyte.co's avatar
gbyte.co committed
30
    ];
31

gbyte.co's avatar
gbyte.co committed
32
    $form['simple_sitemap_custom']['custom_links'] = [
33
      '#type' => 'textarea',
34
      '#title' => $this->t('Relative Drupal paths'),
35
      '#default_value' => $this->customLinksToString($this->generator->getCustomLinks(FALSE)),
gbyte.co's avatar
gbyte.co committed
36
      '#description' => $this->t("Please specify drupal internal (relative) paths, one per line. Do not forget to prepend the paths with a '/'.<br/>Optionally link priority <em>(0.0 - 1.0)</em> can be added by appending it after a space.<br/> Optionally link change frequency <em>(always / hourly / daily / weekly / monthly / yearly / never)</em> can be added by appending it after a space.<br/><br/><strong>Examples:</strong><br/><em>/ 1.0 daily</em> -> home page with the highest priority and daily change frequency<br/><em>/contact</em> -> contact page with the default priority and no change frequency information"),
gbyte.co's avatar
gbyte.co committed
37
    ];
38

39 40 41 42 43 44 45 46
    $form['simple_sitemap_custom']['include_images'] = [
      '#type' => 'select',
      '#title' => $this->t('Include images'),
      '#description' => $this->t('If a custom link points to an entity, include its referenced images in the sitemap.'),
      '#default_value' => $this->generator->getSetting('custom_links_include_images', 0),
      '#options' => [0 => $this->t('No'), 1 => $this->t('Yes')],
    ];

47
    $this->formHelper->displayRegenerateNow($form['simple_sitemap_custom']);
48

49 50 51 52 53 54 55
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
gbyte.co's avatar
gbyte.co committed
56
    foreach ($this->stringToCustomLinks($form_state->getValue('custom_links')) as $i => $link_config) {
57 58 59 60 61 62 63
      $placeholders = [
        '@line' => ++$i,
        '@path' => $link_config['path'],
        '@priority' => isset($link_config['priority']) ? $link_config['priority'] : '',
        '@changefreq' => isset($link_config['changefreq']) ? $link_config['changefreq'] : '',
        '@changefreq_options' => implode(', ', FormHelper::getChangefreqOptions()),
      ];
64

65
      // Checking if internal path exists.
66
      if (!$this->pathValidator->isValid($link_config['path'])
gbyte.co's avatar
gbyte.co committed
67
//      if (!$this->pathValidator->getUrlIfValidWithoutAccessCheck($link_config['path']) //todo
gbyte.co's avatar
gbyte.co committed
68 69
      // Path validator does not see a double slash as an error. Catching this to prevent breaking path generation.
       || strpos($link_config['path'], '//') !== FALSE) {
gbyte.co's avatar
gbyte.co committed
70
        $form_state->setErrorByName('', $this->t('<strong>Line @line</strong>: The path <em>@path</em> does not exist.', $placeholders));
71
      }
72 73

      // Making sure the paths start with a slash.
gbyte.co's avatar
gbyte.co committed
74
      if ($link_config['path'][0] !== '/') {
gbyte.co's avatar
gbyte.co committed
75
        $form_state->setErrorByName('', $this->t("<strong>Line @line</strong>: The path <em>@path</em> needs to start with a '/'.", $placeholders));
76
      }
77 78

      // Making sure the priority is formatted correctly.
79
      if (isset($link_config['priority']) && !FormHelper::isValidPriority($link_config['priority'])) {
gbyte.co's avatar
gbyte.co committed
80
        $form_state->setErrorByName('', $this->t('<strong>Line @line</strong>: The priority setting <em>@priority</em> for path <em>@path</em> is incorrect. Set the priority from 0.0 to 1.0.', $placeholders));
81
      }
82 83 84

      // Making sure changefreq is formatted correctly.
      if (isset($link_config['changefreq']) && !FormHelper::isValidChangefreq($link_config['changefreq'])) {
gbyte.co's avatar
gbyte.co committed
85
        $form_state->setErrorByName('', $this->t('<strong>Line @line</strong>: The changefreq setting <em>@changefreq</em> for path <em>@path</em> is incorrect. The following are the correct values: <em>@changefreq_options</em>.', $placeholders));
86
      }
87 88 89 90 91 92 93
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
gbyte.co's avatar
gbyte.co committed
94
    $custom_links = $this->stringToCustomLinks($form_state->getValue('custom_links'));
95
    $this->generator->removeCustomLinks();
96
    foreach ($custom_links as $link_config) {
97
      $this->generator->addCustomLink($link_config['path'], $link_config);
98
    }
99
    $this->generator->saveSetting('custom_links_include_images', $form_state->getValue('include_images'));
100 101
    parent::submitForm($form, $form_state);

102
    // Regenerate sitemaps according to user setting.
gbyte.co's avatar
gbyte.co committed
103
    if ($form_state->getValue('simple_sitemap_regenerate_now')) {
104
      $this->generator->generateSitemap();
105
    }
106
  }
107

gbyte.co's avatar
gbyte.co committed
108 109 110 111
  /**
   * @param $custom_links_string
   * @return array
   */
gbyte.co's avatar
gbyte.co committed
112 113
  protected function stringToCustomLinks($custom_links_string) {

114 115
    // Unify newline characters and explode into array.
    $custom_links_string_lines = explode("\n", str_replace("\r\n", "\n", $custom_links_string));
gbyte.co's avatar
gbyte.co committed
116

117
    // Remove empty values and whitespaces from array.
118
    $custom_links_string_lines = array_filter(array_map('trim', $custom_links_string_lines));
gbyte.co's avatar
gbyte.co committed
119

120
    $custom_links = [];
gbyte.co's avatar
gbyte.co committed
121
    foreach ($custom_links_string_lines as $i => &$line) {
122
      $link_settings = explode(' ', $line);
123
      $custom_links[$i]['path'] = $link_settings[0];
124 125 126 127

      // If two arguments are provided for a link, assume the first to be
      // priority, the second to be changefreq.
      if (!empty($link_settings[1]) && !empty($link_settings[2])) {
128
        $custom_links[$i]['priority'] = $link_settings[1];
129 130 131 132 133 134 135 136 137 138 139 140 141
        $custom_links[$i]['changefreq'] = $link_settings[2];
      }
      else {
        // If one argument is provided for a link, guess if it is priority or
        // changefreq.
        if (!empty($link_settings[1])) {
          if (is_numeric($link_settings[1])) {
            $custom_links[$i]['priority'] = $link_settings[1];
          }
          else {
            $custom_links[$i]['changefreq'] = $link_settings[1];
          }
        }
142 143
      }
    }
144
    return $custom_links;
145
  }
gbyte.co's avatar
gbyte.co committed
146 147 148 149 150 151 152 153

  /**
   * @param array $links
   * @return string
   */
  protected function customLinksToString(array $links) {
    $setting_string = '';
    foreach ($links as $custom_link) {
154
      $setting_string .= $custom_link['path'];
gbyte.co's avatar
gbyte.co committed
155
      $setting_string .= isset($custom_link['priority'])
156 157 158 159 160
        ? ' ' . $this->formHelper->formatPriority($custom_link['priority'])
        : '';
      $setting_string .= isset($custom_link['changefreq'])
        ? ' ' . $custom_link['changefreq']
        : '';
gbyte.co's avatar
gbyte.co committed
161 162 163 164
      $setting_string .= "\r\n";
    }
    return $setting_string;
  }
165
}