summaryrefslogtreecommitdiffstats
path: root/page_manager/page_manager.admin.inc
blob: e53992575260d9acb9b825d387e056de8e35903c (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
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
<?php
// $Id$

/**
 * @file
 * Administrative functions for the page manager.
 *
 * This provides the UI to list, create, edit and delete pages, though much
 * of this is delegated through to individual tasks.
 */

/**
 * Output a list of pages that are managed.
 */
function page_manager_list_page($js = NULL) {
  // Prevent this page from showing up when random other links fail.
  if ($js && $js != 'ajax' && $js != 'nojs') {
    return drupal_not_found();
  }

  // TRUE if 'ajax', FALSE if otherwise.

  $js = $js == 'ajax';

  $tasks = page_manager_get_tasks_by_type('page');
  $pages = array('operations' => array());

  page_manager_get_pages($tasks, $pages);

  $input = $_POST;

  // Respond to a reset command by clearing session and doing a drupal goto
  // back to the base URL.
  if (isset($input['op']) && $input['op'] == t('Reset')) {
    unset($_SESSION['page_manager']['#admin']);
    if (!$js) {
      return drupal_goto($_GET['q']);
    }
    // clear everything but form id, form build id and form token:
    $keys = array_keys($input);
    foreach ($keys as $id) {
      if ($id != 'form_id' && $id != 'form_build_id' && $id != 'form_token') {
        unset($input[$id]);
      }
    }
    $replace_form = TRUE;
  }
  if (count($input) <= 1) {
    if (isset($_SESSION['page_manager']['#admin']) && is_array($_SESSION['page_manager']['#admin'])) {
      $input  = $_SESSION['page_manager']['#admin'];
    }
  }
  else {
    $_SESSION['page_manager']['#admin'] = $input;
    unset($_SESSION['page_manager']['#admin']['q']);
  }

  $form_state = array(
    'pages' => &$pages,
    'input' => $input,
    'rerender' => TRUE,
    'no_redirect' => TRUE,
  );

  // This form will sort and filter the pages.
  ctools_include('form');
  $form = ctools_build_form('page_manager_list_pages_form', $form_state);

  $header = array(
    array('data' => t('Type'), 'class' => 'page-manager-page-type'),
    array('data' => t('Name'), 'class' => 'page-manager-page-name'),
    array('data' => t('Title'), 'class' => 'page-manager-page-title'),
    array('data' => t('Path'), 'class' => 'page-manager-page-path'),
    array('data' => t('Storage'), 'class' => 'page-manager-page-storage'),
  );

  $header[] = array('data' => t('Operations'), 'class' => 'page-manager-page-operations');
  $table = theme('table', $header, $pages['rows'], array('id' => 'page-manager-list-pages'));
  $table .= '<div id="page-manager-links" class="links">' . theme('links', $pages['operations']) . '</div>';

  drupal_add_css(drupal_get_path('module', 'page_manager') . '/css/page-manager.css');
  
  if (!$js) {
    return $form . $table;
  }
  
  ctools_include('ajax');
  $commands = array();
  $commands[] = ctools_ajax_command_replace('#page-manager-list-pages', $table);
  if (!empty($replace_form)) {
    $commands[] = ctools_ajax_command_replace('#page-manager-list-pages-form', $form);
  }
  ctools_ajax_render($commands);
}

/**
 * Sort tasks into buckets based upon whether or not they have subtasks.
 */
function page_manager_get_pages($tasks, &$pages, $task_id = NULL) {
  foreach ($tasks as $id => $task) {
    if (empty($task_id) && !empty($task['page operations'])) {
      $pages['operations'] = array_merge($pages['operations'], $task['page operations']);
    }

    // If a type has subtasks, add its subtasks in its own table.
    if (!empty($task['subtasks'])) {
      page_manager_get_pages(page_manager_get_task_subtasks($task), $pages, $task['name']);
      continue;
    }

    if (isset($task_id)) {
      $task_name = page_manager_make_task_name($task_id, $task['name']);
    }
    else {
      $task_name = $task['name'];
    }

    $class = 'page-task-' . $id;
    if (isset($task['row class'])) {
      $class .= ' ' . $task['row class'];
    }

    if (!empty($task['disabled'])) {
      $class .= ' page-manager-disabled';
    }

    $row = array('data' => array(), 'class' => $class, 'title' => strip_tags($task['admin description']));

    $type = isset($task['admin type']) ? $task['admin type'] : t('System');
    $pages['types'][$type] = $type;
    $row['data']['type'] = array('data' => $type, 'class' => 'page-manager-page-type');

    $row['data']['name'] = array('data' => $task_name, 'class' => 'page-manager-page-name');
    $row['data']['title'] = array('data' => $task['admin title'], 'class' => 'page-manager-page-title');
    $row['data']['path'] = array('data' => '/' . $task['admin path'], 'class' => 'page-manager-page-path');

    $storage = isset($task['storage']) ? $task['storage'] : t('In code');
    $pages['storages'][$storage] = $storage;
    $row['data']['storage'] = array('data' => $storage, 'class' => 'page-manager-page-storage');

  /*
    if (empty($task['disabled'])) {
      $path = array();
      foreach (explode('/', $task['admin path']) as $bit) {
        if ($bit[0] == '%') {
          $path[] = '%';
        }
        else if ($bit[0] != '!') {
          $path[] = $bit;
        }
      }
      $path = implode('/', $path);
      $item = menu_get_item($path);
      if (empty($item)) {
        dsm($path);
      }
      else {
        dsm($item);
      }
    }
  */
    $operations = array(
      array(
        'title' => t('Edit'),
        'href' => page_manager_edit_url($task_name),
      ),
    );

    if (!empty($task['enable callback'])) {
      if (!empty($task['disabled'])) {
        $operations[] = array(
          'title' => t('Enable'),
          'href' => 'admin/build/pages/nojs/enable/' . $task_name,
        );
      }
      else {
        $operations[] = array(
          'title' => t('Disable'),
          'href' => 'admin/build/pages/nojs/disable/' . $task_name,
        );
      }
    }

    $row['data']['operations'] = array('data' => theme('links', $operations), 'class' => 'page-manager-page-operations');
    
    $pages['disabled'][$task_name] = !empty($task['disabled']);
    $pages['rows'][$task_name] = $row;
  }
}

/**
 * Provide a form for sorting and filtering the list of pages.
 */
function page_manager_list_pages_form(&$form_state) {
  $form['#action'] = url('admin/build/pages/nojs/', array('absolute' => TRUE));
  if (!variable_get('clean_url', FALSE)) {
    $form['q'] = array(
      '#type' => 'hidden',
      '#value' => $_GET['q'],
    );
  }

  $all = array('all' => t('<All>'));

  $form['type'] = array(
    '#type' => 'select',
    '#title' => t('Type'),
    '#options' => $all + $form_state['pages']['types'],
    '#default_value' => 'all',
  );

  $form['storage'] = array(
    '#type' => 'select',
    '#title' => t('Storage'),
    '#options' => $all + $form_state['pages']['storages'],
    '#default_value' => 'all',
  );

  $form['disabled'] = array(
    '#type' => 'select',
    '#title' => t('Enabled'),
    '#options' => $all + array('0' => t('Enabled'), '1' => t('Disabled')),
    '#default_value' => 'all',
  );
  
  $form['search'] = array(
    '#type' => 'textfield',
    '#title' => t('Search'),
  );

  $form['order'] = array(
    '#type' => 'select',
    '#title' => t('Sort by'),
    '#options' => array(
      'disabled' => t('Enabled, title'),
      'title' => t('Title'),
      'name' => t('Name'),
      'path' => t('Path'),
      'type' => t('Type'),
      'storage' => t('Storage'),
    ),
    '#default_value' => 'disabled',
  );

  $form['sort'] = array(
    '#type' => 'select',
    '#title' => t('Order'),
    '#options' => array(
      'asc' => t('Up'),
      'desc' => t('Down'),
    ),
    '#default_value' => 'asc',
  );

  $form['submit'] = array(
    '#name' => '', // so it won't in the $_GET args
    '#type' => 'submit',
    '#id' => 'edit-pages-apply',
    '#value' => t('Apply'),
    '#attributes' => array('class' => 'ctools-use-ajax'),
  );

  $form['reset'] = array(
    '#type' => 'submit',
    '#id' => 'edit-pages-reset',
    '#value' => t('Reset'),
    '#attributes' => array('class' => 'ctools-use-ajax'),
  );

  ctools_add_js('ajax-responder');
  drupal_add_js('misc/jquery.form.js');
  drupal_add_js(drupal_get_path('module', 'page_manager') . '/js/page-list.js');
  $form['#theme'] = array('page_manager_list_pages_form');
  return $form;
}

/**
 * Accept submission from the page manager sort/filter form and apply it
 * to the list of pages.
 */
function page_manager_list_pages_form_submit(&$form, &$form_state) {
  // Filter and re-sort the pages.

  // This is a copy.
  $rows = $form_state['pages']['rows'];

  $sorts = array();
  foreach ($rows as $name => $data) {
    // Filter
    if ($form_state['values']['type'] != 'all' && $form_state['values']['type'] != $data['data']['type']['data']) {
      continue;
    }

    if ($form_state['values']['storage'] != 'all' && $form_state['values']['storage'] != $data['data']['storage']['data']) {
      continue;
    }

    if ($form_state['values']['disabled'] != 'all' && $form_state['values']['disabled'] != $form_state['pages']['disabled'][$name]) {
      continue;
    }

    if ($form_state['values']['search'] &&
        strpos($data['data']['name']['data'], $form_state['values']['search']) === FALSE &&
        strpos($data['data']['path']['data'], $form_state['values']['search']) === FALSE &&
        strpos($data['data']['title']['data'], $form_state['values']['search']) === FALSE) {
          continue;
    }
    // Set up sorting
    switch ($form_state['values']['order']) {
      case 'disabled':
        $sorts[$name] = !$form_state['pages']['disabled'][$name] . $data['data']['title']['data'];
        break;
      case 'title':
        $sorts[$name] = $data['data']['title']['data'];
        break;
      case 'name':
        $sorts[$name] = $data['data']['name']['data'];
        break;
      case 'path':
        $sorts[$name] = $data['data']['path']['data'];
        break;
      case 'type':
        $sorts[$name] = $data['data']['type']['data'];
        break;
      case 'storage':
        $sorts[$name] = $data['data']['storage']['data'];
        break;
    }
  }

  // Now actually sort
  if ($form_state['values']['sort'] == 'desc') {
    arsort($sorts);
  }
  else {
    asort($sorts);
  }

  // Nuke the original.
  $form_state['pages']['rows'] = array();
  // And restore.
  foreach ($sorts as $name => $title) {
    $form_state['pages']['rows'][$name] = $rows[$name];
  }

}

/**
 * Render the edit page for a a page, custom or system.
 */
function page_manager_edit_page($page) {
  ctools_include('form');
  drupal_set_title($page->subtask['admin title']);
  // Provide and process the save page form before anything else.
  $form_state = array('page' => &$page);
  $form = ctools_build_form('page_manager_save_page_form', $form_state);

  $operations = page_manager_get_operations($page);
  $args = array('summary');
  $rendered_operations = page_manager_render_operations($page, $operations, $args, array('class' => 'operations-main'), 'nav');
  $content = page_manager_get_operation_content(FALSE, $page, $args, $operations);

  $output = theme('page_manager_edit_page', $page, $form, $rendered_operations, $content);
  return $output;
}

/**
 * Entry point to edit a single operation for a page.
 *
 * @param $js
 *   Whether or not the page was called via javascript.
 * @param $page
 *   The cached page that is being edited.
 * @param ...
 *   A number of items used to drill down into the actual operation called.
 */
function page_manager_edit_page_operation() {
  $args = func_get_args();
  $js = array_shift($args);
  $page = array_shift($args);

  $operations = page_manager_get_operations($page);
  $content = page_manager_get_operation_content($js, $page, $args, $operations);

  // If the operation requested we go somewhere else afterward, oblige it.
  if (isset($content['new trail'])) {
    $args = $content['new trail'];
    // Get operations again, for the operation may have changed their availability.
    $operations = page_manager_get_operations($page);
    $content = page_manager_get_operation_content($js, $page, $args, $operations);
  }

  // Rendering the content may have been a form submission that changed the
  // operations, such as renaming or adding a handler. Thus we get a new set
  // of operations.
  $operations = page_manager_get_operations($page);
  $rendered_operations = page_manager_render_operations($page, $operations, $args, array('class' => 'operations-main'), 'nav');

  // Since this form should never be submitted to this page, process it late so
  // that we can be sure it notices changes.
  ctools_include('form');
  $form_state = array('page' => &$page);
  $form = ctools_build_form('page_manager_save_page_form', $form_state);

  $output = theme('page_manager_edit_page', $page, $form, $rendered_operations, $content);

  if ($js) {
    $commands = array();
    if (isset($content['js settings'])) {
      $commands[] = ctools_ajax_command_settings($content['js settings']);
    }
    $commands[] = ctools_ajax_command_replace('#page-manager-edit', $output);

    ctools_ajax_render($commands);
  }

  drupal_set_title($page->subtask['admin title']);
  return $output;
}

/**
 * Take the operations array from a task and expand it.
 *
 * This allows some of the operations to be dynamic, based upon settings
 * on the task or the task's handlers. Each operation should have a type. In
 * addition to all the types allowed in page_manager_render_operations, these
 * types will be dynamically replaced with something else:
 * - 'handlers': An automatically created group that contains all the task's
 *   handlers and appropriate links.
 * - 'function': A callback (which will be placed in the 'function' parameter
 *   that should return an array of operations. This can be used to provide
 *   additional, dynamic links if needed.
 */
function page_manager_get_operations($page, $operations = NULL) {
  if (!isset($operations)) {
    // All tasks have at least these 2 ops:
    $operations = array(
      'summary' => array(
        'title' => t('Summary'),
        'description' => t('Get a summary of the information about this page.'),
        'path' => 'admin/build/pages/edit',
        'ajax' => FALSE,
        'no operations' => TRUE,
        'form info' => array(
          'no buttons' => TRUE,
        ),
        'form' => 'page_manager_page_summary',
      ),
      'actions' => array(
        'type' => 'group',
        'title' => '',
        'class' => 'operations-actions',
        'location' => 'primary',
        'children' => array(),
      ),
    );
    
    if (isset($page->subtask['operations'])) {
      $operations += $page->subtask['operations'];
      // add actions separately.
      if (!empty($page->subtask['operations']['actions'])) {
        $operations['actions']['children'] += $page->subtask['operations']['actions']['children'];
      }
    }
    $operations['handlers'] = array('type' => 'handlers');
  }

  $result = array();
  foreach ($operations as $id => $operation) {
    if (empty($operation['type'])) {
      $operation['type'] = 'operation';
    }
    switch ($operation['type']) {
      case 'handlers':
        $result[$id] = page_manager_get_handler_operations($page);
        break;
      case 'function':
        if (function_exists($operation['function'])) {
          $retval = $function($page, $operation);
          if (is_array($retval)) {
            $result[$id] = $retval;
          }
        }
        break;
      default:
        $result[$id] = $operation;
    }
  }

  if (!empty($page->subtask['enable callback']) && !empty($page->subtask['disabled']) && empty($result['actions']['children']['enable'])) {
    $result['actions']['children']['enable'] = array(
      'title' => t('Enable'),
      'description' => t('Activate this page so that it will be in use in your system.'),
      'form' => 'page_manager_enable_form',
      'ajax' => FALSE,
      'silent' => TRUE,
      'form info' => array(
        'finish text' => t('Enable'),
      ),
    );
  }

  if (!empty($page->subtask['enable callback']) && empty($page->subtask['disabled']) && empty($result['actions']['children']['disable'])) {
    $result['actions']['children']['disable'] = array(
      'title' => t('Disable'),
      'description' => t('De-activate this page. The data will remain but the page will not be in use on your system.'),
      'form' => 'page_manager_disable_form',
      'ajax' => FALSE,
      'silent' => TRUE,
      'form info' => array(
        'finish text' => t('Disable'),
      ),
    );
  }

  $result['actions']['children']['add'] = array(
    'title' => t('Add variant'),
    'description' => t('Add a new variant to this page.'),
    'form' => 'page_manager_handler_add',
    'ajax' => FALSE,
    'silent' => TRUE, // prevents a message about updating and prevents this item from showing as changed.
    'form info' => array(
      'finish text' => t('Add variant'),
    ),
  );

  $result['actions']['children']['import'] = array(
    'title' => t('Import variant'),
    'description' => t('Add a new variant to this page from code exported from another page.'),
    'form' => 'page_manager_handler_import',
  );

  if (count($page->handlers) > 1) {
    $result['actions']['children']['rearrange'] = array(
      'title' => t('Reorder variants'),
      'ajax' => FALSE,
      'description' => t('Change the priority of the variants to ensure that the right one gets selected.'),
      'form' => 'page_manager_handler_rearrange',
    );
  }

  // This is a special operation used to configure a new task handler before
  // it is added.
  if (isset($page->new_handler)) {
  $plugin = page_manager_get_task_handler($page->new_handler->handler);
    $result['actions']['children']['configure'] = array(
      'title' => t('Configure'),
      'description' => t('Configure a newly created variant prior to actually adding it to the page.'),
      'ajax' => FALSE,
      'form info' => array(
        // We use our own cancel and finish callback to handle the fun stuff.
        'finish callback' => 'page_manager_handler_add_finish',
        'cancel callback' => 'page_manager_handler_add_cancel',
        'show trail' => TRUE,
        'show back' => TRUE,
        'finish text' => t('Add variant'),
      ),
      'form' => array(
        'forms' => $plugin['forms'],
      ),
    );

    foreach ($page->forms as $id) {
      if (isset($plugin['add features'][$id])) {
        $result['actions']['children']['configure']['form']['order'][$id] = $plugin['add features'][$id];        
      }
      else if (isset($plugin['required forms'][$id])) {
        $result['actions']['children']['configure']['form']['order'][$id] = $plugin['required forms'][$id];        
      }
    }
  }

  if ($page->locked) {
    $result['actions']['children']['break-lock'] = array(
      'title' => t('Break lock'),
      'description' => t('Break the lock on this page so that you can edit it.'),
      'form' => 'page_manager_break_lock',
      'ajax' => FALSE,
      'form info' => array(
        'finish text' => t('Break lock'),
       ),
      'even locked' => TRUE, // show button even if locked
      'silent' => TRUE,
    );
  }

  return $result;
}

/**
 * Collect all the operations related to task handlers (variants) and
 * build a menu.
 */
function page_manager_get_handler_operations(&$page) {
  ctools_include('export');
  $group = array(
    'type' => 'group',
    'class' => 'operations-handlers',
    'title' => t('Variants'),
  );

  $operations = array();

  // If there is only one variant, let's not have it collapsible.
  $collapsible = count($page->handler_info) != 1;
  foreach ($page->handler_info as $id => $info) {
    if ($info['changed'] & PAGE_MANAGER_CHANGED_DELETED) {
      continue;
    }
    $handler = $page->handlers[$id];
    $plugin = page_manager_get_task_handler($handler->handler);

    $operations[$id] = array(
      'type' => 'group',
      'class' => 'operations-handlers-' . $id,
      'title' => page_manager_get_handler_title($plugin, $handler, $page->task, $page->subtask_id),
      'collapsible' => $collapsible,
      'children' => array(),
    );

    $operations[$id]['children']['actions'] = array(
      'type' => 'group',
      'class' => 'operations-handlers-actions-' . $id,
      'title' => t('Variant operations'),
      'children' => array(),
      'location' => $id,
    );

    // There needs to be a 'summary' item here for variants.
    $operations[$id]['children']['summary'] = array(
      'title' => t('Summary'),
      'description' => t('Get a summary of the information about this variant.'),
      'form info' => array(
        'no buttons' => TRUE, 
      ),
      'form' => 'page_manager_handler_summary',
    );

    if ($plugin && isset($plugin['operations'])) {
      $operations[$id]['children'] += $plugin['operations'];
    }
    
    $actions = &$operations[$id]['children']['actions']['children'];

    $actions['clone'] = array(
      'title' => t('Clone'),
      'description' => t('Make an exact copy of this variant.'),
      'form' => 'page_manager_handler_clone',
    );
    $actions['export'] = array(
      'title' => t('Export'),
      'description' => t('Export this variant into code to import into another page.'),
      'form' => 'page_manager_handler_export',
    );
    if ($handler->export_type == (EXPORT_IN_CODE | EXPORT_IN_DATABASE)) {
      $actions['delete'] = array(
        'title' => t('Revert'),
        'description' => t('Remove all changes to this variant and revert to the version in code.'),
        'form' => 'page_manager_handler_delete',
        'form info' => array(
          'finish text' => t('Revert'),
        ),
      );
    }
    else if ($handler->export_type != EXPORT_IN_CODE) {
      $actions['delete'] = array(
        'title' => t('Delete'),
        'description' => t('Remove this variant from the page completely.'),
        'form' => 'page_manager_handler_delete',
        'form info' => array(
          'finish text' => t('Delete'),
        ),
      );
    }
    if (!empty($handler->disabled)) {
      $actions['enable'] = array(
        'title' => t('Enable'),
        'description' => t('Activate this variant so that it will be in use in your system.'),
        'form' => 'page_manager_handler_enable',
        'silent' => TRUE,
        'form info' => array(
          'finish text' => t('Enable'),
        ),
      );
    }
    else {
      $actions['disable'] = array(
        'title' => t('Disable'),
        'description' => t('De-activate this variant. The data will remain but the variant will not be in use on your system.'),
        'form' => 'page_manager_handler_disable',
        'silent' => TRUE,
        'form info' => array(
          'finish text' => t('Disable'),
        ),
      );
    }
  }
  if (empty($operations)) {
    $operations['empty'] = array(
      'type' => 'text',
      'title' => t('No variants'),
    );
  }

  $group['children'] = $operations;
  return $group;
}

/**
 * Get an operation from a trail.
 *
 * @return array($operation, $active, $args)
 */
function page_manager_get_operation($operations, $trail) {
  $args = $trail;
  $stop = FALSE;
  $active = array();
  $titles = array();
  // Drill down into operations array:
  while (!$stop) {
    $check = reset($args);
    $stop = TRUE;
    if (is_array($operations)) {
      if (isset($operations[$check])) {
        $active[] = $check;
        $operation = array_shift($args);
        // check to see if this operation has children. If so, we continue.
        if (!isset($operations[$check]['children'])) {
          $operations = $operations[$check];
        }
        else {
          $titles[] = $operations[$check]['title'];
          $operations = $operations[$check]['children'];
          // continue only if the operation hs children.
          $stop = FALSE;
        }
      }
    }
  }

  return array($operations, $active, $args, $titles);
}

/**
 * Fetch the content for an operation.
 *
 * First, this drills down through the arguments to find the operation, and
 * turns whatever it finds into the active trail which is then used to
 * hilite where we are when rendering the operation list.
 *
 * The arguments are discovered from the URL, and are an exact match for where
 * the operation is in the hierarchy. For example, handlers/foo/settings will
 * be the operation to edit the settings for the handler named foo. This comes
 * in as an array ('handlers', 'foo', 'settings') and is used to find where the
 * data for that operation is in the array.
 */
function page_manager_get_operation_content($js, &$page, $trail, $operations) {
  list($operation, $active, $args, $titles) = page_manager_get_operation($operations, $trail);
  // Once we've found the operation, send it off to render.
  if ($operation) {
    $content = _page_manager_get_operation_content($js, $page, $active, $operation, $titles, $args);
  }

  if (empty($content)) {
    $content = _page_manager_get_operation_content($js, $page, array('summary'), $operations['summary']);
  }

  return $content;
}

/**
 * Fetch the content for an operation, after it's been discovered from arguments.
 *
 * This system runs through the CTools form wizard. Each operation specifies a form
 * or set of forms that it may use. Operations may also specify wrappers and can
 * set their own next/finish handlers so that they can make additional things happen
 * at the end.
 */
function _page_manager_get_operation_content($js, &$page, $active, $operation, $titles = array(), $args = array()) {
  if (isset($operation['form'])) {
    $form_info = array(
      'id' => 'page_manager_page',
      'finish text' => t('Update'),
      'show trail' => FALSE,
      'show back' => FALSE,
      'show return' => FALSE,
      'show cancel' => FALSE,
      'next callback' => 'page_manager_edit_page_next',
      'finish callback' => 'page_manager_edit_page_finish',
      // Items specific to the 'edit' routines that will get moved over:
      'path' => page_manager_edit_url($page->task_name, $active) . "/%step",
    );

    // If $operation['form'] is simply a string, then it is the function
    // name of the form.
    if (!is_array($operation['form'])) {
      $form_info['order'] = array(
        'form' => $operation['title'],
      );
      $form_info['forms'] = array(
        'form' => array('form id' => $operation['form']),
      );
      if (isset($operation['wrapper'])) {
        $form_info['forms']['form']['wrapper'] = $operation['wrapper'];
      }
    }
    // Otherwise it's the order and forms arrays directly.
    else {
      $form_info['order'] = $operation['form']['order'];
      $form_info['forms'] = $operation['form']['forms'];
    }

    // Allow the operation to override any form info settings:
    if (isset($operation['form info'])) {
      foreach ($operation['form info'] as $key => $setting) {
        $form_info[$key] = $setting;
      }
    }

    if (!empty($page->subtask['operations include'])) {
      // Quickly load any files necessary to display the forms.
      $page->subtask['operations include']['function'] = 'nop';
      ctools_plugin_get_function($page->subtask, 'operations include');
    }

    $step = array_shift($args);
    // If step is unset, go with the basic step.
    if (!isset($step)) {
      $step = current(array_keys($form_info['order']));
    }

    // If it is locked, hide the buttonzzz!
    if ($page->locked && empty($operation['even locked'])) {
      $form_info['no buttons'] = TRUE;
    }

    ctools_include('wizard');
    $form_state = array(
      'page' => $page,
      'type' => 'edit',
      'ajax' => $js && (!isset($operation['ajax']) || !empty($operation['ajax'])),
      'rerender' => TRUE,
      'no_redirect' => $js,
      'trail' => $active,
      'task_name' => $page->task_name,
      'task_id' => $page->task_id,
      'task' => $page->task,
      'subtask_id' => $page->subtask_id,
      'subtask' => $page->subtask,
      'operation' => $operation,
    );

    if ($active && $active[0] == 'handlers' && isset($form_state['page']->handlers[$form_state['trail'][1]])) {
      $form_state['handler_id'] = $form_state['trail'][1];
      $form_state['handler'] = &$form_state['page']->handlers[$form_state['handler_id']];
    }

    if ($active && $active[0] == 'actions' && $active[1] == 'configure' && isset($form_state['page']->new_handler)) {
      $form_state['handler_id'] = $form_state['page']->new_handler->name;
      $form_state['handler'] = &$form_state['page']->new_handler;
    }

    $output = ctools_wizard_multistep_form($form_info, $step, $form_state);
    $title = empty($form_state['title']) ? $operation['title'] : $form_state['title'];
    $titles[] = $title;
    $title = implode(' &raquo ', array_filter($titles));
    if (isset($form_state['js settings'])) {
      $js_settings = $form_state['js settings'];
    }

    // If there are messages for the form, render them.
    if ($messages = theme('status_messages')) {
      $output = $messages . $output;
    }

    $return = array(
      'title' => $title,
      'content' => $output,
    );

    // Append any extra content, used for the preview which is submitted then
    // rendered.
    if (isset($form_state['content'])) {
      $return['content'] .= $form_state['content'];
    }
    
    // If the form wanted us to go somewhere else next, pass that along.
    if (isset($form_state['new trail'])) {
      $return['new trail'] = $form_state['new trail'];
    }
  }
  else {
    $return = array(
      'title' => t('Error'),
      'content' => t('This operation trail does not exist.'),
    );
  }

  if (isset($js_settings)) {
    $return['js settings'] = $js_settings;
  }

  $return['active'] = $active;
  return $return;
}

/**
 * Callback generated when the add page process is finished.
 */
function page_manager_edit_page_finish(&$form_state) {
  if (empty($form_state['operation']['silent'])) {
    drupal_set_message(t('The page has been updated. Changes will not be permanent until you save.'));
    $path = array();
    foreach ($form_state['trail'] as $operation) {
      $path[] = $operation;
      $form_state['page']->changes[implode('/', $path)] = TRUE;
    }
  }

  // If a handler was modified, set it to changed so we know to overwrite it.
  if (isset($form_state['handler_id'])) {
    $form_state['page']->handler_info[$form_state['handler_id']]['changed'] |= PAGE_MANAGER_CHANGED_CACHED;
  }

  // While we make buttons go away on locked pages, it is still possible to 
  // have a lock a appear while you were editing, and have your changes
  // disappear. This at least warns the user that this has happened.
  if (!empty($page->locked)) {
    drupal_set_message(t('Unable to update changes due to lock.'));
  }

  if (empty($form_state['do not cache'])) {
    page_manager_set_page_cache($form_state['page']);
  }

  if (isset($form_state['new trail']) && empty($form_state['ajax'])) {
    $form_state['redirect'] = page_manager_edit_url($form_state['page']->task_name, $form_state['new trail']);
  }
}

/**
 * Callback generated when the 'next' button is clicked.
 *
 * All we do here is store the cache.
 */
function page_manager_edit_page_next(&$form_state) {
  page_manager_set_page_cache($form_state['page']);
}

/**
 * Callback generated when the 'cancel' button is clicked.
 *
 * All we do here is clear the cache.
 */
function page_manager_edit_page_cancel(&$form_state) {
  $page = $form_state['page'];
}

/**
 * Render an operations array.
 *
 * This renders an array of operations into a series of nested UL statements, 
 * with ajax automatically on unless specified otherwise. Operations will 
 * automatically have the URLs generated nested.
 *
 * Each operation should have a 'type', which tells the renderer how to deal 
 * with it:
 * - 'operation': An AJAX link to render. This is the default and is
 *   assumed if a type is not specified. Other fields for the operation:
 * - - 'title': The text to display. Can be an image. Must be pre-sanitized.
 * - - 'description': Text to place in the hover box over the link using the 
 *     title attribute.
 * - - 'arguments': Anything optional to put at the end of the URL.
 * - - 'path': If set, overrides the default path.
 * - - 'no operations': If set, the path will not have operations appended.
 * - - 'no task': If set, the path will not have the task id.
 * - - 'no link': If set, this item will just be text, not a link.
 * - - 'ajax': If set to TRUE, ajax will be used. The default is TRUE.
 * - - 'class': An optional class to specify for the link.
 * - - 'form': The form to display for this operation, if using a single form.
 * - - 'forms': An array of forms that must be paired with 'order' of this 
 *      operation uses multiple forms. See wizard tool for details.
 * - - 'order': The form order to use for multiple forms. See wizard tool for
 *     details.
 * - - 'form info': Form info overrides for the wizard. See the wizard tool 
 *      for available settings
 * - 'group':
 * - - 'title': The title of the link. May be HTML.
 * - - 'title class': A class to apply to the title.
 * - - 'children': An array of more operations that this group represents.
 *     All operations within this group will have this group's ID as part
 *     of the AJAX url to make it easier to find.
 * - - 'class': A class to apply to the UL of the children.
 * - - 'collapsible': If TRUE the collapsible tool will be used.
 */
function page_manager_render_operations(&$page, $operations, $active_trail, $attributes, $location, $parents = array()) {
  if (!isset($output[$location])) {
    $output[$location] = '';
  }

  $keys = array_keys($operations);
  $first = array_shift($keys);
  $last = array_pop($keys);

  // Make sure the 'first' and 'last' operations are part of THIS nav tree:
  while ($keys && isset($operations[$first]['location']) && $operations[$first]['location'] != $location) {
    $first = array_shift($keys);
  }
  while ($keys && isset($operations[$last]['location']) && $operations[$last]['location'] != $location) {
    $last = array_pop($keys);
  }

  $active = reset($active_trail);
  foreach ($operations as $id => $operation) {
    $current_path = '';
    if ($parents) {
      $current_path .= implode('/', $parents) . '/';
    }
    $current_path .= $id;

    if (empty($operation['type'])) {
      $operation['type'] = 'operation';
    }

    // We only render an li for things in the same nav tree.
    if (empty($operation['location']) || $operation['location'] == $location) {
      $class = $attributes['class'];
      if ($id == $first) {
        $class .= ' operation-first';
      }
      else if ($id == $last) {
        $class .= ' operation-last';
      }

      if (empty($operation['silent']) && !empty($page->changes[$current_path])) {
        $class .= $operation['type'] == 'group' ? ' changed-group' : ' changed';
      }
      else {
        $class .= ' not-changed';
      }

      if ($active == $id) {
        $class .= $operation['type'] == 'group' ? ' active-group' : ' active';
      }
      else {
        $class .= ' not-active';
      }

      $output[$location] .= '<li class="' . $class . '">';
    }

    switch ($operation['type']) {
      case 'text':
        $output[$location] .= $operation['title'];
        break;
      case 'operation':
        $path = isset($operation['path']) ? $operation['path'] : 'admin/build/pages/nojs/operation';
        if (!isset($operation['no task'])) {
          $path .= '/' . $page->task_name;
        }

        if (!isset($operation['no operations'])) {
          $path .= '/' . $current_path;
          if (isset($operation['arguments'])) {
            $path .= '/' . $arguments;
          }
        }

        $class = 'page-manager-operation';
        if (!isset($operation['ajax']) || !empty($operation['ajax'])) {
          $class .= ' ctools-use-ajax';
        }
        if (!empty($operation['class'])) {
          $class .= ' ' . $operation['class'];
        }

        $description = isset($operation['description']) ? $operation['description'] : '';
        if (empty($operation['silent']) && !empty($page->changes[$current_path])) {
          $description .= ' ' . t('This setting contains unsaved changes.');
        }

        $output[$location] .= l($operation['title'], $path, array('attributes' => array('id' => 'page-manager-operation-' . $id, 'class' => $class, 'title' => $description), 'html' => TRUE));
        break;
      case 'group':
        if ($active == $id) {
          $trail = $active_trail;
          array_shift($trail);
        }
        else {
          $trail = array();
        }
        $group_location = isset($operation['location']) ? $operation['location'] : $location;
        $temp = page_manager_render_operations($page, $operation['children'], $trail, $operation, $group_location, array_merge($parents, array($id)));
        if ($temp) {
          foreach ($temp as $id => $text) {
            if (empty($output[$id])) {
              $output[$id] = '';
            }
            $output[$id] .= $text;
          }
        }
        break;
    }

    if (empty($operation['location']) || $operation['location'] == $location) {
      $output[$location] .= '</li>';
    }
  }

  if ($output[$location]) {
    $output[$location] = '<ul class="page-manager-operations ' . $attributes['class'] . '">' . $output[$location] . '</ul>';

    if (!empty($attributes['title'])) {
      $class = '';
      if (isset($attributes['title class'])) {
        $class = $attributes['title class'];
      }
      $title = '<div class="page-manager-group-title' . $class . '">' . $attributes['title'] . '</div>';

      if (!empty($attributes['collapsible'])) {
        $output[$location] = theme('ctools_collapsible', $title, $output[$location], empty($active_trail));
      }
      else {
        $output[$location] = $title . $output[$location];
      }
    }
    return $output;
  }
}

/**
 * Provide a simple form for saving the page manager info out of the cache.
 */
function page_manager_save_page_form(&$form_state) {
  if (!empty($form_state['page']->changed)) {
    $form['markup'] = array(
      '#value' => '<div class="changed-notification">' . t('You have unsaved changes to this page. You must select Save to write them to the database, or Cancel to discard these changes. Please note that if you have changed any form, you must submit that form before saving.') . '</div>',
    );

    // Always make sure we submit back to the proper page.
    $form['#action'] = url('admin/build/pages/edit/' . $form_state['page']->task_name);
    $form['save'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
      '#submit' => array('page_manager_save_page_form_submit'),
    );

    $form['cancel'] = array(
      '#type' => 'submit',
      '#value' => t('Cancel'),
      '#submit' => array('page_manager_save_page_form_cancel'),
    );
    return $form;
  }
}

/**
 * Save the page.
 */
function page_manager_save_page_form_submit(&$form, &$form_state) {
  page_manager_save_page_cache($form_state['page']);
}

/**
 * Discard changes to the page.
 */
function page_manager_save_page_form_cancel(&$form, &$form_state) {
  drupal_set_message(t('All pending changes have been discarded, and the page is now unlocked.'));
  page_manager_clear_page_cache($form_state['page']->task_name);

  if (!empty($form_state['page']->new)) {
    $form_state['redirect'] = 'admin/build/pages';
  }
}

// --------------------------------------------------------------------------
// Handler (variant) related forms.

/**
 * Add a new task handler.
 */
function page_manager_handler_add(&$form, &$form_state) {
  // Get a list of possible task handlers for this task.
  page_manager_handler_add_form($form, $form_state);
}

/**
 * Handler related forms.
 */
function page_manager_handler_add_submit(&$form, &$form_state) {
  $cache = $form_state['page'];
  $plugin = page_manager_get_task_handler($form_state['values']['handler']);

  // Create a new handler.
  $handler = page_manager_new_task_handler($plugin);
  if (!empty($form_state['values']['title'])) {
    $handler->conf['title'] = $form_state['values']['title'];
  }
  else {
    $handler->conf['title'] = $plugin['title'];
  }
  $cache->new_handler = $handler;

  // Figure out which forms to present them with
  $cache->forms = array();

  $features = $form_state['values']['features'];
  if (isset($features[$form_state['values']['handler']])) {
    $cache->forms = array_merge($cache->forms, array_keys(array_filter($features[$form_state['values']['handler']])));
  }

  if (isset($plugin['required forms'])) {
    $cache->forms = array_merge($cache->forms, array_keys($plugin['required forms']));
  }

  $form_state['no_rerender'] = TRUE;
  if (!empty($cache->forms)) {
    // Tell the form to go to the config page.
    drupal_set_message(t('Before this variant can be added, it must be configured. When you are finished, click "Add variant" to add this to your page.'));
    $form_state['new trail'] = array('actions', 'configure');
  }
  else {
    // It has no forms at all. Add the variant and go to its first operation.
    page_manager_handler_add_finish($form_state);
  }
}

/**
 * Finish the add process and make the new handler official.
 */
function page_manager_handler_add_finish(&$form_state) {
  $page = &$form_state['page'];
  $handler = $page->new_handler;
  page_manager_handler_add_to_page($page, $handler);

  // Remove the temporary page.
  unset($page->new_handler);
  unset($page->forms);

  // Set the new destination
  $plugin = page_manager_get_task_handler($handler->handler);
  if (!empty($plugin['add finish'])) {
    $location = $plugin['add finish'];
  }
  else {
    $keys = array_keys($plugin['operations']);
    $location = reset($keys);
  }

  $form_state['new trail'] = array('handlers', $handler->name, $location);

  // Pass through.
  page_manager_edit_page_finish($form_state);
}

/**
 * Throw away a new handler and return to the add form
 */
function page_manager_handler_add_cancel(&$form_state) {
  $form_state['new trail'] = array('handlers', 'add'); 

  // Remove the temporary page.
  unset($page->new_handler);
  unset($page->forms);
}

/**
 * Provide a consistent UI for adding handlers.
 */
function page_manager_handler_add_form(&$form, $form_state, $features = array()) {
  $task = $form_state['task'];
  $task_handler_plugins = page_manager_get_task_handler_plugins($task);
  foreach ($task_handler_plugins as $id => $plugin) {
    $options[$id] = $plugin['title'];
    if (isset($plugin['add features'])) {
      $features[$id] = $plugin['add features'];
    }
  }

  if (!isset($form_state['type']) || $form_state['type'] != 'add') {
    $form['title'] = array(
      '#type' => 'textfield',
      '#title' => t('Title'),
      '#description' => t('Administrative title of this variant. If you leave blank it will be automatically assigned.'),
    );
  }
  
  $form['handler'] = array(
    '#title' => t('Variant type'),
    '#type' => 'select',
    '#options' => $options,
  );

  // This set of checkboxes is not dangerous at all.
  $form['features'] = array(
    '#type' => 'checkboxes',
    '#validated' => TRUE,
    '#title' => t('Optional features'),
    '#options' => array(),
    '#description' => t('Check any optional features you need to be presented with forms for configuring them. If you do not check them here you will still be able to utilize these features once the new page is created. If you are not sure, leave these unchecked.'),
    '#tree' => TRUE,
  );

  ctools_include('dependent');
  foreach ($features as $plugin => $feature_list) {
    foreach ($feature_list as $feature_id => $feature) {
      $form['features'][$plugin][$feature_id] = array(
        '#type' => 'checkbox',
        '#title' => $feature,
      );

      if ($plugin != 'default') {
        $form['features'][$plugin][$feature_id] += array(
          '#process' => array('ctools_dependent_process'),
          '#dependency' => array('edit-handler' => array($plugin)),
        );
      }
    }
  }
}

/**
 * Rearrange the order of variants.
 */
function page_manager_handler_import(&$form, &$form_state) {
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Variant name'),
    '#description' => t('Enter the name of the new variant.'),
  );

  $form['object'] = array(
    '#type' => 'textarea',
    '#title' => t('Paste variant code here'),
    '#rows' => 15,
  );
}

