Projet

Général

Profil

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

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

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 int
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
   *
202
   * @return array
203
   *   Two dimensional array that contains the data in the CSV file.
204
   */
205
  public function parse(Iterator $lineIterator) {
206
    $skipLine = $this->skipFirstLine;
207
    $rows = array();
208

    
209
    $this->timeoutReached = FALSE;
210
    $this->lastLinePos = 0;
211
    $maxTime = empty($this->timeout) ? FALSE : (microtime() + $this->timeout);
212
    $linesParsed = 0;
213

    
214
    for ($lineIterator->rewind($this->startByte); $lineIterator->valid(); $lineIterator->next()) {
215

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

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

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

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

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

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

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

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

    
283
          if ($nextQuoteIndex === FALSE) {
284
            $nextIndex = $nextDelimiterIndex;
285
          }
286
          elseif ($nextDelimiterIndex === FALSE) {
287
            $nextIndex = $nextQuoteIndex;
288
          }
289
          else {
290
            $nextIndex = min($nextQuoteIndex, $nextDelimiterIndex);
291
          }
292

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

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

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

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

    
372
    return $data;
373
  }
374
}
375

    
376
/**
377
 * Exception thrown when an encoding error occurs during parsing.
378
 */
379
class ParserCSVEncodingException extends Exception {}