Projet

Général

Profil

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

root / drupal7 / sites / all / modules / feeds / libraries / ParserCSV.inc @ ed9a13f1

1
<?php
2

    
3
/**
4
 * @file
5
 * Contains CSV Parser.
6
 *
7
 * Functions in this file are independent of the Feeds specific implementation.
8
 * Thanks to jpetso http://drupal.org/user/56020 for most of the code in this
9
 * file.
10
 */
11

    
12
/**
13
 * Text lines from file iterator.
14
 */
15
class ParserCSVIterator implements Iterator {
16
  private $handle;
17
  private $currentLine;
18
  private $currentPos;
19

    
20
  /**
21
   * {@inheritdoc}
22
   */
23
  public function __construct($filepath) {
24
    $this->handle = fopen($filepath, 'r');
25
    $this->currentLine = NULL;
26
    $this->currentPos = NULL;
27
  }
28

    
29
  /**
30
   * {@inheritdoc}
31
   */
32
  public function __destruct() {
33
    if ($this->handle) {
34
      fclose($this->handle);
35
    }
36
  }
37

    
38
  /**
39
   * Closes the current file.
40
   */
41
  public function releaseHandler() {
42
    if ($this->handle) {
43
      fclose($this->handle);
44
      $this->handle = NULL;
45
    }
46
  }
47

    
48
  /**
49
   * {@inheritdoc}
50
   */
51
  public function rewind($pos = 0) {
52
    if ($this->handle) {
53
      fseek($this->handle, $pos);
54
      $this->next();
55
    }
56
  }
57

    
58
  /**
59
   * {@inheritdoc}
60
   */
61
  public function next() {
62
    if ($this->handle) {
63
      $this->currentLine = feof($this->handle) ? NULL : fgets($this->handle);
64
      $this->currentPos = ftell($this->handle);
65
      return $this->currentLine;
66
    }
67
  }
68

    
69
  /**
70
   * {@inheritdoc}
71
   */
72
  public function valid() {
73
    return isset($this->currentLine);
74
  }
75

    
76
  /**
77
   * {@inheritdoc}
78
   */
79
  public function current() {
80
    return $this->currentLine;
81
  }
82

    
83
  /**
84
   * {@inheritdoc}
85
   */
86
  public function currentPos() {
87
    return $this->currentPos;
88
  }
89

    
90
  /**
91
   * {@inheritdoc}
92
   */
93
  public function key() {
94
    return 'line';
95
  }
96

    
97
}
98

    
99
/**
100
 * Functionality to parse CSV files into a two dimensional array.
101
 */