/**
 * Make sure that an import actually provides a handler.
 */
function page_manager_handler_import_validate($form, &$form_state) {
  $export = page_manager_export_task_handler($form_state['values']['object']);
  ob_start();
  eval($export);
  ob_end_clean();

  if (empty($handler)) {
    $errors = ob_get_contents();
    if (empty($errors)) {
      $errors = t('No variant found.');
    }

    form_error($form['object'], t('Unable to get a variant from the import. Errors reported: @errors', array('@errors' => $errors)));
  }

  $form_state['handler'] = $handler;
}

/**
 * Clone an existing task handler into a new handler.
 */
function page_manager_handler_import_submit($form, &$form_state) {
  $export = page_manager_export_task_handler($form_state['handler']);

  page_manager_handler_add_to_page($form_state['page'], $handler, $form_state['values']['title']);

  $plugin = page_manager_get_task_handler($handler->handler);
  // It has no forms at all. Add the variant and go to its first operation.
  $keys = array_keys($plugin['operations']);
  $form_state['new trail'] = array('handlers', $name, reset($keys));
}

/**
 * Rearrange the order of variants.
 */
function page_manager_handler_rearrange(&$form, &$form_state) {
  $page = $form_state['page'];

  $form['handlers'] = array('#tree' => TRUE);

  foreach ($page->handler_info as $id => $info) {
    if ($info['changed'] & PAGE_MANAGER_CHANGED_DELETED) {
      continue;
    }
    $handler = $page->handlers[$id];
    $plugin = page_manager_get_task_handler($handler->handler);

    $form['handlers'][$id]['title'] = array(
      '#value' => page_manager_get_handler_title($plugin, $handler, $page->task, $page->subtask_id),
    );
  
    $form['handlers'][$id]['weight'] = array(
      '#type' => 'weight',
      '#default_value' => $info['weight'],
    );
  }
}

