Projet

Général

Profil

Paste
Télécharger (63,4 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / ctools / page_manager / page_manager.admin.inc @ 6e3ce7c2

1
<?php
2

    
3
/**
4
 * @file
5
 * Administrative functions for the page manager.
6
 *
7
 * This provides the UI to list, create, edit and delete pages, though much
8
 * of this is delegated through to individual tasks.
9
 */
10

    
11
/**
12
 * Output a list of pages that are managed.
13
 */
14
function page_manager_list_page($js = NULL) {
15
  // Prevent this page from showing up when random other links fail.
16
  if ($js && $js != 'ajax' && $js != 'nojs') {
17
    return MENU_NOT_FOUND;
18
  }
19

    
20
  // TRUE if 'ajax', FALSE if otherwise.
21
  $js = $js == 'ajax';
22

    
23
  // If we do any form rendering, it's to completely replace a form on the
24
  // page, so don't let it force our ids to change.
25
  if ($js && isset($_POST['ajax_html_ids'])) {
26
    unset($_POST['ajax_html_ids']);
27
  }
28

    
29
  if (module_exists('advanced_help') && !$js) {
30
    drupal_set_message(theme('advanced_help_topic', array(
31
      'module' => 'page_manager',
32
      'topic' => 'getting-started',
33
      'type' => t('See the getting started guide for more information.'),
34
    )));
35
  }
36

    
37
  $tasks = page_manager_get_tasks_by_type('page');
38
  $pages = array('operations' => array(), 'tasks' => array());
39

    
40
  page_manager_get_pages($tasks, $pages);
41

    
42
  // Add lock icon to all locked tasks.
43
  global $user;
44

    
45
  ctools_include('object-cache');
46
  $locks = ctools_object_cache_test_objects('page_manager_page', $pages['tasks']);
47
  foreach ($locks as $task_name => $lock) {
48
    if ($lock->uid == $user->uid) {
49
      $pages['rows'][$task_name]['class'][] = ' page-manager-locked';
50
      $pages['rows'][$task_name]['title'] = t('This page is currently locked for editing by you. Nobody else may edit this page until these changes are saved or canceled.');
51
    }
52
    else {
53
      $pages['rows'][$task_name]['class'][] = ' page-manager-locked-other';
54
      $pages['rows'][$task_name]['title'] = t('This page is currently locked for editing by another user. You may not edit this page without breaking the lock.');
55
    }
56
  }
57

    
58
  $input = $_POST;
59

    
60
  // Respond to a reset command by clearing session and doing a drupal goto
61
  // back to the base URL.
62
  if (isset($input['op']) && $input['op'] == t('Reset')) {
63
    unset($_SESSION['page_manager']['#admin']);
64
    if (!$js) {
65
      drupal_goto($_GET['q']);
66
    }
67
    // clear everything but form id, form build id and form token:
68
    $keys = array_keys($input);
69
    foreach ($keys as $id) {
70
      if ($id != 'form_id' && $id != 'form_build_id' && $id != 'form_token') {
71
        unset($input[$id]);
72
      }
73
    }
74
    $replace_form = TRUE;
75
  }
76
  if (count($input) <= 1) {
77
    if (isset($_SESSION['page_manager']['#admin']) && is_array($_SESSION['page_manager']['#admin'])) {
78
      $input  = $_SESSION['page_manager']['#admin'];
79
    }
80
  }
81
  else {
82
    $_SESSION['page_manager']['#admin'] = $input;
83
    unset($_SESSION['page_manager']['#admin']['q']);
84
  }
85

    
86
  $form_state = array(
87
    'pages' => &$pages,
88
    'input' => $input,
89
    'rerender' => TRUE,
90
    'no_redirect' => TRUE,
91
  );
92

    
93
  // This form will sort and filter the pages.
94
  $form = drupal_build_form('page_manager_list_pages_form', $form_state);
95

    
96
  $header = array(
97
    array('data' => t('Type'), 'class' => array('page-manager-page-type')),
98
    array('data' => t('Module'), 'class' => array('page-manager-page-module')),
99
    array('data' => t('Name'), 'class' => array('page-manager-page-name')),
100
    array('data' => t('Title'), 'class' => array('page-manager-page-title')),
101
    array('data' => t('Path'), 'class' => array('page-manager-page-path')),
102
    array('data' => t('Storage'), 'class' => array('page-manager-page-storage')),
103
  );
104

    
105
  $header[] = array('data' => t('Operations'), 'class' => array('page-manager-page-operations'));
106
  $table = theme('table', array('header' => $header, 'rows' => $pages['rows'], 'attributes' => array('id' => 'page-manager-list-pages')));
107

    
108
  $operations = '<div id="page-manager-links" class="links">' . theme('links', array('links' => $pages['operations'])) . '</div>';
109

    
110
  drupal_add_css(drupal_get_path('module', 'page_manager') . '/css/page-manager.css');
111

    
112

    
113
  if (!$js) {
114
    return array('#markup' => drupal_render($form) . $table . $operations);
115
  }
116

    
117
  ctools_include('ajax');
118
  $commands = array();
119
  $commands[] = ajax_command_replace('#page-manager-list-pages', $table);
120
  if (!empty($replace_form)) {
121
    $commands[] = ajax_command_replace('#page-manager-list-pages-form', drupal_render($form));
122
  }
123
  print ajax_render($commands);
124
  ajax_footer();
125
}
126

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

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

    
142
    if (isset($task_id)) {
143
      $task_name = page_manager_make_task_name($task_id, $task['name']);
144
    }
145
    else {
146
      $task_name = $task['name'];
147
    }
148

    
149
    $class = array('page-task-' . $id);
150
    if (isset($task['row class'])) {
151
      $class[] = $task['row class'];
152
    }
153

    
154
    if (!empty($task['disabled'])) {
155
      $class[] = 'page-manager-disabled';
156
    }
157

    
158
    $path = array();
159
    $visible_path = '';
160
    if (!empty($task['admin path'])) {
161
      foreach (explode('/', $task['admin path']) as $bit) {
162
        if (isset($bit[0]) && $bit[0] != '!') {
163
          $path[] = $bit;
164
        }
165
      }
166

    
167
      $path = implode('/', $path);
168
      if (empty($task['disabled']) && strpos($path, '%') === FALSE) {
169
        $visible_path = l('/' . $task['admin path'], $path);
170
      }
171
      else {
172
        $visible_path = '/' . $task['admin path'];
173
      }
174
    }
175

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

    
178
    $type = isset($task['admin type']) ? $task['admin type'] : t('System');
179
    if (isset($task['module'])) {
180
      $module = $task['module'];
181
    }
182
    elseif (isset($task['subtask']->export_module)) {
183
      $module = $task['subtask']->export_module;
184
    }
185
    else {
186
      $module = '';
187
    }
188
    $pages['types'][$type] = $type;
189
    $row['data']['type'] = array('data' => $type, 'class' => array('page-manager-page-type'));
190
    $row['data']['module'] = array('data' => $module, 'class' => array('page-manager-page-module'));
191
    $row['data']['name'] = array('data' => $task_name, 'class' => array('page-manager-page-name'));
192
    $row['data']['title'] = array('data' => $task['admin title'], 'class' => array('page-manager-page-title'));
193
    $row['data']['path'] = array('data' => $visible_path, 'class' => array('page-manager-page-path'));
194

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

    
199

    
200
/*
201
    if (empty($task['disabled'])) {
202
      $item = menu_get_item($path);
203
      if (empty($item)) {
204
        dsm($path);
205
      }
206
      else {
207
        dsm($item);
208
      }
209
    }
210
*/
211
    $operations = array(
212
      array(
213
        'title' => t('Edit'),
214
        'href' => page_manager_edit_url($task_name),
215
      ),
216
    );
217

    
218
    if (!empty($task['enable callback'])) {
219
      if (!empty($task['disabled'])) {
220
        array_unshift($operations, array(
221
          'title' => t('Enable'),
222
          'href' => 'admin/structure/pages/nojs/enable/' . $task_name,
223
          'query' => array('token' => drupal_get_token($task_name)),
224
        ));
225
      }
226
      else {
227
        $operations[] = array(
228
          'title' => t('Disable'),
229
          'href' => 'admin/structure/pages/nojs/disable/' . $task_name,
230
          'query' => array('token' => drupal_get_token($task_name)),
231
        );
232
      }
233
    }
234

    
235
    $ops = theme('links__ctools_dropbutton', array('links' => $operations, 'attributes' => array('class' => array('links', 'inline'))));
236

    
237
    $row['data']['operations'] = array('data' => $ops, 'class' => array('page-manager-page-operations'));
238

    
239
    $pages['disabled'][$task_name] = !empty($task['disabled']);
240
    $pages['tasks'][] = $task_name;
241
    $pages['rows'][$task_name] = $row;
242
  }
