]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Import/sources/ImportFile.php
Release 6.4.0beta1
[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 && UploadStream::path($filename) == null )
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         $this->_enclosure  = ( empty($enclosure) ? '' : trim($enclosure) );
125         $this->setFpAfterBOM();
126     }
127
128     /**
129      * Remove the BOM (Byte Order Mark) from the beginning of the import row if it exists
130      * @return void
131      */
132     private function setFpAfterBOM()
133     {
134         if($this->_fp === FALSE)
135             return;
136
137         rewind($this->_fp);
138         $bomCheck = fread($this->_fp, 3);
139         if($bomCheck != pack("CCC",0xef,0xbb,0xbf)) {
140             rewind($this->_fp);
141         }
142     }
143     /**
144      * Destructor
145      *
146      * Deletes $_importFile if $_deleteFile is true
147      */
148     public function __destruct()
149     {
150         if ( $this->_deleteFile && $this->fileExists() ) {
151             fclose($this->_fp);
152             //Make sure the file exists before unlinking
153             if(file_exists($this->_sourcename)) {
154                unlink($this->_sourcename);
155             }
156         }
157
158         ini_restore('auto_detect_line_endings');
159     }
160
161     /**
162      * Returns true if the filename given exists and is readable
163      *
164      * @return bool
165      */
166     public function fileExists()
167     {
168         return !$this->_fp ? false : true;
169     }
170
171     /**
172      * Gets the next row from $_importFile
173      *
174      * @return array current row of file
175      */
176     public function getNextRow()
177     {
178         $this->_currentRow = FALSE;
179
180         if (!$this->fileExists())
181             return false;
182
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;
188             else
189                 return false;
190         }
191         else {
192             $row = fgetcsv($this->_fp, 8192, $this->_delimiter, $this->_enclosure);
193             if ($row !== false && $row != array(null))
194                 $this->_currentRow = $row;
195             else
196                 return false;
197         }
198
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);
203         }
204
205         $this->_rowsCount++;
206
207         return $this->_currentRow;
208     }
209
210     /**
211      * Returns the number of fields in the current row
212      *
213      * @return int count of fiels in the current row
214      */
215     public function getFieldCount()
216     {
217         return count($this->_currentRow);
218     }
219
220     /**
221      * Determine the number of lines in this file.
222      *
223      * @return int
224      */
225     public function getNumberOfLinesInfile()
226     {
227         $lineCount = 0;
228
229         if ($this->_fp )
230         {
231             rewind($this->_fp);
232             while( !feof($this->_fp) )
233             {
234                 if( fgets($this->_fp) !== FALSE)
235                     $lineCount++;
236             }
237             //Reset the fp to after the bom if applicable.
238             $this->setFpAfterBOM();
239         }
240
241         return $lineCount;
242     }
243
244     //TODO: Add auto detection for field delim and qualifier properteis.
245     public function autoDetectCSVProperties()
246     {
247         // defaults
248         $this->_delimiter  = ",";
249         $this->_enclosure  = '"';
250
251         $this->_detector = new CsvAutoDetect($this->_sourcename);
252
253         $delimiter = $enclosure = false;
254
255         $ret = $this->_detector->getCsvSettings($delimiter, $enclosure);
256         if ($ret)
257         {
258             $this->_delimiter = $delimiter;
259             $this->_enclosure = $enclosure;
260             return TRUE;
261         }
262         else
263         {
264             return FALSE;
265         }
266     }
267
268     public function getFieldDelimeter()
269     {
270         return $this->_delimiter;
271     }
272
273     public function getFieldEnclosure()
274     {
275         return $this->_enclosure;
276     }
277
278     public function autoDetectCharacterSet()
279     {
280         global $locale;
281
282         $this->setFpAfterBOM();
283
284         //Retrieve a sample set of data
285         $rows = array();
286
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++ )
296         {
297             $rows[$i] = $this->getNextRow();
298             if(!empty($rows[$i]) && $able_to_detect)
299             {
300                 foreach($rows[$i] as & $temp_value)
301                 {
302                     $current_charset = mb_detect_encoding($temp_value, $detectable_charsets);
303                     if(!empty($current_charset) && $current_charset != "UTF-8")
304                     {
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.
309                     }
310                 }
311             }
312         }
313
314         //Reset the fp to after the bom if applicable.
315         $this->setFpAfterBOM();
316
317         return $charset_for_import;
318
319     }
320
321     public function getDateFormat()
322     {
323         if ($this->_detector) {
324             $this->_date_format = $this->_detector->getDateFormat();
325         }
326
327         return $this->_date_format;
328     }
329
330     public function getTimeFormat()
331     {
332         if ($this->_detector) {
333             $this->_time_format = $this->_detector->getTimeFormat();
334         }
335
336         return $this->_time_format;
337     }
338
339     public function setHeaderRow($hasHeader)
340     {
341         $this->_hasHeader = $hasHeader;
342     }
343
344     public function hasHeaderRow($autoDetect = TRUE)
345     {
346         if($autoDetect)
347         {
348             if (!isset($_REQUEST['import_module']))
349                 return FALSE;
350
351             $module = $_REQUEST['import_module'];
352
353             $ret = FALSE;
354             $heading = FALSE;
355
356             if ($this->_detector)
357                 $ret = $this->_detector->hasHeader($heading, $module);
358
359             if ($ret)
360                 $this->_hasHeader = $heading;
361         }
362         return $this->_hasHeader;
363     }
364
365     public function setImportFileMap($map)
366     {
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)
371         {
372             $this->$k = $map->$v;
373         }
374     }
375
376     //Begin Implementation for SPL's Iterator interface
377     public function key()
378     {
379         return $this->_rowsCount;
380     }
381
382     public function current()
383     {
384         return $this->_currentRow;
385     }
386
387     public function next()
388     {
389         $this->getNextRow();
390     }
391
392     public function valid()
393     {
394         return $this->_currentRow !== FALSE;
395     }
396
397     public function rewind()
398     {
399         $this->setFpAfterBOM();
400         //Load our first row
401         $this->getNextRow();
402     }
403
404     public function getTotalRecordCount()
405     {
406         $totalCount = $this->getNumberOfLinesInfile();
407         if($this->hasHeaderRow(FALSE) && $totalCount > 0)
408         {
409             $totalCount--;
410         }
411         return $totalCount;
412     }
413
414     public function loadDataSet($totalItems = 0)
415     {
416         $currentLine = 0;
417         $this->_dataSet = array();
418         $this->rewind();
419         //If there's a header don't include it.
420         if( $this->hasHeaderRow(FALSE) )
421             $this->next();
422
423         while( $this->valid() &&  $totalItems > count($this->_dataSet) )
424         {
425             if($currentLine >= $this->_offset)
426             {
427                 $this->_dataSet[] = $this->_currentRow;
428             }
429             $this->next();
430             $currentLine++;
431         }
432
433         return $this;
434     }
435
436     public function getHeaderColumns()
437     {
438         $this->rewind();
439         if($this->hasHeaderRow(FALSE))
440             return $this->_currentRow;
441         else
442             return FALSE;
443     }
444
445 }