Projet

Général

Profil

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

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

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, array &$form_state) {
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(FeedsImporter $importer, $active = 'help', $plugin_key = '') {
277
  // Get plugins and configuration.
278
  $plugins = FeedsPlugin::all();
279

    
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

    
295
    case 'fetcher':
296
    case 'parser':
297
    case 'processor':
298
      $active_container['title'] = t('Select a !plugin_type', array('!plugin_type' => $active));
299
      $active_container['body'] = drupal_get_form('feeds_ui_plugin_form', $importer, $active);
300
      break;
301

    
302
    case 'settings':
303
      drupal_add_js(drupal_get_path('module', 'ctools') . '/js/dependent.js');
304
      ctools_include('dependent');
305
      if (empty($plugin_key)) {
306
        $active_container['title'] = t('Basic settings');
307
        $active_container['body'] = feeds_get_form($importer, 'configForm');
308
      }
309
      // feeds_plugin() returns a correct result because feed has been
310
      // instantiated previously.
311
      elseif (in_array($plugin_key, array_keys($plugins)) && $plugin = feeds_plugin($plugin_key, $importer->id)) {
312
        $active_container['title'] = t('Settings for !plugin', array('!plugin' => $plugins[$plugin_key]['name']));
313
        $active_container['body'] = feeds_get_form($plugin, 'configForm');
314
      }
315
      break;
316

    
317
    case 'mapping':
318
      $processor_name = isset($plugins[$config['processor']['plugin_key']]['name']) ? $plugins[$config['processor']['plugin_key']]['name'] : $plugins['FeedsMissingPlugin']['name'];
319
      $active_container['title'] = t('Mapping for @processor', array('@processor' => $processor_name));
320
      $active_container['body'] = drupal_get_form('feeds_ui_mapping_form', $importer);
321
      break;
322
  }
323

    
324
  // Build config info.
325
  $config_info = $info = array();
326
  $info['class'] = array('config-set');
327

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

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

    
352
  // Fetcher.
353
  $fetcher = isset($plugins[$config['fetcher']['plugin_key']]) ? $plugins[$config['fetcher']['plugin_key']] : $plugins['FeedsMissingPlugin'];
354
  $actions = array();
355
  if ($importer->fetcher->hasConfigForm()) {
356
    $actions = array(l(t('Settings'), $path . '/settings/' . $config['fetcher']['plugin_key']));
357
  }
358
  $info['title'] = t('Fetcher');
359
  $info['body'] = array(
360
    array(
361
      'title' => $fetcher['name'],
362
      'body' => $fetcher['description'],
363
      'actions' => $actions,
364
    ),
365
  );
366
  $info['actions'] = array(l(t('Change'), $path . '/fetcher'));
367
  $config_info[] = $info;
368

    
369
  // Parser.
370
  $parser = isset($plugins[$config['parser']['plugin_key']]) ? $plugins[$config['parser']['plugin_key']] : $plugins['FeedsMissingPlugin'];
371
  $actions = array();
372
  if ($importer->parser->hasConfigForm()) {
373
    $actions = array(l(t('Settings'), $path . '/settings/' . $config['parser']['plugin_key']));
374
  }
375
  $info['title'] = t('Parser');
376
  $info['body'] = array(
377
    array(
378
      'title' => $parser['name'],
379
      'body' => $parser['description'],
380
      'actions' => $actions,
381
    ),
382
  );
383
  $info['actions'] = array(l(t('Change'), $path . '/parser'));
384
  $config_info[] = $info;
385

    
386
  // Processor.
387
  $processor = isset($plugins[$config['processor']['plugin_key']]) ? $plugins[$config['processor']['plugin_key']] : $plugins['FeedsMissingPlugin'];
388
  $actions = array();
389
  if ($importer->processor->hasConfigForm()) {
390
    $actions[] = l(t('Settings'), $path . '/settings/' . $config['processor']['plugin_key']);
391
  }
392
  $actions[] = l(t('Mapping'), $path . '/mapping');
393
  $info['title'] = t('Processor');
394
  $info['body'] = array(
395
    array(
396
      'title' => $processor['name'],
397
      'body' => $processor['description'],
398
      'actions' => $actions,
399
    ),
400
  );
401
  $info['actions'] = array(l(t('Change'), $path . '/processor'));
402
  $config_info[] = $info;
403

    
404
  // Validate configuration.
405
  $errors = $importer->validateConfig();
406
  if (count($errors)) {
407
    $message = t('There are some issues with the importer configuration: !errors', array(
408
      '!errors' => theme('item_list', array('items' => $errors)),
409
    ));
410
    drupal_set_message($message, 'warning');
411
  }
412

    
413
  return theme('feeds_ui_edit_page', array(
414
    'info' => $config_info,
415
    'active' => $active_container,
416
  ));
417
}
418

    
419
/**
420
 * Build a form of plugins to pick from.
421
 *
422
 * @param $form_state
423
 *   Form API form state array.
424
 * @param $importer
425
 *   FeedsImporter object.
426
 * @param $type
427
 *   Plugin type. One of 'fetcher', 'parser', 'processor'.
428
 *
429
 * @return
430
 *   A Form API form definition.
431
 */
