* Copyright (C) 2005-2009 Regis Houssin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /** * \file htdocs/imports/import.php * \ingroup import * \brief Edit import page * \version $Id$ */ require_once("../main.inc.php"); require_once(DOL_DOCUMENT_ROOT."/core/class/html.formfile.class.php"); require_once(DOL_DOCUMENT_ROOT."/core/class/html.formother.class.php"); require_once(DOL_DOCUMENT_ROOT."/imports/class/import.class.php"); require_once(DOL_DOCUMENT_ROOT.'/includes/modules/import/modules_import.php'); require_once(DOL_DOCUMENT_ROOT."/lib/files.lib.php"); $langs->load("exports"); $langs->load("errors"); // Security check if ($user->societe_id) $socid=$user->societe_id; $result=restrictedArea($user,'import',$origin_id,''); $entitytoicon=array( 'invoice'=>'bill','invoice_line'=>'bill', 'order'=>'order' ,'order_line'=>'order', 'intervention'=>'intervention' ,'inter_line'=>'intervention', 'member'=>'user' ,'member_type'=>'group','subscription'=>'payment', 'tax'=>'generic' ,'tax_type'=>'generic', 'account'=>'account', 'payment'=>'payment', 'product'=>'product','stock'=>'generic','warehouse'=>'stock', 'category'=>'generic', 'other'=>'generic' ); $entitytolang=array( // Translation code 'user'=>'User', 'company'=>'Company','contact'=>'Contact', 'invoice'=>'Bill','invoice_line'=>'InvoiceLine', 'order'=>'Order','order_line'=>'OrderLine', 'intervention'=>'Intervention' ,'inter_line'=>'InterLine', 'member'=>'Member','member_type'=>'MemberType','subscription'=>'Subscription', 'tax'=>'SocialContribution','tax_type'=>'DictionnarySocialContributions', 'account'=>'BankTransactions', 'payment'=>'Payment', 'product'=>'Product','stock'=>'Stock','warehouse'=>'Warehouse', 'category'=>'Category', 'other'=>'Other' ); $datatoimport=isset($_GET["datatoimport"])? $_GET["datatoimport"] : (isset($_POST["datatoimport"])?$_POST["datatoimport"]:''); $format=isset($_GET["format"])? $_GET["format"] : (isset($_POST["format"])?$_POST["format"]:''); $filetoimport=isset($_GET["filetoimport"])? $_GET["filetoimport"] : (isset($_POST["filetoimport"])?$_POST["filetoimport"]:''); $action=isset($_GET["action"]) ? $_GET["action"] : (isset($_POST["action"])?$_POST["action"]:''); $step=isset($_GET["step"])? $_GET["step"] : (isset($_POST["step"])?$_POST["step"]:1); $import_name=isset($_POST["import_name"])? $_POST["import_name"] : ''; $hexa=isset($_POST["hexa"])? $_POST["hexa"] : ''; $importmodelid=isset($_POST["importmodelid"])? $_POST["importmodelid"] : ''; $excludefirstline=isset($_GET["excludefirstline"])? $_GET["excludefirstline"] : (isset($_POST["excludefirstline"])?$_POST["excludefirstline"]:0); $objimport=new Import($db); $objimport->load_arrays($user,($step==1?'':$datatoimport)); $objmodelimport=new ModeleImports(); $html = new Form($db); $htmlother = new FormOther($db); $formfile = new FormFile($db); // Init $array_match_file_to_database from _SESSION $serialized_array_match_file_to_database=isset($_SESSION["dol_array_match_file_to_database"])?$_SESSION["dol_array_match_file_to_database"]:''; $array_match_file_to_database=array(); $fieldsarray=explode(',',$serialized_array_match_file_to_database); foreach($fieldsarray as $elem) { $tabelem=explode('=',$elem,2); $key=$tabelem[0]; $val=$tabelem[1]; if ($key && $val) { $array_match_file_to_database[$key]=$val; } } /* * Actions */ /* if ($action=='downfield' || $action=='upfield') { $pos=$array_match_file_to_database[$_GET["field"]]; if ($action=='downfield') $newpos=$pos+1; if ($action=='upfield') $newpos=$pos-1; // Recherche code avec qui switcher $newcode=""; foreach($array_match_file_to_database as $code=>$value) { if ($value == $newpos) { $newcode=$code; break; } } //print("Switch pos=$pos (code=".$_GET["field"].") and newpos=$newpos (code=$newcode)"); if ($newcode) // Si newcode trouve (protection contre resoumission de page) { $array_match_file_to_database[$_GET["field"]]=$newpos; $array_match_file_to_database[$newcode]=$pos; $_SESSION["dol_array_match_file_to_database"]=$serialized_array_match_file_to_database; } } */ if ($action == 'builddoc') { // Build import file $result=$objimport->build_file($user, $_POST['model'], $datatoimport, $array_match_file_to_database); if ($result < 0) { $mesg='
'.$objimport->error.'
'; } else { $mesg='
'.$langs->trans("FileSuccessfullyBuilt").'
'; } } if ($action == 'deleteprof') { if ($_GET["id"]) { $objimport->fetch($_GET["id"]); $result=$objimport->delete($user); } } // Save import config to database if ($action == 'add_import_model') { if ($import_name) { // Set save string $hexa=''; foreach($array_match_file_to_database as $key=>$val) { if ($hexa) $hexa.=','; $hexa.=$key.'='.$val; } $objimport->model_name = $import_name; $objimport->datatoimport = $datatoimport; $objimport->hexa = $hexa; $result = $objimport->create($user); if ($result >= 0) { $mesg='
'.$langs->trans("ImportModelSaved",$objimport->model_name).'
'; } else { $langs->load("errors"); if ($objimport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $mesg='
'.$langs->trans("ErrorImportDuplicateProfil").'
'; } else $mesg='
'.$objimport->error.'
'; } } else { $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentities("ImportModelName")).'
'; } } if ($step == 3 && $datatoimport) { require_once(DOL_DOCUMENT_ROOT."/lib/files.lib.php"); if ( $_POST["sendit"] && ! empty($conf->global->MAIN_UPLOAD_DOC)) { create_exdir($conf->import->dir_temp); $nowyearmonth=dol_date('YmdHis',dol_now(),0); $fullpath=$conf->import->dir_temp . "/" . $nowyearmonth . '-'.$_FILES['userfile']['name']; if (dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $fullpath,1) > 0) { dol_syslog("File ".$fullpath." was added for import"); } else { $langs->load("errors"); $mesg = $langs->trans("ErrorFailedToSaveFile"); } } } if ($step == 4 && $action == 'select_model') { // Reinit match arrays $_SESSION["dol_array_match_file_to_database"]=''; $serialized_array_match_file_to_database=''; $array_match_file_to_database=array(); // Load model from $importmodelid and set $array_match_file_to_database // and $_SESSION["dol_array_match_file_to_database"] $result = $objimport->fetch($importmodelid); if ($result > 0) { $serialized_array_match_file_to_database=$objimport->hexa; $fieldsarray=explode(',',$serialized_array_match_file_to_database); foreach($fieldsarray as $elem) { $tabelem=explode('=',$elem); $key=$tabelem[0]; $val=$tabelem[1]; if ($key && $val) { $array_match_file_to_database[$key]=$val; } } $_SESSION["dol_array_match_file_to_database"]=$serialized_array_match_file_to_database; } } if ($action == 'saveorder') { // Enregistrement de la position des champs dol_syslog("boxorder=".$_GET['boxorder']." datatoimport=".$_GET["datatoimport"], LOG_DEBUG); $part=explode(':',$_GET['boxorder']); $colonne=$part[0]; $list=$part[1]; dol_syslog('column='.$colonne.' list='.$list); // Init targets fields array $fieldstarget=$objimport->array_import_fields[0]; // Reinit match arrays. We redefine array_match_file_to_database $serialized_array_match_file_to_database=''; $array_match_file_to_database=array(); $fieldsarray=explode(',',$list); $pos=0; foreach($fieldsarray as $fieldnb) // For each elem in list. fieldnb start from 1 to ... { // Get name of database fields at position $pos and put it into $namefield $posbis=0;$namefield=''; foreach($fieldstarget as $key => $val) // key: val: { //dol_syslog('AjaxImport key='.$key.' val='.$val); if ($posbis < $pos) { $posbis++; continue; } // We found the key of targets that is at position pos $namefield=$key; //dol_syslog('AjaxImport Field name found for file field nb '.$fieldnb.'='.$namefield); break; } if ($fieldnb && $namefield) { $array_match_file_to_database[$fieldnb]=$namefield; if ($serialized_array_match_file_to_database) $serialized_array_match_file_to_database.=','; $serialized_array_match_file_to_database.=($fieldnb.'='.$namefield); } $pos++; } // We save new matching in session $_SESSION["dol_array_match_file_to_database"]=$serialized_array_match_file_to_database; dol_syslog('dol_array_match_file_to_database='.$serialized_array_match_file_to_database); } /* * View */ // STEP 1: Page to select dataset to import if ($step == 1 || ! $datatoimport) { // Clean saved file-database matching $serialized_array_match_file_to_database=''; $array_match_file_to_database=array(); $_SESSION["dol_array_match_file_to_database"]=''; $parm=''; if ($excludefirstline) $param.='&excludefirstline=1'; llxHeader('',$langs->trans("NewImport"),'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones'); $h = 0; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=1'.$param; $head[$h][1] = $langs->trans("Step")." 1"; $hselected=$h; $h++; /* $head[$h][0] = ''; $head[$h][1] = $langs->trans("Step")." 2"; $h++; */ dol_fiche_head($head, $hselected, $langs->trans("NewImport")); print ''; print $langs->trans("SelectImportDataSet").'
'; // Affiche les modules d'imports print '
'; print ''; print ''; print ''; print ''; print ''; $val=true; if (sizeof($objimport->array_import_code)) { foreach ($objimport->array_import_code as $key => $value) { $val=!$val; print ''; } } else { print ''; } print '
'.$langs->trans("Module").''.$langs->trans("ImportableDatas").' 
'; //print img_object($objimport->array_import_module[$key]->getName(),$import->array_import_module[$key]->picto).' '; print $objimport->array_import_module[$key]->getName(); print ''; //print $value; print img_object($objimport->array_import_module[$key]->getName(),$objimport->array_import_icon[$key]).' '; print $objimport->array_import_label[$key]; print ''; if ($objimport->array_import_perms[$key]) { print ''.img_picto($langs->trans("NewImport"),'filenew').''; } else { print $langs->trans("NotEnoughPermissions"); } print '
'.$langs->trans("NoImportableData").'
'; print ''; print ''; if ($mesg) print $mesg; } // STEP 2: Page to select input format file if ($step == 2 && $datatoimport) { $param='&datatoimport='.$datatoimport; if ($excludefirstline) $param.='&excludefirstline=1'; llxHeader('',$langs->trans("NewImport"),'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones'); $h = 0; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=1'; $head[$h][1] = $langs->trans("Step")." 1"; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=2'.$param; $head[$h][1] = $langs->trans("Step")." 2"; $hselected=$h; $h++; dol_fiche_head($head, $hselected, $langs->trans("NewImport")); print ''; // Module print ''; print ''; // Lot de donnees a importer print ''; print ''; print '
'.$langs->trans("Module").''; //print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_module[0]->picto).' '; print $objimport->array_import_module[0]->getName(); print '
'.$langs->trans("DatasetToImport").''; print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_icon[0]).' '; print $objimport->array_import_label[0]; print '
'; print '
'."\n"; print '
'; print ''; print ''; print ''; $filetoimport=''; $var=true; // Add format informations and link to download example print ''; print ''; $liste=$objmodelimport->liste_modeles($db); foreach($liste as $key) { $var=!$var; print ''; print ''; $text=$objmodelimport->getDriverDesc($key); print ''; print ''; // Action button print ''; print ''; } print '
'.$langs->trans("ChooseFormatOfFileToImport",img_picto('','filenew')).'
'; print $langs->trans("FileMustHaveOneOfFollowingFormat"); print '
'.img_picto_common($key,$objmodelimport->getPicto($key)).''.$html->textwithpicto($objmodelimport->getDriverLabel($key),$text).''.$langs->trans("DownloadEmptyExample").''; print ''.img_picto($langs->trans("SelectFormat"),'filenew').''; print '
'; print ''; if ($mesg) print $mesg; } // STEP 3: Page to select file if ($step == 3 && $datatoimport) { $param='&datatoimport='.$datatoimport.'&format='.$format; if ($excludefirstline) $param.='&excludefirstline=1'; $liste=$objmodelimport->liste_modeles($db); llxHeader('',$langs->trans("NewImport"),'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones'); $h = 0; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=1'.$param; $head[$h][1] = $langs->trans("Step")." 1"; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=2'.$param; $head[$h][1] = $langs->trans("Step")." 2"; $hselected=$h; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=3'.$param; $head[$h][1] = $langs->trans("Step")." 3"; $hselected=$h; $h++; dol_fiche_head($head, $hselected, $langs->trans("NewImport")); print ''; // Module print ''; print ''; // Lot de donnees a importer print ''; print ''; print '
'.$langs->trans("Module").''; //print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_module[0]->picto).' '; print $objimport->array_import_module[0]->getName(); print '
'.$langs->trans("DatasetToImport").''; print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_icon[0]).' '; print $objimport->array_import_label[0]; print '

