summaryrefslogtreecommitdiffstats
path: root/panels_page/panels_page.admin.inc
blob: 61a57c56b1a7d53f0a047b020df33c4ec3cb92fe (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
<?php
// $Id$


/**
 * @file panels_page.admin.inc
 *
 * Administrative screens and functions for panel pages.
 */

/**
 * Provide a list of panels, with links to edit or delete them.
 *
 * TODO Since we've already got the views dependency, should we just do this as
 * a view?
 */
function panels_page_list_page() {
  panels_page_load_include('read');
  panels_load_include('plugins');
  $layouts = panels_get_layouts();
  $items = array();
  $sorts = array();

  $header = array(
    array('data' => t('Page title'), 'field' => 'title'),
    array('data' => t('Name'), 'field' => 'name', 'sort' => 'asc'),
    array('data' => t('Type'), 'field' => 'type'),
    t('Layout'),
    array('data' => t('URL'), 'field' => 'url'),
    t('Operations'),
  );

  // Load all panel pages and their primary displays.
  $panel_pages = panels_page_load_all();
  $dids = array();
  foreach ($panel_pages as $panel_page) {
    if (empty($panel_page->display)) {
      $dids[] = $panel_page->did;
    }
  }
  $displays = panels_load_displays($dids);

  foreach ($panel_pages as $panel_page) {
    $ops = array();
    if (empty($panel_page->disabled)) {
      $ops[] = l(t('Edit'), "admin/panels/panel-page/$panel_page->name/edit");
      $ops[] = l(t('Export'), "admin/panels/panel-page/$panel_page->name/edit/export");
    }
    if ($panel_page->type != t('Default')) {
      $text = $panel_page->type == t('Overridden') ? t('Revert') : t('Delete');
      $ops[] = l($text, "admin/panels/panel-page/$panel_page->name/delete");
    }
    else {
      if (empty($panel_page->disabled)) {
        $ops[] = l(t('Disable'), "admin/panels/panel-page/disable/$panel_page->name", array('query' => drupal_get_destination()));
      }
      else {
        $ops[] = l(t('Enable'), "admin/panels/panel-page/enable/$panel_page->name", array('query' => drupal_get_destination()));
      }
    }

    $path = empty($panel_page->disabled) && strpos($panel_page->path, '%') === FALSE ? l($panel_page->path, $panel_page->path) : check_plain($panel_page->path);
    $item = array();
    $item[] = check_plain(panels_page_get_title($panel_page));
    $item[] = check_plain($panel_page->name);
    // this is safe as it's always programmatic
    $item[] = $panel_page->type;

    if (empty($panel_page->display)) {
      $panel_page->display = $displays[$panel_page->did];
    }
    $item[] = check_plain($layouts[$panel_page->display->layout]['title']);
    $item[] = $path;
    $item[] = implode(' | ', $ops);
    $items[] = $item;
    $ts = tablesort_init($header);
    switch ($ts['sql']) {
      case 'title':
        $sorts[] = $item[0];
        break;

      case 'name':
      default:
        $sorts[] = $item[1];
        break;

      case 'type':
        $sorts[] = $panel_page->type . $item[0];
        break;

      case 'url':
        $sorts[] = $panel_page->path;
        break;
    }
  }

  if (!empty($ts['sort']) && drupal_strtolower($ts['sort']) == 'desc') {
    arsort($sorts);
  }
  else {
    asort($sorts);
  }

  $i = array();
  foreach ($sorts as $id => $title) {
    $i[] = $items[$id];
  }

  $output = theme('table', $header, $i);
  return $output;
}

/**
 * General settings configuration page for panel pages.
 */
function panels_page_settings() {
  panels_load_include('common');
  return drupal_get_form('panels_common_settings', 'panels_page');
}

/**
 * Enable a default panel_page.
 */
function panels_page_enable_page($name = NULL) {
  $defaults = panels_page_default_panels();
  if (isset($defaults[$name])) {
    $status = variable_get('panel_page_defaults', array());
    $status[$name] = FALSE;
    variable_set('panel_page_defaults', $status);
    menu_rebuild();
    drupal_set_message(t('Panel page enabled'));
  }
  drupal_goto();
}

/**
 * Disable a default panel_page.
 */
function panels_page_disable_page($name = NULL) {
  $defaults = panels_page_default_panels();
  if (isset($defaults[$name])) {
    $status = variable_get('panel_page_defaults', array());
    $status[$name] = TRUE;
    variable_set('panel_page_defaults', $status);
    drupal_set_message(t('Panel page disabled'));
    menu_rebuild();
  }
  drupal_goto();
}

/**
 * Provide a form to confirm deletion of a panel page.
 */
function panels_page_delete_confirm(&$form_state, $panel_page) {
  $form_state['panel_page'] = $panel_page;
  if ($panel_page->type != t('Overridden')) {
    return confirm_form($form,
      t('Are you sure you want to delete "@title"?', array('@title' => panels_page_get_title($panel_page))),
      $_GET['destination'] ? $_GET['destination'] : 'admin/panels/panel-page',
      t('This action cannot be undone.'),
      t('Delete'), t('Cancel')
    );
  }
  else {
    return confirm_form($form,
      t('Are you sure you want to revert "@title" to its default configuration?', array('@title' => panels_page_get_title($panel_page))),
      $_GET['destination'] ? $_GET['destination'] : 'admin/panels/panel-page',
      t('This action cannot be undone.'),
      t('Revert'), t('Cancel')
    );
  }
}

/**
 * Handle the submit button to delete a panel page.
 */
function panels_page_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    panels_page_delete($form_state['panel_page']);
    $form_state['redirect'] = 'admin/panels/panel-page';
  }
}

