Projet

Général

Profil

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

root / drupal7 / sites / all / modules / ctools / plugins / export_ui / ctools_export_ui.class.php @ c304a780

1
<?php
2

    
3
/**
4
 * Base class for export UI.
5
 */
6
class ctools_export_ui {
7
  var $plugin;
8
  var $name;
9
  var $options = array();
10

    
11
  /**
12
   * Fake constructor -- this is easier to deal with than the real
13
   * constructor because we are retaining PHP4 compatibility, which
14
   * would require all child classes to implement their own constructor.
15
   */
16
  public function init($plugin) {
17
    ctools_include('export');
18

    
19
    $this->plugin = $plugin;
20
  }
21

    
22
  /**
23
   * Get a page title for the current page from our plugin strings.
24
   */
25
  public function get_page_title($op, $item = NULL) {
26
    if (empty($this->plugin['strings']['title'][$op])) {
27
      return;
28
    }
29

    
30
    // Replace %title that might be there with the exportable title.
31
    $title = $this->plugin['strings']['title'][$op];
32
    if (!empty($item)) {
33
      $export_key = $this->plugin['export']['key'];
34
      $title = (str_replace('%title', check_plain($item->{$export_key}), $title));
35
    }
36

    
37
    return $title;
38
  }
39

    
40
  /**
41
   * Called by ctools_export_ui_load to load the item.
42
   *
43
   * This can be overridden for modules that want to be able to export
44
   * items currently being edited, for example.
45
   */
46
  public function load_item($item_name) {
47
    $item = ctools_export_crud_load($this->plugin['schema'], $item_name);
48
    return empty($item) ? FALSE : $item;
49
  }
50

    
51
  // ------------------------------------------------------------------------
52
  // Menu item manipulation.
53

    
54
  /**
55
   * hook_menu() entry point.
56
   *
57
   * Child implementations that need to add or modify menu items should
58
   * probably call parent::hook_menu($items) and then modify as needed.
59
   */
60
  public function hook_menu(&$items) {
61
    // During upgrades, the schema can be empty as this is called prior to
62
    // actual update functions being run. Ensure that we can cope with this
63
    // situation.
64
    if (empty($this->plugin['schema'])) {
65
      return;
66
    }
67

    
68
    $prefix = ctools_export_ui_plugin_base_path($this->plugin);
69

    
70
    if (isset($this->plugin['menu']['items']) && is_array($this->plugin['menu']['items'])) {
71
      $my_items = array();
72
      foreach ($this->plugin['menu']['items'] as $item) {
73
        // Add menu item defaults.
74
        $item += array(
75
          'file' => 'export-ui.inc',
76
          'file path' => drupal_get_path('module', 'ctools') . '/includes',
77
        );
78

    
79
        $path = !empty($item['path']) ? $prefix . '/' . $item['path'] : $prefix;
80
        unset($item['path']);
81
        $my_items[$path] = $item;
82
      }
83
      $items += $my_items;
84
    }
85
  }
86

    
87
  /**
88
   * Menu callback to determine if an operation is accessible.
89
   *
90
   * This function enforces a basic access check on the configured perm
91
   * string, and then additional checks as needed.
92
   *
93
   * @param $op
94
   *   The 'op' of the menu item, which is defined by 'allowed operations'
95
   *   and embedded into the arguments in the menu item.
96
   * @param $item
97
   *   If an op that works on an item, then the item object, otherwise NULL.
98
   *
99
   * @return
100
   *   TRUE if the current user has access, FALSE if not.
101
   */
102
  public function access($op, $item) {
103
    if (!user_access($this->plugin['access'])) {
104
      return FALSE;
105
    }
106

    
107
    // More fine-grained access control:
108
    if ($op == 'add' && !user_access($this->plugin['create access'])) {
109
      return FALSE;
110
    }
111

    
112
    // More fine-grained access control:
113
    if (($op == 'revert' || $op == 'delete') && !user_access($this->plugin['delete access'])) {
114
      return FALSE;
115
    }
116

    
117
    // If we need to do a token test, do it here.
118
    if (!empty($this->plugin['allowed operations'][$op]['token']) && (!isset($_GET['token']) || !drupal_valid_token($_GET['token'], $op))) {
119
      return FALSE;
120
    }
121

    
122
    switch ($op) {
123
      case 'import':
124
        return user_access('use ctools import');
125

    
126
      case 'revert':
127
        return ($item->export_type & EXPORT_IN_DATABASE) && ($item->export_type & EXPORT_IN_CODE);
128

    
129
      case 'delete':
130
        return ($item->export_type & EXPORT_IN_DATABASE) && !($item->export_type & EXPORT_IN_CODE);
131

    
132
      case 'disable':
133
        return empty($item->disabled);
134

    
135
      case 'enable':
136
        return !empty($item->disabled);
137

    
138
      default:
139
        return TRUE;
140
    }
141
  }
142

    
143
  // ------------------------------------------------------------------------
144
  // These methods are the API for generating the list of exportable items.
145

    
146
  /**
147
   * Master entry point for handling a list.
148
   *
149
   * It is unlikely that a child object will need to override this method,
150
   * unless the listing mechanism is going to be highly specialized.
151
   */
152
  public function list_page($js, $input) {
153
    $this->items = ctools_export_crud_load_all($this->plugin['schema'], $js);
154

    
155
    // Respond to a reset command by clearing session and doing a drupal goto
156
    // back to the base URL.
157
    if (isset($input['op']) && $input['op'] == t('Reset')) {
158
      unset($_SESSION['ctools_export_ui'][$this->plugin['name']]);
159
      if (!$js) {
160
        drupal_goto($_GET['q']);
161
      }
162
      // Clear everything but form id, form build id and form token.
163
      $keys = array_keys($input);
164
      foreach ($keys as $id) {
165
        if (!in_array($id, array('form_id', 'form_build_id', 'form_token'))) {
166
          unset($input[$id]);
167
        }
168
      }
169
      $replace_form = TRUE;
170
    }
171

    
172
    // If there is no input, check to see if we have stored input in the
173
    // session.
174
    if (!isset($input['form_id'])) {
175
      if (isset($_SESSION['ctools_export_ui'][$this->plugin['name']]) && is_array($_SESSION['ctools_export_ui'][$this->plugin['name']])) {
176
        $input  = $_SESSION['ctools_export_ui'][$this->plugin['name']];
177
      }
178
    }
179
    else {
180
      $_SESSION['ctools_export_ui'][$this->plugin['name']] = $input;
181
      unset($_SESSION['ctools_export_ui'][$this->plugin['name']]['q']);
182
    }
183

    
184
    // This is where the form will put the output.
185
    $this->rows = array();
186
    $this->sorts = array();
187

    
188
    $form_state = array(
189
      'plugin' => $this->plugin,
190
      'input' => $input,
191
      'rerender' => TRUE,
192
      'no_redirect' => TRUE,
193
      'object' => &$this,
194
    );
195
    if (!isset($form_state['input']['form_id'])) {
196
      $form_state['input']['form_id'] = 'ctools_export_ui_list_form';
197
    }
198

    
199
    // If we do any form rendering, it's to completely replace a form on the
200
    // page, so don't let it force our ids to change.
201
    if ($js && isset($_POST['ajax_html_ids'])) {
202
      unset($_POST['ajax_html_ids']);
203
    }
204

    
205
    $form = drupal_build_form('ctools_export_ui_list_form', $form_state);
206
    $form = drupal_render($form);
207

    
208
    $output = $this->list_header($form_state) . $this->list_render($form_state) . $this->list_footer($form_state);
209

    
210
    if (!$js) {
211
      $this->list_css();
212
      return $form . $output;
213
    }
214

    
215
    $commands = array();
216
    $commands[] = ajax_command_replace('#ctools-export-ui-list-items', $output);
217
    if (!empty($replace_form)) {
218
      $commands[] = ajax_command_replace('#ctools-export-ui-list-form', $form);
219
    }
220
    print ajax_render($commands);
221
    ajax_footer();
222
  }
223

    
224
  /**
225
   * Create the filter/sort form at the top of a list of exports.
226
   *
227
   * This handles the very default conditions, and most lists are expected
228
   * to override this and call through to parent::list_form() in order to
229
   * get the base form and then modify it as necessary to add search
230
   * gadgets for custom fields.
231
   */
232
  public function list_form(&$form, &$form_state) {
233
    // This forces the form to *always* treat as submitted which is
234
    // necessary to make it work.
235
    $form['#token'] = FALSE;
236
    if (empty($form_state['input'])) {
237
      $form["#post"] = TRUE;
238
    }
239

    
240
    // Add the 'q' in if we are not using clean URLs or it can get lost when
241
    // using this kind of form.
242
    if (!variable_get('clean_url', FALSE)) {
243
      $form['q'] = array(
244
        '#type' => 'hidden',
245
        '#value' => $_GET['q'],
246
      );
247
    }
248

    
249
    $all = array('all' => t('- All -'));
250

    
251
    $form['top row'] = array(
252
      '#prefix' => '<div class="ctools-export-ui-row ctools-export-ui-top-row clearfix">',
253
      '#suffix' => '</div>',
254
    );
255

    
256
    $form['bottom row'] = array(
257
      '#prefix' => '<div class="ctools-export-ui-row ctools-export-ui-bottom-row clearfix">',
258
      '#suffix' => '</div>',
259
    );
260

    
261
    $form['top row']['storage'] = array(
262
      '#type' => 'select',
263
      '#title' => t('Storage'),
264
      '#options' => $all + array(
265
        t('Normal') => t('Normal'),
266
        t('Default') => t('Default'),
267
        t('Overridden') => t('Overridden'),
268
      ),
269
      '#default_value' => 'all',
270
    );
271

    
272
    $form['top row']['disabled'] = array(
273
      '#type' => 'select',
274
      '#title' => t('Enabled'),
275
      '#options' => $all + array(
276
        '0' => t('Enabled'),
277
        '1' => t('Disabled'),
278
      ),
279
      '#default_value' => 'all',
280
    );
281

    
282
    $form['top row']['search'] = array(
283
      '#type' => 'textfield',
284
      '#title' => t('Search'),
285
    );
286

    
287
    $form['bottom row']['order'] = array(
288
      '#type' => 'select',
289
      '#title' => t('Sort by'),
290
      '#options' => $this->list_sort_options(),
291
      '#default_value' => 'disabled',
292
    );
293

    
294
    $form['bottom row']['sort'] = array(
295
      '#type' => 'select',
296
      '#title' => t('Order'),
297
      '#options' => array(
298
        'asc' => t('Up'),
299
        'desc' => t('Down'),
300
      ),
301
      '#default_value' => 'asc',
302
    );
303

    
304
    $form['bottom row']['submit'] = array(
305
      '#type' => 'submit',
306
      '#id' => 'ctools-export-ui-list-items-apply',
307
      '#value' => t('Apply'),
308
      '#attributes' => array('class' => array('use-ajax-submit ctools-auto-submit-click')),
309
    );
310

    
311
    $form['bottom row']['reset'] = array(
312
      '#type' => 'submit',
313
      '#id' => 'ctools-export-ui-list-items-apply',
314
      '#value' => t('Reset'),
315
      '#attributes' => array('class' => array('use-ajax-submit')),
316
    );
317

    
318
    $form['#prefix'] = '<div class="clearfix">';
319
    $form['#suffix'] = '</div>';
320
    $form['#attached']['js'] = array(ctools_attach_js('auto-submit'));
321
    $form['#attached']['library'][] = array('system', 'drupal.ajax');
322
    $form['#attached']['library'][] = array('system', 'jquery.form');
323
    $form['#attributes'] = array('class' => array('ctools-auto-submit-full-form'));
324
  }
325

    
326
  /**
327
   * Validate the filter/sort form.
328
   *
329
   * It is very rare that a filter form needs validation, but if it is
330
   * needed, override this.
331
   */
332
  public function list_form_validate(&$form, &$form_state) { }
333

    
334
  /**
335
   * Submit the filter/sort form.
336
   *
337
   * This submit handler is actually responsible for building up all of the
338
   * rows that will later be rendered, since it is doing the filtering and
339
   * sorting.
340
   *
341
   * For the most part, you should not need to override this method, as the
342
   * fiddly bits call through to other functions.
343
   */
344
  public function list_form_submit(&$form, &$form_state) {
345
    // Filter and re-sort the pages.
346
    $plugin = $this->plugin;
347

    
348
    $prefix = ctools_export_ui_plugin_base_path($plugin);
349

    
350
    foreach ($this->items as $name => $item) {
351
      // Call through to the filter and see if we're going to render this
352
      // row. If it returns TRUE, then this row is filtered out.
353
      if ($this->list_filter($form_state, $item)) {
354
        continue;
355
      }
356

    
357
      $operations = $this->build_operations($item);
358

    
359
      $this->list_build_row($item, $form_state, $operations);
360
    }
361

    
362
    // Now actually sort
363
    if ($form_state['values']['sort'] == 'desc') {
364
      arsort($this->sorts);
365
    }
366
    else {
367
      asort($this->sorts);
368
    }
369

    
370
    // Nuke the original.
371
    $rows = $this->rows;
372
    $this->rows = array();
373
    // And restore.
374
    foreach ($this->sorts as $name => $title) {
375
      $this->rows[$name] = $rows[$name];
376
    }
377
  }
378

    
379
  /**
380
   * Determine if a row should be filtered out.
381
   *
382
   * This handles the default filters for the export UI list form. If you
383
   * added additional filters in list_form() then this is where you should
384
   * handle them.
385
   *
386
   * @return
387
   *   TRUE if the item should be excluded.
388
   */
389
  public function list_filter($form_state, $item) {
390
    $schema = ctools_export_get_schema($this->plugin['schema']);
391
    if ($form_state['values']['storage'] != 'all' && $form_state['values']['storage'] != $item->{$schema['export']['export type string']}) {
392
      return TRUE;
393
    }
394

    
395
    if ($form_state['values']['disabled'] != 'all' && $form_state['values']['disabled'] != !empty($item->disabled)) {
396
      return TRUE;
397
    }
398

    
399
    if ($form_state['values']['search']) {
400
      $search = strtolower($form_state['values']['search']);
401
      foreach ($this->list_search_fields() as $field) {
402
        if (strpos(strtolower($item->$field), $search) !== FALSE) {
403
          $hit = TRUE;
404
          break;
405
        }
406
      }
407
      if (empty($hit)) {
408
        return TRUE;
409
      }
410
    }
411
  }
412

    
413
  /**
414
   * Provide a list of fields to test against for the default "search" widget.
415
   *
416
   * This widget will search against whatever fields are configured here. By
417
   * default it will attempt to search against the name, title and description fields.
418
   */
419
  public function list_search_fields() {
420
    $fields = array(
421
      $this->plugin['export']['key'],
422
    );
423

    
424
    if (!empty($this->plugin['export']['admin_title'])) {
425
      $fields[] = $this->plugin['export']['admin_title'];
426
    }
427
    if (!empty($this->plugin['export']['admin_description'])) {
428
      $fields[] = $this->plugin['export']['admin_description'];
429
    }
430

    
431
    return $fields;
432
  }
433

    
434
  /**
435
   * Provide a list of sort options.
436
   *
437
   * Override this if you wish to provide more or change how these work.
438
   * The actual handling of the sorting will happen in build_row().
439
   */
440
  public function list_sort_options() {
441
    if (!empty($this->plugin['export']['admin_title'])) {
442
      $options = array(
443
        'disabled' => t('Enabled, title'),
444
        $this->plugin['export']['admin_title'] => t('Title'),
445
      );
446
    }
447
    else {
448
      $options = array(
449
        'disabled' => t('Enabled, name'),
450
      );
451
    }
452

    
453
    $options += array(
454
      'name' => t('Name'),
455
      'storage' => t('Storage'),
456
    );
457

    
458
    return $options;
459
  }
460

    
461
  /**
462
   * Add listing CSS to the page.
463
   *
464
   * Override this if you need custom CSS for your list.
465
   */
466
  public function list_css() {
467
    ctools_add_css('export-ui-list');
468
  }
469

    
470
  /**
471
   * Builds the operation links for a specific exportable item.
472
   */
473
  public function build_operations($item) {
474
    $plugin = $this->plugin;
475
    $schema = ctools_export_get_schema($plugin['schema']);
476
    $operations = $plugin['allowed operations'];
477
    $operations['import'] = FALSE;
478

    
479
    if ($item->{$schema['export']['export type string']} == t('Normal')) {
480
      $operations['revert'] = FALSE;
481
    }
482
    elseif ($item->{$schema['export']['export type string']} == t('Overridden')) {
483
      $operations['delete'] = FALSE;
484
    }
485
    else {
486
      $operations['revert'] = FALSE;
487
      $operations['delete'] = FALSE;
488
    }
489
    if (empty($item->disabled)) {
490
      $operations['enable'] = FALSE;
491
    }
492
    else {
493
      $operations['disable'] = FALSE;
494
    }
495

    
496
    $allowed_operations = array();
497

    
498
    foreach ($operations as $op => $info) {
499
      if (!empty($info)) {
500
        $allowed_operations[$op] = array(
501
          'title' => $info['title'],
502
          'href' => ctools_export_ui_plugin_menu_path($plugin, $op, $item->{$this->plugin['export']['key']}),
503
        );
504
        if (!empty($info['ajax'])) {
505
          $allowed_operations[$op]['attributes'] = array('class' => array('use-ajax'));
506
        }
507
        if (!empty($info['token'])) {
508
          $allowed_operations[$op]['query'] = array('token' => drupal_get_token($op));
509
        }
510
      }
511
    }
512

    
513
    return $allowed_operations;
514
  }
515

    
516
  /**
517
   * Build a row based on the item.
518
   *
519
   * By default all of the rows are placed into a table by the render
520
   * method, so this is building up a row suitable for theme('table').
521
   * This doesn't have to be true if you override both.
522
   */
523
  public function list_build_row($item, &$form_state, $operations) {
524
    // Set up sorting
525
    $name = $item->{$this->plugin['export']['key']};
526
    $schema = ctools_export_get_schema($this->plugin['schema']);
527

    
528
    // Note: $item->{$schema['export']['export type string']} should have already been set up by export.inc so
529
    // we can use it safely.
530
    switch ($form_state['values']['order']) {
531
      case 'disabled':
532
        $this->sorts[$name] = empty($item->disabled) . $name;
533
        break;
534
      case 'title':
535
        $this->sorts[$name] = $item->{$this->plugin['export']['admin_title']};
536
        break;
537
      case 'name':
538
        $this->sorts[$name] = $name;
539
        break;
540
      case 'storage':
541
        $this->sorts[$name] = $item->{$schema['export']['export type string']} . $name;
542
        break;
543
    }
544

    
545
    $this->rows[$name]['data'] = array();
546
    $this->rows[$name]['class'] = !empty($item->disabled) ? array('ctools-export-ui-disabled') : array('ctools-export-ui-enabled');
547

    
548
    // If we have an admin title, make it the first row.
549
    if (!empty($this->plugin['export']['admin_title'])) {
550
      $this->rows[$name]['data'][] = array('data' => check_plain($item->{$this->plugin['export']['admin_title']}), 'class' => array('ctools-export-ui-title'));
551
    }
552
    $this->rows[$name]['data'][] = array('data' => check_plain($name), 'class' => array('ctools-export-ui-name'));
553
    $this->rows[$name]['data'][] = array('data' => check_plain($item->{$schema['export']['export type string']}), 'class' => array('ctools-export-ui-storage'));
554

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

    
557
    $this->rows[$name]['data'][] = array('data' => $ops, 'class' => array('ctools-export-ui-operations'));
558

    
559
    // Add an automatic mouseover of the description if one exists.
560
    if (!empty($this->plugin['export']['admin_description'])) {
561
      $this->rows[$name]['title'] = $item->{$this->plugin['export']['admin_description']};
562
    }
563
  }
564

    
565
  /**
566
   * Provide the table header.
567
   *
568
   * If you've added columns via list_build_row() but are still using a
569
   * table, override this method to set up the table header.
570
   */
571
  public function list_table_header() {
572
    $header = array();
573
    if (!empty($this->plugin['export']['admin_title'])) {
574
      $header[] = array('data' => t('Title'), 'class' => array('ctools-export-ui-title'));
575
    }
576

    
577
    $header[] = array('data' => t('Name'), 'class' => array('ctools-export-ui-name'));
578
    $header[] = array('data' => t('Storage'), 'class' => array('ctools-export-ui-storage'));
579
    $header[] = array('data' => t('Operations'), 'class' => array('ctools-export-ui-operations'));
580

    
581
    return $header;
582
  }
583

    
584
  /**
585
   * Render all of the rows together.
586
   *
587
   * By default we place all of the rows in a table, and this should be the
588
   * way most lists will go.
589
   *
590
   * Whatever you do if this method is overridden, the ID is important for AJAX
591
   * so be sure it exists.
592
   */
593
  public function list_render(&$form_state) {
594
    $table = array(
595
      'header' => $this->list_table_header(),
596
      'rows' => $this->rows,
597
      'attributes' => array('id' => 'ctools-export-ui-list-items'),
598
      'empty' => $this->plugin['strings']['message']['no items'],
599
    );
600
    return theme('table', $table);
601
  }
602

    
603
  /**
604
   * Render a header to go before the list.
605
   *
606
   * This will appear after the filter/sort widgets.
607
   */
608
  public function list_header($form_state) { }
609

    
610
  /**
611
   * Render a footer to go after thie list.
612
   *
613
   * This is a good place to add additional links.
614
   */
615
  public function list_footer($form_state) { }
616

    
617
  // ------------------------------------------------------------------------
618
  // These methods are the API for adding/editing exportable items
619

    
620
  /**
621
   * Perform a drupal_goto() to the location provided by the plugin for the
622
   * operation.
623
   *
624
   * @param $op
625
   *   The operation to use. A string must exist in $this->plugin['redirect']
626
   *   for this operation.
627
   * @param $item
628
   *   The item in use; this may be necessary as item IDs are often embedded in
629
   *   redirects.
630
   */
631
  public function redirect($op, $item = NULL) {
632
    if (isset($this->plugin['redirect'][$op])) {
633
      $destination = (array) $this->plugin['redirect'][$op];
634
      if ($item) {
635
        $export_key = $this->plugin['export']['key'];
636
        $destination[0] = str_replace('%ctools_export_ui', $item->{$export_key}, $destination[0]);
637
      }
638
      call_user_func_array('drupal_goto', $destination);
639
    }
640
    else {
641
      // If the operation isn't set, fall back to the plugin's base path.
642
      drupal_goto(ctools_export_ui_plugin_base_path($this->plugin));
643
    }
644
  }
645

    
646
  public function add_page($js, $input, $step = NULL) {
647
    drupal_set_title($this->get_page_title('add'), PASS_THROUGH);
648

    
649
    // If a step not set, they are trying to create a new item. If a step
650
    // is set, they're in the process of creating an item.
651
    if (!empty($this->plugin['use wizard']) && !empty($step)) {
652
      $item = $this->edit_cache_get(NULL, 'add');
653
    }
654
    if (empty($item)) {
655
      $item = ctools_export_crud_new($this->plugin['schema']);
656
    }
657

    
658
    $form_state = array(
659
      'plugin' => $this->plugin,
660
      'object' => &$this,
661
      'ajax' => $js,
662
      'item' => $item,
663
      'op' => 'add',
664
      'form type' => 'add',
665
      'rerender' => TRUE,
666
      'no_redirect' => TRUE,
667
      'step' => $step,
668
      // Store these in case additional args are needed.
669
      'function args' => func_get_args(),
670
    );
671

    
672
    $output = $this->edit_execute_form($form_state);
673
    if (!empty($form_state['executed']) && empty($form_state['rebuild'])) {
674
      $this->redirect($form_state['op'], $form_state['item']);
675
    }
676

    
677
    return $output;
678
  }
679

    
680
  /**
681
   * Main entry point to edit an item.
682
   */
683
  public function edit_page($js, $input, $item, $step = NULL) {
684
    drupal_set_title($this->get_page_title('edit', $item), PASS_THROUGH);
685

    
686
    // Check to see if there is a cached item to get if we're using the wizard.
687
    if (!empty($this->plugin['use wizard'])) {
688
      $cached = $this->edit_cache_get($item, 'edit');
689
      if (!empty($cached)) {
690
        $item = $cached;
691
      }
692
    }
693

    
694
    $form_state = array(
695
      'plugin' => $this->plugin,
696
      'object' => &$this,
697
      'ajax' => $js,
698
      'item' => $item,
699
      'op' => 'edit',
700
      'form type' => 'edit',
701
      'rerender' => TRUE,
702
      'no_redirect' => TRUE,
703
      'step' => $step,
704
      // Store these in case additional args are needed.
705
      'function args' => func_get_args(),
706
    );
707

    
708
    $output = $this->edit_execute_form($form_state);
709
    if (!empty($form_state['executed']) && empty($form_state['rebuild'])) {
710
      $this->redirect($form_state['op'], $form_state['item']);
711
    }
712

    
713
    return $output;
714
  }
715

    
716
  /**
717
   * Main entry point to clone an item.
718
   */
719
  public function clone_page($js, $input, $original, $step = NULL) {
720
    drupal_set_title($this->get_page_title('clone', $original), PASS_THROUGH);
721

    
722
    // If a step not set, they are trying to create a new clone. If a step
723
    // is set, they're in the process of cloning an item.
724
    if (!empty($this->plugin['use wizard']) && !empty($step)) {
725
      $item = $this->edit_cache_get(NULL, 'clone');
726
    }
727
    if (empty($item)) {
728
      // To make a clone of an item, we first export it and then re-import it.
729
      // Export the handler, which is a fantastic way to clean database IDs out of it.
730
      $export = ctools_export_crud_export($this->plugin['schema'], $original);
731
      $item = ctools_export_crud_import($this->plugin['schema'], $export);
732

    
733
      if (!empty($input[$this->plugin['export']['key']])) {
734
        $item->{$this->plugin['export']['key']} = $input[$this->plugin['export']['key']];
735
      }
736
      else {
737
        $item->{$this->plugin['export']['key']} = 'clone_of_' . $item->{$this->plugin['export']['key']};
738
      }
739
    }
740

    
741
    // Tabs and breadcrumb disappearing, this helps alleviate through cheating.
742
    // ...not sure this this is the best way.
743
    $trail = menu_set_active_item(ctools_export_ui_plugin_base_path($this->plugin));
744

    
745
    $name = $original->{$this->plugin['export']['key']};
746

    
747
    $form_state = array(
748
      'plugin' => $this->plugin,
749
      'object' => &$this,
750
      'ajax' => $js,
751
      'item' => $item,
752
      'op' => 'add',
753
      'form type' => 'clone',
754
      'original name' => $name,
755
      'rerender' => TRUE,
756
      'no_redirect' => TRUE,
757
      'step' => $step,
758
      // Store these in case additional args are needed.
759
      'function args' => func_get_args(),
760
    );
761

    
762
    $output = $this->edit_execute_form($form_state);
763
    if (!empty($form_state['executed']) && empty($form_state['rebuild'])) {
764
      $this->redirect($form_state['op'], $form_state['item']);
765
    }
766

    
767
    return $output;
768
  }
769

    
770
  /**
771
   * Execute the form.
772
   *
773
   * Add and Edit both funnel into this, but they have a few different
774
   * settings.
775
   */
776
  public function edit_execute_form(&$form_state) {
777
    if (!empty($this->plugin['use wizard'])) {
778
      return $this->edit_execute_form_wizard($form_state);
779
    }
780
    else {
781
      return $this->edit_execute_form_standard($form_state);
782
    }
783
  }
784

    
785
  /**
786
   * Execute the standard form for editing.
787
   *
788
   * By default, export UI will provide a single form for editing an object.
789
   */
790
  public function edit_execute_form_standard(&$form_state) {
791
    $output = drupal_build_form('ctools_export_ui_edit_item_form', $form_state);
792
    if (!empty($form_state['executed']) && empty($form_state['rebuild'])) {
793
      $this->edit_save_form($form_state);
794
    }
795

    
796
    return $output;
797
  }
798

    
799
  /**
800
   * Get the form info for the wizard.
801
   *
802
   * This gets the form info out of the plugin, then adds defaults based on
803
   * how we want edit forms to work.
804
   *
805
   * Overriding this can allow child UIs to tweak this info for specialized
806
   * wizards.
807
   *
808
   * @param array $form_state
809
   *   The already created form state.
810
   */
811
  public function get_wizard_info(&$form_state) {
812
    if (!isset($form_state['step'])) {
813
      $form_state['step'] = NULL;
814
    }
815

    
816
    $export_key = $this->plugin['export']['key'];
817

    
818
    // When cloning, the name of the item being cloned is referenced in the
819
    // path, not the name of this item.
820
    if ($form_state['form type'] == 'clone') {
821
      $name = $form_state['original name'];
822
    }
823
    else {
824
      $name = $form_state['item']->{$export_key};
825
    }
826

    
827
    $form_info = !empty($this->plugin['form info']) ? $this->plugin['form info'] : array();
828
    $form_info += array(
829
      'id' => 'ctools_export_ui_edit',
830
      'path' => ctools_export_ui_plugin_menu_path($this->plugin, $form_state['form type'], $name) . '/%step',
831
      'show trail' => TRUE,
832
      'free trail' => TRUE,
833
      'show back' => $form_state['form type'] == 'add',
834
      'show return' => FALSE,
835
      'show cancel' => TRUE,
836
      'finish callback' => 'ctools_export_ui_wizard_finish',
837
      'next callback' => 'ctools_export_ui_wizard_next',
838
      'back callback' => 'ctools_export_ui_wizard_back',
839
      'cancel callback' => 'ctools_export_ui_wizard_cancel',
840
      'order' => array(),
841
      'import order' => array(
842
        'import' => t('Import code'),
843
        'settings' => t('Settings'),
844
      ),
845
    );
846

    
847
    // Set the order of forms based on the op if we have a specific one.
848
    if (isset($form_info[$form_state['form type'] . ' order'])) {
849
      $form_info['order'] = $form_info[$form_state['form type'] . ' order'];
850
    }
851

    
852
    // We have generic fallback forms we can use if they are not specified,
853
    // and they automatically delegate back to the UI object. Use these if
854
    // not specified.
855
    foreach ($form_info['order'] as $key => $title) {
856
      if (empty($form_info['forms'][$key])) {
857
        $form_info['forms'][$key] = array(
858
          'form id' => 'ctools_export_ui_edit_item_wizard_form',
859
        );
860
      }
861
    }
862

    
863
    // 'free trail' means the wizard can freely go back and form from item
864
    // via the trail and not with next/back buttons.
865
    if ($form_state['form type'] == 'add' || ($form_state['form type'] == 'import' && empty($form_state['item']->{$export_key}))) {
866
      $form_info['free trail'] = FALSE;
867
    }
868

    
869
    return $form_info;
870
  }
871

    
872
  /**
873
   * Execute the wizard for editing.
874
   *
875
   * For complex objects, sometimes a wizard is needed. This is normally
876
   * activated by setting 'use wizard' => TRUE in the plugin definition
877
   * and then creating a 'form info' array to feed the wizard the data
878
   * it needs.
879
   *
880
   * When creating this wizard, the plugin is responsible for defining all forms
881
   * that will be utilized with the wizard.
882
   *
883
   * Using 'add order' or 'edit order' can be used to ensure that add/edit order
884
   * is different.
885
   */
886
  public function edit_execute_form_wizard(&$form_state) {
887
    $form_info = $this->get_wizard_info($form_state);
888

    
889
    // If there aren't any forms set, fail.
890
    if (empty($form_info['order'])) {
891
      return MENU_NOT_FOUND;
892
    }
893

    
894
    // Figure out if this is a new instance of the wizard
895
    if (empty($form_state['step'])) {
896
      $order = array_keys($form_info['order']);
897
      $form_state['step'] = reset($order);
898
    }
899

    
900
    if (empty($form_info['order'][$form_state['step']]) && empty($form_info['forms'][$form_state['step']])) {
901
      return MENU_NOT_FOUND;
902
    }
903

    
904
    ctools_include('wizard');
905
    $output = ctools_wizard_multistep_form($form_info, $form_state['step'], $form_state);
906
    if (!empty($form_state['complete'])) {
907
      $this->edit_save_form($form_state);
908
    }
909
    elseif ($output && !empty($form_state['item']->export_ui_item_is_cached)) {
910
      // @todo this should be in the plugin strings
911
      drupal_set_message(t('You have unsaved changes. These changes will not be made permanent until you click <em>Save</em>.'), 'warning');
912
    }
913

    
914
    // Unset the executed flag if any non-wizard button was pressed. Those
915
    // buttons require special handling by whatever client is operating them.
916
    if (!empty($form_state['executed']) && empty($form_state['clicked_button']['#wizard type'])) {
917
      unset($form_state['executed']);
918
    }
919
    return $output;
920
  }
921

    
922
  /**
923
   * Wizard 'back' callback when using a wizard to edit an item.
924
   *
925
   * The wizard callback delegates this back to the object.
926
   */
927
  public function edit_wizard_back(&$form_state) {
928
    // This only exists so child implementations can use it.
929
  }
930

    
931
  /**
932
   * Wizard 'next' callback when using a wizard to edit an item.
933
   *
934
   * The wizard callback delegates this back to the object.
935
   */
936
  public function edit_wizard_next(&$form_state) {
937
    $this->edit_cache_set($form_state['item'], $form_state['form type']);
938
  }
939

    
940
  /**
941
   * Wizard 'cancel' callback when using a wizard to edit an item.
942
   *
943
   * The wizard callback delegates this back to the object.
944
   */
945
  public function edit_wizard_cancel(&$form_state) {
946
    $this->edit_cache_clear($form_state['item'], $form_state['form type']);
947
  }
948

    
949
  /**
950
   * Wizard 'cancel' callback when using a wizard to edit an item.
951
   *
952
   * The wizard callback delegates this back to the object.
953
   */
954
  public function edit_wizard_finish(&$form_state) {
955
    $form_state['complete'] = TRUE;
956

    
957
    // If we are importing, and overwrite was selected, delete the original so
958
    // that this one writes properly.
959
    if ($form_state['form type'] == 'import' && !empty($form_state['item']->export_ui_allow_overwrite)) {
960
      ctools_export_crud_delete($this->plugin['schema'], $form_state['item']);
961
    }
962

    
963
    $this->edit_cache_clear($form_state['item'], $form_state['form type']);
964
  }
965

    
966
  /**
967
   * Retrieve the item currently being edited from the object cache.
968
   */
969
  public function edit_cache_get($item, $op = 'edit') {
970
    ctools_include('object-cache');
971
    if (is_string($item)) {
972
      $name = $item;
973
    }
974
    else {
975
      $name = $this->edit_cache_get_key($item, $op);
976
    }
977

    
978
    $cache = ctools_object_cache_get('ctui_' . $this->plugin['name'], $name);
979
    if ($cache) {
980
      $cache->export_ui_item_is_cached = TRUE;
981
      return $cache;
982
    }
983
  }
984

    
985
  /**
986
   * Cache the item currently currently being edited.
987
   */
988
  public function edit_cache_set($item, $op = 'edit') {
989
    ctools_include('object-cache');
990
    $name = $this->edit_cache_get_key($item, $op);
991
    return $this->edit_cache_set_key($item, $name);
992
  }
993

    
994
  public function edit_cache_set_key($item, $name) {
995
    return ctools_object_cache_set('ctui_' . $this->plugin['name'], $name, $item);
996
  }
997

    
998
  /**
999
   * Clear the object cache for the currently edited item.
1000
   */
1001
  public function edit_cache_clear($item, $op = 'edit') {
1002
    ctools_include('object-cache');
1003
    $name = $this->edit_cache_get_key($item, $op);
1004
    return ctools_object_cache_clear('ctui_' . $this->plugin['name'], $name);
1005
  }
1006

    
1007
  /**
1008
   * Figure out what the cache key is for this object.
1009
   */
1010
  public function edit_cache_get_key($item, $op) {
1011
    $export_key = $this->plugin['export']['key'];
1012
    return $op == 'edit' ? $item->{$this->plugin['export']['key']} : "::$op";
1013
  }
1014

    
1015
  /**
1016
   * Called to save the final product from the edit form.
1017
   */
1018
  public function edit_save_form($form_state) {
1019
    $item = &$form_state['item'];
1020
    $export_key = $this->plugin['export']['key'];
1021

    
1022
    $result = ctools_export_crud_save($this->plugin['schema'], $item);
1023

    
1024
    if ($result) {
1025
      $message = str_replace('%title', check_plain($item->{$export_key}), $this->plugin['strings']['confirmation'][$form_state['op']]['success']);
1026
      drupal_set_message($message);
1027
    }
1028
    else {
1029
      $message = str_replace('%title', check_plain($item->{$export_key}), $this->plugin['strings']['confirmation'][$form_state['op']]['fail']);
1030
      drupal_set_message($message, 'error');
1031
    }
1032
  }
1033

    
1034
  /**
1035
   * Provide the actual editing form.
1036
   */
1037
  public function edit_form(&$form, &$form_state) {
1038
    $export_key = $this->plugin['export']['key'];
1039
    $item = $form_state['item'];
1040
    $schema = ctools_export_get_schema($this->plugin['schema']);
1041

    
1042
    if (!empty($this->plugin['export']['admin_title'])) {
1043
      $form['info'][$this->plugin['export']['admin_title']] = array(
1044
        '#type' => 'textfield',
1045
        '#title' => t('Administrative title'),
1046
        '#description' => t('This will appear in the administrative interface to easily identify it.'),
1047
        '#default_value' => $item->{$this->plugin['export']['admin_title']},
1048
      );
1049
    }
1050

    
1051
    $form['info'][$export_key] = array(
1052
      '#title' => t($schema['export']['key name']),
1053
      '#type' => 'textfield',
1054
      '#default_value' => $item->{$export_key},
1055
      '#description' => t('The unique ID for this @export.', array('@export' => $this->plugin['title singular'])),
1056
      '#required' => TRUE,
1057
      '#maxlength' => 255,
1058
    );
1059

    
1060
    if (!empty($this->plugin['export']['admin_title'])) {
1061
      $form['info'][$export_key]['#type'] = 'machine_name';
1062
      $form['info'][$export_key]['#machine_name'] = array(
1063
        'exists' => 'ctools_export_ui_edit_name_exists',
1064
        'source' => array('info', $this->plugin['export']['admin_title']),
1065
      );
1066
    }
1067

    
1068
    if ($form_state['op'] === 'edit') {
1069
      $form['info'][$export_key]['#disabled'] = TRUE;
1070
      $form['info'][$export_key]['#value'] = $item->{$export_key};
1071
    }
1072

    
1073
    if (!empty($this->plugin['export']['admin_description'])) {
1074
      $form['info'][$this->plugin['export']['admin_description']] = array(
1075
        '#type' => 'textarea',
1076
        '#title' => t('Administrative description'),
1077
        '#default_value' => $item->{$this->plugin['export']['admin_description']},
1078
      );
1079
    }
1080

    
1081
    // Add plugin's form definitions.
1082
    if (!empty($this->plugin['form']['settings'])) {
1083
      // Pass $form by reference.
1084
      $this->plugin['form']['settings']($form, $form_state);
1085
    }
1086

    
1087
    // Add the buttons if the wizard is not in use.
1088
    if (empty($form_state['form_info'])) {
1089
      // Make sure that whatever happens, the buttons go to the bottom.
1090
      $form['buttons']['#weight'] = 100;
1091

    
1092
      // Add buttons.
1093
      $form['buttons']['submit'] = array(
1094
        '#type' => 'submit',
1095
        '#value' => t('Save'),
1096
      );
1097

    
1098
      $form['buttons']['delete'] = array(
1099
        '#type' => 'submit',
1100
        '#value' => $item->export_type & EXPORT_IN_CODE ? t('Revert') : t('Delete'),
1101
        '#access' => $form_state['op'] === 'edit' && $item->export_type & EXPORT_IN_DATABASE,
1102
        '#submit' => array('ctools_export_ui_edit_item_form_delete'),
1103
      );
1104
    }
1105
  }
1106

    
1107
  /**
1108
   * Validate callback for the edit form.
1109
   */
1110
  public function edit_form_validate(&$form, &$form_state) {
1111
    if (!empty($this->plugin['form']['validate'])) {
1112
      // Pass $form by reference.
1113
      $this->plugin['form']['validate']($form, $form_state);
1114
    }
1115
  }
1116

    
1117
  /**
1118
   * Perform a final validation check before allowing the form to be
1119
   * finished.
1120
   */
1121
  public function edit_finish_validate(&$form, &$form_state) {
1122
    if ($form_state['op'] != 'edit') {
1123
      // Validate the export key. Fake an element for form_error().
1124
      $export_key = $this->plugin['export']['key'];
1125
      $element = array(
1126
        '#value' => $form_state['item']->{$export_key},
1127
        '#parents' => array($export_key),
1128
      );
1129
      $form_state['plugin'] = $this->plugin;
1130
      ctools_export_ui_edit_name_validate($element, $form_state);
1131
    }
1132
  }
1133

    
1134
  /**
1135
   * Handle the submission of the edit form.
1136
   *
1137
   * At this point, submission is successful. Our only responsibility is
1138
   * to copy anything out of values onto the item that we are able to edit.
1139
   *
1140
   * If the keys all match up to the schema, this method will not need to be
1141
   * overridden.
1142
   */
1143
  public function edit_form_submit(&$form, &$form_state) {
1144
    if (!empty($this->plugin['form']['submit'])) {
1145
      // Pass $form by reference.
1146
      $this->plugin['form']['submit']($form, $form_state);
1147
    }
1148

    
1149
    // Transfer data from the form to the $item based upon schema values.
1150
    $schema = ctools_export_get_schema($this->plugin['schema']);
1151
    foreach (array_keys($schema['fields']) as $key) {
1152
      if(isset($form_state['values'][$key])) {
1153
        $form_state['item']->{$key} = $form_state['values'][$key];
1154
      }
1155
    }
1156
  }
1157

    
1158
  // ------------------------------------------------------------------------
1159
  // These methods are the API for 'other' stuff with exportables such as
1160
  // enable, disable, import, export, delete
1161

    
1162
  /**
1163
   * Callback to enable a page.
1164
   */
1165
  public function enable_page($js, $input, $item) {
1166
    return $this->set_item_state(FALSE, $js, $input, $item);
1167
  }
1168

    
1169
  /**
1170
   * Callback to disable a page.
1171
   */
1172
  public function disable_page($js, $input, $item) {
1173
    return $this->set_item_state(TRUE, $js, $input, $item);
1174
  }
1175

    
1176
  /**
1177
   * Set an item's state to enabled or disabled and output to user.
1178
   *
1179
   * If javascript is in use, this will rebuild the list and send that back
1180
   * as though the filter form had been executed.
1181
   */
1182
  public function set_item_state($state, $js, $input, $item) {
1183
    ctools_export_crud_set_status($this->plugin['schema'], $item, $state);
1184

    
1185
    if (!$js) {
1186
      drupal_goto(ctools_export_ui_plugin_base_path($this->plugin));
1187
    }
1188
    else {
1189
      return $this->list_page($js, $input);
1190
    }
1191
  }
1192

    
1193
  /**
1194
   * Page callback to delete an exportable item.
1195
   */
1196
  public function delete_page($js, $input, $item) {
1197
    $form_state = array(
1198
      'plugin' => $this->plugin,
1199
      'object' => &$this,
1200
      'ajax' => $js,
1201
      'item' => $item,
1202
      'op' => $item->export_type & EXPORT_IN_CODE ? 'revert' : 'delete',
1203
      'rerender' => TRUE,
1204
      'no_redirect' => TRUE,
1205
    );
1206

    
1207
    $output = drupal_build_form('ctools_export_ui_delete_confirm_form', $form_state);
1208
    if (!empty($form_state['executed'])) {
1209
      $this->delete_form_submit($form_state);
1210
      $this->redirect($form_state['op'], $item);
1211
    }
1212

    
1213
    return $output;
1214
  }
1215

    
1216
  /**
1217
   * Deletes exportable items from the database.
1218
   */
1219
  public function delete_form_submit(&$form_state) {
1220
    $item = $form_state['item'];
1221

    
1222
    ctools_export_crud_delete($this->plugin['schema'], $item);
1223
    $export_key = $this->plugin['export']['key'];
1224
    $message = str_replace('%title', check_plain($item->{$export_key}), $this->plugin['strings']['confirmation'][$form_state['op']]['success']);
1225
    drupal_set_message($message);
1226
  }
1227

    
1228
  /**
1229
   * Page callback to display export information for an exportable item.
1230
   */
1231
  public function export_page($js, $input, $item) {
1232
    drupal_set_title($this->get_page_title('export', $item), PASS_THROUGH);
1233
    return drupal_get_form('ctools_export_form', ctools_export_crud_export($this->plugin['schema'], $item), t('Export'));
1234
  }
1235

    
1236
  /**
1237
   * Page callback to import information for an exportable item.
1238
   */
1239
  public function import_page($js, $input, $step = NULL) {
1240
    drupal_set_title($this->get_page_title('import'), PASS_THROUGH);
1241
    // Import is basically a multi step wizard form, so let's go ahead and
1242
    // use CTools' wizard.inc for it.
1243

    
1244
    // If a step not set, they are trying to create a new item. If a step
1245
    // is set, they're in the process of creating an item.
1246
    if (!empty($step)) {
1247
      $item = $this->edit_cache_get(NULL, 'import');
1248
    }
1249
    if (empty($item)) {
1250
      $item = ctools_export_crud_new($this->plugin['schema']);
1251
    }
1252

    
1253
    $form_state = array(
1254
      'plugin' => $this->plugin,
1255
      'object' => &$this,
1256
      'ajax' => $js,
1257
      'item' => $item,
1258
      'op' => 'add',
1259
      'form type' => 'import',
1260
      'rerender' => TRUE,
1261
      'no_redirect' => TRUE,
1262
      'step' => $step,
1263
      // Store these in case additional args are needed.
1264
      'function args' => func_get_args(),
1265
    );
1266

    
1267
    // import always uses the wizard.
1268
    $output = $this->edit_execute_form_wizard($form_state);
1269
    if (!empty($form_state['executed'])) {
1270
      $this->redirect($form_state['op'], $form_state['item']);
1271
    }
1272

    
1273
    return $output;
1274
  }
1275

    
1276
  /**
1277
   * Import form. Provides simple helptext instructions and textarea for
1278
   * pasting a export definition.
1279
   */
1280
  public function edit_form_import(&$form, &$form_state) {
1281
    $form['help'] = array(
1282
      '#type' => 'item',
1283
      '#value' => $this->plugin['strings']['help']['import'],
1284
    );
1285

    
1286
    $form['import'] = array(
1287
      '#title' => t('@plugin code', array('@plugin' => $this->plugin['title singular proper'])),
1288
      '#type' => 'textarea',
1289
      '#rows' => 10,
1290
      '#required' => TRUE,
1291
      '#default_value' => !empty($form_state['item']->export_ui_code) ? $form_state['item']->export_ui_code : '',
1292
    );
1293

    
1294
    $form['overwrite'] = array(
1295
      '#title' => t('Allow import to overwrite an existing record.'),
1296
      '#type' => 'checkbox',
1297
      '#default_value' => !empty($form_state['item']->export_ui_allow_overwrite) ? $form_state['item']->export_ui_allow_overwrite : FALSE,
1298
    );
1299
  }
1300

    
1301
  /**
1302
   * Import form validate handler.
1303
   *
1304
   * Evaluates code and make sure it creates an object before we continue.
1305
   */
1306
  public function edit_form_import_validate($form, &$form_state) {
1307
    $item = ctools_export_crud_import($this->plugin['schema'], $form_state['values']['import']);
1308
    if (is_string($item)) {
1309
      form_error($form['import'], t('Unable to get an import from the code. Errors reported: @errors', array('@errors' => $item)));
1310
      return;
1311
    }
1312

    
1313
    $form_state['item'] = $item;
1314
    $form_state['item']->export_ui_allow_overwrite = $form_state['values']['overwrite'];
1315
    $form_state['item']->export_ui_code = $form_state['values']['import'];
1316
  }
1317

    
1318
  /**
1319
   * Submit callback for import form.
1320
   *
1321
   * Stores the item in the session.
1322
   */
1323
  public function edit_form_import_submit($form, &$form_state) {
1324
    // The validate function already imported and stored the item. This
1325
    // function exists simply to prevent it from going to the default
1326
    // edit_form_submit() method.
1327
  }
1328
}
1329

    
1330
// -----------------------------------------------------------------------
1331
// Forms to be used with this class.
1332
//
1333
// Since Drupal's forms are completely procedural, these forms will
1334
// mostly just be pass-throughs back to the object.
1335

    
1336
/**
1337
 * Add all appropriate includes to forms so that caching the form
1338
 * still loads the files that we need.
1339
 */