'; print ''.$langs->trans("InformationOnSourceFile").''; print ''; //print ''; // Source file format print ''; print ''; print '
'.$langs->trans("InformationOnSourceFile").'
'.$langs->trans("SourceFileFormat").''; $text=$objmodelimport->getDriverDesc($format); print $html->textwithpicto($objmodelimport->getDriverLabel($format),$text); print ''.$langs->trans("DownloadEmptyExample").''; print '
'; print '
'."\n"; print '
'; print ''; print ''; print ''; $filetoimport=''; $var=true; print ''; print ''; // Input file name box $var=false; print '\n"; // Search available imports $dir = $conf->import->dir_temp; $newdir=utf8_check($dir)?utf8_decode($dir):$dir; // opendir need ISO $handle=@opendir($newdir); if ($handle) { //print ''; } print '
'.$langs->trans("ChooseFileToImport",img_picto('','filenew')).'
'.$langs->trans("FileWithDataToImport").'
'; print '     '; print ''; print ''; print ''; print ''; print ''; print "
'; //print ''; // Search available files to import $i=0; while (($file = readdir($handle))!==false) { // readdir return value in ISO and we want UTF8 in memory if (! utf8_check($file)) $file=utf8_encode($file); if (preg_match('/^\./',$file)) continue; $modulepart='import'; $urlsource=$_SERVER["PHP_SELF"].'?step='.$step.$param.'&filetoimport='.urlencode($filetoimport); $relativepath=$file; $var=!$var; print ''; print ''; print ''; // Affiche taille fichier print ''; // Affiche date fichier print ''; // Del button print ''; // Action button print ''; print ''; } //print '
'.img_mime($file).''; $modulepart='import'; //$relativepath=$filetoimport; print ''; print $file; print ''; print ''.dol_print_size(dol_filesize($dir.'/'.$file)).''.dol_print_date(dol_filemtime($dir.'/'.$file),'dayhour').''.img_delete().''; print ''.img_picto($langs->trans("NewImport"),'filenew').''; print '
'; print ''; if ($mesg) print $mesg; } // STEP 4: Page to make matching between source file and database fields if ($step == 4 && $datatoimport) { $model=$format; $liste=$objmodelimport->liste_modeles($db); // Create classe to use for import $dir = DOL_DOCUMENT_ROOT . "/includes/modules/import/"; $file = "import_".$model.".modules.php"; $classname = "Import".ucfirst($model); require_once($dir.$file); $obj = new $classname($db); // Load source fields in input file $fieldssource=array(); $result=$obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport,$langs); if ($result >= 0) { // Read first line $arrayrecord=$obj->import_read_record(); // Put into array fieldssource starting with 1. $i=1; foreach($arrayrecord as $key => $val) { $fieldssource[$i]['example1']=dol_trunc($val['val'],24); $i++; } $obj->import_close_file(); } // Load targets fields in database $fieldstarget=$objimport->array_import_fields[0]; $maxpos=max(sizeof($fieldssource),sizeof($fieldstarget)); //var_dump($array_match_file_to_database); // Is it a first time in page (if yes, we must initialize array_match_file_to_database) if (sizeof($array_match_file_to_database) == 0) { // This is first input in screen, we need to define // $array_match_file_to_database // $serialized_array_match_file_to_database // $_SESSION["dol_array_match_file_to_database"] $pos=1; while ($pos <= sizeof($fieldssource)) { if (sizeof($fieldssource) >= 1 && $pos <= sizeof($fieldssource)) { $posbis=1; foreach($fieldstarget as $key => $val) { if ($posbis < $pos) { $posbis++; continue; } // We found the key of targets that is at position pos $array_match_file_to_database[$pos]=$key; if ($serialized_array_match_file_to_database) $serialized_array_match_file_to_database.=','; $serialized_array_match_file_to_database.=($pos.'='.$key); break; } } $pos++; } // Save the match array in session. We now will use the array in session. $_SESSION["dol_array_match_file_to_database"]=$serialized_array_match_file_to_database; } $array_match_database_to_file=array_flip($array_match_file_to_database); //print $serialized_array_match_file_to_database; //print $_SESSION["dol_array_match_file_to_database"]; //var_dump($array_match_file_to_database);exit; // Now $array_match_file_to_database contains fieldnb(1,2,3...)=>fielddatabase(key in $array_match_file_to_database) $param='&format='.$format.'&datatoimport='.$datatoimport.'&filetoimport='.urlencode($filetoimport); if ($excludefirstline) $param.='&excludefirstline=1'; llxHeader('',$langs->trans("NewImport"),'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones'); $h = 0; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=1'.$param; $head[$h][1] = $langs->trans("Step")." 1"; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=2'.$param; $head[$h][1] = $langs->trans("Step")." 2"; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=3'.$param; $head[$h][1] = $langs->trans("Step")." 3"; $hselected=$h; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=4'.$param; $head[$h][1] = $langs->trans("Step")." 4"; $hselected=$h; $h++; dol_fiche_head($head, $hselected, $langs->trans("NewImport")); print ''; // Module print ''; print ''; // Lot de donnees a importer print ''; print ''; print '
'.$langs->trans("Module").''; //print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_module[0]->picto).' '; print $objimport->array_import_module[0]->getName(); print '
'.$langs->trans("DatasetToImport").''; print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_icon[0]).' '; print $objimport->array_import_label[0]; print '