function page_manager_handler_rearrange_submit(&$form, &$form_state) {
  $handler_info = &$form_state['page']->handler_info;

  foreach ($form_state['values']['handlers'] as $id => $info) {
    if ($handler_info[$id]['weight'] = $info['weight']) {
      $handler_info[$id]['weight'] = $info['weight'];
      $handler_info[$id]['changed'] |= PAGE_MANAGER_CHANGED_MOVED;
    }
  }

  // Sort the new cache.
  uasort($handler_info, '_page_manager_handler_sort');

}

/**
 * Used as a callback to uasort to sort the task cache by weight.
 *
 * The 'name' field is used as a backup when weights are the same, which
 * can happen when multiple modules put items out there at the same
 * weight.
 */
function _page_manager_handler_sort($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;
  }
}

/**
 * Rearrange the order of variants.
 */
function page_manager_handler_delete(&$form, &$form_state) {
  if ($form_state['handler']->type == t('Overridden')) {
    $text = t('Reverting the variant will delete the variant that is in the database, reverting it to the original default variant. This deletion will not be made permanent until you click Save.');
  }
  else {
    $text = t('Are you sure you want to delete this variant? This deletion will not be made permanent until you click Save.');
  }
  $form['markup'] = array(
    '#value' => '<p>' . $text . '</p>',
  );

}

