Dbf -> Db & import from table

1 Import a BIG DBF (aka excel openoffice) into a new table
    then you can see and search content easily

2 Create thirdparties or products from a table
This commit is contained in:
Norbert Penel 2020-01-14 15:31:41 +01:00 committed by GitHub
parent 3aa1166232
commit 43aa5ec658
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 1178 additions and 0 deletions

220
dev/initdata/import-dbf.php Normal file
View File

@ -0,0 +1,220 @@
#!/usr/bin/env php
<?php
/* Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2016 Juanjo Menent <jmenent@2byte.es>
*
* 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 3 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, see <https://www.gnu.org/licenses/>.
*
* WARNING, THIS WILL LOAD MASS DATA ON YOUR INSTANCE
*/
/**
* \file dev/initdata/import-product.php
* \brief Script example to create a table from a large DBF file (openoffice)
* To purge data, you can have a look at purge-data.php
*/
// Test si mode batch
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
$path = dirname(__FILE__) . '/';
if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Erreur: Vous utilisez l'interpreteur PHP pour le mode CGI. Pour executer mailing-send.php en ligne de commande, vous devez utiliser l'interpreteur PHP pour le mode CLI.\n";
exit;
}
// Recupere root dolibarr
$path = dirname($_SERVER["PHP_SELF"]);
require $path . "./../htdocs/master.inc.php";
require $path . "/includes/dbase.class.php";
// Global variables
$version = DOL_VERSION;
$confirmed = 1;
$error = 0;
/*
* Main
*/
@set_time_limit(0);
print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file . " launched with arg " . implode(',', $argv));
$filepath = $argv[1];
$filepatherr = $filepath . '.err';
$startchar = empty($argv[2]) ? 0 : (int) $argv[2];
$deleteTable = empty($argv[3]) ? 1 : 0;
$startlinenb = empty($argv[3]) ? 1 : (int) $argv[3];
$endlinenb = empty($argv[4]) ? 0 : (int) $argv[4];
if (empty($filepath)) {
print "Usage: php $script_file myfilepath.dbf [removeChatColumnName] [startlinenb] [endlinenb]\n";
print "Example: php $script_file myfilepath.dbf 0 2 1002\n";
print "\n";
exit(-1);
}
if (!file_exists($filepath)) {
print "Error: File " . $filepath . " not found.\n";
print "\n";
exit(-1);
}
$ret = $user->fetch('', 'admin');
if (!$ret > 0) {
print 'A user with login "admin" and all permissions must be created to use this script.' . "\n";
exit;
}
$user->getrights();
// Ask confirmation
if (!$confirmed) {
print "Hit Enter to continue or CTRL+C to stop...\n";
$input = trim(fgets(STDIN));
}
// Open input and output files
$fhandle = dbase_open($filepath, 0);
if (!$fhandle) {
print 'Error: Failed to open file ' . $filepath . "\n";
exit(1);
}
$fhandleerr = fopen($filepatherr, 'w');
if (!$fhandleerr) {
print 'Error: Failed to open file ' . $filepatherr . "\n";
exit(1);
}
$langs->setDefaultLang($defaultlang);
$record_numbers = dbase_numrecords($fhandle);
$table_name = substr(basename($filepath), 0, strpos(basename($filepath), '.'));
print 'Info: ' . $record_numbers . " lines in file \n";
$header = dbase_get_header_info($fhandle);
if ($deleteTable) {
$db->query("DROP TABLE IF EXISTS `$table_name`");
}
$sqlCreate = "CREATE TABLE IF NOT EXISTS `$table_name` ( `id` INT(11) NOT NULL AUTO_INCREMENT ";
$fieldArray = array("`id`");
foreach ($header as $value) {
$fieldName = substr(str_replace('_', '', $value['name']), $startchar);
$fieldArray[] = "`$fieldName`";
$sqlCreate .= ", `" . $fieldName . "` VARCHAR({$value['length']}) NULL DEFAULT NULL ";
}
$sqlCreate .= ", PRIMARY KEY (`id`)) ENGINE = InnoDB";
$resql = $db->query($sqlCreate);
if ($resql !== FALSE) {
print "Table $table_name created\n";
} else {
var_dump($db->errno());
print "Impossible : " . $sqlCreate . "\n";
die();
}
$i = 0;
$nboflines++;
$fields = implode(',', $fieldArray);
//var_dump($fieldArray);die();
$maxLength = 0;
for ($i = 1; $i <= $record_numbers; $i++) {
if ($startlinenb && $i < $startlinenb)
continue;
if ($endlinenb && $i > $endlinenb)
continue;
$row = dbase_get_record_with_names($fhandle, $i);
if ($row === FALSE || (isset($row["deleted"]) && $row["deleted"] == '1'))
continue;
$sqlInsert = "INSERT INTO `$table_name`($fields) VALUES (null,";
array_shift($row); // remove delete column
foreach ($row as $value) {
$sqlInsert .= "'" . $db->escape(utf8_encode($value)) . "', ";
}
replaceable_echo(implode("\t", $row));
$sqlInsert = rtrim($sqlInsert, ', ');
$sqlInsert .= ")";
$resql = $db->query($sqlInsert);
if ($resql === false) {
print "Impossible : " . $sqlInsert . "\n";
var_dump($row, $db->errno());
die();
}
// $fields = (object) $row;
// var_dump($fields);
continue;
}
die();
// commit or rollback
print "Nb of lines qualified: " . $nboflines . "\n";
print "Nb of errors: " . $error . "\n";
if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) {
print "Rollback any changes.\n";
$db->rollback();
} else {
print "Commit all changes.\n";
$db->commit();
}
$db->close();
fclose($fhandle);
fclose($fhandleerr);
exit($error);
function replaceable_echo($message, $force_clear_lines = NULL) {
static $last_lines = 0;
if (!is_null($force_clear_lines)) {
$last_lines = $force_clear_lines;
}
$term_width = exec('tput cols', $toss, $status);
if ($status) {
$term_width = 64; // Arbitrary fall-back term width.
}
$line_count = 0;
foreach (explode("\n", $message) as $line) {
$line_count += count(str_split($line, $term_width));
}
// Erasure MAGIC: Clear as many lines as the last output had.
for ($i = 0; $i < $last_lines; $i++) {
// Return to the beginning of the line
echo "\r";
// Erase to the end of the line
echo "\033[K";
// Move cursor Up a line
echo "\033[1A";
// Return to the beginning of the line
echo "\r";
// Erase to the end of the line
echo "\033[K";
// Return to the beginning of the line
echo "\r";
// Can be consolodated into
// echo "\r\033[K\033[1A\r\033[K\r";
}
$last_lines = $line_count;
echo $message . "\n";
}