432
function feeds_ui_plugin_form($form, &$form_state, $importer, $type) {
433
  $plugins = FeedsPlugin::byType($type);
434

    
435
  $form['#importer'] = $importer->id;
436
  $form['#plugin_type'] = $type;
437

    
438
  $importer_key = $importer->config[$type]['plugin_key'];
439

    
440
  foreach ($plugins as $key => $plugin) {
441

    
442
    $form['plugin_key'][$key] = array(
443
      '#type' => 'radio',
444
      '#parents' => array('plugin_key'),
445
      '#title' => check_plain($plugin['name']),
446
      '#description' => filter_xss(isset($plugin['help']) ? $plugin['help'] : $plugin['description']),
447
      '#return_value' => $key,
448
      '#default_value' => ($key == $importer_key) ? $key : '',
449
    );
450
  }
451
  $form['submit'] = array(
452
    '#type' => 'submit',
453
    '#value' => t('Save'),
454
  );
455
  return $form;
456
}
457

    
458
/**
459
 * Submit handler for feeds_ui_plugin_form().
460
 */
461
function feeds_ui_plugin_form_submit($form, &$form_state) {
462
  // Set the plugin and save feed.
463
  $importer = feeds_importer($form['#importer']);
464
  $importer->setPlugin($form_state['values']['plugin_key']);
465
  $importer->save();
466
  drupal_set_message(t('Changed @type plugin.', array('@type' => $form['#plugin_type'])));
467
}
468

    
469
/**
470
 * Theme feeds_ui_plugin_form().
471
 */
472
function theme_feeds_ui_plugin_form($variables) {
473
  $form = $variables['form'];
474
  $output = '';
475

    
476
  foreach (element_children($form['plugin_key']) as $key) {
477

    
478
    // Assemble container, render form elements.
479
    $container = array(
480
      'title' => $form['plugin_key'][$key]['#title'],
481
      'body' => isset($form['plugin_key'][$key]['#description']) ? $form['plugin_key'][$key]['#description'] : '',
482
    );
483
    $form['plugin_key'][$key]['#title'] = t('Select');
484
    $form['plugin_key'][$key]['#attributes']['class'] = array('feeds-ui-radio-link');
485
    unset($form['plugin_key'][$key]['#description']);
486
    $container['actions'] = array(drupal_render($form['plugin_key'][$key]));
487

    
488
    $output .= theme('feeds_ui_container', array('container' => $container));
489
  }
490

    
491
  $output .= drupal_render_children($form);
492
  return $output;
493
}
494

    
495
/**
496
 * Edit mapping.
497
 *
498
 * @todo Completely merge this into config form handling. This is just a
499
 *   shared form of configuration, most of the common functionality can live in
500
 *   FeedsProcessor, a flag can tell whether mapping is supported or not.
501
 */