'; print ''.$langs->trans("InformationOnSourceFile").''; print ''; //print ''; // Source file format print ''; print ''; // File to import print ''; print ''; print '
'.$langs->trans("InformationOnSourceFile").'
'.$langs->trans("SourceFileFormat").''; $text=$objmodelimport->getDriverDesc($format); print $html->textwithpicto($objmodelimport->getDriverLabel($format),$text); print '
'.$langs->trans("FileToImport").''; $modulepart='import'; //$relativepath=$filetoimport; print ''; print $filetoimport; print ''; print '
'; print '
'."\n"; // List of source fields print ''."\n"; print '
'; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print '
'; print $langs->trans("SelectImportFields",img_picto('','uparrow','')).' '; $htmlother->select_import_model($importmodelid,'importmodelid',$datatoimport,1); print ''; print '
'; print '
'; // Title of array with fields print ''; print ''; print ''; print ''; print ''; //var_dump($array_match_file_to_database); print ''; // List of not imported fields print ''; print ''; print ''; print '
'.$langs->trans("FieldsInSourceFile").''.$langs->trans("FieldsInTargetDatabase").'
'; $fieldsplaced=array(); $valforsourcefieldnb=array(); $listofkeys=array(); foreach($array_match_file_to_database as $key => $val) { $listofkeys[$key]=1; } print "\n\n"; print '
'."\n"; // List of source fields $var=true; $lefti=1; foreach ($array_match_file_to_database as $key => $val) { $var=!$var; show_elem($fieldssource,$lefti,$key,$val,$var); // key is field number in source file //print '> '.$lefti.'-'.$key.'-'.$val; $listofkeys[$key]=1; $fieldsplaced[$key]=1; $valforsourcefieldnb[$lefti]=$key; $lefti++; if ($lefti > sizeof($fieldstarget)) break; // Other fields are in the not imported area } //var_dump($valforsourcefieldnb); // Complete source fields from sizeof($fieldssource)+1 to sizeof($fieldstarget) $more=1; while ($lefti <= sizeof($fieldstarget)) { $var=!$var; $newkey=getnewkey($fieldssource,$listofkeys); show_elem($fieldssource,$lefti,$newkey,'',$var); // key start after field number in source file //print '> '.$lefti.'-'.$newkey; $listofkeys[$key]=1; $lefti++; $more++; } print "
\n"; print "\n"; print '
'; // List of targets fields $i = 0; $var=true; $mandatoryfieldshavesource=true; print ''; foreach($fieldstarget as $code=>$label) { $var=!$var; print ''; $i++; $entity=(! empty($objimport->array_import_entities[0][$code])?$objimport->array_import_entities[0][$code]:$objimport->array_import_icon[0]); $tablealias=preg_replace('/(\..*)$/i','',$code); $tablename=$objimport->array_import_tables[0][$tablealias]; $entityicon=$entitytoicon[$entity]?$entitytoicon[$entity]:$entity; $entitylang=$entitytolang[$entity]?$entitytolang[$entity]:$entity; print ''; print ''; // Info field print ''; print ''; $save_select.=$bit; } print '
=>'.img_object('',$entityicon).' '.$langs->trans($entitylang).''; $newlabel=preg_replace('/\*$/','',$label); $text=$langs->trans($newlabel); $more=''; if (preg_match('/\*$/',$label)) { $text=''.$text.''; $more=((! empty($valforsourcefieldnb[$i]) && $valforsourcefieldnb[$i] <= sizeof($fieldssource)) ? '' : img_warning($langs->trans("FieldNeedSource"))); if ($mandatoryfieldshavesource) $mandatoryfieldshavesource=(! empty($valforsourcefieldnb[$i]) && ($valforsourcefieldnb[$i] <= sizeof($fieldssource))); //print 'xx'.($i).'-'.$valforsourcefieldnb[$i].'-'.$mandatoryfieldshavesource; } print $text; print ''; $filecolumn=$array_match_database_to_file[$code]; // Source field info $htmltext =''.$langs->trans("FieldSource").'
'; if ($filecolumn > sizeof($fieldssource)) $htmltext.=$langs->trans("DataComeFromNoWhere").'
'; else { if (empty($objimport->array_import_convertvalue[0][$code])) // If source file does not need convertion { $filecolumntoshow=$filecolumn; $htmltext.=$langs->trans("DataComeFromFileFieldNb",$filecolumntoshow).'
'; } else { if ($objimport->array_import_convertvalue[0][$code]['rule']=='fetchfromref') $htmltext.=$langs->trans("DataComeFromIdFoundFromRef",$filecolumn,$langs->transnoentitiesnoconv($entitylang)).'
'; } } $htmltext.=$langs->trans("SourceRequired").': '.yn(preg_match('/\*$/',$label)).''; $example=$objimport->array_import_examplevalues[0][$code]; if ($example) $htmltext.='
'.$langs->trans("SourceExample").': '.$example.'
'; $htmltext.='
'; // Target field info $htmltext.=''.$langs->trans("FieldTarget").'
'; if (empty($objimport->array_import_convertvalue[0][$code])) // If source file does not need convertion { $htmltext.=$langs->trans("DataIsInsertedInto").'
'; } else { if ($objimport->array_import_convertvalue[0][$code]['rule']=='fetchfromref') $htmltext.=$langs->trans("DataIDSourceIsInsertedInto").'
'; } $htmltext.=$langs->trans("FieldTitle").": ".$langs->trans($newlabel)."
"; $htmltext.=$langs->trans("Table")." -> ".$langs->trans("Field").': '.$tablename." -> ".preg_replace('/^.*\./','',$code)."
"; print $html->textwithpicto($more,$htmltext); print '
'; print '
'.$langs->trans("NotImportedFields").'
'; print "\n\n"; print '\n"; print "\n"; print ''; $i=0; while ($i < $nbofnotimportedfields) { // Print empty cells show_elem('','','','none',$var,'nostyle'); $i++; } print '
'; print ''; if ($conf->use_javascript_ajax) { print ''."\n"; } if ($mesg) print $mesg; /* * Barre d'action */ print '
'; if (sizeof($array_match_file_to_database)) { if ($mandatoryfieldshavesource) { print ''.$langs->trans("NextStep").''; } else { print ''.$langs->trans("NextStep").''; } } print '
'; // Area for profils import if (sizeof($array_match_file_to_database)) { print '
'."\n"; print ''."\n"; print $langs->trans("SaveImportModel"); print '
'; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; $var=false; print ''; print ''; // List of existing import profils $sql = "SELECT rowid, label"; $sql.= " FROM ".MAIN_DB_PREFIX."import_model"; $sql.= " WHERE type = '".$datatoimport."'"; $sql.= " ORDER BY rowid"; $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; $var=false; while ($i < $num) { $var=!$var; $obj = $db->fetch_object($resql); print ''; $i++; } } else { dol_print_error($db); } print '
'.$langs->trans("ImportModelName").' 
'; print ''; print '
'; print $obj->label; print ''; print 'rowid.'&filetoimport='.urlencode($filetoimport).'">'; print img_delete(); print ''; print '
'; print '
'; } } // STEP 5: Summary of choices and launch simulation if ($step == 5 && $datatoimport) { $model=$format; $liste=$objmodelimport->liste_modeles($db); // Create classe to use for import $dir = DOL_DOCUMENT_ROOT . "/includes/modules/import/"; $file = "import_".$model.".modules.php"; $classname = "Import".ucfirst($model); require_once($dir.$file); $obj = new $classname($db); // Load source fields in input file $fieldssource=array(); $result=$obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport,$langs); if ($result >= 0) { // Read first line $arrayrecord=$obj->import_read_record(); // Put into array fieldssource starting with 1. $i=1; foreach($arrayrecord as $key => $val) { $fieldssource[$i]['example1']=dol_trunc($val['val'],24); $i++; } $obj->import_close_file(); } $nboflines=dol_count_nb_of_line($conf->import->dir_temp.'/'.$filetoimport); $param='&format='.$format.'&datatoimport='.$datatoimport.'&filetoimport='.urlencode($filetoimport).'&nboflines='.$nboflines; $param2='&format='.$format.'&datatoimport='.$datatoimport.'&filetoimport='.urlencode($filetoimport).'&nboflines='.$nboflines; if ($excludefirstline) $param.='&excludefirstline=1'; llxHeader('',$langs->trans("NewImport"),'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones'); $h = 0; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=1'.$param; $head[$h][1] = $langs->trans("Step")." 1"; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=2'.$param; $head[$h][1] = $langs->trans("Step")." 2"; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=3'.$param; $head[$h][1] = $langs->trans("Step")." 3"; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=4'.$param; $head[$h][1] = $langs->trans("Step")." 4"; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=5'.$param; $head[$h][1] = $langs->trans("Step")." 5"; $hselected=$h; $h++; dol_fiche_head($head, $hselected, $langs->trans("NewImport")); print ''; // Module print ''; print ''; // Lot de donnees a importer print ''; print ''; print '
'.$langs->trans("Module").''; //print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_module[0]->picto).' '; print $objimport->array_import_module[0]->getName(); print '
'.$langs->trans("DatasetToImport").''; print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_icon[0]).' '; print $objimport->array_import_label[0]; print '

