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 && 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 $this->_enclosure = ( empty($enclosure) ? '' : trim($enclosure) );
125 $this->setFpAfterBOM();
129 * Remove the BOM (Byte Order Mark) from the beginning of the import row if it exists
132 private function setFpAfterBOM()
134 if($this->_fp === FALSE)
138 $bomCheck = fread($this->_fp, 3);
139 if($bomCheck != pack("CCC",0xef,0xbb,0xbf)) {
146 * Deletes $_importFile if $_deleteFile is true
148 public function __destruct()
150 if ( $this->_deleteFile && $this->fileExists() ) {
152 //Make sure the file exists before unlinking
153 if(file_exists($this->_sourcename)) {
154 unlink($this->_sourcename);
158 ini_restore('auto_detect_line_endings');
162 * Returns true if the filename given exists and is readable
166 public function fileExists()
168 return !$this->_fp ? false : true;
172 * Gets the next row from $_importFile
174 * @return array current row of file
176 public function getNextRow()
178 $this->_currentRow = FALSE;
180 if (!$this->fileExists())
183 // explode on delimiter instead if enclosure is an empty string
184 if ( empty($this->_enclosure) ) {
185 $row = explode($this->_delimiter,rtrim(fgets($this->_fp, 8192),"\r\n"));
186 if ($row !== false && !( count($row) == 1 && trim($row[0]) == '') )
187 $this->_currentRow = $row;
192 $row = fgetcsv($this->_fp, 8192, $this->_delimiter, $this->_enclosure);
193 if ($row !== false && $row != array(null))
194 $this->_currentRow = $row;
199 // Bug 26219 - Convert all line endings to the same style as PHP_EOL
200 foreach ( $this->_currentRow as $key => $value ) {
201 // use preg_replace instead of str_replace as str_replace may cause extra lines on Windows
202 $this->_currentRow[$key] = preg_replace("[\r\n|\n|\r]", PHP_EOL, $value);
207 return $this->_currentRow;
211 * Returns the number of fields in the current row
213 * @return int count of fiels in the current row
215 public function getFieldCount()
217 return count($this->_currentRow);
221 * Determine the number of lines in this file.
225 public function getNumberOfLinesInfile()
232 while( !feof($this->_fp) )
234 if( fgets($this->_fp) !== FALSE)
237 //Reset the fp to after the bom if applicable.
238 $this->setFpAfterBOM();
244 //TODO: Add auto detection for field delim and qualifier properteis.
245 public function autoDetectCSVProperties()
248 $this->_delimiter = ",";
249 $this->_enclosure = '"';
251 $this->_detector = new CsvAutoDetect($this->_sourcename);
253 $delimiter = $enclosure = false;
255 $ret = $this->_detector->getCsvSettings($delimiter, $enclosure);
258 $this->_delimiter = $delimiter;
259 $this->_enclosure = $enclosure;
268 public function getFieldDelimeter()
270 return $this->_delimiter;
273 public function getFieldEnclosure()
275 return $this->_enclosure;
278 public function autoDetectCharacterSet()
282 $this->setFpAfterBOM();
284 //Retrieve a sample set of data
287 $user_charset = $locale->getExportCharset();
288 $system_charset = $locale->default_export_charset;
289 $other_charsets = 'UTF-8, UTF-7, ASCII, CP1252, EUC-JP, SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP';
290 $detectable_charsets = "UTF-8, {$user_charset}, {$system_charset}, {$other_charsets}";
291 // Bug 26824 - mb_detect_encoding() thinks CP1252 is IS0-8859-1, so use that instead in the encoding list passed to the function
292 $detectable_charsets = str_replace('CP1252','ISO-8859-1',$detectable_charsets);
293 $charset_for_import = $user_charset; //We will set the default import charset option by user's preference.
294 $able_to_detect = function_exists('mb_detect_encoding');
295 for ( $i = 0; $i < 3; $i++ )
297 $rows[$i] = $this->getNextRow();
298 if(!empty($rows[$i]) && $able_to_detect)
300 foreach($rows[$i] as & $temp_value)
302 $current_charset = mb_detect_encoding($temp_value, $detectable_charsets);
303 if(!empty($current_charset) && $current_charset != "UTF-8")
305 $temp_value = $locale->translateCharset($temp_value, $current_charset);// we will use utf-8 for displaying the data on the page.
306 $charset_for_import = $current_charset;
307 //set the default import charset option according to the current_charset.
308 //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.
314 //Reset the fp to after the bom if applicable.
315 $this->setFpAfterBOM();
317 return $charset_for_import;
321 public function getDateFormat()
323 if ($this->_detector) {
324 $this->_date_format = $this->_detector->getDateFormat();
327 return $this->_date_format;
330 public function getTimeFormat()
332 if ($this->_detector) {
333 $this->_time_format = $this->_detector->getTimeFormat();
336 return $this->_time_format;
339 public function setHeaderRow($hasHeader)
341 $this->_hasHeader = $hasHeader;
344 public function hasHeaderRow($autoDetect = TRUE)
348 if (!isset($_REQUEST['import_module']))
351 $module = $_REQUEST['import_module'];
356 if ($this->_detector)
357 $ret = $this->_detector->hasHeader($heading, $module);
360 $this->_hasHeader = $heading;
362 return $this->_hasHeader;
365 public function setImportFileMap($map)
367 $this->_importFile = $map;
368 $importMapProperties = array('_delimiter' => 'delimiter','_enclosure' => 'enclosure', '_hasHeader' => 'has_header');
369 //Inject properties from the import map
370 foreach($importMapProperties as $k => $v)
372 $this->$k = $map->$v;
376 //Begin Implementation for SPL's Iterator interface
377 public function key()
379 return $this->_rowsCount;
382 public function current()
384 return $this->_currentRow;
387 public function next()
392 public function valid()
394 return $this->_currentRow !== FALSE;
397 public function rewind()
399 $this->setFpAfterBOM();
404 public function getTotalRecordCount()
406 $totalCount = $this->getNumberOfLinesInfile();
407 if($this->hasHeaderRow(FALSE) && $totalCount > 0)
414 public function loadDataSet($totalItems = 0)
417 $this->_dataSet = array();
419 //If there's a header don't include it.
420 if( $this->hasHeaderRow(FALSE) )
423 while( $this->valid() && $totalItems > count($this->_dataSet) )
425 if($currentLine >= $this->_offset)
427 $this->_dataSet[] = $this->_currentRow;
436 public function getHeaderColumns()
439 if($this->hasHeaderRow(FALSE))
440 return $this->_currentRow;