simple_sitemap.module 8.03 KB
Newer Older
gbyte.co's avatar
gbyte.co committed
1
<?php
gbyte.co's avatar
gbyte.co committed
2

3 4 5 6
/**
 * @file
 * Main module file containing hooks.
 */
gbyte.co's avatar
gbyte.co committed
7

8
use Drupal\Core\Form\FormStateInterface;
gbyte.co's avatar
gbyte.co committed
9 10
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;
11
use Drupal\system\MenuInterface;
12
use Drupal\language\ConfigurableLanguageInterface;
13

14
/**
15
 *Implements hook_help().
gbyte.co's avatar
gbyte.co committed
16 17 18 19
 *
 * @param $route_name
 * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
 * @return \Drupal\Component\Render\MarkupInterface|null
20
 */
gbyte.co's avatar
gbyte.co committed
21
function simple_sitemap_help($route_name, RouteMatchInterface $route_match) {
22
  return $route_name === 'help.page.simple_sitemap' ?
23
    check_markup(file_get_contents(dirname(__FILE__) . "/README.md")) : NULL;
24 25
}

26
/**
27
 * Implements hook_form_alter().
28 29
 *
 * Adds sitemap settings to entity types that are supported via plugins.
gbyte.co's avatar
gbyte.co committed
30 31 32 33
 *
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
34
 */
gbyte.co's avatar
gbyte.co committed
35
function simple_sitemap_form_alter(&$form, FormStateInterface $form_state, $form_id) {
36

37
  /** @var Drupal\simple_sitemap\Form\FormHelper $f */
gbyte.co's avatar
gbyte.co committed
38 39
  $f = \Drupal::service('simple_sitemap.form_helper');
  if (!$f->processForm($form_state)) {
40
    return;
gbyte.co's avatar
gbyte.co committed
41
  }
gbyte.co's avatar
gbyte.co committed
42 43 44 45 46

  $form['simple_sitemap'] = [
    '#type' => 'details',
    '#group' => isset($form['additional_settings']) ? 'additional_settings' : 'advanced',
    '#title' => t('Simple XML sitemap'),
gbyte.co's avatar
gbyte.co committed
47
    '#description' => $f->getEntityCategory() === 'instance' ? t('Settings for this entity can be overridden here.') : '',
48
    '#weight' => 10,
gbyte.co's avatar
gbyte.co committed
49
  ];
50

gbyte.co's avatar
gbyte.co committed
51
  // Attach some js magic to forms.
gbyte.co's avatar
gbyte.co committed
52
  // todo: JS not working on comment entity form, hence disabling.
gbyte.co's avatar
gbyte.co committed
53
  if ($f->getEntityTypeId() !== 'comment' || $f->getEntityCategory() !== 'instance') {
gbyte.co's avatar
gbyte.co committed
54
    $form['#attached']['library'][] = 'simple_sitemap/form';
gbyte.co's avatar
gbyte.co committed
55
  }
56

gbyte.co's avatar
gbyte.co committed
57 58 59
  // Only attach fieldset summary js to 'additional settings' vertical tabs.
  if (isset($form['additional_settings'])) {
    $form['#attached']['library'][] = 'simple_sitemap/fieldsetSummaries';
60
  }
61

62
  $f->displayEntitySettings($form['simple_sitemap'])
gbyte.co's avatar
gbyte.co committed
63 64
  // todo: do not show setting when creating new bundle.
    ->displayRegenerateNow($form['simple_sitemap']);
65

66
  // Add submission handler.
67
  if (isset($form['actions']['submit']['#submit'])) {
68
    foreach (array_keys($form['actions']) as $action) {
gbyte.co's avatar
gbyte.co committed
69
      if ($action !== 'preview'
70 71
        && isset($form['actions'][$action]['#type'])
        && $form['actions'][$action]['#type'] === 'submit') {
72 73 74
        $form['actions'][$action]['#submit'][] = 'simple_sitemap_entity_form_submit';
      }
    }
75
  }
gbyte.co's avatar
gbyte.co committed
76 77
  // Fix for account page rendering other submit handlers not usable.
  else {
gbyte.co's avatar
gbyte.co committed
78
    $form['#submit'][] = 'simple_sitemap_entity_form_submit';
79
  }
gbyte.co's avatar
gbyte.co committed
80 81
}

82
/**
83
 * Form submission handler called in hook_form_alter.
gbyte.co's avatar
gbyte.co committed
84 85 86
 *
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
87
 */
gbyte.co's avatar
gbyte.co committed
88
function simple_sitemap_entity_form_submit($form, FormStateInterface &$form_state) {
89

90
  /** @var Drupal\simple_sitemap\Form\FormHelper $f */
gbyte.co's avatar
gbyte.co committed
91 92 93 94
  $f = \Drupal::service('simple_sitemap.form_helper');
  if (!$f->processForm($form_state)) {
    return;
  }
95

96 97 98 99
  $values = $form_state->getValues();

  // Fix for values appearing in a sub array on a commerce product entity.
  $values = isset($values['simple_sitemap']) ? $values['simple_sitemap'] : $values;
100

101
  // Only make changes in DB if sitemap settings actually changed.
102
  if ($f->valuesChanged($form, $values)) {
103

104
    /** @var \Drupal\simple_sitemap\Simplesitemap $generator */
105
    $generator = \Drupal::service('simple_sitemap.generator');
106

107
    $settings = [
108
      'index' => (bool) $values['simple_sitemap_index_content'],
109 110
      'priority' => $values['simple_sitemap_priority'],
      'changefreq' => $values['simple_sitemap_changefreq'],
111
      'include_images' => (bool) $values['simple_sitemap_include_images'],
112 113
    ];

114
    switch ($f->getEntityCategory()) {
115 116

      case 'bundle':
117 118 119
        $generator->setBundleSettings(
          $f->getEntityTypeId(),
          !empty($f->getBundleName()) ? $f->getBundleName() : $f->getFormEntityId(),
120
          $settings
121
        );
122 123
        break;

124
      case 'instance':
125 126 127
        $generator->setEntityInstanceSettings(
          $f->getEntityTypeId(),
          !empty($f->getInstanceId()) ? $f->getInstanceId() : $f->getFormEntityId(),
128
          $settings
129
        );
130
        break;
131
    }
132 133 134

    // Regenerate sitemaps according to user setting.
    if ($values['simple_sitemap_regenerate_now']) {
gbyte.co's avatar
gbyte.co committed
135
      $generator->rebuildQueue()->generateSitemap();
136
    }
137 138 139 140
  }
}

