Projet

Général

Profil

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

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

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
   * @return
64
   *   An array of lower-cased column names to use as keys for the parsed items.
65
   */
66
  protected function parseHeader(ParserCSV $parser, ParserCSVIterator $iterator) {
67
    $parser->setLineLimit(1);
68
    $rows = $parser->parse($iterator);
69
    if (!count($rows)) {
70
      return FALSE;
71
    }
72
    $header = array_shift($rows);
73
    foreach ($header as $i => $title) {
74
      $header[$i] = trim(drupal_strtolower($title));
75
    }
76
    return $header;
77
  }
78

    
79
  /**
80
   * Parse all of the items from the CSV.
81
   *
82
   * @param ParserCSV $parser
83
   * @param ParserCSVIterator $iterator
84
   * @return
85
   *   An array of rows of the CSV keyed by the column names previously set
86
   */
87
  protected function parseItems(ParserCSV $parser, ParserCSVIterator $iterator, $start = 0, $limit = 0) {
88
    $parser->setLineLimit($limit);
89
    $parser->setStartByte($start);
90
    $rows = $parser->parse($iterator);
91
    return $rows;
92
  }
93

    
94
  /**
95
   * Override parent::getMappingSources().
96
   */
97
  public function getMappingSources() {
98
    return FALSE;
99
  }
100

    
101
  /**
102
   * Override parent::getSourceElement() to use only lower keys.
103
   */
104
  public function getSourceElement(FeedsSource $source, FeedsParserResult $result, $element_key) {
105
    return parent::getSourceElement($source, $result, drupal_strtolower($element_key));
106
  }
107

    
108
  /**
109
   * Override parent::getMappingSourceList() to use only lower keys.
110
   */
111
  public function getMappingSourceList() {
112
    return array_map('drupal_strtolower', parent::getMappingSourceList());
113
  }
114

    
115
  /**
116
   * Define defaults.
117
   */
118
  public function sourceDefaults() {
119
    return array(
120
      'delimiter' => $this->config['delimiter'],
121
      'encoding' => $this->config['encoding'],
122
      'no_headers' => $this->config['no_headers'],
123
    );
124
  }
125

    
126
  /**
127
   * Source form.
128
   *
129
   * Show mapping configuration as a guidance for import form users.
130
   */
131
  public function sourceForm($source_config) {
132
    $form = array();
133
    $form['#weight'] = -10;
134

    
135
    $mappings = feeds_importer($this->id)->processor->config['mappings'];
136
    $sources = $uniques = array();
137
    foreach ($mappings as $mapping) {
138
      if (strpos($mapping['source'], ',') !== FALSE) {
139
        $sources[] = '"' . $mapping['source'] . '"';
140
      }
141
      else {
142
        $sources[] = $mapping['source'];
143
      }
144
      if (!empty($mapping['unique'])) {
145
        $uniques[] = $mapping['source'];
146
      }
147
    }
148
    $sources = array_unique($sources);
149

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

    
187
  /**
188
   * Define default configuration.
189
   */
190
  public function configDefaults() {
191
    return array(
192
      'delimiter' => ',',
193
      'encoding' => 'UTF-8',
194
      'no_headers' => 0,
195
    );
196
  }
197

    
198
  /**
199
   * Build configuration form.
200
   */
201
  public function configForm(&$form_state) {
202
    $form = array();
203
    $form['delimiter'] = array(
204
      '#type' => 'select',
205
      '#title' => t('Default delimiter'),
206
      '#description' => t('Default field delimiter.'),
207
      '#options' => $this->getAllDelimiterTypes(),
208
      '#default_value' => $this->config['delimiter'],
209
    );
210
    $form['no_headers'] = array(
211
      '#type' => 'checkbox',
212
      '#title' => t('No headers'),
213
      '#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.'),
214
      '#default_value' => $this->config['no_headers'],
215
    );
216
    $form['encoding'] = $this->configEncodingForm();
217
    return $form;
218
  }
219

    
220
  /**
221
   * Builds configuration field for setting file encoding.
222
   *
223
   * If the mbstring extension is not available a markup render array
224
   * will be returned instead.
225
   *
226
   * @return array
227
   *   A renderable array.
228
   */
