Projet

Général

Profil

Paste
Télécharger (37,6 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / feeds / feeds_ui / feeds_ui.admin.inc @ 2c8c2b87

1
<?php
2

    
3
/**
4
 * @file
5
 * Contains all page callbacks, forms and theming functions for Feeds
6
 * administrative pages.
7
 */
8

    
9
/**
10
 * Introductory help for admin/structure/feeds/%feeds_importer page
11
 */
12
function feeds_ui_edit_help() {
13
  return t('
14
    <p>
15
    You can create as many Feeds importer configurations as you would like to. Each can have a distinct purpose like letting your users aggregate RSS feeds or importing a CSV file for content migration. Here are a couple of things that are important to understand in order to get started with Feeds:
16
    </p>
17
    <ul>
18
    <li>
19
    Every importer configuration consists of basic settings, a fetcher, a parser and a processor and their settings.
20
    </li>
21
    <li>
22
    The <strong>basic settings</strong> define the general behavior of the importer. <strong>Fetchers</strong> are responsible for loading data, <strong>parsers</strong> for organizing it and <strong>processors</strong> for "doing stuff" with it, usually storing it.
23
    </li>
24
    <li>
25
    In Basic settings, you can <strong>attach an importer configuration to a content type</strong>. This is useful when many imports of a kind should be created, for example in an RSS aggregation scenario. If you don\'t attach a configuration to a content type, you can use it on the !import page.
26
    </li>
27
    <li>
28
    Imports can be <strong>scheduled periodically</strong> - see the periodic import select box in the Basic settings.
29
    </li>
30
    <li>
31
    Processors can have <strong>mappings</strong> in addition to settings. Mappings allow you to define what elements of a data feed should be mapped to what content fields on a granular level. For instance, you can specify that a feed item\'s author should be mapped to a node\'s body.
32
    </li>
33
    </ul>
34
    ', array('!import' => l(t('Import'), 'import')));
35
}
36

    
37
/**
38
 * Help text for mapping.
39
 */
40
function feeds_ui_mapping_help() {
41
  return t('
42
  <p>
43
  Define which elements of a single item of a feed (= <em>Sources</em>) map to which content pieces in Drupal (= <em>Targets</em>). Make sure that at least one definition has a <em>Unique target</em>. A unique target means that a value for a target can only occur once. E. g. only one item with the URL <em>http://example.com/content/1</em> can exist.
44
  </p>
45
  ');
46
}
47

    
48
/**
49
 * Build overview of available configurations.
50
 */
51
function feeds_ui_overview_form($form, &$form_status) {
52
  $form = $form['enabled'] = $form['disabled'] = array();
53

    
54
  $form['#header'] = array(
55
    t('Name'),
56
    t('Description'),
57
    t('Attached to'),
58
    t('Status'),
59
    t('Operations'),
60
    t('Enabled'),
61
  );
62
  foreach (feeds_importer_load_all(TRUE) as $importer) {
63
    $importer_form = array();
64
    $importer_form['name']['#markup'] = check_plain($importer->config['name']);
65
    $importer_form['description']['#markup'] = check_plain($importer->config['description']);
66
    if (empty($importer->config['content_type'])) {
67
      $importer_form['attached']['#markup'] = '[none]';
68
    }
69
    else {
70
      if (!$importer->disabled) {
71
        $importer_form['attached']['#markup'] = l(node_type_get_name($importer->config['content_type']), 'node/add/' . str_replace('_', '-', $importer->config['content_type']));
72
      }
73
      else {
74
        $importer_form['attached']['#markup'] = check_plain(node_type_get_name($importer->config['content_type']));
75
      }
76
    }
77

    
78
    if ($importer->export_type == EXPORT_IN_CODE) {
79
      $status = t('Default');
80
      $edit = t('Override');
81
      $delete = '';
82
    }
83
    elseif ($importer->export_type == EXPORT_IN_DATABASE) {
84
      $status = t('Normal');
85
      $edit = t('Edit');
86
      $delete = t('Delete');
87
    }
88
    elseif ($importer->export_type == (EXPORT_IN_CODE | EXPORT_IN_DATABASE)) {
89
      $status = t('Overridden');
90
      $edit = t('Edit');
91
      $delete = t('Revert');
92
    }
93
    $importer_form['status'] = array(
94
      '#markup' => $status,
95
    );
96
    $importer_form['operations'] = array(
97
      '#markup' =>
98
        l($edit, 'admin/structure/feeds/' . $importer->id) . ' | ' .
99
        l(t('Export'), 'admin/structure/feeds/' . $importer->id . '/export') . ' | ' .
100
        l(t('Clone'), 'admin/structure/feeds/' . $importer->id . '/clone') .
101
        (empty($delete) ? '' :  ' | ' . l($delete, 'admin/structure/feeds/' . $importer->id . '/delete')),
102
    );
103

    
104
    $importer_form[$importer->id] = array(
105
      '#type' => 'checkbox',
106
      '#default_value' => !$importer->disabled,
107
    );
108

    
109
    if ($importer->disabled) {
110
      $form['disabled'][$importer->id] = $importer_form;
111
    }
112
    else {
113
      $form['enabled'][$importer->id] = $importer_form;
114
    }
115
  }
116
  $form['submit'] = array(
117
    '#type' => 'submit',
118
    '#value' => t('Save'),
119
  );
120
  return $form;
121
}
122

    
123
/**
124
 * Submit handler for feeds_ui_overview_form().
125
 */
126
function feeds_ui_overview_form_submit($form, &$form_state) {
127

    
128
  $disabled = array();
129
  foreach (feeds_importer_load_all(TRUE) as $importer) {
130
    $disabled[$importer->id] = !$form_state['values'][$importer->id];
131
  }
132
  variable_set('default_feeds_importer', $disabled);
133
  feeds_cache_clear();
134
}
135

    
136
/**
137
 * Create a new configuration.
138
 *
139
 * @param $form_state
140
 *  Form API form state array.
141
 * @param $from_importer
142
 *   FeedsImporter object. If given, form will create a new importer as a copy
143
 *   of $from_importer.
144
 */
145
function feeds_ui_create_form($form, &$form_state, $from_importer = NULL) {
146
  $form['#from_importer'] = $from_importer;
147
  $form['name'] = array(
148
    '#type' => 'textfield',
149
    '#title' => t('Name'),
150
    '#description' => t('A natural name for this configuration. Example: RSS Feed. You can always change this name later.'),
151
    '#required' => TRUE,
152
    '#maxlength' => 128,
153
  );
154
  $form['id'] = array(
155
    '#type' => 'machine_name',
156
    '#required' => TRUE,
157
    '#maxlength' => 128,
158
    '#machine_name' => array(
159
      'exists' => 'feeds_ui_importer_machine_name_exists',
160
    ),
161
  );
162
  $form['description'] = array(
163
    '#type' => 'textfield',
164
    '#title' => t('Description'),
165
    '#description' => t('A description of this configuration.'),
166
  );
167
  $form['submit'] = array(
168
    '#type' => 'submit',
169
    '#value' => t('Create'),
170
  );
171
  return $form;
172
}
173

    
174
/**
175
 * Validation callback for the importer machine name field.
176
 */
177
function feeds_ui_importer_machine_name_exists($id) {
178
  if ($id == 'create') {
179
    // Create is a reserved path for the add importer form.
180
    return TRUE;
181
  }
182
  ctools_include('export');
183
  if (ctools_export_load_object('feeds_importer', 'conditions', array('id' => $id))) {
184
    return TRUE;
185
  }
186
}
187

    
188
/**
189
 * Validation handler for feeds_build_create_form().
190
 */
191
function feeds_ui_create_form_validate($form, &$form_state) {
192
  if (!empty($form_state['values']['id'])) {
193
    $importer = feeds_importer($form_state['values']['id']);
194
    $importer->configFormValidate($form_state['values']);
195
  }
196
}
197

    
198
/**
199
 * Submit handler for feeds_build_create_form().
200
 */
201
function feeds_ui_create_form_submit($form, &$form_state) {
202
  // Create feed.
203
  $importer = feeds_importer($form_state['values']['id']);
204
  // If from_importer is given, copy its configuration.
205
  if (!empty($form['#from_importer'])) {
206
    $importer->copy($form['#from_importer']);
207
  }
208
  // In any case, we want to set this configuration's title and description.
209
  $importer->addConfig($form_state['values']);
210
  $importer->save();
211

    
212
  // Set a message and redirect to settings form.
213
  if (empty($form['#from_importer'])) {
214
    drupal_set_message(t('Your configuration has been created with default settings. If they do not fit your use case you can adjust them here.'));
215
  }
216
  else {
217
    drupal_set_message(t('A clone of the @name configuration has been created.', array('@name' => $form['#from_importer']->config['name'])));
218
  }
219
  $form_state['redirect'] = 'admin/structure/feeds/' . $importer->id;
220
  feeds_cache_clear();
221
}
222

    
223
/**
224
 * Delete configuration form.
225
 */
226
function feeds_ui_delete_form($form, &$form_state, $importer) {
227
  $form['#importer'] = $importer->id;
228
  if ($importer->export_type & EXPORT_IN_CODE) {
229
    $title = t('Would you really like to revert the importer @importer?', array('@importer' => $importer->config['name']));
230
    $button_label = t('Revert');
231
  }
232
  else {
233
    $title = t('Would you really like to delete the importer @importer?', array('@importer' => $importer->config['name']));
234
    $button_label = t('Delete');
235
  }
236
  return confirm_form(
237
    $form,
238
    $title,
239
    'admin/structure/feeds',
240
    t('This action cannot be undone.'),
241
    $button_label
242
  );
243
}
244

    
245
/**
246
 * Submit handler for feeds_ui_delete_form().
247
 */
248
function feeds_ui_delete_form_submit($form, &$form_state) {
249
  $form_state['redirect'] = 'admin/structure/feeds';
250

    
251
  // Remove importer.
252
  feeds_importer($form['#importer'])->delete();
253

    
254
  // Clear cache, deleting a configuration may have an affect on menu tree.
255
  feeds_cache_clear();
256
}
257

    
258
/**
259
 * Export a feed configuration.
260
 */
261
function feeds_ui_export_form($form, &$form_state, $importer) {
262
  $code = feeds_export($importer->id);
263

    
264
  $form['export'] = array(
265
    '#title' => t('Export feed configuration'),
266
    '#type' => 'textarea',
267
    '#value' => $code,
268
    '#rows' => substr_count($code, "\n"),
269
  );
270
  return $form;
271
}
272

    
273
/**
274
 * Edit feed configuration.
275
 */
276
function feeds_ui_edit_page($importer, $active = 'help', $plugin_key = '') {
277

    
278
  // Get plugins and configuration.
279
  $plugins = FeedsPlugin::all();
280
  $config = $importer->config;
281
  // Base path for changing the active container.
282
  $path = 'admin/structure/feeds/' . $importer->id;
283

    
284
  $active_container = array(
285
    'class' => array('active-container'),
286
    'actions' => array(l(t('Help'), $path)),
287
  );
288
  switch ($active) {
289
    case 'help':
290
      $active_container['title'] = t('Getting started');
291
      $active_container['body'] = '<div class="help feeds-admin-ui">' . feeds_ui_edit_help() . '</div>';
292
      unset($active_container['actions']);
293
      break;
294
    case 'fetcher':
295
    case 'parser':
296
    case 'processor':
297
      $active_container['title'] = t('Select a !plugin_type', array('!plugin_type' => $active));
298
      $active_container['body'] = drupal_get_form('feeds_ui_plugin_form', $importer, $active);
299
      break;
300
    case 'settings':
301
      drupal_add_js(drupal_get_path('module', 'ctools') . '/js/dependent.js');
302
      ctools_include('dependent');
303
      if (empty($plugin_key)) {
304
        $active_container['title'] = t('Basic settings');
305
        $active_container['body'] = feeds_get_form($importer, 'configForm');
306
      }
307
      // feeds_plugin() returns a correct result because feed has been
308
      // instantiated previously.
309
      elseif (in_array($plugin_key, array_keys($plugins)) && $plugin = feeds_plugin($plugin_key, $importer->id)) {
310
        $active_container['title'] = t('Settings for !plugin', array('!plugin' => $plugins[$plugin_key]['name']));
311
        $active_container['body'] = feeds_get_form($plugin, 'configForm');
312
      }
313
      break;
314
    case 'mapping':
315
      $active_container['title'] = t('Mapping for !processor', array('!processor' => $plugins[$config['processor']['plugin_key']]['name']));
316
      $active_container['body'] = drupal_get_form('feeds_ui_mapping_form', $importer);
317
      break;
318
  }
319

    
320
  // Build config info.
321
  $config_info = $info = array();
322
  $info['class'] = array('config-set');
323

    
324
  // Basic information.
325
  $items = array();
326
  $items[] = t('Attached to: @type', array('@type' => $importer->config['content_type'] ? node_type_get_name($importer->config['content_type']) : t('[none]')));
327
  if ($importer->config['import_period'] == FEEDS_SCHEDULE_NEVER) {
328
    $import_period = t('off');
329
  }
330
  elseif ($importer->config['import_period'] == 0) {
331
    $import_period = t('as often as possible');
332
  }
333
  else {
334
    $import_period = t('every !interval', array('!interval' => format_interval($importer->config['import_period'])));
335
  }
336
  $items[] = t('Periodic import: !import_period', array('!import_period' => $import_period));
337
  $items[] = $importer->config['import_on_create'] ? t('Import on submission') : t('Do not import on submission');
338

    
339
  $info['title'] = t('Basic settings');
340
  $info['body'] = array(
341
    array(
342
      'body' => theme('item_list', array('items' => $items)),
343
      'actions' => array(l(t('Settings'), $path . '/settings')),
344
    ),
345
  );
346
  $config_info[] = $info;
347

    
348
  // Fetcher.
349
  $fetcher = $plugins[$config['fetcher']['plugin_key']];
350
  $actions = array();
351
  if (feeds_get_form($importer->fetcher, 'configForm')) {
352
    $actions = array(l(t('Settings'), $path . '/settings/' . $config['fetcher']['plugin_key']));
353
  }
354
  $info['title'] = t('Fetcher');
355
  $info['body'] = array(
356
    array(
357
      'title' => $fetcher['name'],
358
      'body' => $fetcher['description'],
359
      'actions' => $actions,
360
    ),
361
  );
362
  $info['actions'] = array(l(t('Change'), $path . '/fetcher'));
363
  $config_info[] = $info;
364

    
365
  // Parser.
366
  $parser = $plugins[$config['parser']['plugin_key']];
367
  $actions = array();
368
  if (feeds_get_form($importer->parser, 'configForm')) {
369
    $actions = array(l(t('Settings'), $path . '/settings/' . $config['parser']['plugin_key']));
370
  }
371
  $info['title'] = t('Parser');
372
  $info['body'] = array(
373
    array(
374
      'title' => $parser['name'],
375
      'body' => $parser['description'],
376
      'actions' => $actions,
377
    )
378
  );
379
  $info['actions'] = array(l(t('Change'), $path . '/parser'));
380
  $config_info[] = $info;
381

    
382
  // Processor.
383
  $processor = $plugins[$config['processor']['plugin_key']];
384
  $actions = array();
385
  if (feeds_get_form($importer->processor, 'configForm')) {
386
    $actions[] = l(t('Settings'), $path . '/settings/' . $config['processor']['plugin_key']);
387
  }
388
  $actions[] = l(t('Mapping'), $path . '/mapping');
389
  $info['title'] = t('Processor');
390
  $info['body'] = array(
391
    array(
392
      'title' => $processor['name'],
393
      'body' => $processor['description'],
394
      'actions' => $actions,
395
    )
396
  );
397
  $info['actions'] = array(l(t('Change'), $path . '/processor'));
398
  $config_info[] = $info;
399

    
400
  return theme('feeds_ui_edit_page', array(
401
    'info' => $config_info,
402
    'active' => $active_container,
403
  ));
404
}
405

    
406
/**
407
 * Build a form of plugins to pick from.
408
 *
409
 * @param $form_state
410
 *   Form API form state array.
411
 * @param $importer
412
 *   FeedsImporter object.
413
 * @param $type
414
 *   Plugin type. One of 'fetcher', 'parser', 'processor'.
415
 *
416
 * @return
417
 *   A Form API form definition.
418
 */
419
function feeds_ui_plugin_form($form, &$form_state, $importer, $type) {
420
  $plugins = FeedsPlugin::byType($type);
421

    
422
  $form['#importer'] = $importer->id;
423
  $form['#plugin_type'] = $type;
424

    
425
  $importer_key = $importer->config[$type]['plugin_key'];
426

    
427
  foreach ($plugins as $key => $plugin) {
428

    
429
    $form['plugin_key'][$key] = array(
430
      '#type' => 'radio',
431
      '#parents' => array('plugin_key'),
432
      '#title' => check_plain($plugin['name']),
433
      '#description' => filter_xss(isset($plugin['help']) ? $plugin['help'] : $plugin['description']),
434
      '#return_value' => $key,
435
      '#default_value' => ($key == $importer_key) ? $key : '',
436
    );
437
  }
438
  $form['submit'] = array(
439
    '#type' => 'submit',
440
    '#value' => t('Save'),
441
  );
442
  return $form;
443
}
444

    
445
/**
446
 * Submit handler for feeds_ui_plugin_form().
447
 */
448
function feeds_ui_plugin_form_submit($form, &$form_state) {
449
  // Set the plugin and save feed.
450
  $importer = feeds_importer($form['#importer']);
451
  $importer->setPlugin($form_state['values']['plugin_key']);
452
  $importer->save();
453
  drupal_set_message(t('Changed @type plugin.', array('@type' => $form['#plugin_type'])));
454
}
455

    
456
/**
457
 * Theme feeds_ui_plugin_form().
458
 */
459
function theme_feeds_ui_plugin_form($variables) {
460
  $form = $variables['form'];
461
  $output = '';
462

    
463
  foreach (element_children($form['plugin_key']) as $key) {
464

    
465
    // Assemble container, render form elements.
466
    $container = array(
467
      'title' => $form['plugin_key'][$key]['#title'],
468
      'body' => isset($form['plugin_key'][$key]['#description']) ? $form['plugin_key'][$key]['#description'] : '',
469
    );
470
    $form['plugin_key'][$key]['#title'] = t('Select');
471
    $form['plugin_key'][$key]['#attributes']['class'] = array('feeds-ui-radio-link');
472
    unset($form['plugin_key'][$key]['#description']);
473
    $container['actions'] = array(drupal_render($form['plugin_key'][$key]));
474

    
475
    $output .= theme('feeds_ui_container', array('container' => $container));
476
  }
477

    
478
  $output .= drupal_render_children($form);
479
  return $output;
480
}
481

    
482
/**
483
 * Edit mapping.
484
 *
485
 * @todo Completely merge this into config form handling. This is just a
486
 *   shared form of configuration, most of the common functionality can live in
487
 *   FeedsProcessor, a flag can tell whether mapping is supported or not.
488
 */
489
function feeds_ui_mapping_form($form, &$form_state, $importer) {
490
  $form['#importer'] = $importer->id;
491
  $form['#mappings'] = $mappings = $importer->processor->getMappings();
492
  $form['help']['#markup'] = feeds_ui_mapping_help();
493
  $form['#prefix'] = '<div id="feeds-ui-mapping-form-wrapper">';
494
  $form['#suffix'] = '</div>';
495

    
496
  // Get mapping sources from parsers and targets from processor, format them
497
  // for output.
498
  // Some parsers do not define mapping sources but let them define on the fly.
499
  if ($sources = $importer->parser->getMappingSources()) {
500
    $source_options = _feeds_ui_format_options($sources);
501
    foreach ($sources as $k => $source) {
502
      $legend['sources'][$k]['name']['#markup'] = empty($source['name']) ? $k : $source['name'];
503
      $legend['sources'][$k]['description']['#markup'] = empty($source['description']) ? '' : $source['description'];
504
    }
505
  }
506
  else {
507
    $legend['sources']['#markup'] = t('This parser supports free source definitions. Enter the name of the source field in lower case into the Source text field above.');
508
  }
509
  $targets = $importer->processor->getMappingTargets();
510
  $target_options = _feeds_ui_format_options($targets);
511
  $legend['targets'] = array();
512
  foreach ($targets as $k => $target) {
513
    $legend['targets'][$k]['name']['#markup'] = empty($target['name']) ? $k : $target['name'];
514
    $legend['targets'][$k]['description']['#markup'] = empty($target['description']) ? '' : $target['description'];
515
  }
516

    
517
  // Legend explaining source and target elements.
518
  $form['legendset'] = array(
519
    '#type' => 'fieldset',
520
    '#title' => t('Legend'),
521
    '#collapsible' => TRUE,
522
    '#collapsed' => TRUE,
523
    '#tree' => TRUE,
524
  );
525
  $form['legendset']['legend'] = $legend;
526

    
527
  // Add config forms and remove flags to mappings.
528
  $form['config'] = $form['remove_flags'] = $form['mapping_weight'] = array(
529
    '#tree' => TRUE,
530
  );
531
  if (is_array($mappings)) {
532

    
533
    $delta = count($mappings) + 2;
534

    
535
    foreach ($mappings as $i => $mapping) {
536
      if (isset($targets[$mapping['target']])) {
537
        $form['config'][$i] = feeds_ui_mapping_settings_form($form, $form_state, $i, $mapping, $targets[$mapping['target']]);
538
      }
539

    
540
      $form['remove_flags'][$i] = array(
541
        '#type' => 'checkbox',
542
        '#title' => t('Remove'),
543
        '#prefix' => '<div class="feeds-ui-checkbox-link">',
544
        '#suffix' => '</div>',
545
      );
546

    
547
      $form['mapping_weight'][$i] = array(
548
        '#type' => 'weight',
549
        '#title' => '',
550
        '#default_value' => $i,
551
        '#delta' => $delta,
552
        '#attributes' => array(
553
          'class' => array(
554
            'feeds-ui-mapping-weight'
555
          ),
556
        ),
557
      );
558
    }
559
  }
560

    
561
  if (isset($source_options)) {
562
    $form['source'] = array(
563
      '#type' => 'select',
564
      '#title' => t('Source'),
565
      '#title_display' => 'invisible',
566
      '#options' => $source_options,
567
      '#empty_option' => t('- Select a source -'),
568
      '#description' => t('An element from the feed.'),
569
    );
570
  }
571
  else {
572
    $form['source'] = array(
573
      '#type' => 'textfield',
574
      '#title' => t('Source'),
575
      '#title_display' => 'invisible',
576
      '#size' => 20,
577
      '#default_value' => '',
578
      '#description' => t('The name of source field.'),
579
    );
580
  }
581
  $form['target'] = array(
582
    '#type' => 'select',
583
    '#title' => t('Target'),
584
    '#title_display' => 'invisible',
585
    '#options' => $target_options,
586
    '#empty_option' => t('- Select a target -'),
587
    '#description' => t('The field that stores the data.'),
588
  );
589

    
590
  $form['actions'] = array('#type' => 'actions');
591
  $form['actions']['save'] = array(
592
    '#type' => 'submit',
593
    '#value' => t('Save'),
594
  );
595
  return $form;
596
}
597

    
598
/**
599
 * Per mapper configuration form that is a part of feeds_ui_mapping_form().
600
 */
601
function feeds_ui_mapping_settings_form($form, $form_state, $i, $mapping, $target) {
602
  $form_state += array(
603
    'mapping_settings_edit' => NULL,
604
    'mapping_settings' => array(),
605
  );
606

    
607
  $base_button = array(
608
    '#submit' => array('feeds_ui_mapping_form_multistep_submit'),
609
    '#ajax' => array(
610
      'callback' => 'feeds_ui_mapping_settings_form_callback',
611
      'wrapper' => 'feeds-ui-mapping-form-wrapper',
612
      'effect' => 'fade',
613
      'progress' => 'none',
614
    ),
615
    '#i' => $i,
616
  );
617

    
618
  if (isset($form_state['mapping_settings'][$i])) {
619
    $mapping = $form_state['mapping_settings'][$i] + $mapping;
620
  }
621

    
622
  if ($form_state['mapping_settings_edit'] === $i) {
623
    // Build the form.
624
    if (isset($target['form_callback'])) {
625
      $settings_form = call_user_func($target['form_callback'], $mapping, $target, $form, $form_state);
626
    }
627
    else {
628
      $settings_form = array();
629
    }
630

    
631
    // Merge in the optional unique form.
632
    $settings_form += feeds_ui_mapping_settings_optional_unique_form($mapping, $target, $form, $form_state);
633

    
634
    return array(
635
      '#type' => 'container',
636
      'settings' => $settings_form,
637
      'save_settings' => $base_button + array(
638
        '#type' => 'submit',
639
        '#name' => 'mapping_settings_update_' . $i,
640
        '#value' => t('Update'),
641
        '#op' => 'update',
642
      ),
643
      'cancel_settings' => $base_button + array(
644
        '#type' => 'submit',
645
        '#name' => 'mapping_settings_cancel_' . $i,
646
        '#value' => t('Cancel'),
647
        '#op' => 'cancel',
648
      ),
649
    );
650
  }
651
  else {
652
    // Build the summary.
653
    if (isset($target['summary_callback'])) {
654
      $summary = call_user_func($target['summary_callback'], $mapping, $target, $form, $form_state);
655
    }
656
    else {
657
      $summary = '';
658
    }
659

    
660
    // Append the optional unique summary.
661
    if ($optional_unique_summary = feeds_ui_mapping_settings_optional_unique_summary($mapping, $target, $form, $form_state)) {
662
      $summary .= ' ' . $optional_unique_summary;
663
    }
664

    
665
    if ($summary) {
666
      return array(
667
        'summary' => array(
668
          '#prefix' => '<div>',
669
          '#markup' => $summary,
670
          '#suffix' => '</div>',
671
        ),
672
       'edit_settings' => $base_button + array(
673
          '#type' => 'image_button',
674
          '#name' => 'mapping_settings_edit_' . $i,
675
          '#src' => 'misc/configure.png',
676
          '#attributes' => array('alt' => t('Edit')),
677
          '#op' => 'edit',
678
        ),
679
      );
680
    }
681
  }
682
}
683

    
684
/**
685
 * Submit callback for a per mapper configuration form. Switches between edit
686
 * and summary mode.
687
 */
688
function feeds_ui_mapping_form_multistep_submit($form, &$form_state) {
689
  $trigger = $form_state['triggering_element'];
690

    
691
  switch ($trigger['#op']) {
692
    case 'edit':
693
      $form_state['mapping_settings_edit'] = $trigger['#i'];
694
      break;
695

    
696
    case 'update':
697
      $values = $form_state['values']['config'][$trigger['#i']]['settings'];
698
      $form_state['mapping_settings'][$trigger['#i']] = $values;
699
      unset($form_state['mapping_settings_edit']);
700
      break;
701

    
702
    case 'cancel':
703
      unset($form_state['mapping_settings_edit']);
704
      break;
705
  }
706

    
707
  $form_state['rebuild'] = TRUE;
708
}
709

    
710
/**
711
 * AJAX callback that returns the whole feeds_ui_mapping_form().
712
 */
713
function feeds_ui_mapping_settings_form_callback($form, $form_state) {
714
  return $form;
715
}
716

    
717
/**
718
 * Validation handler for feeds_ui_mapping_form().
719
 */
720
function feeds_ui_mapping_form_validate($form, &$form_state) {
721
  if (empty($form_state['values']['source']) xor empty($form_state['values']['target'])) {
722

    
723
    // Check triggering_element here so we can react differently for ajax
724
    // submissions.
725
    switch ($form_state['triggering_element']['#name']) {
726

    
727
      // Regular form submission.
728
      case 'op':
729
        if (empty($form_state['values']['source'])) {
730
          form_error($form['source'], t('You must select a mapping source.'));
731
        }
732
        else {
733
          form_error($form['target'], t('You must select a mapping target.'));
734
        }
735
        break;
736

    
737
      // Be more relaxed on ajax submission.
738
      default:
739
        form_set_value($form['source'], '', $form_state);
740
        form_set_value($form['target'], '', $form_state);
741
        break;
742
    }
743
  }
744
}
745

    
746
/**
747
 * Submission handler for feeds_ui_mapping_form().
748
 */
749
function feeds_ui_mapping_form_submit($form, &$form_state) {
750
  $importer = feeds_importer($form['#importer']);
751
  $processor = $importer->processor;
752

    
753
  $form_state += array(
754
    'mapping_settings' => array(),
755
    'mapping_settings_edit' => NULL,
756
  );
757

    
758
  // If an item is in edit mode, prepare it for saving.
759
  if ($form_state['mapping_settings_edit'] !== NULL) {
760
    $values = $form_state['values']['config'][$form_state['mapping_settings_edit']]['settings'];
761
    $form_state['mapping_settings'][$form_state['mapping_settings_edit']] = $values;
762
  }
763

    
764
  // We may set some settings to mappings that we remove in the subsequent step,
765
  // that's fine.
766
  $mappings = $form['#mappings'];
767
  foreach ($form_state['mapping_settings'] as $k => $v) {
768
    $mappings[$k] = array(
769
      'source' => $mappings[$k]['source'],
770
      'target' => $mappings[$k]['target'],
771
    ) + $v;
772
  }
773

    
774
  if (!empty($form_state['values']['remove_flags'])) {
775
    $remove_flags = array_keys(array_filter($form_state['values']['remove_flags']));
776

    
777
    foreach ($remove_flags as $k) {
778
      unset($mappings[$k]);
779
      unset($form_state['values']['mapping_weight'][$k]);
780
      drupal_set_message(t('Mapping has been removed.'), 'status', FALSE);
781
    }
782
  }
783

    
784
  // Keep our keys clean.
785
  $mappings = array_values($mappings);
786

    
787
  if (!empty($mappings)) {
788
    array_multisort($form_state['values']['mapping_weight'], $mappings);
789
  }
790

    
791
  $processor->addConfig(array('mappings' => $mappings));
792

    
793
  if (!empty($form_state['values']['source']) && !empty($form_state['values']['target'])) {
794
    try {
795
      $mappings = $processor->getMappings();
796
      $mappings[] = array(
797
        'source' => $form_state['values']['source'],
798
        'target' => $form_state['values']['target'],
799
        'unique' => FALSE,
800
      );
801
      $processor->addConfig(array('mappings' => $mappings));
802
      drupal_set_message(t('Mapping has been added.'));
803
    }
804
    catch (Exception $e) {
805
      drupal_set_message($e->getMessage(), 'error');
806
    }
807
  }
808

    
809
  $importer->save();
810
  drupal_set_message(t('Your changes have been saved.'));
811
}
812

    
813
/**
814
 * Walk the result of FeedsParser::getMappingSources() or
815
 * FeedsProcessor::getMappingTargets() and format them into
816
 * a Form API options array.
817
 */
818
function _feeds_ui_format_options($options) {
819
  $result = array();
820
  foreach ($options as $k => $v) {
821
    if (is_array($v) && !empty($v['name'])) {
822
      $result[$k] = $v['name'];
823
    }
824
    elseif (is_array($v)) {
825
      $result[$k] = $k;
826
    }
827
    else {
828
      $result[$k] = $v;
829
    }
830
  }
831
  asort($result);
832
  return $result;
833
}
834

    
835
/**
836
 * Per mapping settings summary callback. Shows whether a mapping is used as
837
 * unique or not.
838
 */
839
function feeds_ui_mapping_settings_optional_unique_summary($mapping, $target, $form, $form_state) {
840
  if (!empty($target['optional_unique'])) {
841
    if ($mapping['unique']) {
842
      return t('Used as <strong>unique</strong>.');
843
    }
844
    else {
845
      return t('Not used as unique.');
846
    }
847
  }
848
}
849

    
850
/**
851
 * Per mapping settings form callback. Lets the user choose if a target is as
852
 * unique or not.
853
 */
854
function feeds_ui_mapping_settings_optional_unique_form($mapping, $target, $form, $form_state) {
855
  $settings_form = array();
856

    
857
  if (!empty($target['optional_unique'])) {
858
    $settings_form['unique'] = array(
859
      '#type' => 'checkbox',
860
      '#title' => t('Unique'),
861
      '#default_value' => !empty($mapping['unique']),
862
    );
863
  }
864

    
865
  return $settings_form;
866
}
867

    
868
/**
869
 * Theme feeds_ui_overview_form().
870
 */
871
function theme_feeds_ui_overview_form($variables) {
872
  $form = $variables['form'];
873
  drupal_add_css(drupal_get_path('module', 'feeds_ui') . '/feeds_ui.css');
874

    
875
  // Iterate through all importers and build a table.
876
  $rows = array();
877
  foreach (array('enabled', 'disabled') as $type) {
878
    if (isset($form[$type])) {
879
      foreach (element_children($form[$type]) as $id) {
880
        $row = array();
881
        foreach (element_children($form[$type][$id]) as $col) {
882
          $row[$col] = array(
883
            'data' => drupal_render($form[$type][$id][$col]),
884
            'class' => array($type),
885
          );
886
        }
887
        $rows[] = array(
888
          'data' => $row,
889
          'class' => array($type),
890
        );
891
      }
892
    }
893
  }
894

    
895
  $output = theme('table', array(
896
    'header' => $form['#header'],
897
    'rows' => $rows,
898
    'attributes' => array('class' => array('feeds-admin-importers')),
899
    'empty' => t('No importers available.'),
900
  ));
901

    
902
  if (!empty($rows)) {
903
    $output .= drupal_render_children($form);
904
  }
905

    
906
  return $output;
907
}
908

    
909
/**
910
 * Theme feeds_ui_edit_page().
911
 */
912
function theme_feeds_ui_edit_page($variables) {
913
  $config_info = $variables['info'];
914
  $active_container = $variables['active'];
915
  drupal_add_css(drupal_get_path('module', 'feeds_ui') . '/feeds_ui.css');
916

    
917
  // Outer wrapper.
918
  $output = '<div class="feeds-settings clear-block">';
919

    
920
  // Build left bar.
921
  $output .= '<div class="left-bar">';
922
  foreach ($config_info as $info) {
923
    $output .= theme('feeds_ui_container', array('container' => $info));
924
  }
925
  $output .= '</div>';
926

    
927
  // Build configuration space.
928
  $output .= '<div class="configuration">';
929
  $output .= '<div class="configuration-squeeze">';
930
  $output .= theme('feeds_ui_container', array('container' => $active_container));
931
  $output .= '</div>';
932
  $output .= '</div>';
933

    
934
  $output .= '</div>'; // ''<div class="feeds-settings">';
935

    
936
  return $output;
937
}
938

    
939
/**
940
 * Render a simple container. A container can have a title, a description and
941
 * one or more actions. Recursive.
942
 *
943
 * @todo Replace with theme_fieldset or a wrapper to theme_fieldset?
944
 *
945
 * @param $variables
946
 *   An array containing an array at 'container'.
947
 *   A 'container' array may contain one or more of the following keys:
948
 *   array(
949
 *     'title' => 'the title',
950
 *     'body' => 'the body of the container, may also be an array of more
951
 *                containers or a renderable array.',
952
 *     'class' => array('the class of the container.'),
953
 *     'id' => 'the id of the container',
954
 *   );
955
 */
956
function theme_feeds_ui_container($variables) {
957
  $container = $variables['container'];
958

    
959
  $class = array_merge(array('feeds-container'), empty($container['class']) ? array('plain') : $container['class']);
960
  $id = empty($container['id']) ? '': ' id="' . $container['id'] . '"';
961
  $output = '<div class="' . implode(' ', $class) . '"' . $id . '>';
962

    
963
  if (isset($container['actions']) && count($container['actions'])) {
964
    $output .= '<ul class="container-actions">';
965
    foreach ($container['actions'] as $action) {
966
      $output .= '<li>' . $action . '</li>';
967
    }
968
    $output .= '</ul>';
969
  }
970

    
971
  if (!empty($container['title'])) {
972
    $output .= '<h4 class="feeds-container-title">';
973
    $output .= $container['title'];
974
    $output .= '</h4>';
975
  }
976

    
977
  if (!empty($container['body'])) {
978
    $output .= '<div class="feeds-container-body">';
979
    if (is_array($container['body'])) {
980
      if (isset($container['body']['#type'])) {
981
        $output .= drupal_render($container['body']);
982
      }
983
      else {
984
        foreach ($container['body'] as $c) {
985
          $output .= theme('feeds_ui_container', array('container' => $c));
986
        }
987
      }
988
    }
989
    else {
990
      $output .= $container['body'];
991
    }
992
    $output .= '</div>';
993
  }
994

    
995
  $output .= '</div>';
996
  return $output;
997
}
998

    
999
/**
1000
 * Theme function for feeds_ui_mapping_form().
1001
 */
1002
function theme_feeds_ui_mapping_form($variables) {
1003
  $form = $variables['form'];
1004

    
1005
  // Build the actual mapping table.
1006
  $header = array(
1007
    t('Source'),
1008
    t('Target'),
1009
    t('Target configuration'),
1010
    '&nbsp;',
1011
    t('Weight'),
1012
  );
1013
  $rows = array();
1014
  if (is_array($form['#mappings'])) {
1015
    foreach ($form['#mappings'] as $i => $mapping) {
1016
      // Some parsers do not define source options.
1017
      $source = isset($form['source']['#options'][$mapping['source']]) ? $form['source']['#options'][$mapping['source']] : $mapping['source'];
1018
      $target = isset($form['target']['#options'][$mapping['target']]) ? check_plain($form['target']['#options'][$mapping['target']]) : '<em>' . t('Missing') . '</em>';
1019
      $rows[] = array(
1020
        'data' => array(
1021
          check_plain($source),
1022
          $target,
1023
          drupal_render($form['config'][$i]),
1024
          drupal_render($form['remove_flags'][$i]),
1025
          drupal_render($form['mapping_weight'][$i]),
1026
        ),
1027
        'class' => array('draggable', 'tabledrag-leaf'),
1028
      );
1029
    }
1030
  }
1031
  if (!count($rows)) {
1032
    $rows[] = array(
1033
      array(
1034
        'colspan' => 5,
1035
        'data' => t('No mappings defined.'),
1036
      ),
1037
    );
1038
  }
1039
  $rows[] = array(
1040
    drupal_render($form['source']),
1041
    drupal_render($form['target']),
1042
    '',
1043
    drupal_render($form['add']),
1044
    '',
1045
  );
1046
  $output = '<div class="help feeds-admin-ui">' . drupal_render($form['help']) . '</div>';
1047
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'feeds-ui-mapping-overview')));
1048

    
1049
  // Build the help table that explains available sources.
1050
  $legend = '';
1051
  $rows = array();
1052
  foreach (element_children($form['legendset']['legend']['sources']) as $k) {
1053
    $rows[] = array(
1054
      check_plain(drupal_render($form['legendset']['legend']['sources'][$k]['name'])),
1055
      check_plain(drupal_render($form['legendset']['legend']['sources'][$k]['description'])),
1056
    );
1057
  }
1058
  if (count($rows)) {
1059
    $legend .= '<h4>' . t('Sources') . '</h4>';
1060
    $legend .= theme('table', array('header' => array(t('Name'), t('Description')), 'rows' => $rows));
1061
  }
1062

    
1063
  // Build the help table that explains available targets.
1064
  $rows = array();
1065
  foreach (element_children($form['legendset']['legend']['targets']) as $k) {
1066
    $rows[] = array(
1067
      check_plain(drupal_render($form['legendset']['legend']['targets'][$k]['name'])),
1068
      check_plain(drupal_render($form['legendset']['legend']['targets'][$k]['description'])),
1069
    );
1070
  }
1071
  $legend .= '<h4>' . t('Targets') . '</h4>';
1072
  $legend .= theme('table', array('header' => array(t('Name'), t('Description')), 'rows' => $rows));
1073

    
1074
  // Stick tables into collapsible fieldset.
1075
  $form['legendset']['legend'] = array(
1076
    '#markup' => '<div>' . $legend . '</div>',
1077
  );
1078

    
1079
  $output .= drupal_render($form['legendset']);
1080
  $output .= drupal_render_children($form);
1081

    
1082
  drupal_add_tabledrag('feeds-ui-mapping-overview', 'order', 'sibling', 'feeds-ui-mapping-weight');
1083
  return $output;
1084
}
1085

    
1086
/**
1087
 * Page callback to import a Feeds importer.
1088
 */