243
}
244

    
245
/**
246
 * Provide a form for sorting and filtering the list of pages.
247
 */
248
function page_manager_list_pages_form($form, &$form_state) {
249
  // This forces the form to *always* treat as submitted which is
250
  // necessary to make it work.
251
  if (empty($_POST)) {
252
    $form["#programmed"] = TRUE;
253
  }
254
  $form['#action'] = url('admin/structure/pages/nojs/', array('absolute' => TRUE));
255
  if (!variable_get('clean_url', FALSE)) {
256
    $form['q'] = array(
257
      '#type' => 'hidden',
258
      '#value' => $_GET['q'],
259
    );
260
  }
261

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

    
264
  $form['type'] = array(
265
    '#type' => 'select',
266
    '#title' => t('Type'),
267
    '#options' => $all + $form_state['pages']['types'],
268
    '#default_value' => 'all',
269
  );
270

    
271
  $form['storage'] = array(
272
    '#type' => 'select',
273
    '#title' => t('Storage'),
274
    '#options' => $all + $form_state['pages']['storages'],
275
    '#default_value' => 'all',
276
  );
277

    
278
  $form['disabled'] = array(
279
    '#type' => 'select',
280
    '#title' => t('Enabled'),
281
    '#options' => $all + array('0' => t('Enabled'), '1' => t('Disabled')),
282
    '#default_value' => 'all',
283
  );
284

    
285
  $form['search'] = array(
286
    '#type' => 'textfield',
287
    '#title' => t('Search'),
288
  );
289

    
290
  $form['order'] = array(
291
    '#type' => 'select',
292
    '#title' => t('Sort by'),
293
    '#options' => array(
294
      'disabled' => t('Enabled, title'),
295
      'title' => t('Title'),
296
      'name' => t('Name'),
297
      'path' => t('Path'),
298
      'type' => t('Type'),
299
      'storage' => t('Storage'),
300
    ),
301
    '#default_value' => 'disabled',
302
  );
303

    
304
  $form['sort'] = array(
305
    '#type' => 'select',
306
    '#title' => t('Order'),
307
    '#options' => array(
308
      'asc' => t('Up'),
309
      'desc' => t('Down'),
310
    ),
311
    '#default_value' => 'asc',
312
  );
313

    
314
  $form['submit'] = array(
315
    '#name' => '', // so it won't in the $_GET args
316
    '#type' => 'submit',
317
    '#id' => 'edit-pages-apply',
318
    '#value' => t('Apply'),
319
    '#attributes' => array('class' => array('use-ajax-submit ctools-auto-submit-click')),
320
  );
321

    
322
  $form['reset'] = array(
323
    '#type' => 'submit',
324
    '#id' => 'edit-pages-reset',
325
    '#value' => t('Reset'),
326
    '#attributes' => array('class' => array('use-ajax-submit')),
327
  );
328

    
329
  $form['#attached']['js'] = array(ctools_attach_js('auto-submit'), ctools_attach_js('page-list', 'page_manager'));
330
  $form['#attached']['library'][] = array('system', 'drupal.ajax');
331
  $form['#attached']['library'][] = array('system', 'jquery.form');
332
  $form['#prefix'] = '<div class="clearfix">';
333
  $form['#suffix'] = '</div>';
334
  $form['#attributes'] = array('class' => array('ctools-auto-submit-full-form'));
335

    
336
  return $form;
337
}
338

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

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

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

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

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

    
364
    if ($form_state['values']['search'] &&
365
        strpos($data['data']['name']['data'], $form_state['values']['search']) === FALSE &&
366
        strpos($data['data']['path']['data'], $form_state['values']['search']) === FALSE &&
367
        strpos($data['data']['title']['data'], $form_state['values']['search']) === FALSE) {
368
          continue;
369
    }
370
    // Set up sorting
371
    switch ($form_state['values']['order']) {
372
      case 'disabled':
373
        $sorts[$name] = !$form_state['pages']['disabled'][$name] . $data['data']['title']['data'];
374
        break;
375
      case 'title':
376
        $sorts[$name] = $data['data']['title']['data'];
377
        break;
378
      case 'name':
379
        $sorts[$name] = $data['data']['name']['data'];
380
        break;
381
      case 'path':
382
        $sorts[$name] = $data['data']['path']['data'];
383
        break;
384
      case 'type':
385
        $sorts[$name] = $data['data']['type']['data'];
386
        break;
387
      case 'storage':
388
        $sorts[$name] = $data['data']['storage']['data'];
389
        break;
390
    }
391
  }
392

    
393
  // Now actually sort
394
  if ($form_state['values']['sort'] == 'desc') {
395
    arsort($sorts);
396
  }
397
  else {
398
    asort($sorts);
399
  }
400

    
401
  // Nuke the original.
402
  $form_state['pages']['rows'] = array();
403
  // And restore.
404
  foreach ($sorts as $name => $title) {
405
    $form_state['pages']['rows'][$name] = $rows[$name];
406
  }
407

    
408
}
409

    
410
/**
411
 * Render the edit page for a a page, custom or system.
412
 */
413
function page_manager_edit_page($page) {
414
  drupal_set_title($page->subtask['admin title'], PASS_THROUGH);
415
  // Provide and process the save page form before anything else.
416
  $form_state = array('page' => &$page);
417
  $built_form = drupal_build_form('page_manager_save_page_form', $form_state);
418
  $form = drupal_render($built_form);
419

    
420
  $operations = page_manager_get_operations($page);
421
  $args = array('summary');
422
  $rendered_operations = page_manager_render_operations($page, $operations, $args, array('class' => array('operations-main')), 'nav');
423
  $content = page_manager_get_operation_content(FALSE, $page, $args, $operations);
424
  $output = theme('page_manager_edit_page', array('page' => $page, 'save' => $form, 'operations' => $rendered_operations, 'content' => $content));
425
  return array('#markup' => $output);
426
}
427

    
428
/**
429
 * Entry point to edit a single operation for a page.
430
 *
431
 * @param $js
432
 *   Whether or not the page was called via javascript.
433
 * @param $page
434
 *   The cached page that is being edited.
435
 * @param ...
436
 *   A number of items used to drill down into the actual operation called.
437
 */