'; print ''.$langs->trans("InformationOnSourceFile").''; print ''; //print ''; // Source file format print ''; print ''; // File to import print ''; print ''; // Nb of fields print ''; // Checkbox do not import first line print ''; print '
'.$langs->trans("InformationOnSourceFile").'
'.$langs->trans("SourceFileFormat").''; $text=$objmodelimport->getDriverDesc($format); print $html->textwithpicto($objmodelimport->getDriverLabel($format),$text); print '
'.$langs->trans("FileToImport").''; $modulepart='import'; //$relativepath=$filetoimport; print ''; print $filetoimport; print ''; print '
'; print $langs->trans("NbOfSourceLines"); print ''; print $nboflines; print '
'; print $langs->trans("Option"); print ''; print ''; print ' '.$langs->trans("DoNotImportFirstLine"); print '
'; print '
'; print ''.$langs->trans("InformationOnTargetTables").''; print ''; //print ''; // Tables imported print ''; // Fields imported print ''; print '
'.$langs->trans("InformationOnTargetTables").'
'; print $langs->trans("TablesTarget"); print ''; $listtables=array(); $sort_array_match_file_to_database=$array_match_file_to_database; foreach($array_match_file_to_database as $code=>$label) { //var_dump($fieldssource); if ($code > sizeof($fieldssource)) continue; //print $code.'-'.$label; $alias=preg_replace('/(\..*)$/i','',$label); $listtables[$alias]=$objimport->array_import_tables[0][$alias]; } if (sizeof($listtables)) { $newval=''; //ksort($listtables); foreach ($listtables as $val) { if ($newval) print ', '; $newval=$val; // Link to Dolibarr wiki pages /*$helppagename='EN:Table_'.$newval; if ($helppagename && empty($conf->global->MAIN_HELP_DISABLELINK)) { // Get helpbaseurl, helppage and mode from helppagename and langs $arrayres=getHelpParamFor($helppagename,$langs); $helpbaseurl=$arrayres['helpbaseurl']; $helppage=$arrayres['helppage']; $mode=$arrayres['mode']; $newval.=' '.img_picto($langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage'),DOL_URL_ROOT.'/theme/common/helpdoc.png','',1).''; }*/ print $newval; } } else print $langs->trans("Error"); print '
'; print $langs->trans("FieldsTarget").''; $listfields=array(); $i=0; //print 'fieldsource='.$fieldssource; $sort_array_match_file_to_database=$array_match_file_to_database; ksort($sort_array_match_file_to_database); //var_dump($sort_array_match_file_to_database); foreach($sort_array_match_file_to_database as $code=>$label) { $i++; //var_dump($fieldssource); if ($code > sizeof($fieldssource)) continue; //print $code.'-'.$label; $alias=preg_replace('/(\..*)$/i','',$label); $listfields[$i]=$langs->trans("Field").' '.$code.'->'.$label; } print sizeof($listfields)?(join(', ',$listfields)):$langs->trans("Error"); print '
'; print ''; if (GETPOST('action') != 'launchsimu') { // Show import id print $langs->trans("NowClickToTestTheImport",$langs->transnoentitiesnoconv("RunSimulateImportFile")).'
'; print '
'; // Actions print '
'; if ($user->rights->import->run) { print ''.$langs->trans("RunSimulateImportFile").''; } else { print ''.$langs->trans("RunSimulateImportFile").''; } print '
'; } else { // Launch import $arrayoferrors=array(); $arrayofwarnings=array(); $maxnboferrors=empty($conf->global->IMPORT_MAX_NB_OF_ERRORS)?50:$conf->global->IMPORT_MAX_NB_OF_ERRORS; $maxnbofwarnings=empty($conf->global->IMPORT_MAX_NB_OF_WARNINGS)?50:$conf->global->IMPORT_MAX_NB_OF_WARNINGS; $nboferrors=0; $nbofwarnings=0; $importid=dol_print_date(dol_now('tzserver'),'%Y%m%d%H%M%S'); //var_dump($array_match_file_to_database); $db->begin(); // Open input file $nbok=0; $pathfile=$conf->import->dir_temp.'/'.$filetoimport; $result=$obj->import_open_file($pathfile,$langs); if ($result > 0) { $sourcelinenb=0; // Loop on each input file record while ($sourcelinenb < $nboflines) { $sourcelinenb++; $arrayrecord=$obj->import_read_record(); if ($excludefirstline && $sourcelinenb == 1) continue; $result=$obj->import_insert($arrayrecord,$array_match_file_to_database,$objimport,sizeof($fieldssource),$importid); if (sizeof($obj->errors)) $arrayoferrors[$sourcelinenb]=$obj->errors; if (sizeof($obj->warnings)) $arrayofwarnings[$sourcelinenb]=$obj->warnings; if (! sizeof($obj->errors) && ! sizeof($obj->warnings)) $nbok++; } // Close file $obj->import_close_file(); } else { print $langs->trans("ErrorFailedToOpenFile",$pathfile); } $db->rollback(); // We force rollback because this was just a simulation. // Show OK if (! sizeof($arrayoferrors) && ! sizeof($arrayofwarnings)) print img_tick().' '.$langs->trans("NoError").'