/**
 * Submit handler to delete a view.
 */
function page_manager_handler_delete_submit(&$form, &$form_state) {
  $form_state['page']->handler_info[$form_state['handler_id']]['changed'] |= PAGE_MANAGER_CHANGED_DELETED;
  $form_state['new trail'] = array('summary');
}

/**
 * Entry point to export a page.
 */
function page_manager_handler_export(&$form, &$form_state) {
  $export = page_manager_export_task_handler($form_state['handler']);

  $lines = substr_count($export, "\n");
  $form['code'] = array(
    '#type' => 'textarea',
    '#default_value' => $export,
    '#rows' => $lines,
  );

  unset($form['buttons']);
}

/**
 * Rearrange the order of variants.
 */
function page_manager_handler_clone(&$form, &$form_state) {
  // This provides its own button because it does something totally different.
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Variant name'),
    '#description' => t('Enter the name of the new variant.'),
  );
}

/**
 * Clone an existing task handler into a new handler.
 */
function page_manager_handler_clone_submit($form, &$form_state) {
  $export = page_manager_export_task_handler($form_state['handler']);
  ob_start();
  eval($export);
  ob_end_clean();

  page_manager_handler_add_to_page($form_state['page'], $handler, $form_state['values']['title']);

  $plugin = page_manager_get_task_handler($handler->handler);
  // It has no forms at all. Add the variant and go to its first operation.
  $keys = array_keys($plugin['operations']);
  $form_state['new trail'] = array('handlers', $handler->name, reset($keys));
}

