Projet

Général

Profil

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

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

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
    $parser->setLineLimit(1);
70
    $rows = $parser->parse($iterator);
71
    if (!count($rows)) {
72
      return FALSE;
73
    }
74
    $header = array_shift($rows);
75
    foreach ($header as $i => $title) {
76
      $header[$i] = trim(drupal_strtolower($title));
77
    }
78
    return $header;
79
  }
80

    
81
  /**
82
   * Parse all of the items from the CSV.
83
   *
84
   * @param ParserCSV $parser
85
   * @param ParserCSVIterator $iterator
86
   * @param int $start
87
   *   The byte number from where to start parsing the file.
88
   * @param int $limit
89
   *   The number of lines to parse, 0 for all lines.
90
   *
91
   * @return array
92
   *   An array of rows of the CSV keyed by the column names previously set.
93
   */
94
  protected function parseItems(ParserCSV $parser, ParserCSVIterator $iterator, $start = 0, $limit = 0) {
95
    $parser->setLineLimit($limit);
96
    $parser->setStartByte($start);
97
    $rows = $parser->parse($iterator);
98
    return $rows;
99
  }
100

    
101
  /**
102
   * Override parent::getMappingSources().
103
   */
104
  public function getMappingSources() {
105
    return FALSE;
106
  }
107

    
108
  /**
109
   * Override parent::getSourceElement() to use only lower keys.
110
   */
111
  public function getSourceElement(FeedsSource $source, FeedsParserResult $result, $element_key) {
112
    return parent::getSourceElement($source, $result, drupal_strtolower($element_key));
113
  }
114

    
115
  /**
116
   * Override parent::getMappingSourceList() to use only lower keys.
117
   */
118
  public function getMappingSourceList() {
119
    return array_map('drupal_strtolower', parent::getMappingSourceList());
120
  }
121

    
122
  /**
123
   * Define defaults.
124
   */
125
  public function sourceDefaults() {
126
    return array(
127
      'delimiter' => $this->config['delimiter'],
128
      'encoding' => $this->config['encoding'],
129
      'no_headers' => $this->config['no_headers'],
130
    );
131
  }
132

    
133
  /**
134
   * Source form.
135
   *
136
   * Show mapping configuration as a guidance for import form users.
137
   */
138
  public function sourceForm($source_config) {
139
    $form = array();
140
    $form['#weight'] = -10;
141

    
142
    $mappings = feeds_importer($this->id)->processor->config['mappings'];
143
    $sources = $uniques = array();
144
    foreach ($mappings as $mapping) {
145
      if (strpos($mapping['source'], ',') !== FALSE) {
146
        $sources[] = '"' . $mapping['source'] . '"';
147
      }
148
      else {
149
        $sources[] = $mapping['source'];
150
      }
151
      if (!empty($mapping['unique'])) {
152
        $uniques[] = $mapping['source'];
153
      }
154
    }
155
    $sources = array_unique($sources);
156

    
157
    $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)));
158
    $items = array();
159
    if ($uniques) {
160
      $items[] = format_plural(count($uniques),
161
        'Column <strong>@columns</strong> is mandatory and considered unique: only one item per @columns value will be created.',
162
        '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.',
163
        array(
164
          '@columns' => implode(', ', $uniques),
165
        )
166
      );
167
    }
168
    else {
169
      $items[] = t('No columns are unique. The import will only create new items, no items will be updated.');
170
    }
171
    $items[] = l(t('Download a template'), 'import/' . $this->id . '/template');
172
    $form['help'] = array(
173
      '#prefix' => '<div class="help">',
174
      '#suffix' => '</div>',
175
      'description' => array(
176
        '#prefix' => '<p>',
177
        '#markup' => $output,
178
        '#suffix' => '</p>',
179
      ),
180
      'list' => array(
181
        '#theme' => 'item_list',
182
        '#items' => $items,
183
      ),
184
    );
185
    $form['delimiter'] = array(
186
      '#type' => 'select',
187
      '#title' => t('Delimiter'),
188
      '#description' => t('The character that delimits fields in the CSV file.'),
189
      '#options' => $this->getAllDelimiterTypes(),
190
      '#default_value' => isset($source_config['delimiter']) ? $source_config['delimiter'] : ',',
191
    );
192
    $form['no_headers'] = array(
193
      '#type' => 'checkbox',
194
      '#title' => t('No Headers'),
195
      '#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.'),
196
      '#default_value' => isset($source_config['no_headers']) ? $source_config['no_headers'] : 0,
197
    );
198
    $form['encoding'] = $this->configEncodingForm();
199
    if (isset($source_config['encoding'])) {
200
      $form['encoding']['#default_value'] = $source_config['encoding'];
201
    }
202
    return $form;
203
  }
204

    
205
  /**
206
   * Define default configuration.
207
   */
208
  public function configDefaults() {
209
    return array(
210
      'delimiter' => ',',
211
      'encoding' => 'UTF-8',
212
      'no_headers' => 0,
213
    );
214
  }
215

    
216
  /**
217
   * Build configuration form.
218
   */
219
  public function configForm(&$form_state) {
220
    $form = array();
221
    $form['delimiter'] = array(
222
      '#type' => 'select',
223
      '#title' => t('Default delimiter'),
224
      '#description' => t('Default field delimiter.'),
225
      '#options' => $this->getAllDelimiterTypes(),
226
      '#default_value' => $this->config['delimiter'],
227
    );
228
    $form['no_headers'] = array(
229
      '#type' => 'checkbox',
230
      '#title' => t('No headers'),
231
      '#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.'),
232
      '#default_value' => $this->config['no_headers'],
233
    );