502
function feeds_ui_mapping_form($form, &$form_state, $importer) {
503
  $form['#importer'] = $importer->id;
504
  $form['#mappings'] = $mappings = $importer->processor->getMappings();
505
  $form['#feeds_targets'] = $importer->processor->getMappingTargets();
506
  $form['#feeds_sources'] = $importer->parser->getMappingSources();
507
  $form['help']['#markup'] = feeds_ui_mapping_help();
508
  $form['#prefix'] = '<div id="feeds-ui-mapping-form-wrapper">';
509
  $form['#suffix'] = '</div>';
510

    
511
  // Show message when target configuration gets changed.
512
  if (!empty($form_state['mapping_settings'])) {
513
    $form['#mapping_settings'] = $form_state['mapping_settings'];
514
    $form['changed'] = array(
515
      '#theme_wrappers' => array('container'),
516
      '#attributes' => array('class' => array('messages', 'warning')),
517
      '#markup' => t('* Changes made to target configuration are stored temporarily. Click Save to make your changes permanent.'),
518
    );
519
  }
520

    
521
  // Get mapping sources from parsers and targets from processor, format them
522
  // for output.
523
  // Some parsers do not define mapping sources but let them define on the fly.
524
  if ($sources = $importer->parser->getMappingSources()) {
525
    $source_options = _feeds_ui_format_options($sources);
526
    foreach ($sources as $k => $source) {
527
      if (!empty($source['deprecated'])) {
528
        continue;
529
      }
530
      $legend['sources'][$k]['name']['#markup'] = empty($source['name']) ? $k : $source['name'];
531
      $legend['sources'][$k]['description']['#markup'] = empty($source['description']) ? '' : $source['description'];
532
    }
533
  }
534
  else {
535
    $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.');
536
  }
537
  $targets = $importer->processor->getMappingTargets();
538
  $target_options = _feeds_ui_format_options($targets);
539
  $legend['targets'] = array();
540
  foreach ($targets as $k => $target) {
541
    if (!empty($target['deprecated'])) {
542
      continue;
543
    }
544
    $legend['targets'][$k]['name']['#markup'] = empty($target['name']) ? $k : $target['name'];
545
    $legend['targets'][$k]['description']['#markup'] = empty($target['description']) ? '' : $target['description'];
546
  }
547

    
548
  // Legend explaining source and target elements.
549
  $form['legendset'] = array(
550
    '#type' => 'fieldset',
551
    '#title' => t('Legend'),
552
    '#collapsible' => TRUE,
553
    '#collapsed' => TRUE,
554
    '#tree' => TRUE,
555
  );
556
  $form['legendset']['legend'] = $legend;
557

    
558
  // Add config forms and remove flags to mappings.
559
  $form['config'] = $form['remove_flags'] = $form['mapping_weight'] = array(
560
    '#tree' => TRUE,
561
  );
562
  if (is_array($mappings)) {
563

    
564
    $delta = count($mappings) + 2;
565

    
566
    foreach ($mappings as $i => $mapping) {
567
      if (isset($targets[$mapping['target']])) {
568
        $form['config'][$i] = feeds_ui_mapping_settings_form($form, $form_state, $i, $mapping, $targets[$mapping['target']]);
569
      }
570

    
571
      $form['remove_flags'][$i] = array(
572
        '#type' => 'checkbox',
573
        '#title' => t('Remove'),
574
        '#prefix' => '<div class="feeds-ui-checkbox-link">',
575
        '#suffix' => '</div>',
576
      );
577

    
578
      $form['mapping_weight'][$i] = array(
579
        '#type' => 'weight',
580
        '#title' => '',
581
        '#default_value' => $i,
582
        '#delta' => $delta,
583
        '#attributes' => array(
584
          'class' => array(
585
            'feeds-ui-mapping-weight',
586
          ),
587
        ),
588
      );
589
    }
590
  }
591

    
592
  if (isset($source_options)) {
593
    $form['source'] = array(
594
      '#type' => 'select',
595
      '#title' => t('Source'),
596
      '#title_display' => 'invisible',
597
      '#options' => $source_options,
598
      '#empty_option' => t('- Select a source -'),
599
      '#description' => t('An element from the feed.'),
600
    );
601
  }
602
  else {
603
    $form['source'] = array(
604
      '#type' => 'textfield',
605
      '#title' => t('Source'),
606
      '#title_display' => 'invisible',
607
      '#size' => 20,
608
      '#default_value' => '',
609
      '#description' => t('The name of source field.'),
610
    );
611
  }
612
  $form['target'] = array(
613
    '#type' => 'select',
614
    '#title' => t('Target'),
615
    '#title_display' => 'invisible',
616
    '#options' => $target_options,
617
    '#empty_option' => t('- Select a target -'),
618
    '#description' => t('The field that stores the data.'),
619
  );
620

    
621
  $form['actions'] = array('#type' => 'actions');
622
  $form['actions']['save'] = array(
623
    '#type' => 'submit',
624
    '#value' => t('Save'),
625
  );
626
  return $form;
627
}
628

    
629
/**
630
 * Per mapper configuration form that is a part of feeds_ui_mapping_form().
631
 */
