2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
4 /*********************************************************************************
5 * SugarCRM Community Edition is a customer relationship management program developed by
6 * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU Affero General Public License version 3 as published by the
10 * Free Software Foundation with the addition of the following permission added
11 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
12 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
13 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
20 * You should have received a copy of the GNU Affero General Public License along with
21 * this program; if not, see http://www.gnu.org/licenses or write to the Free
22 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
25 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
26 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
28 * The interactive user interfaces in modified source and object code versions
29 * of this program must display Appropriate Legal Notices, as required under
30 * Section 5 of the GNU Affero General Public License version 3.
32 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
33 * these Appropriate Legal Notices must retain the display of the "Powered by
34 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
35 * technical reasons, the Appropriate Legal Notices must display the words
36 * "Powered by SugarCRM".
37 ********************************************************************************/
39 /*********************************************************************************
41 * Description: Class to handle processing an import file
42 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
43 * All Rights Reserved.
44 ********************************************************************************/
46 require_once('modules/Import/CsvAutoDetect.php');
47 require_once('modules/Import/sources/ImportDataSource.php');
49 class ImportFile extends ImportDataSource
52 * Stores whether or not we are deleting the import file in the destructor
57 * File pointer returned from fopen() call
62 * True if the csv file has a header row.
64 private $_hasHeader = FALSE;
67 * True if the csv file has a header row.
69 private $_detector = null;
74 private $_date_format = false;
79 private $_time_format = false;
82 * The import file map that this import file inherits properties from.
84 private $_importFile = null;
87 * Delimiter string we are using (i.e. , or ;)
92 * Enclosure string we are using (i.e. ' or ")
100 * @param string $filename
101 * @param string $delimiter
102 * @param string $enclosure
103 * @param bool $deleteFile
105 public function __construct( $filename, $delimiter = ',', $enclosure = '',$deleteFile = true, $checkUploadPath = TRUE )
107 if ( !is_file($filename) || !is_readable($filename) ) {
111 if ( $checkUploadPath && UploadStream::path($filename) == null )
113 $GLOBALS['log']->fatal("ImportFile detected attempt to access to the following file not within the sugar upload dir: $filename");
117 // turn on auto-detection of line endings to fix bug #10770
118 ini_set('auto_detect_line_endings', '1');
120 $this->_fp = sugar_fopen($filename,'r');
121 $this->_sourcename = $filename;
122 $this->_deleteFile = $deleteFile;
123 $this->_delimiter = ( empty($delimiter) ? ',' : $delimiter );
124 if ($this->_delimiter == '\t') {
125 $this->_delimiter = "\t";
127 $this->_enclosure = ( empty($enclosure) ? '' : trim($enclosure) );
128 $this->setFpAfterBOM();
132 * Remove the BOM (Byte Order Mark) from the beginning of the import row if it exists
135 private function setFpAfterBOM()
137 if($this->_fp === FALSE)
141 $bomCheck = fread($this->_fp, 3);
142 if($bomCheck != pack("CCC",0xef,0xbb,0xbf)) {
149 * Deletes $_importFile if $_deleteFile is true
151 public function __destruct()
153 if ( $this->_deleteFile && $this->fileExists() ) {
155 //Make sure the file exists before unlinking
156 if(file_exists($this->_sourcename)) {
157 unlink($this->_sourcename);
161 ini_restore('auto_detect_line_endings');
165 * This is needed to prevent unserialize vulnerability
167 public function __wakeup()
169 // clean all properties
170 foreach(get_object_vars($this) as $k => $v) {
173 throw new Exception("Not a serializable object");
177 * Returns true if the filename given exists and is readable
181 public function fileExists()
183 return !$this->_fp ? false : true;
187 * Gets the next row from $_importFile
189 * @return array current row of file
191 public function getNextRow()
193 $this->_currentRow = FALSE;
195 if (!$this->fileExists())
198 // explode on delimiter instead if enclosure is an empty string
199 if ( empty($this->_enclosure) ) {
200 $row = explode($this->_delimiter,rtrim(fgets($this->_fp, 8192),"\r\n"));
201 if ($row !== false && !( count($row) == 1 && trim($row[0]) == '') )
202 $this->_currentRow = $row;
207 $row = fgetcsv($this->_fp, 8192, $this->_delimiter, $this->_enclosure);
208 if ($row !== false && $row != array(null))
209 $this->_currentRow = $row;
214 // Bug 26219 - Convert all line endings to the same style as PHP_EOL
215 foreach ( $this->_currentRow as $key => $value ) {
216 // use preg_replace instead of str_replace as str_replace may cause extra lines on Windows
217 $this->_currentRow[$key] = preg_replace("[\r\n|\n|\r]", PHP_EOL, $value);
222 return $this->_currentRow;
226 * Returns the number of fields in the current row
228 * @return int count of fiels in the current row
230 public function getFieldCount()
232 return count($this->_currentRow);
236 * Determine the number of lines in this file.
240 public function getNumberOfLinesInfile()
247 while( !feof($this->_fp) )
249 if( fgets($this->_fp) !== FALSE)
252 //Reset the fp to after the bom if applicable.
253 $this->setFpAfterBOM();
259 //TODO: Add auto detection for field delim and qualifier properteis.
260 public function autoDetectCSVProperties()
263 $this->_delimiter = ",";
264 $this->_enclosure = '"';
266 $this->_detector = new CsvAutoDetect($this->_sourcename);
268 $delimiter = $enclosure = false;
270 $ret = $this->_detector->getCsvSettings($delimiter, $enclosure);
273 $this->_delimiter = $delimiter;
274 $this->_enclosure = $enclosure;
283 public function getFieldDelimeter()
285 return $this->_delimiter;
288 public function getFieldEnclosure()
290 return $this->_enclosure;
293 public function autoDetectCharacterSet()
297 $this->setFpAfterBOM();
299 //Retrieve a sample set of data
302 $user_charset = $locale->getExportCharset();
303 $system_charset = $locale->default_export_charset;
304 $other_charsets = 'UTF-8, UTF-7, ASCII, CP1252, EUC-JP, SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP';
305 $detectable_charsets = "UTF-8, {$user_charset}, {$system_charset}, {$other_charsets}";
306 // Bug 26824 - mb_detect_encoding() thinks CP1252 is IS0-8859-1, so use that instead in the encoding list passed to the function
307 $detectable_charsets = str_replace('CP1252','ISO-8859-1',$detectable_charsets);
308 $charset_for_import = $user_charset; //We will set the default import charset option by user's preference.
309 $able_to_detect = function_exists('mb_detect_encoding');
310 for ( $i = 0; $i < 3; $i++ )
312 $rows[$i] = $this->getNextRow();
313 if(!empty($rows[$i]) && $able_to_detect)
315 foreach($rows[$i] as & $temp_value)
317 $current_charset = mb_detect_encoding($temp_value, $detectable_charsets);
318 if(!empty($current_charset) && $current_charset != "UTF-8")
320 $temp_value = $locale->translateCharset($temp_value, $current_charset);// we will use utf-8 for displaying the data on the page.
321 $charset_for_import = $current_charset;
322 //set the default import charset option according to the current_charset.
323 //If it is not utf-8, tt may be overwritten by the later one. So the uploaded file should not contain two types of charset($user_charset, $system_charset), and I think this situation will not occur.
329 //Reset the fp to after the bom if applicable.
330 $this->setFpAfterBOM();
332 return $charset_for_import;
336 public function getDateFormat()
338 if ($this->_detector) {
339 $this->_date_format = $this->_detector->getDateFormat();
342 return $this->_date_format;
345 public function getTimeFormat()
347 if ($this->_detector) {
348 $this->_time_format = $this->_detector->getTimeFormat();
351 return $this->_time_format;
354 public function setHeaderRow($hasHeader)
356 $this->_hasHeader = $hasHeader;
359 public function hasHeaderRow($autoDetect = TRUE)
363 if (!isset($_REQUEST['import_module']))
366 $module = $_REQUEST['import_module'];
371 if ($this->_detector)
372 $ret = $this->_detector->hasHeader($heading, $module);
375 $this->_hasHeader = $heading;
377 return $this->_hasHeader;
380 public function setImportFileMap($map)
382 $this->_importFile = $map;
383 $importMapProperties = array('_delimiter' => 'delimiter','_enclosure' => 'enclosure', '_hasHeader' => 'has_header');
384 //Inject properties from the import map
385 foreach($importMapProperties as $k => $v)
387 $this->$k = $map->$v;
391 //Begin Implementation for SPL's Iterator interface
392 public function key()
394 return $this->_rowsCount;
397 public function current()
399 return $this->_currentRow;
402 public function next()
407 public function valid()
409 return $this->_currentRow !== FALSE;
412 public function rewind()
414 $this->setFpAfterBOM();
419 public function getTotalRecordCount()
421 $totalCount = $this->getNumberOfLinesInfile();
422 if($this->hasHeaderRow(FALSE) && $totalCount > 0)
429 public function loadDataSet($totalItems = 0)
432 $this->_dataSet = array();
434 //If there's a header don't include it.
435 if( $this->hasHeaderRow(FALSE) )
438 while( $this->valid() && $totalItems > count($this->_dataSet) )
440 if($currentLine >= $this->_offset)
442 $this->_dataSet[] = $this->_currentRow;
451 public function getHeaderColumns()
454 if($this->hasHeaderRow(FALSE))
455 return $this->_currentRow;