Files
edlp_d8/sites/all/modules/contrib/dev/devel/devel.module
T

627 lines
20 KiB
Plaintext

<?php
/**
* @file
* This module holds functions useful for Drupal development.
* Please contribute!
*/
define('DEVEL_ERROR_HANDLER_NONE', 0);
define('DEVEL_ERROR_HANDLER_STANDARD', 1);
define('DEVEL_ERROR_HANDLER_BACKTRACE_KINT', 2);
define('DEVEL_ERROR_HANDLER_BACKTRACE_DPM', 4);
define('DEVEL_MIN_TEXTAREA', 50);
use Drupal\comment\CommentInterface;
use Drupal\Core\Database\Database;
use Drupal\Core\Database\Query\AlterableInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\Render\Element;
use Drupal\Core\Utility\Error;
/**
* Implements hook_help().
*/
function devel_help($route_name) {
switch ($route_name) {
case 'devel.reinstall':
$output = '<p>' . t('<strong>Warning</strong> - will delete your module tables and configuration.') . '</p>';
$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>';
return $output;
case 'devel/session':
return '<p>' . t('Here are the contents of your <code>$_SESSION</code> variable.') . '</p>';
case 'devel.state_system_page':
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>';
}
}
/**
* Implements hook_entity_type_alter().
*/
function devel_entity_type_alter(array &$entity_types) {
/** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
foreach ($entity_types as $entity_type_id => $entity_type) {
if ($entity_type->hasViewBuilderClass() && $entity_type->hasLinkTemplate('canonical')) {
$entity_type->setLinkTemplate('devel-render', "/devel/$entity_type_id/{{$entity_type_id}}/render");
}
if (($entity_type->getFormClass('default') || $entity_type->getFormClass('edit')) && $entity_type->hasLinkTemplate('edit-form')) {
$entity_type->setLinkTemplate('devel-load', "/devel/$entity_type_id/{{$entity_type_id}}");
}
}
}
/**
* Implements hook_entity_operation().
*/
function devel_entity_operation(EntityInterface $entity) {
$operations = array();
if (\Drupal::currentUser()->hasPermission('access devel information')) {
if ($entity->hasLinkTemplate('devel-load')) {
$operations['devel'] = array(
'title' => t('Devel'),
'weight' => 100,
'url' => $entity->toUrl('devel-load'),
);
}
elseif ($entity->hasLinkTemplate('devel-render')) {
$operations['devel'] = array(
'title' => t('Devel'),
'weight' => 100,
'url' => $entity->toUrl('devel-render'),
);
}
}
return $operations;
}
/**
* Sets message.
*/
function devel_set_message($msg, $type = NULL) {
if (function_exists('drush_log')) {
drush_log($msg, $type);
}
else {
drupal_set_message($msg, $type, TRUE);
}
}
/**
* Gets error handlers.
*/
function devel_get_handlers() {
$error_handlers = \Drupal::config('devel.settings')->get('error_handlers');
if (!empty($error_handlers)) {
unset($error_handlers[DEVEL_ERROR_HANDLER_NONE]);
}
return $error_handlers;
}
/**
* Sets a new error handler or restores the prior one.
*/
function devel_set_handler($handlers) {
if (empty($handlers)) {
restore_error_handler();
}
elseif (count($handlers) == 1 && isset($handlers[DEVEL_ERROR_HANDLER_STANDARD])) {
// Do nothing.
}
else {
set_error_handler('backtrace_error_handler');
}
}
/**
* Displays backtrace showing the route of calls to the current error.
*
* @param int $error_level
* The level of the error raised.
* @param string $message
* The error message.
* @param string $filename
* The filename that the error was raised in.
* @param int $line
* The line number the error was raised at.
* @param array $context
* An array that points to the active symbol table at the point the error
* occurred.
*/
function backtrace_error_handler($error_level, $message, $filename, $line, $context) {
// Hide stack trace and parameters from unqualified users.
if (!\Drupal::currentUser()->hasPermission('access devel information')) {
// Do what core does in bootstrap.inc and errors.inc.
// (We need to duplicate the core code here rather than calling it
// to avoid having the backtrace_error_handler() on top of the call stack.)
if ($error_level & error_reporting()) {
$types = drupal_error_levels();
list($severity_msg, $severity_level) = $types[$error_level];
$backtrace = debug_backtrace();
$caller = Error::getLastCaller($backtrace);
// We treat recoverable errors as fatal.
_drupal_log_error(array(
'%type' => isset($types[$error_level]) ? $severity_msg : 'Unknown error',
'@message' => $message,
'%function' => $caller['function'],
'%file' => $caller['file'],
'%line' => $caller['line'],
'severity_level' => $severity_level,
'backtrace' => $backtrace,
), $error_level == E_RECOVERABLE_ERROR);
}
return;
}
// Don't respond to the error if it was suppressed with a '@'
if (error_reporting() == 0) {
return;
}
// Don't respond to warning caused by ourselves.
if (preg_match('#Cannot modify header information - headers already sent by \\([^\\)]*[/\\\\]devel[/\\\\]#', $message)) {
return;
}
if ($error_level & error_reporting()) {
// Only write each distinct NOTICE message once, as repeats do not give any
// further information and can choke the page output.
if ($error_level == E_NOTICE) {
static $written = array();
if (!empty($written[$line][$filename][$message])) {
return;
}
$written[$line][$filename][$message] = TRUE;
}
$types = drupal_error_levels();
list($severity_msg, $severity_level) = $types[$error_level];
$backtrace = debug_backtrace();
$caller = Error::getLastCaller($backtrace);
$variables = array(
'%type' => isset($types[$error_level]) ? $severity_msg : 'Unknown error',
'@message' => $message,
'%function' => $caller['function'],
'%file' => $caller['file'],
'%line' => $caller['line'],
);
$msg = t('%type: @message in %function (line %line of %file).', $variables);
// Show message if error_level is ERROR_REPORTING_DISPLAY_SOME or higher.
// (This is Drupal's error_level, which is different from $error_level,
// and we purposely ignore the difference between _SOME and _ALL,
// see #970688!)
if (\Drupal::config('system.logging')->get('error_level') != 'hide') {
$error_handlers = devel_get_handlers();
if (!empty($error_handlers[DEVEL_ERROR_HANDLER_STANDARD])) {
drupal_set_message($msg, ($severity_level <= RfcLogLevel::NOTICE ? 'error' : 'warning'), TRUE);
}
if (!empty($error_handlers[DEVEL_ERROR_HANDLER_BACKTRACE_KINT])) {
print kprint_r(ddebug_backtrace(TRUE, 1), $return = TRUE, $msg);
}
if (!empty($error_handlers[DEVEL_ERROR_HANDLER_BACKTRACE_DPM])) {
dpm(ddebug_backtrace(TRUE, 1), $msg, 'warning');
}
}
\Drupal::logger('php')->log($severity_level, $msg);
}
}
/**
* Implements hook_page_attachments_alter().
*/
function devel_page_attachments_alter(&$page) {
if (\Drupal::currentUser()->hasPermission('access devel information') && \Drupal::config('devel.settings')->get('page_alter')) {
dpm($page, 'page');
}
}
/**
* Prints an object using either Kint (if enabled) or devel_print_object().
*
* @param array|object $object
* An array or object to print.
* @param string $prefix
* @todo: this parameter is not needed with Kint.
* Prefix for output items.
*
* @deprecated in Devel 8.x-dev, will be removed before Devel 8.0.
* Use kpr() or devel.dumper service instead.
*
* @TODO remove in https://www.drupal.org/node/2703343
*/
function kdevel_print_object($object, $prefix = NULL) {
return kpr($object, TRUE, $prefix);
}
/**
* Wrapper for DevelDumperManager::dump().
*
* Calls the http://www.firephp.org/ fb() function if it is found.
*
* @see \Drupal\devel\DevelDumperManager::dump()
*/
function dfb() {
$args = func_get_args();
\Drupal::service('devel.dumper')->dump($args, NULL, 'firephp');
}
/**
* Wrapper for DevelDumperManager::dump().
*
* Calls dfb() to output a backtrace.
*
* @see \Drupal\devel\DevelDumperManager::dump()
*/
function dfbt($label) {
\Drupal::service('devel.dumper')->dump(FirePHP::TRACE, $label, 'firephp');
}
/**
* Wrapper for DevelDumperManager::dump().
*
* Wrapper for ChromePHP Class log method.
*
* @see \Drupal\devel\DevelDumperManager::dump()
*/
function dcp() {
$args = func_get_args();
\Drupal::service('devel.dumper')->dump($args, NULL, 'chromephp');
}
if (!function_exists('dd')) {
/**
* Wrapper for DevelDumperManager::debug().
*
* @see \Drupal\devel\DevelDumperManager::debug()
*/
function dd($data, $label = NULL) {
return \Drupal::service('devel.dumper')->debug($data, $label, 'default');
}
}
/**
* Wrapper for DevelDumperManager::message().
*
* Prints a variable to the 'message' area of the page.
*
* Uses drupal_set_message().
*
* @param $input
* An arbitrary value to output.
* @param string $name
* Optional name for identifying the output.
* @param string $type
* Optional message type for drupal_set_message(), defaults to 'status'.
*
* @return input
* The unaltered input value.
*
* @see \Drupal\devel\DevelDumperManager::message()
*/
function dpm($input, $name = NULL, $type = 'status') {
\Drupal::service('devel.dumper')->message($input, $name, $type);
return $input;
}
/**
* Wrapper for DevelDumperManager::message().
*
* Displays a Variable::export() variable to the 'message' area of the page.
*
* Uses drupal_set_message().
*
* @param $input
* An arbitrary value to output.
* @param string $name
* Optional name for identifying the output.
*
* @return input
* The unaltered input value.
*
* @see \Drupal\devel\DevelDumperManager::message()
*/
function dvm($input, $name = NULL) {
\Drupal::service('devel.dumper')->message($input, $name, 'status', 'drupal_variable');
return $input;
}
/**
* An alias for dpm(), for historic reasons.
*/
function dsm($input, $name = NULL) {
return dpm($input, $name);
}
/**
* Wrapper for DevelDumperManager::dumpOrExport().
*
* An alias for the devel.dumper service. Saves carpal tunnel syndrome.
*
* @see \Drupal\devel\DevelDumperManager::dumpOrExport()
*/
function dpr($input, $export = FALSE, $name = NULL) {
return \Drupal::service('devel.dumper')->dumpOrExport($input, $name, $export, 'default');
}
/**
* Wrapper for DevelDumperManager::dumpOrExport().
*
* An alias for devel_dump(). Saves carpal tunnel syndrome.
*
* @see \Drupal\devel\DevelDumperManager::dumpOrExport()
*/
function kpr($input, $export = FALSE, $name = NULL) {
return \Drupal::service('devel.dumper')->dumpOrExport($input, $name, $export);
}
/**
* Kint print.
*
* @deprecated in Devel 8.x-dev, will be removed before Devel 8.0.
* Use kpr() or devel.dumper service instead.
*
* @TODO remove in https://www.drupal.org/node/2703343
*/
function kprint_r($input, $export = FALSE, $name = NULL, $function = 'print_r') {
return kpr($input, $export, $name);
}
/**
* Wrapper for DevelDumperManager::dumpOrExport().
*
* Like dpr(), but uses Variable::export() instead.
*
* @see \Drupal\devel\DevelDumperManager::dumpOrExport()
*/
function dvr($input, $export = FALSE, $name = NULL) {
return \Drupal::service('devel.dumper')->dumpOrExport($input, $name, $export, 'drupal_variable');
}
/**
* Prints the arguments passed into the current function.
*/
function dargs($always = TRUE) {
static $printed;
if ($always || !$printed) {
$bt = debug_backtrace();
print kdevel_print_object($bt[1]['args']);
$printed = TRUE;
}
}
/**
* Prints a SQL string from a DBTNG Select object. Includes quoted arguments.
*
* @param object $query
* An object that implements the SelectInterface interface.
* @param boolean $return
* Whether to return the string. Default is FALSE, meaning to print it
* and return $query instead.
* @param string $name
* Optional name for identifying the output.
*
* @return object|string
* The $query object, or the query string if $return was TRUE.
*/
function dpq($query, $return = FALSE, $name = NULL) {
if (\Drupal::currentUser()->hasPermission('access devel information')) {
if (method_exists($query, 'preExecute')) {
$query->preExecute();
}
$sql = (string) $query;
$quoted = array();
$connection = Database::getConnection();
foreach ((array) $query->arguments() as $key => $val) {
$quoted[$key] = is_null($val) ? 'NULL' : $connection->quote($val);
}
$sql = strtr($sql, $quoted);
if ($return) {
return $sql;
}
dpm($sql, $name);
}
return ($return ? NULL : $query);
}
/**
* Prints a renderable array element to the screen using kprint_r().
*
* #pre_render and/or #post_render pass-through callback for kprint_r().
*
* @todo Investigate appending to #suffix.
* @todo Investigate label derived from #id, #title, #name, and #theme.
*/
function devel_render() {
$args = func_get_args();
// #pre_render and #post_render pass the rendered $element as last argument.
kprint_r(end($args));
// #pre_render and #post_render expect the first argument to be returned.
return reset($args);
}
/**
* Prints the function call stack.
*
* @param $return
* Pass TRUE to return the formatted backtrace rather than displaying it in
* the browser via kprint_r().
* @param $pop
* How many items to pop from the top of the stack; useful when calling from
* an error handler.
* @param $options
* Options to pass on to PHP's debug_backtrace().
*
* @return string|NULL
* The formatted backtrace, if requested, or NULL.
*
* @see http://php.net/manual/en/function.debug-backtrace.php
*/
function ddebug_backtrace($return = FALSE, $pop = 0, $options = DEBUG_BACKTRACE_PROVIDE_OBJECT) {
if (\Drupal::currentUser()->hasPermission('access devel information')) {
$backtrace = debug_backtrace($options);
while ($pop-- > 0) {
array_shift($backtrace);
}
$counter = count($backtrace);
$path = $backtrace[$counter - 1]['file'];
$path = substr($path, 0, strlen($path) - 10);
$paths[$path] = strlen($path) + 1;
$paths[DRUPAL_ROOT] = strlen(DRUPAL_ROOT) + 1;
$nbsp = "\xC2\xA0";
// Show message if error_level is ERROR_REPORTING_DISPLAY_SOME or higher.
// (This is Drupal's error_level, which is different from $error_level,
// and we purposely ignore the difference between _SOME and _ALL,
// see #970688!)
if (\Drupal::config('system.logging')->get('error_level') != 'hide') {
while (!empty($backtrace)) {
$call = array();
if (isset($backtrace[0]['file'])) {
$call['file'] = $backtrace[0]['file'];
foreach ($paths as $path => $len) {
if (strpos($backtrace[0]['file'], $path) === 0) {
$call['file'] = substr($backtrace[0]['file'], $len);
}
}
$call['file'] .= ':' . $backtrace[0]['line'];
}
if (isset($backtrace[1])) {
if (isset($backtrace[1]['class'])) {
$function = $backtrace[1]['class'] . $backtrace[1]['type'] . $backtrace[1]['function'] . '()';
}
else {
$function = $backtrace[1]['function'] . '()';
}
$backtrace[1] += array('args' => array());
foreach ($backtrace[1]['args'] as $key => $value) {
$call['args'][$key] = $value;
}
}
else {
$function = 'main()';
$call['args'] = $_GET;
}
$nicetrace[($counter <= 10 ? $nbsp : '') . --$counter . ': ' . $function] = $call;
array_shift($backtrace);
}
if ($return) {
return $nicetrace;
}
kprint_r($nicetrace);
}
}
}
/*
* Migration-related functions.
*/
/**
* Regenerates the data in node_comment_statistics table.
* Technique - http://www.artfulsoftware.com/infotree/queries.php?&bw=1280#101
*
* @return void
*/
function devel_rebuild_node_comment_statistics() {
// Empty table.
db_truncate('node_comment_statistics')->execute();
// TODO: DBTNG. Ignore keyword is Mysql only? Is only used in the rare case
// when two comments on the same node share same timestamp.
$sql = "
INSERT IGNORE INTO {node_comment_statistics} (nid, cid, last_comment_timestamp, last_comment_name, last_comment_uid, comment_count) (
SELECT c.nid, c.cid, c.created, c.name, c.uid, c2.comment_count FROM {comment} c
JOIN (
SELECT c.nid, MAX(c.created) AS created, COUNT(*) AS comment_count FROM {comment} c WHERE status = 1 GROUP BY c.nid
) AS c2 ON c.nid = c2.nid AND c.created = c2.created
)";
db_query($sql, array(':published' => CommentInterface::PUBLISHED));
// Insert records into the node_comment_statistics for nodes that are missing.
$query = db_select('node', 'n');
$query->leftJoin('node_comment_statistics', 'ncs', 'ncs.nid = n.nid');
$query->addField('n', 'changed', 'last_comment_timestamp');
$query->addField('n', 'uid', 'last_comment_uid');
$query->addField('n', 'nid');
$query->addExpression('0', 'comment_count');
$query->addExpression('NULL', 'last_comment_name');
$query->isNull('ncs.comment_count');
db_insert('node_comment_statistics', array('return' => Database::RETURN_NULL))
->from($query)
->execute();
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Adds mouse-over hints on the Permissions page to display
* language-independent machine names and module base names.
*
* @see \Drupal\user\Form\UserPermissionsForm::buildForm()
*/
function devel_form_user_admin_permissions_alter(&$form, FormStateInterface $form_state) {
if (\Drupal::currentUser()->hasPermission('access devel information') && \Drupal::config('devel.settings')->get('raw_names')) {
foreach (Element::children($form['permissions']) as $key) {
if (isset($form['permissions'][$key][0])) {
$form['permissions'][$key][0]['#wrapper_attributes']['title'] = $key;
}
elseif(isset($form['permissions'][$key]['description'])) {
$form['permissions'][$key]['description']['#wrapper_attributes']['title'] = $key;
}
}
}
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Adds mouse-over hints on the Modules page to display module base names.
*
* @see \Drupal\system\Form\ModulesListForm::buildForm()
* @see theme_system_modules_details()
*/
function devel_form_system_modules_alter(&$form, FormStateInterface $form_state) {
if (\Drupal::currentUser()->hasPermission('access devel information') && \Drupal::config('devel.settings')->get('raw_names', FALSE) && isset($form['modules']) && is_array($form['modules'])) {
foreach (Element::children($form['modules']) as $group) {
if (is_array($form['modules'][$group])) {
foreach (Element::children($form['modules'][$group]) as $key) {
if (isset($form['modules'][$group][$key]['name']['#markup'])) {
$form['modules'][$group][$key]['name']['#markup'] = '<span title="' . $key . '">' . $form['modules'][$group][$key]['name']['#markup'] . '</span>';
}
}
}
}
}
}
/**
* Implements hook_query_TAG_alter().
*
* Makes debugging entity query much easier.
*
* Example usage:
* @code
* $query = \Drupal::entityQuery('node');
* $query->condition('status', NODE_PUBLISHED);
* $query->addTag('debug');
* $query->execute();
* @endcode
*/
function devel_query_debug_alter(AlterableInterface $query) {
if (!$query->hasTag('debug-semaphore')) {
$query->addTag('debug-semaphore');
dpq($query);
}
}