632
function feeds_ui_mapping_settings_form($form, $form_state, $i, $mapping, $target) {
633
  $form_state += array(
634
    'mapping_settings_edit' => NULL,
635
    'mapping_settings' => array(),
636
  );
637

    
638
  $base_button = array(
639
    '#submit' => array('feeds_ui_mapping_form_multistep_submit'),
640
    '#ajax' => array(
641
      'callback' => 'feeds_ui_mapping_settings_form_callback',
642
      'wrapper' => 'feeds-ui-mapping-form-wrapper',
643
      'effect' => 'fade',
644
      'progress' => 'none',
645
    ),
646
    '#i' => $i,
647
  );
648

    
649
  if (isset($form_state['mapping_settings'][$i])) {
650
    $mapping = $form_state['mapping_settings'][$i] + $mapping;
651
  }
652

    
653
  if ($form_state['mapping_settings_edit'] === $i) {
654
    $settings_form = array();
655

    
656
    foreach ($target['form_callbacks'] as $callback) {
657
      $settings_form += call_user_func($callback, $mapping, $target, $form, $form_state);
658
    }
659

    
660
    // Merge in the optional unique form.
661
    $settings_form += feeds_ui_mapping_settings_optional_unique_form($mapping, $target, $form, $form_state);
662

    
663
    return array(
664
      '#type' => 'container',
665
      '#attributes' => array(
666
        'class' => array('feeds-target-config'),
667
      ),
668
      'settings' => $settings_form,
669
      'save_settings' => $base_button + array(
670
        '#type' => 'submit',
671
        '#name' => 'mapping_settings_update_' . $i,
672
        '#value' => t('Update'),
673
        '#op' => 'update',
674
      ),
675
      'cancel_settings' => $base_button + array(
676
        '#type' => 'submit',
677
        '#name' => 'mapping_settings_cancel_' . $i,
678
        '#value' => t('Cancel'),
679
        '#op' => 'cancel',
680
      ),
681
    );
682
  }
683
  else {
684
    // Build the summary.
685
    $summary = array();
686

    
687
    foreach ($target['summary_callbacks'] as $callback) {
688
      $summary[] = call_user_func($callback, $mapping, $target, $form, $form_state);
689
    }
690

    
691
    // Filter out empty summary values.
692
    $summary = implode('<br />', array_filter($summary));
693

    
694
    // Append the optional unique summary.
695
    if ($optional_unique_summary = feeds_ui_mapping_settings_optional_unique_summary($mapping, $target, $form, $form_state)) {
696
      $summary .= ' ' . $optional_unique_summary;
697
    }
698

    
699
    if ($summary) {
700
      return array(
701
        'summary' => array(
702
          '#prefix' => '<div>',
703
          '#markup' => $summary,
704
          '#suffix' => '</div>',
705
        ),
706
        'edit_settings' => $base_button + array(
707
          '#type' => 'image_button',
708
          '#name' => 'mapping_settings_edit_' . $i,
709
          '#src' => 'misc/configure.png',
710
          '#attributes' => array('alt' => t('Edit')),
711
          '#op' => 'edit',
712
        ),
713
      );
714
    }
715
  }
716
  return array();
717
}
718

    
719
/**
720
 * Submit callback for a per mapper configuration form. Switches between edit
721
 * and summary mode.
722
 */
723
function feeds_ui_mapping_form_multistep_submit($form, &$form_state) {
724
  $trigger = $form_state['triggering_element'];
725

    
726
  switch ($trigger['#op']) {
727
    case 'edit':
728
      $form_state['mapping_settings_edit'] = $trigger['#i'];
729
      break;
730

    
731
    case 'update':
732
      $values = $form_state['values']['config'][$trigger['#i']]['settings'];
733
      $form_state['mapping_settings'][$trigger['#i']] = $values;
734
      unset($form_state['mapping_settings_edit']);
735
      break;
736

    
737
    case 'cancel':
738
      unset($form_state['mapping_settings_edit']);
739
      break;
740
  }
741

    
742
  $form_state['rebuild'] = TRUE;
743
}
744

    
745
/**
746
 * AJAX callback that returns the whole feeds_ui_mapping_form().
747
 */
748
function feeds_ui_mapping_settings_form_callback($form, $form_state) {
749
  return $form;
750
}
751

    
752
/**
753
 * Validation handler for feeds_ui_mapping_form().
754
 */
755
function feeds_ui_mapping_form_validate($form, &$form_state) {
756
  if (!strlen($form_state['values']['source']) xor !strlen($form_state['values']['target'])) {
757

    
758
    // Check triggering_element here so we can react differently for ajax
759
    // submissions.
760
    switch ($form_state['triggering_element']['#name']) {
761

    
762
      // Regular form submission.
763
      case 'op':
764
        if (!strlen($form_state['values']['source'])) {
765
          form_error($form['source'], t('You must select a mapping source.'));
766
        }
767
        else {
768
          form_error($form['target'], t('You must select a mapping target.'));
769
        }
770
        break;
771

    
772
      // Be more relaxed on ajax submission.
773
      default:
774
        form_set_value($form['source'], '', $form_state);
775
        form_set_value($form['target'], '', $form_state);
776
        break;
777
    }
778
  }
779
}
780

    
781
/**
782
 * Submission handler for feeds_ui_mapping_form().
783
 */