/**
 * Form to enable a handler.
 */
function page_manager_handler_enable(&$form, &$form_state) {
  $form['markup'] = array(
    '#value' => t('This variant is currently disabled. Enabling it will make it available in your system. This will not take effect until you save this page.'),
  );
}

/**
 * Enable the page after it has been confirmed.
 */
function page_manager_handler_enable_submit(&$form, &$form_state) {
  $form_state['handler']->disabled = FALSE;
  $form_state['page']->handler_info[$form_state['handler_id']]['disabled'] = FALSE;
  $form_state['page']->handler_info[$form_state['handler_id']]['changed'] |= PAGE_MANAGER_CHANGED_STATUS;
  $form_state['new trail'] = array('handlers', $form_state['handler_id'], 'disable');
}

/**
 * Form to disable a page.
 */
function page_manager_handler_disable(&$form, &$form_state) {
  $form['markup'] = array(
    '#value' => t('This variant is currently enabled. Disabling it will make it unavailable in your system, and it will not be used. This will not take effect until you save this page.'),
  );
}

/**
 * Form to disable a page.
 */
function page_manager_handler_summary(&$form, &$form_state) {
  $handler = $form_state['handler'];
  $page = $form_state['page'];
  $plugin = page_manager_get_task_handler($handler->handler);

  $form['markup'] = array(
    '#value' => page_manager_get_handler_summary($plugin, $handler, $page->task, $page->subtask),
  );
}