438
function page_manager_edit_page_operation() {
439
  $args = func_get_args();
440
  $js = array_shift($args);
441
  $page = array_shift($args);
442

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

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

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

    
460
  // Since this form should never be submitted to this page, process it late so
461
  // that we can be sure it notices changes.
462
  $form_state = array('page' => &$page);
463
  $built_form = drupal_build_form('page_manager_save_page_form', $form_state);
464
  $form = drupal_render($built_form);
465

    
466
  $output = theme('page_manager_edit_page', array('page' => $page, 'save' => $form, 'operations' => $rendered_operations, 'content' => $content));
467

    
468
  if ($js) {
469
    $commands = array();
470
    $commands[] = ajax_command_replace('#page-manager-edit', $output);
471

    
472
    print ajax_render($commands);
473
    ajax_footer();
474
    return;
475
  }
476

    
477
  drupal_set_title($page->subtask['admin title'], PASS_THROUGH);
478
  return $output;
479
}
480

    
481
/**
482
 * Take the operations array from a task and expand it.
483
 *
484
 * This allows some of the operations to be dynamic, based upon settings
485
 * on the task or the task's handlers. Each operation should have a type. In
486
 * addition to all the types allowed in page_manager_render_operations, these
487
 * types will be dynamically replaced with something else:
488
 * - 'handlers': An automatically created group that contains all the task's
489
 *   handlers and appropriate links.
490
 * - 'function': A callback (which will be placed in the 'function' parameter
491
 *   that should return an array of operations. This can be used to provide
492
 *   additional, dynamic links if needed.
493
 */
494
function page_manager_get_operations($page, $operations = NULL) {
495
  if (!isset($operations)) {
496
    // All tasks have at least these 2 ops:
497
    $operations = array(
498
      'summary' => array(
499
        'title' => t('Summary'),
500
        'description' => t('Get a summary of the information about this page.'),
501
        'path' => 'admin/structure/pages/edit',
502
        'ajax' => FALSE,
503
        'no operations' => TRUE,
504
        'form info' => array(
505
          'no buttons' => TRUE,
506
        ),
507
        'form' => 'page_manager_page_summary',
508
      ),
509
      'actions' => array(
510
        'type' => 'group',
511
        'title' => '',
512
        'class' => array('operations-actions'),
513
        'location' => 'primary',
514
        'children' => array(),
515
      ),
516
    );
517

    
518
    if (isset($page->subtask['operations'])) {
519
      $operations += $page->subtask['operations'];
520
      // add actions separately.
521
      if (!empty($page->subtask['operations']['actions'])) {
522
        $operations['actions']['children'] += $page->subtask['operations']['actions']['children'];
523
      }
524
    }
525
    $operations['handlers'] = array('type' => 'handlers');
526
  }
527

    
528
  $result = array();
529
  foreach ($operations as $id => $operation) {
530
    if (empty($operation['type'])) {
531
      $operation['type'] = 'operation';
532
    }
533
    switch ($operation['type']) {
534
      case 'handlers':
535
        $result[$id] = page_manager_get_handler_operations($page);
536
        break;
537
      case 'function':
538
        if (function_exists($operation['function'])) {
539
          $retval = $function($page, $operation);
540
          if (is_array($retval)) {
541
            $result[$id] = $retval;
542
          }
543
        }
544
        break;
545
      default:
546
        $result[$id] = $operation;
547
    }
548
  }
549

    
550
  if (!empty($page->subtask['enable callback']) && !empty($page->subtask['disabled']) && empty($result['actions']['children']['enable'])) {
551
    $result['actions']['children']['enable'] = array(
552
      'title' => t('Enable'),
553
      'description' => t('Activate this page so that it will be in use in your system.'),
554
      'form' => 'page_manager_enable_form',
555
      'ajax' => FALSE,
556
      'silent' => TRUE,
557
      'no update and save' => TRUE,
558
      'form info' => array(
559
        'finish text' => t('Enable'),
560
      ),
561
    );
562
  }
563

    
564
  if (!empty($page->subtask['enable callback']) && empty($page->subtask['disabled']) && empty($result['actions']['children']['disable'])) {
565
    $result['actions']['children']['disable'] = array(
566
      'title' => t('Disable'),
567
      'description' => t('De-activate this page. The data will remain but the page will not be in use on your system.'),
568
      'form' => 'page_manager_disable_form',
569
      'ajax' => FALSE,
570
      'silent' => TRUE,
571
      'no update and save' => TRUE,
572
      'form info' => array(
573
        'finish text' => t('Disable'),
574
      ),
575
    );
576
  }
577

    
578
  $result['actions']['children']['add'] = array(
579
    'title' => t('Add variant'),
580
    'description' => t('Add a new variant to this page.'),
581
    'form' => 'page_manager_handler_add',
582
    'ajax' => FALSE,
583
    'silent' => TRUE, // prevents a message about updating and prevents this item from showing as changed.
584
    'no update and save' => TRUE, // get rid of update and save button which is bad here.
585
    'form info' => array(
586
      'finish text' => t('Create variant'),
587
    ),
588
  );
589

    
590
  // Restrict variant import due to security implications.
591
  if (user_access('use ctools import')) {
592
    $result['actions']['children']['import'] = array(
593
      'title' => t('Import variant'),
594
      'description' => t('Add a new variant to this page from code exported from another page.'),
595
      'form' => 'page_manager_handler_import',
596
    );
597
  }
598

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

    
608
  // This is a special operation used to configure a new task handler before
609
  // it is added.
610
  if (isset($page->new_handler)) {
611
  $plugin = page_manager_get_task_handler($page->new_handler->handler);
612
    $result['actions']['children']['configure'] = array(
613
      'title' => t('Configure'),
614
      'description' => t('Configure a newly created variant prior to actually adding it to the page.'),
615
      'ajax' => FALSE,
616
      'no update and save' => TRUE, // get rid of update and save button which is bad here.
617
      'form info' => array(
618
        // We use our own cancel and finish callback to handle the fun stuff.
619
        'finish callback' => 'page_manager_handler_add_finish',
620
        'cancel callback' => 'page_manager_handler_add_cancel',
621
        'show trail' => TRUE,
622
        'show back' => TRUE,
623
        'finish text' => t('Create variant'),
624
      ),
625
      'form' => array(
626
        'forms' => $plugin['forms'],
627
      ),
628
    );
629

    
630
    foreach ($page->forms as $id) {
631
      if (isset($plugin['add features'][$id])) {
632
        $result['actions']['children']['configure']['form']['order'][$id] = $plugin['add features'][$id];
633
      }
634
      elseif (isset($plugin['required forms'][$id])) {
635
        $result['actions']['children']['configure']['form']['order'][$id] = $plugin['required forms'][$id];
636
      }
637
    }
638
  }
639

    
640
  if ($page->locked) {
641
    $result['actions']['children']['break-lock'] = array(
642
      'title' => t('Break lock'),
643
      'description' => t('Break the lock on this page so that you can edit it.'),
644
      'form' => 'page_manager_break_lock',
645
      'ajax' => FALSE,
646
      'no update and save' => TRUE, // get rid of update and save button which is bad here.
647
      'form info' => array(
648
        'finish text' => t('Break lock'),
649
       ),
650
      'even locked' => TRUE, // show button even if locked
651
      'silent' => TRUE,
652
    );
653
  }
654

    
655
  drupal_alter('page_manager_operations', $result, $page);
656
  return $result;
657
}
658

    
659
/**
660
 * Collect all the operations related to task handlers (variants) and
661
 * build a menu.
662
 */