784
function feeds_ui_mapping_form_submit($form, &$form_state) {
785
  $importer = feeds_importer($form['#importer']);
786
  $processor = $importer->processor;
787

    
788
  $form_state += array(
789
    'mapping_settings' => array(),
790
    'mapping_settings_edit' => NULL,
791
  );
792

    
793
  // If an item is in edit mode, prepare it for saving.
794
  if ($form_state['mapping_settings_edit'] !== NULL) {
795
    $values = $form_state['values']['config'][$form_state['mapping_settings_edit']]['settings'];
796
    $form_state['mapping_settings'][$form_state['mapping_settings_edit']] = $values;
797
  }
798

    
799
  // We may set some settings to mappings that we remove in the subsequent step,
800
  // that's fine.
801
  $mappings = $form['#mappings'];
802
  foreach ($form_state['mapping_settings'] as $k => $v) {
803
    $mappings[$k] = array(
804
      'source' => $mappings[$k]['source'],
805
      'target' => $mappings[$k]['target'],
806
    ) + $v;
807
  }
808

    
809
  if (!empty($form_state['values']['remove_flags'])) {
810
    $remove_flags = array_keys(array_filter($form_state['values']['remove_flags']));
811

    
812
    foreach ($remove_flags as $k) {
813
      unset($mappings[$k]);
814
      unset($form_state['values']['mapping_weight'][$k]);
815
      drupal_set_message(t('Mapping has been removed.'), 'status', FALSE);
816
    }
817
  }
818

    
819
  // Keep our keys clean.
820
  $mappings = array_values($mappings);
821

    
822
  if (!empty($mappings)) {
823
    array_multisort($form_state['values']['mapping_weight'], $mappings);
824
  }
825

    
826
  $processor->addConfig(array('mappings' => $mappings));
827

    
828
  if (strlen($form_state['values']['source']) && strlen($form_state['values']['target'])) {
829
    try {
830
      $mappings = $processor->getMappings();
831
      $mappings[] = array(
832
        'source' => $form_state['values']['source'],
833
        'target' => $form_state['values']['target'],
834
        'unique' => FALSE,
835
      );
836
      $processor->addConfig(array('mappings' => $mappings));
837
      drupal_set_message(t('Mapping has been added.'));
838
    }
839
    catch (Exception $e) {
840
      drupal_set_message($e->getMessage(), 'error');
841
    }
842
  }
843

    
844
  $importer->save();
845
  drupal_set_message(t('Your changes have been saved.'));
846
}
847

    
848
/**
849
 * Walk the result of FeedsParser::getMappingSources() or
850
 * FeedsProcessor::getMappingTargets() and format them into
851
 * a Form API options array.
852
 */
853
function _feeds_ui_format_options($options, $show_deprecated = FALSE) {
854
  $result = array();
855
  foreach ($options as $k => $v) {
856
    if (!$show_deprecated && is_array($v) && !empty($v['deprecated'])) {
857
      continue;
858
    }
859
    if (is_array($v) && !empty($v['name'])) {
860
      $result[$k] = $v['name'] . ' (' . $k . ')';
861
      if (!empty($v['deprecated'])) {
862
        $result[$k] .= ' - ' . t('DEPRECATED');
863
      }
864
    }
865
    elseif (is_array($v)) {
866
      $result[$k] = $k;
867
    }
868
    else {
869
      $result[$k] = $v;
870
    }
871
  }
872
  asort($result);
873
  return $result;
874
}
875

    
876
/**
877
 * Per mapping settings summary callback. Shows whether a mapping is used as
878
 * unique or not.
879
 */
880
function feeds_ui_mapping_settings_optional_unique_summary($mapping, $target, $form, $form_state) {
881
  if (!empty($target['optional_unique'])) {
882
    if ($mapping['unique']) {
883
      return t('Used as <strong>unique</strong>.');
884
    }
885
    else {
886
      return t('Not used as unique.');
887
    }
888
  }
889
}
890

    
891
/**
892
 * Per mapping settings form callback. Lets the user choose if a target is as
893
 * unique or not.
894
 */
895
function feeds_ui_mapping_settings_optional_unique_form($mapping, $target, $form, $form_state) {
896
  $settings_form = array();
897

    
898
  if (!empty($target['optional_unique'])) {
899
    $settings_form['unique'] = array(
900
      '#type' => 'checkbox',
901
      '#title' => t('Unique'),
902
      '#default_value' => !empty($mapping['unique']),
903
    );
904
  }
905

    
906
  return $settings_form;
907
}
908

    
909
/**
910
 * Theme feeds_ui_overview_form().
911
 */
