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