663
function page_manager_get_handler_operations(&$page) {
664
  ctools_include('export');
665
  $group = array(
666
    'type' => 'group',
667
    'class' => array('operations-handlers'),
668
    'title' => t('Variants'),
669
  );
670

    
671
  $operations = array();
672

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

    
682
    $operations[$id] = array(
683
      'type' => 'group',
684
      'class' => array('operations-handlers-' . $id),
685
      'title' => page_manager_get_handler_title($plugin, $handler, $page->task, $page->subtask_id),
686
      'collapsible' => $collapsible,
687
      'children' => array(),
688
    );
689

    
690
    $operations[$id]['children']['actions'] = array(
691
      'type' => 'group',
692
      'class' => array('operations-handlers-actions-' . $id),
693
      'title' => t('Variant operations'),
694
      'children' => array(),
695
      'location' => $id,
696
    );
697

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

    
708
    if ($plugin && isset($plugin['operations'])) {
709
      $operations[$id]['children'] += $plugin['operations'];
710
    }
711

    
712
    $actions = &$operations[$id]['children']['actions']['children'];
713

    
714
    $actions['clone'] = array(
715
      'title' => t('Clone'),
716
      'description' => t('Make an exact copy of this variant.'),
717
      'form' => 'page_manager_handler_clone',
718
    );
719
    $actions['export'] = array(
720
      'title' => t('Export'),
721
      'description' => t('Export this variant into code to import into another page.'),
722
      'form' => 'page_manager_handler_export',
723
    );
724
    if ($handler->export_type == (EXPORT_IN_CODE | EXPORT_IN_DATABASE)) {
725
      $actions['delete'] = array(
726
        'title' => t('Revert'),
727
        'description' => t('Remove all changes to this variant and revert to the version in code.'),
728
        'form' => 'page_manager_handler_delete',
729
        'no update and save' => TRUE,
730
        'form info' => array(
731
          'finish text' => t('Revert'),
732
        ),
733
      );
734
    }
735
    elseif ($handler->export_type != EXPORT_IN_CODE) {
736
      $actions['delete'] = array(
737
        'title' => t('Delete'),
738
        'description' => t('Remove this variant from the page completely.'),
739
        'form' => 'page_manager_handler_delete',
740
        'form info' => array(
741
          'finish text' => t('Delete'),
742
          'save text' => t('Delete and save'),
743
        ),
744
      );
745
    }
746
    if (!empty($handler->disabled)) {
747
      $actions['enable'] = array(
748
        'title' => t('Enable'),
749
        'description' => t('Activate this variant so that it will be in use in your system.'),
750
        'form' => 'page_manager_handler_enable',
751
        'silent' => TRUE,
752
        'form info' => array(
753
          'finish text' => t('Enable'),
754
          'save text' => t('Enable and save'),
755
        ),
756
      );
757
    }
758
    else {
759
      $actions['disable'] = array(
760
        'title' => t('Disable'),
761
        'description' => t('De-activate this variant. The data will remain but the variant will not be in use on your system.'),
762
        'form' => 'page_manager_handler_disable',
763
        'silent' => TRUE,
764
        'form info' => array(
765
          'finish text' => t('Disable'),
766
          'save text' => t('Disable and save'),
767
        ),
768
      );
769
    }
770

    
771
    drupal_alter('page_manager_variant_operations', $operations[$id], $handler);
772
  }
773
  if (empty($operations)) {
774
    $operations['empty'] = array(
775
      'type' => 'text',
776
      'title' => t('No variants'),
777
    );
778
  }
779

    
780
  $group['children'] = $operations;
781
  return $group;
782
}
783

    
784
/**
785
 * Get an operation from a trail.
786
 *
787
 * @return array($operation, $active, $args)
788
 */
789
function page_manager_get_operation($operations, $trail) {
790
  $args = $trail;
791
  $stop = FALSE;
792
  $active = array();
793
  $titles = array();
794
  // Drill down into operations array:
795
  while (!$stop) {
796
    $check = reset($args);
797
    $stop = TRUE;
798
    if (is_array($operations)) {
799
      if (isset($operations[$check])) {
800
        $active[] = $check;
801
        $operation = array_shift($args);
802
        // check to see if this operation has children. If so, we continue.
803
        if (!isset($operations[$check]['children'])) {
804
          $operations = $operations[$check];
805
        }
806
        else {
807
          $titles[] = $operations[$check]['title'];
808
          $operations = $operations[$check]['children'];
809
          // continue only if the operation hs children.
810
          $stop = FALSE;
811
        }
812
      }
813
    }
814
  }
815

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

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

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

    
843
  return $content;
844
}
845

    
846
/**
847
 * Fetch the content for an operation, after it's been discovered from arguments.
848
 *
849
 * This system runs through the CTools form wizard. Each operation specifies a form
850
 * or set of forms that it may use. Operations may also specify wrappers and can
851
 * set their own next/finish handlers so that they can make additional things happen
852
 * at the end.
853
 */