912
function theme_feeds_ui_overview_form($variables) {
913
  $form = $variables['form'];
914
  drupal_add_css(drupal_get_path('module', 'feeds_ui') . '/feeds_ui.css');
915

    
916
  // Iterate through all importers and build a table.
917
  $rows = array();
918
  foreach (array('enabled', 'disabled') as $type) {
919
    if (isset($form[$type])) {
920
      foreach (element_children($form[$type]) as $id) {
921
        $row = array();
922
        foreach (element_children($form[$type][$id]) as $col) {
923
          $row[$col] = array(
924
            'data' => drupal_render($form[$type][$id][$col]),
925
            'class' => array($type),
926
          );
927
        }
928
        $rows[] = array(
929
          'data' => $row,
930
          'class' => array($type),
931
        );
932
      }
933
    }
934
  }
935

    
936
  $output = theme('table', array(
937
    'header' => $form['#header'],
938
    'rows' => $rows,
939
    'attributes' => array('class' => array('feeds-admin-importers')),
940
    'empty' => t('No importers available.'),
941
  ));
942

    
943
  if (!empty($rows)) {
944
    $output .= drupal_render_children($form);
945
  }
946

    
947
  return $output;
948
}
949

    
950
/**
951
 * Theme feeds_ui_edit_page().
952
 */
953
function theme_feeds_ui_edit_page($variables) {
954
  $config_info = $variables['info'];
955
  $active_container = $variables['active'];
956
  drupal_add_css(drupal_get_path('module', 'feeds_ui') . '/feeds_ui.css');
957

    
958
  // Outer wrapper.
959
  $output = '<div class="feeds-settings clearfix">';
960

    
961
  // Build left bar.
962
  $output .= '<div class="left-bar">';
963
  foreach ($config_info as $info) {
964
    $output .= theme('feeds_ui_container', array('container' => $info));
965
  }
966
  $output .= '</div>';
967

    
968
  // Build configuration space.
969
  $output .= '<div class="configuration">';
970
  $output .= '<div class="configuration-squeeze">';
971
  $output .= theme('feeds_ui_container', array('container' => $active_container));
972
  $output .= '</div>';
973
  $output .= '</div>';
974

    
975
  // Close the outer wrapper.
976
  $output .= '</div>';
977

    
978
  return $output;
979
}
980

    
981
/**
982
 * Render a simple container. A container can have a title, a description and
983
 * one or more actions. Recursive.
984
 *
985
 * @todo Replace with theme_fieldset or a wrapper to theme_fieldset?
986
 *
987
 * @param $variables
988
 *   An array containing an array at 'container'.
989
 *   A 'container' array may contain one or more of the following keys:
990
 *   array(
991
 *     'title' => 'the title',
992
 *     'body' => 'the body of the container, may also be an array of more
993
 *                containers or a renderable array.',
994
 *     'class' => array('the class of the container.'),
995
 *     'id' => 'the id of the container',
996
 *   );
997
 */
998
function theme_feeds_ui_container($variables) {
999
  $container = $variables['container'];
1000

    
1001
  $class = array_merge(array('feeds-container'), empty($container['class']) ? array('plain') : $container['class']);
1002
  $id = empty($container['id']) ? '' : ' id="' . $container['id'] . '"';
1003
  $output = '<div class="' . implode(' ', $class) . '"' . $id . '>';
1004

    
1005
  if (isset($container['actions']) && count($container['actions'])) {
1006
    $output .= '<ul class="container-actions">';
1007
    foreach ($container['actions'] as $action) {
1008
      $output .= '<li>' . $action . '</li>';
1009
    }
1010
    $output .= '</ul>';
1011
  }
1012

    
1013
  if (!empty($container['title'])) {
1014
    $output .= '<h4 class="feeds-container-title">';
1015
    $output .= $container['title'];
1016
    $output .= '</h4>';
1017
  }
1018

    
1019
  if (!empty($container['body'])) {
1020
    $output .= '<div class="feeds-container-body">';
1021
    if (is_array($container['body'])) {
1022
      if (isset($container['body']['#type'])) {
1023
        $output .= drupal_render($container['body']);
1024
      }
1025
      else {
1026
        foreach ($container['body'] as $c) {
1027
          $output .= theme('feeds_ui_container', array('container' => $c));
1028
        }
1029
      }
1030
    }
1031
    else {
1032
      $output .= $container['body'];
1033
    }
1034
    $output .= '</div>';
1035
  }
1036

    
1037
  $output .= '</div>';
1038
  return $output;
1039
}
1040

    
1041
/**
1042
 * Theme function for feeds_ui_mapping_form().
1043
 */