/**
 * Handle the add panel-page page.
 */
function panels_page_add_handler($layout = NULL) {
  drupal_set_title(t('Add panel page'));
  panels_load_include('plugins');

  $layouts = panels_get_layouts();
  $output = '';

  // If no page layout is given, choose one first.
  if ($layout === NULL) {
    foreach ($layouts as $id => $layout) {
      $output .= panels_print_layout_link($id, $layout, $_GET['q'] . '/' . $id);
    }
    return $output;
  }

  $panel_page = new stdClass();
  $panel_page->primary = panels_new_display();
  $panel_page->primary->layout = $layout;
  $panel_page->display = &$panel_page->primary;

  $panel_page->pid = 'new';
  $panel_page->did = 'new';
  $panel_page->name = '';
  $panel_page->title = '';
  $panel_page->css_id = '';
  $panel_page->path = '';

  return drupal_get_form('panels_page_edit_form', panels_page_sanitize($panel_page));
}

/**
 * Edit a panel page.
 *
 * Called from both the add and edit points to provide for common flow.
 */
function panels_page_edit($panel_page, $next = NULL) {
  drupal_set_title(check_plain(panels_page_get_title($panel_page)));
  return drupal_get_form('panels_page_edit_form', $panel_page, $next);
  /*
  $form_state = array(
    'panel_page' => $panel_page,
    'pid' => $panel_page->pid,
    'next' => $next,
  );
  $output = drupal_build_form('panels_page_edit_form', $form_state);
  // no output == submit
  if (!$output) {
    if (!empty($form_state['clicked_button']['#save-display'])) {
      drupal_set_message(t('Panel content has been updated.'));
      panels_save_display($display);
    }
    else {
      drupal_set_message(t('Your changes have been discarded.'));
    }

    panels_cache_clear('display', $display->did);
    if ($destination) {
      return drupal_goto($destination);
    }
    return $form_state['display'];
  }

  return $output;*/
}

/**
 * The form to edit the page portion of a panel.
 */
