summaryrefslogtreecommitdiffstats
path: root/devel.module
blob: 44a4eb089c4cf1f1c50e037be2e27af2dbdda6b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
<?php
// $Id$

// This module holds functions useful for Drupal development.
// Please contribute!

// Suggested profiling and stacktrace library from http://www.xdebug.org/index.php

define('DEVEL_QUERY_SORT_BY_SOURCE', 0);
define('DEVEL_QUERY_SORT_BY_DURATION', 1);

define('DEVEL_ERROR_HANDLER_NONE', 0);
define('DEVEL_ERROR_HANDLER_STANDARD', 1);
define('DEVEL_ERROR_HANDLER_BACKTRACE', 2);

define('DEVEL_MIN_TEXTAREA', 50);

/**
 * Implementation of hook_help().
 */
function devel_help($section) {
  switch ($section) {
    case 'devel/reference':
      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>';
    case 'devel/reinstall':
      return '<p>'. t('Clicking a module\'s reinstall button will simulate uninstalling/installing a module. <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. You may have to manually clear out any existing tables first if the module doesn\'t implement <code>hook_uninstall()</code>.'). '</p>';
    case 'devel/session':
      return '<p>'. t('Here are the contents of your <code>$_SESSION</code> variable.'). '</p>';
    case 'devel/variable':
      $api = variable_get('devel_api_url', 'api.drupal.org');
      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>';
  }
}

/**
 * Implementation of hook_menu().
 */
