Ejemplo n.º 1
0
 /**
  * Parse this content
  *
  * @global object
  * @global object
  * @param string $content passed by ref for memory reasons, unset after return
  * @param string $encoding content encoding
  * @param string $delimiter_name separator (comma, semicolon, colon, cfg)
  * @param string $column_validation name of function for columns validation, must have one param $columns
  * @return bool false if error, count of data lines if ok; use get_error() to get error string
  */
 function load_csv_content(&$content, $encoding, $delimiter_name, $column_validation = null)
 {
     global $USER, $CFG;
     $this->close();
     $this->_error = null;
     $content = textlib::convert($content, $encoding, 'utf-8');
     // remove Unicode BOM from first line
     $content = textlib::trim_utf8_bom($content);
     // Fix mac/dos newlines
     $content = preg_replace('!\\r\\n?!', "\n", $content);
     // is there anyting in file?
     $columns = strtok($content, "\n");
     if ($columns === false) {
         $this->_error = get_string('csvemptyfile', 'error');
         return false;
     }
     $csv_delimiter = csv_import_reader::get_delimiter($delimiter_name);
     $csv_encode = csv_import_reader::get_encoded_delimiter($delimiter_name);
     // process header - list of columns
     $columns = explode($csv_delimiter, $columns);
     $col_count = count($columns);
     if ($col_count === 0) {
         $this->_error = get_string('csvemptyfile', 'error');
         return false;
     }
     foreach ($columns as $key => $value) {
         $columns[$key] = str_replace($csv_encode, $csv_delimiter, trim($value));
     }
     if ($column_validation) {
         $result = $column_validation($columns);
         if ($result !== true) {
             $this->_error = $result;
             return false;
         }
     }
     $this->_columns = $columns;
     // cached columns
     // open file for writing
     $filename = $CFG->tempdir . '/csvimport/' . $this->_type . '/' . $USER->id . '/' . $this->_iid;
     $fp = fopen($filename, "w");
     fwrite($fp, serialize($columns) . "\n");
     // again - do we have any data for processing?
     $line = strtok("\n");
     $data_count = 0;
     while ($line !== false) {
         $line = explode($csv_delimiter, $line);
         foreach ($line as $key => $value) {
             $line[$key] = str_replace($csv_encode, $csv_delimiter, trim($value));
         }
         if (count($line) !== $col_count) {
             // this is critical!!
             $this->_error = get_string('csvweirdcolumns', 'error');
             fclose($fp);
             $this->cleanup();
             return false;
         }
         fwrite($fp, serialize($line) . "\n");
         $data_count++;
         $line = strtok("\n");
     }
     fclose($fp);
     return $data_count;
 }