View File

@ -0,0 +1,241 @@
#!/usr/bin/env php
<?php
/* Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2016 Juanjo Menent <jmenent@2byte.es>
*
* 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 3 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, see <https://www.gnu.org/licenses/>.
*
* WARNING, THIS WILL LOAD MASS DATA ON YOUR INSTANCE
*/
/**
* \file dev/initdata/import-product.php
* \brief Script example to insert products from a csv file.
* To purge data, you can have a look at purge-data.php
*/
// Test si mode batch
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
$path = dirname(__FILE__) . '/';
if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Erreur: Vous utilisez l'interpreteur PHP pour le mode CGI. Pour executer mailing-send.php en ligne de commande, vous devez utiliser l'interpreteur PHP pour le mode CLI.\n";
exit;
}
// Recupere root dolibarr
$path = preg_replace('/importdb-products.php/i', '', $_SERVER["PHP_SELF"]);
require $path . "../../htdocs/master.inc.php";
require $path . "includes/dbase.class.php";
include_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
include_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
//$delimiter = ',';
//$enclosure = '"';
//$linelength = 10000;
//$escape = '/';
// Global variables
$version = DOL_VERSION;
$confirmed = 1;
$error = 0;
$tvas = [
'1' => "20.00",
'2' => "5.50",
'3' => "0.00",
'4' => "20.60",
'5' => "19.60",
];
$tvasD = [
'1' => "20",
'2' => "5.5",
'3' => "0",
'4' => "20",
'5' => "20",
];
/*
* Main
*/
@set_time_limit(0);
print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file . " launched with arg " . implode(',', $argv));
$table = $argv[1];
if (empty($argv[1])) {
print "Error: Quelle table ?\n";
print "\n";
exit(-1);
}
$ret = $user->fetch('', 'admin');
if (!$ret > 0) {
print 'A user with login "admin" and all permissions must be created to use this script.' . "\n";
exit;
}
$sql = "SELECT * FROM `$table` WHERE 1";
$resql = $db->query($sql);
if ($resql)
while ($fields = $db->fetch_array($resql)) {
$errorrecord = 0;
if ($fields === FALSE)
continue;
$nboflines++;
$produit = new Product($db);
$produit->type = 0;
$produit->status = 1;
$produit->ref = trim($fields['REF']);
if ($produit->ref == '')
continue;
print "Process line nb " . $j . ", ref " . $produit->ref;
$produit->label = trim($fields['LIBELLE']);
if ($produit->label == '')
$produit->label = $produit->ref;
if (empty($produit->label))
continue;
//$produit->description = trim($fields[4] . "\n" . ($fields[5] ? $fields[5] . ' x ' . $fields[6] . ' x ' . $fields[7] : ''));
// $produit->volume = price2num($fields[8]);
// $produit->volume_unit = 0;
$produit->weight = price2num($fields['MASSE']);
$produit->weight_units = 0; // -3 = g
//$produit->customcode = $fields[10];
$produit->barcode = str_pad($fields['CODE'], 12, "0", STR_PAD_LEFT);
$produit->barcode_type = '2';
$produit->import_key = $fields['CODE'];
$produit->status = 1;
$produit->status_buy = 1;
$produit->finished = 1;
// $produit->multiprices[0] = price2num($fields['TARIF0']);
// $produit->multiprices[1] = price2num($fields['TARIF1']);
// $produit->multiprices[2] = price2num($fields['TARIF2']);
// $produit->multiprices[3] = price2num($fields['TARIF3']);
// $produit->multiprices[4] = price2num($fields['TARIF4']);
// $produit->multiprices[5] = price2num($fields['TARIF5']);
// $produit->multiprices[6] = price2num($fields['TARIF6']);
// $produit->multiprices[7] = price2num($fields['TARIF7']);
// $produit->multiprices[8] = price2num($fields['TARIF8']);
// $produit->multiprices[9] = price2num($fields['TARIF9']);
// $produit->price_min = null;
// $produit->price_min_ttc = null;
// $produit->price = price2num($fields[11]);
// $produit->price_ttc = price2num($fields[12]);
// $produit->price_base_type = 'TTC';
// $produit->tva_tx = price2num($fields[13]);
$produit->tva_tx = (int) ($tvas[$fields['CODTVA']]);
$produit->tva_npr = 0;
// $produit->cost_price = price2num($fields[16]);
//compta
$produit->accountancy_code_buy = trim($fields['COMACH']);
$produit->accountancy_code_sell = trim($fields['COMVEN']);
// $produit->accountancy_code_sell_intra=trim($fields['COMVEN']);
// $produit->accountancy_code_sell_export=trim($fields['COMVEN']);
// Extrafields
// $produit->array_options['options_ecotaxdeee'] = price2num($fields[17]);
$produit->seuil_stock_alerte = $fields['STALERTE'];
$ret = $produit->create($user, 0);
if ($ret < 0) {
print " - Error in create result code = " . $ret . " - " . $produit->errorsToString();
$errorrecord++;
} else {
print " - Creation OK with ref " . $produit->ref . " - id = " . $ret;
}
dol_syslog("Add prices");
// If we use price level, insert price for each level
if (!$errorrecord && 1) {
//$ret1 = $produit->updatePrice($produit->price_ttc, $produit->price_base_type, $user, $produit->tva_tx, $produit->price_min, 1, $produit->tva_npr, 0, 0, array());
$ret1 = false;
for ($i = 0; $i < 10; $i++) {
if ($fields['TARIF' . ($i)] == 0)
continue;
$ret1 = $ret1 || $produit->updatePrice(price2num($fields['TARIF' . ($i)]), 'HT', $user, $produit->tva_tx, $produit->price_min, $i + 1, $produit->tva_npr, 0, 0, array()) < 0;
}
if ($ret1) {
print " - Error in updatePrice result " . $produit->errorsToString();
$errorrecord++;
} else {
print " - updatePrice OK";
}
}
// dol_syslog("Add multilangs");
// Add alternative languages
// if (!$errorrecord && 1) {
// $produit->multilangs['fr_FR'] = array('label' => $produit->label, 'description' => $produit->description, 'note' => $produit->note_private);
// $produit->multilangs['en_US'] = array('label' => $fields[3], 'description' => $produit->description, 'note' => $produit->note_private);
//
// $ret = $produit->setMultiLangs($user);
// if ($ret < 0) {
// print " - Error in setMultiLangs result code = " . $ret . " - " . $produit->errorsToString();
// $errorrecord++;
// } else {
// print " - setMultiLangs OK";
// }
// }
dol_syslog("Add stocks");
// stocks
if (!$errorrecord && $fields['STOCK'] != 0) {
$rets = $produit->correct_stock($user, 1, $fields['STOCK'], 0, 'Stock importé');
if ($rets < 0) {
print " - Error in correct_stock result " . $produit->errorsToString();
$errorrecord++;
} else {
print " - correct_stock OK";
}
}
//update date créa
if (!$errorrecord) {
$date = substr($fields['DATCREA'], 0, 4) . '-' . substr($fields['DATCREA'], 4, 2) . '-' . substr($fields['DATCREA'], 6, 2);
$retd = $db->query("UPDATE `llx_product` SET `datec` = '$date 00:00:00' WHERE `llx_product`.`rowid` = $produit->id");
if ($retd < 1) {
print " - Error in update date créa result " . $produit->errorsToString();
$errorrecord++;
} else {
print " - update date créa OK";
}
}
print "\n";
if ($errorrecord) {
print( 'Error on record nb ' . $i . " - " . $produit->errorsToString() . "\n");
var_dump($db);
die();
$error++; // $errorrecord will be reset
}
$j++;
} else
die("error : $sql");
// commit or rollback
print "Nb of lines qualified: " . $nboflines . "\n";
print "Nb of errors: " . $error . "\n";
$db->close();
exit($error);

