Projet

Général

Profil

Paste
Télécharger (12,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / feeds / plugins / FeedsCSVParser.inc @ ed9a13f1

1
<?php
2

    
3
/**
4
 * @file
5
 * Contains the FeedsCSVParser class.
6
 */
7

    
8
/**
9
 * Parses a given file as a CSV file.
10
 */
11
class FeedsCSVParser extends FeedsParser {
12

    
13
  /**
14
   * Implements FeedsParser::parse().
15
   */
16
  public function parse(FeedsSource $source, FeedsFetcherResult $fetcher_result) {
17
    $source_config = $source->getConfigFor($this);
18
    $state = $source->state(FEEDS_PARSE);
19

    
20
    // Load and configure parser.
21
    feeds_include_library('ParserCSV.inc', 'ParserCSV');
22
    $parser = new ParserCSV();
23
    $delimiter = $this->getDelimiterChar($source_config);
24
    $parser->setDelimiter($delimiter);
25
    if (isset($source_config['encoding'])) {
26
      // Encoding can only be set when the mbstring extension is loaded.
27
      $parser->setEncoding($source_config['encoding']);
28
    }
29

    
30
    $iterator = new ParserCSVIterator($fetcher_result->getFilePath());
31
    if (empty($source_config['no_headers'])) {
32
      // Get first line and use it for column names, convert them to lower case.
33
      $header = $this->parseHeader($parser, $iterator);
34
      if (!$header) {
35
        drupal_set_message(t('The CSV file is empty.'), 'warning', FALSE);
36
        return new FeedsParserResult();
37
      }
38
      $parser->setColumnNames($header);
39
    }
40

    
41
    // Determine section to parse, parse.
42
    $start = $state->pointer ? $state->pointer : $parser->lastLinePos();
43
    $limit = $source->importer->getLimit();
44
    $rows = $this->parseItems($parser, $iterator, $start, $limit);
45

    
46
    // Report progress.
47
    $state->total = filesize($fetcher_result->getFilePath());
48
    $state->pointer = $parser->lastLinePos();
49
    $progress = $parser->lastLinePos() ? $parser->lastLinePos() : $state->total;
50
    $state->progress($state->total, $progress);
51

    
52
    // Create a result object and return it.
53
    return new FeedsParserResult($rows, $source->feed_nid);
54
  }
55

    
56
  /**
57
   * Get first line and use it for column names, convert them to lower case.
58
   * Be aware that the $parser and iterator objects can be modified in this
59
   * function since they are passed in by reference.
60
   *
61
   * @param ParserCSV $parser
62
   * @param ParserCSVIterator $iterator
63
   *
64
   * @return array|false
65
   *   An array of lower-cased column names to use as keys for the parsed items
66
   *   or FALSE if the document was empty.
67
   */
68
  protected function parseHeader(ParserCSV $parser, ParserCSVIterator $iterator) {
69
    try {
70
      $parser->setLineLimit(1);
71
      $rows = $parser->parse($iterator);
72
      if (!count($rows)) {
73
        return FALSE;
74
      }
75
      $header = array_shift($rows);
76
      foreach ($header as $i => $title) {
77
        $header[$i] = trim(drupal_strtolower($title));
78
      }
79
      return $header;
80
    }
81
    catch (Exception $e) {
82
      // Make sure that the file on the iterator gets properly closed when
83
      // exceptions occur during parsing.
84
      $iterator->releaseHandler();
85
      throw $e;
86
    }
87
  }
88

    
89
  /**
90
   * Parse all of the items from the CSV.
91
   *
92
   * @param ParserCSV $parser
93
   * @param ParserCSVIterator $iterator
94
   * @param int $start
95
   *   The byte number from where to start parsing the file.
96
   * @param int $limit
97
   *   The number of lines to parse, 0 for all lines.
98
   *
99
   * @return array
100
   *   An array of rows of the CSV keyed by the column names previously set.
101
   */
102
  protected function parseItems(ParserCSV $parser, ParserCSVIterator $iterator, $start = 0, $limit = 0) {
103
    try {
104
      $parser->setLineLimit($limit);
105
      $parser->setStartByte($start);
106
      $rows = $parser->parse($iterator);
107
      return $rows;
108
    }
109
    catch (Exception $e) {
110
      // Make sure that the file on the iterator gets properly closed when
111
      // exceptions occur during parsing.
112
      $iterator->releaseHandler();
113
      throw $e;
114
    }
115
  }
116

    
117
  /**
118
   * Override parent::getMappingSources().
119
   */
120
  public function getMappingSources() {
121
    return FALSE;
122
  }
123

    
124
  /**
125
   * Override parent::getSourceElement() to use only lower keys.
126
   */
127
  public function getSourceElement(FeedsSource $source, FeedsParserResult $result, $element_key) {
128
    return parent::getSourceElement($source, $result, drupal_strtolower($element_key));
129
  }
130

    
131
  /**
132
   * Override parent::getMappingSourceList() to use only lower keys.
133
   */
134
  public function getMappingSourceList() {
135
    return array_map('drupal_strtolower', parent::getMappingSourceList());
136
  }
137

    
138
  /**
139
   * Define defaults.
140
   */
141
  public function sourceDefaults() {
142
    return array(
143
      'delimiter' => $this->config['delimiter'],
144
      'encoding' => $this->config['encoding'],
145
      'no_headers' => $this->config['no_headers'],
146
    );
147
  }
148

    
149
  /**
150
   * Source form.
151
   *
152
   * Show mapping configuration as a guidance for import form users.
153
   */
154
  public function sourceForm($source_config) {
155
    $form = array();
156
    $form['#weight'] = -10;
157

    
158
    $mappings = feeds_importer($this->id)->processor->config['mappings'];
159
    $sources = $uniques = array();
160
    foreach ($mappings as $mapping) {
161
      if (strpos($mapping['source'], ',') !== FALSE) {
162
        $sources[] = '"' . $mapping['source'] . '"';
163
      }
164
      elseif (strlen(trim($mapping['source']))) {
165
        $sources[] = $mapping['source'];
166
      }
167
      if (!empty($mapping['unique']) && strlen(trim($mapping['source']))) {
168
        $uniques[] = $mapping['source'];
169
      }
170
    }
171
    $sources = array_unique($sources);
172

    
173
    $output = t('Import !csv_files with one or more of these columns: @columns.', array('!csv_files' => l(t('CSV files'), 'http://en.wikipedia.org/wiki/Comma-separated_values'), '@columns' => implode(', ', $sources)));
174
    $items = array();
175
    if ($uniques) {
176
      $items[] = format_plural(count($uniques),
177
        'Column <strong>@columns</strong> is mandatory and considered unique: only one item per @columns value will be created.',
178
        'Columns <strong>@columns</strong> are mandatory and values in these columns are considered unique: only one entry per value in one of these column will be created.',
179
        array(
180
          '@columns' => implode(', ', $uniques),
181
        )
182
      );
183
    }
184
    else {
185
      $items[] = t('No columns are unique. The import will only create new items, no items will be updated.');
186
    }
187
    $items[] = l(t('Download a template'), 'import/' . $this->id . '/template');
188
    $form['help'] = array(
189
      '#prefix' => '<div class="help">',
190
      '#suffix' => '</div>',
191
      'description' => array(
192
        '#prefix' => '<p>',
193
        '#markup' => $output,
194
        '#suffix' => '</p>',
195
      ),
196
      'list' => array(
197
        '#theme' => 'item_list',
198
        '#items' => $items,
199
      ),
200
    );
201
    $form['delimiter'] = array(
202
      '#type' => 'select',
203
      '#title' => t('Delimiter'),
204
      '#description' => t('The character that delimits fields in the CSV file.'),
205
      '#options' => $this->getAllDelimiterTypes(),
206
      '#default_value' => isset($source_config['delimiter']) ? $source_config['delimiter'] : ',',
207
    );
208
    $form['no_headers'] = array(
209
      '#type' => 'checkbox',
210
      '#title' => t('No Headers'),
211
      '#description' => t('Check if the imported CSV file does not start with a header row. If checked, mapping sources must be named \'0\', \'1\', \'2\' etc.'),
212
      '#default_value' => isset($source_config['no_headers']) ? $source_config['no_headers'] : 0,
213
    );
214
    $form['encoding'] = $this->configEncodingForm();
215
    if (isset($source_config['encoding'])) {
216
      $form['encoding']['#default_value'] = $source_config['encoding'];
217
    }
218
    return $form;
219
  }
220

    
221
  /**
222
   * Define default configuration.
223
   */
224
  public function configDefaults() {
225
    return array(
226
      'delimiter' => ',',
227
      'encoding' => 'UTF-8',
228
      'no_headers' => 0,
229
    ) + parent::configDefaults();
230
  }
231

    
232
  /**
233
   * Build configuration form.
234
   */
235
  public function configForm(&$form_state) {
236
    $form = array();
237
    $form['delimiter'] = array(
238
      '#type' => 'select',
239
      '#title' => t('Default delimiter'),
240
      '#description' => t('Default field delimiter.'),
241
      '#options' => $this->getAllDelimiterTypes(),
242
      '#default_value' => $this->config['delimiter'],
243
    );
244
    $form['no_headers'] = array(
245
      '#type' => 'checkbox',
246
      '#title' => t('No headers'),
247
      '#description' => t('Check if the imported CSV file does not start with a header row. If checked, mapping sources must be named \'0\', \'1\', \'2\' etc.'),
248
      '#default_value' => $this->config['no_headers'],
249
    );
250
    $form['encoding'] = $this->configEncodingForm();
251
    return $form;
252
  }
253

    
254
  /**
255
   * Builds configuration field for setting file encoding.
256
   *
257
   * If the mbstring extension is not available a markup render array
258
   * will be returned instead.
259
   *
260
   * @return array
261
   *   A renderable array.
262
   */
263
  public function configEncodingForm() {
264
    if (extension_loaded('mbstring') && variable_get('feeds_use_mbstring', TRUE)) {
265
      // Get the system's list of available encodings.
266
      $options = mb_list_encodings();
267
      // Make the key/values the same in the array.
268
      $options = array_combine($options, $options);
269
      // Sort alphabetically not-case sensitive.
270
      natcasesort($options);
271
      return array(
272
        '#type' => 'select',
273
        '#title' => t('File encoding'),
274
        '#description' => t('Performs character encoding conversion from selected option to UTF-8.'),
275
        '#options' => $options,
276
        '#default_value' => $this->config['encoding'],
277
      );
278
    }
279
    else {
280
      return array(
281
        '#markup' => '<em>' . t('PHP mbstring extension must be available for character encoding conversion.') . '</em>',
282
      );
283
    }
284
  }
285

    
286
  /**
287
   * {@inheritdoc}
288
   */
289
  public function getTemplate() {
290
    $mappings = feeds_importer($this->id)->processor->config['mappings'];
291
    $sources = $uniques = array();
292

    
293
    foreach ($mappings as $mapping) {
294
      if (in_array($mapping['source'], $uniques) || in_array($mapping['source'], $sources)) {
295
        // Skip columns we've already seen.
296
        continue;
297
      }
298

    
299
      if (!empty($mapping['unique'])) {
300
        $uniques[] = $mapping['source'];
301
      }
302
      else {
303
        $sources[] = $mapping['source'];
304
      }
305
    }
306

    
307
    $sep = $this->getDelimiterChar($this->config);
308
    $columns = array();
309

    
310
    foreach (array_merge($uniques, $sources) as $col) {
311
      if (strpos($col, $sep) !== FALSE) {
312
        $col = '"' . str_replace('"', '""', $col) . '"';
313
      }
314

    
315
      // Prevent columns without headers from being added to the template.
316
      if (strlen(trim($col))) {
317
        $columns[] = $col;
318
      }
319
    }
320

    
321
    $template_file_details = $this->getTemplateFileDetails($this->config);
322

    
323
    $filename = "{$this->id}_template.{$template_file_details['extension']}";
324
    $cache_control = 'max-age=60, must-revalidate';
325
    $content_disposition = 'attachment; filename="' . $filename . '"';
326
    $content_type = "{$template_file_details['mime_type']}; charset=utf-8";
327

    
328
    drupal_add_http_header('Cache-Control', $cache_control);
329
    drupal_add_http_header('Content-Disposition', $content_disposition);
330
    drupal_add_http_header('Content-type', $content_type);
331

    
332
    print implode($sep, $columns);
333
  }
334

    
335
  /**
336
   * Gets an associative array of the delimiters supported by this parser.
337
   *
338
   * The keys represent the value that is persisted into the database, and the
339
   * value represents the text that is shown in the admins UI.
340
   *
341
   * @return array
342
   *   The associative array of delimiter types to display name.
343
   */
344
  protected function getAllDelimiterTypes() {
345
    $delimiters = array(
346
      ',',
347
      ';',
348
      'TAB',
349
      '|',
350
      '+',
351
    );
352

    
353
    return array_combine($delimiters, $delimiters);
354
  }
355

    
356
  /**
357
   * Gets the appropriate delimiter character for the delimiter in the config.
358
   *
359
   * @param array $config
360
   *   The configuration for the parser.
361
   *
362
   * @return string
363
   *   The delimiter character.
364
   */
365
  protected function getDelimiterChar(array $config) {
366
    $config_delimiter = $config['delimiter'];
367

    
368
    switch ($config_delimiter) {
369
      case 'TAB':
370
        $delimiter = "\t";
371
        break;
372

    
373
      default:
374
        $delimiter = $config_delimiter;
375
        break;
376
    }
377

    
378
    return $delimiter;
379
  }
380

    
381
  /**
382
   * Gets details about the template file, for the delimiter in the config.
383
   *
384
   * The resulting details indicate the file extension and mime type for the
385
   * delimiter type.
386
   *
387
   * @param array $config
388
   *   The configuration for the parser.
389
   *
390
   * @return array
391
   *   An array with the following information:
392
   *     - 'extension': The file extension for the template ('tsv', 'csv', etc).
393
   *     - 'mime-type': The mime type for the template
394
   *       ('text/tab-separated-values', 'text/csv', etc).
395
   */
396
  protected function getTemplateFileDetails(array $config) {
397
    switch ($config['delimiter']) {
398
      case 'TAB':
399
        $extension = 'tsv';
400
        $mime_type = 'text/tab-separated-values';
401
        break;
402

    
403
      default:
404
        $extension = 'csv';
405
        $mime_type = 'text/csv';
406
        break;
407
    }
408

    
409
    return array(
410
      'extension' => $extension,
411
      'mime_type' => $mime_type,
412
    );
413
  }
414

    
415
}