Projet

Général

Profil

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

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

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
  public function __construct($filepath) {
21
    $this->handle = fopen($filepath, 'r');
22
    $this->currentLine = NULL;
23
    $this->currentPos = NULL;
24
  }
25

    
26
  function __destruct() {
27
    if ($this->handle) {
28
      fclose($this->handle);
29
    }
30
  }
31

    
32
  public function rewind($pos = 0) {
33
    if ($this->handle) {
34
      fseek($this->handle, $pos);
35
      $this->next();
36
    }
37
  }
38

    
39
  public function next() {
40
    if ($this->handle) {
41
      $this->currentLine = feof($this->handle) ? NULL : fgets($this->handle);
42
      $this->currentPos = ftell($this->handle);
43
      return $this->currentLine;
44
    }
45
  }
46

    
47
  public function valid() {
48
    return isset($this->currentLine);
49
  }
50

    
51
  public function current() {
52
    return $this->currentLine;
53
  }
54

    
55
  public function currentPos() {
56
    return $this->currentPos;
57
  }
58

    
59
  public function key() {
60
    return 'line';
61
  }
62
}
63

    
64
/**
65
 * Functionality to parse CSV files into a two dimensional array.
66
 */
67
class ParserCSV {
68
  private $delimiter;
69
  private $fromEncoding;
70
  private $toEncoding;
71
  private $skipFirstLine;
72
  private $columnNames;
73
  private $timeout;
74
  private $timeoutReached;
75
  private $startByte;
76
  private $lineLimit;
77
  private $lastLinePos;
78
  private $useMbString;
79

    
80
  public function __construct() {
81
    $this->delimiter = ',';
82
    $this->fromEncoding = 'UTF-8';
83
    $this->toEncoding = 'UTF-8';
84
    $this->skipFirstLine = FALSE;
85
    $this->columnNames = FALSE;
86
    $this->timeout = FALSE;
87
    $this->timeoutReached = FALSE;
88
    $this->startByte = 0;
89
    $this->lineLimit = 0;
90
    $this->lastLinePos = 0;
91
    ini_set('auto_detect_line_endings', TRUE);
92
    if (extension_loaded('mbstring') && variable_get('feeds_use_mbstring', TRUE)) {
93
      $this->useMbString = TRUE;
94
    }
95
  }
96

    
97
  /**
98
   * Set the column delimiter string.
99
   * By default, the comma (',') is used as delimiter.
100
   */
101
  public function setDelimiter($delimiter) {
102
    $this->delimiter = $delimiter;
103
  }
104

    
105
  /**
106
   * Sets the source file encoding.
107
   *
108
   * By default, the encoding is UTF-8.
109
   *
110
   * @param string $encoding
111
   *   The encoding to set.
112
   */
113
  public function setEncoding($encoding) {
114
    $this->fromEncoding = $encoding;
115
  }
116

    
117
  /**
118
   * Set this to TRUE if the parser should skip the first line of the CSV text,
119
   * which might be desired if the first line contains the column names.
120
   * By default, this is set to FALSE and the first line is not skipped.
121
   */
122
  public function setSkipFirstLine($skipFirstLine) {
123
    $this->skipFirstLine = $skipFirstLine;
124
  }
125

    
126
  /**
127
   * Specify an array of column names if you know them in advance, or FALSE
128
   * (which is the default) to unset any prior column names. If no column names
129
   * are set, the parser will put each row into a simple numerically indexed
130
   * array. If column names are given, the parser will create arrays with
131
   * these column names as array keys instead.
132
   */
133
  public function setColumnNames($columnNames) {
134
    $this->columnNames = $columnNames;
135
  }
136

    
137
  /**
138
   * Define the time (in milliseconds) after which the parser stops parsing,
139
   * even if it has not yet finished processing the CSV data. If the timeout
140
   * has been reached before parsing is done, the parse() method will return
141
   * an incomplete list of rows - a single row will never be cut off in the
142
   * middle, though. By default, no timeout (@p $timeout == FALSE) is defined.
143
   *
144
   * You can check if the timeout has been reached by calling the
145
   * timeoutReached() method after parse() has been called.
146
   */
147
  public function setTimeout($timeout) {
148
    $this->timeout = $timeout;
149
  }
150

    
151
  /**
152
   * After calling the parse() method, determine if the timeout (set by the
153
   * setTimeout() method) has been reached.
154
   *
155
   * @deprecated Use lastLinePos() instead to determine whether a file has
156
   *   finished parsing.
157
   */
158
  public function timeoutReached() {
159
    return $this->timeoutReached;
160
  }
161

    
162
  /**
163
   * Define the number of lines to parse in one parsing operation.
164
   *
165
   * By default, all lines of a file are being parsed.
166
   */
167
  public function setLineLimit($lines) {
168
    $this->lineLimit = $lines;
169
  }
170

    
171
  /**
172
   * Get the byte number where the parser left off after last parse() call.
173
   *
174
   * @return
175
   *  0 if all lines or no line has been parsed, the byte position of where a
176
   *  timeout or the line limit has been reached otherwise. This position can be
177
   *  used to set the start byte for the next iteration after parse() has
178
   *  reached the timeout set with setTimeout() or the line limit set with
179
   *  setLineLimit().
180
   *
181
   * @see ParserCSV::setStartByte()
182
   */
183
  public function lastLinePos() {
184
    return $this->lastLinePos;
185
  }
186

    
187
  /**
188
   * Set the byte where file should be started to read.
189
   *
190
   * Useful when parsing a file in batches.
191
   */
192
  public function setStartByte($start) {
193
    return $this->startByte = $start;
194
  }
195

    
196
  /**
197
   * Parse CSV files into a two dimensional array.
198
   *
199
   * @param Iterator $lineIterator
200
   *   An Iterator object that yields line strings, e.g. ParserCSVIterator.
201
   * @param $start
202
   *   The byte number from where to start parsing the file.
203
   * @param $lines
204
   *   The number of lines to parse, 0 for all lines.
205
   * @return
206
   *   Two dimensional array that contains the data in the CSV file.
207
   */
208
  public function parse(Iterator $lineIterator) {
209
    $skipLine = $this->skipFirstLine;
210
    $rows = array();
211

    
212
    $this->timeoutReached = FALSE;
213
    $this->lastLinePos = 0;
214
    $maxTime = empty($this->timeout) ? FALSE : (microtime() + $this->timeout);
215
    $linesParsed = 0;
216

    
217
    for ($lineIterator->rewind($this->startByte); $lineIterator->valid(); $lineIterator->next()) {
218

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

    
222
      // Skip empty lines.
223
      if (empty($line)) {
224
        continue;
225
      }
226
      // If the first line contains column names, skip it.
227
      if ($skipLine) {
228
        $skipLine = FALSE;
229
        continue;
230
      }
231

    
232
      // The actual parser. explode() is unfortunately not suitable because the
233
      // delimiter might be located inside a quoted field, and that would break
234
      // the field and/or require additional effort to re-join the fields.
235
      $quoted = FALSE;
236
      $currentIndex = 0;
237
      $currentField = '';
238
      $fields = array();
239

    
240
      // We must use strlen() as we're parsing byte by byte using strpos(), so
241
      // drupal_strlen() will not work properly.
242
      while ($currentIndex <= strlen($line)) {
243
        if ($quoted) {
244
          $nextQuoteIndex = strpos($line, '"', $currentIndex);
245

    
246
          if ($nextQuoteIndex === FALSE) {
247
            // There's a line break before the quote is closed, so fetch the
248
            // next line and start from there.
249
            $currentField .= substr($line, $currentIndex);
250
            $lineIterator->next();
251

    
252
            if (!$lineIterator->valid()) {
253
              // Whoa, an unclosed quote! Well whatever, let's just ignore
254
              // that shortcoming and record it nevertheless.
255
              $fields[] = $currentField;
256
              break;
257
            }
258
            // Ok, so, on with fetching the next line, as mentioned above.
259
            $currentField .= "\n";
260
            $line = trim($this->fixEncoding($lineIterator->current()), "\r\n");
261
            $currentIndex = 0;
262
            continue;
263
          }
264

    
265
          // There's actually another quote in this line...
266
          // find out whether it's escaped or not.
267
          $currentField .= substr($line, $currentIndex, $nextQuoteIndex - $currentIndex);
268

    
269
          if (isset($line[$nextQuoteIndex + 1]) && $line[$nextQuoteIndex + 1] === '"') {
270
            // Escaped quote, add a single one to the field and proceed quoted.
271
            $currentField .= '"';
272
            $currentIndex = $nextQuoteIndex + 2;
273
          }
274
          else {
275
            // End of the quoted section, close the quote and let the
276
            // $quoted == FALSE block finalize the field.
277
            $quoted = FALSE;
278
            $currentIndex = $nextQuoteIndex + 1;
279
          }
280
        }
281
        else { // $quoted == FALSE
282
          // First, let's find out where the next character of interest is.
283
          $nextQuoteIndex = strpos($line, '"', $currentIndex);
284
          $nextDelimiterIndex = strpos($line, $this->delimiter, $currentIndex);
285

    
286
          if ($nextQuoteIndex === FALSE) {
287
            $nextIndex = $nextDelimiterIndex;
288
          }
289
          elseif ($nextDelimiterIndex === FALSE) {
290
            $nextIndex = $nextQuoteIndex;
291
          }
292
          else {
293
            $nextIndex = min($nextQuoteIndex, $nextDelimiterIndex);
294
          }
295

    
296
          if ($nextIndex === FALSE) {
297
            // This line is done, add the rest of it as last field.
298
            $currentField .= substr($line, $currentIndex);
299
            $fields[] = $currentField;
300
            break;
301
          }
302
          elseif ($line[$nextIndex] === $this->delimiter[0]) {
303
            $length = ($nextIndex + strlen($this->delimiter) - 1) - $currentIndex;
304
            $currentField .= substr($line, $currentIndex, $length);
305
            $fields[] = $currentField;
306
            $currentField = '';
307
            $currentIndex += $length + 1;
308
            // Continue with the next field.
309
          }
310
          else { // $line[$nextIndex] == '"'
311
            $quoted = TRUE;
312
            $currentField .= substr($line, $currentIndex, $nextIndex - $currentIndex);
313
            $currentIndex = $nextIndex + 1;
314
            // Continue this field in the $quoted == TRUE block.
315
          }
316
        }
317
      }
318
      // End of CSV parser. We've now got all the fields of the line as strings
319
      // in the $fields array.
320

    
321
      if (empty($this->columnNames)) {
322
        $row = $fields;
323
      }
324
      else {
325
        $row = array();
326
        foreach ($this->columnNames as $columnName) {
327
          $field = array_shift($fields);
328
          $row[$columnName] = isset($field) ? $field : '';
329
        }
330
      }
331
      $rows[] = $row;
332

    
333
      // Quit parsing if timeout has been reached or requested lines have been
334
      // reached.
335
      if (!empty($maxTime) && microtime() > $maxTime) {
336
        $this->timeoutReached = TRUE;
337
        $this->lastLinePos = $lineIterator->currentPos();
338
        break;
339
      }
340
      $linesParsed++;
341
      if ($this->lineLimit && $linesParsed >= $this->lineLimit) {
342
        $this->lastLinePos = $lineIterator->currentPos();
343
        break;
344
      }
345
    }
346
    return $rows;
347
  }
348

    
349
  /**
350
   * Converts encoding of input data.
351
   *
352
   * @param string $data
353
   *   A chunk of data.
354
   *
355
   * @return string
356
   *   The encoded data.
357
   *
358
   * @throws ParserCSVEncodingException
359
   *   Thrown when a given encoding does not match.
360
   */
361
  public function fixEncoding($data) {
362
    if ($this->useMbString) {
363
      if (mb_check_encoding($data, $this->fromEncoding)) {
364
        if ($this->toEncoding != $this->fromEncoding) {
365
          // Convert encoding. The conversion is to UTF-8 by default to prevent
366
          // SQL errors.
367
          $data = mb_convert_encoding($data, $this->toEncoding, $this->fromEncoding);
368
        }
369
      }
370
      else {
371
        throw new ParserCSVEncodingException(t('Source file is not in %encoding encoding.', array('%encoding' => $this->fromEncoding)));
372
      }
373
    }
374

    
375
    return $data;
376
  }
377
}
378

    
379
/**
380
 * Exception thrown when an encoding error occurs during parsing.
381
 */
382
class ParserCSVEncodingException extends Exception {}