summaryrefslogtreecommitdiff
path: root/kolab.org/www/drupal-7.15/sites/all/modules/ctools/page_manager/page_manager.module
blob: 62f6d275cfa3afcff48f6f88e6bc4cdfc1372e08 (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
<?php

/**
 * @file
 * The page manager module provides a UI and API to manage pages.
 *
 * It defines pages, both for system pages, overrides of system pages, and
 * custom pages using Drupal's normal menu system. It allows complex
 * manipulations of these pages, their content, and their hierarchy within
 * the site. These pages can be exported to code for superior revision
 * control.
 */

/**
 * Bit flag on the 'changed' value to tell us if an item was moved.
 */
define('PAGE_MANAGER_CHANGED_MOVED', 0x01);

/**
 * Bit flag on the 'changed' value to tell us if an item edited or added.
 */
define('PAGE_MANAGER_CHANGED_CACHED', 0x02);

/**
 * Bit flag on the 'changed' value to tell us if an item deleted.
 */
define('PAGE_MANAGER_CHANGED_DELETED', 0x04);

/**
 * Bit flag on the 'changed' value to tell us if an item has had its disabled status changed.
 */
define('PAGE_MANAGER_CHANGED_STATUS', 0x08);

// --------------------------------------------------------------------------
// Drupal hooks

/**
 * Implements hook_permission().
 */
function page_manager_permission() {
  return array(
    'use page manager' => array(
      'title' => t('Use Page Manager'),
      'description' => t("Allows users to use most of Page Manager's features, though restricts some of the most powerful, potentially site-damaging features. Note that even the reduced featureset still allows for enormous control over your website."),
      'restrict access' => TRUE,
    ),
    'administer page manager' => array(
      'title' => t('Administer Page Manager'),
      'description' => t('Allows complete control over Page Manager, i.e., complete control over your site. Grant with extreme caution.'),
      'restrict access' => TRUE,
    ),
  );

}

/**
 * Implements hook_ctools_plugin_directory() to let the system know
 * where our task and task_handler plugins are.
 */
function page_manager_ctools_plugin_directory($owner, $plugin_type) {
  if ($owner == 'page_manager') {
    return 'plugins/' . $plugin_type;
  }
  if ($owner == 'ctools' && $plugin_type == 'cache') {
    return 'plugins/' . $plugin_type;
  }
}

/**
 * Implements hook_ctools_plugin_type() to inform the plugin system that Page
 * Manager owns task, task_handler, and page_wizard plugin types.
 *
 * All of these are empty because the defaults all work.
 */
function page_manager_ctools_plugin_type() {
  return array(
    'tasks' => array(),
    'task_handlers' => array(),
    'page_wizards' => array(),
  );
}

/**
 * Delegated implementation of hook_menu().
 */
function page_manager_menu() {
  // For some reason, some things can activate modules without satisfying
  // dependencies. I don't know how, but this helps prevent things from
  // whitescreening when this happens.
  if (!module_exists('ctools')) {
    return;
  }

  $items = array();
  $base = array(
    'access arguments' => array('use page manager'),
    'file' => 'page_manager.admin.inc',
    'theme callback' => 'ajax_base_page_theme',
  );

  $items['admin/structure/pages'] = array(
    'title' => 'Pages',
    'description' => 'Add, edit and remove overridden system pages and user defined pages from the system.',
    'page callback' => 'page_manager_list_page',
  ) + $base;

  $items['admin/structure/pages/list'] = array(
    'title' => 'List',
    'page callback' => 'page_manager_list_page',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  ) + $base;

  $items['admin/structure/pages/edit/%page_manager_cache'] = array(
    'title' => 'Edit',
    'page callback' => 'page_manager_edit_page',
    'page arguments' => array(4),
    'type' => MENU_NORMAL_ITEM,
  ) + $base;

  $items['admin/structure/pages/%ctools_js/operation/%page_manager_cache'] = array(
    'page callback' => 'page_manager_edit_page_operation',
    'page arguments' => array(3, 5),
    'type' => MENU_NORMAL_ITEM,
  ) + $base;

  $items['admin/structure/pages/%ctools_js/enable/%page_manager_cache'] = array(
    'page callback' => 'page_manager_enable_page',
    'page arguments' => array(FALSE, 3, 5),
    'type' => MENU_CALLBACK,
  ) + $base;

  $items['admin/structure/pages/%ctools_js/disable/%page_manager_cache'] = array(
    'page callback' => 'page_manager_enable_page',
    'page arguments' => array(TRUE, 3, 5),
    'type' => MENU_CALLBACK,
  ) + $base;

  $tasks = page_manager_get_tasks();

  // Provide menu items for each task.
  foreach ($tasks as $task_id => $task) {
    // Allow the task to add its own menu items.
    if ($function = ctools_plugin_get_function($task, 'hook menu')) {
      $function($items, $task);
    }

    // And for those that provide subtasks, provide menu items for them, as well.
    foreach (page_manager_get_task_subtasks($task) as $subtask_id => $subtask) {
      // Allow the task to add its own menu items.
      if ($function = ctools_plugin_get_function($task, 'hook menu')) {
        $function($items, $subtask);
      }
    }
  }

  return $items;
}

function page_manager_admin_paths() {
  /* @todo FIX ME this is a major resource suck. */
  return;

  $items = array();
  ctools_include('page', 'page_manager', 'plugins/tasks');
  $pages = page_manager_page_load_all();
  foreach ($pages as $page) {
    // Make sure the page we're on is set to be an administrative path and that
    // it is not set to be a frontpage path.
    if ((isset($page->conf['admin_paths']) && $page->conf['admin_paths']) && (!isset($page->make_frontpage) || !$page->make_frontpage)) {
      $path_parts = explode('/', $page->path);
      foreach ($path_parts as $key => $part) {
        if (strpos($part, '%') !== FALSE || strpos($part, '!') !== FALSE) {
          $path_parts[$key] = '*';
        }
      }
      $path = implode('/', $path_parts);
      if ($page->menu['type'] == 'default tab') {
        array_pop($path_parts);
        $parent_path = implode('/', $path_parts);
        $items[$parent_path] = TRUE;
      }
      $items[$path] = TRUE;
    }
  }
  return $items;
}

/**
 * Implements hook_menu_alter.
 *
 * Get a list of all tasks and delegate to them.
 */
function page_manager_menu_alter(&$items) {
  // For some reason, some things can activate modules without satisfying
  // dependencies. I don't know how, but this helps prevent things from
  // whitescreening when this happens.
  if (!module_exists('ctools')) {
    return;
  }

  $tasks = page_manager_get_tasks();

  foreach ($tasks as $task) {
    if ($function = ctools_plugin_get_function($task, 'hook menu alter')) {
      $function($items, $task);
    }
    // let the subtasks alter the menu items too.
    foreach (page_manager_get_task_subtasks($task) as $subtask_id => $subtask) {
      if ($function = ctools_plugin_get_function($subtask, 'hook menu alter')) {
        $function($items, $subtask);
      }
    }
  }

  return $items;
}

/*
 * Implements hook_theme()
 */
function page_manager_theme() {
  // For some reason, some things can activate modules without satisfying
  // dependencies. I don't know how, but this helps prevent things from
  // whitescreening when this happens.
  if (!module_exists('ctools')) {
    return;
  }

  $base = array(
    'path' => drupal_get_path('module', 'page_manager') . '/theme',
    'file' => 'page_manager.theme.inc',
  );

  $items = array(
    'page_manager_handler_rearrange' => array(
      'render element' => 'form',
    ) + $base,
    'page_manager_edit_page' => array(
      'template' => 'page-manager-edit-page',
      'variables' => array('page' => NULL, 'save' => NULL, 'operations' => array(), 'content' => array()),
    ) + $base,
    'page_manager_lock' => array(
      'variables' => array('page' => array()),
    ) + $base,
    'page_manager_changed' => array(
      'variables' => array('text' => NULL, 'description' => NULL),
    ) + $base,
  );

  // Allow task plugins to have theme registrations by passing through:
  $tasks = page_manager_get_tasks();

  // Provide menu items for each task.
  foreach ($tasks as $task_id => $task) {
    if ($function = ctools_plugin_get_function($task, 'hook theme')) {
      $function($items, $task);
    }
  }

  return $items;
}

// --------------------------------------------------------------------------
// Page caching
//
// The page cache is used to store a page temporarily, using the ctools object
// cache. When loading from the page cache, it will either load the cached
// version, or if there is not one, load the real thing and create a cache
// object which can then be easily stored.

/**
 * Get the cached changes to a given task handler.
 */
function page_manager_get_page_cache($task_name) {
  $caches = drupal_static(__FUNCTION__, array());
  if (!isset($caches[$task_name])) {
    ctools_include('object-cache');
    $cache = ctools_object_cache_get('page_manager_page', $task_name);
    if (!$cache) {
      $cache = new stdClass();
      $cache->task_name = $task_name;
      list($cache->task_id, $cache->subtask_id) = page_manager_get_task_id($cache->task_name);

      $cache->task = page_manager_get_task($cache->task_id);
      if (empty($cache->task)) {
        return FALSE;
      }

      if ($cache->subtask_id) {
        $cache->subtask = page_manager_get_task_subtask($cache->task, $cache->subtask_id);
        if (empty($cache->subtask)) {
          return FALSE;
        }
      }
      else {
        $cache->subtask = $cache->task;
        $cache->subtask['name'] = '';
      }

      $cache->handlers = page_manager_load_sorted_handlers($cache->task, $cache->subtask_id);
      $cache->handler_info = array();
      foreach ($cache->handlers as $id => $handler) {
        $cache->handler_info[$id] = array(
          'weight' => $handler->weight,
          'changed' => FALSE,
          'name' => $id,
        );
      }
    }
    else {
      // ensure the task is loaded.
      page_manager_get_task($cache->task_id);
    }

    if ($task_name != '::new') {
      $cache->locked = ctools_object_cache_test('page_manager_page', $task_name);
    }
    else {
      $cache->locked = FALSE;
    }

    $caches[$task_name] = $cache;
  }

  return $caches[$task_name];
}

/**
 * Store changes to a task handler in the object cache.
 */
function page_manager_set_page_cache($page) {
  if (!empty($page->locked)) {
    return;
  }

  if (empty($page->task_name)) {
    return;
  }

  ctools_include('object-cache');
  $page->changed = TRUE;
  $cache = ctools_object_cache_set('page_manager_page', $page->task_name, $page);
}

/**
 * Remove an item from the object cache.
 */
function page_manager_clear_page_cache($name) {
  ctools_include('object-cache');
  ctools_object_cache_clear('page_manager_page', $name);
}

/**
 * Write all changes from the page cache and clear it out.
 */
function page_manager_save_page_cache($cache) {
  // Save the subtask:
  if ($function = ctools_plugin_get_function($cache->task, 'save subtask callback')) {
    $function($cache->subtask, $cache);
  }

  // Iterate through handlers and save/delete/update as necessary.
  // Go through each of the task handlers, check to see if it needs updating,
  // and update it if so.
  foreach ($cache->handler_info as $id => $info) {
    $handler = &$cache->handlers[$id];
    // If it has been marked for deletion, delete it.

    if ($info['changed'] & PAGE_MANAGER_CHANGED_DELETED) {
      page_manager_delete_task_handler($handler);
    }
    // If it has been somehow edited (or added), write the cached version
    elseif ($info['changed'] & PAGE_MANAGER_CHANGED_CACHED) {
      // Make sure we get updated weight from the form for this.
      $handler->weight = $info['weight'];
      page_manager_save_task_handler($handler);
    }
    // Otherwise, check to see if it has moved and, if so, update the weight.
    elseif ($info['weight'] != $handler->weight) {
      // Theoretically we could only do this for in code objects, but since our
      // load mechanism checks for all, this is less database work.
      page_manager_update_task_handler_weight($handler, $info['weight']);
    }

    // Set enable/disabled status.
    if ($info['changed'] & PAGE_MANAGER_CHANGED_STATUS) {
      ctools_include('export');
      ctools_export_set_object_status($cache->handlers[$id], $info['disabled']);
    }
  }

  page_manager_clear_page_cache($cache->task_name);

  if (!empty($cache->path_changed) || !empty($cache->new)) {
    // Force a menu rebuild to make sure the menu entries are set.
    menu_rebuild();
  }
  cache_clear_all();
}

/**
 * Menu callback to load a page manager cache object for menu callbacks.
 */
function page_manager_cache_load($task_name) {
  // load context plugin as there may be contexts cached here.
  ctools_include('context');
  return page_manager_get_page_cache($task_name);
}

/**
 * Generate a unique name for a task handler.
 *
 * Task handlers need to be named but they aren't allowed to set their own
 * names. Instead, they are named based upon their parent task and type.
 */
function page_manager_handler_get_name($task_name, $handlers, $handler) {
  $base = str_replace('-', '_', $task_name);
  // Generate a unique name. Unlike most named objects, we don't let people choose
  // names for task handlers because they mostly don't make sense.
  $base .= '_' . $handler->handler;

  // Once we have a base, check to see if it is used. If it is, start counting up.
  $name = $base;
  $count = 1;
  // If taken
  while (isset($handlers[$name])) {
    $name = $base . '_' . ++$count;
  }

  return $name;
}

/**
 * Import a handler into a page.
 *
 * This is used by both import and clone, since clone just exports the
 * handler and immediately imports it.
 */
function page_manager_handler_add_to_page(&$page, &$handler, $title = NULL) {
  $last = end($page->handler_info);
  $handler->weight = $last ? $last['weight'] + 1 : 0;
  $handler->task = $page->task_id;
  $handler->subtask = $page->subtask_id;
  $handler->export_type = EXPORT_IN_DATABASE;
  $handler->type = t('Normal');

  if ($title) {
    $handler->conf['title'] = $title;
  }

  $name = page_manager_handler_get_name($page->task_name, $page->handlers, $handler);

  $handler->name = $name;

  $page->handlers[$name] = $handler;
  $page->handler_info[$name] = array(
    'weight' => $handler->weight,
    'name' => $handler->name,
    'changed' => PAGE_MANAGER_CHANGED_CACHED,
  );
}

// --------------------------------------------------------------------------
// Database routines
//
// This includes fetching plugins and plugin info as well as specialized
// fetch methods to get groups of task handlers per task.

/**
 * Load a single task handler by name.
 *
 * Handlers can come from multiple sources; either the database or by normal
 * export method, which is handled by the ctools library, but handlers can
 * also be bundled with task/subtask. We have to check there and perform
 * overrides as appropriate.
 *
 * Handlers bundled with the task are of a higher priority than default
 * handlers provided by normal code, and are of a lower priority than
 * the database, so we have to check the source of handlers when we have
 * multiple to choose from.
 */
function page_manager_load_task_handler($task, $subtask_id, $name) {
  ctools_include('export');
  $result = ctools_export_load_object('page_manager_handlers', 'names', array($name));
  $handlers = page_manager_get_default_task_handlers($task, $subtask_id);
  return page_manager_compare_task_handlers($result, $handlers, $name);
}

/**
 * Load all task handlers for a given task/subtask.
 */
function page_manager_load_task_handlers($task, $subtask_id = NULL, $default_handlers = NULL) {
  ctools_include('export');
  $conditions = array(
    'task' => $task['name'],
  );

  if (isset($subtask_id)) {
    $conditions['subtask'] = $subtask_id;
  }

  $handlers = ctools_export_load_object('page_manager_handlers', 'conditions', $conditions);
  $defaults = isset($default_handlers) ? $default_handlers : page_manager_get_default_task_handlers($task, $subtask_id);
  foreach ($defaults as $name => $default) {
    $result = page_manager_compare_task_handlers($handlers, $defaults, $name);

    if ($result) {
      $handlers[$name] = $result;
      // Ensure task and subtask are correct, because it's easy to change task
      // names when editing a default and fail to do it on the associated handlers.
      $result->task = $task['name'];
      $result->subtask = $subtask_id;
    }
  }

  // Override weights from the weight table.
  if ($handlers) {
    $names = array();
    $placeholders = array();
    foreach ($handlers as $handler) {
      $names[] = $handler->name;
      $placeholders[] = "'%s'";
    }

    $result = db_query('SELECT name, weight FROM {page_manager_weights} WHERE name IN (:names)', array(':names' => $names));
    foreach ($result as $weight) {
      $handlers[$weight->name]->weight = $weight->weight;
    }
  }

  return $handlers;
}

/**
 * Get the default task handlers from a task, if they exist.
 *
 * Tasks can contain 'default' task handlers which are provided by the
 * default task. Because these can come from either the task or the
 * subtask, the logic is abstracted to reduce code duplication.
 */
function page_manager_get_default_task_handlers($task, $subtask_id) {
  // Load default handlers that are provied by the task/subtask itself.
  $handlers = array();
  if ($subtask_id) {
    $subtask = page_manager_get_task_subtask($task, $subtask_id);
    if (isset($subtask['default handlers'])) {
      $handlers = $subtask['default handlers'];
    }
  }
  else if (isset($task['default handlers'])) {
    $handlers = $task['default handlers'];
  }

  return $handlers;
}

/**
 * Compare a single task handler from two lists and provide the correct one.
 *
 * Task handlers can be gotten from multiple sources. As exportable objects,
 * they can be provided by default hooks and the database. But also, because
 * they are tightly bound to tasks, they can also be provided by default
 * tasks. This function reconciles where to pick up a task handler between
 * the exportables list and the defaults provided by the task itself.
 *
 * @param $result
 *   A list of handlers provided by export.inc
 * @param $handlers
 *   A list of handlers provided by the default task.
 * @param $name
 *   Which handler to compare.
 * @return
 *   Which handler to use, if any. May be NULL.
 */
function page_manager_compare_task_handlers($result, $handlers, $name) {
  // Compare our special default handler against the actual result, if
  // any, and do the right thing.
  if (!isset($result[$name]) && isset($handlers[$name])) {
    $handlers[$name]->type = t('Default');
    $handlers[$name]->export_type = EXPORT_IN_CODE;
    return $handlers[$name];
  }
  else if (isset($result[$name]) && !isset($handlers[$name])) {
    return $result[$name];
  }
  else if (isset($result[$name]) && isset($handlers[$name])) {
    if ($result[$name]->export_type & EXPORT_IN_DATABASE) {
      $result[$name]->type = t('Overridden');
      $result[$name]->export_type = $result[$name]->export_type | EXPORT_IN_CODE;
      return $result[$name];
    }
    else {
      // In this case, our default is a higher priority than the standard default.
      $handlers[$name]->type = t('Default');
      $handlers[$name]->export_type = EXPORT_IN_CODE;
      return $handlers[$name];
    }
  }
}

/**
 * Load all task handlers for a given task and subtask and sort them.
 */
function page_manager_load_sorted_handlers($task, $subtask_id = NULL, $enabled = FALSE) {
  $handlers = page_manager_load_task_handlers($task, $subtask_id);
  if ($enabled) {
    foreach ($handlers as $id => $handler) {
      if (!empty($handler->disabled)) {
        unset($handlers[$id]);
      }
    }
  }
  uasort($handlers, 'page_manager_sort_task_handlers');
  return $handlers;
}

/**
 * Callback for uasort to sort task handlers.
 *
 * Task handlers are sorted by weight then by name.
 */
function page_manager_sort_task_handlers($a, $b) {
  if ($a->weight < $b->weight) {
    return -1;
  }
  elseif ($a->weight > $b->weight) {
    return 1;
  }
  elseif ($a->name < $b->name) {
    return -1;
  }
  elseif ($a->name > $b->name) {
    return 1;
  }

  return 0;
}

/**
 * Write a task handler to the database.
 */
function page_manager_save_task_handler(&$handler) {
  $update = (isset($handler->did)) ? array('did') : array();
  // Let the task handler respond to saves:
  if ($function = ctools_plugin_load_function('page_manager', 'task_handlers', $handler->handler, 'save')) {
    $function($handler, $update);
  }

  drupal_write_record('page_manager_handlers', $handler, $update);
  db_delete('page_manager_weights')
    ->condition('name', $handler->name)
    ->execute();

  // If this was previously a default handler, we may have to write task handlers.
  if (!$update) {
    // @todo wtf was I going to do here?
  }
  return $handler;
}

/**
 * Remove a task handler.
 */
function page_manager_delete_task_handler($handler) {
  // Let the task handler respond to saves:
  if ($function = ctools_plugin_load_function('page_manager', 'task_handlers', $handler->handler, 'delete')) {
    $function($handler);
  }
  db_delete('page_manager_handlers')
    ->condition('name', $handler->name)
    ->execute();
  db_delete('page_manager_weights')
    ->condition('name', $handler->name)
    ->execute();
}

/**
 * Export a task handler into code suitable for import or use as a default
 * task handler.
 */
function page_manager_export_task_handler($handler, $indent = '') {
  ctools_include('export');
  ctools_include('plugins');
  $handler = clone $handler;

  $append = '';
  if ($function = ctools_plugin_load_function('page_manager', 'task_handlers', $handler->handler, 'export')) {
    $append = $function($handler, $indent);
  }

  $output = ctools_export_object('page_manager_handlers', $handler, $indent);
  $output .= $append;

  return $output;
}

/**
 * Loads page manager handler for export.
 *
 * Callback to load page manager handler within ctools_export_crud_load().
 *
 * @param string $name
 *   The name of the handler to load.
 *
 * @return
 *   Loaded page manager handler object, extended with external properties.
 */
function page_manager_export_task_handler_load($name) {
  $table = 'page_manager_handlers';
  $schema = ctools_export_get_schema($table);
  $export = $schema['export'];

  $result = ctools_export_load_object($table, 'names', array($name));
  if (isset($result[$name])) {
    $handler = $result[$name];

    // Weight is stored in additional table so that in-code task handlers
    // don't need to get written to the database just because they have their
    // weight changed. Therefore, handler could have no correspondent database
    // entry. Revert will not be performed for this handler and the weight
    // will not be reverted. To make possible revert of the weight field
    // export_type must simulate that the handler is stored in the database.
    $handler->export_type = EXPORT_IN_DATABASE;

    // Also, page manager handler weight should be overriden with correspondent
    // weight from page_manager_weights table, if there is one.
    $result = db_query('SELECT weight FROM {page_manager_weights} WHERE name = (:names)', array(':names' => $handler->name))->fetchField();
    if (is_numeric($result)) {
      $handler->weight = $result;
    }
    return $handler;
  }
}

/**
 * Create a new task handler object.
 *
 * @param $plugin
 *   The plugin this task handler is created from.
 */
function page_manager_new_task_handler($plugin) {
  // Generate a unique name. Unlike most named objects, we don't let people choose
  // names for task handlers because they mostly don't make sense.

  // Create a new, empty handler object.
  $handler          = new stdClass;
  $handler->title   = $plugin['title'];
  $handler->task    = NULL;
  $handler->subtask = NULL;
  $handler->name    = NULL;
  $handler->handler = $plugin['name'];
  $handler->weight  = 0;
  $handler->conf    = array();

  // These are provided by the core export API provided by ctools and we
  // set defaults here so that we don't cause notices. Perhaps ctools should
  // provide a way to do this for us so we don't have to muck with it.
  $handler->export_type = EXPORT_IN_DATABASE;
  $handler->type = t('Local');

  if (isset($plugin['default conf'])) {
    if (is_array($plugin['default conf'])) {
      $handler->conf = $plugin['default conf'];
    }
    else if (function_exists($plugin['default conf'])) {
      $handler->conf = $plugin['default conf']($handler);
    }
  }

  return $handler;
}

/**
 * Set an overidden weight for a task handler.
 *
 * We do this so that in-code task handlers don't need to get written
 * to the database just because they have their weight changed.
 */
function page_manager_update_task_handler_weight($handler, $weight) {
  db_delete('page_manager_weights')
    ->condition('name', $handler->name)
    ->execute();
  db_insert('page_manager_weights')
    ->fields(array(
      'name' => $handler->name,
      'weight' => $weight,
    ))
    ->execute();
}


/**
 * Shortcut function to get task plugins.
 */
function page_manager_get_tasks() {
  ctools_include('plugins');
  return ctools_get_plugins('page_manager', 'tasks');
}

/**
 * Shortcut function to get a task plugin.
 */
function page_manager_get_task($id) {
  ctools_include('plugins');
  return ctools_get_plugins('page_manager', 'tasks', $id);
}

/**
 * Get all tasks for a given type.
 */
function page_manager_get_tasks_by_type($type) {
  ctools_include('plugins');
  $all_tasks = ctools_get_plugins('page_manager', 'tasks');
  $tasks = array();
  foreach ($all_tasks as $id => $task) {
    if (isset($task['task type']) && $task['task type'] == $type) {
      $tasks[$id] = $task;
    }
  }

  return $tasks;
}

/**
 * Fetch all subtasks for a page managertask.
 *
 * @param $task
 *   A loaded $task plugin object.
 */
function page_manager_get_task_subtasks($task) {
  if (empty($task['subtasks'])) {
    return array();
  }

  if ($function = ctools_plugin_get_function($task, 'subtasks callback')) {
    $retval = $function($task);
    if (is_array($retval)) {
      return $retval;
    }
    else {
      dsm($retval);
    }
  }

  return array();
}

/**
 * Fetch all subtasks for a page managertask.
 *
 * @param $task
 *   A loaded $task plugin object.
 * @param $subtask_id
 *   The subtask ID to load.
 */
function page_manager_get_task_subtask($task, $subtask_id) {
  if (empty($task['subtasks'])) {
    return;
  }

  if ($function = ctools_plugin_get_function($task, 'subtask callback')) {
    return $function($task, $subtask_id);
  }
}

/**
 * Shortcut function to get task handler plugins.
 */
function page_manager_get_task_handlers() {
  ctools_include('plugins');
  return ctools_get_plugins('page_manager', 'task_handlers');
}

/**
 * Shortcut function to get a task handler plugin.
 */
function page_manager_get_task_handler($id) {
  ctools_include('plugins');
  return ctools_get_plugins('page_manager', 'task_handlers', $id);
}

/**
 * Retrieve a list of all applicable task handlers for a given task.
 *
 * This looks at the $task['handler type'] and compares that to $task_handler['handler type'].
 * If the task has no type, the id of the task is used instead.
 */
function page_manager_get_task_handler_plugins($task, $all = FALSE) {
  $type = isset($task['handler type']) ? $task['handler type'] : $task['name'];
  $name = $task['name'];

  $handlers = array();
  $task_handlers = page_manager_get_task_handlers();
  foreach ($task_handlers as $id => $handler) {
    $task_type = is_array($handler['handler type']) ? $handler['handler type'] : array($handler['handler type']);
    if (in_array($type, $task_type) || in_array($name, $task_type)) {
      if ($all || !empty($handler['visible'])) {
        $handlers[$id] = $handler;
      }
    }
  }

  return $handlers;
}

/**
 * Get the title for a given handler.
 *
 * If the plugin has no 'admin title' function, the generic title of the
 * plugin is used instead.
 */
function page_manager_get_handler_title($plugin, $handler, $task, $subtask_id) {
  $function = ctools_plugin_get_function($plugin, 'admin title');
  if ($function) {
    return $function($handler, $task, $subtask_id);
  }
  else {
    return $plugin['title'];
  }
}

/**
 * Get the admin summary (additional info) for a given handler.
 */
function page_manager_get_handler_summary($plugin, $handler, $page, $title = TRUE) {
  if ($function = ctools_plugin_get_function($plugin, 'admin summary')) {
    return $function($handler, $page->task, $page->subtask, $page, $title);
  }
}

/**
 * Get the admin summary (additional info) for a given page.
 */
function page_manager_get_page_summary($task, $subtask) {
  if ($function = ctools_plugin_get_function($subtask, 'admin summary')) {
    return $function($task, $subtask);
  }
}

/**
 * Split a task name into a task id and subtask id, if applicable.
 */
function page_manager_get_task_id($task_name) {
  if (strpos($task_name, '-') !== FALSE) {
    return explode('-', $task_name, 2);
  }
  else {
    return array($task_name, NULL);
  }
}

/**
 * Turn a task id + subtask_id into a task name.
 */
function page_manager_make_task_name($task_id, $subtask_id) {
  if ($subtask_id) {
    return $task_id . '-' . $subtask_id;
  }
  else {
    return $task_id;
  }
}

/**
 * Get the render function for a handler.
 */
function page_manager_get_renderer($handler) {
  return ctools_plugin_load_function('page_manager', 'task_handlers', $handler->handler, 'render');
}

// --------------------------------------------------------------------------
// Functions existing on behalf of tasks and task handlers


/**
 * Page manager arg load function because menu system will not load extra
 * files for these; they must be in a .module.
 */
function pm_arg_load($value, $subtask, $argument) {
  page_manager_get_task('page');
  return _pm_arg_load($value, $subtask, $argument);
}

/**
 * Special arg_load function to use %menu_tail like functionality to
 * get everything after the arg together as a single value.
 */
function pm_arg_tail_load($value, $subtask, $argument, $map) {
  $value = implode('/', array_slice($map, $argument));
  page_manager_get_task('page');
  return _pm_arg_load($value, $subtask, $argument);
}

/**
 * Special menu _load() function for the user:uid argument.
 *
 * This is just the normal page manager argument. It only exists so that
 * the to_arg can exist.
 */
function pm_uid_arg_load($value, $subtask, $argument) {
  page_manager_get_task('page');
  return _pm_arg_load($value, $subtask, $argument);
}

/**
 * to_arg function for the user:uid argument to provide the arg for the
 * current global user.
 */
function pm_uid_arg_to_arg($arg) {
  return user_uid_optional_to_arg($arg);
}

/**
 * Callback for access control ajax form on behalf of page.inc task.
 *
 * Returns the cached access config and contexts used.
 */
function page_manager_page_ctools_access_get($argument) {
  $page = page_manager_get_page_cache($argument);

  $contexts = array();

  // Load contexts based on argument data:
  if ($arguments = _page_manager_page_get_arguments($page->subtask['subtask'])) {
    $contexts = ctools_context_get_placeholders_from_argument($arguments);
  }

  return array($page->subtask['subtask']->access, $contexts);
}

/**
 * Callback for access control ajax form on behalf of page.inc task.
 *
 * Writes the changed access to the cache.
 */
function page_manager_page_ctools_access_set($argument, $access) {
  $page = page_manager_get_page_cache($argument);
  $page->subtask['subtask']->access = $access;
  page_manager_set_page_cache($page);
}

/**
 * Callback for access control ajax form on behalf of context task handler.
 *
 * Returns the cached access config and contexts used.
 */
function page_manager_task_handler_ctools_access_get($argument) {
  list($task_name, $name) = explode('*', $argument);
  $page = page_manager_get_page_cache($task_name);
  if (empty($name)) {
    $handler = &$page->new_handler;
  }
  else {
    $handler = &$page->handlers[$name];
  }

  if (!isset($handler->conf['access'])) {
    $handler->conf['access'] = array();
  }

  ctools_include('context-task-handler');

  $contexts = ctools_context_handler_get_all_contexts($page->task, $page->subtask, $handler);

  return array($handler->conf['access'], $contexts);
}

/**
 * Callback for access control ajax form on behalf of context task handler.
 *
 * Writes the changed access to the cache.
 */
function page_manager_task_handler_ctools_access_set($argument, $access) {
  list($task_name, $name) = explode('*', $argument);
  $page = page_manager_get_page_cache($task_name);
  if (empty($name)) {
    $handler = &$page->new_handler;
  }
  else {
    $handler = &$page->handlers[$name];
  }

  $handler->conf['access'] = $access;
  page_manager_set_page_cache($page);
}

/**
 * Form a URL to edit a given page given the trail.
 */
function page_manager_edit_url($task_name, $trail = array()) {
  if (!is_array($trail)) {
    $trail = array($trail);
  }

  if (empty($trail) || $trail == array('summary')) {
    return "admin/structure/pages/edit/$task_name";
  }

  return 'admin/structure/pages/nojs/operation/' . $task_name . '/' . implode('/', $trail);
}

/**
 * Watch menu links during the menu rebuild, and re-parent things if we need to.
 */
function page_manager_menu_link_alter(&$item) {
  return;
/** -- disabled, concept code --
  static $mlids = array();
  // Keep an array of mlids as links are saved that we can use later.
  if (isset($item['mlid'])) {
    $mlids[$item['path']] = $item['mlid'];
  }

  if (isset($item['parent_path'])) {
    if (isset($mlids[$item['parent_path']])) {
      $item['plid'] = $mlids[$item['parent_path']];
    }
    else {
      // Since we didn't already see an mlid, let's check the database for one.
      $mlid = db_query('SELECT mlid FROM {menu_links} WHERE router_path = :path', array('path' => $item['parent_path']))->fetchField();
      if ($mlid) {
        $item['plid'] = $mlid;
      }
    }
  }
 */
}

/**
 * Callback to list handlers available for export.
 */
function page_manager_page_manager_handlers_list() {
  $list = $types = array();
  $tasks = page_manager_get_tasks();
  foreach ($tasks as $type => $info) {
    if (empty($info['non-exportable'])) {
      $types[] = $type;
    }
  }

  $handlers = ctools_export_load_object('page_manager_handlers');
  foreach ($handlers as $handler) {
    if (in_array($handler->task, $types)) {
      $plugin = page_manager_get_task_handler($handler->handler);
      $title = page_manager_get_handler_title($plugin, $handler, $tasks[$handler->task], $handler->subtask);

      if ($title) {
        $list[$handler->name] = check_plain("$handler->task: $title ($handler->name)");
      }
      else {
        $list[$handler->name] = check_plain("$handler->task: ($handler->name)");
      }
    }
  }
  return $list;
}

/**
 * Callback to bulk export page manager pages.
 */
function page_manager_page_manager_pages_to_hook_code($names = array(), $name = 'foo') {
  $schema = ctools_export_get_schema('page_manager_pages');
  $export = $schema['export'];
  $objects = ctools_export_load_object('page_manager_pages', 'names', array_values($names));
  if ($objects) {
    $code = "/**\n";
    $code .= " * Implements hook_{$export['default hook']}()\n";
    $code .= " */\n";
    $code .= "function " . $name . "_{$export['default hook']}() {\n";
    foreach ($objects as $object) {
      // Have to implement our own because this export func sig requires it
      $code .= $export['export callback']($object, TRUE, '  ');
      $code .= "  \${$export['identifier']}s['" . check_plain($object->$export['key']) . "'] = \${$export['identifier']};\n\n";
    }
    $code .= "  return \${$export['identifier']}s;\n";
    $code .= "}\n";
    return $code;
  }
}

/**
 * Get the current page information.
 *
 * @return $page
 *   An array containing the following information.
 *
 * - 'name': The name of the page as used in the page manager admin UI.
 * - 'task': The plugin for the task in use. If this is a system page it
 *   will contain information about that page, such as what functions
 *   it uses.
 * - 'subtask': The plugin for the subtask. If this is a custom page, this
 *   will contain information about that custom page. See 'subtask' in this
 *   array to get the actual page object.
 * - 'handler': The actual handler object used. If using panels, see
 *   $page['handler']->conf['display'] for the actual panels display
 *   used to render.
 * - 'contexts': The context objects used to render this page.
 * - 'arguments': The raw arguments from the URL used on this page.
 */
function page_manager_get_current_page($page = NULL) {
  static $current = array();
  if (isset($page)) {
    $current = $page;
  }

  return $current;
}

/**
 * Implementation of hook_panels_dashboard_blocks().
 *
 * Adds page information to the Panels dashboard.
 */
function page_manager_panels_dashboard_blocks(&$vars) {
  $vars['links']['page_manager'] = array(
    'weight' => -100,
    'title' => l(t('Panel page'), 'admin/structure/pages/add'),
    'description' => t('Panel pages can be used as landing pages. They have a URL path, accept arguments and can have menu entries.'),
  );

  module_load_include('inc', 'page_manager', 'page_manager.admin');
  $tasks = page_manager_get_tasks_by_type('page');
  $pages = array('operations' => array());

  page_manager_get_pages($tasks, $pages);
  $count = 0;
  $rows = array();
  foreach ($pages['rows'] as $id => $info) {
    $rows[] = array(
      'data' => array(
        $info['data']['title'],
        $info['data']['operations'],
      ),
      'class' => $info['class'],
    );

    // Only show 10.
    if (++$count >= 10) {
      break;
    }
  }

  $vars['blocks']['page_manager'] = array(
    'weight' => -100,
    'title' => t('Manage pages'),
    'link' => l(t('Go to list'), 'admin/structure/pages'),
    'content' => theme('table', array('header' => array(), 'rows' => $rows, 'attributes' => array('class' => 'panels-manage'))),
    'class' => 'dashboard-pages',
    'section' => 'right',
  );
}

/**
 * Implement pseudo-hook to fetch addressable content.
 *
 * For Page Manager, the address will be an array. The first
 * element will be the $task and the second element will be the
 * $task_handler. The third elements will be the arguments
 * provided.
 */
function page_manager_addressable_content($address, $type) {
  if (count($address) < 3) {
    return;
  }

  $task_name = array_shift($address);
  $subtask_name = array_shift($address);
  $handler_name = array_shift($address);
  if ($address) {
    $arguments = array_shift($address);
  }

  // Since $arguments is an array of arbitrary size, we need to implode it:
  if (!empty($arguments)) {
    // The only choices we have for separators since :: is already
    // used involve ., - or _. Since - and _ are more common than .
    // in URLs, let's try .. as an argument separator.
    $arguments = explode('..', $arguments);
  }
  else {
    // implode does not return an empty array on an empty
    // string so do it specifically.
    $arguments = array();
  }

  $task = page_manager_get_task($task_name);
  if (!$task) {
    return;
  }

  $handler = page_manager_load_task_handler($task, $subtask_name, $handler_name);
  if (!$handler) {
    return;
  }

  $handler_plugin = page_manager_get_task_handler($handler->handler);
  if (!$handler_plugin) {
    return;
  }

  // Load the contexts for the task.
  ctools_include('context');
  ctools_include('context-task-handler');
  $contexts = ctools_context_handler_get_task_contexts($task, $subtask_name, $arguments);

  // With contexts loaded, ensure the task is accessible. Tasks without a callback
  // are automatically accessible.
  $function = ctools_plugin_get_function($task, 'access callback');
  if ($function && !$function($task, $subtask_name, $contexts)) {
    return;
  }

  $function = ctools_plugin_get_function($handler_plugin, 'addressable callback');
  if ($function) {
    return $function($task, $subtask_name, $handler, $address, $contexts, $arguments, $type);
  }
}