1044
function theme_feeds_ui_mapping_form($variables) {
1045
  $form = $variables['form'];
1046

    
1047
  $targets = $form['#feeds_targets'];
1048
  $targets = _feeds_ui_format_options($targets, TRUE);
1049

    
1050
  $sources = $form['#feeds_sources'];
1051
  // Some parsers do not define source options.
1052
  $sources = $sources ? _feeds_ui_format_options($sources, TRUE) : array();
1053

    
1054
  // Build the actual mapping table.
1055
  $header = array(
1056
    t('Source'),
1057
    t('Target'),
1058
    t('Target configuration'),
1059
    '&nbsp;',
1060
    t('Weight'),
1061
  );
1062
  $rows = array();
1063
  if (is_array($form['#mappings'])) {
1064
    foreach ($form['#mappings'] as $i => $mapping) {
1065
      $source = isset($sources[$mapping['source']]) ? check_plain($sources[$mapping['source']]) : check_plain($mapping['source']);
1066
      $target = isset($targets[$mapping['target']]) ? check_plain($targets[$mapping['target']]) : '<em>' . t('Missing') . '</em>';
1067
      // Add indicator to target if target configuration changed.
1068
      if (isset($form['#mapping_settings'][$i])) {
1069
        $target .= '<span class="warning">*</span>';
1070
      }
1071
      $rows[] = array(
1072
        'data' => array(
1073
          $source,
1074
          $target,
1075
          drupal_render($form['config'][$i]),
1076
          drupal_render($form['remove_flags'][$i]),
1077
          drupal_render($form['mapping_weight'][$i]),
1078
        ),
1079
        'class' => array('draggable', 'tabledrag-leaf'),
1080
      );
1081
    }
1082
  }
1083
  if (!count($rows)) {
1084
    $rows[] = array(
1085
      array(
1086
        'colspan' => 5,
1087
        'data' => t('No mappings defined.'),
1088
      ),
1089
    );
1090
  }
1091
  $rows[] = array(
1092
    drupal_render($form['source']),
1093
    drupal_render($form['target']),
1094
    '',
1095
    drupal_render($form['add']),
1096
    '',
1097
  );
1098
  $output = '';
1099
  if (!empty($form['changed'])) {
1100
    // This form element is only available if target configuration changed.
1101
    $output .= drupal_render($form['changed']);
1102
  }
1103
  $output .= '<div class="help feeds-admin-ui">' . drupal_render($form['help']) . '</div>';
1104
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'feeds-ui-mapping-overview')));
1105

    
1106
  // Build the help table that explains available sources.
1107
  $legend = '';
1108
  $rows = array();
1109
  foreach (element_children($form['legendset']['legend']['sources']) as $k) {
1110
    $rows[] = array(
1111
      check_plain(drupal_render($form['legendset']['legend']['sources'][$k]['name'])),
1112
      check_plain(drupal_render($form['legendset']['legend']['sources'][$k]['description'])),
1113
    );
1114
  }
1115
  if (count($rows)) {
1116
    $legend .= '<h4>' . t('Sources') . '</h4>';
1117
    $legend .= theme('table', array('header' => array(t('Name'), t('Description')), 'rows' => $rows));
1118
  }
1119

    
1120
  // Build the help table that explains available targets.
1121
  $rows = array();
1122
  foreach (element_children($form['legendset']['legend']['targets']) as $k) {
1123
    $rows[] = array(
1124
      check_plain(drupal_render($form['legendset']['legend']['targets'][$k]['name']) . ' (' . $k . ')'),
1125
      check_plain(drupal_render($form['legendset']['legend']['targets'][$k]['description'])),
1126
    );
1127
  }
1128
  $legend .= '<h4>' . t('Targets') . '</h4>';
1129
  $legend .= theme('table', array('header' => array(t('Name'), t('Description')), 'rows' => $rows));
1130

    
1131
  // Stick tables into collapsible fieldset.
1132
  $form['legendset']['legend'] = array(
1133
    '#markup' => '<div>' . $legend . '</div>',
1134
  );
1135

    
1136
  $output .= drupal_render($form['legendset']);
1137
  $output .= drupal_render_children($form);
1138

    
1139
  drupal_add_tabledrag('feeds-ui-mapping-overview', 'order', 'sibling', 'feeds-ui-mapping-weight');
1140
  return $output;
1141
}
1142

    
1143
/**
1144
 * Page callback to import a Feeds importer.
1145
 */
1146
function feeds_ui_importer_import($form, &$form_state) {
1147
  $form['id'] = array(
1148
    '#type' => 'textfield',
1149
    '#title' => t('Importer id'),
1150
    '#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.'),
1151
  );