1340
function _ctools_export_ui_add_form_files($form, &$form_state) {
1341
  ctools_form_include($form_state, 'export');
1342
  ctools_form_include($form_state, 'export-ui');
1343

    
1344
  // Also make sure the plugin .inc file is loaded.
1345
  ctools_form_include_file($form_state, $form_state['object']->plugin['path'] . '/' . $form_state['object']->plugin['file']);
1346
}
1347

    
1348
/**
1349
 * Form callback to handle the filter/sort form when listing items.
1350
 *
1351
 * This simply loads the object defined in the plugin and hands it off.
1352
 */
1353
function ctools_export_ui_list_form($form, &$form_state) {
1354
  $form_state['object']->list_form($form, $form_state);
1355
  return $form;
1356
}
1357

    
1358
/**
1359
 * Validate handler for ctools_export_ui_list_form.
1360
 */
1361
function ctools_export_ui_list_form_validate(&$form, &$form_state) {
1362
  $form_state['object']->list_form_validate($form, $form_state);
1363
}
1364

    
1365
/**
1366
 * Submit handler for ctools_export_ui_list_form.
1367
 */
1368
function ctools_export_ui_list_form_submit(&$form, &$form_state) {
1369
  $form_state['object']->list_form_submit($form, $form_state);
1370
}
1371

    
1372
/**
1373
 * Form callback to edit an exportable item.
1374
 *
1375
 * This simply loads the object defined in the plugin and hands it off.
1376
 */