function devel_menu() {
  $items = array();

  $items['devel/cache/clear'] = array(
    'title' => 'Empty cache',
    'page callback' => 'devel_cache_clear',
    'access arguments' => array('access devel information'),
    'type' => MENU_CALLBACK,
  );
  $items['devel/rebuild_node_comment_statistics'] = array(
    'title' => 'Rebuild node_comment_statistics table',
    'page callback' => 'devel_rebuild_node_comment_statistics_page',
    'access' => array('access devel information'),
    'type' => MENU_CALLBACK,
  );
  if (variable_get('devel_store_queries', 0)) {
    $items['devel/queries'] = array(
      'title' => 'Database queries',
      'page callback' => 'devel_queries',
      'access arguments' => array('access devel information'));
    $items['devel/queries/empty'] = array(
      'title' => 'Empty database queries',
      'page callback' => 'devel_queries_empty',
      'access arguments' => array('access devel information'),
      'type' => MENU_CALLBACK);
  }
  $items['devel/reference'] = array(
    'title' => 'function reference',
    'page callback' => 'devel_function_reference',
    'access arguments' => array('access devel information'),
    'type' => MENU_CALLBACK,
  );
  $items['devel/reinstall'] = array(
    'title' => 'Reinstall modules',
    'page callback' => 'devel_reinstall',
    'access arguments' => array('access devel information'),
    'type' => MENU_CALLBACK,
  );
  $items['devel/menu/reset'] = array(
    'title' => 'Reset menus',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('devel_menu_reset'),
    'access arguments' => array('access devel information'),
    'type' => MENU_CALLBACK,
  );
  $items['devel/variable'] = array(
    'title' => 'Variable editor',
    'page callback' => 'devel_variable_page',
    'access arguments' => array('access devel information'),
    'type' => MENU_CALLBACK,
  );
  // we don't want the abbreviated version provided by status report
  $items['devel/phpinfo'] = array(
    'title' => 'PHPinfo()',
    'page callback' => 'devel_phpinfo',
    'access arguments' => array('access devel information'),
    'type' => MENU_CALLBACK,
  );
  $items['devel/theme/registry'] = array(
    'title' => 'Theme registry',
    'page callback' => 'devel_theme_registry',
    'access arguments' => array('access devel information'),
    'type' => MENU_CALLBACK,
  );
  $items['devel/elements'] = array(
    'title' => 'hook_elements()',
    'page callback' => 'devel_elements_page',
    'access arguments' => array('access devel information'),
    'type' => MENU_CALLBACK,
  );
  $items['devel/variable/edit/%'] = array(
    'title' => 'Variable editor',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('devel_variable_edit', 3),
    'access arguments' => array('access devel information'),
    'type' => MENU_CALLBACK,
  );
  $items['devel/session'] = array(
    'title' => 'Session viewer',
    'page callback' => 'devel_session',
    'access arguments' => array('access devel information'),
    'type' => MENU_CALLBACK,
  );
  $items['devel/switch'] = array(
    'title' => 'Switch user',
    'page callback' => 'devel_switch_user',
    'access arguments' => array('switch users'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/settings/devel'] = array(
    'title' => 'Devel',
    'description' =>  'Helper functions, pages, and blocks to assist Drupal developers. The devel blocks can be managed via the !block page.', array('!block' => l(t('block administration'), 'admin/build/block')),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('devel_admin_settings'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM
  );
  $items['node/%node/load'] = array(
    'title' => 'Dev load',
    'page callback' => 'devel_load_object',
    'page arguments' => array(1, 'node'),
    'access callback' => 'user_access',
    'access arguments' => array('access devel information'),
    'type' => MENU_LOCAL_TASK,
  );
  $items['node/%node/render'] = array(
    'title' => 'Dev render',
    'page callback' => 'devel_render_object',
    'page arguments' => array('node', 1),
    'access callback' => 'user_access',
    'access arguments' => array('access devel information'),
    'type' => MENU_LOCAL_TASK,
  );
  $items['user/%user/load'] = array(
    'title' => 'Devel load',
    'page callback' => 'devel_load_object',
    'page arguments' => array(1, 'user'),
    'access callback' => 'user_access',
    'access arguments' => array('access devel information'),
    'type' => MENU_LOCAL_TASK,
  );
  $items['user/%user/render'] = array(
    'title' => 'Dev render',
    'page callback' => 'devel_render_object',
    'page arguments' => array('user', 1),
    'access callback' => 'user_access',
    'access arguments' => array('access devel information'),
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

/**
 * Implementation of hook_theme()
 */
function devel_theme() { // &$cache, $type, $theme, $path
  return array(
    'devel_variable_form' => array(
        'arguments' => array('form' => NULL)
    ),
  );
}

/**
 * Implementation of hook_init().
 */
function devel_init() {
  if (!devel_silent()) {
    if (user_access('access devel information')) {
      devel_set_handler(variable_get('devel_error_handler', DEVEL_ERROR_HANDLER_STANDARD));
      // we want to include the class early so that anyone may call krumo() as needed.
      has_krumo();
    }
  }
}

// return boolean. no need for cache here.
function has_krumo() {
  // see README.txt or just download from http://krumo.sourceforge.net/
  @include_once './'. drupal_get_path('module', 'devel'). '/krumo/class.krumo.php';
  if (function_exists('krumo')) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

function devel_set_handler($handler) {
  switch ($handler) {
    case DEVEL_ERROR_HANDLER_STANDARD:
      // do nothing
      break;
    case DEVEL_ERROR_HANDLER_BACKTRACE:
      if(has_krumo()) {
        set_error_handler('backtrace_error_handler');
      }
      break;
    case DEVEL_ERROR_HANDLER_NONE:
      restore_error_handler();
      break;
  }
}


function devel_silent() {
  // isset($_GET['q']) is needed on IIS when calling the front page. q is not set.
  // Don't interfere with private files/images.
  return isset($GLOBALS['devel_shutdown']) || strstr($_SERVER['PHP_SELF'], 'update.php') || (isset($_GET['q']) && (in_array($_GET['q'], array('upload/js')) || substr($_GET['q'], 0, strlen('system/files')) == 'system/files'));
}

/**
 * Implementation of hook_boot(). Runs even for cached pages.
 */
function devel_boot() {
  if (!devel_silent()) {
    devel_start();
  }
}

// kickoff all our tricks. put here all code which must run for ached pages too. called from both hook_boot and hook_init.
function devel_start() {
  if (variable_get('dev_mem', 0) && function_exists('memory_get_usage')) {
    global $memory_init;
    $memory_init = memory_get_usage();
  }

  // we need user_access() in the shutdown function. make sure it gets loaded
  drupal_load('module', 'user');
  register_shutdown_function('devel_shutdown');
}

function backtrace_error_handler($errno, $message, $filename, $line) {
  if ($errno & (E_ALL ^ E_NOTICE)) {
    $types = array(1 => 'error', 2 => 'warning', 4 => 'parse error', 8 => 'notice', 16 => 'core error', 32 => 'core warning', 64 => 'compile error', 128 => 'compile warning', 256 => 'user error', 512 => 'user warning', 1024 => 'user notice', 2048 => 'strict warning');
    $entry = $types[$errno] .': '. $message .' in '. $filename .' on line '. $line .'.';

    if (variable_get('error_level', 1) == 1) {
      $backtrace = debug_backtrace();
      foreach ($backtrace as $call) {
        $nicetrace[$call['function']] = $call;
      }
      krumo($nicetrace);
    }

    watchdog('php', '%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line), WATCHDOG_ERROR);
  }
}

/**
 * Implementation of hook_perm().
 */
function devel_perm() {
  return array('access devel information', 'execute php code', 'switch users');
}

/**
 * Implementation of hook_block().
 */
function devel_block($op = 'list', $delta = 0) {
  if ($op == 'list') {
    $blocks[0]['info'] = t('Switch user');
    $blocks[1]['info'] = t('Devel');
    $blocks[2]['info'] = t('Execute PHP');
    return $blocks;
  }
  else if ($op == 'view') {
    $block = array();
    switch ($delta) {
      case 0:
        $block = devel_block_switch_user();
        break;
      case 1:
        $block = devel_block_devel();
        break;
      case 2:
        if (user_access('execute php code')) {
          $block['subject'] = t('Execute PHP');
          $block['content'] = drupal_get_form('devel_execute_form');
        }
        break;
    }
    return $block;
  }
}

function devel_block_devel() {
  $links = array();
  $block['subject'] = t('devel');
  if (user_access('access devel information')) {
    $links[] = l(t('Devel settings'), 'admin/settings/devel', array('attributes' => array('title' => t('Adjust module settings for devel module.'))));
    $links[] = l(t('Empty cache'), 'devel/cache/clear', array('attributes' => array('title' => t('Clear the CSS cache and all database cache tables which store page, node, theme and variable caches.')), 'query' => drupal_get_destination()));
    $links[] = l(t('PHPinfo()'), 'devel/phpinfo', array('attributes' => array('title' => t('Display information about your PHP installation.'))));

    $mini[] = l(t('func'), 'devel/reference', array('attributes' => array('title' => t('View a list of currently defined user functions with documentation links.'))));
    $mini[] = l(t('theme'), 'devel/theme/registry', array('attributes' => array('title' => t('View a list of available theme functions acros the whole site.'))));
    $mini[] = l(t('elements'), 'devel/elements', array('attributes' => array('title' => t('View the active form/render elements for this site.'))));
    $mini[] = l(t('sess'), 'devel/session', array('attributes' => array('title' => t('List the contents of $_SESSION.'))));
    $links[] = implode('&nbsp;&nbsp;', $mini);

    $links[] = l(t('Reinstall modules'), 'devel/reinstall', array('attributes' => array('title' => t('Re-run hook_install() for a given module.')), 'query' => drupal_get_destination()));
    $links[] = l(t('Rebuild menus'), 'devel/menu/reset', array('attributes' => array('title' => t('Rebuild menu based on hook_menu() and any custom changes all menu items to their default settings.')), 'query' => drupal_get_destination()));
    $links[] = l(t('Variable editor'), 'devel/variable', array('attributes' => array('title' => t('Edit and delete site variables.'))));
    // of limited usefulness
    // $links[] = l('Rebuild NCS table', 'devel/rebuild_node_comment_statistics', array('title' => t('Rebuild node_comment_statistics table'), 'query' => drupal_get_destination()));
  }
  if (function_exists('devel_node_access_perm') && user_access(DNA_ACCESS_VIEW)) {
    // True only if devel_node_access enabled.
    $links[] = l(t('Node access summary'), 'devel/node_access/summary');
  }

  if ($links) {
    $block['content'] = theme('item_list', $links). drupal_get_form('devel_doc_function_form');
    return $block;
  }
}

function devel_block_switch_user() {
  $block['subject'] = t('Switch user');
  $links = array();
  if (user_access('switch users')) {
    $dest = drupal_get_destination();
    // Try to find at least 10 users that can switch.
    $roles = user_roles(1, 'switch users');
    if (isset($roles[2])) {
      // If authenticated users have this permission, just grab
      // the last 10 users, since there won't be records in
      // {user_roles} and every user on the system can switch.
      $users = db_query_range("SELECT DISTINCT u.uid, u.name, u.access FROM {users} u WHERE u.uid > 0 ORDER BY u.access DESC", 0, 10);
    }
    else {
      $where = array('u.uid = 1');
      if (count($roles)) {
        $where[] = 'r.rid IN ('. implode(',', array_keys($roles)) .')';
      }
      $where_sql = implode(' OR ', $where);
      $users = db_query_range("SELECT DISTINCT u.uid, u.name, u.access FROM {users} u LEFT JOIN {users_roles} r ON u.uid = r.uid WHERE $where_sql ORDER BY u.access DESC", 0, 10);
    }
    while ($user = db_fetch_object($users)) {
      $links[$user->uid] = l(theme('placeholder', $user->name), 'devel/switch/'. $user->name, array('attributes' => array('title' => t('This user can switch back.')), 'query' => $dest, 'html' => TRUE));
    }
    $num_links = count($links);
    if ($num_links < 10) {
      // If we don't have enough, add distinct uids until we hit 10.
      $users = db_query_range('SELECT uid, name, access FROM {users} WHERE uid > 0 AND uid NOT IN ('. implode(',', array_keys($links)) .') ORDER BY access DESC', 0, 10 - $num_links);
      while (($user = db_fetch_object($users)) && count($links) < 10) {
        $links[$user->uid] = l($user->name ? $user->name : 'anon', 'devel/switch/'. $user->name, array('attributes' => array('title' => t('Caution: this user will be unable switch back.')), 'query' => $dest));
      }
    }
  }
  if (!empty($links)) {
    $block['content'] = theme('item_list', $links);
    $block['content'] .= drupal_get_form('devel_switch_user_form');
    return $block;
  }
}

function devel_phpinfo() {
  print phpinfo();
  exit;
}

function devel_switch_user_form() {
  $form['username'] = array(
    '#type' => 'textfield',
    '#description' => t('Enter username'),
    '#size' => 16,
    '#maxlength' => 255,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Switch'),
  );
  return $form;

}

function devel_doc_function_form() {
  $version = drupal_major_version_map(VERSION);
  $form['function'] = array(
    '#type' => 'textfield',
    '#description' => t('Enter function name for api lookup'),
    '#size' => 16,
    '#maxlength' => 255,
  );
  $form['version'] = array('#type' => 'value', '#value' => $version);
  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

function devel_doc_function_form_submit($form, &$form_state) {
  $version = $form_state['values']['version'];
  $function = $form_state['values']['function'];
  $api = variable_get('devel_api_url', 'api.drupal.org');
  $form_state['redirect'] =   "http://$api/api/$version/function/$function";
}

function devel_switch_user_form_validate($form, &$form_state) {
  if (!$account = user_load(array('name' => $form_state['values']['username']))) {
    form_set_error('username', t('Username not found'));
  }
}

function devel_switch_user_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'devel/switch/'. $form_state['values']['username'];
}


/**
 * TODO: i switched params as per http://drupal.org/node/144132#form-alter but needs work still
 * Implementation of hook_form_alter().
 */
function devel_form_alter(&$form, $form_state, $form_id, $key_in = NULL) {
  if (user_access('access devel information') && variable_get('devel_form_weights', 0)) {
    $children = element_children($form);
    if (empty($children)) {
      if (isset($form['#type']) && !in_array($form['#type'], array('value', 'hidden'))) {
        if (!isset($form['#title'])) {
          $form['#title'] = '';
        }
        $form['#title'] .= " (key=$key_in, weight=". (isset($form['#weight']) ? $form['#weight'] : 0) .')';
      }
    }
    else {
      foreach (element_children($form) as $key) {
        // We need to add the weight to fieldsets.
        if (element_children($form[$key])) { // Which are a container of others.
          if (!isset($form[$key]['#title'])) {
            $form[$key]['#title'] = '';
          }
          $form[$key]['#title'] .= " (key=$key, weight=". (isset($form[$key]['#weight']) ? $form[$key]['#weight'] : 0) .')';
        }
        devel_form_alter($form[$key], $form_state, $form_id, $key);
      }
    }
  }
}

function devel_exit($destination = NULL) {
  global $user;

  if (isset($destination)) {
    // The page we are leaving is a drupal_goto(). Present a redirection page
    // so that the developer can see the intermediate query log.
    if (isset($user) && user_access('access devel information') && variable_get('devel_redirect_page', 0)) {
      $output = t('<p>The user is being redirected to <a href="@destination">@destination</a>.</p>', array('@destination' => $destination));
      print theme('page', $output);

      // Don't allow the automatic redirect to happen.
      drupal_page_footer();
      exit();
    }
    else {
      $GLOBALS['devel_redirecting'] = TRUE;
    }
  }
}

/**
 * See devel_start() which registers this function as a shutdown function. Displays developer information in the footer.
 */
function devel_shutdown() {
  global $queries, $memory_init, $user;
  $output = $txt = '';

  // set $GLOBALS['devel_shutdown'] = FALSE in order to supress the devel footer for a page. not necessary if your page
  // outputs a text/javascript or text/xml Content-type http header. Thats advised where applicable.
  if (!isset($GLOBALS['devel_shutdown']) && !isset($GLOBALS['devel_redirecting'])) {
    // Try not to break non html pages.
    if (function_exists('drupal_get_headers')) {
      $headers = drupal_get_headers();
      if(strstr($headers, 'xml') || strstr($headers, 'javascript') || strstr($headers, 'plain') || strstr($headers, 'image')) {
        return;
      }
    }

    // don't append gunk to CLI scripts
    if (empty($_SERVER['REQUEST_METHOD'])) {
      return;
    }

    if (isset($user) && user_access('access devel information')) {
      list($counts, $query_summary) = devel_query_summary();
      // Query log off, timer on.
      if (!variable_get('devel_query_display', 0) && variable_get('dev_timer', 0)) {
        $output .= '<div class="dev-timer">'. devel_timer() .' '. $query_summary. '</div>';
      }

      // Query log on.
      $sum = 0;
      if (variable_get('devel_query_display', FALSE)) {
        $output .= '<div class="dev-query">';
        $output .= $query_summary;
        // calling theme() during shutdown is very bad if registry gets rebuilt like when making a change on  admin/build/modules
        // so we check for presence of theme registry before calling theme('table'  )
        if (function_exists('theme_get_registry') && theme_get_registry()) {
          $txt = t_safe(' Queries taking longer than %threshold ms and queries executed more than once, are <span class="marker">highlighted</span>.', array('%threshold' => variable_get('devel_execution', 5)));
          if (variable_get('dev_timer', 0)) {
            $txt .= devel_timer();
          }
          $output .= $txt. devel_query_table($queries, $counts);
        }
        else {
          $output .= $txt;
          ob_start();
          dprint_r($queries);
          $output .= ob_get_clean();
        }
        $output .= '</div>';
      }

      if (variable_get('dev_mem', FALSE) && function_exists('memory_get_usage')) {
        $memory_shutdown = memory_get_usage();
        $args = array('%memory_init' => round($memory_init / 1024 / 1024, 2), '%memory_shutdown' => round($memory_shutdown / 1024 / 1024, 2));
        $msg = '<div class="dev-memory-usage"><h3>Memory usage:</h3> Memory used at: devel_init()=<strong>%memory_init</strong> MB, devel_shutdown()=<strong>%memory_shutdown</strong> MB.</div>';
        // theme() may not be available. not t() either.
        $output .= t_safe($msg, $args);
      }
      // TODO: gzip this text if we are sending a gzip page. see drupal_page_header().
    }

    if ($output) {
      print $output;
    }
  }
  devel_store_queries();
}

function devel_store_queries() {
  if (variable_get('devel_store_queries', 0) && rand(1, variable_get('devel_store_random', 1)) == 1) {
    global $active_db, $queries;
    $qids = array();
    $values = array();
    $fields = array();
    // We need this for the devel_queries insert below.
    setlocale(LC_NUMERIC, 'C');
    foreach ($queries as $value) {
      list($function, $query) = explode("\n", $value[0]);
      $query = preg_replace(array("/'.*'/s", "/\d.*\.\d.*/", "/\d.*/"), array("S", "F", "D"), $query);
      $hash = md5($function . $query);
      if (!isset($qids[$hash])) {
        $qids[$hash] = db_result(devel_db_query("SELECT qid FROM {devel_queries} WHERE hash = '%s'", $hash));
        if (!$qids[$hash]) {
          devel_db_query("INSERT INTO {devel_queries} (query, function, hash) VALUES ('%s', '%s', '%s')", $query, $function, $hash);
          $qids[$hash] = mysql_insert_id();
        }
      }
      $fields[] = "(%d, '%f')";
      $values[] = $qids[$hash];
      $values[] = $value[1];
    }
    if (count($fields)) {
      devel_db_query('INSERT INTO {devel_times} (qid, time) VALUES '. implode(',', $fields), $values);
    }
  }
}

function devel_query_summary() {
  if (variable_get('dev_query', FALSE)) {
    global $queries;
    $sum = 0;
    foreach ($queries as $query) {
      $text[] = $query[0];
      $sum += $query[1];
    }
    $counts = array_count_values($text);
    return array($counts, t_safe('Executed %queries queries in %time milliseconds.', array('%queries' => count($queries), '%time' => round($sum * 1000, 2))));
  }
}

function t_safe($string, $args) {
  // get_t caused problems here with theme registry after changing on admin/build/modules. the theme_get_registry call is needed.
  if (function_exists('t') && function_exists('theme_get_registry')) {
    theme_get_registry();
    return t($string, $args);
  }
  else {
    strtr($string, $args);
  }
}

/**
 * Returns a list of all currently defined user functions in the current
 * request lifecycle, with links their documentation.
 */
function devel_function_reference() {
  $functions = get_defined_functions();
  $version = drupal_major_version_map(VERSION);
  $ufunctions = $functions['user'];
  sort($ufunctions);
  $api = variable_get('devel_api_url', 'api.drupal.org');
  foreach($ufunctions as $function) {
    $links[] = l($function, "http://$api/api/$version/function/$function");
  }
  return theme('item_list', $links);
}

// verify the keys in map
function drupal_major_version_map($version = NULL) {
  $map = array(
    '4.7' => '4.7',
    '5.1' => '5.1',
    '6.0' => '6.0',
    '6.0-dev' => 'HEAD',
  );
  return $version ? $map[$version] : $map;
}

function devel_db_query($query) {
  global $active_db;
  $args = func_get_args();
  array_shift($args);
  $query = db_prefix_tables($query);
  if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
    $args = $args[0];
  }
  _db_query_callback($args, TRUE);
  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
  return mysql_query($query, $active_db);
}

function devel_admin_settings() {
  $form['queries'] = array('#type' => 'fieldset', '#title' => t('Query log'));
  $form['queries']['dev_query'] = array('#type' => 'checkbox',
    '#title' => t('Collect query info'),
    '#default_value' => variable_get('dev_query', 0),
    '#description' => t("Collect query info. If disabled, no query log functionality will work."));
  $form['queries']['devel_query_display'] = array('#type' => 'checkbox',
    '#title' => t('Display query log'),
    '#default_value' => variable_get('devel_query_display', 0),
    '#description' => t('Display a log of the database queries needed to generate the current page, and the execution time for each. Also, queries which are repeated during a single page view are summed in the # column, and printed in red since they are candidates for caching.'));
  $form['queries']['devel_query_sort'] = array('#type' => 'radios',
    '#title' => t('Sort query log'),
    '#default_value' =>   variable_get('devel_query_sort', DEVEL_QUERY_SORT_BY_SOURCE),
    '#options' => array(t('by source'), t('by duration')),
    '#description' => t('The query table can be sorted in the order that the queries were executed or by descending duration.'),
  );
  $form['queries']['devel_execution'] = array('#type' => 'textfield',
    '#title' => t('Slow query highlighting'),
    '#default_value' => variable_get('devel_execution', 5),
    '#size' => 4,
    '#maxlength' => 4,
    '#description' => t('Enter an integer in milliseconds. Any query which takes longer than this many milliseconds will be highlighted in the query log. This indicates a possibly inefficient query, or a candidate for caching.'),
  );
  $form['queries']['devel_store_queries'] = array('#type' => 'checkbox',
    '#title' => t('Store executed queries'),
    '#default_value' => variable_get('devel_store_queries', 0),
    '#description' => t('Store statistics about executed queries. See the devel_x tables. This feature is currently only available for the MySQL database backend.'));
  $form['queries']['devel_store_random'] = array('#type' => 'textfield',
    '#title' => t('Sampling interval'),
    '#default_value' => variable_get('devel_store_random', 1),
    '#size' => 4,
    '#description' => t('If storing query statistics, only store every nth page view. 1 means every page view, 2 every second, and so on.'));

  $form['devel_api_url'] = array('#type' => 'textfield',
    '#title' => t('API Site'),
    '#default_value' => variable_get('devel_api_url', 'api.drupal.org'),
    '#description' => t('The base URL for your developer documentation links. You might change this if you run <a href="!url">api.module</a> locally.', array('!url' => url('http://drupal.org/project/api'))));
  $form['dev_timer'] = array('#type' => 'checkbox',
    '#title' => t('Display page timer'),
    '#default_value' => variable_get('dev_timer', 0),
    '#description' => t('Display page execution time in the query log box.'),
  );
  $form['dev_mem'] = array('#type' => 'checkbox',
    '#title' => t('Display memory usage'),
    '#default_value' => variable_get('dev_mem', 0),
    '#description' => t('Display how much memory is used to generate the current page. This will show memory usage when devel_init() is called and when devel_exit() is called. PHP must have been compiled with the <em>--enable-memory-limit</em> configuration option for this feature to work.'),
  );
  $form['devel_redirect_page'] = array('#type' => 'checkbox',
    '#title' => t('Display redirection page'),
    '#default_value' => variable_get('devel_redirect_page', 0),
    '#description' => t('When a module executes drupal_goto(), the query log and other developer information is lost. Enabling this setting presents an intermediate page to developers so that the log can be examined before continuing to the destination page.'),
  );
  $form['devel_form_weights'] = array('#type' => 'checkbox',
    '#title' => t('Display form element keys and weights'),
    '#default_value' => variable_get('devel_form_weights', 0),
    '#description' => t('Form element names are needed for performing themeing or altering a form. Their weights determine the position of the element. Enabling this setting will show these keys and weights beside each form item.'),
  );
  $form['devel_error_handler'] = array('#type' => 'radios',
    '#title' => t('Error handler'),
    '#default_value' => variable_get('devel_error_handler', DEVEL_ERROR_HANDLER_STANDARD),
    '#options' => array(DEVEL_ERROR_HANDLER_NONE => t('None'), DEVEL_ERROR_HANDLER_STANDARD => t('Standard drupal'), DEVEL_ERROR_HANDLER_BACKTRACE => t('Backtrace')),
    '#description' => t('Choose an error handler for your site. <em>Backtrace</em> prints nice debug information when an error is noticed, and you !choose. <strong>Backtrace requires the <a href="!krumo">krumo library</a></strong>. <em>None</em> is a good option when stepping through the site in your debugger.', array('!krumo' => url("http://krumo.sourceforge.net"), '!choose' => l(t('choose to show errors on screen'), 'admin/settings/error-reporting'))),
  );

  // Save any old SMTP library
  if (variable_get('smtp_library', '') != '' && variable_get('smtp_library', '') != drupal_get_filename('module', 'devel')) {
    variable_set('devel_old_smtp_library', variable_get('smtp_library', ''));
  }
  $smtp_options = array(
    '' => t('Default'),
    drupal_get_filename('module', 'devel') => t('Log only'),
  );
  if (variable_get('devel_old_smtp_library', '') != '') {
    $smtp_options[variable_get('devel_old_smtp_library', '')] = t('Other (!library)', array('!library' => variable_get('devel_old_smtp_library', '')));
  }
  $form['smtp_library'] = array(
    '#type' => 'radios',
    '#title' => t('SMTP library'),
    '#options' => $smtp_options,
    '#default_value' => variable_get('smtp_library', ''),
  );

  return system_settings_form($form);
}

/**
 * Menu callback; clears all caches, then redirects to the previous page.
 */
function devel_cache_clear() {
  // clear core tables
  $core = array('cache', 'cache_filter', 'cache_form', 'cache_page');
  $alltables = array_merge($core, module_invoke_all('devel_caches'));
  foreach ($alltables as $table) {
    cache_clear_all('*', $table, TRUE);
  }

  drupal_clear_css_cache();
  drupal_rebuild_theme_registry();
  menu_rebuild();

  drupal_set_message('Cache cleared.');

  drupal_goto();
}

/**
 * Generates the execute block form.
 */
function devel_execute_form() {
  $form['code'] = array(
    '#type' => 'textarea',
    '#title' => t('PHP code to execute'),
    '#description' => t('Enter some code. Do not use <code>&lt;?php ?&gt;</code> tags.')
  );
  $form['op'] = array('#type' => 'submit', '#value' => t('Execute'));
  $form['#redirect'] = FALSE;
  $form['#skip_duplicate_check'] = TRUE;
  return $form;
}

/**
 * Process PHP execute form submissions.
 */
function devel_execute_form_submit($form, &$form_state) {
  ob_start();
  print eval($form_state['values']['code']);
  dsm(ob_get_clean());
}

/**
 * Menu callback; clear the database, resetting the menu to factory defaults.
 */
function devel_menu_reset() {
  menu_rebuild();
  drupal_set_message(t('The menu router has been built.'));
  drupal_goto();
}

/**
 * Implementation of hook_forms().
 */
function devel_forms() {
  $forms = array();
  if (user_access('access devel information')) {
    // registers each devel_reinstall_$module form_id
    $modules = module_list();
    foreach ($modules as $module) {
      $forms['devel_reinstall_'. $module]['callback'] = 'devel_reinstall_form';
    }
  }
  return $forms;
}

function devel_reinstall_form(&$form_state, $module) {
  $form = array(
    '#submit' => array('devel_reinstall_submit'),
    'submit' => array(
      '#type' => 'submit',
      '#value' => t('Reinstall @name module', array('@name' => $module))
    ),
  );
  return $form;
}

/**
 * Menu callback; Display a list of installed modules with the option to reinstall them via hook_install.
 */
function devel_reinstall() {
  $output = '';
  $modules = module_list();
  sort($modules);
  foreach ($modules as $module) {
    $output .= drupal_get_form('devel_reinstall_'. $module, $module);
  }
  drupal_set_message(t('Warning - will delete your module tables and variables.'), 'error');
  return $output;
}

/**
 * Process reinstall menu form submissions.
 */
function devel_reinstall_submit($form, &$form_state) {
  include_once './includes/install.inc';
  $module = str_replace('devel_reinstall_', '', $form_state['values']['form_id']);
  module_load_install($module);
  $versions = drupal_get_schema_versions($module);
  drupal_set_installed_schema_version($module, $versions ? max($versions) : SCHEMA_INSTALLED);
  module_invoke($module, 'uninstall');
  module_invoke($module, 'install');
  drupal_set_message(t('Uninstalled and reinstalled the %name module.', array('%name' => $module)));
}

// Menu callback.
function devel_theme_registry() {
  init_theme();
  $hooks = theme_get_registry();
  return kprint_r($hooks, TRUE);
}

/**
 * Menu callback; display all variables.
 */
function  devel_variable_page() {
  // we print our own page so as to avoid blocks
  $output = drupal_get_form('devel_variable_form');
  print theme('page', $output, FALSE);
}

function devel_variable_form() {
  $header = array(
    array(''),
    array('data' => t('Name'), 'field' => 'name', 'sort' => 'asc'),
    array('data' => t('Value'), 'field' => 'value'),
    array('data' => t('Length'), 'field' => 'length'),
    array('data' => t('Operations')),
  );
  // TODO: we could get variables out of $conf but that would include hard coded ones too. ideally i would highlight overrridden/hard coded variables
  $sql = "SELECT *, LENGTH(value) AS length FROM {variable}";
  $result = db_query($sql. tablesort_sql($header));
  while ($row = db_fetch_object($result)) {
    $variables[$row->name] = '';
    $form['name'][$row->name] = array('#value' => $row->name);
    if (has_krumo()) {
      $value = krumo_ob(variable_get($row->name, NULL));
    }
    else {
      if (drupal_strlen($row->value) > 70) {
        $value = drupal_substr($row->value, 0, 65) .'...';
      }
      else {
        $value = $row->value;
      }
    }
    $form[$row->name]['value'] = array('#value' => $value);
    $form[$row->name]['length'] = array('#value' => $row->length);
    $form[$row->name]['edit'] = array('#value' => l(t('edit'), "devel/variable/edit/$row->name"));
  }
  $form['variables'] = array('#type' => 'checkboxes', '#options' => $variables);
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Delete'),
  );
  return $form;
}

function theme_devel_variable_form($form) {
  // TODO: this is not being called for some reason
  // die(form);
  $children = element_children($form['name']);
  foreach ($children as $key) {
    $rows[] = array(
      drupal_render($form['variables'][$key]),
      drupal_render($form['name'][$key]),
      drupal_render($form[$key]['value']),
      drupal_render($form[$key]['length']),
      drupal_render($form[$key]['edit']),
    );
  }
  $header = array(
    theme('table_select_header_cell'),
    array('data' => t('Name'), 'field' => 'name', 'sort' => 'asc'),
    array('data' => t('Value'), 'field' => 'value'),
    array('data' => t('Length'), 'field' => 'length'),
    array('data' => t('Operations'), 'colspan' => 2),
  );
  $output = theme('table', $header, $rows);
  $output .= drupal_render($form);

  return $output;
}

function devel_variable_form_submit($form, &$form_state) {
  $deletes = array_filter($form_state['values']['variables']);
  array_walk($deletes, 'variable_del');
  drupal_set_message(format_plural(count($deletes), 'One variable deleted.', '@count variables deleted.'));
}

function devel_variable_edit($form_state, $name) {
  $value = variable_get($name, 'not found');
  $form['name'] = array(
    '#type' => 'value',
    '#value' => $name
  );
  $form['value'] = array(
    '#type' => 'item',
    '#title' => t('Old value'), // maybe check_plain() done by fapi
    '#value' => dpr($value, TRUE),
  );
  if (is_string($value) || is_numeric($value)) {
    $form['new'] = array(
      '#type' => 'textarea',
      '#title' => t('New value'),
      '#default_value' => $value
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );
  }
  else {
    $api = variable_get('devel_api_url', 'api.drupal.org');
    $form['new'] = array(
      '#type' => 'item',
      '#title' => t('New value'),
      '#value' => t('Sorry, complex variable types may not be edited yet. Use the <em>Execute PHP</em> block and the <a href="@variable-set-doc">variable_set()</a> function.', array('@variable-set-doc' => "http://$api/api/HEAD/function/variable_set"))
    );
  }
  drupal_set_title($name);
  return $form;
}

function devel_variable_edit_submit($form, &$form_state) {
  variable_set($form_state['values']['name'], $form_state['values']['new']);
  drupal_set_message(t('Saved new value for %name.', array('%name' => $form_state['values']['name'])));
   'devel/variable';
}

/**
 * Menu callback: display the session.
 */
function devel_session() {
  return dprint_r($_SESSION, TRUE);
}

/**
 * Switch from original user to another user and back.
 *
 * Note: taken from mailhandler.module.
 *
 * Note: You first need to run devel_switch_user without
 * argument to store the current user. Call devel_switch_user
 * without argument to set the user back to the original user.
 *
 * @param $name The username to switch to.
 *
 */
function devel_switch_user($name = NULL) {
  global $user;
  static $orig_user = array();

  if (isset($name)) {
    $user = user_load(array('name' => $name));
  }
  // Retrieve the initial user. Can be called multiple times.
  else if (count($orig_user)) {
    $user = array_shift($orig_user);
    array_unshift($orig_user, $user);
  }
  // Store the initial user.
  else {
    $orig_user[] = $user;
  }
  drupal_goto();
}

/**
 * Menu callback; prints the loaded structure of the current node/user.
 */
function devel_load_object($object, $name = NULL) {
  $title = isset($object->title) ? $object->title : $object->name;
  drupal_set_title(check_plain($title));
  return kdevel_print_object($object, '$'. $name .'->');
}

/**
 * Menu callback; prints the render structure of the current object (currently node or user).
 */
function devel_render_object($type, $object) {
  $output = '';
  $title = isset($object->title) ? $object->title : $object->name;
  // not sure why menu system doesn't give us a reasonable title here.
  drupal_set_title(check_plain($title));
  $function = $type. '_build_content';
  $content = $function($object, FALSE, FALSE);
  return kdevel_print_object($content, '$'. $type .'->');
}

function devel_elements_page() {
  return kdevel_print_object(module_invoke_all('elements'));
}

/**
 * Print an object or array using either Krumo (if installed) or devel_print_object()
 *
 * @param $object
 *   array or object to print
 * @param $prefix
 *   prefixing for output items
 */
function kdevel_print_object($object, $prefix = NULL) {
  return has_krumo() ? krumo_ob($object) : devel_print_object($object, $prefix);
}

// Save krumo htlm using output buffering.
function krumo_ob($object) {
  ob_start();
  krumo($object);
  $output = ob_get_contents();
  ob_end_clean();
  return $output;
}

/**
 * Display an object or array
 *
 * @param $object
 *   the object or array
 * @param $prefix
 *   prefix for the output items (example "$node->", "$user->", "$")
 * @param $header
 *   set to FALSE to suppress the output of the h3
 */
function devel_print_object($object, $prefix = NULL, $header = TRUE) {
  drupal_add_css(drupal_get_path('module', 'devel'). '/devel.css');
  $output = '<div class="devel-obj-output">';
  if ($header) {
    $output .= '<h3>'. t('Display of !type !obj', array('!type' => str_replace(array('$', '->'), '', $prefix), '!obj' => gettype($object))). '</h3>';
  }
  $output .= _devel_print_object($object, $prefix);
  $output .= '</div>';
  return $output;
}

/**
 * Recursive (and therefore magical) function goes through an array or object and
 * returns a nicely formatted listing of its contents.
 *
 * @param $obj
 *   array or object to recurse through
 * @param $prefix
 *   prefix for the output items (example "$node->", "$user->", "$")
 * @param $parents
 *   used by recursion
 * @param $object
 *   used by recursion
 * @return
 *   fomatted html
 *
 * @todo
 *   currently there are problems sending an array with a varname
 */
function _devel_print_object($obj, $prefix = NULL, $parents = FALSE, $object = FALSE) {

  static $root_type, $out_format;
  if (!isset($root_type)) {
    $root_type = gettype($obj);
  }

  if (is_object($obj)) {
    $obj = (array)$obj;
  }
  if (is_array($obj)) {
    $output .= "<dl>\n";
    foreach($obj as $field => $value) {
      if ($parents) {
        if ($object) {
          $field = $parents .'->'. $field;
        }
        else {
          if (is_int($field)) {
            $field = $parents .'['. $field .']';
          }
          else {
            $field = $parents .'[\''. $field .'\']';
          }
        }
      }

      $type = "";
      if (!is_string($value)) {
        $type = " (". gettype($value) .")";
      }

      $output .= '<span class="devel-attr">';
      $output .= "<dt><span class=\"field\">{$prefix}{$field}</span>$type</dt>\n";
      $output .= "<dd>\n";
      if (is_array($value)) {
        $output .= _devel_print_object($value, $prefix, $field);
      }
      elseif (is_object($value)) {
        $output .= _devel_print_object((array)$value, $prefix, $field, TRUE);
      }
      else {
        $value = is_bool($value) ? ($value ? 'TRUE' : 'FALSE') : $value;
        $output .= htmlspecialchars(print_r($value, TRUE)) ."\n";
      }
      $output .= "</dd></span>\n";
    }
    $output .= "</dl>\n";
  }
  return $output;
}

/**
 * Adds a table at the bottom of the page cataloguing data on all the database queries that were made to
 * generate the page.
 */
function devel_query_table($queries, $counts) {
  $version = drupal_major_version_map(VERSION);
  $header = array ('ms', '#', 'where', 'query');
  $i = 0;
  $api = variable_get('devel_api_url', 'api.drupal.org');
  foreach ($queries as $query) {
    // dprint_r($query);
    $ar = explode("\n", $query[0]);
    $function=array_shift($ar);
    $count = isset($counts[$query[0]]) ? $counts[$query[0]] : 0;
    $query[0]=join(' ',$ar);

    $diff = round($query[1] * 1000, 2);
    if ($diff > variable_get('devel_execution', 5)) {
      $cell[$i][] = array ('data' => $diff, 'class' => 'marker');
    }
    else {
      $cell[$i][] = $diff;
    }
    if ($count > 1) {
      $cell[$i][] = array ('data' => $count, 'class' => 'marker');
    }
    else {
      $cell[$i][] = $count;
    }
    $cell[$i][] = l($function, "http://$api/api/$version/function/$function");
    $pos = strpos($query[0], '*/') + 3;
    $cell[$i][] = check_plain(substr($query[0], $pos));
    $i++;
    unset($diff, $count);
  }
  if (variable_get('devel_query_sort', DEVEL_QUERY_SORT_BY_SOURCE)) {
    usort($cell, '_devel_table_sort');
  }
  return theme('table', $header, $cell);
}

function _devel_table_sort($a, $b) {
  $a = is_array($a[0]) ? $a[0]['data'] : $a[0];
  $b = is_array($b[0]) ? $b[0]['data'] : $b[0];
  if ($a < $b) { return 1; }
  if ($a > $b) { return -1; }
  return 0;
}

/**
 * Displays page execution time at the bottom of the page.
 */
function devel_timer() {
  $time = timer_read('page');
  return t_safe(' Page execution time was %time ms.', array('%time' => $time));
}

/**
 * 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;
  }
}

/**
 * Print a variable to the 'message' area of the page. Uses drupal_set_message()
 */
function dpm($input, $name = NULL) {
  if (user_access('access devel information')) {
    $export = dprint_r($input, TRUE, $name);
    drupal_set_message($export);
  }
}

/**
 * Var_dump() a variable to the 'message' area of the page. Uses drupal_set_message()
 */
function dvm($input, $name = NULL) {
  if (user_access('access devel information')) {
    $export = dprint_r($input, TRUE, $name, 'var_dump');
    drupal_set_message($export);
  }
}

// legacy function that was poorly named. use dpm() instead, since the 'p' maps to 'print_r'
function dsm($input, $name = NULL) {
  dpm($input, $name);
}

/**
 * An alias for dprint_r(). Saves carpal tunnel syndrome.
 */
function dpr($input, $return = FALSE, $name = NULL) {
  return dprint_r($input, $return, $name);
}

/**
 * Like dpr, but uses var_dump() instead
 */
function dvr($input, $return = FALSE, $name = NULL) {
  return dprint_r($input, $return, $name, 'var_dump');
}

function kprint_r($input, $return = FALSE, $name = NULL, $function = 'print_r') {
  if (has_krumo()) {
    if (user_access('access devel information')) {
      return $return ? krumo_ob($input) : krumo($input);
    }
  }
  else {
    return dprint_r($input, $return = FALSE, $name = NULL, $function = 'print_r');
  }
}


/**
 * Pretty-print a variable to the browser.
 * Displays only for users with proper permissions. If
 * you want a string returned instead of a print, use the 2nd param.
 */
function dprint_r($input, $return = FALSE, $name = NULL, $function = 'print_r') {
  if (user_access('access devel information')) {
    if ($name) {
      $name .= ' => ';
    }
    ob_start();
    $function($input);
    $output = check_plain(ob_get_clean());
    if (count($input, COUNT_RECURSIVE) > DEVEL_MIN_TEXTAREA) {
      if (has_krumo()) {
        krumo($output);
      }
      else {
        // don't use fapi here because sometimes fapi will not be loaded
        $printed_value = "<textarea rows=30 style=\"width: 100%;\">\n". $name . $output . '</textarea>';
      }
    }
    else {
      $printed_value = '<pre>' . $name . $output . '</pre>';
    }
    if ($return) {
      return $printed_value;
    }
    else {
      print $printed_value;
    }
  }
}

/**
 *
 */
function dkr($input, $return = FALSE, $name = NULL) {
  require_once './'. drupal_get_path('module', 'devel'). '/krumo/class.krumo.php';
  if ($return) {
    ob_start();
    krumo($input);
    $output = check_plain(ob_get_clean());
  }
  dprint_r($input, $return, $name, 'krumo', TRUE);
}

/**
 * Print the function call stack.
 */
function ddebug_backtrace() {
  if (user_access('access devel information')) {
    if (function_exists('debug_print_backtrace')) {
      debug_print_backtrace();
    }
    else {
      dprint_r(debug_backtrace());
    }
  }
}

/**
 * Debugging version of db_query().
 *
 * Echoes the query to the browser.
 */
function db_queryd($query) {
  $args = func_get_args();
  array_shift($args);
  $query = db_prefix_tables($query);
  if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
    $args = $args[0];
  }
  _db_query_callback($args, TRUE);
  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
  return _db_query($query, 1);
}

// Only define our mail wrapper if the devel module is the current mail
// wrapper.
if (variable_get('smtp_library', '') == drupal_get_filename('module', 'devel')) {
  /**
   * Log the mails sent out instead of mailing.
   */
  function drupal_mail_wrapper($mailkey, $to, $subject, $body, $from, $headers) {
    $mimeheaders = array();
    foreach ($headers as $name => $value) {
      // the check_plain nicely encodes <> chars for web presentation
      $mimeheaders[] = check_plain($name .': '. mime_header_encode($value));
    }
    watchdog(
      'devel',
      'Mail sent:<br />Key: %mailkey<br />To: %to<br />From: %from<br />Subject: %subject<br />Body: %body<br /><br />Additional headers: !header',
       array(
         '%mailkey' => $mailkey,
         '%to' => $to,
         '%from' => $from,
         '%subject' => $subject,
         '%body' => $body,
         '!header' => implode("<br />", $mimeheaders),
         WATCHDOG_INFO,
         )
    );
    return TRUE;
  }
}

function devel_queries() {
  $header = array(
                  array('data' => t('Total (ms)'), 'field' => 'total_time', 'sort' => 'desc'),
                  array('data' => t('Average (ms)'), 'field' => 'average', 'sort' => 'desc'),
                  array('data' => t('Std deviation (ms)')),
                  array('data' => t('Count'), 'field' => 'count'),
                  array('data' => t('Function'), 'field' => 'q.function'),
                  array('data' => t('Query'), 'field' => 'q.query'),
                  );

  $result = pager_query('SELECT q.qid, q.query, q.function, t.*, COUNT(t.qid) AS count, SUM(t.time) AS total_time, AVG(t.time) AS average, STDDEV(t.time) AS stddev FROM {devel_queries} q INNER JOIN {devel_times} t ON q.qid = t.qid GROUP BY t.qid '. tablesort_sql($header), 30, 0, 'SELECT COUNT(qid) FROM {devel_queries}');
  while ($log = db_fetch_object($result)) {
    $rows[] = array(
                    round($log->total_time * 1000, 3),
                    round($log->average * 1000, 3),
                    round($log->stddev * 1000, 3),
                    $log->count,
                    $log->function,
                    check_plain($log->query)
                    );
  }

  drupal_set_title(check_plain($node->title));
  $output = theme('table', $header, $rows);
  $output .= theme('pager', NULL, 30, 0);
  $output .= l(t('Delete collected query statistics'), 'devel/queries/empty');

  print theme('page', $output, FALSE);
}

function devel_queries_empty() {
  db_query('DELETE FROM {devel_queries}');
  db_query('DELETE FROM {devel_times}');
  drupal_set_message(t('Stored query statistics deleted.'));
  drupal_goto('devel/queries');
}

/*
 * migration related functions
 */

/**
 * Menu callback. Rebuild node _comment_stats table.
 *
 * @return void
 **/
function devel_rebuild_node_comment_statistics_page() {
  devel_rebuild_node_comment_statistics();
  drupal_set_message('node_comment_statistics table has been rebuilt.');
  drupal_goto('admin');
}

/**
 * Empty node_comment_statistics table and rebuild. Is fast.
 * TODO: if 2 comments have exact same timestamp, the function can get wrong uid and name fields.
 * Handles when comment timestamps have been manually set in admin
 *
 * @return void
 **/
function devel_rebuild_node_comment_statistics() {
  $sql = "DELETE FROM {node_comment_statistics}";
  db_query($sql);
  $sql = "INSERT INTO {node_comment_statistics} (nid, last_comment_timestamp, last_comment_name, last_comment_uid, comment_count) (select nid, c.timestamp, name, uid, comment_count FROM {comments} c INNER JOIN (SELECT MAX(timestamp) AS timestamp, COUNT(*) AS comment_count FROM {comments} WHERE status=%d GROUP BY nid) as c2 ON c.timestamp=c2.timestamp)";
  db_query($sql, COMMENT_PUBLISHED);
}

/**
 * Set sequences table to a sane state. Useful after a bulk import.
 *
 * @return void
 **/
function sequence_reset($table, $column) {
  $max = db_result(db_query("SELECT MAX($column) FROM {$table}"));
  $max = ($max ? $max+1 : 2);
  db_query("UPDATE {sequences} SET id = $max WHERE name='${table}_$column'");
}

/**
 * Enable or disable indexes for a given table. Useful during a bulk import.
 *
 * @return void
 **/
function devel_table_keys($tables, $verb = 'ENABLE') {
  foreach ($tables as $table) {
    db_query("ALTER TABLE $table $verb KEYS");
  }
}

/**
 * Save contents of an url to filesystem. Works for images.
 *
 * @return void
 **/
function wget($url, $file) {
  if (file_exists($file)) {
    return;
  }
  print "get: $url\n";
  $ch = curl_init($url);
  $fp = fopen($file, "w");
  curl_setopt($ch, CURLOPT_FILE, $fp);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_exec($ch);
  curl_close($ch);
  fclose($fp);
}