]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Import/views/view.step4.php
Release 6.2.0
[Github/sugarcrm.git] / modules / Import / views / view.step4.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: view handler for step 4 of the import process
42  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
43  * All Rights Reserved.
44  ********************************************************************************/
45  
46 require_once('include/MVC/View/SugarView.php');
47 require_once('modules/Import/ImportFile.php');
48 require_once('modules/Import/ImportFileSplitter.php');
49 require_once('modules/Import/ImportCacheFiles.php');
50 require_once('modules/Import/ImportFieldSanitize.php');
51 require_once('modules/Import/ImportDuplicateCheck.php');
52
53 class ImportViewStep4 extends SugarView 
54 {       
55     /** 
56      * @see SugarView::display()
57      */
58         public function display()
59     {
60         global $sugar_config;
61         
62         // Increase the max_execution_time since this step can take awhile
63         ini_set("max_execution_time", max($sugar_config['import_max_execution_time'],3600));
64         
65         // stop the tracker
66         TrackerManager::getInstance()->pause();
67         
68         // use our own error handler
69         set_error_handler(array('ImportViewStep4','handleImportErrors'),E_ALL);
70         
71         global $mod_strings, $app_strings, $current_user, $import_bean_map;
72         global $app_list_strings, $timedate;
73         
74         $update_only = ( isset($_REQUEST['import_type']) && $_REQUEST['import_type'] == 'update' );
75         $firstrow    = unserialize(base64_decode($_REQUEST['firstrow']));
76         
77         // All the Look Up Caches are initialized here
78         $enum_lookup_cache=array();
79         
80         // setup the importable fields array.
81         $importable_fields = $this->bean->get_importable_fields();
82         
83         // loop through all request variables
84         $importColumns = array();
85         foreach ($_REQUEST as $name => $value) {
86             // only look for var names that start with "fieldNum"
87             if (strncasecmp($name, "colnum_", 7) != 0) {
88                 continue;
89             }
90             
91             // pull out the column position for this field name
92             $pos = substr($name, 7);
93             
94             if ( isset($importable_fields[$value]) ) {
95                 // now mark that we've seen this field
96                 $importColumns[$pos] = $value;
97             }
98         }
99         
100         
101         // set the default locale settings
102         $ifs = new ImportFieldSanitize();
103         $ifs->dateformat = $_REQUEST['importlocale_dateformat'];
104         $ifs->timeformat = $_REQUEST['importlocale_timeformat'];
105         $ifs->timezone = $_REQUEST['importlocale_timezone'];
106         $currency = new Currency();
107         $currency->retrieve($_REQUEST['importlocale_currency']);
108         $ifs->currency_symbol = $currency->symbol;
109         $ifs->default_currency_significant_digits 
110             = $_REQUEST['importlocale_default_currency_significant_digits'];
111         $ifs->num_grp_sep 
112             = $_REQUEST['importlocale_num_grp_sep'];
113         $ifs->dec_sep = $_REQUEST['importlocale_dec_sep'];
114         $ifs->default_locale_name_format 
115             = $_REQUEST['importlocale_default_locale_name_format'];
116         
117         // Check to be sure we are getting an import file that is in the right place
118         if ( realpath(dirname($_REQUEST['tmp_file']).'/') != realpath($sugar_config['upload_dir']) )
119             trigger_error($mod_strings['LBL_CANNOT_OPEN'],E_USER_ERROR);
120         
121         // Open the import file
122         $importFile = new ImportFile(
123                         $_REQUEST['tmp_file'],
124                         $_REQUEST['custom_delimiter'],
125                         html_entity_decode($_REQUEST['custom_enclosure'],ENT_QUOTES)
126                         );
127         
128         if ( !$importFile->fileExists() ) {
129             trigger_error($mod_strings['LBL_CANNOT_OPEN'],E_USER_ERROR);
130         }
131         
132         $fieldDefs = $this->bean->getFieldDefinitions();
133         
134         while ( $row = $importFile->getNextRow() ) {
135             $focus = clone $this->bean;
136             $focus->unPopulateDefaultValues();
137             $focus->save_from_post = false;
138             $focus->team_id = null;
139             $ifs->createdBeans = array();
140         
141             $do_save = true;
142             
143             for ( $fieldNum = 0; $fieldNum < $_REQUEST['columncount']; $fieldNum++ ) {
144                 // loop if this column isn't set
145                 if ( !isset($importColumns[$fieldNum]) ) {
146                     continue;
147                 }
148                 
149                 // get this field's properties
150                 $field           = $importColumns[$fieldNum];
151                 $fieldDef        = $focus->getFieldDefinition($field);
152                 $fieldTranslated = translate((isset($fieldDef['vname'])?$fieldDef['vname']:$fieldDef['name']),
153                                         $_REQUEST['module'])." (".$fieldDef['name'].")";
154                 
155                 // Bug 37241 - Don't re-import over a field we already set during the importing of another field
156                 if ( !empty($focus->$field) ) {
157                     continue;
158                 }
159                 
160                 //DETERMINE WHETHER OR NOT $fieldDef['name'] IS DATE_MODIFIED AND SET A VAR, USE DOWN BELOW
161                 
162                 // translate strings
163                 global $locale;
164                 if(empty($locale)) {
165                     $locale = new Localization();
166                 }
167                 if ( isset($row[$fieldNum]) )
168                     $rowValue = $locale->translateCharset(
169                                     strip_tags(trim($row[$fieldNum])), 
170                                     $_REQUEST['importlocale_charset'],
171                                     $sugar_config['default_charset']
172                                     );
173                 else
174                     $rowValue = '';
175                 
176                 // If there is an default value then use it instead
177                 if ( !empty($_REQUEST[$field]) ) {
178                     if ( is_array($_REQUEST[$field]) )
179                         $defaultRowValue = encodeMultienumValue($_REQUEST[$field]);
180                     else
181                         $defaultRowValue = $_REQUEST[$field];
182                     // translate default values to the date/time format for the import file               
183                     if ( $fieldDef['type'] == 'date' 
184                             && $ifs->dateformat != $timedate->get_date_format() )
185                         $defaultRowValue = $timedate->swap_formats(
186                             $defaultRowValue, $ifs->dateformat, $timedate->get_date_format());
187                     if ( $fieldDef['type'] == 'time' 
188                             && $ifs->timeformat != $timedate->get_time_format() )
189                         $defaultRowValue = $timedate->swap_formats(
190                             $defaultRowValue, $ifs->timeformat, $timedate->get_time_format());
191                     if ( ($fieldDef['type'] == 'datetime' || $fieldDef['type'] == 'datetimecombo') 
192                             && $ifs->dateformat.' '.$ifs->timeformat != $timedate->get_date_time_format() )
193                         $defaultRowValue = $timedate->swap_formats(
194                             $defaultRowValue, $ifs->dateformat.' '.$ifs->timeformat, 
195                             $timedate->get_date_time_format());
196                     if ( in_array($fieldDef['type'],array('currency','float','int','num'))
197                             && $ifs->num_grp_sep != $current_user->getPreference('num_grp_sep') )
198                         $defaultRowValue = str_replace($current_user->getPreference('num_grp_sep'),
199                             $ifs->num_grp_sep,$defaultRowValue);
200                     if ( in_array($fieldDef['type'],array('currency','float'))
201                             && $ifs->dec_sep != $current_user->getPreference('dec_sep') )
202                         $defaultRowValue = str_replace($current_user->getPreference('dec_sep'),
203                             $ifs->dec_sep,$defaultRowValue);
204                     $currency->retrieve('-99');
205                     $user_currency_symbol = $currency->symbol;
206                     if ( $fieldDef['type'] == 'currency' 
207                             && $ifs->currency_symbol != $user_currency_symbol )
208                         $defaultRowValue = str_replace($user_currency_symbol,
209                             $ifs->currency_symbol,$defaultRowValue);
210                             
211                     
212                     if ( empty($rowValue) ) {
213                         $rowValue = $defaultRowValue;
214                         unset($defaultRowValue);
215                     }
216                 }
217                 
218                 // Bug 22705 - Don't update the First Name or Last Name value if Full Name is set
219                 if ( in_array($field, array('first_name','last_name')) && !empty($focus->full_name) )
220                     continue;
221                 
222                 // loop if this value has not been set
223                 if ( !isset($rowValue) )
224                     continue;
225                 
226                 // If the field is required and blank then error out
227                 if ( array_key_exists($field,$focus->get_import_required_fields())
228                         && empty($rowValue) 
229                         && $rowValue!='0') {
230                     $importFile->writeError(
231                         $mod_strings['LBL_REQUIRED_VALUE'],
232                         $fieldTranslated,
233                         'NULL'
234                         );
235                     $do_save = false;
236                 }
237     
238                 // Handle the special case "Sync to Outlook"
239                 if ( $focus->object_name == "Contacts" && $field == 'sync_contact' ) {
240                     $bad_names = array();
241                     $returnValue = $ifs->synctooutlook(
242                             $rowValue, 
243                             $fieldDef, 
244                             $bad_names);
245                     // try the default value on fail
246                     if ( !$returnValue && !empty($defaultRowValue) )
247                         $returnValue = $ifs->synctooutlook(
248                             $defaultRowValue, 
249                             $fieldDef, 
250                             $bad_names);
251                     if ( !$returnValue ) {
252                         $importFile->writeError(
253                             $mod_strings['LBL_ERROR_SYNC_USERS'],
254                             $fieldTranslated,
255                             explode(",",$bad_names));
256                         $do_save = 0;
257                     }
258                 }
259                 
260                 // Handle email1 and email2 fields ( these don't have the type of email )
261                 if ( $field == 'email1' || $field == 'email2' ) {
262                     $returnValue = $ifs->email($rowValue, $fieldDef, $focus);
263                     // try the default value on fail
264                     if ( !$returnValue && !empty($defaultRowValue) )
265                         $returnValue = $ifs->email(
266                             $defaultRowValue, 
267                             $fieldDef);
268                     if ( $returnValue === FALSE ) {
269                         $do_save=0;
270                         $importFile->writeError(
271                             $mod_strings['LBL_ERROR_INVALID_EMAIL'],
272                             $fieldTranslated,
273                             $rowValue);
274                     }
275                     else {
276                         $rowValue = $returnValue;
277                         // check for current opt_out and invalid email settings for this email address
278                         // if we find any, set them now
279                         $emailres = $focus->db->query(
280                             "SELECT opt_out, invalid_email FROM email_addresses 
281                                 WHERE email_address = '".$focus->db->quote($rowValue)."'");
282                         if ( $emailrow = $focus->db->fetchByAssoc($emailres) ) {
283                             $focus->email_opt_out = $emailrow['opt_out'];
284                             $focus->invalid_email = $emailrow['invalid_email'];
285                         }
286                     }
287                 }
288                 
289                 // Handle splitting Full Name into First and Last Name parts
290                 if ( $field == 'full_name' && !empty($rowValue) ) {
291                     $ifs->fullname(
292                             $rowValue, 
293                             $fieldDef,
294                             $focus);
295                 }
296                 
297                 // to maintain 451 compatiblity
298                 if(!isset($fieldDef['module']) && $fieldDef['type']=='relate')
299                     $fieldDef['module'] = ucfirst($fieldDef['table']);
300     
301                 if(isset($fieldDef['custom_type']) && !empty($fieldDef['custom_type']))
302                     $fieldDef['type'] = $fieldDef['custom_type'];
303                 
304                 // If the field is empty then there is no need to check the data
305                 if( !empty($rowValue) ) {  
306                     switch ($fieldDef['type']) {
307                     case 'enum':
308                     case 'multienum':
309                         if ( isset($fieldDef['type']) && $fieldDef['type'] == "multienum" ) 
310                             $returnValue = $ifs->multienum($rowValue,$fieldDef);
311                         else
312                             $returnValue = $ifs->enum($rowValue,$fieldDef);
313                         // try the default value on fail
314                         if ( !$returnValue && !empty($defaultRowValue) )
315                             if ( isset($fieldDef['type']) && $fieldDef['type'] == "multienum" ) 
316                                 $returnValue = $ifs->multienum($defaultRowValue,$fieldDef);
317                             else
318                                 $returnValue = $ifs->enum($defaultRowValue,$fieldDef);
319                         if ( $returnValue === FALSE ) {
320                             $importFile->writeError(
321                                 $mod_strings['LBL_ERROR_NOT_IN_ENUM']
322                                     . implode(",",$app_list_strings[$fieldDef['options']]),
323                                 $fieldTranslated,
324                                 $rowValue);
325                             $do_save = 0;
326                         }
327                         else
328                             $rowValue = $returnValue;
329                         
330                         break;
331                     case 'relate':
332                     case 'parent':
333                         $returnValue = $ifs->relate(
334                             $rowValue, 
335                             $fieldDef, 
336                             $focus,
337                             empty($defaultRowValue));
338                         if ( !$returnValue && !empty($defaultRowValue) )
339                             $returnValue = $ifs->relate(
340                                 $defaultRowValue, 
341                                 $fieldDef, 
342                                 $focus);
343                         // Bug 33623 - Set the id value found from the above method call as an importColumn
344                         if ( $returnValue !== false )
345                             $importColumns[] = $fieldDef['id_name'];
346                         break;
347                     case 'teamset':
348                         $returnValue = $ifs->teamset(
349                             $rowValue, 
350                             $fieldDef, 
351                             $focus);
352                             $importColumns[] = 'team_set_id';
353                             $importColumns[] = 'team_id';
354                         break;
355                     case 'fullname':
356                         break;
357                     default:
358                         $fieldtype = $fieldDef['type'];
359                         $returnValue = $ifs->$fieldtype($rowValue, $fieldDef, $focus);
360                         // try the default value on fail
361                         if ( !$returnValue && !empty($defaultRowValue) )
362                             $returnValue = $ifs->$fieldtype(
363                                 $defaultRowValue, 
364                                 $fieldDef, 
365                                 $focus);
366                         if ( !$returnValue ) {
367                             $do_save=0;
368                             $importFile->writeError(
369                                 $mod_strings['LBL_ERROR_INVALID_'.strtoupper($fieldDef['type'])],
370                                 $fieldTranslated,
371                                 $rowValue, 
372                                 $focus);
373                         }
374                         else {
375                             $rowValue = $returnValue;
376                         }
377                     }
378                 }
379                 $focus->$field = $rowValue;
380                 unset($defaultRowValue);
381             }
382             
383             // Now try to validate flex relate fields
384             if ( isset($focus->field_defs['parent_name']) 
385                     && isset($focus->parent_name)
386                     && ($focus->field_defs['parent_name']['type'] == 'parent') ) {
387                 // populate values from the picker widget if the import file doesn't have them
388                 $parent_idField = $focus->field_defs['parent_name']['id_name'];
389                 if ( empty($focus->$parent_idField) && !empty($_REQUEST[$parent_idField]) )
390                     $focus->$parent_idField = $_REQUEST[$parent_idField];
391                 $parent_typeField = $focus->field_defs['parent_name']['type_name'];
392                 if ( empty($focus->$parent_typeField) && !empty($_REQUEST[$parent_typeField]) )
393                     $focus->$parent_typeField = $_REQUEST[$parent_typeField];
394                 // now validate it
395                 $returnValue = $ifs->parent(
396                     $focus->parent_name, 
397                     $focus->field_defs['parent_name'], 
398                     $focus,
399                     empty($_REQUEST['parent_name']));
400                 if ( !$returnValue && !empty($_REQUEST['parent_name']) )
401                     $returnValue = $ifs->parent(
402                         $_REQUEST['parent_name'], 
403                         $focus->field_defs['parent_name'], 
404                         $focus);
405             }
406             
407             // check to see that the indexes being entered are unique.
408             if (isset($_REQUEST['display_tabs_def']) && $_REQUEST['display_tabs_def'] != ""){
409                 $idc = new ImportDuplicateCheck($focus);
410                 if ( $idc->isADuplicateRecord(explode('&', $_REQUEST['display_tabs_def'])) ){
411                     $importFile->markRowAsDuplicate();
412                     $this->_undoCreatedBeans($ifs->createdBeans);
413                     continue;
414                 }
415             }
416         
417             // if the id was specified
418             $newRecord = true;
419             if ( !empty($focus->id) ) {
420                 $focus->id = $this->_convertId($focus->id);
421         
422                 // check if it already exists
423                 $query = "SELECT * FROM {$focus->table_name} WHERE id='".$focus->db->quote($focus->id)."'";
424                 $result = $focus->db->query($query) 
425                             or sugar_die("Error selecting sugarbean: ");
426         
427                 $dbrow = $focus->db->fetchByAssoc($result);
428         
429                 if (isset ($dbrow['id']) && $dbrow['id'] != -1) {
430                     // if it exists but was deleted, just remove it
431                     if (isset ($dbrow['deleted']) && $dbrow['deleted'] == 1 && $update_only==false) {
432                         $query2 = "DELETE FROM {$focus->table_name} WHERE id='".$focus->db->quote($focus->id)."'";
433                         $result2 = $focus->db->query($query2) or sugar_die($mod_strings['LBL_ERROR_DELETING_RECORD']." ".$focus->id);
434                         if ($focus->hasCustomFields()) {
435                             $query3 = "DELETE FROM {$focus->table_name}_cstm WHERE id_c='".$focus->db->quote($focus->id)."'";
436                             $result2 = $focus->db->query($query3);
437                         }
438                         $focus->new_with_id = true;
439                     } 
440                     else {
441                         if( !$update_only ) {
442                             $do_save = 0;
443                             $importFile->writeError($mod_strings['LBL_ID_EXISTS_ALREADY'],'ID',$focus->id);
444                             $this->_undoCreatedBeans($ifs->createdBeans);
445                             continue;
446                         }
447                         $existing_focus = clone $this->bean;
448                         $newRecord = false;
449                         if ( !( $existing_focus->retrieve($dbrow['id']) instanceOf SugarBean ) ) {
450                             $do_save = 0;
451                             $importFile->writeError($mod_strings['LBL_RECORD_CANNOT_BE_UPDATED'],'ID',$focus->id);
452                             $this->_undoCreatedBeans($ifs->createdBeans);
453                             continue;
454                         }
455                         else {
456                             $newData = $focus->toArray();
457                             foreach ( $newData as $focus_key => $focus_value )
458                                 if ( in_array($focus_key,$importColumns) )
459                                     $existing_focus->$focus_key = $focus_value;
460                                                    
461                             $focus = $existing_focus;
462                         }
463                         unset($existing_focus);
464                     }
465                 }
466                 else {
467                     $focus->new_with_id = true;
468                 }
469             }
470         
471             if ($do_save) {
472                 // Populate in any default values to the bean
473                 $focus->populateDefaultValues();
474                 
475                 if ( !isset($focus->assigned_user_id) || $focus->assigned_user_id == '' && $newRecord ) {
476                     $focus->assigned_user_id = $current_user->id;
477                 }
478                 /*
479                  * Bug 34854: Added all conditions besides the empty check on date modified. Currently, if
480                  * we do an update to a record, it doesn't update the date_modified value.
481                  * Hack note: I'm doing a to_display and back to_db on the fetched row to make sure that any truncating that happens
482                  * when $focus->date_modified goes to_display and back to_db also happens on the fetched db value. Otherwise,
483                  * in some cases we truncate the seconds on one and not the other, and the comparison fails when it should pass
484                  */
485                 if ( ( !empty($focus->new_with_id) && !empty($focus->date_modified) ) ||
486                      ( empty($focus->new_with_id) && $timedate->to_db($focus->date_modified) != $timedate->to_db($timedate->to_display_date_time($focus->fetched_row['date_modified'])) )
487                    )
488                     $focus->update_date_modified = false;
489
490                 $focus->optimistic_lock = false;
491                 if ( $focus->object_name == "Contacts" && isset($focus->sync_contact) ) {
492                     //copy the potential sync list to another varible
493                     $list_of_users=$focus->sync_contact;
494                     //and set it to false for the save
495                     $focus->sync_contact=false;
496                 } else if($focus->object_name == "User" && !empty($current_user) && $focus->is_admin && !is_admin($current_user) && is_admin_for_module($current_user, 'Users')) {
497                         sugar_die($GLOBALS['mod_strings']['ERR_IMPORT_SYSTEM_ADMININSTRATOR']);
498                 }
499                 //bug# 40260 setting it true as the module in focus is involved in an import
500                 $focus->in_import=true;
501                 // call any logic needed for the module preSave
502                 $focus->beforeImportSave();
503                 
504                 
505                 $focus->save(false);
506                 
507                 // call any logic needed for the module postSave
508                 $focus->afterImportSave();
509                 
510                 if ( $focus->object_name == "Contacts" && isset($list_of_users) ) 
511                     $focus->process_sync_to_outlook($list_of_users);
512                 
513                 // Update the created/updated counter
514                 $importFile->markRowAsImported($newRecord);
515                 
516                 // Add ID to User's Last Import records
517                 if ( $newRecord )
518                     ImportFile::writeRowToLastImport(
519                         $_REQUEST['import_module'],
520                         ($focus->object_name == 'Case' ? 'aCase' : $focus->object_name),
521                         $focus->id);
522             }
523             else
524                 $this->_undoCreatedBeans($ifs->createdBeans);
525                 
526             unset($defaultRowValue);
527         }
528         
529         // save mapping if requested
530         if ( isset($_REQUEST['save_map_as']) && $_REQUEST['save_map_as'] != '' ) {
531             $mapping_file = new ImportMap();
532             if ( isset($_REQUEST['has_header']) && $_REQUEST['has_header'] == 'on') {
533                 $header_to_field = array ();
534                 foreach ($importColumns as $pos => $field_name) {
535                     if (isset($firstrow[$pos]) && isset($field_name)) {
536                         $header_to_field[$firstrow[$pos]] = $field_name;
537                     }
538                 }
539                 $mapping_file->setMapping($header_to_field);
540             } 
541             else {
542                 $mapping_file->setMapping($importColumns);
543             }
544             
545             // save default fields
546             $defaultValues = array();
547             for ( $i = 0; $i < $_REQUEST['columncount']; $i++ )
548                 
549             if (isset($importColumns[$i]) && !empty($_REQUEST[$importColumns[$i]])) {
550                 $field = $importColumns[$i];
551                 $fieldDef = $focus->getFieldDefinition($field);
552                                 if(!empty($fieldDef['custom_type']) && $fieldDef['custom_type'] == 'teamset') {
553                   require_once('include/SugarFields/Fields/Teamset/SugarFieldTeamset.php');
554                                   $sugar_field = new SugarFieldTeamset('Teamset');
555                                   $teams = $sugar_field->getTeamsFromRequest($field);
556                                   if(isset($_REQUEST['primary_team_name_collection'])) {
557                                          $primary_index = $_REQUEST['primary_team_name_collection'];
558                                   }     
559                                   
560                                   //If primary_index was selected, ensure that the first Array entry is the primary team
561                                   if(isset($primary_index)) {
562                                           $count = 0;
563                                           $new_teams = array(); 
564                                           foreach($teams as $id=>$name) {
565                                                  if($primary_index == $count++) {
566                                                         $new_teams[$id] = $name;
567                                                         unset($teams[$id]);                                             
568                                                         break;
569                                                  }
570                                           }
571                                           
572                                           foreach($teams as $id=>$name) {
573                                                  $new_teams[$id] = $name;
574                                           }
575                                           $teams = $new_teams;                                            
576                                   } //if
577                                   
578                                   $json = getJSONobj();
579                                   $defaultValues[$field] = $json->encode($teams);
580                                 } else {
581                   $defaultValues[$field] = $_REQUEST[$importColumns[$i]];
582                                 }
583             }
584                     
585             $mapping_file->setDefaultValues($defaultValues);      
586             $result = $mapping_file->save(
587                 $current_user->id, 
588                 $_REQUEST['save_map_as'], 
589                 $_REQUEST['import_module'], 
590                 $_REQUEST['source'],
591                 ( isset($_REQUEST['has_header']) && $_REQUEST['has_header'] == 'on'),
592                 $_REQUEST['custom_delimiter'],
593                 html_entity_decode($_REQUEST['custom_enclosure'],ENT_QUOTES)
594                 );
595         }
596         
597         $importFile->writeStatus();
598     }
599     
600     /**
601      * If a bean save is not done for some reason, this method will undo any of the beans that were created
602      *
603      * @param array $ids ids of user_last_import records created
604      */
605     protected function _undoCreatedBeans(
606         array $ids
607         )
608     {
609         $focus = new UsersLastImport();
610         foreach ($ids as $id)
611             $focus->undoById($id);
612     }
613     
614     /**
615      * clean id's when being imported
616      *
617      * @param  string $string
618      * @return string
619      */
620     protected function _convertId(
621         $string
622         )
623     {
624         return preg_replace_callback( 
625             '|[^A-Za-z0-9\-]|',
626             create_function(
627             // single quotes are essential here,
628             // or alternative escape all $ as \$
629             '$matches',
630             'return ord($matches[0]);'
631                  ) ,
632             $string);
633     }
634     
635     /**
636      * Replaces PHP error handler in Step4
637      *
638      * @param int    $errno
639      * @param string $errstr
640      * @param string $errfile
641      * @param string $errline
642      */
643     public static function handleImportErrors(
644         $errno, 
645         $errstr, 
646         $errfile, 
647         $errline
648         )
649     {
650         if ( !defined('E_DEPRECATED') )
651             define('E_DEPRECATED','8192');
652         if ( !defined('E_USER_DEPRECATED') )
653             define('E_USER_DEPRECATED','16384');
654         
655         // check to see if current reporting level should be included based upon error_reporting() setting, if not
656         // then just return
657         if ( !(error_reporting() & $errno) )
658             return true;
659     
660         switch ($errno) {
661         case E_USER_ERROR:
662             echo "ERROR: [$errno] $errstr on line $errline in file $errfile<br />\n";
663             exit(1);
664             break;
665         case E_USER_WARNING:
666         case E_WARNING:
667             echo "WARNING: [$errno] $errstr on line $errline in file $errfile<br />\n";
668             break;
669         case E_USER_NOTICE:
670         case E_NOTICE:
671             echo "NOTICE: [$errno] $errstr on line $errline in file $errfile<br />\n";
672             break;
673         case E_STRICT: 
674         case E_DEPRECATED:
675         case E_USER_DEPRECATED:   
676             // don't worry about these
677             //echo "STRICT ERROR: [$errno] $errstr on line $errline in file $errfile<br />\n";
678             break;
679         default:
680             echo "Unknown error type: [$errno] $errstr on line $errline in file $errfile<br />\n";
681             break;
682         }
683     
684         return true;
685     }
686 }