1377
function ctools_export_ui_edit_item_form($form, &$form_state) {
1378
  // When called using #ajax via ajax_form_callback(), 'export' may
1379
  // not be included so include it here.
1380
  _ctools_export_ui_add_form_files($form, $form_state);
1381

    
1382
  $form_state['object']->edit_form($form, $form_state);
1383
  return $form;
1384
}
1385

    
1386
/**
1387
 * Validate handler for ctools_export_ui_edit_item_form.
1388
 */
1389
function ctools_export_ui_edit_item_form_validate(&$form, &$form_state) {
1390
  $form_state['object']->edit_form_validate($form, $form_state);
1391
}
1392

    
1393
/**
1394
 * Submit handler for ctools_export_ui_edit_item_form.
1395
 */
1396
function ctools_export_ui_edit_item_form_submit(&$form, &$form_state) {
1397
  $form_state['object']->edit_form_submit($form, $form_state);
1398
}
1399

    
1400
/**
1401
 * Submit handler to delete for ctools_export_ui_edit_item_form
1402
 *
1403
 * @todo Put this on a callback in the object.
1404
 */
1405
function ctools_export_ui_edit_item_form_delete(&$form, &$form_state) {
1406
  _ctools_export_ui_add_form_files($form, $form_state);
1407

    
1408
  $export_key = $form_state['plugin']['export']['key'];
1409
  $path = $form_state['item']->export_type & EXPORT_IN_CODE ? 'revert' : 'delete';
1410

    
1411
  drupal_goto(ctools_export_ui_plugin_menu_path($form_state['plugin'], $path, $form_state['item']->{$export_key}), array('cancel_path' => $_GET['q']));
1412
}
1413

    
1414
/**
1415
 * Validate that an export item name is acceptable and unique during add.
1416
 */