/**
 * Disable the page after it has been confirmed.
 */
function page_manager_handler_disable_submit(&$form, &$form_state) {
  $form_state['handler']->disabled = TRUE;
  $form_state['page']->handler_info[$form_state['handler_id']]['disabled'] = TRUE;
  $form_state['page']->handler_info[$form_state['handler_id']]['changed'] |= PAGE_MANAGER_CHANGED_STATUS;
  $form_state['new trail'] = array('handlers', $form_state['handler_id'], 'enable');
}

/**
 * Break the lock on a page so that it can be edited.
 */
function page_manager_break_lock(&$form, &$form_state) {
  $form['markup'] = array(
    '#value' => t('Breaking the lock on this page will <strong>discard</strong> any pending changes made by the locking user. Are you REALLY sure you want to do this?')
  );
}

/**
 * Submit to break the lock on a page.
 */
function page_manager_break_lock_submit(&$form, &$form_state) {
  $page = &$form_state['page'];
  $form_state['page']->locked = FALSE;
  ctools_object_cache_clear_all('page_manager_page', $page->task_name);
  $form_state['do not cache'] = TRUE;
  drupal_set_message(t('The lock has been cleared and all changes discarded. You may now make changes to this page.'));
}

/**
 * Form to enable a page.
 */
function page_manager_enable_form(&$form, &$form_state) {
  $form['markup'] = array(
    '#value' => t('Enabling this page will immediately make it available in your system (there is no need to wait for a save.)'),
  );
}

