summaryrefslogtreecommitdiffstats
path: root/panels.module
blob: 9dc659b36160f39cc35964dd3b9467ed08ac8d89 (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
<?php
// $Id$

/**
 * @file panels.module
 *
 * Core functionality for the Panels engine.
 */

define('PANELS_REQUIRED_CTOOLS_API', '1.7.2');

define('PANELS_TITLE_FIXED', 0); // Hide title use to be true/false. So false remains old behavior.
define('PANELS_TITLE_NONE', 1); // And true meant no title.
define('PANELS_TITLE_PANE', 2); // And this is the new behavior, where the title field will pick from a pane.

/**
 * Returns the API version of Panels. This didn't exist in 1.
 *
 * @return An array with the major and minor versions
 */
function panels_api_version() {
  return array(3, 1);
}

// --------------------------------------------------------------------------
// Core Drupal hook implementations

/**
 * Implementation of hook_theme()
 */
function panels_theme() {
  // Safety: go away if CTools is not at an appropriate version.
  if (!module_invoke('ctools', 'api_version', PANELS_REQUIRED_CTOOLS_API)) {
    return array();
  }

  $theme = array();
  $theme['panels_layout_link'] = array(
    'arguments' => array('title', 'id', 'image', 'link'),
  );
  $theme['panels_layout_icon'] = array(
    'arguments' => array('id', 'image', 'title' => NULL),
  );
  $theme['panels_pane'] = array(
    'arguments' => array('output' => array(), 'pane' => array(), 'display' => array()),
    'path' => drupal_get_path('module', 'panels') . '/templates',
    'template' => 'panels-pane',
  );
  $theme['panels_common_content_list'] = array(
    'arguments' => array('display'),
    'file' => 'includes/common.inc',
  );
  $theme['panels_render_display_form'] = array(
    'arguments' => array('form' => NULL),
  );

  $theme['panels_dashboard'] = array(
    'arguments' => array(),
    'path' => drupal_get_path('module', 'panels') . '/templates',
    'file' => '../includes/callbacks.inc',
    'template' => 'panels-dashboard',
  );

  // Register layout and style themes on behalf of all of these items.
  ctools_include('plugins', 'panels');

  // No need to worry about files; the plugin has to already be loaded for us
  // to even know what the theme function is, so files will be auto included.
  $layouts = panels_get_layouts();
  foreach ($layouts as $name => $data) {
    foreach (array('theme', 'admin theme') as $callback) {
      if (!empty($data[$callback])) {
        $theme[$data[$callback]] = array(
          'arguments' => array('css_id' => NULL, 'content' => NULL, 'settings' => NULL, 'display' => NULL, 'layout' => NULL, 'renderer' => NULL),
          'path' => $data['path'],
          'file' => $data['file'],
        );

        // if no theme function exists, assume template.
        if (!function_exists("theme_$data[theme]")) {
          $theme[$data[$callback]]['template'] = str_replace('_', '-', $data[$callback]);
          $theme[$data[$callback]]['file'] = $data['file']; // for preprocess.
        }
      }
    }
  }

  $styles = panels_get_styles();
  foreach ($styles as $name => $data) {
    if (!empty($data['render pane'])) {
      $theme[$data['render pane']] = array(
        'arguments' => array('output' => NULL, 'pane' => NULL, 'display' => NULL, 'style' => NULL),
        'path' => $data['path'],
        'file' => $data['file'],
      );
    }
    // If we're in legacy mode, include the old callback key for legacy styles.
    if (variable_get('panels_legacy_rendering_mode', TRUE)) {
      if (!empty($data['render panel'])) {
        $theme[$data['render panel']] = array(
          'arguments' => array('display' => NULL, 'panel_id' => NULL, 'panes' => NULL, 'settings' => NULL, 'style' => NULL),
          'path' => $data['path'],
          'file' => $data['file'],
        );
      }
    }
    if (!empty($data['render region'])) {
      $theme[$data['render region']] = array(
        'arguments' => array('display' => NULL, 'region_id' => NULL, 'panes' => NULL, 'settings' => NULL, 'style' => NULL),
        'path' => $data['path'],
        'file' => $data['file'],
      );
    }

    if (!empty($data['hook theme'])) {
      if (is_array($data['hook theme'])) {
        $theme += $data['hook theme'];
      }
      else if (function_exists($data['hook theme'])) {
        $data['hook theme']($theme, $data);
      }
    }
  }

  return $theme;
}

/**
 * Implementation of hook_menu
 */
function panels_menu() {
  // Safety: go away if CTools is not at an appropriate version.
  if (!module_invoke('ctools', 'api_version', PANELS_REQUIRED_CTOOLS_API)) {
    return array();
  }
  $items = array();

  // Base AJAX router callback.
  $items['panels/ajax'] = array(
    'access arguments' => array('access content'),
    'page callback' => 'panels_ajax_router',
    'type' => MENU_CALLBACK,
  );

  $admin_base = array(
    'file' => 'includes/callbacks.inc',
    'access arguments' => array('use panels dashboard'),
  );
  // Provide a nice location for a panels admin panel.
  $items['admin/build/panels'] = array(
    'title' => 'Panels',
    'page callback' => 'panels_admin_page',
    'description' => 'Administer items related to the Panels module.',
  ) + $admin_base;

  $items['admin/build/panels/dashboard'] = array(
    'title' => 'Dashboard',
    'page callback' => 'panels_admin_page',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  ) + $admin_base;

  $items['admin/build/panels/settings'] = array(
    'title' => 'Settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('panels_admin_settings_page'),
    'type' => MENU_LOCAL_TASK,
  ) + $admin_base;

  $items['admin/build/panels/settings/general'] = array(
    'title' => 'General',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('panels_admin_settings_page'),
    'access arguments' => array('administer page manager'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  ) + $admin_base;

  if (module_exists('page_manager')) {
    $items['admin/build/panels/settings/panel-page'] = array(
      'title' => 'Panel pages',
      'page callback' => 'panels_admin_panel_context_page',
      'type' => MENU_LOCAL_TASK,
      'weight' => -10,
    ) + $admin_base;
  }

  ctools_include('plugins', 'panels');
  $layouts = panels_get_layouts();
  foreach ($layouts as $name => $data) {
    if (!empty($data['hook menu'])) {
      if (is_array($data['hook menu'])) {
        $items += $data['hook menu'];
      }
      else if (function_exists($data['hook menu'])) {
        $data['hook menu']($items, $data);
      }
    }
  }


  return $items;
}

/**
 * Menu loader function to load a cache item for Panels AJAX.
 *
 * This load all of the includes needed to perform AJAX, and loads the
 * cache object and makes sure it is valid.
 */
function panels_edit_cache_load($cache_key) {
  ctools_include('display-edit', 'panels');
  ctools_include('plugins', 'panels');
  ctools_include('ajax');
  ctools_include('modal');
  ctools_include('context');

  return panels_edit_cache_get($cache_key);
}

/**
 * Implementation of hook_init()
 */
function panels_init() {
  // Safety: go away if CTools is not at an appropriate version.
  if (!module_invoke('ctools', 'api_version', PANELS_REQUIRED_CTOOLS_API)) {
    if (user_access('administer site configuration')) {
      drupal_set_message(t('Panels is enabled but CTools is out of date. All Panels modules are disabled until CTools is updated. See the status page for more information.'), 'error');
    }
    return;
  }

  ctools_add_css('panels', 'panels');
  ctools_add_js('panels', 'panels');
}

/**
 * Implementation of hook_perm
 */
function panels_perm() {
  return array(
    'view all panes',
    'view pane admin links',
    'administer pane visibility',
    'administer pane access',
    'administer advanced pane settings',
    'administer panels layouts',
    'use panels caching features',
    'use panels dashboard',
    'use panels in place editing',
  );
}

/**
 * Implementation of hook_flush_caches().
 *
 * We implement this so that we can be sure our legacy rendering state setting
 * in $conf is updated whenever caches are cleared.
 */
function panels_flush_caches() {
  $legacy = panels_get_legacy_state();
  $legacy->determineStatus();
}

// ---------------------------------------------------------------------------
// CTools hook implementations
//
// These aren't core Drupal hooks but they are just as important.

/**
 * Implementation of hook_ctools_plugin_directory() to let the system know
 * we implement task and task_handler plugins.
 */
function panels_ctools_plugin_directory($module, $plugin) {
  // Safety: go away if CTools is not at an appropriate version.
  if (!module_invoke('ctools', 'api_version', PANELS_REQUIRED_CTOOLS_API)) {
    return;
  }
  if ($module == 'page_manager' || $module == 'panels' || $module == 'ctools') {
    return 'plugins/' . $plugin;
  }
}

/**
 * Inform CTools that the layout plugin can be loaded from themes.
 */
function panels_ctools_plugin_layouts() {
  return array(
    'load themes' => TRUE,
    'use hooks' => TRUE,
    'process' => 'panels_layout_process',
  );
}

/**
 * Ensure a layout has a minimal set of data.
 */
function panels_layout_process(&$plugin) {
  $plugin += array(
    'category' => t('Miscellaneous'),
    'description' => '',
  );
}

/**
 * Inform CTools that the style plugin can be loaded from themes.
 */
function panels_ctools_plugin_styles() {
  return array(
    'load themes' => TRUE,
    'use hooks' => TRUE,
    'process' => 'panels_plugin_styles_process',
  );
}

/**
 * Implementation of hook_ctools_plugin_api().
 *
 * Inform CTools about version information for various plugins implemented by
 * Panels.
 *
 * @param string $owner
 *   The system name of the module owning the API about which information is
 *   being requested.
 * @param string $api
 *   The name of the API about which information is being requested.
 */
function panels_ctools_plugin_api($owner, $api) {
  if ($owner == 'panels' && $api == 'styles') {
    // As of 6.x-3.6, Panels has a slightly new system for style plugins.
    return array('version' => 2.0);
  }

  if ($owner == 'panels' && $api == 'pipelines') {
    return array(
      'version' => 1,
      'path' => drupal_get_path('module', 'panels') . '/includes',
    );
  }
}

/**
 * Perform additional processing on a style plugin.
 *
 * Currently this is only being used to apply versioning information to style
 * plugins in order to ensure the legacy renderer passes the right type of
 * parameters to a style plugin in a hybrid environment of both new and old
 * plugins.
 *
 * @see _ctools_process_data()
 *
 * @param array $plugin
 *   The style plugin that is being processed.
 * @param array $info
 *   The style plugin type info array.
 */
function panels_plugin_styles_process(&$plugin, $info) {
  $plugin += array(
    'weight' => 0,
  );

  $compliant_modules = ctools_plugin_api_info('panels', 'styles', 2.0, 2.0);
  $plugin['version'] = empty($compliant_modules[$plugin['module']]) ? 1.0 : $compliant_modules[$plugin['module']]['version'];
}

/**
 * Declare what style types Panels uses.
 */
function panels_ctools_style_base_types() {
  return array(
    'region' => array(
      'title' => t('Panel region'),
      'preview' => 'panels_stylizer_region_preview',
      'theme arguments' => array('settings' => NULL, 'classes' => NULL, 'content' => NULL),
    ),
    'pane' => array(
      'title' => t('Panel pane'),
      'preview' => 'panels_stylizer_pane_preview',
      'theme arguments' => array('settings' => NULL, 'content' => NULL, 'pane' => NULL, 'display' => NULL),
    ),
  );
}

function panels_stylizer_lipsum() {
  return "
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus at velit dolor. Donec egestas tellus sit amet urna rhoncus adipiscing. Proin nec porttitor sem. Maecenas aliquam, purus nec tempus dignissim, nulla arcu aliquam diam, non tincidunt massa ante vel dolor. Aliquam sapien sapien, tincidunt id tristique at, pretium sagittis libero.</p>

    <p>Nulla facilisi. Curabitur lacinia, tellus sed tristique consequat, diam lorem scelerisque felis, at dictum purus augue facilisis lorem. Duis pharetra dignissim rutrum. Curabitur ac elit id dui dapibus tincidunt. Nulla eget sem quam, non eleifend eros. Cras porttitor tempus lectus ac scelerisque. Curabitur vehicula bibendum lorem, vitae ornare ligula venenatis ut.</p>
  ";
}

/**
 * Generate a preview given the current settings.
 */
function panels_stylizer_region_preview($plugin, $settings) {
  ctools_stylizer_add_css($plugin, $settings);
  return theme($plugin['theme'], $settings, ctools_stylizer_get_css_class($plugin, $settings), panels_stylizer_lipsum());
}

/**
 * Generate a preview given the current settings.
 */
function panels_stylizer_pane_preview($plugin, $settings) {
  ctools_stylizer_add_css($plugin, $settings);
  $pane = new stdClass();

  $content = new stdClass;
  $content->title = t('Lorem ipsum');
  $content->content = panels_stylizer_lipsum();
  $content->type = 'dummy';
  $content->subtype = 'dummy';

  $content->css_class = ctools_stylizer_get_css_class($plugin, $settings);

  $display = new panels_display();

  if (!empty($plugin['theme'])) {
    return theme($plugin['theme'], $settings, $content, $pane, $display);
  }
  else {
    return theme('panels_pane', $content, $pane, $display);
  }
}

// ---------------------------------------------------------------------------
// Panels display editing

/**
 * @defgroup mainapi Functions comprising the main panels API
 * @{
 */

/**
 * Main API entry point to edit a panel display.
 *
 * Sample implementations utiltizing the the complex $destination behavior can be found
 * in panels_page_edit_content() and, in a separate contrib module, OG Blueprints
 * (http://drupal.org/project/og_blueprints), og_blueprints_blueprint_edit().
 *
 * @ingroup mainapi
 *
 * @param object $display instanceof panels_display \n
 *  A fully loaded panels $display object, as returned from panels_load_display().
 *  Merely passing a did is NOT sufficient. \n
 *  Note that 'fully loaded' means the $display must already be loaded with any contexts
 *  the caller wishes to have set for the display.
 * @param mixed $destination \n
 *  The redirect destination that the user should be taken to on form submission or
 *  cancellation. With panels_edit, $destination has complex effects on the return
 *  values of panels_edit() once the form has been submitted. See the explanation of
 *  the return value below to understand the different types of values returned by panels_edit()
 *  at different stages of FAPI. Under most circumstances, simply passing in
 *  drupal_get_destination() is all that's necessary.
 * @param array $content_types \n
 *  An associative array of allowed content types, typically as returned from
 *  panels_common_get_allowed_types(). Note that context partially governs available content types,
 *  so you will want to create any relevant contexts using panels_create_context() or
 *  panels_create_context_empty() to make sure all the appropriate content types are available.
 *
 * @return
 *  Because the functions called by panels_edit() invoke the form API, this function
 *  returns different values depending on the stage of form submission we're at. In Drupal 5,
 *  the phase of form submission is indicated by the contents of $_POST['op']. Here's what you'll
 *  get at different stages:
 *    -# If !$_POST['op']: then we're on on the initial passthrough and the form is being
 *       rendered, so it's the $form itself that's being returned. Because negative margins,
 *       a common CSS technique, bork the display editor's ajax drag-and-drop, it's important
 *       that the $output be printed, not returned. Use this syntax in the caller function: \n
 *          print theme('page', panels_edit($display, $destination, $content_types), FALSE); \n
 *    -# If $_POST['op'] == t('Cancel'): form submission has been cancelled. If empty($destination) == FALSE,
 *       then there is no return value and the panels API takes care of redirecting to $destination.
 *       If empty($destination) == TRUE, then there's still no return value, but the caller function
 *       has to take care of form redirection.
 *    -# If $_POST['op'] == ('Save'): the form has been submitted successfully and has run through
 *        panels_edit_display_submit(). $output depends on the value of $destination:
 *      - If empty($destination) == TRUE: $output contains the modified $display
 *        object, and no redirection will occur. This option is useful if the caller
 *        needs to perform additional operations on or with the modified $display before
 *        the page request is complete. Using hook_form_alter() to add an additional submit
 *        handler is typically the preferred method for something like this, but there
 *        are certain use cases where that is infeasible and $destination = NULL should
 *        be used instead. If this method is employed, the caller will need to handle form
 *        redirection. Note that having $_REQUEST['destination'] set, whether via
 *        drupal_get_destination() or some other method, will NOT interfere with this
 *        functionality; consequently, you can use drupal_get_destination() to safely store
 *        your desired redirect in the caller function, then simply use drupal_goto() once
 *        panels_edit() has done its business.
 *      - If empty($destination) == FALSE: the form will redirect to the URL string
 *        given in $destination and NO value will be returned.
 */
function panels_edit($display, $destination = NULL, $content_types = NULL, $title = FALSE) {
  ctools_include('display-edit', 'panels');
  ctools_include('ajax');
  ctools_include('plugins', 'panels');
  return _panels_edit($display, $destination, $content_types, $title);
}

/**
 * API entry point for selecting a layout for a given display.
 *
 * Layout selection is nothing more than a list of radio items encompassing the available
 * layouts for this display, as defined by .inc files in the panels/layouts subdirectory.
 * The only real complexity occurs when a user attempts to change the layout of a display
 * that has some content in it.
 *
 * @param object $display instanceof panels_display \n
 *  A fully loaded panels $display object, as returned from panels_load_display().
 *  Merely passing a did is NOT sufficient.
 * @param string $finish
 *  A string that will be used for the text of the form submission button. If no value is provided,
 *  then the form submission button will default to t('Save').
 * @param mixed $destination
 *  Basic usage is a string containing the URL that the form should redirect to upon submission.
 *  For a discussion of advanced usages, see panels_edit().
 * @param mixed $allowed_layouts
 *  Allowed layouts has three different behaviors that depend on which of three value types
 *  are passed in by the caller:
 *    #- if $allowed_layouts instanceof panels_allowed_layouts (includes subclasses): the most
 *       complex use of the API. The caller is passing in a loaded panels_allowed_layouts object
 *       that the client module previously created and stored somewhere using a custom storage
 *       mechanism.
 *    #- if is_string($allowed_layouts): the string will be used in a call to variable_get() which
 *       will call the $allowed_layouts . '_allowed_layouts' var. If the data was stored properly
 *       in the system var, the $allowed_layouts object will be unserialized and recreated.
 *       @see panels_common_set_allowed_layouts()
 *    #- if is_null($allowed_layouts): the default behavior, which also provides backwards
 *       compatibility for implementations of the Panels2 API written before beta4. In this case,
 *       a dummy panels_allowed_layouts object is created which does not restrict any layouts.
 *       Subsequent behavior is indistinguishable from pre-beta4 behavior.
 *
 * @return
 *  Can return nothing, or a modified $display object, or a redirection string; return values for the
 *  panels_edit* family of functions are quite complex. See panels_edit() for detailed discussion.
 * @see panels_edit()
 */
function panels_edit_layout($display, $finish, $destination = NULL, $allowed_layouts = NULL) {
  ctools_include('display-layout', 'panels');
  ctools_include('plugins', 'panels');
  return _panels_edit_layout($display, $finish, $destination, $allowed_layouts);
}

// ---------------------------------------------------------------------------
// Panels database functions

/**
 * Forms the basis of a panel display
 *
 */
class panels_display {
  var $args = array();
  var $content = array();
  var $panels = array();
  var $incoming_content = NULL;
  var $css_id = NULL;
  var $context = array();
  var $did = 'new';
  var $renderer;

  function panels_display() {
    // Set the default renderer to either the legacy or the standard renderer,
    // depending on the legacy rendering state
    $this->renderer = variable_get('panels_legacy_rendering_mode', TRUE) ? 'legacy' : 'standard';
  }

  function add_pane(&$pane, $location = NULL) {
    // If no location specified, use what's set in the pane.
    if (empty($location)) {
      $location = $pane->panel;
    }
    else {
      $pane->panel = $location;
    }

    // Get a temporary pid for this pane.
    $pane->pid = "new-" . $this->next_new_pid();

    // Add the pane to the approprate spots.
    $this->content[$pane->pid] = &$pane;
    $this->panels[$location][] = $pane->pid;
  }

  function duplicate_pane($pid, $location = FALSE) {
    $pane = $this->clone_pane($pid);
    $this->add_pane($pane, $location);
  }

  function clone_pane($pid) {
    $pane = drupal_clone($this->content[$pid]);
    return $pane;
  }

  function next_new_pid() {
    // We don't use static vars to record the next new pid because
    // temporary pids can last for years in exports and in caching
    // during editing.
    $id = array(0);
    foreach (array_keys($this->content) as $pid) {
      if (!is_numeric($pid)) {
        $id[] = substr($pid, 4);
      }
    }
    $next_id = max($id);
    return ++$next_id;
  }

  /**
   * Get the title from a display.
   *
   * The display must have already been rendered, or the setting to set the
   * display's title from a pane's title will not have worked.
   *
   * @return
   *   The title to use. If NULL, this means to let any default title that may be in use
   *   pass through. i.e, do not actually set the title.
   */
  function get_title() {
    switch ($this->hide_title) {
      case PANELS_TITLE_NONE:
        return '';

      case PANELS_TITLE_PANE:
        return isset($this->stored_pane_title) ? $this->stored_pane_title : '';

      case PANELS_TITLE_FIXED:
      case FALSE; // For old exported panels that are not in the database.
        if (!empty($this->title)) {
          return filter_xss_admin(ctools_context_keyword_substitute($this->title, array(), $this->context));
        }
        return NULL;
    }
  }

  /**
   * Render this panels display.
   *
   * After checking to ensure the designated layout plugin is valid, a
   * display renderer object is spawned and runs its rendering logic.
   *
   * @param mixed $renderer
   *    An instantiated display renderer object, or the name of a display
   *    renderer plugin+class to be fetched. Defaults to NULL. When NULL, the
   *    predesignated display renderer will be used.
   */
  function render($renderer = NULL) {
    $layout = panels_get_layout($this->layout);
    if (!$layout) {
      return NULL;
    }

    // If we were not given a renderer object, load it.
    if (!is_object($renderer)) {
      // If the renderer was not specified, default to $this->renderer
      // which is either standard or was already set for us.
      $renderer = panels_get_renderer_handler(!empty($renderer) ? $renderer : $this->renderer, $this);
      if (!$renderer) {
        return NULL;
      }
    }

    $output = '';
    // Let modules act just prior to render.
    foreach (module_implements('panels_pre_render') as $module) {
      $function = $module . '_panels_pre_render';
      $output .= $function($display, $renderer);
    }

    $output .= $renderer->render();

    // Let modules act just after render.
    foreach (module_implements('panels_post_render') as $module) {
      $function = $module . '_panels_post_render';
      $output .= $function($display, $renderer);
    }
    return $output;
  }
}

/**
 * }@ End of 'defgroup mainapi', although other functions are specifically added later
 */

/**
 * Creates a new display, setting the ID to our magic new id.
 */
function panels_new_display() {
  ctools_include('export');
  $display = ctools_export_new_object('panels_display', FALSE);
  $display->did = 'new';
  return $display;
}

/**
 * Create a new pane.
 *
 * @todo -- use schema API for some of this?
 */
function panels_new_pane($type, $subtype, $set_defaults = FALSE) {
  ctools_include('export');
  $pane = ctools_export_new_object('panels_pane', FALSE);
  $pane->pid = 'new';
  $pane->type = $type;
  $pane->subtype = $subtype;
  if ($set_defaults) {
    $content_type = ctools_get_content_type($type);
    $content_subtype = ctools_content_get_subtype($content_type, $subtype);
    $pane->configuration = ctools_content_get_defaults($content_type, $content_subtype);
  }

  return $pane;
}

/**
 * Load and fill the requested $display object(s).
 *
 * Helper function primarily for for panels_load_display().
 *
 * @param array $dids
 *  An indexed array of dids to be loaded from the database.
 *
 * @return $displays
 *  An array of displays, keyed by their display dids.
 *
 * @todo schema API can drasticly simplify this code.
 */
function panels_load_displays($dids) {
  $displays = array();
  if (empty($dids) || !is_array($dids)) {
    return $displays;
  }

  $result = db_query("SELECT * FROM {panels_display} WHERE did IN (" .  db_placeholders($dids) . ")", $dids);

  ctools_include('export');
  while ($obj = db_fetch_object($result)) {
    $displays[$obj->did] = ctools_export_unpack_object('panels_display', $obj);
    // Modify the hide_title field to go from a bool to an int if necessary.
  }

  $result = db_query("SELECT * FROM {panels_pane} WHERE did IN (" . db_placeholders($dids) . ") ORDER BY did, panel, position", $dids);

  while ($obj = db_fetch_object($result)) {
    $pane = ctools_export_unpack_object('panels_pane', $obj);

    $displays[$pane->did]->panels[$pane->panel][] = $pane->pid;
    $displays[$pane->did]->content[$pane->pid] = $pane;
  }

  return $displays;
}

/**
 * Load a single display.
 *
 * @ingroup mainapi
 *
 * @param int $did
 *  The display id (did) of the display to be loaded.
 *
 * @return object $display instanceof panels_display \n
 *  Returns a partially-loaded panels_display object. $display objects returned from
 *  from this function have only the following data:
 *    - $display->did (the display id)
 *    - $display->name (the 'name' of the display, where applicable - it often isn't)
 *    - $display->layout (a string with the system name of the display's layout)
 *    - $display->panel_settings (custom layout style settings contained in an associative array; NULL if none)
 *    - $display->layout_settings (panel size and configuration settings for Flexible layouts; NULL if none)
 *    - $display->css_id (the special css_id that has been assigned to this display, if any; NULL if none)
 *    - $display->content (an array of pane objects, keyed by pane id (pid))
 *    - $display->panels (an associative array of panel regions, each an indexed array of pids in the order they appear in that region)
 *    - $display->cache (any relevant data from panels_simple_cache)
 *    - $display->args
 *    - $display->incoming_content
 *
 * While all of these members are defined, $display->context is NEVER defined in the returned $display;
 * it must be set using one of the ctools_context_create() functions.
 */
function panels_load_display($did) {
  $displays = panels_load_displays(array($did));
  if (!empty($displays)) {
    return array_shift($displays);
  }
}

/**
 * Save a display object.
 *
 * @ingroup mainapi
 *
 * Note a new $display only receives a real did once it is run through this function.
 * Until then, it uses a string placeholder, 'new', in place of a real did. The same
 * applies to all new panes (whether on a new $display or not); in addition,
 * panes have sequential numbers appended, of the form 'new-1', 'new-2', etc.
 *
 * @param object $display instanceof panels_display \n
 *  The display object to be saved. Passed by reference so the caller need not use
 *  the return value for any reason except convenience.
 *
 * @return object $display instanceof panels_display \n
 */
function panels_save_display(&$display) {
  $update = (isset($display->did) && is_numeric($display->did)) ? array('did') : array();
  drupal_write_record('panels_display', $display, $update);

  $pids = array();
  if ($update) {
    // Get a list of all panes currently in the database for this display so we can know if there
    // are panes that need to be deleted. (i.e, aren't currently in our list of panes).
    $result = db_query("SELECT pid FROM {panels_pane} WHERE did = %d", $display->did);
    while ($pane = db_fetch_object($result)) {
      $pids[$pane->pid] = $pane->pid;
    }
  }

  // update all the panes
  ctools_include('plugins', 'panels');
  ctools_include('content');

  foreach ($display->panels as $id => $panes) {
    $position = 0;
    $new_panes = array();
    foreach ((array) $panes as $pid) {
      if (!isset($display->content[$pid])) {
        continue;
      }
      $pane = $display->content[$pid];
      $type = ctools_get_content_type($pane->type);

      $pane->position = $position++;
      $pane->did = $display->did;

      $old_pid = $pane->pid;
      drupal_write_record('panels_pane', $pane, is_numeric($pid) ? array('pid') : array());

      if ($pane->pid != $old_pid) {
        // and put it back so our pids and positions can be used
        unset($display->content[$id]);
        $display->content[$pane->pid] = $pane;

        // If the title pane was one of our panes that just got its ID changed,
        // we need to change it in the database, too.
        if (isset($display->title_pane) && $display->title_pane == $old_pid) {
          $display->title_pane = $pane->pid;
          // Do a simple update query to write it so we don't have to rewrite
          // the whole record. We can't just save writing the whole record here
          // because it was needed to get the did. Chicken, egg, more chicken.
          db_query("UPDATE {panels_display} SET title_pane = %d WHERE did = %d", $pane->pid, $display->did);
        }
      }

      // re-add this to the list of content for this panel.
      $new_panes[] = $pane->pid;

      // Remove this from the list of panes scheduled for deletion.
      if (isset($pids[$pane->pid])) {
        unset($pids[$pane->pid]);
      }
    }

    $display->panels[$id] = $new_panes;
  }
  if (!empty($pids)) {
    db_query("DELETE FROM {panels_pane} WHERE pid IN (" . db_placeholders($pids) . ")", $pids);
  }

  // Clear any cached content for this display.
  panels_clear_cached_content($display);

  // Allow other modules to take action when a display is saved.
  module_invoke_all('panels_display_save', $display);

  // Log the change to watchdog, using the same style as node.module
  $watchdog_args = array('%did' => $display->did);
  if (!empty($display->title)) {
    $watchdog_args['%title'] = $display->title;
    watchdog('content', 'Panels: saved display "%title" with display id %did', $watchdog_args, WATCHDOG_NOTICE);
  }
  else {
    watchdog('content', 'Panels: saved display with id %did', $watchdog_args, WATCHDOG_NOTICE);
  }

  // to be nice, even tho we have a reference.
  return $display;
}

/**
 * Delete a display.
 */
function panels_delete_display($display) {
  if (is_object($display)) {
    $did = $display->did;
  }
  else {
    $did = $display;
  }
  db_query("DELETE FROM {panels_display} WHERE did = %d", $did);
  db_query("DELETE FROM {panels_pane} WHERE did = %d", $did);
}

/**
 * Exports the provided display into portable code.
 *
 * This function is primarily intended as a mechanism for cloning displays.
 * It generates an exact replica (in code) of the provided $display, with
 * the exception that it replaces all ids (dids and pids) with 'new-*' values.
 * Only once panels_save_display() is called on the code version of $display will
 * the exported display written to the database and permanently saved.
 *
 * @see panels_page_export() or _panels_page_fetch_display() for sample implementations.
 *
 * @ingroup mainapi
 *
 * @param object $display instanceof panels_display \n
 *  This export function does no loading of additional data about the provided
 *  display. Consequently, the caller should make sure that all the desired data
 *  has been loaded into the $display before calling this function.
 * @param string $prefix
 *  A string prefix that is prepended to each line of exported code. This is primarily
 *  used for prepending a double space when exporting so that the code indents and lines up nicely.
 *
 * @return string $output
 *  The passed-in $display expressed as code, ready to be imported. Import by running
 *  eval($output) in the caller function; doing so will create a new $display variable
 *  with all the exported values. Note that if you have already defined a $display variable in
 *  the same scope as where you eval(), your existing $display variable WILL be overwritten.
 */
function panels_export_display($display, $prefix = '') {
  ctools_include('export');
  $output = ctools_export_object('panels_display', $display, $prefix);

  // Initialize empty properties.
  $output .= $prefix . '$display->content = array()' . ";\n";
  $output .= $prefix . '$display->panels = array()' . ";\n";
  $panels = array();

  $title_pid = 0;
  if (!empty($display->content)) {
    $pid_counter = 0;
    $region_counters = array();
    foreach ($display->content as $pane) {
      $pid = 'new-' . ++$pid_counter;
      if ($pane->pid == $display->title_pane) {
        $title_pid = $pid;
      }
      $pane->pid = $pid;
      $output .= ctools_export_object('panels_pane', $pane, $prefix . '  ');
      $output .= "$prefix  " . '$display->content[\'' . $pane->pid . '\'] = $pane' . ";\n";
      if (!isset($region_counters[$pane->panel])) {
        $region_counters[$pane->panel] = 0;
      }
      $output .= "$prefix  " . '$display->panels[\'' . $pane->panel . '\'][' . $region_counters[$pane->panel]++ .'] = \'' . $pane->pid . "';\n";
    }
  }
  $output .= $prefix . '$display->hide_title = ';
  switch ($display->hide_title) {
    case PANELS_TITLE_FIXED:
      $output .= 'PANELS_TITLE_FIXED';
      break;
    case PANELS_TITLE_NONE:
      $output .= 'PANELS_TITLE_NONE';
      break;
    case PANELS_TITLE_PANE:
      $output .= 'PANELS_TITLE_PANE';
      break;
  }
  $output .= ";\n";

  $output .= $prefix . '$display->title_pane =' . " '$title_pid';\n";
  return $output;
}

/**
 * Render a display by loading the content into an appropriate
 * array and then passing through to panels_render_layout.
 *
 * if $incoming_content is NULL, default content will be applied. Use
 * an empty string to indicate no content.
 * @ingroup hook_invocations
 */
function panels_render_display(&$display, $renderer = NULL) {
  ctools_include('display-render', 'panels');
  ctools_include('plugins', 'panels');
  ctools_include('context');

  if (!empty($display->context)) {
    if ($form_context = ctools_context_get_form($display->context)) {
      $form_context->form['#theme'] = 'panels_render_display_form';
      $form_context->form['#display'] = &$display;
      $form_context->form['#form_context_id'] = $form_context->id;
      return drupal_render_form($form_context->form_id, $form_context->form);
    }
  }
  return $display->render($renderer);
}

/**
 * Theme function to render our panel as a form.
 *
 * When rendering a display as a form, the entire display needs to be
 * inside the <form> tag so that the form can be spread across the
 * panes. This sets up the form system to be the main caller and we
 * then operate as a theme function of the form.
 */
function theme_panels_render_display_form($form) {
  $form['#children'] = $form['#display']->render();
  drupal_render($form);
  return theme('form', $form);
}

// @layout
function panels_print_layout_icon($id, $layout, $title = NULL) {
  ctools_add_css('panels_admin', 'panels');
  $file = $layout['path'] . '/' . $layout['icon'];
  return theme('panels_layout_icon', $id, theme('image', $file, strip_tags($layout['title']), strip_tags($layout['description'])), $title);
}

/**
 * Theme the layout icon image
 * @layout
 * @todo move to theme.inc
 */
function theme_panels_layout_icon($id, $image, $title = NULL) {
  $output = '<div class="layout-icon">';
  $output .= $image;
  if ($title) {
    $output .= '<div class="caption">' . $title . '</div>';
  }
  $output .= '</div>';
  return $output;
}

/**
 * Theme the layout link image
 * @layout
 */
function theme_panels_layout_link($title, $id, $image, $link) {
  $output = '<div class="layout-link">';
  $output .= $image;
  $output .= '<div>' . $title . '</div>';
  $output .= '</div>';
  return $output;
}

/**
 * Print the layout link. Sends out to a theme function.
 * @layout
 */
function panels_print_layout_link($id, $layout, $link, $options = array()) {
  if (isset($options['query']['q'])) {
    unset($options['query']['q']);
  }

  ctools_add_css('panels_admin', 'panels');
  $file = $layout['path'] . '/' . $layout['icon'];
  $image = l(theme('image', $file), $link, array('html' => true) + $options);
  $title = l($layout['title'], $link, $options);
  return theme('panels_layout_link', $title, $id, $image, $link);
}


/**
 * Gateway to the PanelsLegacyState class/object, which does all legacy state
 * checks and provides information about the cause of legacy states as needed.
 *
 * @return PanelsLegacyState $legacy
 */
function panels_get_legacy_state() {
  static $legacy = NULL;
  if (!isset($legacy)) {
    ctools_include('legacy', 'panels');
    $legacy = new PanelsLegacyState();
  }
  return $legacy;
}

/**
 * Get the display that is currently being rendered as a page.
 *
 * Unlike in previous versions of this, this only returns the display,
 * not the page itself, because there are a number of different ways
 * to get to this point. It is hoped that the page data isn't needed
 * at this point. If it turns out there is, we will do something else to
 * get that functionality.
 */
function panels_get_current_page_display($change = NULL) {
  static $display = NULL;
  if ($change) {
    $display = $change;
  }

  return $display;
}

/**
 * Clean up the panel pane variables for the template.
 */
function template_preprocess_panels_pane($vars) {
  $content = $vars['output'];
  // basic classes
  $vars['classes'] = 'panel-pane';
  $vars['id'] = '';

  // Add some usable classes based on type/subtype
  ctools_include('cleanstring');
  $type_class = $content->type ? 'pane-'. ctools_cleanstring($content->type, array('lower case' => TRUE)) : '';
  $subtype_class = $content->subtype ? 'pane-'. ctools_cleanstring($content->subtype, array('lower case' => TRUE)) : '';

  // Sometimes type and subtype are the same. Avoid redudant classes.
  if ($type_class != $subtype_class) {
    $vars['classes'] .= " $type_class $subtype_class";
  }
  else {
    $vars['classes'] .= " $type_class";
  }

  // Add id and custom class if sent in.
  if (!empty($content->content)) {
    if (!empty($content->css_id)) {
      $vars['id'] = ' id="' . $content->css_id . '"';
    }
    if (!empty($content->css_class)) {
      $vars['classes'] .= ' ' . $content->css_class;
    }
  }

  // administrative links, only if there is permission.
  $vars['admin_links'] = '';
  if (user_access('view pane admin links') && !empty($content->admin_links)) {
    $vars['admin_links'] = theme('links', $content->admin_links);
  }

  $vars['title'] = !empty($content->title) ? $content->title : '';

  $vars['feeds'] = !empty($content->feeds) ? implode(' ', $content->feeds) : '';
  $vars['content'] = !empty($content->content) ? $content->content : '';

  $vars['links'] = !empty($content->links) ? theme('links', $content->links) : '';
  $vars['more'] = '';
  if (!empty($content->more)) {
    if (empty($content->more['title'])) {
      $content->more['title'] = t('more');
    }
    $vars['more'] = l($content->more['title'], $content->more['href'], $content->more);
  }
}

/**
 * Route Panels' AJAX calls to the correct object.
 *
 * Panels' AJAX is controlled mostly by renderer objects. This menu callback
 * accepts the incoming request, figures out which object should handle the
 * request, and attempts to route it. If no object can be found, the default
 * Panels editor object is used.
 *
 * Calls are routed via the ajax_* method space. For example, if visiting
 * panels/ajax/add-pane then $renderer::ajax_add_pane() will be called.
 * This means commands can be added without having to create new callbacks.
 *
 * The first argument *must always* be the cache key so that a cache object
 * can be passed through. Other arguments will be passed through untouched
 * so that the method can do whatever it needs to do.
 */
function panels_ajax_router() {
  $args = func_get_args();
  if (count($args) < 3) {
    return MENU_NOT_FOUND;
  }

  ctools_include('display-edit', 'panels');
  ctools_include('plugins', 'panels');
  ctools_include('ajax');
  ctools_include('modal');
  ctools_include('context');
  ctools_include('content');

  $plugin_name = array_shift($args);
  $method = array_shift($args);
  $cache_key = array_shift($args);

  $plugin = panels_get_display_renderer($plugin_name);
  if (!$plugin) {
    // This is the default renderer for handling AJAX commands.
    $plugin = panels_get_display_renderer('editor');
  }

  $cache = panels_edit_cache_get($cache_key);
  if (empty($cache)) {
    return MENU_ACCESS_DENIED;
  }

  $renderer = panels_get_renderer_handler($plugin, $cache->display);
  if (!$renderer) {
    return MENU_ACCESS_DENIED;
  }

  $method = 'ajax_' . str_replace('-', '_', $method);
  if (!method_exists($renderer, $method)) {
    return MENU_NOT_FOUND;
  }

  $renderer->cache = &$cache;
  ctools_include('cleanstring');
  $renderer->clean_key = ctools_cleanstring($cache_key);

  $output = call_user_func_array(array($renderer, $method), $args);
  if (empty($output) && !empty($renderer->commands)) {
    return ctools_ajax_render($renderer->commands);
  }
  return $output;
}

// --------------------------------------------------------------------------
// Panels caching functions and callbacks
//
// When editing displays and the like, Panels has a caching system that relies
// on a callback to determine where to get the actual cache.

// @todo This system needs to be better documented so that it can be
// better used.

/**
 * Get an object from cache.
 */
function panels_cache_get($obj, $did, $skip_cache = FALSE) {
  ctools_include('object-cache');
  // we often store contexts in cache, so let's just make sure we can load
  // them.
  ctools_include('context');
  return ctools_object_cache_get($obj, 'panels_display:' . $did, $skip_cache);
}

/**
 * Save the edited object into the cache.
 */
function panels_cache_set($obj, $did, $cache) {
  ctools_include('object-cache');
  return ctools_object_cache_set($obj, 'panels_display:' . $did, $cache);
}

/**
 * Clear a object from the cache; used if the editing is aborted.
 */
function panels_cache_clear($obj, $did) {
  ctools_include('object-cache');
  return ctools_object_cache_clear($obj, 'panels_display:' . $did);
}

/**
 * Create the default cache for editing panel displays.
 *
 * If an application is using the Panels display editor without having
 * specified a cache key, this method can be used to create the default
 * cache.
 */
function panels_edit_cache_get_default(&$display, $content_types = NULL, $title = FALSE) {
  if (empty($content_types)) {
    $content_types = ctools_content_get_available_types();
  }

  $display->cache_key = $display->did;
  panels_cache_clear('display', $display->did);

  $cache = new stdClass();
  $cache->display = &$display;
  $cache->content_types = $content_types;
  $cache->display_title = $title;

  panels_edit_cache_set($cache);
  return $cache;
}

/**
 * Method to allow modules to provide their own caching mechanism for the
 * display editor.
 */
function panels_edit_cache_get($cache_key) {
  if (strpos($cache_key, ':') !== FALSE) {
    list($module, $argument) = explode(':', $cache_key, 2);
    return module_invoke($module, 'panels_cache_get', $argument);
  }

  // Fall back to our normal method:
  return panels_cache_get('display', $cache_key);
}

/**
 * Method to allow modules to provide their own caching mechanism for the
 * display editor.
 */
function panels_edit_cache_set($cache) {
  $cache_key = $cache->display->cache_key;
  if (strpos($cache_key, ':') !== FALSE) {
    list($module, $argument) = explode(':', $cache_key, 2);
    return module_invoke($module, 'panels_cache_set', $argument, $cache);
  }

  // Fall back to our normal method:
  return panels_cache_set('display', $cache_key, $cache);
}

/**
 * Method to allow modules to provide their own mechanism to write the
 * cache used in the display editor.
 */
function panels_edit_cache_save($cache) {
  $cache_key = $cache->display->cache_key;
  if (strpos($cache_key, ':') !== FALSE) {
    list($module, $argument) = explode(':', $cache_key, 2);
    if (function_exists($module . '_panels_cache_save')) {
      return module_invoke($module, 'panels_cache_save', $argument, $cache);
    }
  }

  // Fall back to our normal method:
  return panels_save_display($cache->display);
}

/**
 * Method to allow modules to provide their own mechanism to clear the
 * cache used in the display editor.
 */
function panels_edit_cache_clear($cache) {
  $cache_key = $cache->display->cache_key;
  if (strpos($cache_key, ':') !== FALSE) {
    list($module, $argument) = explode(':', $cache_key, 2);
    if (function_exists($module . '_panels_cache_clear')) {
      return module_invoke($module, 'panels_cache_clear', $argument, $cache);
    }
  }

  // Fall back to our normal method:
  return panels_cache_clear('display', $cache_key);
}

/**
 * Method to allow modules to provide a mechanism to break locks.
 */
function panels_edit_cache_break_lock($cache) {
  if (empty($cache->locked)) {
    return;
  }

  $cache_key = $cache->display->cache_key;
  if (strpos($cache_key, ':') !== FALSE) {
    list($module, $argument) = explode(':', $cache_key, 2);
    if (function_exists($module . '_panels_cache_break_lock')) {
      return module_invoke($module, 'panels_cache_break_lock', $argument, $cache);
    }
  }

  // Normal panel display editing has no locks, so we do nothing if there is
  // no fallback.
  return;
}

// --------------------------------------------------------------------------
// Callbacks on behalf of the panel_context plugin.
//
// The panel_context plugin lets Panels be used in page manager. These
// callbacks allow the display editing system to use the page manager
// cache rather than the default display cache. They are routed by the cache
// key via panels_edit_cache_* functions.

/**
 * Get display edit cache on behalf of panel context.
 *
 * The key is the second half of the key in this form:
 * panel_context:TASK_NAME:HANDLER_NAME;
 */
function panel_context_panels_cache_get($key) {
  ctools_include('common', 'panels');
  ctools_include('context');
  ctools_include('context-task-handler');
  // this loads the panel context inc even if we don't use the plugin.
  $plugin = page_manager_get_task_handler('panel_context');

  list($task_name, $handler_name) = explode(':', $key, 2);
  $page = page_manager_get_page_cache($task_name);
  if (isset($page->display_cache[$handler_name])) {
    return $page->display_cache[$handler_name];
  }

  if ($handler_name) {
    $handler = &$page->handlers[$handler_name];
  }
  else {
    $handler = &$page->new_handler;
  }
  $cache = new stdClass();

  $cache->display = &panels_panel_context_get_display($handler);
  $cache->display->context = ctools_context_handler_get_all_contexts($page->task, $page->subtask, $handler);
  $cache->display->cache_key = 'panel_context:' . $key;
  $cache->content_types = panels_common_get_allowed_types('panels_page', $cache->display->context);
  $cache->display_title = TRUE;
  $cache->locked = $page->locked;

  return $cache;
}

/**
 * Get the Page Manager cache for the panel_context plugin.
 */
function _panel_context_panels_cache_get_page_cache($key, $cache) {
  list($task_name, $handler_name) = explode(':', $key, 2);
  $page = page_manager_get_page_cache($task_name);
  $page->display_cache[$handler_name] = $cache;
  if ($handler_name) {
    $page->handlers[$handler_name]->conf['display'] = $cache->display;
    $page->handler_info[$handler_name]['changed'] |= PAGE_MANAGER_CHANGED_CACHED;
  }
  else {
    $page->new_handler->conf['display'] = $cache->display;
  }

  return $page;
}

/**
 * Store a display edit in progress in the page cache.
 */
function panel_context_panels_cache_set($key, $cache) {
  $page = _panel_context_panels_cache_get_page_cache($key, $cache);
  page_manager_set_page_cache($page);
}

/**
 * Save all changes made to a display using the Page Manager page cache.
 */
function panel_context_panels_cache_clear($key, $cache) {
  $page = _panel_context_panels_cache_get_page_cache($key, $cache);
  page_manager_clear_page_cache($page->task_name);
}

/**
 * Save all changes made to a display using the Page Manager page cache.
 */
function panel_context_panels_cache_save($key, $cache) {
  $page = _panel_context_panels_cache_get_page_cache($key, $cache);
  page_manager_save_page_cache($page);
}

/**
 * Break the lock on a page manager page.
 */
function panel_context_panels_cache_break_lock($key, $cache) {
  $page = _panel_context_panels_cache_get_page_cache($key, $cache);
  ctools_object_cache_clear_all('page_manager_page', $page->task_name);
}

// --------------------------------------------------------------------------
// General utility functions

/**
 * Perform a drupal_goto on a destination that may be an array like url().
 */
function panels_goto($destination) {
  if (!is_array($destination)) {
    return drupal_goto($destination);
  }
  else {
    // Prevent notices by adding defaults
    $destination += array(
      'query' => NULL,
      'fragment' => NULL,
      'http_response_code' => NULL,
    );

    return drupal_goto($destination['path'], $destination['query'], $destination['fragment'], $destination['http_response_code']);
  }
}

// --------------------------------------------------------------------------
// Deprecated functions
//
// Everything below this line will eventually go away.

/**
 * Load a panels include file.
 *
 * @deprecated This function is deprecated and should no longer be used. It will
 * be removed in the next major version of Panels. Use ctools_include() instead.
 */
function panels_load_include($include, $path = 'includes/') {
  static $loaded = array();
  if (empty($loaded["$path$include.inc"])) {
    require_once './' . panels_get_path("$path$include.inc");
    $loaded["$path$include.inc"] = TRUE;
  }
}

/**
 * panels path helper function
 */
function panels_get_path($file, $base_path = FALSE, $module = 'panels') {
  $output = $base_path ? base_path() : '';
  return $output . drupal_get_path('module', $module) . '/' . $file;
}


/**
 * For external use: Given a layout ID and a $content array, return the
 * panel display. The content array is filled in based upon the content
 * available in the layout. If it's a two column with a content
 * array defined like array('left' => t('Left side'), 'right' =>
 * t('Right side')), then the $content array should be array('left' =>
 * $output_left, 'right' => $output_right)
 *
 * @deprecated This function represents an old approach to rendering, and is
 * retained only as a temporary support for other modules still using that
 * approach. It will be removed in the next major version of Panels.
 */
function panels_print_layout($id, $content) {
  ctools_include('display-render', 'panels');
  ctools_include('plugins', 'panels');
  $layout = panels_get_layout($id);
  if (!$layout) {
    return;
  }

  return panels_render_layout($layout, $content);
}

/**
 * Get a list of panel regions available in the layout.
 *
 * @deprecated Use panels_get_regions instead.
 */
function panels_get_panels($layout, $display) {
  return panels_get_regions($layout, $display);
}


/**
 * Select a context for a pane.
 *
 * @param $pane
 *   A fully populated pane.
 * @param $contexts
 *   A keyed array of available contexts.
 *
 * @return
 *   The matching contexts or NULL if none or necessary, or FALSE if
 *   requirements can't be met.
 *
 * @deprecated this function will be removed.
 */
function panels_pane_select_context($pane, $contexts) {
  return ctools_content_select_context($pane->type, $pane->subtype, $pane->configuration, $contexts);
}