]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Import/views/view.confirm.php
Release 6.3.0beta2
[Github/sugarcrm.git] / modules / Import / views / view.confirm.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 /*********************************************************************************
39
40  * Description: view handler for step 1 of the import process
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
42  * All Rights Reserved.
43  ********************************************************************************/
44 require_once('modules/Import/views/ImportView.php');
45 require_once('modules/Import/sources/ImportFile.php');
46 require_once('modules/Import/ImportFileSplitter.php');
47 require_once('modules/Import/CsvAutoDetect.php');
48
49 require_once('include/upload_file.php');
50
51 class ImportViewConfirm extends ImportView
52 {
53     const SAMPLE_ROW_SIZE = 3;
54         protected $pageTitleKey = 'LBL_CONFIRM_TITLE';
55     protected $errorScript = "";
56     
57         /**
58      * @see SugarView::display()
59      */
60         public function display()
61     {
62         global $mod_strings, $app_strings, $current_user;
63         global $sugar_config, $locale;
64         
65         //echo "<pre>";print_r($_REQUEST);die();
66         $this->ss->assign("IMPORT_MODULE", $_REQUEST['import_module']);
67         $this->ss->assign("TYPE",( !empty($_REQUEST['type']) ? $_REQUEST['type'] : "import" ));
68         $this->ss->assign("SOURCE_ID", $_REQUEST['source_id']);
69
70         $this->instruction = 'LBL_SELECT_PROPERTY_INSTRUCTION';
71         $this->ss->assign('INSTRUCTION', $this->getInstruction());
72
73         $this->ss->assign("MODULE_TITLE", json_encode(htmlentities($this->getModuleTitle(false), ENT_NOQUOTES)));
74         $this->ss->assign("CURRENT_STEP", $this->currentStep);
75         $sugar_config['import_max_records_per_file'] = ( empty($sugar_config['import_max_records_per_file']) ? 1000 : $sugar_config['import_max_records_per_file'] );
76         $importSource = isset($_REQUEST['source']) ? $_REQUEST['source'] : 'csv' ;
77
78         // Clear out this user's last import
79         $seedUsersLastImport = new UsersLastImport();
80         $seedUsersLastImport->mark_deleted_by_user_id($current_user->id);
81         ImportCacheFiles::clearCacheFiles();
82
83         // handle uploaded file
84         $uploadFile = new UploadFile('userfile');
85         if (isset($_FILES['userfile']) && $uploadFile->confirm_upload())
86         {
87             $uploadFile->final_move('IMPORT_'.$this->bean->object_name.'_'.$current_user->id);
88             $uploadFileName = $uploadFile->get_upload_path('IMPORT_'.$this->bean->object_name.'_'.$current_user->id);
89         }
90         elseif( !empty($_REQUEST['tmp_file']) )
91         {
92             $uploadFileName = $_REQUEST['tmp_file'];
93         }
94         else
95         {
96             $this->_showImportError($mod_strings['LBL_IMPORT_MODULE_ERROR_NO_UPLOAD'],$_REQUEST['import_module'],'Step2', true, null, true);
97             return;
98         }
99
100         //check the file size, we dont want to process an empty file
101         if(isset($_FILES['userfile']['size']) && $_FILES['userfile']['size'] == 0){
102             //this file is empty, throw error message
103             $this->_showImportError($mod_strings['LBL_NO_LINES'],$_REQUEST['import_module'],'Step2', false, null, true);
104             return;
105         }
106
107         $mimeTypeOk = true;
108
109         //check to see if the file mime type is not a form of text or application octed streramand fire error if not
110         if(isset($_FILES['userfile']['type']) && strpos($_FILES['userfile']['type'],'octet-stream') === false && strpos($_FILES['userfile']['type'],'text') === false
111             && strpos($_FILES['userfile']['type'],'application/vnd.ms-excel') === false) {
112             //this file does not have a known text or application type of mime type, issue the warning
113             $error_msgs[] = $mod_strings['LBL_MIME_TYPE_ERROR_1'];
114             $error_msgs[] = $mod_strings['LBL_MIME_TYPE_ERROR_2'];
115             $this->_showImportError($error_msgs,$_REQUEST['import_module'],'Step2', true, $mod_strings['LBL_OK']);
116             $mimeTypeOk = false;
117         }
118
119         $this->ss->assign("FILE_NAME", $uploadFileName);
120
121         // Now parse the file and look for errors
122         $importFile = new ImportFile( $uploadFileName, $_REQUEST['custom_delimiter'], html_entity_decode($_REQUEST['custom_enclosure'],ENT_QUOTES), FALSE);
123
124         if( $this->shouldAutoDetectProperties($importSource) )
125         {
126             $GLOBALS['log']->debug("Auto detecing csv properties...");
127             $autoDetectOk = $importFile->autoDetectCSVProperties();
128             $importFileMap = array();
129             $this->ss->assign("SOURCE", 'csv');
130             if($autoDetectOk === FALSE)
131             {
132                 //show error only if previous mime type check has passed
133                 if($mimeTypeOk){
134                      $this->ss->assign("AUTO_DETECT_ERROR",  $mod_strings['LBL_AUTO_DETECT_ERROR']);
135                  }
136             }
137             else
138             {
139                 $dateFormat = $importFile->getDateFormat();
140                 $timeFormat = $importFile->getTimeFormat();
141                 if ($dateFormat) {
142                     $importFileMap['importlocale_dateformat'] = $dateFormat;
143                 }
144                 if ($timeFormat) {
145                     $importFileMap['importlocale_timeformat'] = $timeFormat;
146                 }
147             }
148         }
149         else
150         {
151             $impotMapSeed = $this->getImportMap($importSource);
152             $importFile->setImportFileMap($impotMapSeed);
153             $importFileMap = $impotMapSeed->getMapping();
154         }
155
156         $delimeter = $importFile->getFieldDelimeter();
157         $enclosure = $importFile->getFieldEnclosure();
158         $hasHeader = $importFile->hasHeaderRow();
159
160         $encodeOutput = TRUE;
161         //Handle users navigating back through the wizard.
162         if( !empty($_REQUEST['previous_action']) && $_REQUEST['previous_action'] == 'Confirm')
163         {
164             $encodeOutput = FALSE;
165             $importFileMap = $this->overloadImportFileMapFromRequest($importFileMap);
166             $delimeter = !empty($_REQUEST['custom_delimiter']) ? $_REQUEST['custom_delimiter'] : $delimeter;
167             $enclosure = isset($_REQUEST['custom_enclosure']) ? $_REQUEST['custom_enclosure'] : $enclosure;
168             $enclosure = html_entity_decode($enclosure, ENT_QUOTES);
169             $hasHeader = !empty($_REQUEST['has_header']) ? $_REQUEST['has_header'] : $hasHeader;
170             if ($hasHeader == 'on') {
171                 $hasHeader = true;
172             } else if ($hasHeader == 'off') {
173                 $hasHeader = false;
174             }
175         }
176
177         $this->ss->assign("IMPORT_ENCLOSURE_OPTIONS",  $this->getEnclosureOptions($enclosure));
178         $this->ss->assign("CUSTOM_DELIMITER",  $delimeter);
179         $this->ss->assign("CUSTOM_ENCLOSURE",  htmlentities($enclosure, ENT_QUOTES));
180         $hasHeaderFlag = $hasHeader ? " CHECKED" : "";
181         $this->ss->assign("HAS_HEADER_CHECKED", $hasHeaderFlag);
182
183         if ( !$importFile->fileExists() ) {
184             $this->_showImportError($mod_strings['LBL_CANNOT_OPEN'],$_REQUEST['import_module'],'Step2', false, null, true);
185             return;
186         }
187
188          //Check if we will exceed the maximum number of records allowed per import.
189          $maxRecordsExceeded = FALSE;
190          $maxRecordsWarningMessg = "";
191          $lineCount = $importFile->getNumberOfLinesInfile();
192          $maxLineCount = isset($sugar_config['import_max_records_total_limit'] ) ? $sugar_config['import_max_records_total_limit'] : 5000;
193          if( !empty($maxLineCount) && ($lineCount > $maxLineCount) )
194          {
195              $maxRecordsExceeded = TRUE;
196              $maxRecordsWarningMessg = string_format($mod_strings['LBL_IMPORT_ERROR_MAX_REC_LIMIT_REACHED'], array($lineCount, $maxLineCount) );
197          }
198
199         //Retrieve a sample set of data
200         $rows = $this->getSampleSet($importFile);
201         $this->ss->assign('column_count', $this->getMaxColumnsInSampleSet($rows) );
202         $this->ss->assign('HAS_HEADER', $importFile->hasHeaderRow(FALSE) );
203         $this->ss->assign('getNumberJs', $locale->getNumberJs());
204         $this->setImportFileCharacterSet($importFile, $importFileMap);
205         $this->setDateTimeProperties($importFileMap);
206         $this->setCurrencyOptions($importFileMap);
207         $this->setNumberFormatOptions($importFileMap);
208         $this->setNameFormatProperties($importFileMap);
209
210         $importMappingJS = $this->getImportMappingJS();
211
212         $this->ss->assign("SAMPLE_ROWS",$rows);
213         $JS = $this->_getJS($maxRecordsExceeded, $maxRecordsWarningMessg, $importMappingJS, $importFileMap );
214         $content = $this->ss->fetch('modules/Import/tpls/confirm.tpl');
215
216         $submitContent = "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><td align=\"right\">";
217         $submitContent .= "<input title=\"".$mod_strings['LBL_IMPORT_COMPLETE']."\" onclick=\"SUGAR.importWizard.closeDialog();\" accessKey=\"\" class=\"button\" type=\"submit\" name=\"finished\" value=\"  ".$mod_strings['LBL_IMPORT_COMPLETE']."  \" id=\"finished\">";
218         $submitContent .= "<input title=\"".$mod_strings['LBL_BACK']."\" accessKey=\"\" class=\"button\" type=\"submit\" name=\"button\" value=\"  ".$mod_strings['LBL_BACK']."  \" id=\"goback\">";
219             $submitContent .= "<input title=\"".$mod_strings['LBL_NEXT']."\" accessKey=\"\" class=\"button primary\" type=\"submit\" name=\"button\" value=\"  ".$mod_strings['LBL_NEXT']."  \" id=\"gonext\"></td></tr></table></form>";
220
221         $this->sendJsonOutput($content, $submitContent,$JS, $encodeOutput);
222     }
223
224     private function getEnclosureOptions($enclosure)
225     {
226         $results = array();
227         foreach ($GLOBALS['app_list_strings']['import_enclosure_options'] as $k => $v)
228         {
229             $results[htmlentities($k, ENT_QUOTES)] = $v;
230         }
231
232         return get_select_options_with_id($results, htmlentities($enclosure, ENT_QUOTES));
233     }
234
235     private function overloadImportFileMapFromRequest($importFileMap)
236     {
237         $overideKeys = array(
238             'importlocale_dateformat','importlocale_timeformat','importlocale_timezone','importlocale_charset',
239             'importlocale_currency','importlocale_default_currency_significant_digits','importlocale_num_grp_sep',
240             'importlocale_dec_sep','importlocale_default_locale_name_format','custom_delimiter', 'custom_enclosure'
241         );
242
243         foreach($overideKeys as $key)
244         {
245             if( !empty( $_REQUEST[$key]) )
246                 $importFileMap[$key] = $_REQUEST[$key];
247         }
248         return $importFileMap;
249     }
250
251     private function shouldAutoDetectProperties($importSource)
252     {
253         if(empty($importSource) || $importSource == 'csv' )
254             return TRUE;
255         else
256             return FALSE;
257     }
258
259     private function getImportMap($importSource)
260     {
261         if ( strncasecmp("custom:",$importSource,7) == 0)
262         {
263             $id = substr($importSource,7);
264             $import_map_seed = new ImportMap();
265             $import_map_seed->retrieve($id, false);
266
267             $this->ss->assign("SOURCE_ID", $import_map_seed->id);
268             $this->ss->assign("SOURCE_NAME", $import_map_seed->name);
269             $this->ss->assign("SOURCE", $import_map_seed->source);
270         }
271         else
272         {
273             $classname = 'ImportMap' . ucfirst($importSource);
274             if ( file_exists("modules/Import/maps/{$classname}.php") )
275                 require_once("modules/Import/maps/{$classname}.php");
276             elseif ( file_exists("custom/modules/Import/maps/{$classname}.php") )
277                 require_once("custom/modules/Import/maps/{$classname}.php");
278             else
279             {
280                 require_once("custom/modules/Import/maps/ImportMapOther.php");
281                 $classname = 'ImportMapOther';
282                 $importSource = 'other';
283             }
284             if ( class_exists($classname) )
285             {
286                 $import_map_seed = new $classname;
287                 $this->ss->assign("SOURCE", $importSource);
288             }
289         }
290
291         return $import_map_seed;
292     }
293
294     private function setNameFormatProperties($field_map = array())
295     {
296         global $locale, $current_user;
297
298         $localized_name_format = isset($field_map['importlocale_default_locale_name_format'])? $field_map['importlocale_default_locale_name_format'] : $locale->getLocaleFormatMacro($current_user);
299         $this->ss->assign('default_locale_name_format', $localized_name_format);
300         $this->ss->assign('getNameJs', $locale->getNameJs());
301
302     }
303
304     private function setNumberFormatOptions($field_map = array())
305     {
306         global $locale, $current_user, $sugar_config;
307
308         $num_grp_sep = isset($field_map['importlocale_num_grp_sep'])? $field_map['importlocale_num_grp_sep'] : $current_user->getPreference('num_grp_sep');
309         $dec_sep = isset($field_map['importlocale_dec_sep'])? $field_map['importlocale_dec_sep'] : $current_user->getPreference('dec_sep');
310
311         $this->ss->assign("NUM_GRP_SEP",( empty($num_grp_sep) ? $sugar_config['default_number_grouping_seperator'] : $num_grp_sep ));
312         $this->ss->assign("DEC_SEP",( empty($dec_sep)? $sugar_config['default_decimal_seperator'] : $dec_sep ));
313
314
315         $significantDigits = isset($field_map['importlocale_default_currency_significant_digits']) ? $field_map['importlocale_default_currency_significant_digits']
316                                 :  $locale->getPrecedentPreference('default_currency_significant_digits', $current_user);
317
318         $sigDigits = '';
319         for($i=0; $i<=6; $i++)
320         {
321             if($significantDigits == $i)
322             {
323                 $sigDigits .= '<option value="'.$i.'" selected="true">'.$i.'</option>';
324             } else
325             {
326                 $sigDigits .= '<option value="'.$i.'">'.$i.'</option>';
327             }
328         }
329
330         $this->ss->assign('sigDigits', $sigDigits);
331     }
332
333
334     private function setCurrencyOptions($field_map = array() )
335     {
336         global $locale, $current_user;
337         $cur_id = isset($field_map['importlocale_currency'])? $field_map['importlocale_currency'] : $locale->getPrecedentPreference('currency', $current_user);
338         // get currency preference
339         require_once('modules/Currencies/ListCurrency.php');
340         $currency = new ListCurrency();
341         if($cur_id)
342             $selectCurrency = $currency->getSelectOptions($cur_id);
343         else
344             $selectCurrency = $currency->getSelectOptions();
345
346         $this->ss->assign("CURRENCY", $selectCurrency);
347
348         $currenciesVars = "";
349         $i=0;
350         foreach($locale->currencies as $id => $arrVal)
351         {
352             $currenciesVars .= "currencies[{$i}] = '{$arrVal['symbol']}';\n";
353             $i++;
354         }
355         $currencySymbolsJs = <<<eoq
356 var currencies = new Object;
357 {$currenciesVars}
358 function setSymbolValue(id) {
359     document.getElementById('symbol').value = currencies[id];
360 }
361 eoq;
362         return $currencySymbolsJs;
363
364     }
365
366
367     private function setDateTimeProperties( $field_map = array() )
368     {
369         global $current_user, $sugar_config;
370
371         $timeFormat = $current_user->getUserDateTimePreferences();
372         $defaultTimeOption = isset($field_map['importlocale_timeformat'])? $field_map['importlocale_timeformat'] : $timeFormat['time'];
373         $defaultDateOption = isset($field_map['importlocale_dateformat'])? $field_map['importlocale_dateformat'] : $timeFormat['date'];
374
375         $timeOptions = get_select_options_with_id($sugar_config['time_formats'], $defaultTimeOption);
376         $dateOptions = get_select_options_with_id($sugar_config['date_formats'], $defaultDateOption);
377
378         // get list of valid timezones
379         $userTZ = isset($field_map['importlocale_timezone'])? $field_map['importlocale_timezone'] : $current_user->getPreference('timezone');
380         if(empty($userTZ))
381             $userTZ = TimeDate::userTimezone();
382
383         $this->ss->assign('TIMEZONE_CURRENT', $userTZ);
384         $this->ss->assign('TIMEOPTIONS', $timeOptions);
385         $this->ss->assign('DATEOPTIONS', $dateOptions);
386         $this->ss->assign('TIMEZONEOPTIONS', TimeDate::getTimezoneList());
387     }
388
389     private function setImportFileCharacterSet($importFile, $field_map = array())
390     {
391         global $locale;
392         $charset_for_import = isset($field_map['importlocale_charset']) ? $field_map['importlocale_charset'] : $importFile->autoDetectCharacterSet();
393         $charsetOptions = get_select_options_with_id( $locale->getCharsetSelect(), $charset_for_import);//wdong,  bug 25927, here we should use the charset testing results from above.
394         $this->ss->assign('CHARSETOPTIONS', $charsetOptions);
395     }
396
397     protected function getImportMappingJS()
398     {
399         $results = array();
400         $importMappings = array('ImportMapSalesforce', 'ImportMapOutlook');
401         foreach($importMappings as $importMap)
402         {
403             $tmpFile = "modules/Import/$importMap.php";
404             if( file_exists($tmpFile) )
405             {
406                 require_once($tmpFile);
407                 $t = new $importMap();
408                 $results[$t->name] = array('delim' => $t->delimiter, 'enclos' => $t->enclosure, 'has_header' => $t->has_header);
409             }
410         }
411         return $results;
412     }
413
414     public function getMaxColumnsInSampleSet($sampleSet)
415     {
416         $maxColumns = 0;
417         foreach($sampleSet as $v)
418         {
419             if(count($v) > $maxColumns)
420                 $maxColumns = count($v);
421             else
422                 continue;
423         }
424
425         return $maxColumns;
426     }
427
428     public function getSampleSet($importFile)
429     {
430         $rows = array();
431         for($i=0; $i < self::SAMPLE_ROW_SIZE; $i++)
432         {
433             $rows[] = $importFile->getNextRow();
434         }
435
436         if( ! $importFile->hasHeaderRow(FALSE) )
437         {
438             array_unshift($rows, array_fill(0,1,'') );
439         }
440
441         return $rows;
442     }
443
444     /**
445      * Returns JS used in this view
446      */
447     private function _getJS($maxRecordsExceeded, $maxRecordsWarningMessg, $importMappingJS, $importFileMap)
448     {
449         global $mod_strings, $locale;
450         $maxRecordsExceededJS = $maxRecordsExceeded?"true":"false";
451         $importMappingJS = json_encode($importMappingJS);
452         
453         $currencySymbolJs = $this->setCurrencyOptions($importFileMap);
454         $getNumberJs = $locale->getNumberJs();
455         $getNameJs = $locale->getNameJs();
456         
457         return <<<EOJAVASCRIPT
458
459
460 var import_mapping_js = $importMappingJS;
461 document.getElementById('goback').onclick = function(){
462     document.getElementById('importconfirm').action.value = 'Step2';
463         var success = function(data) {          
464                         var response = YAHOO.lang.JSON.parse(data.responseText);
465                         importWizardDialogDiv = document.getElementById('importWizardDialogDiv');
466                         importWizardDialogTitle = document.getElementById('importWizardDialogTitle');
467                         submitDiv = document.getElementById('submitDiv');
468                         importWizardDialogDiv.innerHTML = response['html'];
469                         importWizardDialogTitle.innerHTML = response['title'];
470                         submitDiv.innerHTML = response['submitContent'];
471                         eval(response['script']);
472                 } 
473         var formObject = document.getElementById('importconfirm');
474                 YAHOO.util.Connect.setForm(formObject);
475                 var cObj = YAHOO.util.Connect.asyncRequest('POST', "index.php", {success: success, failure: success});
476 }
477
478 document.getElementById('gonext').onclick = function(){
479     document.getElementById('importconfirm').action.value = 'Step3';
480     
481         var success = function(data) {
482                         var response = YAHOO.lang.JSON.parse(data.responseText);
483                         importWizardDialogDiv = document.getElementById('importWizardDialogDiv');
484                         importWizardDialogTitle = document.getElementById('importWizardDialogTitle');
485                         submitDiv = document.getElementById('submitDiv');
486                         importWizardDialogDiv.innerHTML = response['html'];
487                         importWizardDialogTitle.innerHTML = response['title'];
488                         
489                         submitDiv.innerHTML = response['submitContent'];
490                         SUGAR.util.evalScript(response['submitContent']);
491                         eval(response['script']);
492
493                 }
494     
495         var formObject = document.getElementById('importconfirm');
496                 YAHOO.util.Connect.setForm(formObject);
497                 var cObj = YAHOO.util.Connect.asyncRequest('POST', "index.php", {success: success, failure: success});
498
499 }
500
501 document.getElementById('custom_enclosure').onchange = function()
502 {
503     document.getElementById('importconfirm').custom_enclosure_other.style.display = ( this.value == 'other' ? '' : 'none' );
504 }
505
506 document.getElementById('toggleImportOptions').onclick = function() {
507     if (document.getElementById('importOptions').style.display == 'none'){
508         document.getElementById('importOptions').style.display = '';
509         document.getElementById('toggleImportOptions').value='  {$mod_strings['LBL_HIDE_ADVANCED_OPTIONS']}  ';
510         document.getElementById('toggleImportOptions').title='{$mod_strings['LBL_HIDE_ADVANCED_OPTIONS']}';
511     }
512     else {
513         document.getElementById('importOptions').style.display = 'none';
514         document.getElementById('toggleImportOptions').value='  {$mod_strings['LBL_SHOW_ADVANCED_OPTIONS']}  ';
515         document.getElementById('toggleImportOptions').title='{$mod_strings['LBL_SHOW_ADVANCED_OPTIONS']}';
516     }
517 }
518
519 YAHOO.util.Event.onDOMReady(function(){
520     if($maxRecordsExceededJS)
521     {
522         var contImport = confirm('$maxRecordsWarningMessg');
523         if(!contImport)
524         {
525             var module = document.getElementById('importconfirm').import_module.value;
526             var source = document.getElementById('importconfirm').source.value;
527             var returnUrl = "index.php?module=Import&action=Step2&import_module=" + module + "&source=" + source;
528             document.location.href = returnUrl;
529         }
530     }
531
532     function refreshDataTable(e)
533     {
534         var callback = {
535           success: function(o) {
536             document.getElementById('confirm_table').innerHTML = o.responseText;
537           },
538           failure: function(o) {},
539         };
540
541         var importFile = document.getElementById('importconfirm').file_name.value;
542         var fieldDelimeter = document.getElementById('custom_delimiter').value;
543         var fieldQualifier = document.getElementById('custom_enclosure').value;
544         var hasHeader = document.getElementById('importconfirm').has_header.checked ? 'true' : '';
545
546         if(fieldQualifier == 'other' && this.id == 'custom_enclosure')
547         {
548             return;
549         }
550         else if( fieldQualifier == 'other' )
551         {
552             fieldQualifier = document.getElementById('custom_enclosure_other').value;
553         }
554
555         var url = 'index.php?action=RefreshMapping&module=Import&importFile=' + importFile
556                     + '&delim=' + fieldDelimeter + '&qualif=' + fieldQualifier + "&header=" + hasHeader;
557
558         YAHOO.util.Connect.asyncRequest('GET', url, callback);
559     }
560     var subscribers = ["custom_delimiter", "custom_enclosure", "custom_enclosure_other", "has_header", "importlocale_charset"];
561     YAHOO.util.Event.addListener(subscribers, "change", refreshDataTable);
562
563     function setMappingProperties(el)
564     {
565        var sourceEl = document.getElementById('source');
566        if(sourceEl.value != '' && sourceEl.value != 'csv' && sourceEl.value != 'salesforce' && sourceEl.value != 'outlook')
567        {
568            if( !confirm(SUGAR.language.get('Import','LBL_CONFIRM_MAP_OVERRIDE')) )
569            {
570                 deSelectExternalSources();
571                 return;
572            }
573         }
574         var selectedMap = this.value;
575         if( typeof(import_mapping_js[selectedMap]) == 'undefined')
576             return;
577
578         sourceEl.value = selectedMap;
579         document.getElementById('custom_delimiter').value = import_mapping_js[selectedMap].delim;
580         document.getElementById('custom_enclosure').value = import_mapping_js[selectedMap].enclos;
581         document.getElementById('has_header').checked = import_mapping_js[selectedMap].has_header;
582
583         refreshDataTable();
584     }
585
586     function deSelectExternalSources()
587     {
588         var els = document.getElementsByName('external_source');
589         for(i=0;i<els.length;i++)
590         {
591             els[i].checked = false;
592         }
593     }
594     YAHOO.util.Event.addListener(['sf_map', 'outlook_map'], "click", setMappingProperties);
595 });
596 var deselectEl = document.getElementById('deselect');
597 if(deselectEl)
598 {
599     deselectEl.onclick = function() {
600         var els = document.getElementsByName('external_source');
601         for(i=0;i<els.length;i++)
602         {
603             els[i].checked = false;
604         }
605     }
606 }
607
608 {$currencySymbolJs}
609 {$getNumberJs}
610 {$getNameJs}
611 setSigDigits();
612 setSymbolValue(document.getElementById('currency_select').selectedIndex);
613
614 EOJAVASCRIPT;
615     }
616
617     /**
618      * Displays the Smarty template for an error
619      *
620      * @param string $message error message to show
621      * @param string $module what module we were importing into
622      * @param string $action what page we should go back to
623      */
624     protected function _showImportError($message,$module,$action = 'Step1',$showCancel = false, $cancelLabel = null, $display = false)
625     {
626         if(!is_array($message)){
627             $message = array($message);
628         }
629         $ss = new Sugar_Smarty();
630         $display_msg = '';
631         foreach($message as $m){
632             $display_msg .= '<p>'.htmlentities($m, ENT_QUOTES).'</p><br>';
633         }
634                 global $mod_strings;
635
636         $ss->assign("MESSAGE",$display_msg);
637         $ss->assign("ACTION",$action);
638         $ss->assign("IMPORT_MODULE",$module);
639         $ss->assign("MOD", $GLOBALS['mod_strings']);
640         $ss->assign("SOURCE","");
641         $ss->assign("SHOWCANCEL",$showCancel);
642         if ( isset($_REQUEST['source']) )
643             $ss->assign("SOURCE", $_REQUEST['source']);
644
645         if ($cancelLabel) {
646             $ss->assign('CANCELLABEL', $cancelLabel);
647         }
648
649         $content = $ss->fetch('modules/Import/tpls/error.tpl');
650         $nothing ="";
651         $ss->assign("CONTENT",json_encode($nothing));
652         $ss->assign("SUBMITCONTENT",json_encode($nothing));
653         $ss->assign("JS",json_encode($content));
654
655         $this->errorScript .= htmlspecialchars($content, ENT_NOQUOTES);
656
657
658         if ($display){
659             echo json_encode(array(
660                 'html'          => $nothing,
661                 'submitContent' => $nothing,
662                 'title'         => $this->getModuleTitle(false),
663                 'script'        => $this->errorScript,
664             ));
665         }
666     }
667 }
668
669 ?>