1417
function ctools_export_ui_edit_name_validate($element, &$form_state) {
1418
  $plugin = $form_state['plugin'];
1419
  // Check for string identifier sanity
1420
  if (!preg_match('!^[a-z0-9_]+$!', $element['#value'])) {
1421
    form_error($element, t('The export id can only consist of lowercase letters, underscores, and numbers.'));
1422
    return;
1423
  }
1424

    
1425
  // Check for name collision
1426
  if (empty($form_state['item']->export_ui_allow_overwrite) && $exists = ctools_export_crud_load($plugin['schema'], $element['#value'])) {
1427
    form_error($element, t('A @plugin with this name already exists. Please choose another name or delete the existing item before creating a new one.', array('@plugin' => $plugin['title singular'])));
1428
  }
1429
}
1430

    
1431
/**
1432
 * Test for #machine_name type to see if an export exists.
1433
 */
1434
function ctools_export_ui_edit_name_exists($name, $element, &$form_state) {
1435
  $plugin = $form_state['plugin'];
1436

    
1437
  return (empty($form_state['item']->export_ui_allow_overwrite) && ctools_export_crud_load($plugin['schema'], $name));
1438
}
1439

    
1440
/**
1441
 * Delete/Revert confirm form.
1442
 *
1443
 * @todo -- call back into the object instead.
1444
 */
