Including security review as a submodule - with patched for Yaffs.
[yaffs-website] / web / modules / contrib / devel / devel.module
1 <?php
2
3 /**
4  * @file
5  * This module holds functions useful for Drupal development.
6  * Please contribute!
7  */
8
9 define('DEVEL_ERROR_HANDLER_NONE', 0);
10 define('DEVEL_ERROR_HANDLER_STANDARD', 1);
11 define('DEVEL_ERROR_HANDLER_BACKTRACE_KINT', 2);
12 define('DEVEL_ERROR_HANDLER_BACKTRACE_DPM', 4);
13
14 define('DEVEL_MIN_TEXTAREA', 50);
15
16 use Drupal\comment\CommentInterface;
17 use Drupal\Core\Database\Database;
18 use Drupal\Core\Database\Query\AlterableInterface;
19 use Drupal\Core\Entity\EntityInterface;
20 use Drupal\Core\Form\FormStateInterface;
21 use Drupal\Core\Logger\RfcLogLevel;
22 use Drupal\Core\Menu\LocalTaskDefault;
23 use Drupal\Core\Render\Element;
24 use Drupal\Core\Routing\RouteMatchInterface;
25 use Drupal\Core\Url;
26 use Drupal\Core\Utility\Error;
27 use Drupal\devel\EntityTypeInfo;
28 use Drupal\devel\ToolbarHandler;
29
30 /**
31  * Implements hook_help().
32  */
33 function devel_help($route_name, RouteMatchInterface $route_match) {
34   switch ($route_name) {
35     case 'help.page.devel':
36       $output = '';
37       $output .= '<h3>' . t('About') . '</h3>';
38       $output .= '<p>' . t('The Devel module provides a suite of modules containing fun for module developers and themers. For more information, see the <a href=":url">online documentation for the Devel module</a>.', [':url' => 'https://www.drupal.org/docs/8/modules/devel']) . '</p>';
39       $output .= '<h3>' . t('Uses') . '</h3>';
40       $output .= '<dl>';
41       $output .= '<dt>' . t('Inspecting Service Container') . '</dt>';
42       $output .= '<dd>' . t('The module allows you to inspect Services and Parameters registered in the Service Container. You can see those informations on <a href=":url">Container info</a> page.', [':url' => Url::fromRoute('devel.container_info.service')->toString()]) . '</dd>';
43       $output .= '<dt>' . t('Inspecting Routes') . '</dt>';
44       $output .= '<dd>' . t('The module allows you to inspect routes information, gathering all routing data from <em>.routing.yml</em> files and from classes which subscribe to the route build/alter events. You can see those informations on <a href=":url">Routes info</a> page.', [':url' => Url::fromRoute('devel.route_info')->toString()]) . '</dd>';
45       $output .= '<dt>' . t('Inspecting Events') . '</dt>';
46       $output .= '<dd>' . t('The module allow you to inspect listeners registered in the event dispatcher. You can see those informations on <a href=":url">Events info</a> page.', [':url' => Url::fromRoute('devel.event_info')->toString()]) . '</dd>';
47       $output .= '</dl>';
48       return $output;
49
50     case 'devel.container_info.service':
51     case 'devel.container_info.parameter':
52       $output = '';
53       $output .= '<p>' . t('Displays Services and Parameters registered in the Service Container. For more informations on the Service Container, see the <a href=":url">Symfony online documentation</a>.', [':url' => 'http://symfony.com/doc/current/service_container.html']) . '</p>';
54       return $output;
55
56     case 'devel.route_info':
57       $output = '';
58       $output .= '<p>' . t('Displays registered routes for the site. For a complete overview of the routing system, see the <a href=":url">online documentation</a>.', [':url' => 'https://www.drupal.org/docs/8/api/routing-system']) . '</p>';
59       return $output;
60
61     case 'devel.event_info':
62       $output = '';
63       $output .= '<p>' . t('Displays events and listeners registered in the event dispatcher. For a complete overview of the event system, see the <a href=":url">Symfony online documentation</a>.', [':url' => 'http://symfony.com/doc/current/components/event_dispatcher.html']) . '</p>';
64       return $output;
65
66     case 'devel.reinstall':
67       $output = '<p>' . t('<strong>Warning</strong> - will delete your module tables and configuration.') . '</p>';
68       $output .= '<p>' . t('Uninstall and then install the selected modules. <code>hook_uninstall()</code> and <code>hook_install()</code> will be executed and the schema version number will be set to the most recent update number.') . '</p>';
69       return $output;
70
71     case 'devel/session':
72       return '<p>' . t('Here are the contents of your <code>$_SESSION</code> variable.') . '</p>';
73
74     case 'devel.state_system_page':
75       return '<p>' . t('This is a list of state variables and their values. For more information read online documentation of <a href=":documentation">State API in Drupal 8</a>.', array(':documentation' => "https://www.drupal.org/developing/api/8/state")) . '</p>';
76
77   }
78 }
79
80 /**
81  * Implements hook_entity_type_alter().
82  */
83 function devel_entity_type_alter(array &$entity_types) {
84   return \Drupal::service('class_resolver')
85     ->getInstanceFromDefinition(EntityTypeInfo::class)
86     ->entityTypeAlter($entity_types);
87 }
88
89 /**
90  * Implements hook_entity_operation().
91  */
92 function devel_entity_operation(EntityInterface $entity) {
93   return \Drupal::service('class_resolver')
94     ->getInstanceFromDefinition(EntityTypeInfo::class)
95     ->entityOperation($entity);
96 }
97
98 /**
99  * Implements hook_toolbar().
100  */
101 function devel_toolbar() {
102   return \Drupal::service('class_resolver')
103     ->getInstanceFromDefinition(ToolbarHandler::class)
104     ->toolbar();
105 }
106
107 /**
108  * Implements hook_local_tasks_alter().
109  */
110 function devel_local_tasks_alter(&$local_tasks) {
111   if (\Drupal::moduleHandler()->moduleExists('toolbar')) {
112     $local_tasks['devel.toolbar.settings_form'] = [
113       'title' => 'Toolbar Settings',
114       'base_route' => 'devel.admin_settings',
115       'route_name' => 'devel.toolbar.settings_form',
116       'class' => LocalTaskDefault::class,
117       'options' => [],
118     ];
119   }
120 }
121
122 /**
123  * Sets message.
124  */
125 function devel_set_message($msg, $type = NULL) {
126   if (function_exists('drush_log')) {
127     drush_log($msg, $type);
128   }
129   else {
130     drupal_set_message($msg, $type, TRUE);
131   }
132 }
133
134 /**
135  * Gets error handlers.
136  */
137 function devel_get_handlers() {
138   $error_handlers = \Drupal::config('devel.settings')->get('error_handlers');
139   if (!empty($error_handlers)) {
140     unset($error_handlers[DEVEL_ERROR_HANDLER_NONE]);
141   }
142   return $error_handlers;
143 }
144
145 /**
146  * Sets a new error handler or restores the prior one.
147  */
148 function devel_set_handler($handlers) {
149   if (empty($handlers)) {
150     restore_error_handler();
151   }
152   elseif (count($handlers) == 1 && isset($handlers[DEVEL_ERROR_HANDLER_STANDARD])) {
153     // Do nothing.
154   }
155   else {
156     set_error_handler('backtrace_error_handler');
157   }
158 }
159
160 /**
161  * Displays backtrace showing the route of calls to the current error.
162  *
163  * @param int $error_level
164  *   The level of the error raised.
165  * @param string $message
166  *   The error message.
167  * @param string $filename
168  *   The filename that the error was raised in.
169  * @param int $line
170  *   The line number the error was raised at.
171  * @param array $context
172  *   An array that points to the active symbol table at the point the error
173  *   occurred.
174  */
175 function backtrace_error_handler($error_level, $message, $filename, $line, $context) {
176   // Hide stack trace and parameters from unqualified users.
177   if (!\Drupal::currentUser()->hasPermission('access devel information')) {
178     // Do what core does in bootstrap.inc and errors.inc.
179     // (We need to duplicate the core code here rather than calling it
180     // to avoid having the backtrace_error_handler() on top of the call stack.)
181     if ($error_level & error_reporting()) {
182       $types = drupal_error_levels();
183       list($severity_msg, $severity_level) = $types[$error_level];
184       $backtrace = debug_backtrace();
185       $caller = Error::getLastCaller($backtrace);
186
187       // We treat recoverable errors as fatal.
188       _drupal_log_error(array(
189         '%type' => isset($types[$error_level]) ? $severity_msg : 'Unknown error',
190         '@message' => $message,
191         '%function' => $caller['function'],
192         '%file' => $caller['file'],
193         '%line' => $caller['line'],
194         'severity_level' => $severity_level,
195         'backtrace' => $backtrace,
196       ), $error_level == E_RECOVERABLE_ERROR);
197     }
198
199     return;
200   }
201
202   // Don't respond to the error if it was suppressed with a '@'
203   if (error_reporting() == 0) {
204     return;
205   }
206
207   // Don't respond to warning caused by ourselves.
208   if (preg_match('#Cannot modify header information - headers already sent by \\([^\\)]*[/\\\\]devel[/\\\\]#', $message)) {
209     return;
210   }
211
212   if ($error_level & error_reporting()) {
213     // Only write each distinct NOTICE message once, as repeats do not give any
214     // further information and can choke the page output.
215     if ($error_level == E_NOTICE) {
216       static $written = array();
217       if (!empty($written[$line][$filename][$message])) {
218         return;
219       }
220       $written[$line][$filename][$message] = TRUE;
221     }
222
223     $types = drupal_error_levels();
224     list($severity_msg, $severity_level) = $types[$error_level];
225
226     $backtrace = debug_backtrace();
227     $caller = Error::getLastCaller($backtrace);
228     $variables = array(
229       '%type' => isset($types[$error_level]) ? $severity_msg : 'Unknown error',
230       '@message' => $message,
231       '%function' => $caller['function'],
232       '%file' => $caller['file'],
233       '%line' => $caller['line'],
234     );
235     $msg = t('%type: @message in %function (line %line of %file).', $variables);
236
237     // Show message if error_level is ERROR_REPORTING_DISPLAY_SOME or higher.
238     // (This is Drupal's error_level, which is different from $error_level,
239     // and we purposely ignore the difference between _SOME and _ALL,
240     // see #970688!)
241     if (\Drupal::config('system.logging')->get('error_level') != 'hide') {
242       $error_handlers = devel_get_handlers();
243       if (!empty($error_handlers[DEVEL_ERROR_HANDLER_STANDARD])) {
244         drupal_set_message($msg, ($severity_level <= RfcLogLevel::NOTICE ? 'error' : 'warning'), TRUE);
245       }
246       if (!empty($error_handlers[DEVEL_ERROR_HANDLER_BACKTRACE_KINT])) {
247         print kpr(ddebug_backtrace(TRUE, 1), TRUE, $msg);
248       }
249       if (!empty($error_handlers[DEVEL_ERROR_HANDLER_BACKTRACE_DPM])) {
250         dpm(ddebug_backtrace(TRUE, 1), $msg, 'warning');
251       }
252     }
253
254     \Drupal::logger('php')->log($severity_level, $msg);
255   }
256 }
257
258 /**
259  * Implements hook_page_attachments_alter().
260  */
261 function devel_page_attachments_alter(&$page) {
262   if (\Drupal::currentUser()->hasPermission('access devel information') && \Drupal::config('devel.settings')->get('page_alter')) {
263     dpm($page, 'page');
264   }
265 }
266
267 /**
268  * Wrapper for DevelDumperManager::dump().
269  *
270  * Calls the http://www.firephp.org/ fb() function if it is found.
271  *
272  * @see \Drupal\devel\DevelDumperManager::dump()
273  */
274 function dfb() {
275   $args = func_get_args();
276   \Drupal::service('devel.dumper')->dump($args, NULL, 'firephp');
277 }
278
279 /**
280  * Wrapper for DevelDumperManager::dump().
281  *
282  * Calls dfb() to output a backtrace.
283  *
284  * @see \Drupal\devel\DevelDumperManager::dump()
285  */
286 function dfbt($label) {
287   \Drupal::service('devel.dumper')->dump(FirePHP::TRACE, $label, 'firephp');
288 }
289
290 /**
291  * Wrapper for DevelDumperManager::dump().
292  *
293  * Wrapper for ChromePHP Class log method.
294  *
295  * @see \Drupal\devel\DevelDumperManager::dump()
296  */
297 function dcp() {
298   $args = func_get_args();
299   \Drupal::service('devel.dumper')->dump($args, NULL, 'chromephp');
300 }
301
302 if (!function_exists('dd')) {
303   /**
304    * Wrapper for DevelDumperManager::debug().
305    *
306    * @see \Drupal\devel\DevelDumperManager::debug()
307    */
308   function dd($data, $label = NULL) {
309     return \Drupal::service('devel.dumper')->debug($data, $label, 'default');
310   }
311 }
312
313 /**
314  * Wrapper for DevelDumperManager::message().
315  *
316  * Prints a variable to the 'message' area of the page.
317  *
318  * Uses drupal_set_message().
319  *
320  * @param $input
321  *   An arbitrary value to output.
322  * @param string $name
323  *   Optional name for identifying the output.
324  * @param string $type
325  *   Optional message type for drupal_set_message(), defaults to 'status'.
326  *
327  * @return input
328  *   The unaltered input value.
329  *
330  * @see \Drupal\devel\DevelDumperManager::message()
331  */
332 function dpm($input, $name = NULL, $type = 'status') {
333   \Drupal::service('devel.dumper')->message($input, $name, $type);
334   return $input;
335 }
336
337 /**
338  * Wrapper for DevelDumperManager::message().
339  *
340  * Displays a Variable::export() variable to the 'message' area of the page.
341  *
342  * Uses drupal_set_message().
343  *
344  * @param $input
345  *   An arbitrary value to output.
346  * @param string $name
347  *   Optional name for identifying the output.
348  *
349  * @return input
350  *   The unaltered input value.
351  *
352  * @see \Drupal\devel\DevelDumperManager::message()
353  */
354 function dvm($input, $name = NULL) {
355   \Drupal::service('devel.dumper')->message($input, $name, 'status', 'drupal_variable');
356   return $input;
357 }
358
359 /**
360  * An alias for dpm(), for historic reasons.
361  */
362 function dsm($input, $name = NULL) {
363   return dpm($input, $name);
364 }
365
366 /**
367  * Wrapper for DevelDumperManager::dumpOrExport().
368  *
369  * An alias for the devel.dumper service. Saves carpal tunnel syndrome.
370  *
371  * @see \Drupal\devel\DevelDumperManager::dumpOrExport()
372  */
373 function dpr($input, $export = FALSE, $name = NULL) {
374   return \Drupal::service('devel.dumper')->dumpOrExport($input, $name, $export, 'default');
375 }
376
377 /**
378  * Wrapper for DevelDumperManager::dumpOrExport().
379  *
380  * An alias for devel_dump(). Saves carpal tunnel syndrome.
381  *
382  * @see \Drupal\devel\DevelDumperManager::dumpOrExport()
383  */
384 function kpr($input, $export = FALSE, $name = NULL) {
385   return \Drupal::service('devel.dumper')->dumpOrExport($input, $name, $export);
386 }
387
388 /**
389  * Wrapper for DevelDumperManager::dumpOrExport().
390  *
391  * Like dpr(), but uses Variable::export() instead.
392  *
393  * @see \Drupal\devel\DevelDumperManager::dumpOrExport()
394  */
395 function dvr($input, $export = FALSE, $name = NULL) {
396   return \Drupal::service('devel.dumper')->dumpOrExport($input, $name, $export, 'drupal_variable');
397 }
398
399 /**
400  * Prints the arguments passed into the current function.
401  */
402 function dargs($always = TRUE) {
403   static $printed;
404   if ($always || !$printed) {
405     $bt = debug_backtrace();
406     print kpr($bt[1]['args'], TRUE);
407     $printed = TRUE;
408   }
409 }
410
411 /**
412  * Prints a SQL string from a DBTNG Select object. Includes quoted arguments.
413  *
414  * @param object $query
415  *   An object that implements the SelectInterface interface.
416  * @param boolean $return
417  *   Whether to return the string. Default is FALSE, meaning to print it
418  *   and return $query instead.
419  * @param string $name
420  *   Optional name for identifying the output.
421  *
422  * @return object|string
423  *   The $query object, or the query string if $return was TRUE.
424  */
425 function dpq($query, $return = FALSE, $name = NULL) {
426   if (\Drupal::currentUser()->hasPermission('access devel information')) {
427     if (method_exists($query, 'preExecute')) {
428       $query->preExecute();
429     }
430     $sql = (string) $query;
431     $quoted = array();
432     $connection = Database::getConnection();
433     foreach ((array) $query->arguments() as $key => $val) {
434       $quoted[$key] = is_null($val) ? 'NULL' : $connection->quote($val);
435     }
436     $sql = strtr($sql, $quoted);
437     if ($return) {
438       return $sql;
439     }
440     dpm($sql, $name);
441   }
442   return ($return ? NULL : $query);
443 }
444
445 /**
446  * Prints a renderable array element to the screen using kprint_r().
447  *
448  * #pre_render and/or #post_render pass-through callback for kprint_r().
449  *
450  * @todo Investigate appending to #suffix.
451  * @todo Investigate label derived from #id, #title, #name, and #theme.
452  */
453 function devel_render() {
454   $args = func_get_args();
455   // #pre_render and #post_render pass the rendered $element as last argument.
456   kpr(end($args));
457   // #pre_render and #post_render expect the first argument to be returned.
458   return reset($args);
459 }
460
461 /**
462  * Prints the function call stack.
463  *
464  * @param $return
465  *   Pass TRUE to return the formatted backtrace rather than displaying it in
466  *   the browser via kprint_r().
467  * @param $pop
468  *   How many items to pop from the top of the stack; useful when calling from
469  *   an error handler.
470  * @param $options
471  *   Options to pass on to PHP's debug_backtrace().
472  *
473  * @return string|NULL
474  *   The formatted backtrace, if requested, or NULL.
475  *
476  * @see http://php.net/manual/en/function.debug-backtrace.php
477  */
478 function ddebug_backtrace($return = FALSE, $pop = 0, $options = DEBUG_BACKTRACE_PROVIDE_OBJECT) {
479   if (\Drupal::currentUser()->hasPermission('access devel information')) {
480     $backtrace = debug_backtrace($options);
481     while ($pop-- > 0) {
482       array_shift($backtrace);
483     }
484     $counter = count($backtrace);
485     $path = $backtrace[$counter - 1]['file'];
486     $path = substr($path, 0, strlen($path) - 10);
487     $paths[$path] = strlen($path) + 1;
488     $paths[DRUPAL_ROOT] = strlen(DRUPAL_ROOT) + 1;
489     $nbsp = "\xC2\xA0";
490
491     // Show message if error_level is ERROR_REPORTING_DISPLAY_SOME or higher.
492     // (This is Drupal's error_level, which is different from $error_level,
493     // and we purposely ignore the difference between _SOME and _ALL,
494     // see #970688!)
495     if (\Drupal::config('system.logging')->get('error_level') != 'hide') {
496       while (!empty($backtrace)) {
497         $call = array();
498         if (isset($backtrace[0]['file'])) {
499           $call['file'] = $backtrace[0]['file'];
500           foreach ($paths as $path => $len) {
501             if (strpos($backtrace[0]['file'], $path) === 0) {
502               $call['file'] = substr($backtrace[0]['file'], $len);
503             }
504           }
505           $call['file'] .= ':' . $backtrace[0]['line'];
506         }
507         if (isset($backtrace[1])) {
508           if (isset($backtrace[1]['class'])) {
509             $function = $backtrace[1]['class'] . $backtrace[1]['type'] . $backtrace[1]['function'] . '()';
510           }
511           else {
512             $function = $backtrace[1]['function'] . '()';
513           }
514           $backtrace[1] += array('args' => array());
515           foreach ($backtrace[1]['args'] as $key => $value) {
516             $call['args'][$key] = $value;
517           }
518         }
519         else {
520           $function = 'main()';
521           $call['args'] = $_GET;
522         }
523         $nicetrace[($counter <= 10 ? $nbsp : '') . --$counter . ': ' . $function] = $call;
524         array_shift($backtrace);
525       }
526       if ($return) {
527         return $nicetrace;
528       }
529       kpr($nicetrace);
530     }
531   }
532 }
533
534 /*
535  * Migration-related functions.
536  */
537
538 /**
539  * Regenerates the data in node_comment_statistics table.
540  * Technique - http://www.artfulsoftware.com/infotree/queries.php?&bw=1280#101
541  *
542  * @return void
543  */
544 function devel_rebuild_node_comment_statistics() {
545   // Empty table.
546   db_truncate('node_comment_statistics')->execute();
547
548   // TODO: DBTNG. Ignore keyword is Mysql only? Is only used in the rare case
549   // when two comments on the same node share same timestamp.
550   $sql = "
551     INSERT IGNORE INTO {node_comment_statistics} (nid, cid, last_comment_timestamp, last_comment_name, last_comment_uid, comment_count) (
552       SELECT c.nid, c.cid, c.created, c.name, c.uid, c2.comment_count FROM {comment} c
553       JOIN (
554         SELECT c.nid, MAX(c.created) AS created, COUNT(*) AS comment_count FROM {comment} c WHERE status = 1 GROUP BY c.nid
555       ) AS c2 ON c.nid = c2.nid AND c.created = c2.created
556     )";
557   db_query($sql, array(':published' => CommentInterface::PUBLISHED));
558
559   // Insert records into the node_comment_statistics for nodes that are missing.
560   $query = db_select('node', 'n');
561   $query->leftJoin('node_comment_statistics', 'ncs', 'ncs.nid = n.nid');
562   $query->addField('n', 'changed', 'last_comment_timestamp');
563   $query->addField('n', 'uid', 'last_comment_uid');
564   $query->addField('n', 'nid');
565   $query->addExpression('0', 'comment_count');
566   $query->addExpression('NULL', 'last_comment_name');
567   $query->isNull('ncs.comment_count');
568
569   db_insert('node_comment_statistics', array('return' => Database::RETURN_NULL))
570     ->from($query)
571     ->execute();
572 }
573
574 /**
575  * Implements hook_form_FORM_ID_alter().
576  *
577  * Adds mouse-over hints on the Permissions page to display
578  * language-independent machine names and module base names.
579  *
580  * @see \Drupal\user\Form\UserPermissionsForm::buildForm()
581  */
582 function devel_form_user_admin_permissions_alter(&$form, FormStateInterface $form_state) {
583   if (\Drupal::currentUser()->hasPermission('access devel information') && \Drupal::config('devel.settings')->get('raw_names')) {
584     foreach (Element::children($form['permissions']) as $key) {
585       if (isset($form['permissions'][$key][0])) {
586         $form['permissions'][$key][0]['#wrapper_attributes']['title'] = $key;
587       }
588       elseif(isset($form['permissions'][$key]['description'])) {
589         $form['permissions'][$key]['description']['#wrapper_attributes']['title']  = $key;
590       }
591     }
592   }
593 }
594
595 /**
596  * Implements hook_form_FORM_ID_alter().
597  *
598  * Adds mouse-over hints on the Modules page to display module base names.
599  *
600  * @see \Drupal\system\Form\ModulesListForm::buildForm()
601  * @see theme_system_modules_details()
602  */
603 function devel_form_system_modules_alter(&$form, FormStateInterface $form_state) {
604   if (\Drupal::currentUser()->hasPermission('access devel information') && \Drupal::config('devel.settings')->get('raw_names', FALSE) && isset($form['modules']) && is_array($form['modules'])) {
605     foreach (Element::children($form['modules']) as $group) {
606       if (is_array($form['modules'][$group])) {
607         foreach (Element::children($form['modules'][$group]) as $key) {
608           if (isset($form['modules'][$group][$key]['name']['#markup'])) {
609             $form['modules'][$group][$key]['name']['#markup'] = '<span title="' . $key . '">' . $form['modules'][$group][$key]['name']['#markup'] . '</span>';
610           }
611         }
612       }
613     }
614   }
615 }
616
617 /**
618  * Implements hook_query_TAG_alter().
619  *
620  * Makes debugging entity query much easier.
621  *
622  * Example usage:
623  * @code
624  * $query = \Drupal::entityQuery('node');
625  * $query->condition('status', NODE_PUBLISHED);
626  * $query->addTag('debug');
627  * $query->execute();
628  * @endcode
629  */
630 function devel_query_debug_alter(AlterableInterface $query) {
631   if (!$query->hasTag('debug-semaphore')) {
632     $query->addTag('debug-semaphore');
633     dpq($query);
634   }
635 }