/**
141
 * Implements hook_cron().
142
 */
gbyte.co's avatar
gbyte.co committed
143
function simple_sitemap_cron() {
144

145
  /** @var \Drupal\simple_sitemap\Simplesitemap $generator */
146
  $generator = \Drupal::service('simple_sitemap.generator');
147

148
  if ($generator->getSetting('cron_generate')) {
149
    $interval = (int) $generator->getSetting('cron_generate_interval', 0) * 60 * 60;
150 151 152 153 154 155 156 157 158 159 160 161
    $request_time = \Drupal::service('datetime.time')->getRequestTime();
    $generation_in_progress = $generator->getQueueWorker()->generationInProgress();
    $state = \Drupal::state();

    if ($interval === 0
      || $generation_in_progress
      || (($state->get('simple_sitemap.last_cron_generate', 0) + $interval) <= $request_time)) {

      if (!$generation_in_progress) {
        $state->set('simple_sitemap.last_cron_generate', $request_time);
      }

162
      $generator->generateSitemap('cron');
163
    }
164
  }
gbyte.co's avatar
gbyte.co committed
165
}
166

167 168 169 170 171 172 173
/**
 * Implements hook_ENTITY_TYPE_delete().
 *
 * When a language is removed from the system remove it also from settings.
 */
function simple_sitemap_configurable_language_delete(ConfigurableLanguageInterface $language) {

174
  /** @var \Drupal\simple_sitemap\Simplesitemap $generator */
175
  $generator = \Drupal::service('simple_sitemap.generator');
gbyte.co's avatar
gbyte.co committed
176

177 178 179 180 181 182 183
  $excluded_languages = $generator->getSetting('excluded_languages');
  if (isset($excluded_languages[$language->id()])) {
    unset($excluded_languages[$language->id()]);
    $generator->saveSetting('excluded_languages', $excluded_languages);
  }
}

184 185 186 187
/**
 * Implements hook_entity_delete().
 *
 * Removes settings of the removed entity.
188 189
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
190
 */
gbyte.co's avatar
gbyte.co committed
191
function simple_sitemap_entity_delete(EntityInterface $entity) {
192

193
  /** @var \Drupal\simple_sitemap\Simplesitemap $generator */
194 195 196 197
  $generator = \Drupal::service('simple_sitemap.generator');
  $generator->removeEntityInstanceSettings(
    $entity->getEntityTypeId(), $entity->id()
  );
198
}
199 200 201 202 203

/**
 * Implements hook_entity_bundle_delete().
 *
 * Removes settings of the removed bundle.
gbyte.co's avatar
gbyte.co committed
204 205 206
 *
 * @param string $entity_type_id
 * @param string $bundle
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
 */
function simple_sitemap_entity_bundle_delete($entity_type_id, $bundle) {
  simple_sitemap_delete_bundle_config($entity_type_id, $bundle);
}

/**
 * Implements hook_menu_delete().
 *
 * Removes settings for the removed menu.
 *
 * @param \Drupal\system\MenuInterface $menu
 */
function simple_sitemap_menu_delete(MenuInterface $menu) {
  simple_sitemap_delete_bundle_config('menu_link_content', $menu->id());
}

/**
 * Helper function used by simple_sitemap_entity_bundle_delete() and
 * simple_sitemap_menu_delete() hooks. This is needed, as menus are technically
 * not bundles.
 *
 * @param string $entity_type_id
 * @param string $bundle
 */
function simple_sitemap_delete_bundle_config($entity_type_id, $bundle) {
232

233
  /** @var \Drupal\simple_sitemap\Simplesitemap $generator */
234 235
  $generator = \Drupal::service('simple_sitemap.generator');

gbyte.co's avatar
gbyte.co committed
236
  if (!empty($deleted_bundle_settings = $generator->getBundleSettings($entity_type_id, $bundle))) {
237 238
    \Drupal::service('config.factory')->getEditable("simple_sitemap.bundle_settings.$entity_type_id.$bundle")->delete();

gbyte.co's avatar
gbyte.co committed
239 240 241 242 243 244
    if (!empty($deleted_bundle_settings['index'])) {
      $message = 'You may want to <a href="@url">regenerate</a> your XML sitemaps now.';
      if ($generator->getSetting('cron_generate')) {
        $message .= ' Otherwise the sitemaps will be regenerated during a future cron run.';
      }
      \Drupal::messenger()->addMessage(t($message, ['@url' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap']));
245 246 247
    }
  }
}
248 249 250

/**
 * Implements hook_robotstxt().
251 252 253
 *
 * @todo Use sitemap base URL setting?
 * @todo include non-default sitemaps as well?
254 255 256
 */
function simple_sitemap_robotstxt() {
  return [
257 258
    '# XML sitemaps',
    'Sitemap: ' . $GLOBALS['base_url'] . '/sitemap.xml',
259 260
  ];
}
261