function panels_page_edit_form(&$form_state, &$panel_page, $next = NULL) {
  panels_load_include('common');
  drupal_add_css(panels_get_path('css/panels_admin.css'));
  $layout = panels_get_layout($panel_page->display->layout);

  $form_state['panel_page'] = &$panel_page;
  $form_state['pid']        = $panel_page->pid;
  $form_state['next']       = $next;

  $form['right'] = array(
    '#prefix' => '<div class="layout-container">',
    '#suffix' => '</div>',
  );

  $form['left'] = array(
    '#prefix' => '<div class="panel-page-info-container">',
    '#suffix' => '</div>',
  );

  $form['left']['info'] = array(
    '#type' => 'fieldset',
    '#title' => t('Page settings'),
  );

  $form['right']['layout'] = array(
    '#type' => 'fieldset',
    '#title' => t('Layout'),
  );

  $form['right']['layout']['layout-icon'] = array(
    '#value' => panels_print_layout_icon($panel_page->display->layout, $layout),
  );

  $form['right']['layout']['layout-display'] = array(
    '#value' => check_plain($layout['title']),
  );

  $panel_page->context = $panel_page->display->context = panels_context_load_contexts($panel_page);

  $form['right']['layout']['layout-content'] = array(
    '#value' => theme('panels_common_content_list', $panel_page->display), //$content,
  );

  $contexts = theme('panels_common_context_list', $panel_page);
  if ($contexts) {
    $form['right']['context'] = array(
      '#type' => 'fieldset',
      '#title' => t('Contexts'),
    );

    $form['right']['context']['context'] = array(
      '#value' => $contexts,
    );
  }

  $form['left']['info']['name'] = array(
    '#type' => 'textfield',
    '#size' => 35,
    '#default_value' => $panel_page->name,
    '#title' => t('Panel name'),
    '#description' => t('A unique name used to identify this panel page internally. It must be only be alpha characters and underscores. No spaces, numbers or uppercase characters.'),
    '#required' => TRUE,
  );

  $form['left']['info']['title'] = array(
    '#type' => 'textfield',
    '#size' => 35,
    '#default_value' => $panel_page->title,
    '#title' => t('Page title'),
    '#description' => t("The page title for this panels layout. It will be used as the main title on this panel page, unless it is overriden later."),
  );

  $form['left']['info']['css_id'] = array(
    '#type' => 'textfield',
    '#size' => 35,
    '#default_value' => $panel_page->css_id,
    '#title' => t('CSS ID'),
    '#description' => t('The CSS ID to apply to this page'),
  );

  $form['left']['info']['path'] = array(
    '#type' => 'textfield',
    '#size' => 35,
    '#default_value' => $panel_page->path,
    '#title' => t('Path'),
    '#description' => t('The URL path to give this page, i.e, path/to/page. You may use "%" as an argument placeholder: i.e, node/%/panel'),
    '#required' => TRUE,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $panel_page->pid == 'new' ? t('Save and proceed') : t('Save'),
  );

  return $form;
}

/**
 * Validate a panel page edit form.
 */
function panels_page_edit_form_validate($form, &$form_state) {
  // Validate the system name; check for its presence, pass it through a preg
  // filter for allowed characters, and test for uniqueness.
  if (!$form_state['values']['name']) {
    form_error($form['left']['info']['name'], t('Panel name is required.'));
  }
  else if (preg_match("/[^A-Za-z0-9_]/", $form_state['values']['name'])) {
    form_error($form['left']['info']['name'], t('Panel name must be alphanumeric or underscores only.'));
  }
  else {
    if (db_result(db_query("SELECT pid FROM {panels_page} WHERE name = '%s' AND pid <> %d", $form_state['values']['name'], $form_state['pid']))) {
      form_error($form['left']['info']['name'], t('Panel name must be unique.'));
    }
  }

  // Validate the path; check for its presence, uniqueness within panels_page,
  // and uniqueness with respect to path aliases.
  if (!$form_state['values']['path']) {
    form_error($form['left']['info']['path'], t('Path is required.'));
  }
  else {
    if ($result = db_result(db_query("SELECT name FROM {panels_page} WHERE path = '%s' AND pid <> %d", $form_state['values']['path'], $form_state['pid']))) {
      form_error($form['left']['info']['path'], t("'Path' must be unique among Panels Page paths. The path '@path' is currently in owned by '@name'.",
        array('@path' => $form_state['values']['path'], '@name' => $result)));
    }
    if (db_result(db_query("SELECT src FROM {url_alias} WHERE dst = '%s'", $form_state['values']['path']))) {
      form_error($form['left']['info']['path'], t('The path you have chosen is already aliased to @src.', array('@src' => $result)));
    }
  }
}

/**
 * Process submission of the panel page edit form
 */
