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-2011 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 && realpath(dirname($filename).'/') != realpath($GLOBALS['sugar_config']['upload_dir']) )
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 * Returns true if the filename given exists and is readable
169 public function fileExists()
171 return !$this->_fp ? false : true;
175 * Gets the next row from $_importFile
177 * @return array current row of file
179 public function getNextRow()
181 $this->_currentRow = FALSE;
183 if (!$this->fileExists())
186 // explode on delimiter instead if enclosure is an empty string
187 if ( empty($this->_enclosure) ) {
188 $row = explode($this->_delimiter,rtrim(fgets($this->_fp, 8192),"\r\n"));
189 if ($row !== false && !( count($row) == 1 && trim($row[0]) == '') )
190 $this->_currentRow = $row;
195 $row = fgetcsv($this->_fp, 8192, $this->_delimiter, $this->_enclosure);
196 if ($row !== false && $row != array(null))
197 $this->_currentRow = $row;
202 // Bug 26219 - Convert all line endings to the same style as PHP_EOL
203 foreach ( $this->_currentRow as $key => $value ) {
204 // use preg_replace instead of str_replace as str_replace may cause extra lines on Windows
205 $this->_currentRow[$key] = preg_replace("[\r\n|\n|\r]", PHP_EOL, $value);
210 return $this->_currentRow;
214 * Returns the number of fields in the current row
216 * @return int count of fiels in the current row
218 public function getFieldCount()
220 return count($this->_currentRow);
224 * Determine the number of lines in this file.
228 public function getNumberOfLinesInfile()
235 while( !feof($this->_fp) )
237 if( fgets($this->_fp) !== FALSE)
240 //Reset the fp to after the bom if applicable.
241 $this->setFpAfterBOM();
247 //TODO: Add auto detection for field delim and qualifier properteis.
248 public function autoDetectCSVProperties()
251 $this->_delimiter = ",";
252 $this->_enclosure = '"';
254 $this->_detector = new CsvAutoDetect($this->_sourcename);
256 $delimiter = $enclosure = false;
258 $ret = $this->_detector->getCsvSettings($delimiter, $enclosure);
261 $this->_delimiter = $delimiter;
262 $this->_enclosure = $enclosure;
271 public function getFieldDelimeter()
273 return $this->_delimiter;
276 public function getFieldEnclosure()
278 return $this->_enclosure;
281 public function autoDetectCharacterSet()
285 $this->setFpAfterBOM();
287 //Retrieve a sample set of data
290 $user_charset = $locale->getExportCharset();
291 $system_charset = $locale->default_export_charset;
292 $other_charsets = 'UTF-8, UTF-7, ASCII, CP1252, EUC-JP, SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP';
293 $detectable_charsets = "UTF-8, {$user_charset}, {$system_charset}, {$other_charsets}";
294 // Bug 26824 - mb_detect_encoding() thinks CP1252 is IS0-8859-1, so use that instead in the encoding list passed to the function
295 $detectable_charsets = str_replace('CP1252','ISO-8859-1',$detectable_charsets);
296 $charset_for_import = $user_charset; //We will set the default import charset option by user's preference.
297 $able_to_detect = function_exists('mb_detect_encoding');
298 for ( $i = 0; $i < 3; $i++ )
300 $rows[$i] = $this->getNextRow();
301 if(!empty($rows[$i]) && $able_to_detect)
303 foreach($rows[$i] as & $temp_value)
305 $current_charset = mb_detect_encoding($temp_value, $detectable_charsets);
306 if(!empty($current_charset) && $current_charset != "UTF-8")
308 $temp_value = $locale->translateCharset($temp_value, $current_charset);// we will use utf-8 for displaying the data on the page.
309 $charset_for_import = $current_charset;
310 //set the default import charset option according to the current_charset.
311 //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.
317 //Reset the fp to after the bom if applicable.
318 $this->setFpAfterBOM();
320 return $charset_for_import;
324 public function getDateFormat()
326 if ($this->_detector) {
327 $this->_date_format = $this->_detector->getDateFormat();
330 return $this->_date_format;
333 public function getTimeFormat()
335 if ($this->_detector) {
336 $this->_time_format = $this->_detector->getTimeFormat();
339 return $this->_time_format;
342 public function setHeaderRow($hasHeader)
344 $this->_hasHeader = $hasHeader;
347 public function hasHeaderRow($autoDetect = TRUE)
351 if (!isset($_REQUEST['import_module']))
354 $module = $_REQUEST['import_module'];
359 if ($this->_detector)
360 $ret = $this->_detector->hasHeader($heading, $module);
363 $this->_hasHeader = $heading;
365 return $this->_hasHeader;
368 public function setImportFileMap($map)
370 $this->_importFile = $map;
371 $importMapProperties = array('_delimiter' => 'delimiter','_enclosure' => 'enclosure', '_hasHeader' => 'has_header');
372 //Inject properties from the import map
373 foreach($importMapProperties as $k => $v)
375 $this->$k = $map->$v;
379 //Begin Implementation for SPL's Iterator interface
380 public function key()
382 return $this->_rowsCount;
385 public function current()
387 return $this->_currentRow;
390 public function next()
395 public function valid()
397 return $this->_currentRow !== FALSE;
400 public function rewind()
402 $this->setFpAfterBOM();
407 public function getTotalRecordCount()
409 $totalCount = $this->getNumberOfLinesInfile();
410 if($this->hasHeaderRow(FALSE) && $totalCount > 0)
417 public function loadDataSet($totalItems = 0)
420 $this->_dataSet = array();
422 //If there's a header don't include it.
423 if( $this->hasHeaderRow(FALSE) )
426 while( $this->valid() && $totalItems > count($this->_dataSet) )
428 if($currentLine >= $this->_offset)
430 $this->_dataSet[] = $this->_currentRow;
439 public function getHeaderColumns()
442 if($this->hasHeaderRow(FALSE))
443 return $this->_currentRow;