]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Import/sources/ImportFile.php
Release 6.3.0
[Github/sugarcrm.git] / modules / Import / sources / ImportFile.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3
4 /*********************************************************************************
5  * SugarCRM Community Edition is a customer relationship management program developed by
6  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
7  * 
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.
14  * 
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
18  * details.
19  * 
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
23  * 02110-1301 USA.
24  * 
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.
27  * 
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.
31  * 
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  ********************************************************************************/
38
39 /*********************************************************************************
40
41  * Description: Class to handle processing an import file
42  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
43  * All Rights Reserved.
44  ********************************************************************************/
45
46 require_once('modules/Import/CsvAutoDetect.php');
47 require_once('modules/Import/sources/ImportDataSource.php');
48
49 class ImportFile extends ImportDataSource
50 {
51     /**
52      * Stores whether or not we are deleting the import file in the destructor
53      */
54     private $_deleteFile;
55     
56     /**
57      * File pointer returned from fopen() call
58      */
59     private $_fp = FALSE;
60
61     /**
62      * True if the csv file has a header row.
63      */
64     private $_hasHeader = FALSE;
65
66     /**
67      * True if the csv file has a header row.
68      */
69     private $_detector = null;
70
71     /**
72      * CSV date format
73      */
74     private $_date_format = false;
75
76     /**
77      * CSV time format
78      */
79     private $_time_format = false;
80
81     /**
82      * The import file map that this import file inherits properties from.
83      */
84     private $_importFile = null;
85
86     /**
87      * Delimiter string we are using (i.e. , or ;)
88      */
89     private $_delimiter;
90
91     /**
92      * Enclosure string we are using (i.e. ' or ")
93      */
94     private $_enclosure;
95
96     
97     /**
98      * Constructor
99      *
100      * @param string $filename
101      * @param string $delimiter
102      * @param string $enclosure
103      * @param bool   $deleteFile
104      */
105     public function __construct( $filename, $delimiter  = ',', $enclosure  = '',$deleteFile = true, $checkUploadPath = TRUE )
106     {
107         if ( !is_file($filename) || !is_readable($filename) ) {
108             return false;
109         }
110
111         if ( $checkUploadPath && realpath(dirname($filename).'/') != realpath($GLOBALS['sugar_config']['upload_dir']) )
112         {
113             $GLOBALS['log']->fatal("ImportFile detected attempt to access to the following file not within the sugar upload dir: $filename");
114             return null;
115         }
116
117         // turn on auto-detection of line endings to fix bug #10770
118         ini_set('auto_detect_line_endings', '1');
119         
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";
126         }
127         $this->_enclosure  = ( empty($enclosure) ? '' : trim($enclosure) );
128         $this->setFpAfterBOM();
129     }
130
131     /**
132      * Remove the BOM (Byte Order Mark) from the beginning of the import row if it exists
133      * @return void
134      */
135     private function setFpAfterBOM()
136     {
137         if($this->_fp === FALSE)
138             return;
139
140         rewind($this->_fp);
141         $bomCheck = fread($this->_fp, 3);
142         if($bomCheck != pack("CCC",0xef,0xbb,0xbf)) {
143             rewind($this->_fp);
144         }
145     }
146     /**
147      * Destructor
148      *
149      * Deletes $_importFile if $_deleteFile is true
150      */
151     public function __destruct()
152     {
153         if ( $this->_deleteFile && $this->fileExists() ) {
154             fclose($this->_fp);
155             //Make sure the file exists before unlinking
156             if(file_exists($this->_sourcename)) {
157                unlink($this->_sourcename);
158             }
159         }
160         
161         ini_restore('auto_detect_line_endings');
162     }
163     
164     /**
165      * Returns true if the filename given exists and is readable
166      *
167      * @return bool
168      */
169     public function fileExists()
170     {
171         return !$this->_fp ? false : true;
172     }
173     
174     /**
175      * Gets the next row from $_importFile
176      *
177      * @return array current row of file
178      */
179     public function getNextRow()
180     {
181         $this->_currentRow = FALSE;
182         
183         if (!$this->fileExists()) 
184             return false;
185         
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;
191             else
192                 return false;
193         }
194         else {
195             $row = fgetcsv($this->_fp, 8192, $this->_delimiter, $this->_enclosure);
196             if ($row !== false && $row != array(null))
197                 $this->_currentRow = $row;
198             else
199                 return false;
200         }
201         
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);
206         }
207             
208         $this->_rowsCount++;
209         
210         return $this->_currentRow;
211     }
212     
213     /**
214      * Returns the number of fields in the current row
215      *
216      * @return int count of fiels in the current row
217      */
218     public function getFieldCount()
219     {
220         return count($this->_currentRow);
221     }
222
223     /**
224      * Determine the number of lines in this file.
225      *
226      * @return int
227      */
228     public function getNumberOfLinesInfile()
229     {
230         $lineCount = 0;
231
232         if ($this->_fp )
233         {
234             rewind($this->_fp);
235             while( !feof($this->_fp) )
236             {
237                 if( fgets($this->_fp) !== FALSE)
238                     $lineCount++;
239             }
240             //Reset the fp to after the bom if applicable.
241             $this->setFpAfterBOM();
242         }
243
244         return $lineCount;
245     }
246
247     //TODO: Add auto detection for field delim and qualifier properteis.
248     public function autoDetectCSVProperties()
249     {
250         // defaults
251         $this->_delimiter  = ",";
252         $this->_enclosure  = '"';
253
254         $this->_detector = new CsvAutoDetect($this->_sourcename);
255
256         $delimiter = $enclosure = false;
257
258         $ret = $this->_detector->getCsvSettings($delimiter, $enclosure);
259         if ($ret)
260         {
261             $this->_delimiter = $delimiter;
262             $this->_enclosure = $enclosure;
263             return TRUE;
264         }
265         else
266         {
267             return FALSE;
268         }
269     }
270
271     public function getFieldDelimeter()
272     {
273         return $this->_delimiter;
274     }
275
276     public function getFieldEnclosure()
277     {
278         return $this->_enclosure;
279     }
280
281     public function autoDetectCharacterSet()
282     {
283         global $locale;
284
285         $this->setFpAfterBOM();
286         
287         //Retrieve a sample set of data
288         $rows = array();
289
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++ )
299         {
300             $rows[$i] = $this->getNextRow();
301             if(!empty($rows[$i]) && $able_to_detect)
302             {
303                 foreach($rows[$i] as & $temp_value)
304                 {
305                     $current_charset = mb_detect_encoding($temp_value, $detectable_charsets);
306                     if(!empty($current_charset) && $current_charset != "UTF-8")
307                     {
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.
312                     }
313                 }
314             }
315         }
316
317         //Reset the fp to after the bom if applicable.
318         $this->setFpAfterBOM();
319
320         return $charset_for_import;
321
322     }
323
324     public function getDateFormat()
325     {
326         if ($this->_detector) {
327             $this->_date_format = $this->_detector->getDateFormat();
328         }
329
330         return $this->_date_format;
331     }
332
333     public function getTimeFormat()
334     {
335         if ($this->_detector) {
336             $this->_time_format = $this->_detector->getTimeFormat();
337         }
338
339         return $this->_time_format;
340     }
341
342     public function setHeaderRow($hasHeader)
343     {
344         $this->_hasHeader = $hasHeader;
345     }
346
347     public function hasHeaderRow($autoDetect = TRUE)
348     {
349         if($autoDetect)
350         {
351             if (!isset($_REQUEST['import_module']))
352                 return FALSE;
353
354             $module = $_REQUEST['import_module'];
355
356             $ret = FALSE;
357             $heading = FALSE;
358
359             if ($this->_detector)
360                 $ret = $this->_detector->hasHeader($heading, $module);
361
362             if ($ret)
363                 $this->_hasHeader = $heading;
364         }
365         return $this->_hasHeader;
366     }
367
368     public function setImportFileMap($map)
369     {
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)
374         {
375             $this->$k = $map->$v;
376         }
377     }
378
379     //Begin Implementation for SPL's Iterator interface
380     public function key()
381     {
382         return $this->_rowsCount;
383     }
384
385     public function current()
386     {
387         return $this->_currentRow;
388     }
389
390     public function next()
391     {
392         $this->getNextRow();
393     }
394
395     public function valid()
396     {
397         return $this->_currentRow !== FALSE;
398     }
399
400     public function rewind()
401     {
402         $this->setFpAfterBOM();
403         //Load our first row
404         $this->getNextRow();
405     }
406
407     public function getTotalRecordCount()
408     {
409         $totalCount = $this->getNumberOfLinesInfile();
410         if($this->hasHeaderRow(FALSE) && $totalCount > 0)
411         {
412             $totalCount--;
413         }
414         return $totalCount;
415     }
416     
417     public function loadDataSet($totalItems = 0)
418     {
419         $currentLine = 0;
420         $this->_dataSet = array();
421         $this->rewind();
422         //If there's a header don't include it.
423         if( $this->hasHeaderRow(FALSE) )
424             $this->next();
425         
426         while( $this->valid() &&  $totalItems > count($this->_dataSet) )
427         {
428             if($currentLine >= $this->_offset)
429             {
430                 $this->_dataSet[] = $this->_currentRow;
431             }
432             $this->next();
433             $currentLine++;
434         }
435
436         return $this;
437     }
438
439     public function getHeaderColumns()
440     {
441         $this->rewind();
442         if($this->hasHeaderRow(FALSE))
443             return $this->_currentRow;
444         else
445             return FALSE;
446     }
447
448 }