SimplesitemapSettingsForm.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. <?php
  2. namespace Drupal\simple_sitemap\Form;
  3. use Symfony\Component\DependencyInjection\ContainerInterface;
  4. use Drupal\Core\Form\FormStateInterface;
  5. use Drupal\simple_sitemap\Simplesitemap;
  6. use Drupal\Component\Utility\UrlHelper;
  7. use Drupal\Core\Language\LanguageManager;
  8. use Drupal\Core\Database\Connection;
  9. /**
  10. * Class SimplesitemapSettingsForm
  11. * @package Drupal\simple_sitemap\Form
  12. */
  13. class SimplesitemapSettingsForm extends SimplesitemapFormBase {
  14. /**
  15. * @var \Drupal\Core\Language\LanguageManagerInterface
  16. */
  17. protected $languageManager;
  18. /**
  19. * @var \Drupal\Core\Database\Connection
  20. */
  21. protected $db;
  22. /**
  23. * SimplesitemapSettingsForm constructor.
  24. * @param \Drupal\simple_sitemap\Simplesitemap $generator
  25. * @param \Drupal\simple_sitemap\Form\FormHelper $form_helper
  26. * @param \Drupal\Core\Language\LanguageManager $language_manager
  27. * @param \Drupal\Core\Database\Connection $database
  28. */
  29. public function __construct(
  30. Simplesitemap $generator,
  31. FormHelper $form_helper,
  32. LanguageManager $language_manager,
  33. Connection $database
  34. ) {
  35. parent::__construct(
  36. $generator,
  37. $form_helper
  38. );
  39. $this->languageManager = $language_manager;
  40. $this->db = $database;
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public static function create(ContainerInterface $container) {
  46. return new static(
  47. $container->get('simple_sitemap.generator'),
  48. $container->get('simple_sitemap.form_helper'),
  49. $container->get('language_manager'),
  50. $container->get('database')
  51. );
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function getFormId() {
  57. return 'simple_sitemap_settings_form';
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function buildForm(array $form, FormStateInterface $form_state) {
  63. $form['simple_sitemap_settings']['#prefix'] = $this->getDonationText();
  64. $form['simple_sitemap_settings']['status'] = [
  65. '#type' => 'fieldset',
  66. '#title' => $this->t('Sitemap status'),
  67. '#markup' => '<div class="description">' . $this->t('Sitemaps can be regenerated on demand here.') . '</div>',
  68. '#description' => $this->t('Variants can be configured <a href="@url">here</a>.', ['@url' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap/variants']),
  69. ];
  70. $form['simple_sitemap_settings']['status']['actions'] = [
  71. '#prefix' => '<div class="clearfix"><div class="form-item">',
  72. '#suffix' => '</div></div>',
  73. ];
  74. $form['simple_sitemap_settings']['status']['actions']['regenerate_submit'] = [
  75. '#type' => 'submit',
  76. '#value' => $this->t('Generate from queue'),
  77. '#submit' => ['::generateSitemap'],
  78. '#validate' => [],
  79. ];
  80. // $form['simple_sitemap_settings']['status']['actions']['regenerate_backend_submit'] = [
  81. // '#type' => 'submit',
  82. // '#value' => $this->t('Generate from queue (background)'),
  83. // '#submit' => ['::generateSitemapBackend'],
  84. // '#validate' => [],
  85. // ];
  86. $form['simple_sitemap_settings']['status']['actions']['rebuild_queue_submit'] = [
  87. '#type' => 'submit',
  88. '#value' => $this->t('Rebuild queue'),
  89. '#submit' => ['::rebuildQueue'],
  90. '#validate' => [],
  91. ];
  92. $form['simple_sitemap_settings']['status']['progress'] = [
  93. '#prefix' => '<div class="clearfix">',
  94. '#suffix' => '</div>',
  95. ];
  96. $form['simple_sitemap_settings']['status']['progress']['title']['#markup'] = $this->t('Progress of sitemap regeneration');
  97. $queue_worker = $this->generator->getQueueWorker();
  98. $total_count = $queue_worker->getInitialElementCount();
  99. if (!empty($total_count)) {
  100. $indexed_count = $queue_worker->getProcessedElementCount();
  101. $percent = round(100 * $indexed_count / $total_count);
  102. // With all results processed, there still may be some stashed results to be indexed.
  103. $percent = $percent === 100 && $queue_worker->generationInProgress() ? 99 : $percent;
  104. $index_progress = [
  105. '#theme' => 'progress_bar',
  106. '#percent' => $percent,
  107. '#message' => t('@indexed out of @total items have been processed.', ['@indexed' => $indexed_count, '@total' => $total_count]),
  108. ];
  109. $form['simple_sitemap_settings']['status']['progress']['bar']['#markup'] = render($index_progress);
  110. }
  111. else {
  112. $form['simple_sitemap_settings']['status']['progress']['bar']['#markup'] = '<div class="description">' . $this->t('There are no items to be indexed.') . '</div>';
  113. }
  114. $sitemap_manager = $this->generator->getSitemapManager();
  115. $sitemap_statuses = $this->fetchSitemapInstanceStatuses();
  116. foreach ($sitemap_manager->getSitemapTypes() as $type_name => $type_definition) {
  117. if (!empty($variants = $sitemap_manager->getSitemapVariants($type_name, FALSE))) {
  118. $form['simple_sitemap_settings']['status']['types'][$type_name] = [
  119. '#type' => 'details',
  120. '#title' => '<em>' . $type_definition['label'] . '</em> ' . $this->t('sitemaps'),
  121. '#open' => !empty($variants) && count($variants) <= 5,
  122. '#description' => !empty($type_definition['description']) ? '<div class="description">' . $type_definition['description'] . '</div>' : '',
  123. ];
  124. $form['simple_sitemap_settings']['status']['types'][$type_name]['table'] = [
  125. '#type' => 'table',
  126. '#header' => [$this->t('Variant'), $this->t('Status'), /*$this->t('Actions')*/],
  127. '#attributes' => ['class' => ['form-item', 'clearfix']],
  128. ];
  129. foreach ($variants as $variant_name => $variant_definition) {
  130. $row = [];
  131. $row['name']['data']['#markup'] = '<span title="' . $variant_name . '">' . $variant_definition['label'] . '</span>';
  132. if (!isset($sitemap_statuses[$variant_name])) {
  133. $row['status'] = $this->t('pending');
  134. }
  135. else {
  136. $url = $GLOBALS['base_url'] . '/' . $variant_name . '/sitemap.xml';
  137. switch ($sitemap_statuses[$variant_name]) {
  138. case 0:
  139. $row['status'] = $this->t('generating');
  140. break;
  141. case 1:
  142. $row['status']['data']['#markup'] = $this->t('<a href="@url" target="_blank">published</a>', ['@url' => $url]);
  143. break;
  144. case 2:
  145. $row['status'] = $this->t('<a href="@url" target="_blank">published</a>, regenerating', ['@url' => $url]);
  146. break;
  147. }
  148. }
  149. // $row['actions'] = '';
  150. $form['simple_sitemap_settings']['status']['types'][$type_name]['table']['#rows'][$variant_name] = $row;
  151. unset($sitemap_statuses[$variant_name]);
  152. }
  153. }
  154. }
  155. if (empty($form['simple_sitemap_settings']['status']['types'])) {
  156. $form['simple_sitemap_settings']['status']['types']['#markup'] = $this->t('No variants have been defined');
  157. }
  158. /* if (!empty($sitemap_statuses)) {
  159. $form['simple_sitemap_settings']['status']['types']['&orphans'] = [
  160. '#type' => 'details',
  161. '#title' => $this->t('Orphans'),
  162. '#open' => TRUE,
  163. ];
  164. $form['simple_sitemap_settings']['status']['types']['&orphans']['table'] = [
  165. '#type' => 'table',
  166. '#header' => [$this->t('Variant'), $this->t('Status'), $this->t('Actions')],
  167. ];
  168. foreach ($sitemap_statuses as $orphan_name => $orphan_info) {
  169. $form['simple_sitemap_settings']['status']['types']['&orphans']['table']['#rows'][$orphan_name] = [
  170. 'name' => $orphan_name,
  171. 'status' => $this->t('orphaned'),
  172. 'actions' => '',
  173. ];
  174. }
  175. }*/
  176. $form['simple_sitemap_settings']['settings'] = [
  177. '#type' => 'fieldset',
  178. '#title' => $this->t('Settings'),
  179. ];
  180. $form['simple_sitemap_settings']['settings']['cron_generate'] = [
  181. '#type' => 'checkbox',
  182. '#title' => $this->t('Regenerate the sitemaps during cron runs'),
  183. '#description' => $this->t('Uncheck this if you intend to only regenerate the sitemaps manually or via drush.'),
  184. '#default_value' => $this->generator->getSetting('cron_generate', TRUE),
  185. ];
  186. $form['simple_sitemap_settings']['settings']['cron_generate_interval'] = [
  187. '#type' => 'select',
  188. '#title' => $this->t('Sitemap generation interval'),
  189. '#description' => $this->t('The sitemap will be generated according to this interval.'),
  190. '#default_value' => $this->generator->getSetting('cron_generate_interval', 0),
  191. '#options' => [
  192. 0 => $this->t('On every cron run'),
  193. 1 => $this->t('Once an hour'),
  194. 3 => $this->t('Once every @hours hours', ['@hours' => 3]),
  195. 6 => $this->t('Once every @hours hours', ['@hours' => 6]),
  196. 12 => $this->t('Once every @hours hours', ['@hours' => 12]),
  197. 24 => $this->t('Once a day'),
  198. 48 => $this->t('Once every @days days', ['@days' => 48/24]),
  199. 72 => $this->t('Once every @days days', ['@days' => 72/24]),
  200. 96 => $this->t('Once every @days days', ['@days' => 96/24]),
  201. 120 => $this->t('Once every @days days', ['@days' => 120/24]),
  202. 144 => $this->t('Once every @days days', ['@days' => 144/24]),
  203. 168 => $this->t('Once a week'),
  204. ],
  205. '#states' => [
  206. 'visible' => [
  207. ':input[name="cron_generate"]' => ['checked' => TRUE],
  208. ],
  209. ],
  210. ];
  211. $form['simple_sitemap_settings']['settings']['languages'] = [
  212. '#type' => 'details',
  213. '#title' => $this->t('Language settings'),
  214. '#open' => FALSE,
  215. ];
  216. $language_options = [];
  217. foreach ($this->languageManager->getLanguages() as $language) {
  218. if (!$language->isDefault()) {
  219. $language_options[$language->getId()] = $language->getName();
  220. }
  221. }
  222. $form['simple_sitemap_settings']['settings']['languages']['skip_untranslated'] = [
  223. '#type' => 'checkbox',
  224. '#title' => $this->t('Skip non-existent translations'),
  225. '#description' => $this->t('If checked, entity links are generated exclusively for languages the entity has been translated to as long as the language is not excluded below.<br/>Otherwise entity links are generated for every language installed on the site apart from languages excluded below.<br/>Bear in mind that non-entity paths like homepage will always be generated for every non-excluded language.'),
  226. '#default_value' => $this->generator->getSetting('skip_untranslated', FALSE),
  227. ];
  228. $form['simple_sitemap_settings']['settings']['languages']['excluded_languages'] = [
  229. '#title' => $this->t('Exclude languages'),
  230. '#type' => 'checkboxes',
  231. '#options' => $language_options,
  232. '#description' => !empty($language_options)
  233. ? $this->t('There will be no links generated for languages checked here.')
  234. : $this->t('There are no languages other than the default language <a href="@url">available</a>.', ['@url' => $GLOBALS['base_url'] . '/admin/config/regional/language']),
  235. '#default_value' => $this->generator->getSetting('excluded_languages', []),
  236. ];
  237. $form['simple_sitemap_settings']['advanced'] = [
  238. '#type' => 'details',
  239. '#title' => $this->t('Advanced settings'),
  240. '#open' => TRUE,
  241. ];
  242. $variants = $this->generator->getSitemapManager()->getSitemapVariants(NULL, FALSE);
  243. $default_variant = $this->generator->getSetting('default_variant');
  244. $form['simple_sitemap_settings']['advanced']['default_variant'] = [
  245. '#type' => 'select',
  246. '#title' => $this->t('Default sitemap variant'),
  247. '#description' => $this->t('This sitemap variant will be available under <em>/sitemap.xml</em> in addition to its default path <em>/variant-name/sitemap.xml</em>.<br/>Variants can be configured <a href="@url">here</a>.', ['@url' => $GLOBALS['base_url'] . '/admin/config/search/simplesitemap/variants']),
  248. '#default_value' => isset($variants[$default_variant]) ? $default_variant : '',
  249. '#options' => ['' => $this->t('- None -')] + array_map(function($variant) { return $this->t($variant['label']); }, $variants),
  250. ];
  251. $form['simple_sitemap_settings']['advanced']['base_url'] = [
  252. '#type' => 'textfield',
  253. '#title' => $this->t('Default base URL'),
  254. '#default_value' => $this->generator->getSetting('base_url', ''),
  255. '#size' => 30,
  256. '#description' => $this->t('On some hosting providers it is impossible to pass parameters to cron to tell Drupal which URL to bootstrap with. In this case the base URL of sitemap links can be overridden here.<br/>Example: <em>@url</em>', ['@url' => $GLOBALS['base_url']]),
  257. ];
  258. $form['simple_sitemap_settings']['advanced']['remove_duplicates'] = [
  259. '#type' => 'checkbox',
  260. '#title' => $this->t('Exclude duplicate links'),
  261. '#description' => $this->t('Prevent per-sitemap variant duplicate links.<br/>Uncheck this to significantly speed up the sitemap generation process on a huge site (more than 20 000 indexed entities).'),
  262. '#default_value' => $this->generator->getSetting('remove_duplicates', TRUE),
  263. ];
  264. $form['simple_sitemap_settings']['advanced']['max_links'] = [
  265. '#type' => 'number',
  266. '#title' => $this->t('Maximum links in a sitemap'),
  267. '#min' => 1,
  268. '#description' => $this->t('The maximum number of links one sitemap can hold. If more links are generated than set here, a sitemap index will be created and the links split into several sub-sitemaps.<br/>50 000 links is the maximum Google will parse per sitemap, but an equally important consideration is generation performance: Splitting sitemaps into chunks <em>greatly</em> increases it.<br/>If left blank, all links will be shown on a single sitemap.'),
  269. '#default_value' => $this->generator->getSetting('max_links'),
  270. ];
  271. $form['simple_sitemap_settings']['advanced']['generate_duration'] = [
  272. '#type' => 'number',
  273. '#title' => $this->t('Sitemap generation max duration'),
  274. '#min' => 1,
  275. '#description' => $this->t('The maximum duration <strong>in seconds</strong> the generation task can run during a single cron run or during one batch process iteration.<br/>The higher the number, the quicker the generation process, but higher the risk of PHP timeout errors.'),
  276. '#default_value' => $this->generator->getSetting('generate_duration', 10000) / 1000,
  277. '#required' => TRUE,
  278. ];
  279. $this->formHelper->displayRegenerateNow($form['simple_sitemap_settings']);
  280. return parent::buildForm($form, $form_state);
  281. }
  282. /**
  283. * @return array
  284. * Array of sitemap statuses keyed by variant name.
  285. * Status values:
  286. * 0: Instance is unpublished
  287. * 1: Instance is published
  288. * 2: Instance is published but is being regenerated
  289. */
  290. protected function fetchSitemapInstanceStatuses() {
  291. $results = $this->db
  292. ->query('SELECT type, status FROM {simple_sitemap} GROUP BY type, status')
  293. ->fetchAll();
  294. $instances = [];
  295. foreach ($results as $i => $result) {
  296. $instances[$result->type] = isset($instances[$result->type])
  297. ? $result->status + 1
  298. : (int) $result->status;
  299. }
  300. return $instances;
  301. }
  302. /**
  303. * {@inheritdoc}
  304. */
  305. public function validateForm(array &$form, FormStateInterface $form_state) {
  306. $base_url = $form_state->getValue('base_url');
  307. $form_state->setValue('base_url', rtrim($base_url, '/'));
  308. if ($base_url !== '' && !UrlHelper::isValid($base_url, TRUE)) {
  309. $form_state->setErrorByName('base_url', t('The base URL is invalid.'));
  310. }
  311. }
  312. /**
  313. * {@inheritdoc}
  314. */
  315. public function submitForm(array &$form, FormStateInterface $form_state) {
  316. foreach (['max_links',
  317. 'cron_generate',
  318. 'cron_generate_interval',
  319. 'remove_duplicates',
  320. 'skip_untranslated',
  321. 'base_url',
  322. 'default_variant'] as $setting_name) {
  323. $this->generator->saveSetting($setting_name, $form_state->getValue($setting_name));
  324. }
  325. $this->generator->saveSetting('excluded_languages', array_filter($form_state->getValue('excluded_languages')));
  326. $this->generator->saveSetting('generate_duration', $form_state->getValue('generate_duration') * 1000);
  327. parent::submitForm($form, $form_state);
  328. // Regenerate sitemaps according to user setting.
  329. if ($form_state->getValue('simple_sitemap_regenerate_now')) {
  330. $this->generator->rebuildQueue()->generateSitemap();
  331. }
  332. }
  333. /**
  334. * @param array $form
  335. * @param \Drupal\Core\Form\FormStateInterface $form_state
  336. * @throws \Drupal\Component\Plugin\Exception\PluginException
  337. */
  338. public function generateSitemap(array &$form, FormStateInterface $form_state) {
  339. $this->generator->generateSitemap();
  340. }
  341. /**
  342. * @param array $form
  343. * @param \Drupal\Core\Form\FormStateInterface $form_state
  344. * @throws \Drupal\Component\Plugin\Exception\PluginException
  345. */
  346. public function generateSitemapBackend (array &$form, FormStateInterface $form_state) {
  347. $this->generator->generateSitemap('backend');
  348. }
  349. /**
  350. * @param array $form
  351. * @param \Drupal\Core\Form\FormStateInterface $form_state
  352. * @throws \Drupal\Component\Plugin\Exception\PluginException
  353. */
  354. public function rebuildQueue(array &$form, FormStateInterface $form_state) {
  355. $this->generator->rebuildQueue();
  356. }
  357. }