854
function _page_manager_get_operation_content($js, &$page, $active, $operation, $titles = array(), $args = array()) {
855
  if (isset($operation['form'])) {
856
    $form_info = array(
857
      'id' => 'page_manager_page',
858
      'finish text' => t('Update'),
859
      'show trail' => FALSE,
860
      'show back' => FALSE,
861
      'show return' => FALSE,
862
      'show cancel' => FALSE,
863
      'next callback' => 'page_manager_edit_page_next',
864
      'finish callback' => 'page_manager_edit_page_finish',
865
      // Items specific to the 'edit' routines that will get moved over:
866
      'path' => page_manager_edit_url($page->task_name, $active) . "/%step",
867
      // wrapper function to add an extra finish button.
868
      'wrapper' => 'page_manager_operation_wrapper',
869
    );
870

    
871
    // If $operation['form'] is simply a string, then it is the function
872
    // name of the form.
873
    if (!is_array($operation['form'])) {
874
      $form_info['order'] = array(
875
        'form' => $operation['title'],
876
      );
877
      $form_info['forms'] = array(
878
        'form' => array('form id' => $operation['form']),
879
      );
880
      if (isset($operation['wrapper'])) {
881
        $form_info['forms']['form']['wrapper'] = $operation['wrapper'];
882
      }
883
    }
884
    // Otherwise it's the order and forms arrays directly.
885
    else {
886
      $form_info['order'] = $operation['form']['order'];
887
      $form_info['forms'] = $operation['form']['forms'];
888
    }
889

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

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

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

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

    
914
    ctools_include('wizard');
915
    $form_state = array(
916
      'page' => $page,
917
      'type' => 'edit',
918
      'ajax' => $js && (!isset($operation['ajax']) || !empty($operation['ajax'])),
919
      'rerender' => TRUE,
920
      'trail' => $active,
921
      'task_name' => $page->task_name,
922
      'task_id' => $page->task_id,
923
      'task' => $page->task,
924
      'subtask_id' => $page->subtask_id,
925
      'subtask' => $page->subtask,
926
      'operation' => $operation,
927
    );
928

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

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

    
939
    $built_form = ctools_wizard_multistep_form($form_info, $step, $form_state);
940
    $output = drupal_render($built_form);
941
    $title = empty($form_state['title']) ? $operation['title'] : $form_state['title'];
942
    $titles[] = $title;
943
    $title = implode(' &raquo; ', array_filter($titles));
944

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

    
950
    $description = isset($operation['admin description']) ? $operation['admin description'] : (isset($operation['description']) ? $operation['description'] : '');
951
    $return = array(
952
      'title' => $title,
953
      'content' => $output,
954
      'description' => $description,
955
    );
956

    
957
    // Append any extra content, used for the preview which is submitted then
958
    // rendered.
959
    if (isset($form_state['content'])) {
960
      $return['content'] .= $form_state['content'];
961
    }
962

    
963
    // If the form wanted us to go somewhere else next, pass that along.
964
    if (isset($form_state['new trail'])) {
965
      $return['new trail'] = $form_state['new trail'];
966
    }
967
  }
968
  else {
969
    $return = array(
970
      'title' => t('Error'),
971
      'content' => t('This operation trail does not exist.'),
972
    );
973
  }
974

    
975
  $return['active'] = $active;
976
  return $return;
977
}
978

    
979
function page_manager_operation_wrapper($form, &$form_state) {
980
  if (empty($form_state['operation']['no update and save']) && !empty($form['buttons']['return']['#wizard type']) && $form['buttons']['return']['#wizard type']) {
981
    $form['buttons']['save'] = array(
982
      '#type' => 'submit',
983
      '#value' => !empty($form_state['form_info']['save text']) ? $form_state['form_info']['save text'] : t('Update and save'),
984
      '#wizard type' => 'finish',
985
      '#attributes' => $form['buttons']['return']['#attributes'],
986
      '#save' => TRUE,
987
    );
988
  }
989

    
990
  return $form;
991
}
992

    
993
/**
994
 * Callback generated when the an operation edit finished.
995
 */
996
function page_manager_edit_page_finish(&$form_state) {
997
  if (empty($form_state['operation']['silent'])) {
998
    if (empty($form_state['clicked_button']['#save'])) {
999
      drupal_set_message(t('The page has been updated. Changes will not be permanent until you save.'));
1000
    }
1001
    else {
1002
      drupal_set_message(t('The page has been updated and saved.'));
1003
    }
1004
    $path = array();
1005
    foreach ($form_state['trail'] as $operation) {
1006
      $path[] = $operation;
1007
      $form_state['page']->changes[implode('/', $path)] = TRUE;
1008
    }
1009
  }
1010

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

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

    
1023
  // If the 'Update and Save' button was selected, write our cache out.
1024
  if (!empty($form_state['clicked_button']['#save'])) {
1025
    page_manager_save_page_cache($form_state['page']);
1026
    page_manager_clear_page_cache($form_state['page']->task_name);
1027
    $form_state['page'] = page_manager_get_page_cache($form_state['page']->task_name);
1028
  }
1029
  else {
1030
    if (empty($form_state['do not cache'])) {
1031
      page_manager_set_page_cache($form_state['page']);
1032
    }
1033
  }
1034

    
1035
  // We basically always want to force a rerender when the forms
1036
  // are finished, so make sure there is a new trail.
1037
  if (empty($form_state['new trail'])) {
1038
    // force a rerender to get rid of old form items that may have changed
1039
    // during save.
1040
    $form_state['new trail'] = $form_state['trail'];
1041
  }
1042

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

    
1047
  $form_state['complete'] = TRUE;
1048
}
1049

    
1050
/**
1051
 * Callback generated when the 'next' button is clicked.
1052
 *
1053
 * All we do here is store the cache.
1054
 */
1055
function page_manager_edit_page_next(&$form_state) {
1056
  page_manager_set_page_cache($form_state['page']);
1057
}
1058

    
1059
/**
1060
 * Callback generated when the 'cancel' button is clicked.
1061
 *
1062
 * All we do here is clear the cache.
1063
 */
1064
function page_manager_edit_page_cancel(&$form_state) {
1065
  $page = $form_state['page'];
1066
}
1067

    
1068
/**
1069
 * Render an operations array.
1070
 *
1071
 * This renders an array of operations into a series of nested UL statements,
1072
 * with ajax automatically on unless specified otherwise. Operations will
1073
 * automatically have the URLs generated nested.
1074
 *
1075
 * Each operation should have a 'type', which tells the renderer how to deal
1076
 * with it:
1077
 * - 'operation': An AJAX link to render. This is the default and is
1078
 *   assumed if a type is not specified. Other fields for the operation:
1079
 * - - 'title': The text to display. Can be an image. Must be pre-sanitized.
1080
 * - - 'description': Text to place in the hover box over the link using the
1081
 *     title attribute.
1082
 * - - 'arguments': Anything optional to put at the end of the URL.
1083
 * - - 'path': If set, overrides the default path.
1084
 * - - 'no operations': If set, the path will not have operations appended.
1085
 * - - 'no task': If set, the path will not have the task id.
1086
 * - - 'no link': If set, this item will just be text, not a link.
1087
 * - - 'ajax': If set to TRUE, ajax will be used. The default is TRUE.
1088
 * - - 'class': An optional class to specify for the link.
1089
 * - - 'form': The form to display for this operation, if using a single form.
1090
 * - - 'forms': An array of forms that must be paired with 'order' of this
1091
 *      operation uses multiple forms. See wizard tool for details.
1092
 * - - 'order': The form order to use for multiple forms. See wizard tool for
1093
 *     details.
1094
 * - - 'form info': Form info overrides for the wizard. See the wizard tool
1095
 *      for available settings
1096
 * - 'group':
1097
 * - - 'title': The title of the link. May be HTML.
1098
 * - - 'title class': A class to apply to the title.
1099
 * - - 'children': An array of more operations that this group represents.
1100
 *     All operations within this group will have this group's ID as part
1101
 *     of the AJAX url to make it easier to find.
1102
 * - - 'class': A class to apply to the UL of the children.
1103
 * - - 'collapsible': If TRUE the collapsible tool will be used.
1104
 */