/**
 * Enable the page after it has been confirmed.
 */
function page_manager_enable_form_submit(&$form, &$form_state) {
  $page = &$form_state['page'];
  if ($function = ctools_plugin_get_function($page->subtask, 'enable callback')) {
    $result = $function($page, FALSE);
    menu_rebuild();
  }
  $form_state['new trail'] = array('actions', 'disable');

  // We don't want to cause this to cache if it wasn't already. If it was 
  // cached, however, we want to update the enabled state.
  if (empty($form_state['page']->changed)) {
    $form_state['do not cache'] = TRUE;
  }
}

/**
 * Form to disable a page.
 */
function page_manager_disable_form(&$form, &$form_state) {
  $form['markup'] = array(
    '#value' => t('Disabling this page will immediately make it unavailable in your system (there is no need to wait for a save.)'),
  );
}

/**
 * Disable the page after it has been confirmed.
 */
function page_manager_disable_form_submit(&$form, &$form_state) {
  $page = &$form_state['page'];
  if ($function = ctools_plugin_get_function($page->subtask, 'enable callback')) {
    $result = $function($page, TRUE);
      menu_rebuild();
    $form_state['new trail'] = array('actions', 'enable');

    // We don't want to cause this to cache if it wasn't already. If it was 
    // cached, however, we want to update the enabled state.
    if (empty($form_state['page']->changed)) {
      $form_state['do not cache'] = TRUE;
    }
  }
}