function panels_page_edit_form_submit($form, &$form_state) {
  $panel_page = $form_state['panel_page'];

  $panel_page->title  = $form_state['values']['title'];
  $panel_page->name   = preg_replace("/[\W]+/", '', $form_state['values']['name']);
  $panel_page->css_id = $form_state['values']['css_id'];
  $panel_page->path   = $form_state['values']['path'];

  if ($panel_page->pid == 'new') {
    unset($_SESSION['pp_import']);
    drupal_set_message(t('Your new panel page %title has been saved.', array('%title' => $panel_page->title)));
    panels_page_load_include('write');
    panels_page_save($panel_page);
    $form_state['values']['pid'] = $panel_page->pid;
    $layout = panels_get_layout($panel_page->display->layout);

    if (!empty($layout['settings form'])) {
      $form_state['redirect'] =  "admin/panels/panel-page/$panel_page->name/edit/settings/next";
    }
    else {
      $form_state['redirect'] = "admin/panels/panel-page/$panel_page->name/edit/advanced/next";
    }
    return;
  }
  else {
    drupal_set_message(t('Your changes have been saved.'));
    panels_page_load_include('write');
    panels_page_save($panel_page);
  }
  // The path may have changed - rebuild the menu.
  menu_rebuild();
}

/**
 * Edit advanced settings of a panel page.
 */
function panels_page_edit_advanced($panel_page, $next = NULL) {
  drupal_set_title(check_plain(panels_page_get_title($panel_page)));
  return drupal_get_form('panels_page_advanced_form', $panel_page, $next);
}

/**
 * The form to edit the advanced settings of a panel page.
 */