1105
function page_manager_render_operations(&$page, $operations, $active_trail, $attributes, $location, $parents = array()) {
1106
  drupal_add_library('system', 'drupal.ajax');
1107

    
1108
  if (!isset($output[$location])) {
1109
    $output[$location] = '';
1110
  }
1111

    
1112
  $keys = array_keys($operations);
1113
  $first = array_shift($keys);
1114
  $last = array_pop($keys);
1115

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

    
1124
  $active = reset($active_trail);
1125
  foreach ($operations as $id => $operation) {
1126
    $current_path = '';
1127
    if ($parents) {
1128
      $current_path .= implode('/', $parents) . '/';
1129
    }
1130
    $current_path .= $id;
1131

    
1132
    if (empty($operation['type'])) {
1133
      $operation['type'] = 'operation';
1134
    }
1135

    
1136
    // We only render an li for things in the same nav tree.
1137
    if (empty($operation['location']) || $operation['location'] == $location) {
1138
      if (!is_array($attributes['class'])) {
1139
        $attributes['class'] = array($attributes['class']);
1140
      }
1141

    
1142
      $class = empty($attributes['class']) || !is_array($attributes['class']) ? array() : $attributes['class'];
1143

    
1144
      if ($id == $first) {
1145
        $class[] = 'operation-first';
1146
      }
1147
      elseif ($id == $last) {
1148
        $class[] = 'operation-last';
1149
      }
1150

    
1151
      if (empty($operation['silent']) && !empty($page->changes[$current_path])) {
1152
        $class[] = $operation['type'] == 'group' ? 'changed-group' : 'changed';
1153
      }
1154
      else {
1155
        $class[] = 'not-changed';
1156
      }
1157

    
1158
      if ($active == $id) {
1159
        $class[] = $operation['type'] == 'group' ? 'active-group' : 'active';
1160
      }
1161
      else {
1162
        $class[] = 'not-active';
1163
      }
1164

    
1165
      $output[$location] .= '<li class="' . implode(' ', $class) . '">';
1166
    }
1167

    
1168
    switch ($operation['type']) {
1169
      case 'text':
1170
        $output[$location] .= $operation['title'];
1171
        break;
1172
      case 'operation':
1173
        $path = isset($operation['path']) ? $operation['path'] : 'admin/structure/pages/nojs/operation';
1174
        if (!isset($operation['no task'])) {
1175
          $path .= '/' . $page->task_name;
1176
        }
1177

    
1178
        if (!isset($operation['no operations'])) {
1179
          $path .= '/' . $current_path;
1180
          if (isset($operation['arguments'])) {
1181
            $path .= '/' . $arguments;
1182
          }
1183
        }
1184

    
1185
        $class = array('page-manager-operation');
1186
        if (!isset($operation['ajax']) || !empty($operation['ajax'])) {
1187
          $class[] = 'use-ajax';
1188
        }
1189
        if (!empty($operation['class'])) {
1190
          $class[] = $operation['class'];
1191
        }
1192

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

    
1198
        $output[$location] .= l($operation['title'], $path, array('attributes' => array('id' => 'page-manager-operation-' . $id, 'class' => $class, 'title' => $description), 'html' => TRUE));
1199
        break;
1200
      case 'group':
1201
        if ($active == $id) {
1202
          $trail = $active_trail;
1203
          array_shift($trail);
1204
        }
1205
        else {
1206
          $trail = array();
1207
        }
1208
        $group_location = isset($operation['location']) ? $operation['location'] : $location;
1209
        $temp = page_manager_render_operations($page, $operation['children'], $trail, $operation, $group_location, array_merge($parents, array($id)));
1210
        if ($temp) {
1211
          foreach ($temp as $id => $text) {
1212
            if (empty($output[$id])) {
1213
              $output[$id] = '';
1214
            }
1215
            $output[$id] .= $text;
1216
          }
1217
        }
1218
        break;
1219
    }
1220

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

    
1226
  if ($output[$location]) {
1227
    $classes = isset($attributes['class']) && is_array($attributes['class']) ? $attributes['class'] : array();
1228
    $classes[] = 'page-manager-operations';
1229

    
1230
    $output[$location] = '<ul class="' . implode(' ', $classes) . '">' . $output[$location] . '</ul>';
1231

    
1232
    if (!empty($attributes['title'])) {
1233
      $class = '';
1234
      if (isset($attributes['title class'])) {
1235
        $class = $attributes['title class'];
1236
      }
1237
      $title = '<div class="page-manager-group-title' . $class . '">' . $attributes['title'] . '</div>';
1238

    
1239
      if (!empty($attributes['collapsible'])) {
1240
        $output[$location] = theme('ctools_collapsible', array('handle' => $title, 'content' => $output[$location], 'collapsed' => empty($active_trail)));
1241
      }
1242
      else {
1243
        $output[$location] = $title . $output[$location];
1244
      }
1245
    }
1246
    return $output;
1247
  }
1248
}
1249

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

    
1259
    // Always make sure we submit back to the proper page.
1260
    $form['#action'] = url('admin/structure/pages/edit/' . $form_state['page']->task_name);
1261
    $form['save'] = array(
1262
      '#type' => 'submit',
1263
      '#value' => t('Save'),
1264
      '#submit' => array('page_manager_save_page_form_submit'),
1265
    );
1266

    
1267
    $form['cancel'] = array(
1268
      '#type' => 'submit',
1269
      '#value' => t('Cancel'),
1270
      '#submit' => array('page_manager_save_page_form_cancel'),
1271
    );
1272
    return $form;
1273
  }
1274
}
1275

    
1276
/**
1277
 * Save the page.
1278
 */
1279
function page_manager_save_page_form_submit(&$form, &$form_state) {
1280
  page_manager_save_page_cache($form_state['page']);
1281
}
1282

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

    
1290
  if (!empty($form_state['page']->new)) {
1291
    $form_state['redirect'] = 'admin/structure/pages';
1292
  }
1293
}
1294

    
1295
// --------------------------------------------------------------------------
1296
// Handler (variant) related forms.
1297

    
1298
/**
1299
 * Add a new task handler.
1300
 */
1301
function page_manager_handler_add($form, &$form_state) {
1302
  // Get a list of possible task handlers for this task.
1303
  return page_manager_handler_add_form($form, $form_state);
1304
}
1305

    
1306
/**
1307
 * Handler related forms.
1308
 */
1309
function page_manager_handler_add_submit(&$form, &$form_state) {
1310
  $cache = $form_state['page'];
1311
  $plugin = page_manager_get_task_handler($form_state['values']['handler']);
1312

    
1313
  // Create a new handler.
1314
  $handler = page_manager_new_task_handler($plugin);
1315
  if (!empty($form_state['values']['title'])) {
1316
    $handler->conf['title'] = $form_state['values']['title'];
1317
  }
1318
  else {
1319
    $handler->conf['title'] = $plugin['title'];
1320
  }
1321
  $handler->conf['name'] = $form_state['values']['name'];
1322
  $cache->new_handler = $handler;
1323

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

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

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

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

    
1348
/**
1349
 * Finish the add process and make the new handler official.
1350
 */
1351
function page_manager_handler_add_finish(&$form_state) {
1352
  $page = &$form_state['page'];
1353
  $handler = $page->new_handler;
1354
  page_manager_handler_add_to_page($page, $handler);
1355

    
1356
  // Remove the temporary page.
1357
  unset($page->new_handler);
1358
  unset($page->forms);
1359

    
1360
  // Set the new destination
1361
  $plugin = page_manager_get_task_handler($handler->handler);
1362
  if (!empty($plugin['add finish'])) {
1363
    $location = $plugin['add finish'];
1364
  }
1365
  else {
1366
    $keys = array_keys($plugin['operations']);
1367
    $location = reset($keys);
1368
  }
1369

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

    
1372
  // Pass through.
1373
  page_manager_edit_page_finish($form_state);
1374
}
1375

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

    
1382
  // Remove the temporary page.
1383
  unset($page->new_handler);
1384
  unset($page->forms);
1385
}
1386

    
1387
/**
1388
 * Provide a consistent UI for adding handlers.
1389
 */