'; else print $langs->trans("NbOfLinesOK",$nbok).'

'; // Show Errors //var_dump($arrayoferrors); if (sizeof($arrayoferrors)) { print img_error().' '.$langs->trans("ErrorsOnXLines",sizeof($arrayoferrors)).'
'; print '
'; foreach ($arrayoferrors as $key => $val) { $nboferrors++; if ($nboferrors > $maxnboferrors) { print $langs->trans("TooMuchErrors",(sizeof($arrayoferrors)-$nboferrors))."
"; break; } print '* '.$langs->trans("Line").' '.$key.'
'; foreach($val as $i => $err) { print '     > '.$err['lib'].'
'; } } print '
'; print '
'; } // Show Warnings //var_dump($arrayoferrors); if (sizeof($arrayofwarnings)) { print img_warning().' '.$langs->trans("WarningsOnXLines",sizeof($arrayofwarnings)).'
'; print '
'; foreach ($arrayofwarnings as $key => $val) { $nbofwarnings++; if ($nbofwarnings > $maxnbofwarnings) { print $langs->trans("TooMuchWarnings",(sizeof($arrayofwarnings)-$nbofwarnings))."
"; break; } print ' * '.$langs->trans("Line").' '.$key.'
'; foreach($val as $i => $err) { print '     > '.$err['lib'].'
'; } } print '
'; print '
'; } // Show import id $importid=dol_print_date(dol_now('tzserver'),'%Y%m%d%H%M%S'); print '
'; print $langs->trans("NowClickToRunTheImport",$langs->transnoentitiesnoconv("RunImportFile")).'
'; print $langs->trans("DataLoadedWithId",$importid).'
'; print '
'; print '
'; // Actions print '
'; if ($user->rights->import->run) { if (empty($nboferrors)) { print ''.$langs->trans("RunImportFile").''; } else { //print ''.$langs->trans("RunSimulateImportFile").''; print ''.$langs->trans("RunImportFile").''; } } else { print ''.$langs->trans("RunSimulateImportFile").''; print ''.$langs->trans("RunImportFile").''; } print '
'; } if ($mesg) print $mesg; } // STEP 6: Real import if ($step == 6 && $datatoimport) { $model=$format; $liste=$objmodelimport->liste_modeles($db); $importid=$_REQUEST["importid"]; // Create classe to use for import $dir = DOL_DOCUMENT_ROOT . "/includes/modules/import/"; $file = "import_".$model.".modules.php"; $classname = "Import".ucfirst($model); require_once($dir.$file); $obj = new $classname($db); // Load source fields in input file $fieldssource=array(); $result=$obj->import_open_file($conf->import->dir_temp.'/'.$filetoimport,$langs); if ($result >= 0) { // Read first line $arrayrecord=$obj->import_read_record(); // Put into array fieldssource starting with 1. $i=1; foreach($arrayrecord as $key => $val) { $fieldssource[$i]['example1']=dol_trunc($val['val'],24); $i++; } $obj->import_close_file(); } $nboflines=(! empty($_GET["nboflines"])?$_GET["nboflines"]:dol_count_nb_of_line($conf->import->dir_temp.'/'.$filetoimport)); $param='&format='.$format.'&datatoimport='.$datatoimport.'&filetoimport='.urlencode($filetoimport).'&nboflines='.$nboflines; if ($excludefirstline) $param.='&excludefirstline=1'; llxHeader('',$langs->trans("NewImport"),'EN:Module_Imports_En|FR:Module_Imports|ES:Módulo_Importaciones'); $h = 0; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=1'.$param; $head[$h][1] = $langs->trans("Step")." 1"; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=2'.$param; $head[$h][1] = $langs->trans("Step")." 2"; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=3'.$param; $head[$h][1] = $langs->trans("Step")." 3"; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=4'.$param; $head[$h][1] = $langs->trans("Step")." 4"; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=5'.$param; $head[$h][1] = $langs->trans("Step")." 5"; $h++; $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step=6'.$param; $head[$h][1] = $langs->trans("Step")." 6"; $hselected=$h; $h++; dol_fiche_head($head, $hselected, $langs->trans("NewImport")); print ''; // Module print ''; print ''; // Lot de donnees a importer print ''; print ''; print '
'.$langs->trans("Module").''; //print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_module[0]->picto).' '; print $objimport->array_import_module[0]->getName(); print '
'.$langs->trans("DatasetToImport").''; print img_object($objimport->array_import_module[0]->getName(),$objimport->array_import_icon[0]).' '; print $objimport->array_import_label[0]; print '