function panels_page_advanced_form(&$form_state, $panel_page, $next) {
  drupal_add_css(panels_get_path('css/panels_admin.css'));
  $form_state['panel_page'] = &$panel_page;
  $form_state['next'] = $next;

  $form['right'] = array(
    '#prefix' => '<div class="right-container">',
    '#suffix' => '</div>',
  );

  $form['left'] = array(
    '#prefix' => '<div class="left-container">',
    '#suffix' => '</div>',
  );

  $form['right']['advanced'] = array(
    '#type' => 'fieldset',
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
    '#title' => t('Advanced settings'),
  );

  $form['right']['advanced']['no_blocks'] = array(
    '#type' => 'checkbox',
    '#default_value' => $panel_page->no_blocks,
    '#title' => t('Disable Drupal blocks/regions'),
    '#description' => t('Check this to have the panel page disable all regions displayed in the theme.'),
  );

  $rids = array();
  $result = db_query("SELECT r.rid, r.name FROM {role} r ORDER BY r.name");
  while ($obj = db_fetch_object($result)) {
    $rids[$obj->rid] = $obj->name;
  }

  $form['right']['advanced']['access'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Access'),
    '#default_value' => $panel_page->access,
    '#options' => $rids,
    '#description' => t('Only the checked roles will be able to see this panel in any form; if no roles are checked, access will not be restricted.'),
  );

  $form['right']['advanced']['css'] = array(
    '#type' => 'textarea',
    '#title' => t('CSS code'),
    '#description' => t('Enter well-formed CSS code here; this code will be embedded into the page, and should only be used for minor adjustments; it is usually better to try to put CSS for the page into the theme if possible.'),
    '#default_value' => $panel_page->css,
  );

  $form['left']['menu-info'] = array(
    '#type' => 'fieldset',
    '#collapsible' => FALSE,
    '#title' => t('Menu'),
  );

  $form['left']['menu-info']['menu'] = array(
    '#type' => 'checkbox',
    '#title' => t('Provide Menu'),
    '#return_value' => 1,
    '#default_value' => $panel_page->menu,
    '#description' => t('If checked this panel be given a menu entry in the Drupal menu system. If not checked the data in this group will be ignored.'),
  );

  $form['left']['menu-info']['menu_tab'] = array(
    '#type' => 'checkbox',
    '#title' => t('Provide Menu as Tab'),
    '#return_value' => 1,
    '#default_value' => $panel_page->menu_tab,
    '#description' => t("If checked this panel's menu entry will be provided as a tab rather than in the main menu system."),
  );

  $form['left']['menu-info']['menu_tab_weight'] = array(
    '#type' => 'textfield',
    '#title' => t('Tab Weight'),
    '#default_value' => $panel_page->menu_tab_weight,
    '#size' => 5,
    '#description' => t('If this is a menu tab, select the weight; lower numbers will be further to the left.'),
  );

  $form['left']['menu-info']['menu_title'] = array(
    '#type' => 'textfield',
    '#title' => t('Menu Title'),
    '#default_value' => $panel_page->menu_title,
    '#size' => 35,
    '#maxlength' => 255,
    '#description' => t('Enter the title to use for the menu entry or tab. If blank, the page title will be used.'),
  );

  $form['left']['menu-info']['default-tab'] = array(
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#title' => t('Default Menu Tab'),
  );

  $form['left']['menu-info']['default-tab']['menu_tab_default'] = array(
    '#type' => 'checkbox',
    '#title' => t('Make Default Menu Tab'),
    '#return_value' => 1,
    '#default_value' => $panel_page->menu_tab_default,
    '#description' => t("If checked this panel's menu entry will be provided as a tab, and will be the default tab for that URL path. For example, if the URL is 'tracker/all' and it is set as the default menu tab, it will be put into the menu as 'tracker' and 'tracker/all' will be the default tab. The following settings allow you to customize the parent item, for example 'tracker'. For tabs to work properly, one tab in the group must be set as the default."),
  );

  $form['left']['menu-info']['default-tab']['menu_tab_default_parent_type'] = array(
    '#type' => 'select',
    '#title' => t('Parent Menu Item Type'),
    '#default_value' => $panel_page->menu_tab_default_parent_type,
    '#options' => array(
      'tab' => t("Tab"),
      'normal' => t("Normal menu item"),
      'existing' => t("Already exists (don't create)"),
    ),
    '#description' => t("Select type of parent item to use for this default menu tab. You can either specify the parent should be a tab (the default), a normal menu item, or to use the menu item that already exists at the specified URL. For example, if the URL for the default tab is 'tracker/all', then 'tracker' would already have to be a valid menu item to use this final choice."),
  );

  $form['left']['menu-info']['default-tab']['menu_parent_tab_weight'] = array(
    '#type' => 'textfield',
    '#title' => t('Tab Weight'),
    '#disabled' => TRUE,
    '#default_value' => $panel_page->menu_parent_tab_weight,
    '#size' => 5,
    '#description' => t('If the parent menu item is a tab, select the weight; lower numbers will be further to the left. <b>DISABLED IN D6 ALPHA</b>'),
  );

  $form['left']['menu-info']['default-tab']['menu_parent_title'] = array(
    '#type' => 'textfield',
    '#title' => t('Parent Menu Item Title'),
    '#disabled' => TRUE,
    '#default_value' => $panel_page->menu_parent_title,
    '#size' => 35,
    '#maxlength' => 255,
    '#description' => t('If the Parent Menu Item is being defined by this panel (if you set the %type_field to either %tab or %menu), you can specify its title here.  If blank, the menu title will be used if that is defined, or the page title if not. <b>DISABLED IN D6 ALPHA</b>', array('%type_field' => t('Parent Menu Item Type'), '%tab' => t('Tab'), '%menu' => t('Normal menu item'))),
  );

  $label = ($next) ? t('Save and proceed') : t('Save');
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $label,
  );

  return $form;
}

/**
 * Process submission of the panel page edit form.
 */
function panels_page_advanced_form_submit($form, &$form_state) {
  $panel_page = $form_state['panel_page'];

  $panel_page->css                          = $form_state['values']['css'];
  $panel_page->no_blocks                    = $form_state['values']['no_blocks'];
  $panel_page->menu                         = $form_state['values']['menu'];
  $panel_page->menu_tab                     = $form_state['values']['menu_tab'];
  $panel_page->menu_tab_weight              = $form_state['values']['menu_tab_weight'];
  $panel_page->menu_title                   = $form_state['values']['menu_title'];
  $panel_page->menu_tab_default             = $form_state['values']['menu_tab_default'];
  $panel_page->menu_tab_default_parent_type = $form_state['values']['menu_tab_default_parent_type'];
  $panel_page->menu_parent_title            = $form_state['values']['menu_parent_title'];
  $panel_page->menu_parent_tab_weight       = $form_state['values']['menu_parent_tab_weight'];

  $panel_page->access = array_keys(array_filter($form_state['values']['access']));

  panels_page_load_include('write');
  panels_page_save($panel_page);
  if ($form_state['next']) {
    $form_state['redirect'] = "admin/panels/panel-page/$panel_page->name/edit/context/next";
  }
  drupal_set_message(t('Your changes have been saved.'));
}