1390
function page_manager_handler_add_form($form, $form_state, $features = array()) {
1391
  $task = $form_state['task'];
1392
  $task_handler_plugins = page_manager_get_task_handler_plugins($task);
1393
  if (empty($task_handler_plugins)) {
1394
    drupal_set_message(t('There are currently no variants available and a page may not be added. Perhaps you need to install the Panels module to get a variant?'), 'error');
1395
    $form['buttons']['return']['#disabled'] = TRUE;
1396
    return;
1397
  }
1398

    
1399
  foreach ($task_handler_plugins as $id => $plugin) {
1400
    $options[$id] = $plugin['title'];
1401
    if (isset($plugin['add features'])) {
1402
      $features[$id] = $plugin['add features'];
1403
    }
1404
  }
1405

    
1406
  if (!isset($form_state['type']) || $form_state['type'] != 'add') {
1407
    $form['title'] = array(
1408
      '#type' => 'textfield',
1409
      '#title' => t('Title'),
1410
      '#description' => t('Administrative title of this variant. If you leave blank it will be automatically assigned.'),
1411
    );
1412

    
1413
    $form['name'] = array(
1414
      '#type' => 'machine_name',
1415
      '#title' => t('Machine name'),
1416
      '#required' => FALSE,
1417
      '#description' => t("A unique machine-readable name for this variant. It must only contain lowercase letters, numbers, and underscores. This name will be used when exporting the variant. If left empty the variant's name will be used instead."),
1418
      '#size' => 32,
1419
      '#maxlength' => 32,
1420
      '#machine_name' => array(
1421
        'exists' => 'page_manager_handler_check_machine_name',
1422
        'source' => array('title'),
1423
      ),
1424
      '#field_prefix' => '<span dir="ltr">' . $form_state['task_name'] . '__',
1425
      '#field_suffix' => '</span>&lrm;',
1426
    );
1427
  }
1428

    
1429
  $form['handler'] = array(
1430
    '#title' => t('Variant type'),
1431
    '#type' => 'select',
1432
    '#options' => $options,
1433
  );
1434

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

    
1443
  ctools_include('dependent');
1444
  foreach ($features as $plugin => $feature_list) {
1445
    foreach ($feature_list as $feature_id => $feature) {
1446
      $form['features'][$plugin][$feature_id] = array(
1447
        '#type' => 'checkbox',
1448
        '#title' => $feature,
1449
      );
1450
      if (!empty($form_state['page']->forms) && in_array($feature_id, $form_state['page']->forms)) {
1451
        $form['features'][$plugin][$feature_id]['#default_value'] = TRUE;
1452
      }
1453

    
1454
      if ($plugin != 'default') {
1455
        $form['features'][$plugin][$feature_id] += array(
1456
          '#dependency' => array('edit-handler' => array($plugin)),
1457
        );
1458
      }
1459
    }
1460
  }
1461

    
1462
  return $form;
1463
}
1464

    
1465
/*
1466
 * Check if handler's machine-name is unique
1467
 */
1468
function page_manager_handler_check_machine_name($name, $element, $form_state) {
1469
  $name = $form_state['task_name'] . '__' . $name;
1470

    
1471
  return count(ctools_export_load_object('page_manager_handlers', 'names', array($name)));
1472
}
1473

    
1474
/**
1475
 * Rearrange the order of variants.
1476
 */
1477
function page_manager_handler_import($form, &$form_state) {
1478
  $form['title'] = array(
1479
    '#type' => 'textfield',
1480
    '#title' => t('Variant name'),
1481
    '#description' => t('Enter the name of the new variant.'),
1482
  );
1483

    
1484
  if (user_access('use ctools import')) {
1485
    $form['object'] = array(
1486
      '#type' => 'textarea',
1487
      '#title' => t('Paste variant code here'),
1488
      '#rows' => 15,
1489
    );
1490
  }
1491
  // Users ordinarily can't get here without the 'import' permission, due to
1492
  // security implications. In case they somehow do, though, disable the form
1493
  // widget for extra safety.
1494
  else {
1495
    $form['shoveoff'] = array(
1496
      '#markup' => '<div>' . t('You do not have sufficient permissions to perform this action.') . '</div>',
1497
    );
1498
  }
1499

    
1500
  return $form;
1501
}
1502

    
1503
/**
1504
 * Make sure that an import actually provides a handler.
1505
 */
1506
function page_manager_handler_import_validate($form, &$form_state) {
1507
  if (!user_access('use ctools import')) {
1508
    form_error($form['shoveoff'], t('You account permissions do not permit you to import.'));
1509
    return;
1510
  }
1511
  ob_start();
1512
  eval($form_state['values']['object']);
1513
  ob_end_clean();
1514

    
1515
  if (empty($handler)) {
1516
    $errors = ob_get_contents();
1517
    if (empty($errors)) {
1518
      $errors = t('No variant found.');
1519
    }
1520

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

    
1524
  $form_state['handler'] = $handler;
1525
}
1526

    
1527
/**
1528
 * Clone an existing task handler into a new handler.
1529
 */
1530
function page_manager_handler_import_submit(&$form, &$form_state) {
1531
  $handler = $form_state['handler'];
1532

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

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

    
1541
/**
1542
 * Rearrange the order of variants.
1543
 */
1544
function page_manager_handler_rearrange($form, &$form_state) {
1545
  ctools_include('context-task-handler');
1546
  $page = $form_state['page'];
1547

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

    
1550
  // Get the number of variants to be displayed in order to set the delta
1551
  // to the proper value.  This fixes problems in previous versions with sorting
1552
  // large numbers of variants.
1553
  $delta = count($page->handler_info)/2 + 1;
1554

    
1555
  foreach ($page->handler_info as $id => $info) {
1556
    if ($info['changed'] & PAGE_MANAGER_CHANGED_DELETED) {
1557
      continue;
1558
    }
1559
    $handler = $page->handlers[$id];
1560
    $plugin = page_manager_get_task_handler($handler->handler);
1561
    $object = ctools_context_handler_get_task_object($page->task, $page->subtask, $handler);
1562
    $display = new stdClass();
1563
    $display->context = ctools_context_load_contexts($object, TRUE);
1564
    $content = page_manager_get_handler_title($plugin, $handler, $page->task, $page->subtask_id);
1565
    $access = ctools_access_group_summary(!empty($handler->conf['access']) ? $handler->conf['access'] : array(), $display->context);
1566
    if ($access) {
1567
      $access = t('This panel will be selected if @conditions.', array('@conditions' => $access));
1568
    }
1569
    else {
1570
      $access = t('This panel will always be selected.');
1571
    }
1572
    $content .= '<div>' . $access . '</div>';
1573
    $form['handlers'][$id]['title'] = array(
1574
      '#markup' => $content,
1575
    );
1576

    
1577
    $form['handlers'][$id]['weight'] = array(
1578
      '#type' => 'weight',
1579
      '#default_value' => $info['weight'],
1580
      '#delta' => $delta,
1581
    );
1582
  }
1583

    
1584
  return $form;
1585
}
1586

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

    
1590
  foreach ($form_state['values']['handlers'] as $id => $info) {
1591
    if ($handler_info[$id]['weight'] = $info['weight']) {
1592
      $handler_info[$id]['weight'] = $info['weight'];
1593
      $handler_info[$id]['changed'] |= PAGE_MANAGER_CHANGED_MOVED;
1594
    }
1595
  }
1596

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

    
1600
}
1601

    
1602
/**
1603
 * Used as a callback to uasort to sort the task cache by weight.
1604
 *
1605
 * The 'name' field is used as a backup when weights are the same, which
1606
 * can happen when multiple modules put items out there at the same
1607
 * weight.
1608
 */
1609
function _page_manager_handler_sort($a, $b) {
1610
  if ($a['weight'] < $b['weight']) {
1611
    return -1;
1612
  }
1613
  elseif ($a['weight'] > $b['weight']) {
1614
    return 1;
1615
  }
1616
  elseif ($a['name'] < $b['name']) {
1617
    return -1;
1618
  }
1619
  elseif ($a['name'] > $b['name']) {
1620
    return 1;
1621
  }
1622
}
1623

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

    
1638
  return $form;
1639
}
1640

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

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

    
1655
  $lines = substr_count($export, "\n");
