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

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

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

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

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

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

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

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

gbyte's avatar
gbyte 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

gbyte's avatar
gbyte committed
62
  $f->displayEntitySettings($form['simple_sitemap'])
gbyte's avatar
gbyte 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) {
69 70 71
      if ($action != 'preview'
        && isset($form['actions'][$action]['#type'])
        && $form['actions'][$action]['#type'] === 'submit') {
72 73 74
        $form['actions'][$action]['#submit'][] = 'simple_sitemap_entity_form_submit';
      }
    }
75
  }
gbyte's avatar
gbyte committed
76 77
  // Fix for account page rendering other submit handlers not usable.
  else {
gbyte's avatar
gbyte committed
78
    $form['#submit'][] = 'simple_sitemap_entity_form_submit';
79
  }
gbyte's avatar
gbyte committed
80 81
}

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

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

98 99 100 101
  $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;
102

103
  // Only make changes in DB if sitemap settings actually changed.
104
  if ($f->valuesChanged($form, $values)) {
105 106 107 108

    /**
     * @var \Drupal\simple_sitemap\Simplesitemap $generator
     */
gbyte's avatar
gbyte committed
109
    $generator = \Drupal::service('simple_sitemap.generator');
110

111 112 113 114
    $settings = [
      'index' => $values['simple_sitemap_index_content'],
      'priority' => $values['simple_sitemap_priority'],
      'changefreq' => $values['simple_sitemap_changefreq'],
115
      'include_images' => $values['simple_sitemap_include_images'],
116 117
    ];

118
    switch ($f->getEntityCategory()) {
119 120

      case 'bundle':
121 122 123
        $generator->setBundleSettings(
          $f->getEntityTypeId(),
          !empty($f->getBundleName()) ? $f->getBundleName() : $f->getFormEntityId(),
124
          $settings
125
        );
126 127
        break;

128
      case 'instance':
129 130 131
        $generator->setEntityInstanceSettings(
          $f->getEntityTypeId(),
          !empty($f->getInstanceId()) ? $f->getInstanceId() : $f->getFormEntityId(),
132
          $settings
133
        );
134
        break;
135
    }
136 137 138

    // Regenerate sitemaps according to user setting.
    if ($values['simple_sitemap_regenerate_now']) {
gbyte's avatar
gbyte committed
139
      $generator->generateSitemap();
140
    }
141 142 143 144 145 146
  }
}

/**
 * Implements hook_cron.
 */
gbyte's avatar
gbyte committed
147
function simple_sitemap_cron() {
148 149 150 151

  /**
   * @var \Drupal\simple_sitemap\Simplesitemap $generator
   */
gbyte's avatar
gbyte committed
152 153
  $generator = \Drupal::service('simple_sitemap.generator');
  if ($generator->getSetting('cron_generate')) {
154
    $interval = (int) $generator->getSetting('cron_generate_interval', 0) * 60 * 60;
155 156 157
    $requestTime = \Drupal::service('datetime.time')->getRequestTime();
    if ($interval === 0 || ((\Drupal::state()->get('simple_sitemap.last_cron_generate', 0) + $interval) <= $requestTime)) {
      \Drupal::state()->set('simple_sitemap.last_cron_generate', $requestTime);
158 159
      $generator->generateSitemap('backend');
    }
160
  }
gbyte's avatar
gbyte committed
161
}
162

163 164 165 166
/**
 * Implements hook_entity_delete().
 *
 * Removes settings of the removed entity.
167 168
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
169
 */
gbyte's avatar
gbyte committed
170
function simple_sitemap_entity_delete(EntityInterface $entity) {
171 172 173 174 175 176 177 178

  /**
   * @var \Drupal\simple_sitemap\Simplesitemap $generator
   */
  $generator = \Drupal::service('simple_sitemap.generator');
  $generator->removeEntityInstanceSettings(
    $entity->getEntityTypeId(), $entity->id()
  );
179
}
180 181 182 183 184

/**
 * Implements hook_entity_bundle_delete().
 *
 * Removes settings of the removed bundle.
gbyte's avatar
gbyte committed
185 186 187
 *
 * @param string $entity_type_id
 * @param string $bundle
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
 */
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) {
213 214 215 216

  /**
   * @var \Drupal\simple_sitemap\Simplesitemap $generator
   */
217 218 219 220 221 222 223 224 225
  $generator = \Drupal::service('simple_sitemap.generator');
  $deleted_bundle_settings = $generator->getBundleSettings($entity_type_id, $bundle);
  if ($deleted_bundle_settings !== FALSE) {

    // Delete bundle settings.
    \Drupal::service('config.factory')->getEditable("simple_sitemap.bundle_settings.$entity_type_id.$bundle")->delete();

    $message = "You may want to <a href='@url'>regenerate</a> your XML sitemap now.";
    if ($generator->getSetting('cron_generate')) {
226
      $message .= ' Otherwise the sitemap will be regenerated during a future cron run.';
227 228 229 230
    }
    drupal_set_message(t($message, ['@url' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap']));
  }
}
231 232 233 234 235 236 237

/**
 * Implements hook_robotstxt().
 */
function simple_sitemap_robotstxt() {
  return [
    '# XML sitemap',
238
    'Sitemap: ' . $GLOBALS['base_url'] . '/sitemap.xml', //todo: Use base URL setting?
239 240
  ];
}