/**
 * Edit advanced settings of a panel page.
 */
function panels_page_edit_context($panel_page, $next = NULL) {
  drupal_set_title(check_plain(panels_page_get_title($panel_page)));
  if (!empty($_POST)) {
    $panel_page = panels_cache_get('panel_object:panel_page', $panel_page->name);
  }
  else {
    panels_cache_set('panel_object:panel_page', $panel_page->name, $panel_page);
  }

  // drupal_set_title(check_plain(panels_page_get_title($panel_page)));
  return drupal_get_form('panels_page_context_form', $panel_page, $next);
}

/**
 * The form to edit the context settings of a panel page.
 */
function panels_page_context_form(&$form_state, $panel_page, $next) {
  panels_load_include('plugins');
  $form_state['panel_page'] = $panel_page;
  $form_state['next'] = $next;

  drupal_add_css(panels_get_path('css/panels_admin.css'));
  $layout = panels_get_layout($panel_page->display->layout);

  $form['right'] = array(
    '#prefix' => '<div class="right-container">',
    '#suffix' => '</div>',
  );

  $form['left'] = array(
    '#prefix' => '<div class="left-container">',
    '#suffix' => '</div>',
  );

  panels_load_include('common-context');
  panels_load_include('ajax');

  $settings = panels_common_add_argument_form('panel_page', $form, $form_state, $form['left']['arguments_table'], $panel_page);
  $settings += panels_common_add_context_form('panel_page', $form, $form_state, $form['right']['contexts_table'], $panel_page);
  $settings += panels_common_add_relationship_form('panel_page', $form, $form_state, $form['left']['relationships_table'], $panel_page);
  panels_common_add_context_js($settings);

  $label = ($next) ? t('Save and proceed') : t('Save');
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $label,
  );

  return $form;
}

/**
 * Process submission of the panel page edit form.
 */
function panels_page_context_form_submit($form, &$form_state) {
  $panel_page = $form_state['panel_page'];

  // Organize these from the common form.
  panels_common_save_context('argument', $panel_page->arguments, $form_state['values']);

  // Match up our displays, carry them forward and add new ones.
  $old_displays = $panel_page->displays;
  $panel_page->displays = array();

  foreach ($panel_page->arguments as $id => $argument) {
    $def = panels_get_argument($argument['name']);
    if (function_exists($def['displays'])) {
      // Figure out which instance of this particular argument type we're using.

      $displays = $def['displays']($argument['argument_settings'], $argument['id']);
      foreach ($displays as $did => $info) {
        $pdid = "argument_$id" . '-' . $did;
        if (isset($old_displays[$pdid])) {
          $panel_page->displays[$pdid] = $old_displays[$pdid];
          unset($old_displays[$pdid]);
          // ensure titles get updated if necessary
          $panel_page->displays[$pdid]['title'] = $info['title'];
        }
        else {
          $panel_page->displays[$pdid] = array(
            'did' => 'new',
            'title' => $info['title'],
            'default' => "argument_$id" . '-' . $info['default'],
            'argument_id' => $id,
            'context' => $info['context'],
          );
        }
      }
    }
  }

  // Remove remaining old displays.
  foreach ($old_displays as $id => $info) {
    if (is_numeric($info['did'])) {
      panels_delete_display($info['did']);
      drupal_set_message(t('Removed unused display @title', $info['title']));
    }
  }

  drupal_set_message(t('Your changes have been saved.'));

  panels_page_load_include('write');
  panels_page_save($panel_page);
  panels_cache_clear('panel_object:panel_page', $panel_page->name);
  if ($form_state['next']) {
    $form_state['redirect'] = "admin/panels/panel-page/$panel_page->name/edit/content";
  }
}

/**
 * Pass through to the panels layout editor.
 */
