f49ae59c3371238c7af81723be3717237527ea90
[yaffs-website] / web / modules / contrib / linkchecker / src / Form / LinkCheckerAdminSettingsForm.php
1 <?php
2
3 namespace Drupal\linkchecker\Form;
4
5 use Drupal\Core\Form\ConfigFormBase;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\Core\Logger\RfcLogLevel;
8 use Drupal\Core\Url;
9 use Drupal\filter\FilterPluginCollection;
10 use Drupal\user\Entity\User;
11
12 /**
13  * Configure Linkchecker settings for this site.
14  */
15 class LinkCheckerAdminSettingsForm extends ConfigFormBase {
16
17   /**
18    * {@inheritdoc}
19    */
20   public function getFormId() {
21     return 'linkchecker_admin_settings';
22   }
23
24   /**
25    * {@inheritdoc}
26    */
27   protected function getEditableConfigNames() {
28     return ['linkchecker.settings'];
29   }
30
31   /**
32    * {@inheritdoc}
33    */
34   public function buildForm(array $form, FormStateInterface $form_state) {
35     $config = $this->config('linkchecker.settings');
36
37     $form['general'] = [
38       '#type' => 'details',
39       '#title' => $this->t('General settings'),
40       '#description' => $this->t('Configure the <a href=":url">content types</a> that should be scanned for broken links.', [':url' => Url::fromRoute('entity.node_type.collection')->toString()]),
41       '#open' => TRUE,
42     ];
43
44     $block_custom_dependencies = '<div class="admin-requirements">';
45     $block_custom_dependencies .= $this->t('Requires: @module-list', ['@module-list' => (\Drupal::moduleHandler()->moduleExists('block') ? $this->t('@module (<span class="admin-enabled">enabled</span>)', ['@module' => 'Block']) : $this->t('@module (<span class="admin-disabled">disabled</span>)', ['@module' => 'Block']))]);
46     $block_custom_dependencies .= '</div>';
47
48     $form['general']['linkchecker_scan_blocks'] = [
49       '#default_value' => $config->get('scan_blocks'),
50       '#type' => 'checkbox',
51       '#title' => $this->t('Scan blocks for links'),
52       '#description' => $this->t('Enable this checkbox if links in blocks should be checked.') . $block_custom_dependencies,
53       '#disabled' => !\Drupal::moduleHandler()->moduleExists('block'),
54     ];
55     $form['general']['linkchecker_check_links_types'] = [
56       '#type' => 'select',
57       '#title' => $this->t('What type of links should be checked?'),
58       '#description' => $this->t('A full qualified link (http://example.com/foo/bar) to a page is considered external, whereas an absolute (/foo/bar) or relative link (node/123) without a domain is considered internal.'),
59       '#default_value' => $config->get('check_links_types'),
60       '#options' => [
61         '0' => $this->t('Internal and external'),
62         '1' => $this->t('External only (http://example.com/foo/bar)'),
63         '2' => $this->t('Internal only (node/123)'),
64       ],
65     ];
66
67     $form['tag'] = [
68       '#type' => 'details',
69       '#title' => $this->t('Link extraction'),
70       '#open' => TRUE,
71     ];
72     $form['tag']['linkchecker_extract_from_a'] = [
73       '#default_value' => $config->get('extract.from_a'),
74       '#type' => 'checkbox',
75       '#title' => $this->t('Extract links in <code>&lt;a&gt;</code> and <code>&lt;area&gt;</code> tags'),
76       '#description' => $this->t('Enable this checkbox if normal hyperlinks should be extracted. The anchor element defines a hyperlink, the named target destination for a hyperlink, or both. The area element defines a hot-spot region on an image, and associates it with a hypertext link.'),
77     ];
78     $form['tag']['linkchecker_extract_from_audio'] = [
79       '#default_value' => $config->get('extract.from_audio'),
80       '#type' => 'checkbox',
81       '#title' => $this->t('Extract links in <code>&lt;audio&gt;</code> tags including their <code>&lt;source&gt;</code> and <code>&lt;track&gt;</code> tags'),
82       '#description' => $this->t('Enable this checkbox if links in audio tags should be extracted. The audio element is used to embed audio content.'),
83     ];
84     $form['tag']['linkchecker_extract_from_embed'] = [
85       '#default_value' => $config->get('extract.from_embed'),
86       '#type' => 'checkbox',
87       '#title' => $this->t('Extract links in <code>&lt;embed&gt;</code> tags'),
88       '#description' => $this->t('Enable this checkbox if links in embed tags should be extracted. This is an obsolete and non-standard element that was used for embedding plugins in past and should no longer used in modern websites.'),
89     ];
90     $form['tag']['linkchecker_extract_from_iframe'] = [
91       '#default_value' => $config->get('extract.from_iframe'),
92       '#type' => 'checkbox',
93       '#title' => $this->t('Extract links in <code>&lt;iframe&gt;</code> tags'),
94       '#description' => $this->t('Enable this checkbox if links in iframe tags should be extracted. The iframe element is used to embed another HTML page into a page.'),
95     ];
96     $form['tag']['linkchecker_extract_from_img'] = [
97       '#default_value' => $config->get('extract.from_img'),
98       '#type' => 'checkbox',
99       '#title' => $this->t('Extract links in <code>&lt;img&gt;</code> tags'),
100       '#description' => $this->t('Enable this checkbox if links in image tags should be extracted. The img element is used to add images to the content.'),
101     ];
102     $form['tag']['linkchecker_extract_from_object'] = [
103       '#default_value' => $config->get('extract.from_object'),
104       '#type' => 'checkbox',
105       '#title' => $this->t('Extract links in <code>&lt;object&gt;</code> and <code>&lt;param&gt;</code> tags'),
106       '#description' => $this->t('Enable this checkbox if multimedia and other links in object and their param tags should be extracted. The object tag is used for flash, java, quicktime and other applets.'),
107     ];
108     $form['tag']['linkchecker_extract_from_video'] = [
109       '#default_value' => $config->get('extract.from_video'),
110       '#type' => 'checkbox',
111       '#title' => $this->t('Extract links in <code>&lt;video&gt;</code> tags including their <code>&lt;source&gt;</code> and <code>&lt;track&gt;</code> tags'),
112       '#description' => $this->t('Enable this checkbox if links in video tags should be extracted. The video element is used to embed video content.'),
113     ];
114
115     // Get all filters available on the system.
116     $manager = \Drupal::service('plugin.manager.filter');
117     $bag = new FilterPluginCollection($manager, []);
118     $filter_info = $bag->getAll();
119     $filter_options = [];
120     $filter_descriptions = [];
121     foreach ($filter_info as $name => $filter) {
122       if (in_array($name, explode('|', LINKCHECKER_DEFAULT_FILTER_BLACKLIST))) {
123         $filter_options[$name] = $this->t('@title <span class="marker">(Recommended)</span>', array('@title' => $filter->getLabel()));
124       }
125       else {
126         $filter_options[$name] = $filter->getLabel();
127       }
128       $filter_descriptions[$name] = [
129         '#description' => $filter->getDescription(),
130       ];
131     }
132     $form['tag']['linkchecker_filter_blacklist'] = [
133       '#type' => 'checkboxes',
134       '#title' => $this->t('Text formats disabled for link extraction'),
135       '#default_value' => $config->get('extract.filter_blacklist'),
136       '#options' => $filter_options,
137       '#description' => $this->t('If a filter has been enabled for an input format it runs first and afterwards the link extraction. This helps the link checker module to find all links normally created by custom filters (e.g. Markdown filter, Bbcode). All filters used as inline references (e.g. Weblink filter <code>[link: id]</code>) to other content and filters only wasting processing time (e.g. Line break converter) should be disabled. This setting does not have any effect on how content is shown on a page. This feature optimizes the internal link extraction process for link checker and prevents false alarms about broken links in content not having the real data of a link.'),
138     ];
139     $form['tag']['linkchecker_filter_blacklist'] = array_merge($form['tag']['linkchecker_filter_blacklist'], $filter_descriptions);
140
141     $count_lids_enabled = db_query("SELECT count(lid) FROM {linkchecker_link} WHERE status = :status", array(':status' => 1))->fetchField();
142     $count_lids_disabled = db_query("SELECT count(lid) FROM {linkchecker_link} WHERE status = :status", array(':status' => 0))->fetchField();
143     $form['check'] = [
144       '#type' => 'details',
145       '#title' => $this->t('Check settings'),
146       '#description' => $this->t('For simultaneous link checks it is recommended to install the <a href=":httprl">HTTP Parallel Request & Threading Library</a>. This may be <strong>necessary</strong> on larger sites with very many links (30.000+), but will also improve overall link check duration on smaller sites. Currently the site has @count links (@count_enabled enabled / @count_disabled disabled).', [':httprl' => 'http://drupal.org/project/httprl', '@count' => $count_lids_enabled+$count_lids_disabled, '@count_enabled' => $count_lids_enabled, '@count_disabled' => $count_lids_disabled]),
147       '#open' => TRUE,
148     ];
149     $form['check']['linkchecker_check_library'] = [
150       '#type' => 'select',
151       '#title' => $this->t('Check library'),
152       '#description' => $this->t('Defines the library that is used for checking links.'),
153       '#default_value' => $config->get('check.library'),
154       '#options' => [
155         'core' => $this->t('Drupal core'),
156         'httprl' => $this->t('HTTP Parallel Request & Threading Library'),
157       ],
158     ];
159     $form['check']['linkchecker_check_connections_max'] = [
160       '#type' => 'select',
161       '#title' => $this->t('Number of simultaneous connections'),
162       '#description' => $this->t('Defines the maximum number of simultaneous connections that can be opened by the server. <em>HTTP Parallel Request & Threading Library</em> make sure that a single domain is not overloaded beyond RFC limits. For small hosting plans with very limited CPU and RAM it may be required to reduce the default limit.'),
163       '#default_value' => $config->get('check.connections_max'),
164       '#options' => array_combine([2, 4, 8, 16, 24, 32, 48, 64, 96, 128], [2, 4, 8, 16, 24, 32, 48, 64, 96, 128]),
165       '#states' => [
166         // Hide the setting when Drupal core check library is selected.
167         'invisible' => [
168           ':input[name="check_library"]' => ['value' => 'core'],
169         ],
170       ],
171     ];
172     $form['check']['linkchecker_check_useragent'] = [
173       '#type' => 'select',
174       '#title' => $this->t('User-Agent'),
175       '#description' => $this->t('Defines the user agent that will be used for checking links on remote sites. If someone blocks the standard Drupal user agent you can try with a more common browser.'),
176       '#default_value' => $config->get('check.useragent'),
177       '#options' => [
178         'Drupal (+http://drupal.org/)' => 'Drupal (+http://drupal.org/)',
179         'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko' => 'Windows 8.1 (x64), Internet Explorer 11.0',
180         'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586' => 'Windows 10 (x64), Edge',
181         'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0' => 'Windows 8.1 (x64), Mozilla Firefox 47.0',
182         'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0' => 'Windows 10 (x64), Mozilla Firefox 47.0',
183       ],
184     ];
185     $intervals = [86400, 172800, 259200, 604800, 1209600, 2419200, 4838400];
186     $period = array_map([\Drupal::service('date.formatter'), 'formatInterval'], array_combine($intervals, $intervals));
187     $form['check']['linkchecker_check_interval'] = [
188       '#type' => 'select',
189       '#title' => $this->t('Check interval for links'),
190       '#description' => $this->t('This interval setting defines how often cron will re-check the status of links.'),
191       '#default_value' => $config->get('check.interval'),
192       '#options' => $period,
193     ];
194     $form['check']['linkchecker_disable_link_check_for_urls'] = [
195       '#default_value' => $config->get('check.disable_link_check_for_urls'),
196       '#type' => 'textarea',
197       '#title' => $this->t('Do not check the link status of links containing these URLs'),
198       '#description' => $this->t('By default this list contains the domain names reserved for use in documentation and not available for registration. See <a href=":rfc-2606">RFC 2606</a>, Section 3 for more information. URLs on this list are still extracted, but the link setting <em>Check link status</em> becomes automatically disabled to prevent false alarms. If you change this list you need to clear all link data and re-analyze your content. Otherwise this setting will only affect new links added after the configuration change.', array(':rfc-2606' => 'http://www.rfc-editor.org/rfc/rfc2606.txt')),
199     ];
200     //@fixme: constants no longer exists.
201     $form['check']['linkchecker_logging_level'] = [
202       '#default_value' => $config->get('logging.level'),
203       '#type' => 'select',
204       '#title' => $this->t('Log level'),
205       '#description' => $this->t('Controls the severity of logging.'),
206       '#options' => [
207         RfcLogLevel::DEBUG => $this->t('Debug messages'),
208         RfcLogLevel::INFO => $this->t('All messages (default)'),
209         RfcLogLevel::NOTICE => $this->t('Notices and errors'),
210         RfcLogLevel::WARNING => $this->t('Warnings and errors'),
211         RfcLogLevel::ERROR => $this->t('Errors only'),
212       ],
213     ];
214
215     $form['error'] = [
216       '#type' => 'details',
217       '#title' => $this->t('Error handling'),
218       '#description' => $this->t('Defines error handling and custom actions to be executed if specific HTTP requests are failing.'),
219       '#open' => TRUE,
220     ];
221     $linkchecker_default_impersonate_account = User::load(1);
222     $form['error']['linkchecker_impersonate_account'] = [
223       '#type' => 'textfield',
224       '#title' => $this->t('Impersonate user account'),
225       '#description' => $this->t('If below error handling actions are executed they can be impersonated with a custom user account. By default this is user %name, but you are able to assign a custom user to allow easier identification of these automatic revision updates. Make sure you select a user with <em>full</em> permissions on your site or the user may not able to access and save all content.', array('%name' => $linkchecker_default_impersonate_account->getAccountName())),
226       '#size' => 30,
227       '#maxlength' => 60,
228       '#autocomplete_path' => 'user/autocomplete',
229       '#default_value' => $config->get('error.impersonate_account'),
230     ];
231     $form['error']['linkchecker_action_status_code_301'] = [
232       '#title' => $this->t('Update permanently moved links'),
233       '#description' => $this->t('If enabled, outdated links in content providing a status <em>Moved Permanently</em> (status code 301) are automatically updated to the most recent URL. If used, it is recommended to use a value of <em>three</em> to make sure this is not only a temporarily change. This feature trust sites to provide a valid permanent redirect. A new content revision is automatically created on link updates if <em>create new revision</em> is enabled in the <a href=":content_types">content types</a> publishing options. It is recommended to create new revisions for all link checker enabled content types. Link updates are nevertheless always logged in <a href=":dblog">recent log entries</a>.', array(':dblog' => Url::fromRoute('dblog.overview')->toString(), ':content_types' => Url::fromRoute('entity.node_type.collection')->toString())),
234       '#type' => 'select',
235       '#default_value' => $config->get('error.action_status_code_301'),
236       '#options' => [
237         0 => $this->t('Disabled'),
238         1 => $this->t('After one failed check'),
239         2 => $this->t('After two failed checks'),
240         3 => $this->t('After three failed checks'),
241         5 => $this->t('After five failed checks'),
242         10 => $this->t('After ten failed checks'),
243       ],
244     ];
245     $form['error']['linkchecker_action_status_code_404'] = [
246       '#title' => $this->t('Unpublish content on file not found error'),
247       '#description' => $this->t('If enabled, content with one or more broken links (status code 404) will be unpublished and moved to moderation queue for review after the number of specified checks failed. If used, it is recommended to use a value of <em>three</em> to make sure this is not only a temporarily error.'),
248       '#type' => 'select',
249       '#default_value' => $config->get('error.action_status_code_404'),
250       '#options' => [
251         0 => $this->t('Disabled'),
252         1 => $this->t('After one file not found error'),
253         2 => $this->t('After two file not found errors'),
254         3 => $this->t('After three file not found errors'),
255         5 => $this->t('After five file not found errors'),
256         10 => $this->t('After ten file not found errors'),
257       ],
258     ];
259     $form['error']['linkchecker_ignore_response_codes'] = [
260       '#default_value' => $config->get('error.ignore_response_codes'),
261       '#type' => 'textarea',
262       '#title' => $this->t("Don't treat these response codes as errors"),
263       '#description' => $this->t('One HTTP status code per line, e.g. 403.'),
264     ];
265
266     // Buttons are only required for testing and debugging reasons.
267     $description = '<p>' . $this->t('These actions will either clear all link checker tables in the database and/or analyze all selected content types, blocks and fields (see settings above) for new/updated/removed links. Normally there is no need to press one of these buttons. Use this only for immediate cleanup tasks and to force a full re-build of the links to be checked in the linkchecker tables. Keep in mind that all custom link settings will be lost if you clear link data!') . '</p>';
268     $description .= '<p>' . $this->t('<strong>Note</strong>: These functions ONLY collect the links, they do not evaluate the HTTP response codes, this will be done during normal cron runs.') . '</p>';
269
270     $form['clear'] = [
271       '#type' => 'details',
272       '#title' => $this->t('Maintenance'),
273       '#description' => $description,
274       '#open' => FALSE,
275     ];
276     $form['clear']['linkchecker_analyze'] = [
277       '#type' => 'submit',
278       '#value' => $this->t('Reanalyze content for links'),
279       '#submit' => ['::submitForm', '::submitAnalyzeLinks'],
280     ];
281     $form['clear']['linkchecker_clear_analyze'] = [
282       '#type' => 'submit',
283       '#value' => $this->t('Clear link data and analyze content for links'),
284       '#submit' => ['::submitForm', '::submitClearAnalyzeLinks'],
285     ];
286
287     return parent::buildForm($form, $form_state);
288   }
289
290   /**
291    * {@inheritdoc}
292    */
293   public function validateForm(array &$form, FormStateInterface $form_state) {
294     parent::validateForm($form, $form_state);
295
296     $form_state->setValue('linkchecker_disable_link_check_for_urls', trim($form_state->getValue('linkchecker_disable_link_check_for_urls')));
297     $form_state->setValue('linkchecker_ignore_response_codes', trim($form_state->getValue('linkchecker_ignore_response_codes')));
298     $ignore_response_codes = preg_split('/(\r\n?|\n)/', $form_state->getValue('linkchecker_ignore_response_codes'));
299     foreach ($ignore_response_codes as $ignore_response_code) {
300       if (!_linkchecker_isvalid_response_code($ignore_response_code)) {
301         $form_state->setErrorByName('linkchecker_ignore_response_codes', $this->t('Invalid response code %code found.', ['%code' => $ignore_response_code]));
302       }
303     }
304
305     // @fixme: remove constant?
306     // Prevent the removal of RFC documentation domains. This are the official and
307     // reserved documentation domains and not "example" hostnames!
308     $linkchecker_disable_link_check_for_urls = array_filter(preg_split('/(\r\n?|\n)/', $form_state->getValue('linkchecker_disable_link_check_for_urls')));
309     $form_state->setValue('linkchecker_disable_link_check_for_urls', implode("\n", array_unique(array_merge(explode("\n", LINKCHECKER_RESERVED_DOCUMENTATION_DOMAINS), $linkchecker_disable_link_check_for_urls))));
310
311     // Validate impersonation user name.
312     $linkchecker_impersonate_account = user_load_by_name($form_state->getValue('linkchecker_impersonate_account'));
313     if (empty($linkchecker_impersonate_account->id())) {
314       $form_state->setErrorByName('linkchecker_impersonate_account', $this->t('User account %name cannot found.', ['%name' => $form_state->getValue('linkchecker_impersonate_account')]));
315     }
316   }
317
318   /**
319    * {@inheritdoc}
320    */
321   public function submitForm(array &$form, FormStateInterface $form_state) {
322     $config = $this->config('linkchecker.settings');
323     $config
324       ->set('scan_blocks', $form_state->getValue('linkchecker_scan_blocks'))
325       ->set('check_links_types', $form_state->getValue('linkchecker_check_links_types'))
326       ->set('extract.from_a', $form_state->getValue('linkchecker_extract_from_a'))
327       ->set('extract.from_audio', $form_state->getValue('linkchecker_extract_from_audio'))
328       ->set('extract.from_embed', $form_state->getValue('linkchecker_extract_from_embed'))
329       ->set('extract.from_iframe', $form_state->getValue('linkchecker_extract_from_iframe'))
330       ->set('extract.from_img', $form_state->getValue('linkchecker_extract_from_img'))
331       ->set('extract.from_object', $form_state->getValue('linkchecker_extract_from_object'))
332       ->set('extract.from_video', $form_state->getValue('linkchecker_extract_from_video'))
333       ->set('extract.filter_blacklist', $form_state->getValue('linkchecker_filter_blacklist'))
334       ->set('check.connections_max', $form_state->getValue('linkchecker_check_connections_max'))
335       ->set('check.disable_link_check_for_urls', $form_state->getValue('linkchecker_disable_link_check_for_urls'))
336       ->set('check.library', $form_state->getValue('linkchecker_check_library'))
337       ->set('check.interval', $form_state->getValue('linkchecker_check_interval'))
338       ->set('check.useragent', $form_state->getValue('linkchecker_check_useragent'))
339       ->set('error.action_status_code_301', $form_state->getValue('linkchecker_action_status_code_301'))
340       ->set('error.action_status_code_404', $form_state->getValue('linkchecker_action_status_code_404'))
341       ->set('error.ignore_response_codes', $form_state->getValue('linkchecker_ignore_response_codes'))
342       ->set('error.impersonate_account', $form_state->getValue('linkchecker_impersonate_account'))
343       ->set('logging.level', $form_state->getValue('linkchecker_logging_level'))
344       ->save();
345
346     // If block scanning has been selected.
347     if ($form_state->getValue('linkchecker_scan_blocks') > $form['general']['linkchecker_scan_blocks']['#default_value']) {
348       module_load_include('inc', 'linkchecker', 'linkchecker.batch');
349       batch_set(_linkchecker_batch_import_block_custom());
350     }
351
352     parent::submitForm($form, $form_state);
353   }
354
355   /**
356    * Analyze fields in all node types, comments, custom blocks.
357    */
358   function submitAnalyzeLinks(array &$form, FormStateInterface $form_state) {
359     // Start batch and analyze all nodes.
360     $node_types = linkchecker_scan_node_types();
361     if (!empty($node_types)) {
362       module_load_include('inc', 'linkchecker', 'linkchecker.batch');
363       batch_set(_linkchecker_batch_import_nodes($node_types));
364     }
365
366     $comment_types = linkchecker_scan_comment_types();
367     if (!empty($comment_types)) {
368       module_load_include('inc', 'linkchecker', 'linkchecker.batch');
369       batch_set(_linkchecker_batch_import_comments($comment_types));
370     }
371
372     if ($this->config('linkchecker.settings')->get('scan_blocks')) {
373       module_load_include('inc', 'linkchecker', 'linkchecker.batch');
374       batch_set(_linkchecker_batch_import_block_custom());
375     }
376   }
377
378   /**
379    * Clear link data and analyze fields in all content types, comments, custom
380    * blocks.
381    */
382   function submitClearAnalyzeLinks(array &$form, FormStateInterface $form_state) {
383     db_truncate('linkchecker_block_custom')->execute();
384     db_truncate('linkchecker_comment')->execute();
385     db_truncate('linkchecker_node')->execute();
386     db_truncate('linkchecker_link')->execute();
387
388     // Start batch and analyze all nodes.
389     $node_types = linkchecker_scan_node_types();
390     if (!empty($node_types)) {
391       module_load_include('inc', 'linkchecker', 'linkchecker.batch');
392       batch_set(_linkchecker_batch_import_nodes($node_types));
393     }
394
395     $comment_types = linkchecker_scan_comment_types();
396     if (!empty($comment_types)) {
397       module_load_include('inc', 'linkchecker', 'linkchecker.batch');
398       batch_set(_linkchecker_batch_import_comments($comment_types));
399     }
400
401     if ($this->config('linkchecker.settings')->get('scan_blocks')) {
402       module_load_include('inc', 'linkchecker', 'linkchecker.batch');
403       batch_set(_linkchecker_batch_import_block_custom());
404     }
405   }
406
407 }