'; print ''.$langs->trans("InformationOnSourceFile").''; print ''; //print ''; // Source file format print ''; print ''; // File to import print ''; print ''; // Nb of fields print ''; // Checkbox do not import first line print ''; print '
'.$langs->trans("InformationOnSourceFile").'
'.$langs->trans("SourceFileFormat").''; $text=$objmodelimport->getDriverDesc($format); print $html->textwithpicto($objmodelimport->getDriverLabel($format),$text); print '
'.$langs->trans("FileToImport").''; $modulepart='import'; //$relativepath=$filetoimport; print ''; print $filetoimport; print ''; print '
'; print $langs->trans("NbOfSourceLines"); print ''; print $nboflines; print '
'; print $langs->trans("Option"); print ''; print ''; print ' '.$langs->trans("DoNotImportFirstLine"); print '
'; print '
'; print ''.$langs->trans("InformationOnTargetTables").''; print ''; //print ''; // Tables imported print ''; // Fields imported print ''; print '
'.$langs->trans("InformationOnTargetTables").'
'; print $langs->trans("TablesTarget"); print ''; $listtables=array(); foreach($array_match_file_to_database as $code=>$label) { //var_dump($fieldssource); if ($code > sizeof($fieldssource)) continue; //print $code.'-'.$label; $alias=preg_replace('/(\..*)$/i','',$label); $listtables[$alias]=$objimport->array_import_tables[0][$alias]; } if (sizeof($listtables)) { $newval=''; foreach ($listtables as $val) { if ($newval) print ', '; $newval=$val; // Link to Dolibarr wiki pages /*$helppagename='EN:Table_'.$newval; if ($helppagename && empty($conf->global->MAIN_HELP_DISABLELINK)) { // Get helpbaseurl, helppage and mode from helppagename and langs $arrayres=getHelpParamFor($helppagename,$langs); $helpbaseurl=$arrayres['helpbaseurl']; $helppage=$arrayres['helppage']; $mode=$arrayres['mode']; $newval.=' '.img_picto($langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage'),DOL_URL_ROOT.'/theme/common/helpdoc.png','',1).''; }*/ print $newval; } } else print $langs->trans("Error"); print '
'; print $langs->trans("FieldsTarget").''; $listfields=array(); $i=0; $sort_array_match_file_to_database=$array_match_file_to_database; ksort($sort_array_match_file_to_database); //var_dump($sort_array_match_file_to_database); foreach($sort_array_match_file_to_database as $code=>$label) { $i++; //var_dump($fieldssource); if ($code > sizeof($fieldssource)) continue; //print $code.'-'.$label; $alias=preg_replace('/(\..*)$/i','',$label); $listfields[$i]=$langs->trans("Field").' '.$code.'->'.$label; } print sizeof($listfields)?(join(', ',$listfields)):$langs->trans("Error"); print '
'; // Launch import $arrayoferrors=array(); $arrayofwarnings=array(); $maxnboferrors=empty($conf->global->IMPORT_MAX_NB_OF_ERRORS)?50:$conf->global->IMPORT_MAX_NB_OF_ERRORS; $maxnbofwarnings=empty($conf->global->IMPORT_MAX_NB_OF_WARNINGS)?50:$conf->global->IMPORT_MAX_NB_OF_WARNINGS; $nboferrors=0; $nbofwarnings=0; $importid=dol_print_date(dol_now('tzserver'),'%Y%m%d%H%M%S'); //var_dump($array_match_file_to_database); $db->begin(); // Open input file $nbok=0; $pathfile=$conf->import->dir_temp.'/'.$filetoimport; $result=$obj->import_open_file($pathfile,$langs); if ($result > 0) { $sourcelinenb=0; while ($sourcelinenb < $nboflines) { $sourcelinenb++; $arrayrecord=$obj->import_read_record(); if ($excludefirstline && $sourcelinenb == 1) continue; $result=$obj->import_insert($arrayrecord,$array_match_file_to_database,$objimport,sizeof($fieldssource),$importid); if (sizeof($obj->errors)) $arrayoferrors[$sourcelinenb]=$obj->errors; if (sizeof($obj->warnings)) $arrayofwarnings[$sourcelinenb]=$obj->warnings; if (! sizeof($obj->errors) && ! sizeof($obj->warnings)) $nbok++; } // Close file $obj->import_close_file(); } else { print $langs->trans("ErrorFailedToOpenFile",$pathfile); } if (sizeof($arrayoferrors) > 0) $db->rollback(); // We force rollback because this was errors. else $db->commit(); // We can commit if no errors. print ''; // Show result print '
'; print '
'; print $langs->trans("NbOfLinesImported",$nbok).'