function panels_page_edit_layout($panel_page) {
  // The following form will return the $display upon successful submit, if
  // we didn't send the $dest. Which we don't, here. That way we can update
  // our panel_page if necessary and do our own goto.
  $output = panels_edit_layout($panel_page->display, t('Save'));
  if (is_object($output)) {
    $panel_page->display = $output;
    panels_page_save_display($panel_page);

    $dest = "admin/panels/panel-page/edit/$panel_page->name/layout";
    if ($panel_page->display->did != $panel_page->did) {
      $dest .= '/' . $panel_page->display->did;
    }
    drupal_goto($dest);
  }

  drupal_set_title(check_plain(panels_page_get_title($panel_page)));
  return $output;
}

/**
 * Pass through to the panels layout settings editor.
 */
function panels_page_edit_layout_settings($panel_page, $next = NULL) {
  if (empty($next)) {
    $button = t('Save');
    $dest = "admin/panels/panel-page/$panel_page->name/edit/settings";
    if ($panel_page->display->did != $panel_page->did) {
      $dest .= '/' . $panel_page->display->did;
    }
  }
  else {
    $button = t('Save and proceed');
    $dest = "admin/panels/panel-page/$panel_page->name/edit/advanced/next";
  }

  // The following form will return the $display upon successful submit, if
  // we didn't send the $dest. Which we don't, here.
  $output = panels_edit_layout_settings($panel_page->display, $button, NULL, $panel_page->title);
  if (is_object($output)) {
    $panel_page->display = $output;
    panels_page_save_display($panel_page);
    drupal_goto($dest);
  }

  drupal_set_title(check_plain(panels_page_get_title($panel_page)));
  return $output;
}

/**
 * Pass through to the panels content editor.
 */
function panels_page_edit_content($panel_page) {
  panels_load_include('plugins');
  panels_load_include('common');
  // Collect a list of the contexts (potentially) available to this panel page.
  $panel_page->display->context = panels_context_load_contexts($panel_page);
  $panel_page->display->args = array();

  // Get a list of available content.
  $content_types = panels_common_get_allowed_types('panels_page', $panel_page->display->context);

  $output = panels_edit($panel_page->display, NULL, $content_types);
  if (is_object($output)) {
    $panel_page->display = $output;
    panels_page_save_display($panel_page);

    // And do the drupal_goto that a submit function ordinarily would have.
    $dest = "admin/panels/panel-page/$panel_page->name/edit/content";
    if ($panel_page->current != 'primary') {
      $dest .= '/' . $panel_page->display->did;
    }
    drupal_goto($dest);
  }

  // Print this with theme('page') so that blocks are disabled while editing a display.
  // This is important because negative margins in common block layouts (i.e, Garland)
  // messes up the drag & drop.
  drupal_set_title(check_plain(panels_page_get_title($panel_page)));
  print theme('page', $output, FALSE);
}

function panels_page_preview_page(&$form_state, $panel_page) {
  panels_page_load_include('render');
  $args = func_get_args();
  $panel_page = array_shift($args);
  return t('The Preview function has not yet been ported; expect it in a later alpha release.');
  $load_objects = array();
  // FIXME copied from the master loader; this NEEDS to be retooled for previews.
/*  foreach ($panel_page->arguments as $id => $argument) {
    $ignore = $argument['default'] == 'ignore';
    $load_objects[$id] = array_shift($args);
    $context = !empty($load_objects[$id]) ? panels_argument_get_context($argument, $load_objects[$id]) : PANELS_BAD_ARG;
    if (!is_a($context, 'panels_required_context') && !is_a($context, 'panels_context')) {
      if ($context & PANELS_USE_FALLBACK_ROUTER) {
        if ($panel_page->load_flags & PANELS_HAS_FALLBACK_ROUTER) {
          $loader_data['fallback'] = TRUE;
          break;
        }
        else if ($ignore) {
          continue;
        }
      }
      // TODO Are there other cases? If not, this else is an unnecessary overspecification
      else if ($context & PANELS_BAD_ARG && $ignore) {
        continue;
      }
      // Bail out and 404 if we get this far.
      // TODO should this 'business logic' be separated out?
      drupal_not_found();
    }
    $panel_page->context[panels_argument_context_id($argument)] = $context;
  }
  _panels_page_prepare_render($panel_page);
  */
}