1089
function feeds_ui_importer_import($form, &$form_state) {
1090
  $form['id'] = array(
1091
    '#type' => 'textfield',
1092
    '#title' => t('Importer id'),
1093
    '#description' => t('Enter the id to use for this importer if it is different from the source importer. Leave blank to use the id of the importer.'),
1094
  );
1095
  $form['id_override'] = array(
1096
    '#type' => 'checkbox',
1097
    '#title' => t('Replace an existing importer if one exists with the same id.'),
1098
  );
1099
  $form['bypass_validation'] = array(
1100
    '#type' => 'checkbox',
1101
    '#title' => t('Bypass importer validation'),
1102
    '#description' => t('Bypass the validation of plugins when importing.'),
1103
  );
1104
  $form['importer'] = array(
1105
    '#type' => 'textarea',
1106
    '#rows' => 10,
1107
  );
1108
  $form['actions'] = array('#type' => 'actions');
1109
  $form['actions']['submit'] = array(
1110
    '#type' => 'submit',
1111
    '#value' => t('Import'),
1112
  );
1113
  return $form;
1114
}
1115

    
1116
/**
1117
 * Form validation handler for feeds_ui_importer_import().
1118
 *
1119
 * @see feeds_ui_importer_import_submit()
1120
 */
1121
function feeds_ui_importer_import_validate($form, &$form_state) {
1122
  $form_state['values']['importer'] = trim($form_state['values']['importer']);
1123
  $form_state['values']['id'] = trim($form_state['values']['id']);
1124

    
1125
  if (!empty($form_state['values']['id']) && preg_match('/[^a-zA-Z0-9_]/', $form_state['values']['id'])) {
1126
    form_error($form['id'], t('Feeds importer id must be alphanumeric with underscores only.'));
1127
  }
1128

    
1129
  if (substr($form_state['values']['importer'], 0, 5) == '<?php') {
1130
    $form_state['values']['importer'] = substr($form_state['values']['importer'], 5);
1131
  }
1132

    
1133
  $feeds_importer = NULL;
1134
  ob_start();
1135
  eval($form_state['values']['importer']);
1136
  ob_end_clean();
1137

    
1138
  if (!is_object($feeds_importer)) {
1139
    return form_error($form['importer'], t('Unable to interpret Feeds importer code.'));
1140
  }
1141

    
1142
  if (empty($feeds_importer->api_version) || $feeds_importer->api_version < 1) {
1143
    form_error($form['importer'], t('The importer is not compatible with this version of Feeds.'));
1144
  }
1145
  elseif (version_compare($feeds_importer->api_version, feeds_api_version(), '>')) {
1146
    form_error($form['importer'], t('That importer is created for the version %import_version of Feeds, but you only have version %api_version.', array(
1147
      '%import_version' => $feeds_importer->api_version,
1148
      '%api_version' => feeds_api_version())));
1149
  }
1150

    
1151
  $existing = feeds_importer($feeds_importer->id);
1152
  if ($existing && !$form_state['values']['id_override'] && $existing->export_type != EXPORT_IN_CODE) {
1153
    return form_error($form['id'], t('Feeds importer already exists with that id.'));
1154
  }
1155

    
1156
  if (!$form_state['values']['bypass_validation']) {
1157
    foreach (array('fetcher', 'parser', 'processor') as $type) {
1158
      $plugin = feeds_plugin($feeds_importer->config[$type]['plugin_key'], $feeds_importer->id);
1159
      if (get_class($plugin) == 'FeedsMissingPlugin') {
1160
        form_error($form['importer'], t('The plugin %plugin is unavailable.', array('%plugin' => $feeds_importer->config[$type]['plugin_key'])));
1161
      }
1162
    }
1163
  }
1164

    
1165
  $form_state['importer'] = $feeds_importer;
1166
}
1167

    
1168
/**
1169
 * Form submission handler for feeds_ui_importer_import().
1170
 *
1171
 * @see feeds_ui_importer_import_validate()
1172
 */
1173
function feeds_ui_importer_import_submit($form, &$form_state) {
1174
  $importer = $form_state['importer'];
1175
  $importer = feeds_importer($importer->id);
1176
  $importer->setConfig($importer->config);
1177
  foreach (array('fetcher', 'parser', 'processor') as $type) {
1178
    $importer->$type->setConfig($importer->config[$type]['config']);
1179
  }
1180
  $importer->save();
1181

    
1182
  drupal_set_message(t('Successfully imported the %id feeds importer.', array('%id' => $importer->id)));
1183
  $form_state['redirect'] = 'admin/structure/feeds';
1184
}