'; print $langs->trans("FileWasImported",$importid).'
'; print $langs->trans("YouCanUseImportIdToFindRecord",$importid).'
'; print '
'; if ($mesg) print $mesg; } print '
'; $db->close(); llxFooter('$Date$ - $Revision$'); /* * Function to put the movable box of a source field */ function show_elem($fieldssource,$i,$pos,$key,$var,$nostyle='') { global $langs,$bc; print "\n\n\n"; print '
'."\n"; print ''."\n"; if ($pos && $pos > sizeof($fieldssource)) // No fields { print ''; print ''; print ''; print ''; } elseif ($key == 'none') // Empty line { print ''; print ''; print ''; print ''; } else // Print field of source file { print ''; //print ''; print ''; print ''; print ''; } print "
'; print img_picto(($pos>0?$langs->trans("MoveField",$pos):''),'uparrow','class="boxhandle" style="cursor:move;"'); print ''; print $langs->trans("NoFields"); print '
'; print ' '; print ''; print ' '; print '
'.img_file('','').''; // The image must have the class 'boxhandle' beause it's value used in DOM draggable objects to define the area used to catch the full object print img_picto($langs->trans("MoveField",$pos),'uparrow','class="boxhandle" style="cursor:move;"'); print ''; print $langs->trans("Field").' '.$pos; if (! empty($fieldssource[$pos]['example1'])) print ' ('.htmlentities($fieldssource[$pos]['example1']).')'; print '
\n"; print "
\n"; print "\n\n"; } /** * Return not used field number * * @param $listofkey * @return */ function getnewkey(&$fieldssource,&$listofkey) { $i=sizeof($fieldssource)+1; // Max number of key $maxkey=0; foreach($listofkey as $key=>$val) { $maxkey=max($maxkey,$key); } // Found next empty key while($i <= $maxkey) { if (empty($listofkey[$i])) break; else $i++; } $listofkey[$i]=1; return $i; } ?>