/**
 * Print the summary information for a page.
 */
function page_manager_page_summary(&$form, &$form_state) {
  $page = $form_state['page'];

  $output = '';

  if (isset($form_state['subtask']['admin title'])) {
    $form_state['title'] = $form_state['subtask']['admin title'];
  }
  
  if (isset($form_state['subtask']['admin description'])) {
    $output .= '<div class="description">' . $form_state['subtask']['admin description'] . '</div>';
  }

  $output .= page_manager_get_page_summary($page->task, $page->subtask);

  if (!empty($page->handlers)) {
    foreach ($page->handler_info as $id => $info) {
      if ($info['changed'] & PAGE_MANAGER_CHANGED_DELETED) {
        continue;
      }

      $handler = $page->handlers[$id];
      $plugin = page_manager_get_task_handler($handler->handler);

      $output .= '<div class="handler-summary">';
      $output .= page_manager_get_handler_summary($plugin, $handler, $page->task, $page->subtask);
      $output .= '</div>';

    }
  }
  else {
    $output .= '<p>' . t('This page has no variants and thus no output of its own.') . '</p>';
  }

  $links = array(
    array(
      'title' => ' &raquo; ' . t('Add a new variant'),
      'href' => page_manager_edit_url($page->task_name, array('actions', 'add')),
      'html' => TRUE,
    ),
  );

  $output .= '<div class="links">' . theme('links', $links) . '</div>';
  $form['markup'] = array(
    '#value' => $output,
  );
}

/**
 * Menu callback to enable or disable a page
 */
function page_manager_enable_page($disable, $js, $page) {
  if ($page->locked) {
    if ($disable) {
      drupal_set_message(t('Unable to disable due to lock.'));
    }
    else {
      drupal_set_message(t('Unable to enable due to lock.'));
    }
  }
  else {
    if ($function = ctools_plugin_get_function($page->subtask, 'enable callback')) {
      $result = $function($page, $disable);
      menu_rebuild();

      // We want to re-cache this if it's changed so that status is properly
      // updated on the changed form.
      if (!empty($cache->changed)) {
        page_manager_set_page_cache($cache);
      }
    }
  }

  // For now $js is not actually in use on this.
  drupal_goto('admin/build/pages');
}