1445
function ctools_export_ui_delete_confirm_form($form, &$form_state) {
1446
  _ctools_export_ui_add_form_files($form, $form_state);
1447

    
1448
  $plugin = $form_state['plugin'];
1449
  $item = $form_state['item'];
1450

    
1451
  $form = array();
1452

    
1453
  $export_key = $plugin['export']['key'];
1454
  $question = str_replace('%title', check_plain($item->{$export_key}), $plugin['strings']['confirmation'][$form_state['op']]['question']);
1455
  $path = (!empty($_REQUEST['cancel_path']) && !url_is_external($_REQUEST['cancel_path'])) ? $_REQUEST['cancel_path'] : ctools_export_ui_plugin_base_path($plugin);
1456

    
1457
  $form = confirm_form($form,
1458
    $question,
1459
    $path,
1460
    $plugin['strings']['confirmation'][$form_state['op']]['information'],
1461
    $plugin['allowed operations'][$form_state['op']]['title'], t('Cancel')
1462
  );
1463
  return $form;
1464
}
1465

    
1466
// --------------------------------------------------------------------------
1467
// Forms and callbacks for using the edit system with the wizard.
1468

    
1469
/**
1470
 * Form callback to edit an exportable item using the wizard
1471
 *
1472
 * This simply loads the object defined in the plugin and hands it off.
1473
 */