1152
  $form['id_override'] = array(
1153
    '#type' => 'checkbox',
1154
    '#title' => t('Replace an existing importer if one exists with the same id.'),
1155
  );
1156
  $form['bypass_validation'] = array(
1157
    '#type' => 'checkbox',
1158
    '#title' => t('Bypass importer validation'),
1159
    '#description' => t('Bypass the validation of plugins when importing.'),
1160
  );
1161
  $form['importer'] = array(
1162
    '#type' => 'textarea',
1163
    '#rows' => 10,
1164
  );
1165
  $form['actions'] = array('#type' => 'actions');
1166
  $form['actions']['submit'] = array(
1167
    '#type' => 'submit',
1168
    '#value' => t('Import'),
1169
  );
1170
  return $form;
1171
}
1172

    
1173
/**
1174
 * Form validation handler for feeds_ui_importer_import().
1175
 *
1176
 * @see feeds_ui_importer_import_submit()
1177
 */
1178
function feeds_ui_importer_import_validate($form, &$form_state) {
1179
  $form_state['values']['importer'] = trim($form_state['values']['importer']);
1180
  $form_state['values']['id'] = trim($form_state['values']['id']);
1181

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

    
1186
  if (substr($form_state['values']['importer'], 0, 5) == '<?php') {
1187
    $form_state['values']['importer'] = substr($form_state['values']['importer'], 5);
1188
  }
1189

    
1190
  $feeds_importer = NULL;
1191
  ob_start();
1192
  eval($form_state['values']['importer']);
1193
  ob_end_clean();
1194

    
1195
  if (!is_object($feeds_importer)) {
1196
    return form_error($form['importer'], t('Unable to interpret Feeds importer code.'));
1197
  }
1198

    
1199
  if (empty($feeds_importer->api_version) || $feeds_importer->api_version < 1) {
1200
    form_error($form['importer'], t('The importer is not compatible with this version of Feeds.'));
1201
  }
1202
  elseif (version_compare($feeds_importer->api_version, feeds_api_version(), '>')) {
1203
    form_error($form['importer'], t('That importer is created for the version %import_version of Feeds, but you only have version %api_version.', array(
1204
      '%import_version' => $feeds_importer->api_version,
1205
      '%api_version' => feeds_api_version(),
1206
    )));
1207
  }
1208

    
1209
  // Change to user-supplied id.
1210
  if ($form_state['values']['id']) {
1211
    $feeds_importer->id = $form_state['values']['id'];
1212
  }
1213

    
1214
  $exists = feeds_ui_importer_machine_name_exists($feeds_importer->id);
1215

    
1216
  if ($exists && !$form_state['values']['id_override']) {
1217
    return form_error($form['id'], t('Feeds importer already exists with that id.'));
1218
  }
1219

    
1220
  if (!$form_state['values']['bypass_validation']) {
1221
    $errors = array();
1222

    
1223
    $importer = feeds_importer($feeds_importer->id);
1224
    $importer->setConfig($feeds_importer->config);
1225
    foreach (array('fetcher', 'parser', 'processor') as $type) {
1226
      $plugin = feeds_plugin($feeds_importer->config[$type]['plugin_key'], $feeds_importer->id);
1227
      if (!($plugin instanceof FeedsMissingPlugin)) {
1228
        $importer->setPlugin($feeds_importer->config[$type]['plugin_key']);
1229
        $importer->$type->setConfig($feeds_importer->config[$type]['config']);
1230
      }
1231
    }
1232
    $errors = array_merge($errors, $importer->validateConfig());
1233
    if (!empty($errors)) {
1234
      form_error($form['importer'], theme('item_list', array('items' => $errors)));
1235
    }
1236
  }
1237

    
1238
  $form_state['importer'] = $feeds_importer;
1239
}
1240

    
1241
/**
1242
 * Form submission handler for feeds_ui_importer_import().
1243
 *
1244
 * @see feeds_ui_importer_import_validate()
1245
 */
1246
function feeds_ui_importer_import_submit($form, &$form_state) {
1247
  $importer = $form_state['importer'];
1248

    
1249
  // Create a copy of the importer to preserve config.
1250
  $save = feeds_importer($importer->id);
1251
  $save->setConfig($importer->config);
1252
  foreach (array('fetcher', 'parser', 'processor') as $type) {
1253
    $save->setPlugin($importer->config[$type]['plugin_key']);
1254
    $save->$type->setConfig($importer->config[$type]['config']);
1255
  }
1256
  $save->save();
1257

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