1656
  $form['code'] = array(
1657
    '#type' => 'textarea',
1658
    '#default_value' => $export,
1659
    '#rows' => $lines,
1660
  );
1661

    
1662
  unset($form['buttons']);
1663
  return $form;
1664
}
1665

    
1666
/**
1667
 * Rearrange the order of variants.
1668
 */
1669
function page_manager_handler_clone($form, &$form_state) {
1670
  // This provides its own button because it does something totally different.
1671
  $form['title'] = array(
1672
    '#type' => 'textfield',
1673
    '#title' => t('Variant name'),
1674
    '#description' => t('Enter the name of the new variant.'),
1675
  );
1676

    
1677
  return $form;
1678
}
1679

    
1680
/**
1681
 * Clone an existing task handler into a new handler.
1682
 */
1683
function page_manager_handler_clone_submit(&$form, &$form_state) {
1684
  $export = page_manager_export_task_handler($form_state['handler']);
1685
  ob_start();
1686
  eval($export);
1687
  ob_end_clean();
1688

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

    
1691
  // Variant is cloned and added to the Page. Ensure the uuids are re-generated.
1692
  panels_panel_context_get_display($handler);
1693
  if (isset($handler->conf['display']) && method_exists($handler->conf['display'], 'clone_display')) {
1694
    $handler->conf['display'] = $handler->conf['display']->clone_display();
1695
  }
1696

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

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

    
1711
  return $form;
1712
}
1713

    
1714
/**
1715
 * Enable the page after it has been confirmed.
1716
 */
1717
function page_manager_handler_enable_submit(&$form, &$form_state) {
1718
  $form_state['handler']->disabled = FALSE;
1719
  $form_state['page']->handler_info[$form_state['handler_id']]['disabled'] = FALSE;
1720
  $form_state['page']->handler_info[$form_state['handler_id']]['changed'] |= PAGE_MANAGER_CHANGED_STATUS;
1721
  $form_state['new trail'] = array('handlers', $form_state['handler_id'], 'actions', 'disable');
1722
}
1723

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

    
1732
  return $form;
1733
}
1734

    
1735
/**
1736
 * Form to disable a page.
1737
 */
1738
function page_manager_handler_summary($form, &$form_state) {
1739
  $handler = $form_state['handler'];
1740
  $page = $form_state['page'];
1741
  $plugin = page_manager_get_task_handler($handler->handler);
1742

    
1743
  $form['markup'] = array(
1744
    '#markup' => page_manager_get_handler_summary($plugin, $handler, $page, FALSE),
1745
  );
1746

    
1747
  return $form;
1748
}
1749

    
1750
/**
1751
 * Disable the page after it has been confirmed.
1752
 */
1753
function page_manager_handler_disable_submit(&$form, &$form_state) {
1754
  $form_state['handler']->disabled = TRUE;
1755
  $form_state['page']->handler_info[$form_state['handler_id']]['disabled'] = TRUE;
1756
  $form_state['page']->handler_info[$form_state['handler_id']]['changed'] |= PAGE_MANAGER_CHANGED_STATUS;
1757
  $form_state['new trail'] = array('handlers', $form_state['handler_id'], 'actions', 'enable');
1758
}
1759

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

    
1768
  return $form;
1769
}
1770

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

    
1781
  $form_state['new trail'] = array('summary');
1782
}
1783

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

    
1792
  return $form;
1793
}
1794

    
1795
/**
1796
 * Enable the page after it has been confirmed.
1797
 */
1798
function page_manager_enable_form_submit(&$form, &$form_state) {
1799
  $page = &$form_state['page'];
1800
  if ($function = ctools_plugin_get_function($page->subtask, 'enable callback')) {
1801
    $result = $function($page, FALSE);
1802
    menu_rebuild();
1803
  }
1804
  $form_state['new trail'] = array('actions', 'disable');
1805

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

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

    
1821
  return $form;
1822
}
1823

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

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

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

    
1848
  $output = '';
1849

    
1850
/*
1851
  if (isset($form_state['subtask']['admin title'])) {
1852
    $form_state['title'] = $form_state['subtask']['admin title'];
1853
  }
1854
*/
1855

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

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

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

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

    
1871
      $output .= '<div class="handler-summary">';
1872
      $output .= page_manager_get_handler_summary($plugin, $handler, $page);
1873
      $output .= '</div>';
1874

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

    
1881
  $links = array(
1882
    array(
1883
      'title' => ' &raquo; ' . t('Add a new variant'),
1884
      'href' => page_manager_edit_url($page->task_name, array('actions', 'add')),
1885
      'html' => TRUE,
1886
    ),
1887
  );
1888

    
1889
  $output .= '<div class="links">' . theme('links', array('links' => $links)) . '</div>';
1890
  $form['markup'] = array(
1891
    '#markup' => $output,
1892
  );
1893

    
1894
  return $form;
1895
}
1896

    
1897
/**
1898
 * Menu callback to enable or disable a page
1899
 */
1900
function page_manager_enable_page($disable, $js, $page) {
1901
  if (!isset($_GET['token']) || !drupal_valid_token($_GET['token'], $page->task_name)) {
1902
    return MENU_ACCESS_DENIED;
1903
  }
1904
  if ($page->locked) {
1905
    if ($disable) {
1906
      drupal_set_message(t('Unable to disable due to lock.'));
1907
    }
1908
    else {
1909
      drupal_set_message(t('Unable to enable due to lock.'));
1910
    }
1911
  }
1912
  else {
1913
    if ($function = ctools_plugin_get_function($page->subtask, 'enable callback')) {
1914
      $result = $function($page, $disable);
1915
      menu_rebuild();
1916

    
1917
      // We want to re-cache this if it's changed so that status is properly
1918
      // updated on the changed form.
1919
      if (!empty($page->changed)) {
1920
        page_manager_set_page_cache($page);
1921
      }
1922
    }
1923
  }
1924

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