1474
function ctools_export_ui_edit_item_wizard_form($form, &$form_state) {
1475
  _ctools_export_ui_add_form_files($form, $form_state);
1476

    
1477
  $method = 'edit_form_' . $form_state['step'];
1478
  if (!method_exists($form_state['object'], $method)) {
1479
    $method = 'edit_form';
1480
  }
1481

    
1482
  $form_state['object']->$method($form, $form_state);
1483
  return $form;
1484
}
1485

    
1486
/**
1487
 * Validate handler for ctools_export_ui_edit_item_wizard_form.
1488
 */
1489
function ctools_export_ui_edit_item_wizard_form_validate(&$form, &$form_state) {
1490
  $method = 'edit_form_' . $form_state['step'] . '_validate';
1491
  if (!method_exists($form_state['object'], $method)) {
1492
    $method = 'edit_form_validate';
1493
  }
1494

    
1495
  $form_state['object']->$method($form, $form_state);
1496

    
1497
  // Additionally, if there were no errors from that, and we're finishing,
1498
  // perform a final validate to make sure everything is ok.
1499
  if (isset($form_state['clicked_button']['#wizard type']) && $form_state['clicked_button']['#wizard type'] == 'finish' && !form_get_errors()) {
1500
    $form_state['object']->edit_finish_validate($form, $form_state);
1501
  }
1502
}
1503

    
1504
/**
1505
 * Submit handler for ctools_export_ui_edit_item_wizard_form.
1506
 */
