[ Index ]

MailPress 544

[ Index ]     [ Classes ]     [ Functions ]     [ Variables ]     [ Constants ]     [ Statistics ]    

title

Body

[close]

/mp-includes/class/options/import/importers/parsecsv/ -> parsecsv.lib.php (source)

   1  <?php
   2  
   3  class parseCSV {
   4      
   5  /*
   6  
   7      Class: parseCSV v0.4.3 beta
   8      http://code.google.com/p/parsecsv-for-php/
   9      
  10      
  11      Fully conforms to the specifications lined out on wikipedia:
  12       - http://en.wikipedia.org/wiki/Comma-separated_values
  13      
  14      Based on the concept of Ming Hong Ng's CsvFileParser class:
  15       - http://minghong.blogspot.com/2006/07/csv-parser-for-php.html
  16      
  17      
  18      
  19      Copyright (c) 2007 Jim Myhrberg (jim@zydev.info).
  20  
  21      Permission is hereby granted, free of charge, to any person obtaining a copy
  22      of this software and associated documentation files (the "Software"), to deal
  23      in the Software without restriction, including without limitation the rights
  24      to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  25      copies of the Software, and to permit persons to whom the Software is
  26      furnished to do so, subject to the following conditions:
  27  
  28      The above copyright notice and this permission notice shall be included in
  29      all copies or substantial portions of the Software.
  30  
  31      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  32      IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  33      FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  34      AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  35      LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  36      OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37      THE SOFTWARE.
  38      
  39      
  40      
  41      Code Examples
  42      ----------------
  43      # general usage
  44      $csv = new parseCSV('data.csv');
  45      print_r($csv->data);
  46      ----------------
  47      # tab delimited, and encoding conversion
  48      $csv = new parseCSV();
  49      $csv->encoding('UTF-16', 'UTF-8');
  50      $csv->delimiter = "\t";
  51      $csv->parse('data.tsv');
  52      print_r($csv->data);
  53      ----------------
  54      # auto-detect delimiter character
  55      $csv = new parseCSV();
  56      $csv->auto('data.csv');
  57      print_r($csv->data);
  58      ----------------
  59      # modify data in a csv file
  60      $csv = new parseCSV();
  61      $csv->sort_by = 'id';
  62      $csv->parse('data.csv');
  63      # "4" is the value of the "id" column of the CSV row
  64      $csv->data[4] = array('firstname' => 'John', 'lastname' => 'Doe', 'email' => 'john@doe.com');
  65      $csv->save();
  66      ----------------
  67      # add row/entry to end of CSV file
  68      #  - only recommended when you know the extact sctructure of the file
  69      $csv = new parseCSV();
  70      $csv->save('data.csv', array('1986', 'Home', 'Nowhere', ''), true);
  71      ----------------
  72      # convert 2D array to csv data and send headers
  73      # to browser to treat output as a file and download it
  74      $csv = new parseCSV();
  75      $csv->output (true, 'movies.csv', $array);
  76      ----------------
  77      
  78  
  79  */
  80  
  81  
  82      /**
  83       * Configuration
  84       * - set these options with $object->var_name = 'value';
  85       */
  86      
  87      # use first line/entry as field names
  88      var $heading = true;
  89      
  90      # override field names
  91      var $fields = array();
  92      
  93      # sort entries by this field
  94      var $sort_by = null;
  95      var $sort_reverse = false;
  96      
  97      # sort behavior passed to ksort/krsort functions
  98      # regular = SORT_REGULAR
  99      # numeric = SORT_NUMERIC
 100      # string  = SORT_STRING
 101      var $sort_type = null;
 102      
 103      # delimiter (comma) and enclosure (double quote)
 104      var $delimiter = ',';
 105      var $enclosure = '"';
 106      
 107      # basic SQL-like conditions for row matching
 108      var $conditions = null;
 109      
 110      # number of rows to ignore from beginning of data
 111      var $offset = null;
 112      
 113      # limits the number of returned rows to specified amount
 114      var $limit = null;
 115      
 116      # number of rows to analyze when attempting to auto-detect delimiter
 117      var $auto_depth = 15;
 118      
 119      # characters to ignore when attempting to auto-detect delimiter
 120      var $auto_non_chars = "a-zA-Z0-9\n\r";
 121      
 122      # preferred delimiter characters, only used when all filtering method
 123      # returns multiple possible delimiters (happens very rarely)
 124      var $auto_preferred = ",;\t.:|";
 125      
 126      # character encoding options
 127      var $convert_encoding = false;
 128      var $input_encoding = 'ISO-8859-1';
 129      var $output_encoding = 'ISO-8859-1';
 130      
 131      # used by unparse(), save(), and output() functions
 132      var $linefeed = "\r\n";
 133      
 134      # only used by output() function
 135      var $output_delimiter = ',';
 136      var $output_filename = 'data.csv';
 137      
 138      # keep raw file data in memory after successful parsing (useful for debugging)
 139      var $keep_file_data = false;
 140      
 141      /**
 142       * Internal variables
 143       */
 144      
 145      # current file
 146      var $file;
 147      
 148      # loaded file contents
 149      var $file_data;
 150      
 151      # error while parsing input data
 152      #  0 = No errors found. Everything should be fine :)
 153      #  1 = Hopefully correctable syntax error was found.
 154      #  2 = Enclosure character (double quote by default)
 155      #      was found in non-enclosed field. This means
 156      #      the file is either corrupt, or does not
 157      #      standard CSV formatting. Please validate
 158      #      the parsed data yourself.
 159      var $error = 0;
 160      
 161      # detailed error info
 162      var $error_info = array();
 163      
 164      # array of field values in data parsed
 165      var $titles = array();
 166      
 167      # two dimentional array of CSV data
 168      var $data = array();
 169      
 170      
 171      /**
 172       * Constructor
 173       * @param   input   CSV file or string
 174       * @return  nothing
 175       */
 176  	function parseCSV ($input = null, $offset = null, $limit = null, $conditions = null) {
 177          if ( $offset !== null ) $this->offset = $offset;
 178          if ( $limit !== null ) $this->limit = $limit;
 179          if ( count($conditions) > 0 ) $this->conditions = $conditions;
 180          if ( !empty($input) ) $this->parse($input);
 181      }
 182      
 183      
 184      // ==============================================
 185      // ----- [ Main Functions ] ---------------------
 186      // ==============================================
 187      
 188      /**
 189       * Parse CSV file or string
 190       * @param   input   CSV file or string
 191       * @return  nothing
 192       */
 193  	function parse ($input = null, $offset = null, $limit = null, $conditions = null) {
 194          if ( $input === null ) $input = $this->file;
 195          if ( !empty($input) ) {
 196              if ( $offset !== null ) $this->offset = $offset;
 197              if ( $limit !== null ) $this->limit = $limit;
 198              if ( count($conditions) > 0 ) $this->conditions = $conditions;
 199              if ( is_readable($input) ) {
 200                  $this->data = $this->parse_file($input);
 201              } else {
 202                  $this->file_data = &$input;
 203                  $this->data = $this->parse_string();
 204              }
 205              if ( $this->data === false ) return false;
 206          }
 207          return true;
 208      }
 209      
 210      /**
 211       * Save changes, or new file and/or data
 212       * @param   file     file to save to
 213       * @param   data     2D array with data
 214       * @param   append   append current data to end of target CSV if exists
 215       * @param   fields   field names
 216       * @return  true or false
 217       */
 218  	function save ($file = null, $data = array(), $append = false, $fields = array()) {
 219          if ( empty($file) ) $file = &$this->file;
 220          $mode = ( $append ) ? 'at' : 'wt' ;
 221          $is_php = ( preg_match('/\.php$/i', $file) ) ? true : false ;
 222          return $this->_wfile($file, $this->unparse($data, $fields, $append, $is_php), $mode);
 223      }
 224      
 225      /**
 226       * Generate CSV based string for output
 227       * @param   filename    if specified, headers and data will be output directly to browser as a downloable file
 228       * @param   data        2D array with data
 229       * @param   fields      field names
 230       * @param   delimiter   delimiter used to separate data
 231       * @return  CSV data using delimiter of choice, or default
 232       */
 233  	function output ($filename = null, $data = array(), $fields = array(), $delimiter = null) {
 234          if ( empty($filename) ) $filename = $this->output_filename;
 235          if ( $delimiter === null ) $delimiter = $this->output_delimiter;
 236          $data = $this->unparse($data, $fields, null, null, $delimiter);
 237          if ( $filename !== null ) {
 238              header('Content-type: application/csv');
 239              header('Content-Disposition: attachment; filename="'.$filename.'"');
 240              echo $data;
 241          }
 242          return $data;
 243      }
 244      
 245      /**
 246       * Convert character encoding
 247       * @param   input    input character encoding, uses default if left blank
 248       * @param   output   output character encoding, uses default if left blank
 249       * @return  nothing
 250       */
 251  	function encoding ($input = null, $output = null) {
 252          $this->convert_encoding = true;
 253          if ( $input !== null ) $this->input_encoding = $input;
 254          if ( $output !== null ) $this->output_encoding = $output;
 255      }
 256      
 257      /**
 258       * Auto-Detect Delimiter: Find delimiter by analyzing a specific number of
 259       * rows to determine most probable delimiter character
 260       * @param   file           local CSV file
 261       * @param   parse          true/false parse file directly
 262       * @param   search_depth   number of rows to analyze
 263       * @param   preferred      preferred delimiter characters
 264       * @param   enclosure      enclosure character, default is double quote (").
 265       * @return  delimiter character
 266       */
 267  	function auto ($file = null, $parse = true, $search_depth = null, $preferred = null, $enclosure = null) {
 268          
 269          if ( $file === null ) $file = $this->file;
 270          if ( empty($search_depth) ) $search_depth = $this->auto_depth;
 271          if ( $enclosure === null ) $enclosure = $this->enclosure;
 272          
 273          if ( $preferred === null ) $preferred = $this->auto_preferred;
 274          
 275          if ( empty($this->file_data) ) {
 276              if ( $this->_check_data($file) ) {
 277                  $data = &$this->file_data;
 278              } else return false;
 279          } else {
 280              $data = &$this->file_data;
 281          }
 282          
 283          $chars = array();
 284          $strlen = strlen($data);
 285          $enclosed = false;
 286          $n = 1;
 287          $to_end = true;
 288          
 289          // walk specific depth finding posssible delimiter characters
 290          for ( $i=0; $i < $strlen; $i++ ) {
 291              $ch = $data{$i};
 292              $nch = ( isset($data{$i+1}) ) ? $data{$i+1} : false ;
 293              $pch = ( isset($data{$i-1}) ) ? $data{$i-1} : false ;
 294              
 295              // open and closing quotes
 296              if ( $ch == $enclosure ) {
 297                  if ( !$enclosed || $nch != $enclosure ) {
 298                      $enclosed = ( $enclosed ) ? false : true ;
 299                  } elseif ( $enclosed ) {
 300                      $i++;
 301                  }
 302                  
 303              // end of row
 304              } elseif ( ($ch == "\n" && $pch != "\r" || $ch == "\r") && !$enclosed ) {
 305                  if ( $n >= $search_depth ) {
 306                      $strlen = 0;
 307                      $to_end = false;
 308                  } else {
 309                      $n++;
 310                  }
 311                  
 312              // count character
 313              } elseif (!$enclosed) {
 314                  if ( !preg_match('/['.preg_quote($this->auto_non_chars, '/').']/i', $ch) ) {
 315                      if ( !isset($chars[$ch][$n]) ) {
 316                          $chars[$ch][$n] = 1;
 317                      } else {
 318                          $chars[$ch][$n]++;
 319                      }
 320                  }
 321              }
 322          }
 323          
 324          // filtering
 325          $depth = ( $to_end ) ? $n-1 : $n ;
 326          $filtered = array();
 327          foreach( $chars as $char => $value ) {
 328              if ( $match = $this->_check_count($char, $value, $depth, $preferred) ) {
 329                  $filtered[$match] = $char;
 330              }
 331          }
 332          
 333          // capture most probable delimiter
 334          ksort($filtered);
 335          $this->delimiter = reset($filtered);
 336          
 337          // parse data
 338          if ( $parse ) $this->data = $this->parse_string();
 339          
 340          return $this->delimiter;
 341          
 342      }
 343      
 344      
 345      // ==============================================
 346      // ----- [ Core Functions ] ---------------------
 347      // ==============================================
 348      
 349      /**
 350       * Read file to string and call parse_string()
 351       * @param   file   local CSV file
 352       * @return  2D array with CSV data, or false on failure
 353       */
 354  	function parse_file ($file = null) {
 355          if ( $file === null ) $file = $this->file;
 356          if ( empty($this->file_data) ) $this->load_data($file);
 357          return ( !empty($this->file_data) ) ? $this->parse_string() : false ;
 358      }
 359      
 360      /**
 361       * Parse CSV strings to arrays
 362       * @param   data   CSV string
 363       * @return  2D array with CSV data, or false on failure
 364       */
 365  	function parse_string ($data = null) {
 366          if ( empty($data) ) {
 367              if ( $this->_check_data() ) {
 368                  $data = &$this->file_data;
 369              } else return false;
 370          }
 371          
 372          $white_spaces = str_replace($this->delimiter, '', " \t\x0B\0");
 373          
 374          $rows = array();
 375          $row = array();
 376          $row_count = 0;
 377          $current = '';
 378          $head = ( !empty($this->fields) ) ? $this->fields : array() ;
 379          $col = 0;
 380          $enclosed = false;
 381          $was_enclosed = false;
 382          $strlen = strlen($data);
 383          
 384          // walk through each character
 385          for ( $i=0; $i < $strlen; $i++ ) {
 386              $ch = $data{$i};
 387              $nch = ( isset($data{$i+1}) ) ? $data{$i+1} : false ;
 388              $pch = ( isset($data{$i-1}) ) ? $data{$i-1} : false ;
 389              
 390              // open/close quotes, and inline quotes
 391              if ( $ch == $this->enclosure ) {
 392                  if ( !$enclosed ) {
 393                      if ( ltrim($current, $white_spaces) == '' ) {
 394                          $enclosed = true;
 395                          $was_enclosed = true;
 396                      } else {
 397                          $this->error = 2;
 398                          $error_row = count($rows) + 1;
 399                          $error_col = $col + 1;
 400                          if ( !isset($this->error_info[$error_row.'-'.$error_col]) ) {
 401                              $this->error_info[$error_row.'-'.$error_col] = array(
 402                                  'type' => 2,
 403                                  'info' => 'Syntax error found on row '.$error_row.'. Non-enclosed fields can not contain double-quotes.',
 404                                  'row' => $error_row,
 405                                  'field' => $error_col,
 406                                  'field_name' => (!empty($head[$col])) ? $head[$col] : null,
 407                              );
 408                          }
 409                          $current .= $ch;
 410                      }
 411                  } elseif ($nch == $this->enclosure) {
 412                      $current .= $ch;
 413                      $i++;
 414                  } elseif ( $nch != $this->delimiter && $nch != "\r" && $nch != "\n" ) {
 415                      for ( $x=($i+1); isset($data{$x}) && ltrim($data{$x}, $white_spaces) == ''; $x++ ) {}
 416                      if ( $data{$x} == $this->delimiter ) {
 417                          $enclosed = false;
 418                          $i = $x;
 419                      } else {
 420                          if ( $this->error < 1 ) {
 421                              $this->error = 1;
 422                          }
 423                          $error_row = count($rows) + 1;
 424                          $error_col = $col + 1;
 425                          if ( !isset($this->error_info[$error_row.'-'.$error_col]) ) {
 426                              $this->error_info[$error_row.'-'.$error_col] = array(
 427                                  'type' => 1,
 428                                  'info' =>
 429                                      'Syntax error found on row '.(count($rows) + 1).'. '.
 430                                      'A single double-quote was found within an enclosed string. '.
 431                                      'Enclosed double-quotes must be escaped with a second double-quote.',
 432                                  'row' => count($rows) + 1,
 433                                  'field' => $col + 1,
 434                                  'field_name' => (!empty($head[$col])) ? $head[$col] : null,
 435                              );
 436                          }
 437                          $current .= $ch;
 438                          $enclosed = false;
 439                      }
 440                  } else {
 441                      $enclosed = false;
 442                  }
 443                  
 444              // end of field/row
 445              } elseif ( ($ch === $this->delimiter || ($ch === "\n" && $pch !== "\r") || $ch === "\r") && !$enclosed ) {
 446                  $key = ( !empty($head[$col]) ) ? $head[$col] : $col ;
 447                  $row[$key] = ( $was_enclosed ) ? $current : trim($current) ;
 448                  $current = '';
 449                  $was_enclosed = false;
 450                  $col++;
 451                  
 452                  // end of row
 453                  if ( $ch == "\n" || $ch == "\r" ) {
 454                      if ( $this->_validate_offset($row_count) && $this->_validate_row_conditions($row, $this->conditions) ) {
 455                          if ( $this->heading && empty($head) ) {
 456                              $head = $row;
 457                          } elseif ( empty($this->fields) || (!empty($this->fields) && (($this->heading && $row_count > 0) || !$this->heading)) ) {
 458                              if ( !empty($this->sort_by) && !empty($row[$this->sort_by]) ) {
 459                                  if ( isset($rows[$row[$this->sort_by]]) ) {
 460                                      $rows[$row[$this->sort_by].'_0'] = &$rows[$row[$this->sort_by]];
 461                                      unset($rows[$row[$this->sort_by]]);
 462                                      for ( $sn=1; isset($rows[$row[$this->sort_by].'_'.$sn]); $sn++ ) {}
 463                                      $rows[$row[$this->sort_by].'_'.$sn] = $row;
 464                                  } else $rows[$row[$this->sort_by]] = $row;
 465                              } else $rows[] = $row;
 466                          }
 467                      }
 468                      $row = array();
 469                      $col = 0;
 470                      $row_count++;
 471                      if ( $this->sort_by === null && $this->limit !== null && count($rows) == $this->limit ) {
 472                          $i = $strlen;
 473                      }
 474                      if ( $ch == "\r" && $nch == "\n" ) $i++;
 475                  }
 476                  
 477              // append character to current field
 478              } else {
 479                  $current .= $ch;
 480              }
 481          }
 482          $this->titles = $head;
 483          if ( !empty($this->sort_by) ) {
 484              $sort_type = SORT_REGULAR;
 485              if ( $this->sort_type == 'numeric' ) {
 486                  $sort_type = SORT_NUMERIC;
 487              } elseif ( $this->sort_type == 'string' ) {
 488                  $sort_type = SORT_STRING;
 489              }
 490              ( $this->sort_reverse ) ? krsort($rows, $sort_type) : ksort($rows, $sort_type) ;
 491              if ( $this->offset !== null || $this->limit !== null ) {
 492                  $rows = array_slice($rows, ($this->offset === null ? 0 : $this->offset) , $this->limit, true);
 493              }
 494          }
 495          if ( !$this->keep_file_data ) {
 496              $this->file_data = null;
 497          }
 498          return $rows;
 499      }
 500      
 501      /**
 502       * Create CSV data from array
 503       * @param   data        2D array with data
 504       * @param   fields      field names
 505       * @param   append      if true, field names will not be output
 506       * @param   is_php      if a php die() call should be put on the first
 507       *                      line of the file, this is later ignored when read.
 508       * @param   delimiter   field delimiter to use
 509       * @return  CSV data (text string)
 510       */
 511  	function unparse ( $data = array(), $fields = array(), $append = false , $is_php = false, $delimiter = null) {
 512          if ( !is_array($data) || empty($data) ) $data = &$this->data;
 513          if ( !is_array($fields) || empty($fields) ) $fields = &$this->titles;
 514          if ( $delimiter === null ) $delimiter = $this->delimiter;
 515          
 516          $string = ( $is_php ) ? "<?php header('Status: 403'); die(' '); ?>".$this->linefeed : '' ;
 517          $entry = array();
 518          
 519          // create heading
 520          if ( $this->heading && !$append && !empty($fields) ) {
 521              foreach( $fields as $key => $value ) {
 522                  $entry[] = $this->_enclose_value($value);
 523              }
 524              $string .= implode($delimiter, $entry).$this->linefeed;
 525              $entry = array();
 526          }
 527          
 528          // create data
 529          foreach( $data as $key => $row ) {
 530              foreach( $row as $field => $value ) {
 531                  $entry[] = $this->_enclose_value($value);
 532              }
 533              $string .= implode($delimiter, $entry).$this->linefeed;
 534              $entry = array();
 535          }
 536          
 537          return $string;
 538      }
 539      
 540      /**
 541       * Load local file or string
 542       * @param   input   local CSV file
 543       * @return  true or false
 544       */
 545  	function load_data ($input = null) {
 546          $data = null;
 547          $file = null;
 548          if ( $input === null ) {
 549              $file = $this->file;
 550          } elseif ( file_exists($input) ) {
 551              $file = $input;
 552          } else {
 553              $data = $input;
 554          }
 555          if ( !empty($data) || $data = $this->_rfile($file) ) {
 556              if ( $this->file != $file ) $this->file = $file;
 557              if ( preg_match('/\.php$/i', $file) && preg_match('/<\?.*?\?>(.*)/ims', $data, $strip) ) {
 558                  $data = ltrim($strip[1]);
 559              }
 560              if ( $this->convert_encoding ) $data = iconv($this->input_encoding, $this->output_encoding, $data);
 561              if ( substr($data, -1) != "\n" ) $data .= "\n";
 562              $this->file_data = &$data;
 563              return true;
 564          }
 565          return false;
 566      }
 567      
 568      
 569      // ==============================================
 570      // ----- [ Internal Functions ] -----------------
 571      // ==============================================
 572      
 573      /**
 574       * Validate a row against specified conditions
 575       * @param   row          array with values from a row
 576       * @param   conditions   specified conditions that the row must match 
 577       * @return  true of false
 578       */
 579  	function _validate_row_conditions ($row = array(), $conditions = null) {
 580          if ( !empty($row) ) {
 581              if ( !empty($conditions) ) {
 582                  $conditions = (strpos($conditions, ' OR ') !== false) ? explode(' OR ', $conditions) : array($conditions) ;
 583                  $or = '';
 584                  foreach( $conditions as $key => $value ) {
 585                      if ( strpos($value, ' AND ') !== false ) {
 586                          $value = explode(' AND ', $value);
 587                          $and = '';
 588                          foreach( $value as $k => $v ) {
 589                              $and .= $this->_validate_row_condition($row, $v);
 590                          }
 591                          $or .= (strpos($and, '0') !== false) ? '0' : '1' ;
 592                      } else {
 593                          $or .= $this->_validate_row_condition($row, $value);
 594                      }
 595                  }
 596                  return (strpos($or, '1') !== false) ? true : false ;
 597              }
 598              return true;
 599          }
 600          return false;
 601      }
 602      
 603      /**
 604       * Validate a row against a single condition
 605       * @param   row          array with values from a row
 606       * @param   condition   specified condition that the row must match 
 607       * @return  true of false
 608       */
 609  	function _validate_row_condition ($row, $condition) {
 610          $operators = array(
 611              '=', 'equals', 'is',
 612              '!=', 'is not',
 613              '<', 'is less than',
 614              '>', 'is greater than',
 615              '<=', 'is less than or equals',
 616              '>=', 'is greater than or equals',
 617              'contains',
 618              'does not contain',
 619          );
 620          $operators_regex = array();
 621          foreach( $operators as $value ) {
 622              $operators_regex[] = preg_quote($value, '/');
 623          }
 624          $operators_regex = implode('|', $operators_regex);
 625          if ( preg_match('/^(.+) ('.$operators_regex.') (.+)$/i', trim($condition), $capture) ) {
 626              $field = $capture[1];
 627              $op = $capture[2];
 628              $value = $capture[3];
 629              if ( preg_match('/^([\'\"]{1})(.*)([\'\"]{1})$/i', $value, $capture) ) {
 630                  if ( $capture[1] == $capture[3] ) {
 631                      $value = $capture[2];
 632                      $value = str_replace("\\n", "\n", $value);
 633                      $value = str_replace("\\r", "\r", $value);
 634                      $value = str_replace("\\t", "\t", $value);
 635                      $value = stripslashes($value);
 636                  }
 637              }
 638              if ( array_key_exists($field, $row) ) {
 639                  if ( ($op == '=' || $op == 'equals' || $op == 'is') && $row[$field] == $value ) {
 640                      return '1';
 641                  } elseif ( ($op == '!=' || $op == 'is not') && $row[$field] != $value ) {
 642                      return '1';
 643                  } elseif ( ($op == '<' || $op == 'is less than' ) && $row[$field] < $value ) {
 644                      return '1';
 645                  } elseif ( ($op == '>' || $op == 'is greater than') && $row[$field] > $value ) {
 646                      return '1';
 647                  } elseif ( ($op == '<=' || $op == 'is less than or equals' ) && $row[$field] <= $value ) {
 648                      return '1';
 649                  } elseif ( ($op == '>=' || $op == 'is greater than or equals') && $row[$field] >= $value ) {
 650                      return '1';
 651                  } elseif ( $op == 'contains' && preg_match('/'.preg_quote($value, '/').'/i', $row[$field]) ) {
 652                      return '1';
 653                  } elseif ( $op == 'does not contain' && !preg_match('/'.preg_quote($value, '/').'/i', $row[$field]) ) {
 654                      return '1';
 655                  } else {
 656                      return '0';
 657                  }
 658              }
 659          }
 660          return '1';
 661      }
 662      
 663      /**
 664       * Validates if the row is within the offset or not if sorting is disabled
 665       * @param   current_row   the current row number being processed
 666       * @return  true of false
 667       */
 668  	function _validate_offset ($current_row) {
 669          if ( $this->sort_by === null && $this->offset !== null && $current_row < $this->offset ) return false;
 670          return true;
 671      }
 672      
 673      /**
 674       * Enclose values if needed
 675       *  - only used by unparse()
 676       * @param   value   string to process
 677       * @return  Processed value
 678       */
 679  	function _enclose_value ($value = null) {
 680          if ( $value !== null && $value != '' ) {
 681              $delimiter = preg_quote($this->delimiter, '/');
 682              $enclosure = preg_quote($this->enclosure, '/');
 683              if ( preg_match("/".$delimiter."|".$enclosure."|\n|\r/i", $value) || ($value{0} == ' ' || substr($value, -1) == ' ') ) {
 684                  $value = str_replace($this->enclosure, $this->enclosure.$this->enclosure, $value);
 685                  $value = $this->enclosure.$value.$this->enclosure;
 686              }
 687          }
 688          return $value;
 689      }
 690      
 691      /**
 692       * Check file data
 693       * @param   file   local filename
 694       * @return  true or false
 695       */
 696  	function _check_data ($file = null) {
 697          if ( empty($this->file_data) ) {
 698              if ( $file === null ) $file = $this->file;
 699              return $this->load_data($file);
 700          }
 701          return true;
 702      }
 703      
 704      
 705      /**
 706       * Check if passed info might be delimiter
 707       *  - only used by find_delimiter()
 708       * @return  special string used for delimiter selection, or false
 709       */
 710  	function _check_count ($char, $array, $depth, $preferred) {
 711          if ( $depth == count($array) ) {
 712              $first = null;
 713              $equal = null;
 714              $almost = false;
 715              foreach( $array as $key => $value ) {
 716                  if ( $first == null ) {
 717                      $first = $value;
 718                  } elseif ( $value == $first && $equal !== false) {
 719                      $equal = true;
 720                  } elseif ( $value == $first+1 && $equal !== false ) {
 721                      $equal = true;
 722                      $almost = true;
 723                  } else {
 724                      $equal = false;
 725                  }
 726              }
 727              if ( $equal ) {
 728                  $match = ( $almost ) ? 2 : 1 ;
 729                  $pref = strpos($preferred, $char);
 730                  $pref = ( $pref !== false ) ? str_pad($pref, 3, '0', STR_PAD_LEFT) : '999' ;
 731                  return $pref.$match.'.'.(99999 - str_pad($first, 5, '0', STR_PAD_LEFT));
 732              } else return false;
 733          }
 734      }
 735      
 736      /**
 737       * Read local file
 738       * @param   file   local filename
 739       * @return  Data from file, or false on failure
 740       */
 741  	function _rfile ($file = null) {
 742          if ( is_readable($file) ) {
 743              if ( !($fh = fopen($file, 'r')) ) return false;
 744              $data = fread($fh, filesize($file));
 745              fclose($fh);
 746              return $data;
 747          }
 748          return false;
 749      }
 750  
 751      /**
 752       * Write to local file
 753       * @param   file     local filename
 754       * @param   string   data to write to file
 755       * @param   mode     fopen() mode
 756       * @param   lock     flock() mode
 757       * @return  true or false
 758       */
 759  	function _wfile ($file, $string = '', $mode = 'wb', $lock = 2) {
 760          if ( $fp = fopen($file, $mode) ) {
 761              flock($fp, $lock);
 762              $re = fwrite($fp, $string);
 763              $re2 = fclose($fp);
 764              if ( $re != false && $re2 != false ) return true;
 765          }
 766          return false;
 767      }
 768      
 769  }
 770  
 771  ?>


Generated: Thu Apr 28 18:38:52 2016 Cross-referenced by PHPXref 0.7.1