View File

@ -0,0 +1,355 @@
#!/usr/bin/env php
<?php
/* Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2016 Juanjo Menent <jmenent@2byte.es>
*
* 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 3 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, see <https://www.gnu.org/licenses/>.
*
* WARNING, THIS WILL LOAD MASS DATA ON YOUR INSTANCE
*/
/**
* \file dev/initdata/import-product.php
* \brief Script example to insert products from a csv file.
* To purge data, you can have a look at purge-data.php
*/
// Test si mode batch
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
$path = dirname(__FILE__) . '/';
if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Erreur: Vous utilisez l'interpreteur PHP pour le mode CGI. Pour executer mailing-send.php en ligne de commande, vous devez utiliser l'interpreteur PHP pour le mode CLI.\n";
exit;
}
// Recupere root dolibarr
$path = preg_replace('/importdb-thirdparties.php/i', '', $_SERVER["PHP_SELF"]);
require $path . "../../htdocs/master.inc.php";
require $path . "includes/dbase.class.php";
include_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
include_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
//$delimiter = ',';
//$enclosure = '"';
//$linelength = 10000;
//$escape = '/';
// Global variables
$version = DOL_VERSION;
$confirmed = 1;
$error = 0;
$civilPrivate = array("MLLE",
"MM",
"MM/MADAME",
"MME",
"MME.",
"MME²",
"MMONSIEUR",
"MMR",
"MOBNSIEUR",
"MOMSIEUR",
"MON SIEUR",
"MONDIAL",
"MONIEUR",
"MONJSIEUR",
"MONNSIEUR",
"MONRIEUR",
"MONS",
"MONSIEÕR",
"MONSIER",
"MONSIERU",
"MONSIEU",
"monsieue",
"MONSIEUR",
"Monsieur     \"",
"MONSIEUR    \"",
"MONSIEUR   E",
"MONSIEUR  DENIS",
"MONSIEUR ET MME",
"MONSIEUR!",
"MONSIEUR.",
"MONSIEUR.MADAME",
"MONSIEUR3",
"MONSIEURN",
"MONSIEURT",
"MONSIEUR£",
"MONSIEYR",
"Monsigur",
"MONSIIEUR",
"MONSIUER",
"MONSIZEUR",
"MOPNSIEUR",
"MOSIEUR",
"MR",
"Mr  Mme",
"Mr - MME",
"MR BLANC",
"MR ET MME",
"mr mm",
"MR OU MME",
"Mr.",
"MR/MME",
"MRME",
"MRR",
"Mrs",
"Mademoiselle",
"MADAOME",
"madamme",
"MADAME",
"M0NSIEUR",
"M.et Madame",
"M. ET MR",
"M.",
"M%",
"M MME",
"M ET MME",
"M",
"M CROCE",
"M DIEVART",
);
/*
* Main
*/
@set_time_limit(0);
print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file . " launched with arg " . implode(',', $argv));
$table = $argv[1];
if (empty($argv[1])) {
print "Error: Quelle table ?\n";
print "\n";
exit(-1);
}
$ret = $user->fetch('', 'admin');
if (!$ret > 0) {
print 'A user with login "admin" and all permissions must be created to use this script.' . "\n";
exit;
}
$sql = "SELECT * FROM `$table` WHERE 1 "; //ORDER BY REMISE DESC,`LCIVIL` DESC";
$resql = $db->query($sql);
//$db->begin();
if ($resql)
while ($fields = $db->fetch_array($resql)) {
$i++;
$errorrecord = 0;
if ($startlinenb && $i < $startlinenb)
continue;
if ($endlinenb && $i > $endlinenb)
continue;
$nboflines++;
$object = new Societe($db);
$object->import_key = $fields['CODE'];
$object->state = 1;
$object->client = 3;
$object->fournisseur = 0;
$object->name = $fields['FCIVIL'] . ' ' . $fields['FNOM'];
//$object->name_alias = $fields[0] != $fields[13] ? trim($fields[0]) : '';
$date = $fields['DATCREA'] ? $fields['DATCREA'] : ($fields['DATMOD'] ? $fields['DATMOD'] : '20200101');
$object->code_client = 'CU' . substr($date, 2, 2) . substr($date, 4, 2) . '-' . str_pad(substr($fields['CODE'], 0, 5), 5, "0", STR_PAD_LEFT);
$object->address = trim($fields['FADR1']);
if ($fields['FADR2'])
$object->address .= "\n" . trim($fields['FADR2']);
if ($fields['FADR3'])
$object->address .= "\n" . trim($fields['FADR3']);
$object->zip = trim($fields['FPOSTE']);
$object->town = trim($fields['FVILLE']);
if ($fields['FPAYS'])
$object->country_id = dol_getIdFromCode($db, trim(ucwords(strtolower($fields['FPAYS']))), 'c_country', 'label', 'rowid');
else
$object->country_id = 1;
$object->phone = trim($fields['FTEL']) ? trim($fields['FTEL']) : trim($fields['FCONTACT']);
$object->phone = substr($object->phone, 0, 20);
$object->fax = trim($fields['FFAX']) ? trim($fields['FFAX']) : trim($fields['FCONTACT']);
$object->fax = substr($object->fax, 0, 20);
$object->email = trim($fields['FMAIL']);
// $object->idprof2 = trim($fields[29]);
$object->tva_intra = str_replace(['.', ' '], '', $fields['TVAINTRA']);
$object->tva_intra = substr($object->tva_intra, 0, 20);
$object->default_lang = 'fr_FR';
$object->cond_reglement_id = dol_getIdFromCode($db, 'PT_ORDER', 'c_payment_term', 'code', 'rowid', 1);
$object->multicurrency_code = 'EUR';
if ($fields['REMISE'] != '0.00') {
$object->remise_percent = abs($fields['REMISE']);
}
// $object->code_client = $fields[9];
// $object->code_fournisseur = $fields[10];
if ($fields['FCIVIL']) {
$labeltype = in_array($fields['FCIVIL'], $civilPrivate) ? 'TE_PRIVATE' : 'TE_SMALL';
$object->typent_id = dol_getIdFromCode($db, $labeltype, 'c_typent', 'code');
}
// Set price level
$object->price_level = $fields['TARIF'] + 1;
// if ($labeltype == 'Revendeur')
// $object->price_level = 2;
print "Process line nb " . $i . ", code " . $fields['CODE'] . ", name " . $object->name;
// Extrafields
$object->array_options['options_banque'] = $fields['BANQUE'];
$object->array_options['options_banque2'] = $fields['BANQUE2'];
$object->array_options['options_banquevalid'] = $fields['VALID'];
if (!$errorrecord) {
$ret = $object->create($user);
if ($ret < 0) {
print " - Error in create result code = " . $ret . " - " . $object->errorsToString();
$errorrecord++;
var_dump($object->code_client, $db);
die();
} else {
print " - Creation OK with name " . $object->name . " - id = " . $ret;
}
}
if (!$errorrecord) {
dol_syslog("Set price level");
$object->set_price_level($object->price_level, $user);
}
if (!$errorrecord && @$object->remise_percent) {
dol_syslog("Set remise client");
$object->set_remise_client($object->remise_percent, 'Importé', $user);
}
dol_syslog("Add contact");
// Insert an invoice contact if there is an invoice email != standard email
if (!$errorrecord && ($fields['LCIVIL'] || $fields['LNOM'])) {
$madame = array("MADAME",
"MADEMOISELLE",
"MELLE",
"MLLE",
"MM",
"Mme",
"MNE",
);
$monsieur = array("M",
"M ET MME",
"M MME",
"M.",
"M. MME",
"M. OU Mme",
"M.ou Madame",
"MONSEUR",
"MONSIER",
"MONSIEU",
"MONSIEUR",
"monsieur:mme",
"MONSIEUR¨",
"MONSIEZUR",
"MONSIUER",
"MONSKIEUR",
"MR",
);
$ret1 = $ret2 = 0;
$contact = new Contact($db);
if (in_array($fields['LCIVIL'], $madame)) {
// une dame
$contact->civility_id = 'MME';
$contact->lastname = $fields['LNOM'];
} elseif (in_array($fields['LCIVIL'], $monsieur)) {
// un monsieur
$contact->civility_id = 'MR';
$contact->lastname = $fields['LNOM'];
} elseif (in_array($fields['LCIVIL'], ['DOCTEUR'])) {
// un monsieur
$contact->civility_id = 'DR';
$contact->lastname = $fields['LNOM'];
} else {
// un a rattraper
$contact->lastname = $fields['LCIVIL'] . " " . $fields['LNOM'];
}
$contact->address = trim($fields['LADR1']);
if ($fields['LADR2'])
$contact->address .= "\n" . trim($fields['LADR2']);
if ($fields['LADR3'])
$contact->address .= "\n" . trim($fields['LADR3']);
$contact->zip = trim($fields['LPOSTE']);
$contact->town = trim($fields['LVILLE']);
if ($fields['FPAYS'])
$contact->country_id = dol_getIdFromCode($db, trim(ucwords(strtolower($fields['LPAYS']))), 'c_country', 'label', 'rowid');
else
$contact->country_id = 1;
$contact->email = $fields['LMAIL'];
$contact->phone = trim($fields['LTEL']) ? trim($fields['LTEL']) : trim($fields['LCONTACT']);
$contact->fax = trim($fields['LFAX']) ? trim($fields['LFAX']) : trim($fields['LCONTACT']);
$contact->socid = $object->id;
$ret1 = $contact->create($user);
if ($ret1 > 0) {
//$ret2=$contact->add_contact($object->id, 'BILLING');
}
if ($ret1 < 0 || $ret2 < 0) {
print " - Error in create contact result code = " . $ret1 . " " . $ret2 . " - " . $contact->errorsToString();
$errorrecord++;
} else {
print " - create contact OK";
}
}
//update date créa
if (!$errorrecord) {
$datec = substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-' . substr($date, 6, 2);
$retd = $db->query("UPDATE `llx_societe` SET `datec` = '$datec 00:00:00' WHERE `rowid` = $object->id");
if ($retd < 1) {
print " - Error in update date créa result " . $object->errorsToString();
$errorrecord++;
} else {
print " - update date créa OK";
}
}
print "\n";
if ($errorrecord) {
print( 'Error on record nb ' . $i . " - " . $object->errorsToString() . "\n");
var_dump($db, $object, $contact);
// $db->rollback();
die();
$error++; // $errorrecord will be reset
}
$j++;
} else
die("error : $sql");
$db->commit();
// commit or rollback
print "Nb of lines qualified: " . $nboflines . "\n";
print "Nb of errors: " . $error . "\n";
$db->close();
exit($error);