1507
function ctools_export_ui_edit_item_wizard_form_submit(&$form, &$form_state) {
1508
  $method = 'edit_form_' . $form_state['step'] . '_submit';
1509
  if (!method_exists($form_state['object'], $method)) {
1510
    $method = 'edit_form_submit';
1511
  }
1512

    
1513
  $form_state['object']->$method($form, $form_state);
1514
}
1515

    
1516
/**
1517
 * Wizard 'back' callback when using a wizard to edit an item.
1518
 */
1519
function ctools_export_ui_wizard_back(&$form_state) {
1520
  $form_state['object']->edit_wizard_back($form_state);
1521
}
1522

    
1523
/**
1524
 * Wizard 'next' callback when using a wizard to edit an item.
1525
 */
1526
function ctools_export_ui_wizard_next(&$form_state) {
1527
  $form_state['object']->edit_wizard_next($form_state);
1528
}
1529

    
1530
/**
1531
 * Wizard 'cancel' callback when using a wizard to edit an item.
1532
 */
1533
function ctools_export_ui_wizard_cancel(&$form_state) {
1534
  $form_state['object']->edit_wizard_cancel($form_state);
1535
}
1536

    
1537
/**
1538
 * Wizard 'finish' callback when using a wizard to edit an item.
1539
 */
1540
function ctools_export_ui_wizard_finish(&$form_state) {
1541
  $form_state['object']->edit_wizard_finish($form_state);
1542
}