229
  public function configEncodingForm() {
230
    if (extension_loaded('mbstring') && variable_get('feeds_use_mbstring', TRUE)) {
231
      // Get the system's list of available encodings.
232
      $options = mb_list_encodings();
233
      // Make the key/values the same in the array.
234
      $options = array_combine($options, $options);
235
      // Sort alphabetically not-case sensitive.
236
      natcasesort($options);
237
      return array(
238
        '#type' => 'select',
239
        '#title' => t('File encoding'),
240
        '#description' => t('Performs character encoding conversion from selected option to UTF-8.'),
241
        '#options' => $options,
242
        '#default_value' => $this->config['encoding'],
243
      );
244
    }
245
    else {
246
      return array(
247
        '#markup' => '<em>' . t('PHP mbstring extension must be available for character encoding conversion.') . '</em>',
248
      );
249
    }
250
  }
251

    
252
  public function getTemplate() {
253
    $mappings = feeds_importer($this->id)->processor->config['mappings'];
254
    $sources = $uniques = array();
255

    
256
    foreach ($mappings as $mapping) {
257
      if (in_array($mapping['source'], $uniques) || in_array($mapping['source'], $sources)) {
258
        // Skip columns we've already seen.
259
        continue;
260
      }
261

    
262
      if (!empty($mapping['unique'])) {
263
        $uniques[] = $mapping['source'];
264
      }
265
      else {
266
        $sources[] = $mapping['source'];
267
      }
268
    }
269

    
270
    $sep = $this->getDelimiterChar($this->config);
271
    $columns = array();
272

    
273
    foreach (array_merge($uniques, $sources) as $col) {
274
      if (strpos($col, $sep) !== FALSE) {
275
        $col = '"' . str_replace('"', '""', $col) . '"';
276
      }
277

    
278
      $columns[] = $col;
279
    }
280

    
281
    $template_file_details = $this->getTemplateFileDetails($this->config);
282

    
283
    $filename = "{$this->id}_template.{$template_file_details['extension']}";
284
    $cache_control = 'max-age=60, must-revalidate';
285
    $content_disposition = 'attachment; filename="' . $filename . '"';
286
    $content_type = "{$template_file_details['mime_type']}; charset=utf-8";
287

    
288
    drupal_add_http_header('Cache-Control', $cache_control);
289
    drupal_add_http_header('Content-Disposition', $content_disposition);
290
    drupal_add_http_header('Content-type', $content_type);
291

    
292
    print implode($sep, $columns);
293
  }
294

    
295
  /**
296
   * Gets an associative array of the delimiters supported by this parser.
297
   *
298
   * The keys represent the value that is persisted into the database, and the
299
   * value represents the text that is shown in the admins UI.
300
   *
301
   * @return array
302
   *   The associative array of delimiter types to display name.
303
   */
304
  protected function getAllDelimiterTypes() {
305
    $delimiters = array(
306
      ',',
307
      ';',
308
      'TAB',
309
      '|',
310
      '+',
311
    );
312

    
313
    return array_combine($delimiters, $delimiters);
314
  }
315

    
316
  /**
317
   * Gets the appropriate delimiter character for the delimiter in the config.
318
   *
319
   * @param array $config
320
   *   The configuration for the parser.
321
   *
322
   * @return string
323
   *   The delimiter character.
324
   */
325
  protected function getDelimiterChar(array $config) {
326
    $config_delimiter = $config['delimiter'];
327

    
328
    switch ($config_delimiter) {
329
      case 'TAB':
330
        $delimiter = "\t";
331
        break;
332

    
333
      default:
334
        $delimiter = $config_delimiter;
335
        break;
336
    }
337

    
338
    return $delimiter;
339
  }
340

    
341
  /**
342
   * Gets details about the template file, for the delimiter in the config.
343
   *
344
   * The resulting details indicate the file extension and mime type for the
345
   * delimiter type.
346
   *
347
   * @param array $config
348
   *   The configuration for the parser.
349
   *
350
   * @return array
351
   *   An array with the following information:
352
   *     - 'extension': The file extension for the template ('tsv', 'csv', etc).
353
   *     - 'mime-type': The mime type for the template
354
   *       ('text/tab-separated-values', 'text/csv', etc).
355
   */
356
  protected function getTemplateFileDetails(array $config) {
357
    switch ($config['delimiter']) {
358
      case 'TAB':
359
        $extension = 'tsv';
360
        $mime_type = 'text/tab-separated-values';
361
        break;
362

    
363
      default:
364
        $extension = 'csv';
365
        $mime_type = 'text/csv';
366
        break;
367
    }
368

    
369
    return array(
370
      'extension' => $extension,
371
      'mime_type' => $mime_type,
372
    );
373
  }
374
}