234
    $form['encoding'] = $this->configEncodingForm();
235
    return $form;
236
  }
237

    
238
  /**
239
   * Builds configuration field for setting file encoding.
240
   *
241
   * If the mbstring extension is not available a markup render array
242
   * will be returned instead.
243
   *
244
   * @return array
245
   *   A renderable array.
246
   */
247
  public function configEncodingForm() {
248
    if (extension_loaded('mbstring') && variable_get('feeds_use_mbstring', TRUE)) {
249
      // Get the system's list of available encodings.
250
      $options = mb_list_encodings();
251
      // Make the key/values the same in the array.
252
      $options = array_combine($options, $options);
253
      // Sort alphabetically not-case sensitive.
254
      natcasesort($options);
255
      return array(
256
        '#type' => 'select',
257
        '#title' => t('File encoding'),
258
        '#description' => t('Performs character encoding conversion from selected option to UTF-8.'),
259
        '#options' => $options,
260
        '#default_value' => $this->config['encoding'],
261
      );
262
    }
263
    else {
264
      return array(
265
        '#markup' => '<em>' . t('PHP mbstring extension must be available for character encoding conversion.') . '</em>',
266
      );
267
    }
268
  }
269

    
270
  public function getTemplate() {
271
    $mappings = feeds_importer($this->id)->processor->config['mappings'];
272
    $sources = $uniques = array();
273

    
274
    foreach ($mappings as $mapping) {
275
      if (in_array($mapping['source'], $uniques) || in_array($mapping['source'], $sources)) {
276
        // Skip columns we've already seen.
277
        continue;
278
      }
279

    
280
      if (!empty($mapping['unique'])) {
281
        $uniques[] = $mapping['source'];
282
      }
283
      else {
284
        $sources[] = $mapping['source'];
285
      }
286
    }
287

    
288
    $sep = $this->getDelimiterChar($this->config);
289
    $columns = array();
290

    
291
    foreach (array_merge($uniques, $sources) as $col) {
292
      if (strpos($col, $sep) !== FALSE) {
293
        $col = '"' . str_replace('"', '""', $col) . '"';
294
      }
295

    
296
      $columns[] = $col;
297
    }
298

    
299
    $template_file_details = $this->getTemplateFileDetails($this->config);
300

    
301
    $filename = "{$this->id}_template.{$template_file_details['extension']}";
302
    $cache_control = 'max-age=60, must-revalidate';
303
    $content_disposition = 'attachment; filename="' . $filename . '"';
304
    $content_type = "{$template_file_details['mime_type']}; charset=utf-8";
305

    
306
    drupal_add_http_header('Cache-Control', $cache_control);
307
    drupal_add_http_header('Content-Disposition', $content_disposition);
308
    drupal_add_http_header('Content-type', $content_type);
309

    
310
    print implode($sep, $columns);
311
  }
312

    
313
  /**
314
   * Gets an associative array of the delimiters supported by this parser.
315
   *
316
   * The keys represent the value that is persisted into the database, and the
317
   * value represents the text that is shown in the admins UI.
318
   *
319
   * @return array
320
   *   The associative array of delimiter types to display name.
321
   */
322
  protected function getAllDelimiterTypes() {
323
    $delimiters = array(
324
      ',',
325
      ';',
326
      'TAB',
327
      '|',
328
      '+',
329
    );
330

    
331
    return array_combine($delimiters, $delimiters);
332
  }
333

    
334
  /**
335
   * Gets the appropriate delimiter character for the delimiter in the config.
336
   *
337
   * @param array $config
338
   *   The configuration for the parser.
339
   *
340
   * @return string
341
   *   The delimiter character.
342
   */
343
  protected function getDelimiterChar(array $config) {
344
    $config_delimiter = $config['delimiter'];
345

    
346
    switch ($config_delimiter) {
347
      case 'TAB':
348
        $delimiter = "\t";
349
        break;
350

    
351
      default:
352
        $delimiter = $config_delimiter;
353
        break;
354
    }
355

    
356
    return $delimiter;
357
  }
358

    
359
  /**
360
   * Gets details about the template file, for the delimiter in the config.
361
   *
362
   * The resulting details indicate the file extension and mime type for the
363
   * delimiter type.
364
   *
365
   * @param array $config
366
   *   The configuration for the parser.
367
   *
368
   * @return array
369
   *   An array with the following information:
370
   *     - 'extension': The file extension for the template ('tsv', 'csv', etc).
371
   *     - 'mime-type': The mime type for the template
372
   *       ('text/tab-separated-values', 'text/csv', etc).
373
   */
374
  protected function getTemplateFileDetails(array $config) {
375
    switch ($config['delimiter']) {
376
      case 'TAB':
377
        $extension = 'tsv';
378
        $mime_type = 'text/tab-separated-values';
379
        break;
380

    
381
      default:
382
        $extension = 'csv';
383
        $mime_type = 'text/csv';
384
        break;
385
    }
386

    
387
    return array(
388
      'extension' => $extension,
389
      'mime_type' => $mime_type,
390
    );
391
  }
392
}