View File

@ -0,0 +1,362 @@
<?php
// source : https://github.com/donfbecker/php-dbase
define('DBASE_RDONLY', 0);
define('DBASE_WRONLY', 1);
define('DBASE_RDWR', 2);
define('DBASE_TYPE_DBASE', 0);
define('DBASE_TYPE_FOXPRO', 1);
class DBase {
private $fd;
private $headerLength = 0;
private $fields = array();
private $fieldCount = 0;
private $recordLength = 0;
private $recordCount = 0;
//resource dbase_open ( string $filename , int $mode )
public static function open($filename, $mode) {
if (!file_exists($filename))
return false;
$modes = array('r', 'w', 'r+');
$mode = $modes[$mode];
$fd = fopen($filename, $mode);
if (!$fd)
return false;
return new DBase($fd);
}
//resource dbase_create ( string $filename , array $fields [, int $type = DBASE_TYPE_DBASE ] )
public static function create($filename, $fields, $type = DBASE_TYPE_DBASE) {
if (file_exists($filename))
return false;
$fd = fopen($filename, 'c+');
if (!$fd)
return false;
// Byte 0 (1 byte): Valid dBASE for DOS file; bits 0-2 indicate version number, bit 3
// indicates the presence of a dBASE for DOS memo file, bits 4-6 indicate the
// presence of a SQL table, bit 7 indicates the presence of any memo file
// (either dBASE m PLUS or dBASE for DOS)
self::putChar8($fd, 5);
// Byte 1-3 (3 bytes): Date of last update; formatted as YYMMDD
self::putChar8($fd, date('Y') - 1900);
self::putChar8($fd, date('m'));
self::putChar8($fd, date('d'));
// Byte 4-7 (32-bit number): Number of records in the database file. Currently 0
self::putInt32($fd, 0);
// Byte 8-9 (16-bit number): Number of bytes in the header.
self::putInt16($fd, 32 + (32 * count($fields)) + 1);
// Byte 10-11 (16-bit number): Number of bytes in record.
// Make sure the include the byte for deleted flag
$len = 1;
foreach ($fields as &$field)
$len += self::length($field);
self::putInt16($fd, $len);
// Byte 12-13 (2 bytes): Reserved, 0 filled.
self::putInt16($fd, 0);
// Byte 14 (1 byte): Flag indicating incomplete transaction
// The ISMARKEDO function checks this flag. BEGIN TRANSACTION sets it to 1, END TRANSACTION and ROLLBACK reset it to 0.
self::putChar8($fd, 0);
// Byte 15 (1 byte): Encryption flag. If this flag is set to 1, the message Database encrypted appears. Changing this flag to 0 removes the message, but does not decrypt the file.
self::putChar8($fd, 0);
// Byte 16-27 (12 bytes): Reserved for dBASE for DOS in a multi-user environment
self::putInt32($fd, 0);
self::putInt32($fd, 0);
self::putInt32($fd, 0);
// Byte 28 (1 byte): Production .mdx file flag; 0x01 if there is a production .mdx file, 0x00 if not
self::putChar8($fd, 0);
// Byte 29 (1 byte): Language driver ID
// (no clue what this is)
self::putChar8($fd, 0);
// Byte 30-31 (2 bytes): Reserved, 0 filled.
self::putInt16($fd, 0);
// Byte 32 - n (32 bytes each): Field descriptor array
foreach ($fields as &$field) {
self::putString($fd, $field[0], 11); // Byte 0 - 10 (11 bytes): Field name in ASCII (zero-filled)
self::putString($fd, $field[1], 1); // Byte 11 (1 byte): Field type in ASCII (C, D, F, L, M, or N)
self::putInt32($fd, 0); // Byte 12 - 15 (4 bytes): Reserved
self::putChar8($fd, self::length($field)); // Byte 16 (1 byte): Field length in binary. The maximum length of a field is 254 (0xFE).
self::putChar8($fd, $field[3]); // Byte 17 (1 byte): Field decimal count in binary
self::putInt16($fd, 0); // Byte 18 - 19 (2 bytes): Work area ID
self::putChar8($fd, 0); // Byte 20 (1 byte): Example (??)
self::putInt32($fd, 0); // Byte 21 - 30 (10 bytes): Reserved
self::putInt32($fd, 0);
self::putInt16($fd, 0);
self::putChar8($fd, 0); // Byte 31 (1 byte): Production MDX field flag; 1 if field has an index tag in the production MDX file, 0 if not
}
// Byte n + 1 (1 byte): 0x0D as the field descriptor array terminator
self::putChar8($fd, 0x0D);
return new DBase($fd);
}
// Create DBase instance
private function __construct($fd) {
$this->fd = $fd;
// Byte 4-7 (32-bit number): Number of records in the database file. Currently 0
fseek($this->fd, 4, SEEK_SET);
$this->recordCount = self::getInt32($fd);
// Byte 8-9 (16-bit number): Number of bytes in the header.
fseek($this->fd, 8, SEEK_SET);
$this->headerLength = self::getInt16($fd);
// Number of fields is (headerLength - 33) / 32)
$this->fieldCount = ($this->headerLength - 33) / 32;
// Byte 10-11 (16-bit number): Number of bytes in record.
fseek($this->fd, 10, SEEK_SET);
$this->recordLength = self::getInt16($fd);
// Byte 32 - n (32 bytes each): Field descriptor array
fseek($fd, 32, SEEK_SET);
for ($i = 0; $i < $this->fieldCount; $i++) {
$data = fread($this->fd, 32);
$field = array_map('trim', unpack('a11name/a1type/c4/c1length/c1precision/s1workid/c1example/c10/c1production', $data));
$this->fields[] = $field;
}
}
//bool dbase_close ( resource $dbase_identifier )
public function close() {
fclose($this->fd);
}
//array dbase_get_header_info ( resource $dbase_identifier )
public function get_header_info() {
return $this->fields;
}
//int dbase_numfields ( resource $dbase_identifier )
public function numfields() {
return $this->fieldCount;
}
//int dbase_numrecords ( resource $dbase_identifier )
public function numrecords() {
return $this->recordCount;
}
//bool dbase_add_record ( resource $dbase_identifier , array $record )
public function add_record($record) {
if (count($record) != $this->fieldCount)
return false;
// Seek to end of file, minus the end of file marker
fseek($this->fd, 0, SEEK_END);
// Put the deleted flag
self::putChar8($this->fd, 0x20);
// Put the record
if (!$this->putRecord($record))
return false;
// Update the record count
fseek($this->fd, 4);
self::putInt32($this->fd, ++$this->recordCount);
return true;
}
//bool dbase_replace_record ( resource $dbase_identifier , array $record , int $record_number )
public function replace_record($record, $record_number) {
if (count($record) != $this->fieldCount)
return false;
if ($record_number < 1 || $record_number > $this->recordCount)
return false;
// Skip to the record location, plus the 1 byte for the deleted flag
fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1)) + 1);
return $this->putRecord($record);
}
//bool dbase_delete_record ( resource $dbase_identifier , int $record_number )
public function delete_record($record_number) {
if ($record_number < 1 || $record_number > $this->recordCount)
return false;
fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1)));
self::putChar8($this->fd, 0x2A);
return true;
}
//array dbase_get_record ( resource $dbase_identifier , int $record_number )
public function get_record($record_number) {
if ($record_number < 1 || $record_number > $this->recordCount)
return false;
fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1)));
$record = array(
'deleted' => self::getChar8($this->fd) == 0x2A ? 1 : 0
);
foreach ($this->fields as $i => &$field) {
$value = trim(fread($this->fd, $field['length']));
if ($field['type'] == 'L') {
$value = strtolower($value);
if ($value == 't' || $value == 'y')
$value = true;
else if ($value == 'f' || $value == 'n')
$value = false;
else
$value = null;
}
$record[$i] = $value;
}
return $record;
}
//array dbase_get_record_with_names ( resource $dbase_identifier , int $record_number )
public function get_record_with_names($record_number) {
if ($record_number < 1 || $record_number > $this->recordCount)
return false;
$record = $this->get_record($record_number);
foreach ($this->fields as $i => &$field) {
$record[$field['name']] = $record[$i];
unset($record[$i]);
}
return $record;
}
//bool dbase_pack ( resource $dbase_identifier )
public function pack() {
$in_offset = $out_offset = $this->headerLength;
$new_count = 0;
$rec_count = $this->recordCount;
while ($rec_count > 0) {
fseek($this->fd, $in_offset, SEEK_SET);
$record = fread($this->fd, $this->recordLength);
$deleted = substr($record, 0, 1);
if ($deleted != '*') {
fseek($this->fd, $out_offset, SEEK_SET);
fwrite($this->fd, $record);
$out_offset += $this->recordLength;
$new_count++;
}
$in_offset += $this->recordLength;
$rec_count--;
}
ftruncate($this->fd, $out_offset);
// Update the record count
fseek($this->fd, 4);
self::putInt32($this->fd, $new_count);
}
/*
* A few utilitiy functions
*/
private static function length($field) {
switch ($field[1]) {
case 'D': // Date: Numbers and a character to separate month, day, and year (stored internally as 8 digits in YYYYMMDD format)
return 8;
case 'T': // DateTime (YYYYMMDDhhmmss.uuu) (FoxPro)
return 18;
case 'M': // Memo (ignored): All ASCII characters (stored internally as 10 digits representing a .dbt block number, right justified, padded with whitespaces)
case 'N': // Number: -.0123456789 (right justified, padded with whitespaces)
case 'F': // Float: -.0123456789 (right justified, padded with whitespaces)
case 'C': // String: All ASCII characters (padded with whitespaces up to the field's length)
return $field[2];
case 'L': // Boolean: YyNnTtFf? (? when not initialized)
return 1;
}
return 0;
}
/*
* Functions for reading and writing bytes
*/
private static function getChar8($fd) {
return ord(fread($fd, 1));
}
private static function putChar8($fd, $value) {
return fwrite($fd, chr($value));
}
private static function getInt16($fd, $n = 1) {
$data = fread($fd, 2 * $n);
$i = unpack("S$n", $data);
if ($n == 1)
return (int) $i[1];
else
return array_merge($i);
}
private static function putInt16($fd, $value) {
return fwrite($fd, pack('S', $value));
}
private static function getInt32($fd, $n = 1) {
$data = fread($fd, 4 * $n);
$i = unpack("L$n", $data);
if ($n == 1)
return (int) $i[1];
else
return array_merge($i);
}
private static function putInt32($fd, $value) {
return fwrite($fd, pack('L', $value));
}
private static function putString($fd, $value, $length = 254) {
$ret = fwrite($fd, pack('A' . $length, $value));
}
private function putRecord($record) {
foreach ($this->fields as $i => &$field) {
$value = $record[$i];
// Number types are right aligned with spaces
if ($field['type'] == 'N' || $field['type'] == 'F' && strlen($value) < $field['length']) {
$value = str_repeat(' ', $field['length'] - strlen($value)) . $value;
}
self::putString($this->fd, $value, $field['length']);
}
return true;
}
}
if (!function_exists('dbase_open')) {
function dbase_open($filename, $mode) {
return DBase::open($filename, $mode);
}
function dbase_create($filename, $fields, $type = DBASE_TYPE_DBASE) {
return DBase::create($filename, $fields, $type);
}
function dbase_close($dbase_identifier) {
return $dbase_identifier->close();
}
function dbase_get_header_info($dbase_identifier) {
return $dbase_identifier->get_header_info();
}
function dbase_numfields($dbase_identifier) {
$dbase_identifier->numfields();
}
function dbase_numrecords($dbase_identifier) {
return $dbase_identifier->numrecords();
}
function dbase_add_record($dbase_identifier, $record) {
return $dbase_identifier->add_record($record);
}
function dbase_delete_record($dbase_identifier, $record_number) {
return $dbase_identifier->delete_record($record_number);
}
function dbase_replace_record($dbase_identifier, $record, $record_number) {
return $dbase_identifier->replace_record($record, $record_number);
}
function dbase_get_record($dbase_identifier, $record_number) {
return $dbase_identifier->get_record($record_number);
}
function dbase_get_record_with_names($dbase_identifier, $record_number) {
return $dbase_identifier->get_record_with_names($record_number);
}
function dbase_pack($dbase_identifier) {
return $dbase_identifier->pack();
}
}