Issue #1071200 by danielb: Return renderable arrays rather than HTML output.
[project/devel.git] / devel.module
1 <?php
2
3 // This module holds functions useful for Drupal development.
4 // Please contribute!
5
6 // Suggested profiling and stacktrace library from http://www.xdebug.org/index.php
7
8 define('DEVEL_QUERY_SORT_BY_SOURCE', 0);
9 define('DEVEL_QUERY_SORT_BY_DURATION', 1);
10
11 define('DEVEL_ERROR_HANDLER_NONE', 0);
12 define('DEVEL_ERROR_HANDLER_STANDARD', 1);
13 define('DEVEL_ERROR_HANDLER_BACKTRACE', 2);
14
15 define('DEVEL_MIN_TEXTAREA', 50);
16
17 /**
18 * Implementation of hook_help().
19 */
20 function devel_help($section) {
21 switch ($section) {
22 case 'devel/reference':
23 return '<p>'. t('This is a list of defined user functions that generated this current request lifecycle. Click on a function name to view its documention.') .'</p>';
24 case 'devel/session':
25 return '<p>'. t('Here are the contents of your <code>$_SESSION</code> variable.') .'</p>';
26 case 'devel/variable':
27 $api = variable_get('devel_api_url', 'api.drupal.org');
28 return '<p>'. t('This is a list of the variables and their values currently stored in variables table and the <code>$conf</code> array of your settings.php file. These variables are usually accessed with <a href="@variable-get-doc">variable_get()</a> and <a href="@variable-set-doc">variable_set()</a>. Variables that are too long can slow down your pages.', array('@variable-get-doc' => "http://$api/api/HEAD/function/variable_get", '@variable-set-doc' => "http://$api/api/HEAD/function/variable_set")) .'</p>';
29 case 'devel/reinstall':
30 return t('Warning - will delete your module tables and variables.');
31 }
32 }
33
34 /**
35 * Implementationation of hook_menu().
36 */
37 function devel_menu() {
38 $items = array();
39 // Note: we can't dynamically append destination to querystring. Do so at theme layer. Fix in D7?
40 $items['devel/cache/clear'] = array(
41 'title' => 'Empty cache',
42 'page callback' => 'devel_cache_clear',
43 'description' => 'Clear the CSS cache and all database cache tables which store page, node, theme and variable caches.',
44 'access arguments' => array('access devel information'),
45 'file' => 'devel.pages.inc',
46 'menu_name' => 'devel',
47 );
48
49 $items['devel/reference'] = array(
50 'title' => 'Function reference',
51 'description' => 'View a list of currently defined user functions with documentation links.',
52 'page callback' => 'devel_function_reference',
53 'access arguments' => array('access devel information'),
54 'file' => 'devel.pages.inc',
55 'menu_name' => 'devel',
56 );
57 $items['devel/reinstall'] = array(
58 'title' => 'Reinstall modules',
59 'page callback' => 'drupal_get_form',
60 'page arguments' => array('devel_reinstall'),
61 'description' => 'Run hook_uninstall() and then hook_install() for a given module.',
62 'access arguments' => array('access devel information'),
63 'file' => 'devel.pages.inc',
64 'menu_name' => 'devel',
65 );
66 $items['devel/menu/reset'] = array(
67 'title' => 'Rebuild menus',
68 'description' => 'Rebuild menu based on hook_menu() and revert any custom changes. All menu items return to their default settings.',
69 'page callback' => 'drupal_get_form',
70 'page arguments' => array('devel_menu_rebuild'),
71 'access arguments' => array('access devel information'),
72 'file' => 'devel.pages.inc',
73 'menu_name' => 'devel',
74 );
75 $items['devel/menu/item'] = array(
76 'title' => 'Menu item',
77 'description' => 'Details about a given menu item.',
78 'page callback' => 'devel_menu_item',
79 'access arguments' => array('access devel information'),
80 'file' => 'devel.pages.inc',
81 'menu_name' => 'devel',
82 );
83 $items['devel/variable'] = array(
84 'title' => 'Variable editor',
85 'description' => 'Edit and delete site variables.',
86 'page callback' => 'devel_variable_page',
87 'access arguments' => array('access devel information'),
88 'file' => 'devel.pages.inc',
89 'menu_name' => 'devel',
90 );
91 // we don't want the abbreviated version provided by status report
92 $items['devel/phpinfo'] = array(
93 'title' => 'PHPinfo()',
94 'description' => 'View your server\'s PHP configuration',
95 'page callback' => 'devel_phpinfo',
96 'access arguments' => array('access devel information'),
97 'file' => 'devel.pages.inc',
98 'menu_name' => 'devel',
99 );
100 $items['devel/php'] = array(
101 'title' => 'Execute PHP Code',
102 'description' => 'Execute some PHP code',
103 'page callback' => 'drupal_get_form',
104 'page arguments' => array('devel_execute_form'),
105 'access arguments' => array('execute php code'),
106 'file' => 'devel.pages.inc',
107 'menu_name' => 'devel',
108 );
109 $items['devel/theme/registry'] = array(
110 'title' => 'Theme registry',
111 'description' => 'View a list of available theme functions across the whole site.',
112 'page callback' => 'devel_theme_registry',
113 'access arguments' => array('access devel information'),
114 'file' => 'devel.pages.inc',
115 'menu_name' => 'devel',
116 );
117 $items['devel/entity/info'] = array(
118 'title' => 'Entity info',
119 'description' => 'View entity information across the whole site.',
120 'page callback' => 'devel_entity_info_page',
121 'access arguments' => array('access devel information'),
122 'file' => 'devel.pages.inc',
123 'menu_name' => 'devel',
124 );
125 $items['devel/field/info'] = array(
126 'title' => 'Field info',
127 'description' => 'View fields information across the whole site.',
128 'page callback' => 'devel_field_info_page',
129 'access arguments' => array('access devel information'),
130 'file' => 'devel.pages.inc',
131 'menu_name' => 'devel',
132 );
133 $items['devel/elements'] = array(
134 'title' => 'Hook_elements()',
135 'description' => 'View the active form/render elements for this site.',
136 'page callback' => 'devel_elements_page',
137 'access arguments' => array('access devel information'),
138 'file' => 'devel.pages.inc',
139 'menu_name' => 'devel',
140 );
141 $items['devel/variable/edit/%'] = array(
142 'title' => 'Variable editor',
143 'page callback' => 'drupal_get_form',
144 'page arguments' => array('devel_variable_edit', 3),
145 'access arguments' => array('access devel information'),
146 'type' => MENU_CALLBACK,
147 'file' => 'devel.pages.inc',
148 'menu_name' => 'devel',
149 );
150 $items['devel/session'] = array(
151 'title' => 'Session viewer',
152 'description' => 'List the contents of $_SESSION.',
153 'page callback' => 'devel_session',
154 'access arguments' => array('access devel information'),
155 'file' => 'devel.pages.inc',
156 'menu_name' => 'devel',
157 );
158 $items['devel/switch'] = array(
159 'title' => 'Switch user',
160 'page callback' => 'devel_switch_user',
161 'access arguments' => array('switch users'),
162 'type' => MENU_CALLBACK,
163 'file' => 'devel.pages.inc',
164 'menu_name' => 'devel',
165 );
166 $items['devel/explain'] = array(
167 'title' => 'Explain query',
168 'page callback' => 'devel_querylog_explain',
169 'description' => 'Run an EXPLAIN on a given query. Used by query log',
170 'access arguments' => array('access devel information'),
171 'file' => 'devel.pages.inc',
172 'type' => MENU_CALLBACK
173 );
174 $items['devel/arguments'] = array(
175 'title' => 'Arguments query',
176 'page callback' => 'devel_querylog_arguments',
177 'description' => 'Return a given query, with arguments instead of placeholders. Used by query log',
178 'access arguments' => array('access devel information'),
179 'file' => 'devel.pages.inc',
180 'type' => MENU_CALLBACK
181 );
182 $items['devel/run-cron'] = array(
183 'title' => 'Run cron',
184 'page callback' => 'system_run_cron',
185 'access arguments' => array('administer site configuration'),
186 'file' => 'system.admin.inc',
187 'file path' => drupal_get_path('module', 'system'),
188 'menu_name' => 'devel',
189 );
190
191 // Duplicate path in 2 different menus. See http://drupal.org/node/601788.
192 $items['devel/settings'] = array(
193 'title' => 'Devel settings',
194 'description' => 'Helper functions, pages, and blocks to assist Drupal developers. The devel blocks can be managed via the <a href="' . url('admin/structure/block') . '">block administration</a> page.',
195 'page callback' => 'drupal_get_form',
196 'page arguments' => array('devel_admin_settings'),
197 'access arguments' => array('administer site configuration'),
198 'file' => 'devel.admin.inc',
199 'menu_name' => 'devel',
200 );
201 $items['admin/config/development/devel'] = array(
202 'title' => 'Devel settings',
203 'description' => 'Helper functions, pages, and blocks to assist Drupal developers. The devel blocks can be managed via the <a href="' . url('admin/structure/block') . '">block administration</a> page.',
204 'page callback' => 'drupal_get_form',
205 'page arguments' => array('devel_admin_settings'),
206 'file' => 'devel.admin.inc',
207 'access arguments' => array('administer site configuration'),
208 );
209
210 $items['node/%node/devel'] = array(
211 'title' => 'Devel',
212 'page callback' => 'devel_load_object',
213 'page arguments' => array('node', 1),
214 'access arguments' => array('access devel information'),
215 'type' => MENU_LOCAL_TASK,
216 'file' => 'devel.pages.inc',
217 'weight' => 100,
218 );
219 $items['node/%node/devel/load'] = array(
220 'title' => 'Load',
221 'type' => MENU_DEFAULT_LOCAL_TASK,
222 );
223 $items['node/%node/devel/render'] = array(
224 'title' => 'Render',
225 'page callback' => 'devel_render_object',
226 'page arguments' => array('node', 1),
227 'access arguments' => array('access devel information'),
228 'file' => 'devel.pages.inc',
229 'type' => MENU_LOCAL_TASK,
230 'weight' => 100,
231 );
232 $items['comment/%comment/devel'] = array(
233 'title' => 'Devel',
234 'page callback' => 'devel_load_object',
235 'page arguments' => array('comment', 1),
236 'access arguments' => array('access devel information'),
237 'type' => MENU_LOCAL_TASK,
238 'file' => 'devel.pages.inc',
239 'weight' => 100,
240 );
241 $items['comment/%comment/devel/load'] = array(
242 'title' => 'Load',
243 'type' => MENU_DEFAULT_LOCAL_TASK,
244 );
245 $items['comment/%comment/devel/render'] = array(
246 'title' => 'Render',
247 'page callback' => 'devel_render_object',
248 'page arguments' => array('comment', 1),
249 'access arguments' => array('access devel information'),
250 'type' => MENU_LOCAL_TASK,
251 'file' => 'devel.pages.inc',
252 'weight' => 100,
253 );
254 $items['user/%user/devel'] = array(
255 'title' => 'Devel',
256 'page callback' => 'devel_load_object',
257 'page arguments' => array('user', 1),
258 'access arguments' => array('access devel information'),
259 'type' => MENU_LOCAL_TASK,
260 'file' => 'devel.pages.inc',
261 'weight' => 100,
262 );
263 $items['user/%user/devel/load'] = array(
264 'title' => 'Load',
265 'type' => MENU_DEFAULT_LOCAL_TASK,
266 );
267 $items['user/%user/devel/render'] = array(
268 'title' => 'Render',
269 'page callback' => 'devel_render_object',
270 'page arguments' => array('user', 1),
271 'access arguments' => array('access devel information'),
272 'file' => 'devel.pages.inc',
273 'type' => MENU_LOCAL_TASK,
274 'weight' => 100,
275 );
276 $items['taxonomy/term/%taxonomy_term/devel'] = array(
277 'title' => 'Devel',
278 'page callback' => 'devel_load_object',
279 'page arguments' => array('taxonomy_term', 2, 'term'),
280 'access arguments' => array('access devel information'),
281 'file' => 'devel.pages.inc',
282 'type' => MENU_LOCAL_TASK,
283 'weight' => 100,
284 );
285 $items['taxonomy/term/%taxonomy_term/devel/load'] = array(
286 'title' => 'Load',
287 'type' => MENU_DEFAULT_LOCAL_TASK,
288 );
289 $items['taxonomy/term/%taxonomy_term/devel/render'] = array(
290 'title' => 'Render',
291 'page callback' => 'devel_render_object',
292 'page arguments' => array('taxonomy_term', 2, 'term'),
293 'access arguments' => array('access devel information'),
294 'type' => MENU_LOCAL_TASK,
295 'file' => 'devel.pages.inc',
296 'weight' => 100,
297 );
298
299 return $items;
300 }
301
302 /**
303 * Implements hook_admin_paths().
304 */
305 function devel_admin_paths() {
306 $paths = array(
307 'devel/*' => TRUE,
308 'node/*/devel' => TRUE,
309 'node/*/devel/*' => TRUE,
310 'comment/*/devel' => TRUE,
311 'comment/*/devel/*' => TRUE,
312 'user/*/devel' => TRUE,
313 'user/*/devel/*' => TRUE,
314 'taxonomy/term/*/devel' => TRUE,
315 'taxonomy/term/*/devel/*' => TRUE,
316 );
317 return $paths;
318 }
319
320 function devel_menu_need_destination() {
321 return array('devel/cache/clear', 'devel/reinstall', 'devel/menu/reset', 'devel/variable', 'admin/reports/status/run-cron');
322 }
323
324 /**
325 * An implementation of hook_menu_link_alter(). Flag this link as needing alter at display time.
326 * This is more robust than setting alter in hook_menu().
327 * @see devel_translated_menu_link_alter().
328 *
329 **/
330 function devel_menu_link_alter(&$item) {
331 if (in_array($item['link_path'], devel_menu_need_destination()) || $item['link_path'] == 'devel/menu/item') {
332 $item['options']['alter'] = TRUE;
333 }
334 }
335
336 /**
337 * An implementation of hook_translated_menu_item_alter(). Append dynamic
338 * querystring 'destination' to several of our own menu items.
339 *
340 **/
341 function devel_translated_menu_link_alter(&$item) {
342 if (in_array($item['href'], devel_menu_need_destination())) {
343 $item['localized_options']['query'] = drupal_get_destination();
344 }
345 elseif ($item['href'] == 'devel/menu/item') {
346 $item['localized_options']['query'] = array('path' => $_GET['q']);
347 }
348 }
349
350 /**
351 * Implementation of hook_theme()
352 */
353 function devel_theme() {
354 return array(
355 'devel_querylog' => array(
356 'variables' => array('header' => array(), 'rows' => array()),
357 ),
358 'devel_querylog_row' => array(
359 'variables' => array('row' => array()),
360 ),
361 );
362 }
363
364 /**
365 * Implementation of hook_init().
366 */
367 function devel_init() {
368 if (!devel_silent()) {
369 if (user_access('access devel information')) {
370 devel_set_handler(variable_get('devel_error_handler', DEVEL_ERROR_HANDLER_STANDARD));
371 // We want to include the class early so that anyone may call krumo() as needed. See http://krumo.sourceforge.net/
372 has_krumo();
373
374 // See http://www.firephp.org/HQ/Install.htm
375 $path = NULL;
376 if (@include_once('fb.php')) {
377 // FirePHPCore is in include_path. Probably a PEAR installation.
378 $path = '';
379 }
380 elseif (module_exists('libraries')) {
381 // Support Libraries API - http://drupal.org/project/libraries
382 $firephp_path = libraries_get_path('FirePHPCore') . '/lib/FirePHPCore/';
383 $chromephp_path = libraries_get_path('chromephp');
384 }
385 else {
386 $firephp_path = './'. drupal_get_path('module', 'devel') .'/FirePHPCore/lib/FirePHPCore/';
387 $chromephp_path = './' . drupal_get_path('module', 'devel') .'/chromephp';
388 }
389
390 // include FirePHP if exists...
391 if (file_exists($firephp_path .'fb.php')) {
392 include_once $firephp_path .'fb.php';
393 include_once $firephp_path .'FirePHP.class.php';
394 }
395
396 // include ChromePHP if exists...
397 if (file_exists($chromephp_path . '/ChromePhp.php')) {
398 include_once $chromephp_path . '/ChromePhp.php';
399 }
400
401
402 // Add CSS for query log if should be displayed.
403 if (variable_get('devel_query_display', 0)) {
404 drupal_add_css(drupal_get_path('module', 'devel') .'/devel.css');
405 drupal_add_js(drupal_get_path('module', 'devel'). '/devel.js');
406 }
407 }
408 }
409 if (variable_get('devel_rebuild_theme_registry', FALSE)) {
410 drupal_theme_rebuild();
411 if (flood_is_allowed('devel_rebuild_registry_warning', 1)) {
412 flood_register_event('devel_rebuild_registry_warning');
413 if (!devel_silent() && user_access('access devel information')) {
414 drupal_set_message(t('The theme registry is being rebuilt on every request. Remember to <a href="!url">turn off</a> this feature on production websites.', array("!url" => url('admin/config/development/devel'))));
415 }
416 }
417 }
418 }
419
420 function devel_set_message($msg, $type = NULL) {
421 $function = function_exists('drush_log') ? 'drush_log' : 'drupal_set_message';
422 $function($msg, $type);
423 }
424
425 // Return boolean. No need for cache here.
426 function has_krumo() {
427 // see README.txt or just download from http://krumo.sourceforge.net/
428 @include_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'devel') .'/krumo/class.krumo.php';
429 return function_exists('krumo') && !drupal_is_cli();
430 }
431
432 /**
433 * Decide whether or not to print a debug variable using krumo().
434 *
435 * @param $input
436 * @return boolean
437 */
438 function merits_krumo($input) {
439 return (is_object($input) || is_array($input)) && has_krumo() && variable_get('devel_krumo_skin', '') != 'disabled';
440 }
441
442 /**
443 * Calls the http://www.firephp.org/ fb() function if it is found.
444 *
445 * @return void
446 */
447 function dfb() {
448 if (function_exists('fb') && user_access('access devel information') && !headers_sent()) {
449 $args = func_get_args();
450 call_user_func_array('fb', $args);
451 }
452 }
453
454 /**
455 * Calls dfb() to output a backtrace.
456 */
457 function dfbt($label) {
458 dfb($label, FirePHP::TRACE);
459 }
460
461 /**
462 * Wrapper for ChromePHP Class log method
463 */
464 function dcp() {
465 if (class_exists('ChromePhp') && user_access('access devel information')) {
466 $args = func_get_args();
467 call_user_func_array(array('ChromePhp', 'log'), $args);
468 }
469 }
470
471 /**
472 * Implements hook_watchdog().
473 */
474 function devel_watchdog(array $log_entry) {
475 if (class_exists('FirePHP') && !drupal_is_cli()) {
476 switch ($log_entry['severity']) {
477 case WATCHDOG_EMERGENCY:
478 case WATCHDOG_ALERT:
479 case WATCHDOG_CRITICAL:
480 case WATCHDOG_ERROR:
481 $type = FirePHP::ERROR;
482 break;
483 case WATCHDOG_WARNING:
484 $type = FirePHP::WARN;
485 break;
486 case WATCHDOG_NOTICE:
487 case WATCHDOG_INFO:
488 $type = FirePHP::INFO;
489 break;
490 case WATCHDOG_DEBUG:
491 DEFAULT:
492 $type = FirePHP::LOG;
493 }
494 }
495 else {
496 $type = 'watchdog';
497 }
498 $function = function_exists('decode_entities') ? 'decode_entities' : 'html_entity_decode';
499 $watchdog = array(
500 'type' => $log_entry['type'],
501 'message' => $function(strtr($log_entry['message'], (array)$log_entry['variables'])),
502 );
503 if (isset($log_entry['link'])) {
504 $watchdog['link'] = $log_entry['link'];
505 }
506 dfb($watchdog, $type);
507 }
508
509 function devel_set_handler($handler) {
510 switch ($handler) {
511 case DEVEL_ERROR_HANDLER_STANDARD:
512 // do nothing
513 break;
514 case DEVEL_ERROR_HANDLER_BACKTRACE:
515 if (has_krumo()) {
516 set_error_handler('backtrace_error_handler');
517 }
518 break;
519 case DEVEL_ERROR_HANDLER_NONE:
520 restore_error_handler();
521 break;
522 }
523 }
524
525 function devel_silent() {
526 // isset($_GET['q']) is needed when calling the front page. q is not set.
527 // Don't interfere with private files/images.
528 return
529 function_exists('drupal_is_cli') && drupal_is_cli() ||
530 (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'ApacheBench') !== FALSE) ||
531 !empty($_REQUEST['XDEBUG_PROFILE']) ||
532 isset($GLOBALS['devel_shutdown']) ||
533 strstr($_SERVER['PHP_SELF'], 'update.php') ||
534 (isset($_GET['q']) && (
535 in_array($_GET['q'], array( 'admin/content/node-settings/rebuild')) ||
536 substr($_GET['q'], 0, strlen('system/files')) == 'system/files' ||
537 substr($_GET['q'], 0, strlen('batch')) == 'batch' ||
538 substr($_GET['q'], 0, strlen('file/ajax')) == 'file/ajax')
539 );
540 }
541
542 function devel_xhprof_enable() {
543 if (devel_xhprof_is_enabled()) {
544 if ($path = variable_get('devel_xhprof_directory', '')) {
545 include_once $path . '/xhprof_lib/utils/xhprof_lib.php';
546 include_once $path . '/xhprof_lib/utils/xhprof_runs.php';
547 // @todo: consider a variable per-flag instead.
548 xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
549 }
550 }
551 }
552
553 function devel_xhprof_is_enabled() {
554 return extension_loaded('xhprof') && variable_get('devel_xhprof_enabled', FALSE);
555 }
556
557 /**
558 * Implementation of hook_boot(). Runs even for cached pages.
559 */
560 function devel_boot() {
561 // Initialize XHProf.
562 devel_xhprof_enable();
563
564 if (!devel_silent()) {
565 if (variable_get('dev_mem', 0)) {
566 global $memory_init;
567 $memory_init = memory_get_usage();
568 }
569
570 if (devel_query_enabled()) {
571 @include_once DRUPAL_ROOT . '/includes/database/log.inc';
572 Database::startLog('devel');;
573 }
574 }
575
576 // We need user_access() in the shutdown function. make sure it gets loaded.
577 // Also prime the drupal_get_filename() static with user.module's location to
578 // avoid a stray query.
579 drupal_get_filename('module', 'user', 'modules/user/user.module');
580 drupal_load('module', 'user');
581 drupal_register_shutdown_function('devel_shutdown');
582 }
583
584 function backtrace_error_handler($error_level, $message, $filename, $line, $context) {
585 // Hide stack trace and parameters from unqualified users.
586 if (!user_access('access devel information')) {
587 return _drupal_error_handler($error_level, $message, $filename, $line, $context);
588 }
589 // Don't respond to the error if it was suppressed with a '@'
590 if (error_reporting() == 0) {
591 return;
592 }
593 // Don't respond to warning caused by ourselves.
594 if (preg_match('#Cannot modify header information - headers already sent by \\([^\\)]*[/\\\\]devel[/\\\\]#', $message)) {
595 return;
596 }
597 if ($error_level & error_reporting()) {
598 // Only write each distinct NOTICE message once, as repeats do not give any
599 // further information and can choke the page output.
600 if ($error_level == E_NOTICE) {
601 static $written = array();
602 if (!empty($written[$line][$filename][$message])) {
603 return;
604 }
605 $written[$line][$filename][$message] = TRUE;
606 }
607
608 require_once DRUPAL_ROOT . '/includes/errors.inc';
609 $types = drupal_error_levels();
610 $type = $types[$error_level];
611 $backtrace = debug_backtrace();
612 array_shift($backtrace);
613 $variables = array('%error' => $type[0], '%message' => $message, '%function' => $backtrace[0]['function'] .'()', '%file' => $filename, '%line' => $line);
614 $counter = 0;
615
616 if (variable_get('error_level', 1) == 1) {
617 foreach ($backtrace as $call) {
618 $nicetrace[$call['function'] . '<span class="' . $counter++ . '" />'] = $call;
619 }
620 print t('%error: %message in %function (line %line of %file).', $variables) ." =&gt;\n";
621 krumo($nicetrace);
622 }
623
624 watchdog('php', '%error: %message in %function (line %line of %file).', $variables, $type[1]);
625 }
626 }
627
628 /**
629 * Implement hook_permission().
630 */
631 function devel_permission() {
632 return array(
633 'access devel information' => array(
634 'description' => t('View developer output like variable printouts, query log, etc.'),
635 'title' => t('Access developer information'),
636 'restrict access' => TRUE,
637 ),
638 'execute php code' => array(
639 'title' => t('Execute PHP code'),
640 'description' => t('Run arbitrary PHP from a block.'),
641 'restrict access' => TRUE,
642 ),
643 'switch users' => array(
644 'title' => t('Switch users'),
645 'description' => t('Become any user on the site with just a click.'),
646 'restrict access' => TRUE,
647 ),
648 'display source code' => array(
649 'title' => t('Display source code'),
650 'description' => t('View the site\'s php source code.'),
651 'restrict access' => TRUE,
652 ),
653 );
654 }
655
656 function devel_block_info() {
657 $blocks['execute_php'] = array(
658 'info' => t('Execute PHP'),
659 'cache' => DRUPAL_NO_CACHE,
660 );
661 $blocks['switch_user'] = array(
662 'info' => t('Switch user'),
663 'cache' => DRUPAL_NO_CACHE,
664 );
665 return $blocks;
666 }
667
668 /**
669 * Implementation of hook_block_configure().
670 */
671 function devel_block_configure($delta) {
672 if ($delta == 'switch_user') {
673 $form['list_size'] = array(
674 '#type' => 'textfield',
675 '#title' => t('Number of users to display in the list'),
676 '#default_value' => variable_get('devel_switch_user_list_size', 10),
677 '#size' => '3',
678 '#maxlength' => '4',
679 );
680 $form['include_anon'] = array(
681 '#type' => 'checkbox',
682 '#title' => t('Include %anonymous', array('%anonymous' => format_username(drupal_anonymous_user()))),
683 '#default_value' => variable_get('devel_switch_user_include_anon', FALSE),
684 );
685 $form['show_form'] = array(
686 '#type' => 'checkbox',
687 '#title' => t('Allow entering any user name'),
688 '#default_value' => variable_get('devel_switch_user_show_form', TRUE),
689 );
690 return $form;
691 }
692 }
693
694 function devel_block_save($delta, $edit = array()) {
695 if ($delta == 'switch_user') {
696 variable_set('devel_switch_user_list_size', $edit['list_size']);
697 variable_set('devel_switch_user_include_anon', $edit['include_anon']);
698 variable_set('devel_switch_user_show_form', $edit['show_form']);
699 }
700 }
701
702 function devel_block_view($delta) {
703 $block = array();
704 switch ($delta) {
705 case 'switch_user':
706 $block = devel_block_switch_user();
707 break;
708
709 case 'execute_php':
710 if (user_access('execute php code')) {
711 $block['content'] = drupal_get_form('devel_execute_block_form');
712 }
713 break;
714 }
715 return $block;
716 }
717
718 function devel_block_switch_user() {
719 $links = devel_switch_user_list();
720 if (!empty($links) || user_access('switch users')) {
721 $block['subject'] = t('Switch user');
722 $build['devel_links'] = array('#theme' => 'links', '#links' => $links);
723 if (variable_get('devel_switch_user_show_form', TRUE)) {
724 $build['devel_form'] = drupal_get_form('devel_switch_user_form');
725 }
726 $block['content'] = $build;
727 return $block;
728 }
729 }
730
731 function devel_switch_user_list() {
732 global $user;
733
734 $links = array();
735 if (user_access('switch users')) {
736 $list_size = variable_get('devel_switch_user_list_size', 10);
737 if ($include_anon = ($user->uid && variable_get('devel_switch_user_include_anon', FALSE))) {
738 --$list_size;
739 }
740 $dest = drupal_get_destination();
741 // Try to find at least $list_size users that can switch.
742 // Inactive users are omitted from all of the following db selects.
743 $roles = user_roles(TRUE, 'switch users');
744 $query = db_select('users', 'u');
745 $query->addField('u', 'uid');
746 $query->addField('u', 'access');
747 $query->distinct();
748 $query->condition('u.uid', 0, '>');
749 $query->condition('u.status', 0, '>');
750 $query->orderBy('u.access', 'DESC');
751 $query->range(0, $list_size);
752
753 if (!isset($roles[DRUPAL_AUTHENTICATED_RID])) {
754 $query->leftJoin('users_roles', 'r', 'u.uid = r.uid');
755 $or_condition = db_or();
756 $or_condition->condition('u.uid', 1);
757 if (!empty($roles)) {
758 $or_condition->condition('r.rid', array_keys($roles), 'IN');
759 }
760 $query->condition($or_condition);
761 }
762
763 $uids = $query->execute()->fetchCol();
764 $accounts = user_load_multiple($uids);
765
766 foreach ($accounts as $account) {
767 $links[$account->uid] = array(
768 'title' => drupal_placeholder(format_username($account)),
769 'href' => 'devel/switch/'. $account->name,
770 'query' => $dest,
771 'attributes' => array('title' => t('This user can switch back.')),
772 'html' => TRUE,
773 'last_access' => $account->access,
774 );
775 }
776 $num_links = count($links);
777 if ($num_links < $list_size) {
778 // If we don't have enough, add distinct uids until we hit $list_size.
779 $uids = db_query_range('SELECT uid FROM {users} WHERE uid > 0 AND uid NOT IN (:uids) AND status > 0 ORDER BY access DESC', 0, $list_size - $num_links, array(':uids' => array_keys($links)))->fetchCol();
780 $accounts = user_load_multiple($uids);
781 foreach ($accounts as $account) {
782 $links[$account->uid] = array(
783 'title' => format_username($account),
784 'href' => 'devel/switch/'. $account->name,
785 'query' => $dest,
786 'attributes' => array('title' => t('Caution: this user will be unable to switch back.')),
787 'last_access' => $account->access,
788 );
789 }
790 uasort($links, '_devel_switch_user_list_cmp');
791 }
792 if ($include_anon) {
793 $link = array(
794 'title' => format_username(drupal_anonymous_user()),
795 'href' => 'devel/switch',
796 'query' => $dest,
797 'attributes' => array('title' => t('Caution: the anonymous user will be unable to switch back.')),
798 );
799 if (user_access('switch users', drupal_anonymous_user())) {
800 $link['title'] = drupal_placeholder($link['title']);
801 $link['attributes'] = array('title' => t('This user can switch back.'));
802 $link['html'] = TRUE;
803 }
804 $links[] = $link;
805 }
806 }
807 return $links;
808 }
809
810 /**
811 * Comparison helper function for uasort() in devel_switch_user_list().
812 *
813 * Sorts the Switch User links by the user's last access timestamp.
814 */
815 function _devel_switch_user_list_cmp($a, $b) {
816 return $b['last_access'] - $a['last_access'];
817 }
818
819 function devel_switch_user_form() {
820 $form['username'] = array(
821 '#type' => 'textfield',
822 '#description' => t('Enter username'),
823 '#autocomplete_path' => 'user/autocomplete',
824 '#maxlength' => USERNAME_MAX_LENGTH,
825 '#size' => 16,
826 );
827 $form['submit'] = array(
828 '#type' => 'submit',
829 '#value' => t('Switch'),
830 );
831 return $form;
832
833 }
834
835 function devel_doc_function_form() {
836 $version = devel_get_core_version(VERSION);
837 $form['function'] = array(
838 '#type' => 'textfield',
839 '#description' => t('Enter function name for api lookup'),
840 '#size' => 16,
841 '#maxlength' => 255,
842 );
843 $form['version'] = array('#type' => 'value', '#value' => $version);
844 $form['submit_button'] = array(
845 '#type' => 'submit',
846 '#value' => t('Submit'),
847 );
848 return $form;
849 }
850
851 function devel_doc_function_form_submit($form, &$form_state) {
852 $version = $form_state['values']['version'];
853 $function = $form_state['values']['function'];
854 $api = variable_get('devel_api_url', 'api.drupal.org');
855 $form_state['redirect'] = "http://$api/api/function/$function/$version";
856 }
857
858 function devel_switch_user_form_validate($form, &$form_state) {
859 if (!$account = user_load_by_name($form_state['values']['username'])) {
860 form_set_error('username', t('Username not found'));
861 }
862 }
863
864 function devel_switch_user_form_submit($form, &$form_state) {
865 $form_state['redirect'] = 'devel/switch/'. $form_state['values']['username'];
866 }
867
868 /**
869 * Implements hook_drupal_goto_alter().
870 */
871 function devel_drupal_goto_alter($path, $options, $http_response_code) {
872 global $user;
873
874 if (isset($path) && !devel_silent()) {
875 // The page we are leaving is a drupal_goto(). Present a redirection page
876 // so that the developer can see the intermediate query log.
877 // We don't want to load user module here, so keep function_exists() call.
878 if (isset($user) && function_exists('user_access') && user_access('access devel information') && variable_get('devel_redirect_page', 0)) {
879 $destination = function_exists('url') ? url($path, $options) : $path;
880 $output = t_safe('<p>The user is being redirected to <a href="@destination">@destination</a>.</p>', array('@destination' => $destination));
881 drupal_deliver_page($output);
882
883 // Don't allow the automatic redirect to happen.
884 exit();
885 }
886 else {
887 $GLOBALS['devel_redirecting'] = TRUE;
888 }
889 }
890 }
891
892 /**
893 * Implements hook_library_alter().
894 */
895 function devel_library_alter(&$libraries, $module) {
896 // Use an uncompressed version of jQuery for debugging.
897 if ($module === 'system' && variable_get('devel_use_uncompressed_jquery', FALSE) && isset($libraries['jquery'])) {
898 // Make sure we're not changing the jQuery version used on the site.
899 if (version_compare($libraries['jquery']['version'], '1.4.4', '=')) {
900 $libraries['jquery']['js'] = array(
901 drupal_get_path('module', 'devel') . '/jquery-1.4.4-uncompressed.js' => array('weight' => JS_LIBRARY - 20),
902 );
903 }
904 else {
905 if (!devel_silent() && user_access('access devel information')) {
906 drupal_set_message(t('jQuery could not be replaced with an uncompressed version of 1.4.4, because jQuery @version is running on the site.', array('@version' => $libraries['jquery']['version'])));
907 }
908
909 }
910 }
911 }
912
913 /**
914 * See devel_start() which registers this function as a shutdown function.
915 */
916 function devel_shutdown() {
917 // Register the real shutdown function so it runs later than other shutdown functions.
918 drupal_register_shutdown_function('devel_shutdown_real');
919
920 global $devel_run_id;
921 $devel_run_id = devel_xhprof_is_enabled() ? devel_shutdown_xhprof(): NULL;
922 if ($devel_run_id && function_exists('drush_log')) {
923 drush_log('xhprof link: ' . devel_xhprof_link($devel_run_id, 'url'), 'notice');
924 }
925 }
926
927 function devel_page_alter($page) {
928 if (variable_get('devel_page_alter', FALSE) && user_access('access devel information')) {
929 dpm($page, 'page');
930 }
931 }
932
933 // AJAX render reponses sometimers are sent as text/html so we have to catch them here
934 // and disable our footer stuff.
935 function devel_ajax_render_alter() {
936 $GLOBALS['devel_shutdown'] = FALSE;
937 }
938
939 /**
940 * See devel_shutdown() which registers this function as a shutdown function. Displays developer information in the footer.
941 */
942 function devel_shutdown_real() {
943 global $user;
944 $output = $txt = '';
945
946 // Set $GLOBALS['devel_shutdown'] = FALSE in order to supress the
947 // devel footer for a page. Not necessary if your page outputs any
948 // of the Content-type http headers tested below (e.g. text/xml,
949 // text/javascript, etc). This is is advised where applicable.
950 if (!devel_silent() && !isset($GLOBALS['devel_shutdown']) && !isset($GLOBALS['devel_redirecting'])) {
951 // Try not to break non html pages.
952 if (function_exists('drupal_get_http_header')) {
953 $header = drupal_get_http_header('content-type');
954 if ($header) {
955 $formats = array('xml', 'javascript', 'json', 'plain', 'image', 'application', 'csv', 'x-comma-separated-values');
956 foreach ($formats as $format) {
957 if (strstr($header, $format)) {
958 return;
959 }
960 }
961 }
962 }
963
964 if (isset($user) && user_access('access devel information')) {
965 $queries = Database::getLog('devel', 'default');
966 $output .= devel_shutdown_summary($queries);
967 $output .= devel_shutdown_query($queries);
968 }
969
970 if ($output) {
971 // TODO: gzip this text if we are sending a gzip page. see drupal_page_header().
972 // For some reason, this is not actually printing for cached pages even though it gets executed
973 // and $output looks good.
974 print $output;
975 }
976 }
977 }
978
979 function devel_shutdown_summary($queries) {
980 $sum = 0;
981 $output = '';
982 list($counts, $query_summary) = devel_query_summary($queries);
983
984 if (variable_get('devel_query_display', FALSE)) {
985 // Query log on.
986 $output .= $query_summary;
987 $output .= t_safe(' Queries exceeding @threshold ms are <span class="marker">highlighted</span>.', array('@threshold' => variable_get('devel_execution', 5)));
988 }
989
990 if (variable_get('dev_timer', 0)) {
991 $output .= devel_timer();
992 }
993
994 if (devel_xhprof_is_enabled()) {
995 $output .= ' ' . devel_xhprof_link($GLOBALS['devel_run_id']);
996 }
997
998 $output .= devel_shutdown_memory();
999
1000 if ($output) {
1001 return '<div class="dev-query">' . $output . '</div>';
1002 }
1003 }
1004
1005 function devel_shutdown_xhprof() {
1006 $namespace = variable_get('site_name', ''); // namespace for your application
1007 $xhprof_data = xhprof_disable();
1008 $xhprof_runs = new XHProfRuns_Default();
1009 return $xhprof_runs->save_run($xhprof_data, $namespace);
1010 }
1011
1012 function devel_xhprof_link($run_id, $type = 'link') {
1013 // @todo: render results from within Drupal.
1014 $xhprof_url = variable_get('devel_xhprof_url', '');
1015 $namespace = variable_get('site_name', ''); // namespace for your application
1016 if ($xhprof_url) {
1017 $url = $xhprof_url . "/index.php?run=$run_id&source=$namespace";
1018 return $type == 'url' ? $url : t('<a href="@xhprof">XHProf output</a>. ', array('@xhprof' => $url));
1019 }
1020 }
1021
1022 function devel_shutdown_memory() {
1023 global $memory_init;
1024
1025 if (variable_get('dev_mem', FALSE)) {
1026 $memory_shutdown = memory_get_usage();
1027 $args = array('@memory_boot' => round($memory_init / 1024 / 1024, 2), '@memory_shutdown' => round($memory_shutdown / 1024 / 1024, 2), '@memory_peak' => round(memory_get_peak_usage(TRUE) / 1024 / 1024, 2));
1028 $msg = '<span class="dev-memory-usages"> Memory used at: devel_boot()=<strong>@memory_boot</strong> MB, devel_shutdown()=<strong>@memory_shutdown</strong> MB, PHP peak=<strong>@memory_peak</strong> MB.</span>';
1029 // theme() may not be available. not t() either.
1030 return t_safe($msg, $args);
1031 }
1032 }
1033
1034 function devel_shutdown_query($queries) {
1035 if (!empty($queries)) {
1036 if (function_exists('theme_get_registry') && theme_get_registry()) {
1037 // Safe to call theme('table).
1038 list($counts, $query_summary) = devel_query_summary($queries);
1039 $output = devel_query_table($queries, $counts);
1040
1041 // Save all queries to a file in temp dir. Retrieved via AJAX.
1042 devel_query_put_contents($queries);
1043 }
1044 else {
1045 $output = '</div>' . dprint_r($queries, TRUE);
1046 }
1047 return $output;
1048 }
1049 }
1050
1051 // Write the variables information to the a file. It will be retrieved on demand via AJAX.
1052 function devel_query_put_contents($queries) {
1053 $request_id = mt_rand(1, 1000000);
1054 $path = "temporary://devel_querylog";
1055
1056 // Create the devel_querylog within the temp folder, if needed.
1057 file_prepare_directory($path, FILE_CREATE_DIRECTORY);
1058
1059 // Occassionally wipe the querylog dir so that files don't accumulate.
1060 if (mt_rand(1, 1000) == 401) {
1061 devel_empty_dir($path);
1062 }
1063
1064 $path .= "/$request_id.txt";
1065 $path = file_stream_wrapper_uri_normalize($path);
1066 // Save queries as a json array. Suppress errors due to recursion ()
1067 file_put_contents($path, @json_encode($queries));
1068 $settings['devel'] = array(
1069 // A random string that is sent to the browser. It enables the AJAX to retrieve queries from this request.
1070 'request_id' => $request_id,
1071 );
1072 print '<script type="text/javascript">jQuery.extend(Drupal.settings, '. json_encode($settings) .");</script>\n";
1073 }
1074
1075 function devel_query_enabled() {
1076 return method_exists('Database', 'getLog') && variable_get('devel_query_display', FALSE);
1077 }
1078
1079 function devel_query_summary($queries) {
1080 if (variable_get('devel_query_display', FALSE) && is_array($queries)) {
1081 $sum = 0;
1082 foreach ($queries as $query) {
1083 $text[] = $query['query'];
1084 $sum += $query['time'];
1085 }
1086 $counts = array_count_values($text);
1087 return array($counts, t_safe('Executed @queries queries in @time ms.', array('@queries' => count($queries), '@time' => round($sum * 1000, 2))));
1088 }
1089 }
1090
1091 function t_safe($string, $args) {
1092 // get_t caused problems here with theme registry after changing on admin/build/modules. the theme_get_registry call is needed.
1093 if (function_exists('t') && function_exists('theme_get_registry')) {
1094 theme_get_registry();
1095 return t($string, $args);
1096 }
1097 else {
1098 strtr($string, $args);
1099 }
1100 }
1101
1102 function devel_get_core_version($version) {
1103 $version_parts = explode('.', $version);
1104 // Map from 4.7.10 -> 4.7
1105 if ($version_parts[0] < 5) {
1106 return $version_parts[0] .'.'. $version_parts[1];
1107 }
1108 // Map from 5.5 -> 5 or 6.0-beta2 -> 6
1109 else {
1110 return $version_parts[0];
1111 }
1112 }
1113
1114 // See http://drupal.org/node/126098
1115 function devel_is_compatible_optimizer() {
1116 ob_start();
1117 phpinfo();
1118 $info = ob_get_contents();
1119 ob_end_clean();
1120
1121 // Match the Zend Optimizer version in the phpinfo information
1122 $found = preg_match('/Zend&nbsp;Optimizer&nbsp;v([0-9])\.([0-9])\.([0-9])/', $info, $matches);
1123
1124 if ($matches) {
1125 $major = $matches[1];
1126 $minor = $matches[2];
1127 $build = $matches[3];
1128
1129 if ($major >= 3) {
1130 if ($minor >= 3) {
1131 return TRUE;
1132 }
1133 elseif ($minor == 2 && $build >= 8) {
1134 return TRUE;
1135 }
1136 else {
1137 return FALSE;
1138 }
1139 }
1140 else {
1141 return FALSE;
1142 }
1143 }
1144 else {
1145 return TRUE;
1146 }
1147 }
1148
1149 /**
1150 * Generates the execute block form.
1151 */
1152 function devel_execute_block_form() {
1153 $form['execute'] = array(
1154 '#type' => 'fieldset',
1155 '#title' => t('Execute PHP Code'),
1156 '#collapsible' => TRUE,
1157 '#collapsed' => (!isset($_SESSION['devel_execute_code'])),
1158 );
1159 $form['#submit'] = array('devel_execute_form_submit');
1160 return array_merge_recursive($form, devel_execute_form());
1161 }
1162
1163 /**
1164 * Generates the execute form.
1165 */
1166 function devel_execute_form() {
1167 $form['execute']['code'] = array(
1168 '#type' => 'textarea',
1169 '#title' => t('PHP code to execute'),
1170 '#description' => t('Enter some code. Do not use <code>&lt;?php ?&gt;</code> tags.'),
1171 '#default_value' => (isset($_SESSION['devel_execute_code']) ? $_SESSION['devel_execute_code'] : ''),
1172 '#rows' => 20,
1173 );
1174 $form['execute']['op'] = array('#type' => 'submit', '#value' => t('Execute'));
1175 $form['#redirect'] = FALSE;
1176 if (isset($_SESSION['devel_execute_code'])) {
1177 unset($_SESSION['devel_execute_code']);
1178 }
1179 return $form;
1180 }
1181
1182 /**
1183 * Process PHP execute form submissions.
1184 */
1185 function devel_execute_form_submit($form, &$form_state) {
1186 ob_start();
1187 print eval($form_state['values']['code']);
1188 $_SESSION['devel_execute_code'] = $form_state['values']['code'];
1189 dsm(ob_get_clean());
1190 }
1191
1192 /**
1193 * Switch from original user to another user and back.
1194 * We don't call session_save_session() because we really want to change users. Usually unsafe!
1195 *
1196 * @param $name The username to switch to, or NULL to log out.
1197 */
1198 function devel_switch_user($name = NULL) {
1199 global $user;
1200
1201 if ($user->uid) {
1202 module_invoke_all('user_logout', $user);
1203 }
1204 if (isset($name) && $account = user_load_by_name($name)) {
1205 $old_uid = $user->uid;
1206 $user = $account;
1207 $user->timestamp = time() - 9999;
1208 if (!$old_uid) {
1209 // Switch from anonymous to authorized.
1210 drupal_session_regenerate();
1211 }
1212 $edit = array();
1213 user_module_invoke('login', $edit, $user);
1214 }
1215 elseif ($user->uid) {
1216 session_destroy();
1217 }
1218 drupal_goto();
1219 }
1220
1221 /**
1222 * Print an object or array using either Krumo (if installed) or devel_print_object()
1223 *
1224 * @param $object
1225 * array or object to print
1226 * @param $prefix
1227 * prefixing for output items
1228 */
1229 function kdevel_print_object($object, $prefix = NULL) {
1230 return has_krumo() ? krumo_ob($object) : devel_print_object($object, $prefix);
1231 }
1232
1233 // Save krumo htlm using output buffering.
1234 function krumo_ob($object) {
1235 ob_start();
1236 krumo($object);
1237 $output = ob_get_contents();
1238 ob_end_clean();
1239 return $output;
1240 }
1241
1242 /**
1243 * Display an object or array
1244 *
1245 * @param $object
1246 * the object or array
1247 * @param $prefix
1248 * prefix for the output items (example "$node->", "$user->", "$")
1249 * @param $header
1250 * set to FALSE to suppress the output of the h3
1251 */
1252 function devel_print_object($object, $prefix = NULL, $header = TRUE) {
1253 drupal_add_css(drupal_get_path('module', 'devel') .'/devel.css');
1254 $output = '<div class="devel-obj-output">';
1255 if ($header) {
1256 $output .= '<h3>'. t('Display of !type !obj', array('!type' => str_replace(array('$', '->'), '', $prefix), '!obj' => gettype($object))) .'</h3>';
1257 }
1258 $output .= _devel_print_object($object, $prefix);
1259 $output .= '</div>';
1260 return $output;
1261 }
1262
1263 /**
1264 * Recursive (and therefore magical) function goes through an array or object and
1265 * returns a nicely formatted listing of its contents.
1266 *
1267 * @param $obj
1268 * array or object to recurse through
1269 * @param $prefix
1270 * prefix for the output items (example "$node->", "$user->", "$")
1271 * @param $parents
1272 * used by recursion
1273 * @param $object
1274 * used by recursion
1275 * @return
1276 * fomatted html
1277 *
1278 * @todo
1279 * currently there are problems sending an array with a varname
1280 */
1281 function _devel_print_object($obj, $prefix = NULL, $parents = NULL, $object = FALSE) {
1282 static $root_type, $out_format;
1283
1284 // TODO: support objects with references. See http://drupal.org/node/234581.
1285 if (isset($obj->view)) {
1286 return;
1287 }
1288
1289 if (!isset($root_type)) {
1290 $root_type = gettype($obj);
1291 if ($root_type == 'object') {
1292 $object = TRUE;
1293 }
1294 }
1295
1296 if (is_object($obj)) {
1297 $obj = (array)$obj;
1298 }
1299 if (is_array($obj)) {
1300 $output = "<dl>\n";
1301 foreach ($obj as $field => $value) {
1302 if ($field == 'devel_flag_reference') {
1303 continue;
1304 }
1305 if (!is_null($parents)) {
1306 if ($object) {
1307 $field = $parents .'->'. $field;
1308 }
1309 else {
1310 if (is_int($field)) {
1311 $field = $parents .'['. $field .']';
1312 }
1313 else {
1314 $field = $parents .'[\''. $field .'\']';
1315 }
1316 }
1317 }
1318
1319 $type = gettype($value);
1320
1321 $show_summary = TRUE;
1322 $summary = NULL;
1323 if ($show_summary) {
1324 switch ($type) {
1325 case 'string' :
1326 case 'float' :
1327 case 'integer' :
1328 if (strlen($value) == 0) {
1329 $summary = t("{empty}");
1330 }
1331 elseif (strlen($value) < 40) {
1332 $summary = htmlspecialchars($value);
1333 }
1334 else {
1335 $summary = format_plural(drupal_strlen($value), '1 character', '@count characters');
1336 }
1337 break;
1338 case 'array' :
1339 case 'object' :
1340 $summary = format_plural(count((array)$value), '1 element', '@count elements');
1341 break;
1342 case 'boolean' :
1343 $summary = $value ? t('TRUE') : t('FALSE');
1344 break;
1345 }
1346 }
1347 if (!is_null($summary)) {
1348 $typesum = '('. $type .', <em>'. $summary .'</em>)';
1349 }
1350 else {
1351 $typesum = '('. $type .')';
1352 }
1353
1354 $output .= '<span class="devel-attr">';
1355 $output .= "<dt><span class=\"field\">{$prefix}{$field}</span> $typesum</dt>\n";
1356 $output .= "<dd>\n";
1357 // Check for references.
1358 if (is_array($value) && isset($value['devel_flag_reference'])) {
1359 $value['devel_flag_reference'] = TRUE;
1360 }
1361 // Check for references to prevent errors from recursions.
1362 if (is_array($value) && isset($value['devel_flag_reference']) && !$value['devel_flag_reference']) {
1363 $value['devel_flag_reference'] = FALSE;
1364 $output .= _devel_print_object($value, $prefix, $field);
1365 }
1366 elseif (is_object($value)) {
1367 $value->devel_flag_reference = FALSE;
1368 $output .= _devel_print_object((array)$value, $prefix, $field, TRUE);
1369 }
1370 else {
1371 $value = is_bool($value) ? ($value ? 'TRUE' : 'FALSE') : $value;
1372 $output .= htmlspecialchars(print_r($value, TRUE)) ."\n";
1373 }
1374 $output .= "</dd></span>\n";
1375 }
1376 $output .= "</dl>\n";
1377 }
1378 return $output;
1379 }
1380
1381 /**
1382 * Adds a table at the bottom of the page cataloguing data on all the database queries that were made to
1383 * generate the page.
1384 */
1385 function devel_query_table($queries, $counts) {
1386 $version = devel_get_core_version(VERSION);
1387 $header = array ('ms', '#', 'where', 'ops', 'query', 'target');
1388 $i = 0;
1389 $api = variable_get('devel_api_url', 'api.drupal.org');
1390 foreach ($queries as $query) {
1391 $function = !empty($query['caller']['class']) ? $query['caller']['class'] . '::' : '';
1392 $function .= $query['caller']['function'];
1393 $count = isset($counts[$query['query']]) ? $counts[$query['query']] : 0;
1394
1395 $diff = round($query['time'] * 1000, 2);
1396 if ($diff > variable_get('devel_execution', 5)) {
1397 $cell[$i][] = array ('data' => $diff, 'class' => 'marker');
1398 }
1399 else {
1400 $cell[$i][] = $diff;
1401 }
1402 $cell[$i][] = $count;
1403 $cell[$i][] = l($function, "http://$api/api/function/$function/$version");
1404 $ops[] = l('P', '', array('attributes' => array('title' => 'Show placeholders', 'class' => 'dev-placeholders', 'qid' => $i)));
1405 $ops[] = l('A', '', array('attributes' => array('title' => 'Show arguments', 'class' => 'dev-arguments', 'qid' => $i)));
1406 // EXPLAIN only valid for select queries.
1407 if (strpos($query['query'], 'UPDATE') === FALSE && strpos($query['query'], 'INSERT') === FALSE && strpos($query['query'], 'DELETE') === FALSE) {
1408 $ops[] = l('E', '', array('attributes' => array('title' => 'Show EXPLAIN', 'class' => 'dev-explain', 'qid' => $i)));
1409 }
1410 $cell[$i][] = implode(' ', $ops);
1411 // 3 divs for each variation of the query. Last 2 are hidden by default.
1412 $placeholders = '<div class="dev-placeholders">' . check_plain($query['query']) . "</div>\n";
1413 $args = '<div class="dev-arguments" style="display: none;"></div>' . "\n";
1414 $explain = '<div class="dev-explain" style="display: none;"></div>' . "\n";
1415 $cell[$i][] = array(
1416 'id' => "devel-query-$i",
1417 'data' => $placeholders . $args . $explain,
1418 );
1419 $cell[$i][] = $query['target'];
1420 $i++;
1421 unset($diff, $count, $ops);
1422 }
1423 if (variable_get('devel_query_sort', DEVEL_QUERY_SORT_BY_SOURCE)) {
1424 usort($cell, '_devel_table_sort');
1425 }
1426 return theme('devel_querylog', array('header' => $header, 'rows' => $cell));
1427 }
1428
1429 function theme_devel_querylog_row($variables) {
1430 $row = $variables['row'];
1431 $i = 0;
1432 $output = '';
1433 foreach ($row as $cell) {
1434 $i++;
1435
1436 if (is_array($cell)) {
1437 $data = !empty($cell['data']) ? $cell['data'] : '';
1438 unset($cell['data']);
1439 $attr = $cell;
1440 }
1441 else {
1442 $data = $cell;
1443 $attr = array();
1444 }
1445
1446 if (!empty($attr['class'])) {
1447 $attr['class'] .= " cell cell-$i";
1448 }
1449 else {
1450 $attr['class'] = "cell cell-$i";
1451 }
1452 $attr = drupal_attributes($attr);
1453
1454 $output .= "<div $attr>$data</div>";
1455 }
1456 return $output;
1457 }
1458
1459 function theme_devel_querylog($variables) {
1460 $header = $variables['header'];
1461 $rows = $variables['rows'];
1462 $output = '';
1463 if (!empty($header)) {
1464 $output .= "<div class='devel-querylog devel-querylog-header clear-block'>";
1465 $output .= theme('devel_querylog_row', array('row' => $header));
1466 $output .= "</div>";
1467 }
1468 if (!empty($rows)) {
1469 $i = 0;
1470 foreach ($rows as $row) {
1471 $i++;
1472 $zebra = ($i % 2) == 0 ? 'even' : 'odd';
1473 $output .= "<div class='devel-querylog devel-querylog-$zebra clear-block'>";
1474 $output .= theme('devel_querylog_row', array('row' => $row));
1475 $output .= "</div>";
1476 }
1477 }
1478 return $output;
1479 }
1480
1481 function _devel_table_sort($a, $b) {
1482 $a = is_array($a[0]) ? $a[0]['data'] : $a[0];
1483 $b = is_array($b[0]) ? $b[0]['data'] : $b[0];
1484 if ($a < $b) {
1485 return 1;
1486 }
1487 if ($a > $b) {
1488 return -1;
1489 }
1490 return 0;
1491 }
1492
1493 /**
1494 * Displays page execution time at the bottom of the page.
1495 */
1496 function devel_timer() {
1497 $time = timer_read('page');
1498 return t_safe(' Page execution time was @time ms.', array('@time' => $time));
1499 }
1500
1501 // An alias for drupal_debug().
1502 function dd($data, $label = NULL) {
1503 return drupal_debug($data, $label);
1504 }
1505
1506 // Log any variable to a drupal_debug.log in the site's temp directory.
1507 // See http://drupal.org/node/314112
1508 function drupal_debug($data, $label = NULL) {
1509 ob_start();
1510 print_r($data);
1511 $string = ob_get_clean();
1512 if ($label) {
1513 $out = $label .': '. $string;
1514 }
1515 else {
1516 $out = $string;
1517 }
1518 $out .= "\n";
1519
1520 // The temp directory does vary across multiple simpletest instances.
1521 $file = 'temporary://drupal_debug.txt';
1522 if (file_put_contents($file, $out, FILE_APPEND) === FALSE) {
1523 drupal_set_message(t('The file could not be written.'), 'error');
1524 return FALSE;
1525 }
1526 }
1527
1528 /**
1529 * Prints the arguments passed into the current function
1530 */
1531 function dargs($always = TRUE) {
1532 static $printed;
1533 if ($always || !$printed) {
1534 $bt = debug_backtrace();
1535 print kdevel_print_object($bt[1]['args']);
1536 $printed = TRUE;
1537 }
1538 }
1539
1540 /**
1541 * Print a SQL string from a DBTNG Query object. Includes quoted arguments.
1542 *
1543 * @param $query
1544 * A Query object.
1545 * @param $return
1546 * Whether to return or print the string. Default to FALSE.
1547 * @param $name
1548 * Optional name for identifying the output.
1549 */
1550 function dpq($query, $return = FALSE, $name = NULL) {
1551 if (user_access('access devel information')) {
1552 $query->preExecute();
1553 $sql = (string) $query;
1554 $quoted = array();
1555 $connection = Database::getConnection();
1556 foreach ((array)$query->arguments() as $key => $val) {
1557 $quoted[$key] = $connection->quote($val);
1558 }
1559 $sql = strtr($sql, $quoted);
1560 if ($return) {
1561 return $sql;
1562 }
1563 else {
1564 dpm($sql, $name);
1565 }
1566 }
1567 }
1568
1569 /**
1570 * Print a variable to the 'message' area of the page. Uses drupal_set_message()
1571 */
1572 function dpm($input, $name = NULL) {
1573 if (user_access('access devel information')) {
1574 $export = kprint_r($input, TRUE, $name);
1575 drupal_set_message($export);
1576 }
1577 }
1578
1579 /**
1580 * drupal_var_export() a variable to the 'message' area of the page. Uses drupal_set_message()
1581 */
1582 function dvm($input, $name = NULL) {
1583 if (user_access('access devel information')) {
1584 $export = dprint_r($input, TRUE, $name, 'drupal_var_export', FALSE);
1585 drupal_set_message($export);
1586 }
1587 }
1588
1589 // legacy function that was poorly named. use dpm() instead, since the 'p' maps to 'print_r'
1590 function dsm($input, $name = NULL) {
1591 dpm($input, $name);
1592 }
1593
1594 /**
1595 * An alias for dprint_r(). Saves carpal tunnel syndrome.
1596 */
1597 function dpr($input, $return = FALSE, $name = NULL) {
1598 return dprint_r($input, $return, $name);
1599 }
1600
1601 /**
1602 * An alias for kprint_r(). Saves carpal tunnel syndrome.
1603 */
1604 function kpr($input, $return = FALSE, $name = NULL) {
1605 return kprint_r($input, $return, $name);
1606 }
1607
1608 /**
1609 * Like dpr, but uses drupal_var_export() instead
1610 */
1611 function dvr($input, $return = FALSE, $name = NULL) {
1612 return dprint_r($input, $return, $name, 'drupal_var_export', FALSE);
1613 }
1614
1615 function kprint_r($input, $return = FALSE, $name = NULL, $function = 'print_r') {
1616 // We do not want to krumo() strings and integers and such
1617 if (merits_krumo($input)) {
1618 if (user_access('access devel information')) {
1619 return $return ? (isset($name) ? $name .' => ' : '') . krumo_ob($input) : krumo($input);
1620 }
1621 }
1622 else {
1623 return dprint_r($input, $return, $name, $function);
1624 }
1625 }
1626
1627 /**
1628 * Pretty-print a variable to the browser (no krumo).
1629 * Displays only for users with proper permissions. If
1630 * you want a string returned instead of a print, use the 2nd param.
1631 */
1632 function dprint_r($input, $return = FALSE, $name = NULL, $function = 'print_r', $check= TRUE) {
1633 if (user_access('access devel information')) {
1634 if ($name) {
1635 $name .= ' => ';
1636 }
1637 if ($function == 'drupal_var_export') {
1638 include_once DRUPAL_ROOT . '/includes/utility.inc';
1639 $output = drupal_var_export($input);
1640 }
1641 else {
1642 ob_start();
1643 $function($input);
1644 $output = ob_get_clean();
1645 }
1646
1647 if ($check) {
1648 $output = check_plain($output);
1649 }
1650 if (count($input, COUNT_RECURSIVE) > DEVEL_MIN_TEXTAREA) {
1651 // don't use fapi here because sometimes fapi will not be loaded
1652 $printed_value = "<textarea rows=30 style=\"width: 100%;\">\n". $name . $output .'</textarea>';
1653 }
1654 else {
1655 $printed_value = '<pre>'. $name . $output .'</pre>';
1656 }
1657
1658 if ($return) {
1659 return $printed_value;
1660 }
1661 else {
1662 print $printed_value;
1663 }
1664 }
1665 }
1666
1667 /**
1668 * Prints a renderable array element to the screen using kprint_r().
1669 *
1670 * #pre_render and/or #post_render pass-through callback for kprint_r().
1671 *
1672 * @todo Investigate appending to #suffix.
1673 * @todo Investigate label derived from #id, #title, #name, and #theme.
1674 */
1675 function devel_render() {
1676 $args = func_get_args();
1677 // #pre_render and #post_render pass the rendered $element as last argument.
1678 kprint_r(end($args));
1679 // #pre_render and #post_render expect the first argument to be returned.
1680 return reset($args);
1681 }
1682
1683 /**
1684 * Print the function call stack.
1685 */
1686 function ddebug_backtrace() {
1687 if (user_access('access devel information')) {
1688 $trace = debug_backtrace();
1689 array_shift($trace);
1690 $count = count($trace);
1691 foreach ($trace as $i => $call) {
1692 $key = ($count - $i) . ': ' . $call['function'];
1693 $rich_trace[$key] = $call;
1694 }
1695 if (has_krumo()) {
1696 print krumo($rich_trace);
1697 }
1698 else {
1699 dprint_r($rich_trace);
1700 }
1701 }
1702 }
1703
1704 // Delete all files in a dir. http://www.plus2net.com/php_tutorial/php-files-delete.php
1705 function devel_empty_dir($dir) {
1706 foreach (new DirectoryIterator($dir) as $fileInfo) {
1707 unlink($fileInfo->getPathname());
1708 }
1709 }
1710
1711 /*
1712 * migration related functions
1713 */
1714
1715 /**
1716 * Regenerate the data in node_comment_statistics table. Technique comes from
1717 * http://www.artfulsoftware.com/infotree/queries.php?&bw=1280#101
1718 *
1719 * @return void
1720 **/
1721 function devel_rebuild_node_comment_statistics() {
1722 // Empty table
1723 db_truncate('node_comment_statistics')->execute();
1724
1725 // TODO: DBTNG. Ignore keyword is Mysql only? Is only used in the rare case when
1726 // two comments on the same node share same timestamp.
1727 $sql = "
1728 INSERT IGNORE INTO {node_comment_statistics} (nid, cid, last_comment_timestamp, last_comment_name, last_comment_uid, comment_count) (
1729 SELECT c.nid, c.cid, c.created, c.name, c.uid, c2.comment_count FROM {comment} c
1730 JOIN (
1731 SELECT c.nid, MAX(c.created) AS created, COUNT(*) AS comment_count FROM {comment} c WHERE status = 1 GROUP BY c.nid
1732 ) AS c2 ON c.nid = c2.nid AND c.created = c2.created
1733 )";
1734 db_query($sql, array(':published' => COMMENT_PUBLISHED));
1735
1736 // Insert records into the node_comment_statistics for nodes that are missing.
1737 $query = db_select('node', 'n');
1738 $query->leftJoin('node_comment_statistics', 'ncs', 'ncs.nid = n.nid');
1739 $query->addField('n', 'changed', 'last_comment_timestamp');
1740 $query->addField('n', 'uid', 'last_comment_uid');
1741 $query->addField('n', 'nid');
1742 $query->addExpression('0', 'comment_count');
1743 $query->addExpression('NULL', 'last_comment_name');
1744 $query->isNull('ncs.comment_count');
1745
1746 db_insert('node_comment_statistics')
1747 ->from($query)
1748 ->execute();
1749 }