102
class ParserCSV {
103
  private $delimiter;
104
  private $fromEncoding;
105
  private $toEncoding;
106
  private $skipFirstLine;
107
  private $columnNames;
108
  private $timeout;
109
  private $timeoutReached;
110
  private $startByte;
111
  private $lineLimit;
112
  private $lastLinePos;
113
  private $useMbString;
114

    
115
  /**
116
   * {@inheritdoc}
117
   */
118
  public function __construct() {
119
    $this->delimiter = ',';
120
    $this->fromEncoding = 'UTF-8';
121
    $this->toEncoding = 'UTF-8';
122
    $this->skipFirstLine = FALSE;
123
    $this->columnNames = FALSE;
124
    $this->timeout = FALSE;
125
    $this->timeoutReached = FALSE;
126
    $this->startByte = 0;
127
    $this->lineLimit = 0;
128
    $this->lastLinePos = 0;
129
    ini_set('auto_detect_line_endings', TRUE);
130
    if (extension_loaded('mbstring') && variable_get('feeds_use_mbstring', TRUE)) {
131
      $this->useMbString = TRUE;
132
    }
133
  }
134

    
135
  /**
136
   * Set the column delimiter string.
137
   * By default, the comma (',') is used as delimiter.
138
   */
139
  public function setDelimiter($delimiter) {
140
    $this->delimiter = $delimiter;
141
  }
142

    
143
  /**
144
   * Sets the source file encoding.
145
   *
146
   * By default, the encoding is UTF-8.
147
   *
148
   * @param string $encoding
149
   *   The encoding to set.
150
   */
151
  public function setEncoding($encoding) {
152
    $this->fromEncoding = $encoding;
153
  }
154

    
155
  /**
156
   * Set this to TRUE if the parser should skip the first line of the CSV text,
157
   * which might be desired if the first line contains the column names.
158
   * By default, this is set to FALSE and the first line is not skipped.
159
   */
160
  public function setSkipFirstLine($skipFirstLine) {
161
    $this->skipFirstLine = $skipFirstLine;
162
  }
163

    
164
  /**
165
   * Specify an array of column names if you know them in advance, or FALSE
166
   * (which is the default) to unset any prior column names. If no column names
167
   * are set, the parser will put each row into a simple numerically indexed
168
   * array. If column names are given, the parser will create arrays with
169
   * these column names as array keys instead.
170
   */
171
  public function setColumnNames($columnNames) {
172
    $this->columnNames = $columnNames;
173
  }
174

    
175
  /**
176
   * Define the time (in milliseconds) after which the parser stops parsing,
177
   * even if it has not yet finished processing the CSV data. If the timeout
178
   * has been reached before parsing is done, the parse() method will return
179
   * an incomplete list of rows - a single row will never be cut off in the
180
   * middle, though. By default, no timeout (@p $timeout == FALSE) is defined.
181
   *
182
   * You can check if the timeout has been reached by calling the
183
   * timeoutReached() method after parse() has been called.
184
   */
185
  public function setTimeout($timeout) {
186
    $this->timeout = $timeout;
187
  }
188

    
189
  /**
190
   * After calling the parse() method, determine if the timeout (set by the
191
   * setTimeout() method) has been reached.
192
   *
193
   * @deprecated Use lastLinePos() instead to determine whether a file has
194
   *   finished parsing.
195
   */
196
  public function timeoutReached() {
197
    return $this->timeoutReached;
198
  }
199

    
200
  /**
201
   * Define the number of lines to parse in one parsing operation.
202
   *
203
   * By default, all lines of a file are being parsed.
204
   */
205
  public function setLineLimit($lines) {
206
    $this->lineLimit = $lines;
207
  }
208

    
209
  /**
210
   * Get the byte number where the parser left off after last parse() call.
211
   *
212
   * @return int
213
   *   0 if all lines or no line has been parsed, the byte position of where a
214
   *   timeout or the line limit has been reached otherwise. This position can be
215
   *   used to set the start byte for the next iteration after parse() has
216
   *   reached the timeout set with setTimeout() or the line limit set with
217
   *   setLineLimit().
218
   *
219
   * @see ParserCSV::setStartByte()
220
   */
221
  public function lastLinePos() {
222
    return $this->lastLinePos;
223
  }
224

    
225
  /**
226
   * Set the byte where file should be started to read.
227
   *
228
   * Useful when parsing a file in batches.
229
   */
230
  public function setStartByte($start) {
231
    return $this->startByte = $start;
232
  }
233

    
234
  /**
235
   * Parse CSV files into a two dimensional array.
236
   *
237
   * @param Iterator $lineIterator
238
   *   An Iterator object that yields line strings, e.g. ParserCSVIterator.
239
   *
240
   * @return array
241
   *   Two dimensional array that contains the data in the CSV file.
242
   */
243
  public function parse(Iterator $lineIterator) {
244
    $skipLine = $this->skipFirstLine;
245
    $rows = array();
246

    
247
    $this->timeoutReached = FALSE;
248
    $this->lastLinePos = 0;
249
    $maxTime = empty($this->timeout) ? FALSE : (microtime() + $this->timeout);
250
    $linesParsed = 0;
251

    
252
    for ($lineIterator->rewind($this->startByte); $lineIterator->valid(); $lineIterator->next()) {
253

    
254
      // Make really sure we've got lines without trailing newlines.
255
      $line = trim($this->fixEncoding($lineIterator->current()), "\r\n");
256

    
257
      // Skip empty lines.
258
      if (empty($line)) {
259
        continue;
260
      }
261
      // If the first line contains column names, skip it.
262
      if ($skipLine) {
263
        $skipLine = FALSE;
264
        continue;
265
      }
266

    
267
      // The actual parser. explode() is unfortunately not suitable because the
268
      // delimiter might be located inside a quoted field, and that would break
269
      // the field and/or require additional effort to re-join the fields.
270
      $quoted = FALSE;
271
      $currentIndex = 0;
272
      $currentField = '';
273
      $fields = array();
274

    
275
      // We must use strlen() as we're parsing byte by byte using strpos(), so
276
      // drupal_strlen() will not work properly.
277
      while ($currentIndex <= strlen($line)) {
278
        if ($quoted) {
279
          $nextQuoteIndex = strpos($line, '"', $currentIndex);
280

    
281
          if ($nextQuoteIndex === FALSE) {
282
            // There's a line break before the quote is closed, so fetch the
283
            // next line and start from there.
284
            $currentField .= substr($line, $currentIndex);
285
            $lineIterator->next();
286

    
287
            if (!$lineIterator->valid()) {
288
              // Whoa, an unclosed quote! Well whatever, let's just ignore
289
              // that shortcoming and record it nevertheless.
290
              $fields[] = $currentField;
291
              break;
292
            }
293
            // Ok, so, on with fetching the next line, as mentioned above.
294
            $currentField .= "\n";
295
            $line = trim($this->fixEncoding($lineIterator->current()), "\r\n");
296
            $currentIndex = 0;
297
            continue;
298
          }
299

    
300
          // There's actually another quote in this line...
301
          // find out whether it's escaped or not.
302
          $currentField .= substr($line, $currentIndex, $nextQuoteIndex - $currentIndex);
303

    
304
          if (isset($line[$nextQuoteIndex + 1]) && $line[$nextQuoteIndex + 1] === '"') {
305
            // Escaped quote, add a single one to the field and proceed quoted.
306
            $currentField .= '"';
307
            $currentIndex = $nextQuoteIndex + 2;
308
          }
309
          else {
310
            // End of the quoted section, close the quote and let the
311
            // $quoted == FALSE block finalize the field.
312
            $quoted = FALSE;
313
            $currentIndex = $nextQuoteIndex + 1;
314
          }
315
        }
316
        // $quoted == FALSE.
317
        else {
318
          // First, let's find out where the next character of interest is.
319
          $nextQuoteIndex = strpos($line, '"', $currentIndex);
320
          $nextDelimiterIndex = strpos($line, $this->delimiter, $currentIndex);
321

    
322
          if ($nextQuoteIndex === FALSE) {
323
            $nextIndex = $nextDelimiterIndex;
324
          }
325
          elseif ($nextDelimiterIndex === FALSE) {
326
            $nextIndex = $nextQuoteIndex;
327
          }
328
          else {
329
            $nextIndex = min($nextQuoteIndex, $nextDelimiterIndex);
330
          }
331

    
332
          if ($nextIndex === FALSE) {
333
            // This line is done, add the rest of it as last field.
334
            $currentField .= substr($line, $currentIndex);
335
            $fields[] = $currentField;
336
            break;
337
          }
338
          elseif ($line[$nextIndex] === $this->delimiter[0]) {
339
            $length = ($nextIndex + strlen($this->delimiter) - 1) - $currentIndex;
340
            $currentField .= substr($line, $currentIndex, $length);
341
            $fields[] = $currentField;
342
            $currentField = '';
343
            $currentIndex += $length + 1;
344
            // Continue with the next field.
345
          }
346
          // $line[$nextIndex] == '"'.
347
          else {
348
            $quoted = TRUE;
349
            $currentField .= substr($line, $currentIndex, $nextIndex - $currentIndex);
350
            $currentIndex = $nextIndex + 1;
351
            // Continue this field in the $quoted == TRUE block.
352
          }
353
        }
354
      }
355
      // End of CSV parser. We've now got all the fields of the line as strings
356
      // in the $fields array.
357
      if (empty($this->columnNames)) {
358
        $row = $fields;
359
      }
360
      else {
361
        $row = array();
362
        foreach ($this->columnNames as $columnName) {
363
          $field = array_shift($fields);
364
          $row[$columnName] = isset($field) ? $field : '';
365
        }
366
      }
367
      $rows[] = $row;
368

    
369
      // Quit parsing if timeout has been reached or requested lines have been
370
      // reached.
371
      if (!empty($maxTime) && microtime() > $maxTime) {
372
        $this->timeoutReached = TRUE;
373
        $this->lastLinePos = $lineIterator->currentPos();
374
        break;
375
      }
376
      $linesParsed++;
377
      if ($this->lineLimit && $linesParsed >= $this->lineLimit) {
378
        $this->lastLinePos = $lineIterator->currentPos();
379
        break;
380
      }
381
    }
382
    return $rows;
383
  }
384

    
385
  /**
386
   * Converts encoding of input data.
387
   *
388
   * @param string $data
389
   *   A chunk of data.
390
   *
391
   * @return string
392
   *   The encoded data.
393
   *
394
   * @throws ParserCSVEncodingException
395
   *   Thrown when a given encoding does not match.
396
   */
397
  public function fixEncoding($data) {
398
    if ($this->useMbString) {
399
      if (mb_check_encoding($data, $this->fromEncoding)) {
400
        if ($this->toEncoding != $this->fromEncoding) {
401
          // Convert encoding. The conversion is to UTF-8 by default to prevent
402
          // SQL errors.
403
          $data = mb_convert_encoding($data, $this->toEncoding, $this->fromEncoding);
404
        }
405
      }
406
      else {
407
        throw new ParserCSVEncodingException(t('Source file is not in %encoding encoding.', array('%encoding' => $this->fromEncoding)));
408
      }
409
    }
410

    
411
    return $data;
412
  }
413

    
414
}
415

    
416
/**
417
 * Exception thrown when an encoding error occurs during parsing.
418
 */
419
class ParserCSVEncodingException extends Exception {}