function panels_page_admin_view(&$form_state, $panel_page, $args) {
  $form = array();

  $form['fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Administrative preview: enter arguments'),
    '#collapsible' => TRUE,
  );

  $required_args = strpos($panel_page->path, '%') === false ? 0 : count(split($panel_page->path, '%'));

  $url = panels_page_get_url($panel_page, $args);
  if ($args_missing = max($required_args - count($args), 0)) {
    $value = $url;
    $description = format_plural($args_missing,
      t('1 argument is missing to generate a valid URL.'),
      t('%count arguments are missing to generate a valid URL.', array('%count' => $args_missing))
    );
  }
  else {
    $value = l($url, $url);
    $description = t('Click to see the real panel page.');
  }
  $form['fieldset']['url'] = array(
    '#type' => 'item',
    '#title' => t('Real panel URL'),
    '#value' => $value,
    '#description' => $description,
  );

  $contexts = panels_context_load_contexts($panel_page);
  $count = 0;
  foreach ($contexts as $id => $context) {
    if (substr($id, 0, 8) == 'argument') {
      $required = ($count + 1 <= $required_args) ? TRUE : FALSE;
      $description = $required ? t('Required argument (occupies %-placeholder number !position)', array('!position' => $count + 1)) : t('Optional argument');
      $form['fieldset']["arg$count"] = array(
        '#type' => 'textfield',
        '#title' => check_plain($context->identifier),
        '#default_value' => isset($args[$count]) ? $args[$count] : '',
        '#required' => $required,
        '#description' => $description,
      );
    }
    if (isset($args[$count])) {
      unset($args[$count]);
    }
    $count++;
  }

  $add = '';
  if ($args) {
    $add = implode('/', $args);
  }
  $form['fieldset']['additional'] = array(
    '#type' => 'textfield',
    '#title' => t('Additional arguments'),
    '#description' => t('Separated by /'),
    '#default_value' => $add,
  );

  $form['fieldset']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Change arguments'),
  );

  $form['panel_page'] = array(
    '#type' => 'value',
    '#value' => $panel_page,
  );
  $form['contexts'] = array(
    '#type' => 'value',
    '#value' => $contexts,
  );

  return $form;
}

function panels_page_admin_view_submit($form, &$form_state) {
  $count = 0;
  $url = "admin/panels/panel-page/" . $form_state['values']['panel_page']->name . '/edit/preview';
  foreach ($form_state['values']['contexts'] as $context) {
    $url .= "/" . $form_state['values']["arg$count"];
    $count++;
  }
  if (!empty($form_state['values']['additional'])) {
    $url .= "/" . $form_state['values']['additional'];
  }
  $form_state['redirect'] = $url;
}


/**
 * Page callback to import a panel page from PHP code.
 */
function panels_page_import_page() {
  if (!empty($_POST['form_id']) && $_POST['form_id'] == 'panels_page_edit_form') {
    $panel_page = unserialize($_SESSION['pp_import']);
    drupal_set_title(t('Import panel page "@s"', array('@s' => $panel_page->title)));
    return drupal_get_form('panels_page_edit_form', $panel_page);
  }

  return drupal_get_form('panels_page_import_form');
}

/**
 * Form to for the panel page import
 */
function panels_page_import_form(&$form_state) {
  $form['panel_page'] = array(
    '#type' => 'textarea',
    '#title' => t('Panel page code'),
    '#cols' => 60,
    '#rows' => 15,
    '#description' => t('Cut and paste the results of an exported panel page here.'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Import'),
  );

  $form['#redirect'] = FALSE;
  return $form;
}

/**
 * Handle the submit button on importing a panel page.
 */
function panels_page_import_form_submit($form, &$form_state) {
  ob_start();
  eval($form_state['values']['panel_page']);
  ob_end_clean();

  if (isset($page)) {
    drupal_set_title(t('Import panel page "@s"', array('@s' => $page->title)));
    // As $page contains non-stdClass objects,
    // it needs to be serialized before being stored in the session variable.
    $_SESSION['pp_import'] = serialize($page);
    $output = drupal_get_form('panels_page_edit_form', $page);
    print theme('page', $output);
    exit;
  }
  else {
    drupal_set_message(t('Unable to get a panel page out of that.'));
  }
}