5 * This module holds functions useful for Drupal development.
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);
14 define('DEVEL_MIN_TEXTAREA', 50);
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;
26 use Drupal\Core\Utility\Error;
27 use Drupal\devel\EntityTypeInfo;
28 use Drupal\devel\ToolbarHandler;
31 * Implements hook_help().
33 function devel_help($route_name, RouteMatchInterface $route_match) {
34 switch ($route_name) {
35 case 'help.page.devel':
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>';
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>';
50 case 'devel.container_info.service':
51 case 'devel.container_info.parameter':
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>';
56 case 'devel.route_info':
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>';
61 case 'devel.event_info':
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>';
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>';
72 return '<p>' . t('Here are the contents of your <code>$_SESSION</code> variable.') . '</p>';
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>';
81 * Implements hook_entity_type_alter().
83 function devel_entity_type_alter(array &$entity_types) {
84 return \Drupal::service('class_resolver')
85 ->getInstanceFromDefinition(EntityTypeInfo::class)
86 ->entityTypeAlter($entity_types);
90 * Implements hook_entity_operation().
92 function devel_entity_operation(EntityInterface $entity) {
93 return \Drupal::service('class_resolver')
94 ->getInstanceFromDefinition(EntityTypeInfo::class)
95 ->entityOperation($entity);
99 * Implements hook_toolbar().
101 function devel_toolbar() {
102 return \Drupal::service('class_resolver')
103 ->getInstanceFromDefinition(ToolbarHandler::class)
108 * Implements hook_local_tasks_alter().
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,
125 function devel_set_message($msg, $type = NULL) {
126 if (function_exists('drush_log')) {
127 drush_log($msg, $type);
130 drupal_set_message($msg, $type, TRUE);
135 * Gets error handlers.
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]);
142 return $error_handlers;
146 * Sets a new error handler or restores the prior one.
148 function devel_set_handler($handlers) {
149 if (empty($handlers)) {
150 restore_error_handler();
152 elseif (count($handlers) == 1 && isset($handlers[DEVEL_ERROR_HANDLER_STANDARD])) {
156 set_error_handler('backtrace_error_handler');
161 * Displays backtrace showing the route of calls to the current error.
163 * @param int $error_level
164 * The level of the error raised.
165 * @param string $message
167 * @param string $filename
168 * The filename that the error was raised in.
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
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);
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);
202 // Don't respond to the error if it was suppressed with a '@'
203 if (error_reporting() == 0) {
207 // Don't respond to warning caused by ourselves.
208 if (preg_match('#Cannot modify header information - headers already sent by \\([^\\)]*[/\\\\]devel[/\\\\]#', $message)) {
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])) {
220 $written[$line][$filename][$message] = TRUE;
223 $types = drupal_error_levels();
224 list($severity_msg, $severity_level) = $types[$error_level];
226 $backtrace = debug_backtrace();
227 $caller = Error::getLastCaller($backtrace);
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'],
235 $msg = t('%type: @message in %function (line %line of %file).', $variables);
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,
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);
246 if (!empty($error_handlers[DEVEL_ERROR_HANDLER_BACKTRACE_KINT])) {
247 print kpr(ddebug_backtrace(TRUE, 1), TRUE, $msg);
249 if (!empty($error_handlers[DEVEL_ERROR_HANDLER_BACKTRACE_DPM])) {
250 dpm(ddebug_backtrace(TRUE, 1), $msg, 'warning');
254 \Drupal::logger('php')->log($severity_level, $msg);
259 * Implements hook_page_attachments_alter().
261 function devel_page_attachments_alter(&$page) {
262 if (\Drupal::currentUser()->hasPermission('access devel information') && \Drupal::config('devel.settings')->get('page_alter')) {
268 * Wrapper for DevelDumperManager::dump().
270 * Calls the http://www.firephp.org/ fb() function if it is found.
272 * @see \Drupal\devel\DevelDumperManager::dump()
275 $args = func_get_args();
276 \Drupal::service('devel.dumper')->dump($args, NULL, 'firephp');
280 * Wrapper for DevelDumperManager::dump().
282 * Calls dfb() to output a backtrace.
284 * @see \Drupal\devel\DevelDumperManager::dump()
286 function dfbt($label) {
287 \Drupal::service('devel.dumper')->dump(FirePHP::TRACE, $label, 'firephp');
291 * Wrapper for DevelDumperManager::dump().
293 * Wrapper for ChromePHP Class log method.
295 * @see \Drupal\devel\DevelDumperManager::dump()
298 $args = func_get_args();
299 \Drupal::service('devel.dumper')->dump($args, NULL, 'chromephp');
302 if (!function_exists('dd')) {
304 * Wrapper for DevelDumperManager::debug().
306 * @see \Drupal\devel\DevelDumperManager::debug()
308 function dd($data, $label = NULL) {
309 return \Drupal::service('devel.dumper')->debug($data, $label, 'default');
314 * Wrapper for DevelDumperManager::message().
316 * Prints a variable to the 'message' area of the page.
318 * Uses drupal_set_message().
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'.
328 * The unaltered input value.
330 * @see \Drupal\devel\DevelDumperManager::message()
332 function dpm($input, $name = NULL, $type = 'status') {
333 \Drupal::service('devel.dumper')->message($input, $name, $type);
338 * Wrapper for DevelDumperManager::message().
340 * Displays a Variable::export() variable to the 'message' area of the page.
342 * Uses drupal_set_message().
345 * An arbitrary value to output.
346 * @param string $name
347 * Optional name for identifying the output.
350 * The unaltered input value.
352 * @see \Drupal\devel\DevelDumperManager::message()
354 function dvm($input, $name = NULL) {
355 \Drupal::service('devel.dumper')->message($input, $name, 'status', 'drupal_variable');
360 * An alias for dpm(), for historic reasons.
362 function dsm($input, $name = NULL) {
363 return dpm($input, $name);
367 * Wrapper for DevelDumperManager::dumpOrExport().
369 * An alias for the devel.dumper service. Saves carpal tunnel syndrome.
371 * @see \Drupal\devel\DevelDumperManager::dumpOrExport()
373 function dpr($input, $export = FALSE, $name = NULL) {
374 return \Drupal::service('devel.dumper')->dumpOrExport($input, $name, $export, 'default');
378 * Wrapper for DevelDumperManager::dumpOrExport().
380 * An alias for devel_dump(). Saves carpal tunnel syndrome.
382 * @see \Drupal\devel\DevelDumperManager::dumpOrExport()
384 function kpr($input, $export = FALSE, $name = NULL) {
385 return \Drupal::service('devel.dumper')->dumpOrExport($input, $name, $export);
389 * Wrapper for DevelDumperManager::dumpOrExport().
391 * Like dpr(), but uses Variable::export() instead.
393 * @see \Drupal\devel\DevelDumperManager::dumpOrExport()
395 function dvr($input, $export = FALSE, $name = NULL) {
396 return \Drupal::service('devel.dumper')->dumpOrExport($input, $name, $export, 'drupal_variable');
400 * Prints the arguments passed into the current function.
402 function dargs($always = TRUE) {
404 if ($always || !$printed) {
405 $bt = debug_backtrace();
406 print kpr($bt[1]['args'], TRUE);
412 * Prints a SQL string from a DBTNG Select object. Includes quoted arguments.
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.
422 * @return object|string
423 * The $query object, or the query string if $return was TRUE.
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();
430 $sql = (string) $query;
432 $connection = Database::getConnection();
433 foreach ((array) $query->arguments() as $key => $val) {
434 $quoted[$key] = is_null($val) ? 'NULL' : $connection->quote($val);
436 $sql = strtr($sql, $quoted);
442 return ($return ? NULL : $query);
446 * Prints a renderable array element to the screen using kprint_r().
448 * #pre_render and/or #post_render pass-through callback for kprint_r().
450 * @todo Investigate appending to #suffix.
451 * @todo Investigate label derived from #id, #title, #name, and #theme.
453 function devel_render() {
454 $args = func_get_args();
455 // #pre_render and #post_render pass the rendered $element as last argument.
457 // #pre_render and #post_render expect the first argument to be returned.
462 * Prints the function call stack.
465 * Pass TRUE to return the formatted backtrace rather than displaying it in
466 * the browser via kprint_r().
468 * How many items to pop from the top of the stack; useful when calling from
471 * Options to pass on to PHP's debug_backtrace().
473 * @return string|NULL
474 * The formatted backtrace, if requested, or NULL.
476 * @see http://php.net/manual/en/function.debug-backtrace.php
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);
482 array_shift($backtrace);
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;
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,
495 if (\Drupal::config('system.logging')->get('error_level') != 'hide') {
496 while (!empty($backtrace)) {
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);
505 $call['file'] .= ':' . $backtrace[0]['line'];
507 if (isset($backtrace[1])) {
508 if (isset($backtrace[1]['class'])) {
509 $function = $backtrace[1]['class'] . $backtrace[1]['type'] . $backtrace[1]['function'] . '()';
512 $function = $backtrace[1]['function'] . '()';
514 $backtrace[1] += array('args' => array());
515 foreach ($backtrace[1]['args'] as $key => $value) {
516 $call['args'][$key] = $value;
520 $function = 'main()';
521 $call['args'] = $_GET;
523 $nicetrace[($counter <= 10 ? $nbsp : '') . --$counter . ': ' . $function] = $call;
524 array_shift($backtrace);
535 * Migration-related functions.
539 * Regenerates the data in node_comment_statistics table.
540 * Technique - http://www.artfulsoftware.com/infotree/queries.php?&bw=1280#101
544 function devel_rebuild_node_comment_statistics() {
546 db_truncate('node_comment_statistics')->execute();
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.
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
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
557 db_query($sql, array(':published' => CommentInterface::PUBLISHED));
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');
569 db_insert('node_comment_statistics', array('return' => Database::RETURN_NULL))
575 * Implements hook_form_FORM_ID_alter().
577 * Adds mouse-over hints on the Permissions page to display
578 * language-independent machine names and module base names.
580 * @see \Drupal\user\Form\UserPermissionsForm::buildForm()
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;
588 elseif(isset($form['permissions'][$key]['description'])) {
589 $form['permissions'][$key]['description']['#wrapper_attributes']['title'] = $key;
596 * Implements hook_form_FORM_ID_alter().
598 * Adds mouse-over hints on the Modules page to display module base names.
600 * @see \Drupal\system\Form\ModulesListForm::buildForm()
601 * @see theme_system_modules_details()
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>';
618 * Implements hook_query_TAG_alter().
620 * Makes debugging entity query much easier.
624 * $query = \Drupal::entityQuery('node');
625 * $query->condition('status', NODE_PUBLISHED);
626 * $query->addTag('debug');
630 function devel_query_debug_alter(AlterableInterface $query) {
631 if (!$query->hasTag('debug-semaphore')) {
632 $query->addTag('debug-semaphore');