Browse Source

add new rule

Frédéric FRANCE 4 năm trước cách đây
mục cha
commit
6f9c639f08

+ 90 - 83
build/generate_filelist_xml.php

@@ -22,7 +22,9 @@
  * 		\brief      This script create a xml checksum file
  */
 
-if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1');	// Do not create database handler $db
+if (! defined('NOREQUIREDB')) {
+	define('NOREQUIREDB', '1');	// Do not create database handler $db
+}
 
 $sapi_type = php_sapi_name();
 $script_file = basename(__FILE__);
@@ -30,8 +32,8 @@ $path=dirname(__FILE__).'/';
 
 // Test if batch mode
 if (substr($sapi_type, 0, 3) == 'cgi') {
-    echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
-    exit;
+	echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
+	exit;
 }
 
 require_once $path."../htdocs/master.inc.php";
@@ -46,30 +48,32 @@ $includecustom=0;
 $includeconstants=array();
 
 if (empty($argv[1])) {
-    print "Usage:   ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n";
-    print "Example: ".$script_file." release=6.0.0 includecustom=1 includeconstant=FR:INVOICE_CAN_ALWAYS_BE_REMOVED:0 includeconstant=all:MAILING_NO_USING_PHPMAIL:1\n";
-    exit -1;
+	print "Usage:   ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n";
+	print "Example: ".$script_file." release=6.0.0 includecustom=1 includeconstant=FR:INVOICE_CAN_ALWAYS_BE_REMOVED:0 includeconstant=all:MAILING_NO_USING_PHPMAIL:1\n";
+	exit -1;
 }
 parse_str($argv[1]);
 
 $i=0;
 while ($i < $argc) {
-    if (! empty($argv[$i])) parse_str($argv[$i]);
-    if (preg_match('/includeconstant=/', $argv[$i])) {
-        $tmp=explode(':', $includeconstant, 3);
-        if (count($tmp) != 3) {
-            print "Error: Bad parameter includeconstant ".$includeconstant."\n";
-            exit -1;
-        }
-        $includeconstants[$tmp[0]][$tmp[1]] = $tmp[2];
-    }
-    $i++;
+	if (! empty($argv[$i])) {
+		parse_str($argv[$i]);
+	}
+	if (preg_match('/includeconstant=/', $argv[$i])) {
+		$tmp=explode(':', $includeconstant, 3);
+		if (count($tmp) != 3) {
+			print "Error: Bad parameter includeconstant ".$includeconstant."\n";
+			exit -1;
+		}
+		$includeconstants[$tmp[0]][$tmp[1]] = $tmp[2];
+	}
+	$i++;
 }
 
 if (empty($release)) {
-    print "Error: Missing release paramater\n";
-    print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n";
-    exit -1;
+	print "Error: Missing release paramater\n";
+	print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n";
+	exit -1;
 }
 
 $savrelease = $release;
@@ -77,32 +81,34 @@ $savrelease = $release;
 // If release is auto, we take current version
 $tmpver=explode('-', $release, 2);
 if ($tmpver[0] == 'auto' || $tmpver[0] == 'autostable') {
-    $release=DOL_VERSION;
-    if ($tmpver[1] && $tmpver[0] == 'auto') $release.='-'.$tmpver[1];
+	$release=DOL_VERSION;
+	if ($tmpver[1] && $tmpver[0] == 'auto') {
+		$release.='-'.$tmpver[1];
+	}
 }
 
 if (empty($includecustom)) {
-    $tmpverbis=explode('-', $release, 2);
-    if (empty($tmpverbis[1]) || $tmpver[0] == 'autostable') {
-        if (DOL_VERSION != $tmpverbis[0] && $savrelease != 'auto') {
-            print 'Error: When parameter "includecustom" is not set and there is no suffix in release parameter, version declared into filefunc.in.php ('.DOL_VERSION.') must be exact same value than "release" parameter ('.$tmpverbis[0].')'."\n";
-            print "Usage:   ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n";
-            exit -1;
-        }
-    } else {
-        $tmpverter=explode('-', DOL_VERSION, 2);
-        if ($tmpverter[0] != $tmpverbis[0]) {
-            print 'Error: When parameter "includecustom" is not set, version declared into filefunc.in.php ('.DOL_VERSION.') must have value without prefix ('.$tmpverter[0].') that is exact same value than "release" parameter ('.$tmpverbis[0].')'."\n";
-            print "Usage:   ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n";
-            exit -1;
-        }
-    }
+	$tmpverbis=explode('-', $release, 2);
+	if (empty($tmpverbis[1]) || $tmpver[0] == 'autostable') {
+		if (DOL_VERSION != $tmpverbis[0] && $savrelease != 'auto') {
+			print 'Error: When parameter "includecustom" is not set and there is no suffix in release parameter, version declared into filefunc.in.php ('.DOL_VERSION.') must be exact same value than "release" parameter ('.$tmpverbis[0].')'."\n";
+			print "Usage:   ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n";
+			exit -1;
+		}
+	} else {
+		$tmpverter=explode('-', DOL_VERSION, 2);
+		if ($tmpverter[0] != $tmpverbis[0]) {
+			print 'Error: When parameter "includecustom" is not set, version declared into filefunc.in.php ('.DOL_VERSION.') must have value without prefix ('.$tmpverter[0].') that is exact same value than "release" parameter ('.$tmpverbis[0].')'."\n";
+			print "Usage:   ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n";
+			exit -1;
+		}
+	}
 } else {
-    if (! preg_match('/'.preg_quote(DOL_VERSION, '/').'-/', $release)) {
-        print 'Error: When parameter "includecustom" is set, version declared into filefunc.inc.php ('.DOL_VERSION.') must be used with a suffix into "release" parameter (ex: '.DOL_VERSION.'-mydistrib).'."\n";
-        print "Usage:   ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n";
-        exit -1;
-    }
+	if (! preg_match('/'.preg_quote(DOL_VERSION, '/').'-/', $release)) {
+		print 'Error: When parameter "includecustom" is set, version declared into filefunc.inc.php ('.DOL_VERSION.') must be used with a suffix into "release" parameter (ex: '.DOL_VERSION.'-mydistrib).'."\n";
+		print "Usage:   ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n";
+		exit -1;
+	}
 }
 
 print "Working on files into          : ".DOL_DOCUMENT_ROOT."\n";
@@ -110,9 +116,9 @@ print "Release                        : ".$release."\n";
 print "Include custom in signature    : ".$includecustom."\n";
 print "Include constants in signature : ";
 foreach ($includeconstants as $countrycode => $tmp) {
-    foreach ($tmp as $constname => $constvalue) {
-        print $constname.'='.$constvalue." ";
-    }
+	foreach ($tmp as $constname => $constvalue) {
+		print $constname.'='.$constvalue." ";
+	}
 }
 print "\n";
 
@@ -134,13 +140,13 @@ fputs($fp, '<?xml version="1.0" encoding="UTF-8" ?>'."\n");
 fputs($fp, '<checksum_list version="'.$release.'" date="'.dol_print_date(dol_now(), 'dayhourrfc').'" generator="'.$script_file.'">'."\n");
 
 foreach ($includeconstants as $countrycode => $tmp) {
-    fputs($fp, '<dolibarr_constants country="'.$countrycode.'">'."\n");
-    foreach ($tmp as $constname => $constvalue) {
-        $valueforchecksum=(empty($constvalue)?'0':$constvalue);
-        $checksumconcat[]=$valueforchecksum;
-        fputs($fp, '    <constant name="'.$constname.'">'.$valueforchecksum.'</constant>'."\n");
-    }
-    fputs($fp, '</dolibarr_constants>'."\n");
+	fputs($fp, '<dolibarr_constants country="'.$countrycode.'">'."\n");
+	foreach ($tmp as $constname => $constvalue) {
+		$valueforchecksum=(empty($constvalue)?'0':$constvalue);
+		$checksumconcat[]=$valueforchecksum;
+		fputs($fp, '    <constant name="'.$constname.'">'.$valueforchecksum.'</constant>'."\n");
+	}
+	fputs($fp, '</dolibarr_constants>'."\n");
 }
 
 fputs($fp, '<dolibarr_htdocs_dir includecustom="'.$includecustom.'">'."\n");
@@ -157,22 +163,22 @@ $files = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, $regextoinclude, $regextoex
 $dir='';
 $needtoclose=0;
 foreach ($files as $filetmp) {
-    $file = $filetmp['fullname'];
-    //$newdir = str_replace(dirname(__FILE__).'/../htdocs', '', dirname($file));
-    $newdir = str_replace(DOL_DOCUMENT_ROOT, '', dirname($file));
-    if ($newdir!=$dir) {
-    	if ($needtoclose) {
-            fputs($fp, '  </dir>'."\n");
-    	}
-        fputs($fp, '  <dir name="'.$newdir.'">'."\n");
-        $dir = $newdir;
-        $needtoclose=1;
-    }
-    if (filetype($file)=="file") {
-        $md5=md5_file($file);
-        $checksumconcat[]=$md5;
-        fputs($fp, '    <md5file name="'.basename($file).'" size="'.filesize($file).'">'.$md5.'</md5file>'."\n");
-    }
+	$file = $filetmp['fullname'];
+	//$newdir = str_replace(dirname(__FILE__).'/../htdocs', '', dirname($file));
+	$newdir = str_replace(DOL_DOCUMENT_ROOT, '', dirname($file));
+	if ($newdir!=$dir) {
+		if ($needtoclose) {
+			fputs($fp, '  </dir>'."\n");
+		}
+		fputs($fp, '  <dir name="'.$newdir.'">'."\n");
+		$dir = $newdir;
+		$needtoclose=1;
+	}
+	if (filetype($file)=="file") {
+		$md5=md5_file($file);
+		$checksumconcat[]=$md5;
+		fputs($fp, '    <md5file name="'.basename($file).'" size="'.filesize($file).'">'.$md5.'</md5file>'."\n");
+	}
 }
 fputs($fp, '  </dir>'."\n");
 fputs($fp, '</dolibarr_htdocs_dir>'."\n");
@@ -200,22 +206,23 @@ $files = dol_dir_list(dirname(__FILE__).'/../scripts/', 'files', 1, $regextoincl
 $dir='';
 $needtoclose=0;
 foreach ($files as $filetmp) {
-    $file = $filetmp['fullname'];
-    //$newdir = str_replace(dirname(__FILE__).'/../scripts', '', dirname($file));
-    $newdir = str_replace(DOL_DOCUMENT_ROOT, '', dirname($file));
-    $newdir = str_replace(dirname(__FILE__).'/../scripts', '', dirname($file));
-    if ($newdir!=$dir) {
-        if ($needtoclose)
-            fputs($fp, '  </dir>'."\n");
-        fputs($fp, '  <dir name="'.$newdir.'" >'."\n");
-        $dir = $newdir;
-        $needtoclose=1;
-    }
-    if (filetype($file)=="file") {
-        $md5=md5_file($file);
-        $checksumconcat[]=$md5;
-        fputs($fp, '    <md5file name="'.basename($file).'" size="'.filesize($file).'">'.$md5.'</md5file>'."\n");
-    }
+	$file = $filetmp['fullname'];
+	//$newdir = str_replace(dirname(__FILE__).'/../scripts', '', dirname($file));
+	$newdir = str_replace(DOL_DOCUMENT_ROOT, '', dirname($file));
+	$newdir = str_replace(dirname(__FILE__).'/../scripts', '', dirname($file));
+	if ($newdir!=$dir) {
+		if ($needtoclose) {
+			fputs($fp, '  </dir>'."\n");
+		}
+		fputs($fp, '  <dir name="'.$newdir.'" >'."\n");
+		$dir = $newdir;
+		$needtoclose=1;
+	}
+	if (filetype($file)=="file") {
+		$md5=md5_file($file);
+		$checksumconcat[]=$md5;
+		fputs($fp, '    <md5file name="'.basename($file).'" size="'.filesize($file).'">'.$md5.'</md5file>'."\n");
+	}
 }
 fputs($fp, '  </dir>'."\n");
 fputs($fp, '</dolibarr_script_dir>'."\n");

+ 93 - 90
dev/initdata/dbf/import-dbf.php

@@ -30,8 +30,8 @@ $script_file = basename(__FILE__);
 
 $path = dirname(__FILE__) . '/';
 if (substr($sapi_type, 0, 3) == 'cgi') {
-    echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
-    exit;
+	echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
+	exit;
 }
 
 // Recupere root dolibarr
@@ -62,40 +62,40 @@ $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);
+	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);
+	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;
+	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));
+	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);
+	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);
+	print 'Error: Failed to open file ' . $filepatherr . "\n";
+	exit(1);
 }
 
 $langs->setDefaultLang($defaultlang);
@@ -105,23 +105,23 @@ $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`");
+	$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 ";
+	$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";
+	print "Table $table_name created\n";
 } else {
-    var_dump($db->errno());
-    print "Impossible : " . $sqlCreate . "\n";
-    die();
+	var_dump($db->errno());
+	print "Impossible : " . $sqlCreate . "\n";
+	die();
 }
 
 $i = 0;
@@ -131,30 +131,33 @@ $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();
-    }
+	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;
+	continue;
 }
 die();
 
@@ -166,11 +169,11 @@ die();
 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();
+	print "Rollback any changes.\n";
+	$db->rollback();
 } else {
-    print "Commit all changes.\n";
-    $db->commit();
+	print "Commit all changes.\n";
+	$db->commit();
 }
 
 $db->close();
@@ -189,43 +192,43 @@ 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;
-    }
-
-    $toss = array();
-    $status = 0;
-    $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";
+	static $last_lines = 0;
+
+	if (!is_null($force_clear_lines)) {
+		$last_lines = $force_clear_lines;
+	}
+
+	$toss = array();
+	$status = 0;
+	$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";
 }

+ 154 - 146
dev/initdata/dbf/importdb-products.php

@@ -29,8 +29,8 @@ $sapi_type = php_sapi_name();
 $script_file = basename(__FILE__);
 $path = dirname(__FILE__) . '/';
 if (substr($sapi_type, 0, 3) == 'cgi') {
-    echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
-    exit;
+	echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
+	exit;
 }
 
 // Recupere root dolibarr
@@ -50,18 +50,18 @@ $confirmed = 1;
 $error = 0;
 
 $tvas = [
-    '1' => "20.00",
-    '2' => "5.50",
-    '3' => "0.00",
-    '4' => "20.60",
-    '5' => "19.60",
+	'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",
+	'1' => "20",
+	'2' => "5.5",
+	'3' => "0",
+	'4' => "20",
+	'5' => "20",
 ];
 
 /*
@@ -75,159 +75,167 @@ dol_syslog($script_file . " launched with arg " . implode(',', $argv));
 $table = $argv[1];
 
 if (empty($argv[1])) {
-    print "Error: Which table ?\n";
-    print "\n";
-    exit(-1);
+	print "Error: Which 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;
+	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 ($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;
 		}
-		if ($ret1) {
-			print " - Error in updatePrice result " . $produit->errorsToString();
+		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 " - updatePrice OK";
+			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";
+
+		//        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";
+		//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";
+		print "\n";
 
-	if ($errorrecord) {
-		print( 'Error on record nb ' . $i . " - " . $produit->errorsToString() . "\n");
-		var_dump($db);
-		die();
-		$error++;    // $errorrecord will be reset
+		if ($errorrecord) {
+			print( 'Error on record nb ' . $i . " - " . $produit->errorsToString() . "\n");
+			var_dump($db);
+			die();
+			$error++;    // $errorrecord will be reset
+		}
+		$j++;
 	}
-	$j++;
-} else die("error : $sql");
+} else {
+	die("error : $sql");
+}
 
 
 

+ 242 - 229
dev/initdata/dbf/importdb-thirdparties.php

@@ -29,8 +29,8 @@ $sapi_type = php_sapi_name();
 $script_file = basename(__FILE__);
 $path = dirname(__FILE__) . '/';
 if (substr($sapi_type, 0, 3) == 'cgi') {
-    echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
-    exit;
+	echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
+	exit;
 }
 
 // Recupere root dolibarr
@@ -50,73 +50,73 @@ $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",
+	"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",
 );
 
 /*
@@ -130,128 +130,134 @@ 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);
+	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;
+	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']);
-	}
+if ($resql) {
+	while ($fields = $db->fetch_array($resql)) {
+		$i++;
+		$errorrecord = 0;
 
-	//        $object->code_client = $fields[9];
-	//        $object->code_fournisseur = $fields[10];
+		if ($startlinenb && $i < $startlinenb) {
+			continue;
+		}
+		if ($endlinenb && $i > $endlinenb) {
+			continue;
+		}
 
+		$nboflines++;
 
-	if ($fields['FCIVIL']) {
-		$labeltype = in_array($fields['FCIVIL'], $civilPrivate) ? 'TE_PRIVATE' : 'TE_SMALL';
-		$object->typent_id = dol_getIdFromCode($db, $labeltype, 'c_typent', 'code');
-	}
+		$object = new Societe($db);
+		$object->import_key = $fields['CODE'];
+		$object->state = 1;
+		$object->client = 3;
+		$object->fournisseur = 0;
 
-	// Set price level
-	$object->price_level = $fields['TARIF'] + 1;
-	//        if ($labeltype == 'Revendeur')
-	//            $object->price_level = 2;
+		$object->name = $fields['FCIVIL'] . ' ' . $fields['FNOM'];
+		//$object->name_alias = $fields[0] != $fields[13] ? trim($fields[0]) : '';
 
-	print "Process line nb " . $i . ", code " . $fields['CODE'] . ", name " . $object->name;
+		$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);
 
 
-	// Extrafields
-	$object->array_options['options_banque'] = $fields['BANQUE'];
-	$object->array_options['options_banque2'] = $fields['BANQUE2'];
-	$object->array_options['options_banquevalid'] = $fields['VALID'];
+		$object->address = trim($fields['FADR1']);
+		if ($fields['FADR2']) {
+			$object->address .= "\n" . trim($fields['FADR2']);
+		}
+		if ($fields['FADR3']) {
+			$object->address .= "\n" . trim($fields['FADR3']);
+		}
 
-	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();
+		$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 {
-			print " - Creation OK with name " . $object->name . " - id = " . $ret;
+			$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']);
 		}
-	}
 
-	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);
-	}
+		//        $object->code_client = $fields[9];
+		//        $object->code_fournisseur = $fields[10];
 
-	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",
+
+		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",
+			);
+			$monsieur = array("M",
 			"M ET MME",
 			"M MME",
 			"M.",
@@ -268,77 +274,84 @@ while ($fields = $db->fetch_array($resql)) {
 			"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";
+			);
+			$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";
+		//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";
+		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
+		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++;
 	}
-	$j++;
-} else die("error : $sql");
+} else {
+	die("error : $sql");
+}
 
 $db->commit();
 

+ 369 - 351
dev/initdata/dbf/includes/dbase.class.php

@@ -18,382 +18,400 @@ 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;
-                elseif ($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;
-    }
+	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;
+				} elseif ($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)
+	function dbase_open($filename, $mode)
 	{
-        return DBase::open($filename, $mode);
-    }
+		return DBase::open($filename, $mode);
+	}
 
-    function dbase_create($filename, $fields, $type = DBASE_TYPE_DBASE)
+	function dbase_create($filename, $fields, $type = DBASE_TYPE_DBASE)
 	{
-        return DBase::create($filename, $fields, $type);
-    }
+		return DBase::create($filename, $fields, $type);
+	}
 
-    function dbase_close($dbase_identifier)
+	function dbase_close($dbase_identifier)
 	{
-        return $dbase_identifier->close();
-    }
+		return $dbase_identifier->close();
+	}
 
-    function dbase_get_header_info($dbase_identifier)
+	function dbase_get_header_info($dbase_identifier)
 	{
-        return $dbase_identifier->get_header_info();
-    }
+		return $dbase_identifier->get_header_info();
+	}
 
-    function dbase_numfields($dbase_identifier)
+	function dbase_numfields($dbase_identifier)
 	{
-        $dbase_identifier->numfields();
-    }
+		$dbase_identifier->numfields();
+	}
 
-    function dbase_numrecords($dbase_identifier)
+	function dbase_numrecords($dbase_identifier)
 	{
-        return $dbase_identifier->numrecords();
-    }
+		return $dbase_identifier->numrecords();
+	}
 
-    function dbase_add_record($dbase_identifier, $record)
+	function dbase_add_record($dbase_identifier, $record)
 	{
-        return $dbase_identifier->add_record($record);
-    }
+		return $dbase_identifier->add_record($record);
+	}
 
-    function dbase_delete_record($dbase_identifier, $record_number)
+	function dbase_delete_record($dbase_identifier, $record_number)
 	{
-        return $dbase_identifier->delete_record($record_number);
-    }
+		return $dbase_identifier->delete_record($record_number);
+	}
 
-    function dbase_replace_record($dbase_identifier, $record, $record_number)
+	function dbase_replace_record($dbase_identifier, $record, $record_number)
 	{
-        return $dbase_identifier->replace_record($record, $record_number);
-    }
+		return $dbase_identifier->replace_record($record, $record_number);
+	}
 
-    function dbase_get_record($dbase_identifier, $record_number)
+	function dbase_get_record($dbase_identifier, $record_number)
 	{
-        return $dbase_identifier->get_record($record_number);
-    }
+		return $dbase_identifier->get_record($record_number);
+	}
 
-    function dbase_get_record_with_names($dbase_identifier, $record_number)
+	function dbase_get_record_with_names($dbase_identifier, $record_number)
 	{
-        return $dbase_identifier->get_record_with_names($record_number);
-    }
+		return $dbase_identifier->get_record_with_names($record_number);
+	}
 
-    function dbase_pack($dbase_identifier)
+	function dbase_pack($dbase_identifier)
 	{
-        return $dbase_identifier->pack();
-    }
+		return $dbase_identifier->pack();
+	}
 }

+ 66 - 76
dev/initdata/generate-invoice.php

@@ -48,60 +48,59 @@ require_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php";
 define(GEN_NUMBER_FACTURE, 1);
 $year = 2016;
 $dates = array (mktime(12, 0, 0, 1, 3, $year),
-    mktime(12, 0, 0, 1, 9, $year),
-    mktime(12, 0, 0, 2, 13, $year),
-    mktime(12, 0, 0, 2, 23, $year),
-    mktime(12, 0, 0, 3, 30, $year),
-    mktime(12, 0, 0, 4, 3, $year),
-    mktime(12, 0, 0, 4, 3, $year),
-    mktime(12, 0, 0, 5, 9, $year),
-    mktime(12, 0, 0, 5, 1, $year),
-    mktime(12, 0, 0, 5, 13, $year),
-    mktime(12, 0, 0, 5, 19, $year),
-    mktime(12, 0, 0, 5, 23, $year),
-    mktime(12, 0, 0, 6, 3, $year),
-    mktime(12, 0, 0, 6, 19, $year),
-    mktime(12, 0, 0, 6, 24, $year),
-    mktime(12, 0, 0, 7, 3, $year),
-    mktime(12, 0, 0, 7, 9, $year),
-    mktime(12, 0, 0, 7, 23, $year),
-    mktime(12, 0, 0, 7, 30, $year),
-    mktime(12, 0, 0, 8, 9, $year),
-    mktime(12, 0, 0, 9, 23, $year),
-    mktime(12, 0, 0, 10, 3, $year),
-    mktime(12, 0, 0, 11, 12, $year),
-    mktime(12, 0, 0, 11, 13, $year),
-    mktime(12, 0, 0, 1, 3, ($year - 1)),
-    mktime(12, 0, 0, 1, 9, ($year - 1)),
-    mktime(12, 0, 0, 2, 13, ($year - 1)),
-    mktime(12, 0, 0, 2, 23, ($year - 1)),
-    mktime(12, 0, 0, 3, 30, ($year - 1)),
-    mktime(12, 0, 0, 4, 3, ($year - 1)),
-    mktime(12, 0, 0, 4, 3, ($year - 1)),
-    mktime(12, 0, 0, 5, 9, ($year - 1)),
-    mktime(12, 0, 0, 5, 1, ($year - 1)),
-    mktime(12, 0, 0, 5, 13, ($year - 1)),
-    mktime(12, 0, 0, 5, 19, ($year - 1)),
-    mktime(12, 0, 0, 5, 23, ($year - 1)),
-    mktime(12, 0, 0, 6, 3, ($year - 1)),
-    mktime(12, 0, 0, 6, 19, ($year - 1)),
-    mktime(12, 0, 0, 6, 24, ($year - 1)),
-    mktime(12, 0, 0, 7, 3, ($year - 1)),
-    mktime(12, 0, 0, 7, 9, ($year - 1)),
-    mktime(12, 0, 0, 7, 23, ($year - 1)),
-    mktime(12, 0, 0, 7, 30, ($year - 1)),
-    mktime(12, 0, 0, 8, 9, ($year - 1)),
-    mktime(12, 0, 0, 9, 23, ($year - 1)),
-    mktime(12, 0, 0, 10, 3, ($year - 1)),
-    mktime(12, 0, 0, 11, 12, $year),
-    mktime(12, 0, 0, 11, 13, $year),
-    mktime(12, 0, 0, 12, 12, $year),
-    mktime(12, 0, 0, 12, 13, $year),
+	mktime(12, 0, 0, 1, 9, $year),
+	mktime(12, 0, 0, 2, 13, $year),
+	mktime(12, 0, 0, 2, 23, $year),
+	mktime(12, 0, 0, 3, 30, $year),
+	mktime(12, 0, 0, 4, 3, $year),
+	mktime(12, 0, 0, 4, 3, $year),
+	mktime(12, 0, 0, 5, 9, $year),
+	mktime(12, 0, 0, 5, 1, $year),
+	mktime(12, 0, 0, 5, 13, $year),
+	mktime(12, 0, 0, 5, 19, $year),
+	mktime(12, 0, 0, 5, 23, $year),
+	mktime(12, 0, 0, 6, 3, $year),
+	mktime(12, 0, 0, 6, 19, $year),
+	mktime(12, 0, 0, 6, 24, $year),
+	mktime(12, 0, 0, 7, 3, $year),
+	mktime(12, 0, 0, 7, 9, $year),
+	mktime(12, 0, 0, 7, 23, $year),
+	mktime(12, 0, 0, 7, 30, $year),
+	mktime(12, 0, 0, 8, 9, $year),
+	mktime(12, 0, 0, 9, 23, $year),
+	mktime(12, 0, 0, 10, 3, $year),
+	mktime(12, 0, 0, 11, 12, $year),
+	mktime(12, 0, 0, 11, 13, $year),
+	mktime(12, 0, 0, 1, 3, ($year - 1)),
+	mktime(12, 0, 0, 1, 9, ($year - 1)),
+	mktime(12, 0, 0, 2, 13, ($year - 1)),
+	mktime(12, 0, 0, 2, 23, ($year - 1)),
+	mktime(12, 0, 0, 3, 30, ($year - 1)),
+	mktime(12, 0, 0, 4, 3, ($year - 1)),
+	mktime(12, 0, 0, 4, 3, ($year - 1)),
+	mktime(12, 0, 0, 5, 9, ($year - 1)),
+	mktime(12, 0, 0, 5, 1, ($year - 1)),
+	mktime(12, 0, 0, 5, 13, ($year - 1)),
+	mktime(12, 0, 0, 5, 19, ($year - 1)),
+	mktime(12, 0, 0, 5, 23, ($year - 1)),
+	mktime(12, 0, 0, 6, 3, ($year - 1)),
+	mktime(12, 0, 0, 6, 19, ($year - 1)),
+	mktime(12, 0, 0, 6, 24, ($year - 1)),
+	mktime(12, 0, 0, 7, 3, ($year - 1)),
+	mktime(12, 0, 0, 7, 9, ($year - 1)),
+	mktime(12, 0, 0, 7, 23, ($year - 1)),
+	mktime(12, 0, 0, 7, 30, ($year - 1)),
+	mktime(12, 0, 0, 8, 9, ($year - 1)),
+	mktime(12, 0, 0, 9, 23, ($year - 1)),
+	mktime(12, 0, 0, 10, 3, ($year - 1)),
+	mktime(12, 0, 0, 11, 12, $year),
+	mktime(12, 0, 0, 11, 13, $year),
+	mktime(12, 0, 0, 12, 12, $year),
+	mktime(12, 0, 0, 12, 13, $year),
 );
 
 $ret=$user->fetch('', 'admin');
-if (! $ret > 0)
-{
+if (! $ret > 0) {
 	print 'A user with login "admin" and all permissions must be created to use this script.'."\n";
 	exit;
 }
@@ -111,12 +110,10 @@ $user->getrights();
 $socids = array();
 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE client in (1, 3)";
 $resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
 	$num_thirdparties = $db->num_rows($resql);
 	$i = 0;
-	while ($i < $num_thirdparties)
-	{
+	while ($i < $num_thirdparties) {
 		$i++;
 		$row = $db->fetch_row($resql);
 		$socids[$i] = $row[0];
@@ -126,12 +123,10 @@ if ($resql)
 $prodids = array();
 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product WHERE tosell=1";
 $resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
 	$num_prods = $db->num_rows($resql);
 	$i = 0;
-	while ($i < $num_prods)
-	{
+	while ($i < $num_prods) {
 		$i++;
 		$row = $db->fetch_row($resql);
 		$prodids[$i] = $row[0];
@@ -140,8 +135,7 @@ if ($resql)
 
 $i=0;
 $result=0;
-while ($i < GEN_NUMBER_FACTURE && $result >= 0)
-{
+while ($i < GEN_NUMBER_FACTURE && $result >= 0) {
 	$i++;
 	$socid = mt_rand(1, $num_thirdparties);
 
@@ -153,31 +147,27 @@ while ($i < GEN_NUMBER_FACTURE && $result >= 0)
 	$object->cond_reglement_id = 3;
 	$object->mode_reglement_id = 3;
 
-    $fuser = new User($db);
-    $fuser->fetch(mt_rand(1, 2));
-    $fuser->getRights();
+	$fuser = new User($db);
+	$fuser->fetch(mt_rand(1, 2));
+	$fuser->getRights();
 
 	$result=$object->create($fuser);
-	if ($result >= 0)
-	{
+	if ($result >= 0) {
 		$nbp = mt_rand(2, 5);
 		$xnbp = 0;
-		while ($xnbp < $nbp)
-		{
+		while ($xnbp < $nbp) {
 			$prodid = mt_rand(1, $num_prods);
 			$product=new Product($db);
 			$result=$product->fetch($prodids[$prodid]);
 			$result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0, '', '', 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type);
-		    if ($result < 0)
-            {
-                dol_print_error($db, $propal->error);
-            }
-            $xnbp++;
+			if ($result < 0) {
+				dol_print_error($db, $propal->error);
+			}
+			$xnbp++;
 		}
 
-	    $result=$object->validate($fuser);
-		if ($result)
-		{
+		$result=$object->validate($fuser);
+		if ($result) {
 			print " OK with ref ".$object->ref."\n";;
 		} else {
 			dol_print_error($db, $object->error);

+ 135 - 137
dev/initdata/generate-order.php

@@ -31,8 +31,8 @@ $path=dirname(__FILE__).'/';
 // Test si mode batch
 $sapi_type = php_sapi_name();
 if (substr($sapi_type, 0, 3) == 'cgi') {
-    echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
-    exit;
+	echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
+	exit;
 }
 
 // Recupere root dolibarr
@@ -54,62 +54,61 @@ require_once DOL_DOCUMENT_ROOT."/commande/class/commande.class.php";
 define(GEN_NUMBER_COMMANDE, 10);
 $year = 2016;
 $dates = array (mktime(12, 0, 0, 1, 3, $year),
-    mktime(12, 0, 0, 1, 9, $year),
-    mktime(12, 0, 0, 2, 13, $year),
-    mktime(12, 0, 0, 2, 23, $year),
-    mktime(12, 0, 0, 3, 30, $year),
-    mktime(12, 0, 0, 4, 3, $year),
-    mktime(12, 0, 0, 4, 3, $year),
-    mktime(12, 0, 0, 5, 9, $year),
-    mktime(12, 0, 0, 5, 1, $year),
-    mktime(12, 0, 0, 5, 13, $year),
-    mktime(12, 0, 0, 5, 19, $year),
-    mktime(12, 0, 0, 5, 23, $year),
-    mktime(12, 0, 0, 6, 3, $year),
-    mktime(12, 0, 0, 6, 19, $year),
-    mktime(12, 0, 0, 6, 24, $year),
-    mktime(12, 0, 0, 7, 3, $year),
-    mktime(12, 0, 0, 7, 9, $year),
-    mktime(12, 0, 0, 7, 23, $year),
-    mktime(12, 0, 0, 7, 30, $year),
-    mktime(12, 0, 0, 8, 9, $year),
-    mktime(12, 0, 0, 9, 23, $year),
-    mktime(12, 0, 0, 10, 3, $year),
-    mktime(12, 0, 0, 11, 12, $year),
-    mktime(12, 0, 0, 11, 13, $year),
-    mktime(12, 0, 0, 1, 3, ($year - 1)),
-    mktime(12, 0, 0, 1, 9, ($year - 1)),
-    mktime(12, 0, 0, 2, 13, ($year - 1)),
-    mktime(12, 0, 0, 2, 23, ($year - 1)),
-    mktime(12, 0, 0, 3, 30, ($year - 1)),
-    mktime(12, 0, 0, 4, 3, ($year - 1)),
-    mktime(12, 0, 0, 4, 3, ($year - 1)),
-    mktime(12, 0, 0, 5, 9, ($year - 1)),
-    mktime(12, 0, 0, 5, 1, ($year - 1)),
-    mktime(12, 0, 0, 5, 13, ($year - 1)),
-    mktime(12, 0, 0, 5, 19, ($year - 1)),
-    mktime(12, 0, 0, 5, 23, ($year - 1)),
-    mktime(12, 0, 0, 6, 3, ($year - 1)),
-    mktime(12, 0, 0, 6, 19, ($year - 1)),
-    mktime(12, 0, 0, 6, 24, ($year - 1)),
-    mktime(12, 0, 0, 7, 3, ($year - 1)),
-    mktime(12, 0, 0, 7, 9, ($year - 1)),
-    mktime(12, 0, 0, 7, 23, ($year - 1)),
-    mktime(12, 0, 0, 7, 30, ($year - 1)),
-    mktime(12, 0, 0, 8, 9, ($year - 1)),
-    mktime(12, 0, 0, 9, 23, ($year - 1)),
-    mktime(12, 0, 0, 10, 3, ($year - 1)),
-    mktime(12, 0, 0, 11, 12, $year),
-    mktime(12, 0, 0, 11, 13, $year),
-    mktime(12, 0, 0, 12, 12, $year),
-    mktime(12, 0, 0, 12, 13, $year),
+	mktime(12, 0, 0, 1, 9, $year),
+	mktime(12, 0, 0, 2, 13, $year),
+	mktime(12, 0, 0, 2, 23, $year),
+	mktime(12, 0, 0, 3, 30, $year),
+	mktime(12, 0, 0, 4, 3, $year),
+	mktime(12, 0, 0, 4, 3, $year),
+	mktime(12, 0, 0, 5, 9, $year),
+	mktime(12, 0, 0, 5, 1, $year),
+	mktime(12, 0, 0, 5, 13, $year),
+	mktime(12, 0, 0, 5, 19, $year),
+	mktime(12, 0, 0, 5, 23, $year),
+	mktime(12, 0, 0, 6, 3, $year),
+	mktime(12, 0, 0, 6, 19, $year),
+	mktime(12, 0, 0, 6, 24, $year),
+	mktime(12, 0, 0, 7, 3, $year),
+	mktime(12, 0, 0, 7, 9, $year),
+	mktime(12, 0, 0, 7, 23, $year),
+	mktime(12, 0, 0, 7, 30, $year),
+	mktime(12, 0, 0, 8, 9, $year),
+	mktime(12, 0, 0, 9, 23, $year),
+	mktime(12, 0, 0, 10, 3, $year),
+	mktime(12, 0, 0, 11, 12, $year),
+	mktime(12, 0, 0, 11, 13, $year),
+	mktime(12, 0, 0, 1, 3, ($year - 1)),
+	mktime(12, 0, 0, 1, 9, ($year - 1)),
+	mktime(12, 0, 0, 2, 13, ($year - 1)),
+	mktime(12, 0, 0, 2, 23, ($year - 1)),
+	mktime(12, 0, 0, 3, 30, ($year - 1)),
+	mktime(12, 0, 0, 4, 3, ($year - 1)),
+	mktime(12, 0, 0, 4, 3, ($year - 1)),
+	mktime(12, 0, 0, 5, 9, ($year - 1)),
+	mktime(12, 0, 0, 5, 1, ($year - 1)),
+	mktime(12, 0, 0, 5, 13, ($year - 1)),
+	mktime(12, 0, 0, 5, 19, ($year - 1)),
+	mktime(12, 0, 0, 5, 23, ($year - 1)),
+	mktime(12, 0, 0, 6, 3, ($year - 1)),
+	mktime(12, 0, 0, 6, 19, ($year - 1)),
+	mktime(12, 0, 0, 6, 24, ($year - 1)),
+	mktime(12, 0, 0, 7, 3, ($year - 1)),
+	mktime(12, 0, 0, 7, 9, ($year - 1)),
+	mktime(12, 0, 0, 7, 23, ($year - 1)),
+	mktime(12, 0, 0, 7, 30, ($year - 1)),
+	mktime(12, 0, 0, 8, 9, ($year - 1)),
+	mktime(12, 0, 0, 9, 23, ($year - 1)),
+	mktime(12, 0, 0, 10, 3, ($year - 1)),
+	mktime(12, 0, 0, 11, 12, $year),
+	mktime(12, 0, 0, 11, 13, $year),
+	mktime(12, 0, 0, 12, 12, $year),
+	mktime(12, 0, 0, 12, 13, $year),
 );
 
 $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;
+if ($ret <= 0) {
+	print 'A user with login "admin" and all permissions must be created to use this script.'."\n";
+	exit;
 }
 $user->getrights();
 
@@ -117,101 +116,100 @@ $societesid = array();
 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe where client in (1, 3)";
 $resql=$db->query($sql);
 if ($resql) {
-    $num_thirdparties = $db->num_rows($resql);
-    $i = 0;
-    while ($i < $num_thirdparties) {
-        $i++;
-        $row = $db->fetch_row($resql);
-        $societesid[$i] = $row[0];
-    }
-} else { print "err"; }
+	$num_thirdparties = $db->num_rows($resql);
+	$i = 0;
+	while ($i < $num_thirdparties) {
+		$i++;
+		$row = $db->fetch_row($resql);
+		$societesid[$i] = $row[0];
+	}
+} else {
+	print "err";
+}
 
 $commandesid = array();
 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande";
 $resql=$db->query($sql);
 if ($resql) {
-    $num = $db->num_rows($resql);
-    $i = 0;
-    while ($i < $num) {
-        $i++;
-        $row = $db->fetch_row($resql);
-        $commandesid[$i] = $row[0];
-    }
-} else { print "err"; }
+	$num = $db->num_rows($resql);
+	$i = 0;
+	while ($i < $num) {
+		$i++;
+		$row = $db->fetch_row($resql);
+		$commandesid[$i] = $row[0];
+	}
+} else {
+	print "err";
+}
 
 $prodids = array();
 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product WHERE tosell=1";
 $resql = $db->query($sql);
 if ($resql) {
-    $num_prods = $db->num_rows($resql);
-    $i = 0;
-    while ($i < $num_prods) {
-        $i++;
-
-        $row = $db->fetch_row($resql);
-        $prodids[$i] = $row[0];
-    }
+	$num_prods = $db->num_rows($resql);
+	$i = 0;
+	while ($i < $num_prods) {
+		$i++;
+
+		$row = $db->fetch_row($resql);
+		$prodids[$i] = $row[0];
+	}
 }
 
 
 
 print "Build ".GEN_NUMBER_COMMANDE." orders\n";
-for ($s = 0 ; $s < GEN_NUMBER_COMMANDE ; $s++)
-{
-    print "Process order ".$s."\n";
-
-    $object = new Commande($db);
-
-    $object->socid          = $societesid[mt_rand(1, $num_thirdparties)];
-    $object->date_commande  = $dates[mt_rand(1, count($dates)-1)];
-    $object->note           = 'My small comment about this order. Hum. Nothing.';
-    $object->source         = 1;
-    $object->fk_project     = 0;
-    $object->remise_percent = 0;
-    $object->shipping_method_id = mt_rand(1, 2);
-    $object->cond_reglement_id = mt_rand(0, 2);
-    $object->more_reglement_id = mt_rand(0, 7);
-    $object->availability_id = mt_rand(0, 1);
-
-    $listofuserid=array(12,13,16);
-
-    $fuser = new User($db);
-    $fuser->fetch($listofuserid[mt_rand(0, 2)]);
-    $fuser->getRights();
-
-    $db->begin();
-
-    $result=$object->create($fuser);
-    if ($result >= 0)
-    {
-        $nbp = mt_rand(2, 5);
-        $xnbp = 0;
-        while ($xnbp < $nbp)
-        {
-            $prodid = mt_rand(1, $num_prods);
-            $product=new Product($db);
-            $result=$product->fetch($prodids[$prodid]);
-            $result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0, 0, 0, $product->price_base_type, $product->price_ttc, '', '', $product->type);
-            if ($result <= 0)
-            {
-                dol_print_error($db, $object->error);
-            }
-            $xnbp++;
-        }
-
-        $result=$object->valid($fuser);
-        if ($result > 0)
-        {
-            $db->commit();
-            print " OK with ref ".$object->ref."\n";
-        } else {
-            print " KO\n";
-            $db->rollback();
-            dol_print_error($db, $object->error);
-        }
-    } else {
-        print " KO\n";
-        $db->rollback();
-        dol_print_error($db, $object->error);
-    }
+for ($s = 0; $s < GEN_NUMBER_COMMANDE; $s++) {
+	print "Process order ".$s."\n";
+
+	$object = new Commande($db);
+
+	$object->socid          = $societesid[mt_rand(1, $num_thirdparties)];
+	$object->date_commande  = $dates[mt_rand(1, count($dates)-1)];
+	$object->note           = 'My small comment about this order. Hum. Nothing.';
+	$object->source         = 1;
+	$object->fk_project     = 0;
+	$object->remise_percent = 0;
+	$object->shipping_method_id = mt_rand(1, 2);
+	$object->cond_reglement_id = mt_rand(0, 2);
+	$object->more_reglement_id = mt_rand(0, 7);
+	$object->availability_id = mt_rand(0, 1);
+
+	$listofuserid=array(12,13,16);
+
+	$fuser = new User($db);
+	$fuser->fetch($listofuserid[mt_rand(0, 2)]);
+	$fuser->getRights();
+
+	$db->begin();
+
+	$result=$object->create($fuser);
+	if ($result >= 0) {
+		$nbp = mt_rand(2, 5);
+		$xnbp = 0;
+		while ($xnbp < $nbp) {
+			$prodid = mt_rand(1, $num_prods);
+			$product=new Product($db);
+			$result=$product->fetch($prodids[$prodid]);
+			$result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0, 0, 0, $product->price_base_type, $product->price_ttc, '', '', $product->type);
+			if ($result <= 0) {
+				dol_print_error($db, $object->error);
+			}
+			$xnbp++;
+		}
+
+		$result=$object->valid($fuser);
+		if ($result > 0) {
+			$db->commit();
+			print " OK with ref ".$object->ref."\n";
+		} else {
+			print " KO\n";
+			$db->rollback();
+			dol_print_error($db, $object->error);
+		}
+	} else {
+		print " KO\n";
+		$db->rollback();
+		dol_print_error($db, $object->error);
+	}
 }

+ 35 - 24
dev/initdata/generate-product.php

@@ -31,8 +31,8 @@ $path=dirname(__FILE__).'/';
 // Test si mode batch
 $sapi_type = php_sapi_name();
 if (substr($sapi_type, 0, 3) == 'cgi') {
-    echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
-    exit;
+	echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
+	exit;
 }
 
 // Recupere root dolibarr
@@ -54,8 +54,7 @@ define(GEN_NUMBER_PRODUIT, 100000);
 
 
 $ret=$user->fetch('', 'admin');
-if (! $ret > 0)
-{
+if (! $ret > 0) {
 	print 'A user with login "admin" and all permissions must be created to use this script.'."\n";
 	exit;
 }
@@ -65,38 +64,50 @@ $user->getrights();
 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product"; $productsid = array();
 $resql=$db->query($sql);
 if ($resql) {
-    $num = $db->num_rows($resql); $i = 0;
-    while ($i < $num) {      $row = $db->fetch_row($resql);      $productsid[$i] = $row[0];      $i++; }
+	$num = $db->num_rows($resql); $i = 0;
+	while ($i < $num) {
+		$row = $db->fetch_row($resql);      $productsid[$i] = $row[0];      $i++;
+	}
 }
 
 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe"; $societesid = array();
 $resql=$db->query($sql);
 if ($resql) {
 	$num = $db->num_rows($resql); $i = 0;
-    while ($i < $num) { $row = $db->fetch_row($resql);      $societesid[$i] = $row[0];      $i++; }
-} else { print "err"; }
+	while ($i < $num) {
+		$row = $db->fetch_row($resql);      $societesid[$i] = $row[0];      $i++;
+	}
+} else {
+	print "err";
+}
 
 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande"; $commandesid = array();
 $resql=$db->query($sql);
 if ($resql) {
 	$num = $db->num_rows($resql); $i = 0;
-    while ($i < $num) { $row = $db->fetch_row($resql);      $commandesid[$i] = $row[0];      $i++; }
-} else { print "err"; }
+	while ($i < $num) {
+		$row = $db->fetch_row($resql);      $commandesid[$i] = $row[0];      $i++;
+	}
+} else {
+	print "err";
+}
 
 
 print "Generates ".GEN_NUMBER_PRODUIT." products\n";
-for ($s = 0 ; $s < GEN_NUMBER_PRODUIT ; $s++)
-{
-    print "Product ".$s;
-    $produit = new Product($db);
-    $produit->type = mt_rand(0, 1);
-    $produit->status = 1;
-    $produit->ref = ($produit->type?'S':'P').time().$s;
-    $produit->label = 'Label '.time().$s;
-    $produit->description = 'Description '.time().$s;
-    $produit->price = mt_rand(1, 1000);
-    $produit->tva_tx = "19.6";
-    $ret=$produit->create($user);
-    if ($ret < 0) print "Error $ret - ".$produit->error."\n";
-	else print " OK with ref ".$produit->ref."\n";
+for ($s = 0; $s < GEN_NUMBER_PRODUIT; $s++) {
+	print "Product ".$s;
+	$produit = new Product($db);
+	$produit->type = mt_rand(0, 1);
+	$produit->status = 1;
+	$produit->ref = ($produit->type?'S':'P').time().$s;
+	$produit->label = 'Label '.time().$s;
+	$produit->description = 'Description '.time().$s;
+	$produit->price = mt_rand(1, 1000);
+	$produit->tva_tx = "19.6";
+	$ret=$produit->create($user);
+	if ($ret < 0) {
+		print "Error $ret - ".$produit->error."\n";
+	} else {
+		print " OK with ref ".$produit->ref."\n";
+	}
 }

+ 70 - 83
dev/initdata/generate-proposal.php

@@ -50,60 +50,59 @@ require_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php";
 define(GEN_NUMBER_PROPAL, 10);
 $year = 2016;
 $dates = array (mktime(12, 0, 0, 1, 3, $year),
-    mktime(12, 0, 0, 1, 9, $year),
-    mktime(12, 0, 0, 2, 13, $year),
-    mktime(12, 0, 0, 2, 23, $year),
-    mktime(12, 0, 0, 3, 30, $year),
-    mktime(12, 0, 0, 4, 3, $year),
-    mktime(12, 0, 0, 4, 3, $year),
-    mktime(12, 0, 0, 5, 9, $year),
-    mktime(12, 0, 0, 5, 1, $year),
-    mktime(12, 0, 0, 5, 13, $year),
-    mktime(12, 0, 0, 5, 19, $year),
-    mktime(12, 0, 0, 5, 23, $year),
-    mktime(12, 0, 0, 6, 3, $year),
-    mktime(12, 0, 0, 6, 19, $year),
-    mktime(12, 0, 0, 6, 24, $year),
-    mktime(12, 0, 0, 7, 3, $year),
-    mktime(12, 0, 0, 7, 9, $year),
-    mktime(12, 0, 0, 7, 23, $year),
-    mktime(12, 0, 0, 7, 30, $year),
-    mktime(12, 0, 0, 8, 9, $year),
-    mktime(12, 0, 0, 9, 23, $year),
-    mktime(12, 0, 0, 10, 3, $year),
-    mktime(12, 0, 0, 11, 12, $year),
-    mktime(12, 0, 0, 11, 13, $year),
-    mktime(12, 0, 0, 1, 3, ($year - 1)),
-    mktime(12, 0, 0, 1, 9, ($year - 1)),
-    mktime(12, 0, 0, 2, 13, ($year - 1)),
-    mktime(12, 0, 0, 2, 23, ($year - 1)),
-    mktime(12, 0, 0, 3, 30, ($year - 1)),
-    mktime(12, 0, 0, 4, 3, ($year - 1)),
-    mktime(12, 0, 0, 4, 3, ($year - 1)),
-    mktime(12, 0, 0, 5, 9, ($year - 1)),
-    mktime(12, 0, 0, 5, 1, ($year - 1)),
-    mktime(12, 0, 0, 5, 13, ($year - 1)),
-    mktime(12, 0, 0, 5, 19, ($year - 1)),
-    mktime(12, 0, 0, 5, 23, ($year - 1)),
-    mktime(12, 0, 0, 6, 3, ($year - 1)),
-    mktime(12, 0, 0, 6, 19, ($year - 1)),
-    mktime(12, 0, 0, 6, 24, ($year - 1)),
-    mktime(12, 0, 0, 7, 3, ($year - 1)),
-    mktime(12, 0, 0, 7, 9, ($year - 1)),
-    mktime(12, 0, 0, 7, 23, ($year - 1)),
-    mktime(12, 0, 0, 7, 30, ($year - 1)),
-    mktime(12, 0, 0, 8, 9, ($year - 1)),
-    mktime(12, 0, 0, 9, 23, ($year - 1)),
-    mktime(12, 0, 0, 10, 3, ($year - 1)),
-    mktime(12, 0, 0, 11, 12, $year),
-    mktime(12, 0, 0, 11, 13, $year),
-    mktime(12, 0, 0, 12, 12, $year),
-    mktime(12, 0, 0, 12, 13, $year),
+	mktime(12, 0, 0, 1, 9, $year),
+	mktime(12, 0, 0, 2, 13, $year),
+	mktime(12, 0, 0, 2, 23, $year),
+	mktime(12, 0, 0, 3, 30, $year),
+	mktime(12, 0, 0, 4, 3, $year),
+	mktime(12, 0, 0, 4, 3, $year),
+	mktime(12, 0, 0, 5, 9, $year),
+	mktime(12, 0, 0, 5, 1, $year),
+	mktime(12, 0, 0, 5, 13, $year),
+	mktime(12, 0, 0, 5, 19, $year),
+	mktime(12, 0, 0, 5, 23, $year),
+	mktime(12, 0, 0, 6, 3, $year),
+	mktime(12, 0, 0, 6, 19, $year),
+	mktime(12, 0, 0, 6, 24, $year),
+	mktime(12, 0, 0, 7, 3, $year),
+	mktime(12, 0, 0, 7, 9, $year),
+	mktime(12, 0, 0, 7, 23, $year),
+	mktime(12, 0, 0, 7, 30, $year),
+	mktime(12, 0, 0, 8, 9, $year),
+	mktime(12, 0, 0, 9, 23, $year),
+	mktime(12, 0, 0, 10, 3, $year),
+	mktime(12, 0, 0, 11, 12, $year),
+	mktime(12, 0, 0, 11, 13, $year),
+	mktime(12, 0, 0, 1, 3, ($year - 1)),
+	mktime(12, 0, 0, 1, 9, ($year - 1)),
+	mktime(12, 0, 0, 2, 13, ($year - 1)),
+	mktime(12, 0, 0, 2, 23, ($year - 1)),
+	mktime(12, 0, 0, 3, 30, ($year - 1)),
+	mktime(12, 0, 0, 4, 3, ($year - 1)),
+	mktime(12, 0, 0, 4, 3, ($year - 1)),
+	mktime(12, 0, 0, 5, 9, ($year - 1)),
+	mktime(12, 0, 0, 5, 1, ($year - 1)),
+	mktime(12, 0, 0, 5, 13, ($year - 1)),
+	mktime(12, 0, 0, 5, 19, ($year - 1)),
+	mktime(12, 0, 0, 5, 23, ($year - 1)),
+	mktime(12, 0, 0, 6, 3, ($year - 1)),
+	mktime(12, 0, 0, 6, 19, ($year - 1)),
+	mktime(12, 0, 0, 6, 24, ($year - 1)),
+	mktime(12, 0, 0, 7, 3, ($year - 1)),
+	mktime(12, 0, 0, 7, 9, ($year - 1)),
+	mktime(12, 0, 0, 7, 23, ($year - 1)),
+	mktime(12, 0, 0, 7, 30, ($year - 1)),
+	mktime(12, 0, 0, 8, 9, ($year - 1)),
+	mktime(12, 0, 0, 9, 23, ($year - 1)),
+	mktime(12, 0, 0, 10, 3, ($year - 1)),
+	mktime(12, 0, 0, 11, 12, $year),
+	mktime(12, 0, 0, 11, 13, $year),
+	mktime(12, 0, 0, 12, 12, $year),
+	mktime(12, 0, 0, 12, 13, $year),
 );
 
 $ret=$user->fetch('', 'admin');
-if (! $ret > 0)
-{
+if (! $ret > 0) {
 	print 'A user with login "admin" and all permissions must be created to use this script.'."\n";
 	exit;
 }
@@ -113,12 +112,10 @@ $user->getrights();
 $socids = array();
 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE client in (1,3)";
 $resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
 	$num_thirdparties = $db->num_rows($resql);
 	$i = 0;
-	while ($i < $num_thirdparties)
-	{
+	while ($i < $num_thirdparties) {
 		$i++;
 		$row = $db->fetch_row($resql);
 		$socids[$i] = $row[0];
@@ -128,12 +125,10 @@ if ($resql)
 $contids = array();
 $sql = "SELECT rowid, fk_soc FROM ".MAIN_DB_PREFIX."socpeople";
 $resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
 	$num_conts = $db->num_rows($resql);
 	$i = 0;
-	while ($i < $num_conts)
-	{
+	while ($i < $num_conts) {
 		$i++;
 		$row = $db->fetch_row($resql);
 		$contids[$row[1]][0] = $row[0]; // A ameliorer
@@ -143,12 +138,10 @@ if ($resql)
 $prodids = array();
 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product WHERE tosell=1";
 $resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
 	$num_prods = $db->num_rows($resql);
 	$i = 0;
-	while ($i < $num_prods)
-	{
+	while ($i < $num_prods) {
 		$i++;
 		$row = $db->fetch_row($resql);
 		$prodids[$i] = $row[0];
@@ -159,15 +152,13 @@ $user->rights->propal->creer=1;
 $user->rights->propal->propal_advance->validate=1;
 
 
-if (! empty($conf->global->PROPALE_ADDON) && is_readable(DOL_DOCUMENT_ROOT ."/core/modules/propale/".$conf->global->PROPALE_ADDON.".php"))
-{
+if (! empty($conf->global->PROPALE_ADDON) && is_readable(DOL_DOCUMENT_ROOT ."/core/modules/propale/".$conf->global->PROPALE_ADDON.".php")) {
 	require_once DOL_DOCUMENT_ROOT ."/core/modules/propale/".$conf->global->PROPALE_ADDON.".php";
 }
 
 $i=0;
 $result=0;
-while ($i < GEN_NUMBER_PROPAL && $result >= 0)
-{
+while ($i < GEN_NUMBER_PROPAL && $result >= 0) {
 	$i++;
 	$socid = mt_rand(1, $num_thirdparties);
 	print "Proposal ".$i." for socid ".$socid;
@@ -177,9 +168,9 @@ while ($i < GEN_NUMBER_PROPAL && $result >= 0)
 
 	$object = new Propal($db);
 
-    $fuser = new User($db);
-    $fuser->fetch(mt_rand(1, 2));
-    $fuser->getRights();
+	$fuser = new User($db);
+	$fuser->fetch(mt_rand(1, 2));
+	$fuser->getRights();
 
 	$object->contactid = $contids[$socids[$socid]][0];
 	$object->socid = $socids[$socid];
@@ -188,32 +179,28 @@ while ($i < GEN_NUMBER_PROPAL && $result >= 0)
 	$object->mode_reglement_id = 3;
 
 	$result=$object->create($fuser);
-	if ($result >= 0)
-	{
+	if ($result >= 0) {
 		$nbp = mt_rand(2, 5);
 		$xnbp = 0;
-		while ($xnbp < $nbp)
-		{
+		while ($xnbp < $nbp) {
 			$prodid = mt_rand(1, $num_prods);
 			$product=new Product($db);
 			$result=$product->fetch($prodids[$prodid]);
 			$result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0);
-			if ($result < 0)
-			{
+			if ($result < 0) {
 				dol_print_error($db, $object->error);
 			}
 			$xnbp++;
 		}
 
 		$result=$object->valid($fuser);
-		if ($result > 0)
-		{
-		    $db->commit();
-		    print " OK with ref ".$object->ref."\n";
+		if ($result > 0) {
+			$db->commit();
+			print " OK with ref ".$object->ref."\n";
 		} else {
-		    print " KO\n";
-		    $db->rollback();
-		    dol_print_error($db, $object->error);
+			print " KO\n";
+			$db->rollback();
+			dol_print_error($db, $object->error);
 		}
 	} else {
 		dol_print_error($db, $object->error);

+ 47 - 46
dev/initdata/generate-thirdparty.php

@@ -31,8 +31,8 @@ $path=dirname(__FILE__).'/';
 // Test si mode batch
 $sapi_type = php_sapi_name();
 if (substr($sapi_type, 0, 3) == 'cgi') {
-    echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
-    exit;
+	echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
+	exit;
 }
 
 // Recupere root dolibarr
@@ -57,8 +57,7 @@ define(GEN_NUMBER_SOCIETE, 10);
 
 
 $ret=$user->fetch('', 'admin');
-if (! $ret > 0)
-{
+if (! $ret > 0) {
 	print 'A user with login "admin" and all permissions must be created to use this script.'."\n";
 	exit;
 }
@@ -68,8 +67,8 @@ $user->getrights();
 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product"; $productsid = array();
 $resql=$db->query($sql);
 if ($resql) {
-    $num = $db->num_rows($resql); $i = 0;
-    while ($i < $num) {
+	$num = $db->num_rows($resql); $i = 0;
+	while ($i < $num) {
 		$row = $db->fetch_row($resql);
 		$productsid[$i] = $row[0];
 		$i++;
@@ -80,63 +79,65 @@ $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe"; $societesid = array();
 $resql=$db->query($sql);
 if ($resql) {
 	$num = $db->num_rows($resql); $i = 0;
-    while ($i < $num) {
+	while ($i < $num) {
 		$row = $db->fetch_row($resql);
 		$societesid[$i] = $row[0];
 		$i++;
 	}
-} else { print "err"; }
+} else {
+	print "err";
+}
 
 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande"; $commandesid = array();
 $resql=$db->query($sql);
 if ($resql) {
 	$num = $db->num_rows($resql); $i = 0;
-    while ($i < $num) {
+	while ($i < $num) {
 		$row = $db->fetch_row($resql);
 		$commandesid[$i] = $row[0];
 		$i++;
 	}
-} else { print "err"; }
+} else {
+	print "err";
+}
 
 
 
 print "Generates ".GEN_NUMBER_SOCIETE." companies\n";
-for ($s = 0 ; $s < GEN_NUMBER_SOCIETE ; $s++)
-{
-    print "Company $s\n";
-    $soc = new Societe($db);
-    $soc->name = "Company num ".time()."$s";
-    $soc->town = $listoftown[mt_rand(0, count($listoftown)-1)];
-    $soc->client = mt_rand(1, 2);		// Une societe sur 2 est prospect, l'autre client
-    $soc->fournisseur = mt_rand(0, 1);	// Une societe sur 2 est fournisseur
-    $soc->code_client='CU'.time()."$s";
-    $soc->code_fournisseur='SU'.time()."$s";
-    $soc->tva_assuj=1;
-    $soc->country_id=1;
-    $soc->country_code='FR';
+for ($s = 0; $s < GEN_NUMBER_SOCIETE; $s++) {
+	print "Company $s\n";
+	$soc = new Societe($db);
+	$soc->name = "Company num ".time()."$s";
+	$soc->town = $listoftown[mt_rand(0, count($listoftown)-1)];
+	$soc->client = mt_rand(1, 2);		// Une societe sur 2 est prospect, l'autre client
+	$soc->fournisseur = mt_rand(0, 1);	// Une societe sur 2 est fournisseur
+	$soc->code_client='CU'.time()."$s";
+	$soc->code_fournisseur='SU'.time()."$s";
+	$soc->tva_assuj=1;
+	$soc->country_id=1;
+	$soc->country_code='FR';
 	// Un client sur 3 a une remise de 5%
-    $user_remise=mt_rand(1, 3); if ($user_remise==3) $soc->remise_percent=5;
+	$user_remise=mt_rand(1, 3); if ($user_remise==3) {
+		$soc->remise_percent=5;
+	}
 	print "> client=".$soc->client.", fournisseur=".$soc->fournisseur.", remise=".$soc->remise_percent."\n";
-    $soc->note_private = 'Company created by the script generate-societe.php';
-    $socid = $soc->create();
-
-    if ($socid >= 0)
-    {
-        $rand = mt_rand(1, 4);
-        print "> Generates $rand contact(s)\n";
-        for ($c = 0 ; $c < $rand ; $c++)
-        {
-            $contact = new Contact($db);
-            $contact->socid = $soc->id;
-            $contact->lastname = "Lastname".$c;
-            $contact->firstname = $listoflastname[mt_rand(0, count($listoflastname)-1)];
-            if ( $contact->create($user) )
-            {
-            }
-        }
-
-        print "Company ".$s." created nom=".$soc->name."\n";
-    } else {
-    	print "Error: ".$soc->error."\n";
-    }
+	$soc->note_private = 'Company created by the script generate-societe.php';
+	$socid = $soc->create();
+
+	if ($socid >= 0) {
+		$rand = mt_rand(1, 4);
+		print "> Generates $rand contact(s)\n";
+		for ($c = 0; $c < $rand; $c++) {
+			$contact = new Contact($db);
+			$contact->socid = $soc->id;
+			$contact->lastname = "Lastname".$c;
+			$contact->firstname = $listoflastname[mt_rand(0, count($listoflastname)-1)];
+			if ($contact->create($user)) {
+			}
+		}
+
+		print "Company ".$s." created nom=".$soc->name."\n";
+	} else {
+		print "Error: ".$soc->error."\n";
+	}
 }

+ 101 - 109
dev/initdata/import-products.php

@@ -30,8 +30,8 @@ $sapi_type = php_sapi_name();
 $script_file = basename(__FILE__);
 $path=dirname(__FILE__).'/';
 if (substr($sapi_type, 0, 3) == 'cgi') {
-    echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
-    exit;
+	echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
+	exit;
 }
 
 // Recupere root dolibarr
@@ -67,44 +67,40 @@ $startlinenb = empty($argv[4])?1:$argv[4];
 $endlinenb = empty($argv[5])?0:$argv[5];
 
 if (empty($mode) || ! in_array($mode, array('test','confirm','confirmforced')) || empty($filepath)) {
-    print "Usage:  $script_file (test|confirm|confirmforced) filepath.csv [defaultlang] [startlinenb] [endlinenb]\n";
-    print "Usage:  $script_file test myfilepath.csv fr_FR 2 1002\n";
-    print "\n";
-    exit(-1);
+	print "Usage:  $script_file (test|confirm|confirmforced) filepath.csv [defaultlang] [startlinenb] [endlinenb]\n";
+	print "Usage:  $script_file test myfilepath.csv fr_FR 2 1002\n";
+	print "\n";
+	exit(-1);
 }
 if (! file_exists($filepath)) {
-    print "Error: File ".$filepath." not found.\n";
-    print "\n";
-    exit(-1);
+	print "Error: File ".$filepath." not found.\n";
+	print "\n";
+	exit(-1);
 }
 
 $ret=$user->fetch('', 'admin');
-if (! $ret > 0)
-{
+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));
+if (! $confirmed) {
+	print "Hit Enter to continue or CTRL+C to stop...\n";
+	$input = trim(fgets(STDIN));
 }
 
 // Open input and output files
 $fhandle = fopen($filepath, 'r');
-if (! $fhandle)
-{
-    print 'Error: Failed to open file '.$filepath."\n";
-    exit(1);
+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);
+if (! $fhandleerr) {
+	print 'Error: Failed to open file '.$filepatherr."\n";
+	exit(1);
 }
 
 $langs->setDefaultLang($defaultlang);
@@ -114,99 +110,96 @@ $db->begin();
 
 $i=0;
 $nboflines++;
-while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
-{
-    $i++;
-    $errorrecord=0;
-
-    if ($startlinenb && $i < $startlinenb) continue;
-    if ($endlinenb && $i > $endlinenb) continue;
-
-    $nboflines++;
-
-    $produit = new Product($db);
-    $produit->type = 0;
-    $produit->status = 1;
-    $produit->ref = trim($fields[0]);
-
-    print "Process line nb ".$i.", ref ".$produit->ref;
-    $produit->label = trim($fields[2]);
-    $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[9]);
-    $produit->weight_units = 0;          // -3 = g
-
-    $produit->customcode = $fields[10];
-    $produit->barcode = $fields[1];
-
-    $produit->status = 1;
-    $produit->status_buy = 1;
-
-    $produit->finished = 1;
-
-    $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_npr = 0;
-
-    $produit->cost_price = price2num($fields[16]);
-
-    // Extrafields
-    $produit->array_options['options_ecotaxdeee']=price2num($fields[17]);
-
-    $ret=$produit->create($user);
-    if ($ret < 0)
-    {
-        print " - Error in create result code = ".$ret." - ".$produit->errorsToString();
-        $errorrecord++;
-    } else {
-	    print " - Creation OK with ref ".$produit->ref." - id = ".$ret;
+while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) {
+	$i++;
+	$errorrecord=0;
+
+	if ($startlinenb && $i < $startlinenb) {
+		continue;
+	}
+	if ($endlinenb && $i > $endlinenb) {
+		continue;
+	}
+
+	$nboflines++;
+
+	$produit = new Product($db);
+	$produit->type = 0;
+	$produit->status = 1;
+	$produit->ref = trim($fields[0]);
+
+	print "Process line nb ".$i.", ref ".$produit->ref;
+	$produit->label = trim($fields[2]);
+	$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[9]);
+	$produit->weight_units = 0;          // -3 = g
+
+	$produit->customcode = $fields[10];
+	$produit->barcode = $fields[1];
+
+	$produit->status = 1;
+	$produit->status_buy = 1;
+
+	$produit->finished = 1;
+
+	$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_npr = 0;
+
+	$produit->cost_price = price2num($fields[16]);
+
+	// Extrafields
+	$produit->array_options['options_ecotaxdeee']=price2num($fields[17]);
+
+	$ret=$produit->create($user);
+	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());
-	    $ret2=$produit->updatePrice(price2num($fields[14]), 'HT', $user, $produit->tva_tx, $produit->price_min, 2, $produit->tva_npr, 0, 0, array());
-	    if ($ret1 < 0 || $ret2 < 0)
-        {
-            print " - Error in updatePrice result code = ".$ret1." ".$ret2." - ".$produit->errorsToString();
-            $errorrecord++;
-        } else {
-    	    print " - updatePrice OK";
-    	}
+	// 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());
+		$ret2=$produit->updatePrice(price2num($fields[14]), 'HT', $user, $produit->tva_tx, $produit->price_min, 2, $produit->tva_npr, 0, 0, array());
+		if ($ret1 < 0 || $ret2 < 0) {
+			print " - Error in updatePrice result code = ".$ret1." ".$ret2." - ".$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";
-    	}
+	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";
+		}
 	}
 
 	print "\n";
 
-	if ($errorrecord)
-	{
-	    fwrite($fhandleerr, 'Error on record nb '.$i." - ".$produit->errorsToString()."\n");
-	    $error++;    // $errorrecord will be reset
+	if ($errorrecord) {
+		fwrite($fhandleerr, 'Error on record nb '.$i." - ".$produit->errorsToString()."\n");
+		$error++;    // $errorrecord will be reset
 	}
 }
 
@@ -217,13 +210,12 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
 // 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();
+if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) {
+	print "Rollback any changes.\n";
+	$db->rollback();
 } else {
-    print "Commit all changes.\n";
-    $db->commit();
+	print "Commit all changes.\n";
+	$db->commit();
 }
 
 $db->close();

+ 176 - 183
dev/initdata/import-thirdparties.php

@@ -30,8 +30,8 @@ $sapi_type = php_sapi_name();
 $script_file = basename(__FILE__);
 $path=dirname(__FILE__).'/';
 if (substr($sapi_type, 0, 3) == 'cgi') {
-    echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
-    exit;
+	echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
+	exit;
 }
 
 // Recupere root dolibarr
@@ -67,44 +67,40 @@ $startlinenb = empty($argv[3])?1:$argv[3];
 $endlinenb = empty($argv[4])?0:$argv[4];
 
 if (empty($mode) || ! in_array($mode, array('test','confirm','confirmforced')) || empty($filepath)) {
-    print "Usage:  $script_file (test|confirm|confirmforced) filepath.csv [startlinenb] [endlinenb]\n";
-    print "Usage:  $script_file test myfilepath.csv 2 1002\n";
-    print "\n";
-    exit(-1);
+	print "Usage:  $script_file (test|confirm|confirmforced) filepath.csv [startlinenb] [endlinenb]\n";
+	print "Usage:  $script_file test myfilepath.csv 2 1002\n";
+	print "\n";
+	exit(-1);
 }
 if (! file_exists($filepath)) {
-    print "Error: File ".$filepath." not found.\n";
-    print "\n";
-    exit(-1);
+	print "Error: File ".$filepath." not found.\n";
+	print "\n";
+	exit(-1);
 }
 
 $ret=$user->fetch('', 'admin');
-if (! $ret > 0)
-{
+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));
+if (! $confirmed) {
+	print "Hit Enter to continue or CTRL+C to stop...\n";
+	$input = trim(fgets(STDIN));
 }
 
 // Open input and output files
 $fhandle = fopen($filepath, 'r');
-if (! $fhandle)
-{
-    print 'Error: Failed to open file '.$filepath."\n";
-    exit(1);
+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);
+if (! $fhandleerr) {
+	print 'Error: Failed to open file '.$filepatherr."\n";
+	exit(1);
 }
 
 //$langs->setDefaultLang($defaultlang);
@@ -114,175 +110,173 @@ $db->begin();
 
 $i=0;
 $nboflines=0;
-while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
-{
-    $i++;
-    $errorrecord=0;
-
-    if ($startlinenb && $i < $startlinenb) continue;
-    if ($endlinenb && $i > $endlinenb) continue;
-
-    $nboflines++;
-
-    $object = new Societe($db);
-    $object->state = $fields[6];
-    $object->client = $fields[7];
-    $object->fournisseur = $fields[8];
-
-    $object->name = $fields[13]?trim($fields[13]):$fields[0];
-    $object->name_alias = $fields[0]!=$fields[13]?trim($fields[0]):'';
-
-    $object->address = trim($fields[14]);
-    $object->zip = trim($fields[15]);
-    $object->town = trim($fields[16]);
-    $object->country_id = dol_getIdFromCode($db, trim($fields[21]), 'c_country', 'code', 'rowid');
-    $object->phone = trim($fields[22]);
-    $object->fax = trim($fields[23]);
-    $object->email = trim($fields[26]);
-    $object->idprof2 = trim($fields[29]);
-    $object->tva_intra = trim($fields[34]);
-    $object->default_lang = trim($fields[43]);
-
-    //$condpayment = dol_string_unaccent(trim($fields[36]));
-    if ($fields[36])
-    {
-        $condpayment = trim($fields[36]);
-        if ($condpayment == 'A la commande') $condpayment = 'A réception de commande';
-        if ($condpayment == 'A reception facture') $condpayment = 'Réception de facture';
-        $object->cond_reglement_id = dol_getIdFromCode($db, $condpayment, 'c_payment_term', 'libelle_facture', 'rowid', 1);
-        if (empty($object->cond_reglement_id))
-        {
-            print " - Error cant find payment mode for ".$condpayment."\n";
-            $errorrecord++;
-        }
-    }
-
-    $object->code_client = $fields[9];
-    $object->code_fournisseur = $fields[10];
-
-    $labeltype = trim($fields[1]);
-    $object->typent_id = dol_getIdFromCode($db, $labeltype, 'c_typent', 'libelle');
-
-    // Set price level
-    $object->price_level = 1;
-    if ($labeltype == 'Revendeur') $object->price_level = 2;
-
-    print "Process line nb ".$i.", name ".$object->name;
-
-
-    // Extrafields
-    $object->array_options['options_anastate']=price2num($fields[20]);
-    $object->array_options['options_anaregion']=price2num($fields[17]);
-
-    if (! $errorrecord)
-    {
-        $ret=$object->create($user);
-        if ($ret < 0)
-        {
-            print " - Error in create result code = ".$ret." - ".$object->errorsToString();
-            $errorrecord++;
-        } 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);
-    }
+while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) {
+	$i++;
+	$errorrecord=0;
+
+	if ($startlinenb && $i < $startlinenb) {
+		continue;
+	}
+	if ($endlinenb && $i > $endlinenb) {
+		continue;
+	}
+
+	$nboflines++;
+
+	$object = new Societe($db);
+	$object->state = $fields[6];
+	$object->client = $fields[7];
+	$object->fournisseur = $fields[8];
+
+	$object->name = $fields[13]?trim($fields[13]):$fields[0];
+	$object->name_alias = $fields[0]!=$fields[13]?trim($fields[0]):'';
+
+	$object->address = trim($fields[14]);
+	$object->zip = trim($fields[15]);
+	$object->town = trim($fields[16]);
+	$object->country_id = dol_getIdFromCode($db, trim($fields[21]), 'c_country', 'code', 'rowid');
+	$object->phone = trim($fields[22]);
+	$object->fax = trim($fields[23]);
+	$object->email = trim($fields[26]);
+	$object->idprof2 = trim($fields[29]);
+	$object->tva_intra = trim($fields[34]);
+	$object->default_lang = trim($fields[43]);
+
+	//$condpayment = dol_string_unaccent(trim($fields[36]));
+	if ($fields[36]) {
+		$condpayment = trim($fields[36]);
+		if ($condpayment == 'A la commande') {
+			$condpayment = 'A réception de commande';
+		}
+		if ($condpayment == 'A reception facture') {
+			$condpayment = 'Réception de facture';
+		}
+		$object->cond_reglement_id = dol_getIdFromCode($db, $condpayment, 'c_payment_term', 'libelle_facture', 'rowid', 1);
+		if (empty($object->cond_reglement_id)) {
+			print " - Error cant find payment mode for ".$condpayment."\n";
+			$errorrecord++;
+		}
+	}
+
+	$object->code_client = $fields[9];
+	$object->code_fournisseur = $fields[10];
+
+	$labeltype = trim($fields[1]);
+	$object->typent_id = dol_getIdFromCode($db, $labeltype, 'c_typent', 'libelle');
+
+	// Set price level
+	$object->price_level = 1;
+	if ($labeltype == 'Revendeur') {
+		$object->price_level = 2;
+	}
+
+	print "Process line nb ".$i.", name ".$object->name;
+
+
+	// Extrafields
+	$object->array_options['options_anastate']=price2num($fields[20]);
+	$object->array_options['options_anaregion']=price2num($fields[17]);
+
+	if (! $errorrecord) {
+		$ret=$object->create($user);
+		if ($ret < 0) {
+			print " - Error in create result code = ".$ret." - ".$object->errorsToString();
+			$errorrecord++;
+		} 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);
+	}
 
 	// Assign sales representative
-	if (! $errorrecord && $fields[3])
-	{
-    	$salesrep=new User($db);
-
-    	$tmp=explode(' ', $fields[3], 2);
-    	$salesrep->firstname = trim($tmp[0]);
-    	$salesrep->lastname = trim($tmp[1]);
-    	if ($salesrep->lastname) $salesrep->login = strtolower(substr($salesrep->firstname, 0, 1)) . strtolower(substr($salesrep->lastname, 0));
-    	else $salesrep->login=strtolower($salesrep->firstname);
-    	$salesrep->login=preg_replace('/ /', '', $salesrep->login);
-    	$salesrep->fetch(0, $salesrep->login);
-
-    	$result = $object->add_commercial($user, $salesrep->id);
-    	if ($result < 0)
-    	{
-    	    print " - Error in create link with sale representative result code = ".$result." - ".$object->errorsToString();
-    	    $errorrecord++;
-    	} else {
-    	    print " - create link sale representative OK";
-    	}
+	if (! $errorrecord && $fields[3]) {
+		$salesrep=new User($db);
+
+		$tmp=explode(' ', $fields[3], 2);
+		$salesrep->firstname = trim($tmp[0]);
+		$salesrep->lastname = trim($tmp[1]);
+		if ($salesrep->lastname) {
+			$salesrep->login = strtolower(substr($salesrep->firstname, 0, 1)) . strtolower(substr($salesrep->lastname, 0));
+		} else {
+			$salesrep->login=strtolower($salesrep->firstname);
+		}
+		$salesrep->login=preg_replace('/ /', '', $salesrep->login);
+		$salesrep->fetch(0, $salesrep->login);
+
+		$result = $object->add_commercial($user, $salesrep->id);
+		if ($result < 0) {
+			print " - Error in create link with sale representative result code = ".$result." - ".$object->errorsToString();
+			$errorrecord++;
+		} else {
+			print " - create link sale representative OK";
+		}
 	}
 
 	dol_syslog("Add invoice contacts");
 	// Insert an invoice contact if there is an invoice email != standard email
-	if (! $errorrecord && $fields[27] && $fields[26] != $fields[27])
-	{
-	    $ret1=$ret2=0;
-
-	    $contact = new Contact($db);
-	    $contact->lastname = $object->name;
-	    $contact->address=$object->address;
-	    $contact->zip=$object->zip;
-	    $contact->town=$object->town;
-	    $contact->country_id=$object->country_id;
-	    $contact->email=$fields[27];
-	    $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." - ".$object->errorsToString();
-            $errorrecord++;
-        } else {
-    	    print " - create contact OK";
-    	}
+	if (! $errorrecord && $fields[27] && $fields[26] != $fields[27]) {
+		$ret1=$ret2=0;
+
+		$contact = new Contact($db);
+		$contact->lastname = $object->name;
+		$contact->address=$object->address;
+		$contact->zip=$object->zip;
+		$contact->town=$object->town;
+		$contact->country_id=$object->country_id;
+		$contact->email=$fields[27];
+		$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." - ".$object->errorsToString();
+			$errorrecord++;
+		} else {
+			print " - create contact OK";
+		}
 	}
 
 	dol_syslog("Add delivery contacts");
 	// Insert a delivery contact
-	if (! $errorrecord && $fields[47])
-	{
-	    $ret1=$ret2=0;
-
-	    $contact2 = new Contact($db);
-	    $contact2->lastname = 'Service livraison - '.$fields[47];
-	    $contact2->address = $fields[48];
-	    $contact2->zip = $fields[50];
-	    $contact2->town = $fields[51];
-	    $contact2->country_id=dol_getIdFromCode($db, trim($fields[52]), 'c_country', 'code', 'rowid');
-	    $contact2->note_public=$fields[54];
-	    $contact2->socid=$object->id;
-
-	    // Extrafields
-	    $contact2->array_options['options_anazoneliv']=price2num($fields[53]);
-
-	    $ret1=$contact2->create($user);
-	    if ($ret1 > 0)
-	    {
-	        //$ret2=$contact2->add_contact($object->id, 'SHIPPING');
-	    }
-	    if ($ret1 < 0 || $ret2 < 0)
-        {
-            print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString();
-            $errorrecord++;
-        } else {
-    	    print " - create contact OK";
-    	}
+	if (! $errorrecord && $fields[47]) {
+		$ret1=$ret2=0;
+
+		$contact2 = new Contact($db);
+		$contact2->lastname = 'Service livraison - '.$fields[47];
+		$contact2->address = $fields[48];
+		$contact2->zip = $fields[50];
+		$contact2->town = $fields[51];
+		$contact2->country_id=dol_getIdFromCode($db, trim($fields[52]), 'c_country', 'code', 'rowid');
+		$contact2->note_public=$fields[54];
+		$contact2->socid=$object->id;
+
+		// Extrafields
+		$contact2->array_options['options_anazoneliv']=price2num($fields[53]);
+
+		$ret1=$contact2->create($user);
+		if ($ret1 > 0) {
+			//$ret2=$contact2->add_contact($object->id, 'SHIPPING');
+		}
+		if ($ret1 < 0 || $ret2 < 0) {
+			print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString();
+			$errorrecord++;
+		} else {
+			print " - create contact OK";
+		}
 	}
 
 
 	print "\n";
 
-	if ($errorrecord)
-	{
-	    fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n");
-	    $error++;    // $errorrecord will be reset
+	if ($errorrecord) {
+		fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n");
+		$error++;    // $errorrecord will be reset
 	}
 }
 
@@ -293,13 +287,12 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
 // 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();
+if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) {
+	print "Rollback any changes.\n";
+	$db->rollback();
 } else {
-    print "Commit all changes.\n";
-    $db->commit();
+	print "Commit all changes.\n";
+	$db->commit();
 }
 
 $db->close();

+ 62 - 63
dev/initdata/import-users.php

@@ -30,8 +30,8 @@ $sapi_type = php_sapi_name();
 $script_file = basename(__FILE__);
 $path=dirname(__FILE__).'/';
 if (substr($sapi_type, 0, 3) == 'cgi') {
-    echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
-    exit;
+	echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
+	exit;
 }
 
 // Recupere root dolibarr
@@ -67,44 +67,40 @@ $startlinenb = empty($argv[3])?1:$argv[3];
 $endlinenb = empty($argv[4])?0:$argv[4];
 
 if (empty($mode) || ! in_array($mode, array('test','confirm','confirmforced')) || empty($filepath)) {
-    print "Usage:  $script_file (test|confirm|confirmforced) filepath.csv [startlinenb] [endlinenb]\n";
-    print "Usage:  $script_file test myfilepath.csv 2 1002\n";
-    print "\n";
-    exit(-1);
+	print "Usage:  $script_file (test|confirm|confirmforced) filepath.csv [startlinenb] [endlinenb]\n";
+	print "Usage:  $script_file test myfilepath.csv 2 1002\n";
+	print "\n";
+	exit(-1);
 }
 if (! file_exists($filepath)) {
-    print "Error: File ".$filepath." not found.\n";
-    print "\n";
-    exit(-1);
+	print "Error: File ".$filepath." not found.\n";
+	print "\n";
+	exit(-1);
 }
 
 $ret=$user->fetch('', 'admin');
-if (! $ret > 0)
-{
+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));
+if (! $confirmed) {
+	print "Hit Enter to continue or CTRL+C to stop...\n";
+	$input = trim(fgets(STDIN));
 }
 
 // Open input and output files
 $fhandle = fopen($filepath, 'r');
-if (! $fhandle)
-{
-    print 'Error: Failed to open file '.$filepath."\n";
-    exit(1);
+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);
+if (! $fhandleerr) {
+	print 'Error: Failed to open file '.$filepatherr."\n";
+	exit(1);
 }
 
 //$langs->setDefaultLang($defaultlang);
@@ -114,44 +110,48 @@ $db->begin();
 
 $i=0;
 $nboflines=0;
-while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
-{
-    $i++;
-    $errorrecord=0;
-
-    if ($startlinenb && $i < $startlinenb) continue;
-    if ($endlinenb && $i > $endlinenb) continue;
-
-    $nboflines++;
-
-    $object = new User($db);
-    $object->statut = 1;
-
-    $tmp=explode(' ', $fields[3], 2);
-    $object->firstname = trim($tmp[0]);
-    $object->lastname = trim($tmp[1]);
-    if ($object->lastname) $object->login = strtolower(substr($object->firstname, 0, 1)) . strtolower(substr($object->lastname, 0));
-    else $object->login=strtolower($object->firstname);
-    $object->login=preg_replace('/ /', '', $object->login);
-    $object->password = 'init';
-
-    print "Process line nb ".$i.", login ".$object->login;
-
-    $ret=$object->create($user);
-    if ($ret < 0)
-    {
-        print " - Error in create result code = ".$ret." - ".$object->errorsToString();
-        $errorrecord++;
-    } else {
-	    print " - Creation OK with login ".$object->login." - id = ".$ret;
+while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) {
+	$i++;
+	$errorrecord=0;
+
+	if ($startlinenb && $i < $startlinenb) {
+		continue;
+	}
+	if ($endlinenb && $i > $endlinenb) {
+		continue;
+	}
+
+	$nboflines++;
+
+	$object = new User($db);
+	$object->statut = 1;
+
+	$tmp=explode(' ', $fields[3], 2);
+	$object->firstname = trim($tmp[0]);
+	$object->lastname = trim($tmp[1]);
+	if ($object->lastname) {
+		$object->login = strtolower(substr($object->firstname, 0, 1)) . strtolower(substr($object->lastname, 0));
+	} else {
+		$object->login=strtolower($object->firstname);
+	}
+	$object->login=preg_replace('/ /', '', $object->login);
+	$object->password = 'init';
+
+	print "Process line nb ".$i.", login ".$object->login;
+
+	$ret=$object->create($user);
+	if ($ret < 0) {
+		print " - Error in create result code = ".$ret." - ".$object->errorsToString();
+		$errorrecord++;
+	} else {
+		print " - Creation OK with login ".$object->login." - id = ".$ret;
 	}
 
 	print "\n";
 
-	if ($errorrecord)
-	{
-	    fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n");
-	    $error++;    // $errorrecord will be reset
+	if ($errorrecord) {
+		fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n");
+		$error++;    // $errorrecord will be reset
 	}
 }
 
@@ -162,13 +162,12 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape))
 // 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();
+if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) {
+	print "Rollback any changes.\n";
+	$db->rollback();
 } else {
-    print "Commit all changes.\n";
-    $db->commit();
+	print "Commit all changes.\n";
+	$db->commit();
 }
 
 $db->close();

+ 202 - 208
dev/initdata/purge-data.php

@@ -30,8 +30,8 @@ $path=__DIR__.'/';
 
 // Test si mode batch
 if (substr($sapi_type, 0, 3) == 'cgi') {
-    echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
-    exit(-1);
+	echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
+	exit(-1);
 }
 
 // Recupere root dolibarr
@@ -52,121 +52,121 @@ $error=0;
 
 // List of sql to execute
 $sqls=array(
-    'user'=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user IN (SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 0 and login != 'admin') AND fk_user IN (select rowid FROM ".MAIN_DB_PREFIX."user where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."user WHERE admin = 0 and login != 'admin' AND datec < '__DATE__'",
-    ),
-    'event'=>array(
-        //"DELETE FROM ".MAIN_DB_PREFIX."actioncomm WHERE lineid IN (SELECT rowid FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."actioncomm WHERE datec < '__DATE__'",
-    ),
-    'payment'=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."paiement_facture where fk_facture IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."paiement where rowid NOT IN (SELECT fk_paiement FROM ".MAIN_DB_PREFIX."paiement_facture)",
-    ),
-    'supplier_payment'=>array(
-    	"DELETE FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn where fk_facturefourn IN (select rowid FROM ".MAIN_DB_PREFIX."facture_fourn where datec < '__DATE__')",
-    	"DELETE FROM ".MAIN_DB_PREFIX."paiementfourn where rowid NOT IN (SELECT fk_paiementfourn FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn)",
-    ),
-    'bank'=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid IN (SELECT rowid FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank IN (SELECT rowid FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__'",
-    ),
-    'bankaccount'=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."bank_account WHERE datec < '__DATE__'",
-    ),
-    'invoice'=>array(
-        '@payment',
-        "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except where fk_facture_source IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except where fk_facture IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except where fk_facture_line IN (select rowid FROM ".MAIN_DB_PREFIX."facturedet as fd WHERE fd.fk_facture IN (select rowid from ".MAIN_DB_PREFIX."facture where datec < '__DATE__'))",
-        "DELETE FROM ".MAIN_DB_PREFIX."facture_rec where datec < '__DATE__'",
-        "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE fk_facture IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')",
-        "UPDATE ".MAIN_DB_PREFIX."facture SET fk_facture_source = NULL WHERE fk_facture_source IN (select f2.rowid FROM (select * from ".MAIN_DB_PREFIX."facture) as f2 where f2.datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__'",
-    ),
-    'accounting'=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."accounting_bookkeeping where doc_date < '__DATE__'",
-    ),
-    'proposal'=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE fk_propal IN (select rowid FROM ".MAIN_DB_PREFIX."propal where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."propal WHERE datec < '__DATE__'",
-    ),
-    "supplier_proposal"=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE fk_supplier_proposal IN (select rowid FROM ".MAIN_DB_PREFIX."propal where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposal where datec < '__DATE__'",
-    ),
-    'order'=>array(
-        '@shipment',
-        "DELETE FROM ".MAIN_DB_PREFIX."commandedet WHERE fk_commande IN (select rowid FROM ".MAIN_DB_PREFIX."commande where date_creation < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."commande where date_creation < '__DATE__'",
-    ),
-    'supplier_order'=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande IN (select rowid FROM ".MAIN_DB_PREFIX."commande_fournisseur where date_creation < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur where date_creation < '__DATE__'",
-    ),
+	'user'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user IN (SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 0 and login != 'admin') AND fk_user IN (select rowid FROM ".MAIN_DB_PREFIX."user where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."user WHERE admin = 0 and login != 'admin' AND datec < '__DATE__'",
+	),
+	'event'=>array(
+		//"DELETE FROM ".MAIN_DB_PREFIX."actioncomm WHERE lineid IN (SELECT rowid FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."actioncomm WHERE datec < '__DATE__'",
+	),
+	'payment'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."paiement_facture where fk_facture IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."paiement where rowid NOT IN (SELECT fk_paiement FROM ".MAIN_DB_PREFIX."paiement_facture)",
+	),
+	'supplier_payment'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn where fk_facturefourn IN (select rowid FROM ".MAIN_DB_PREFIX."facture_fourn where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."paiementfourn where rowid NOT IN (SELECT fk_paiementfourn FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn)",
+	),
+	'bank'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid IN (SELECT rowid FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank IN (SELECT rowid FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__'",
+	),
+	'bankaccount'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."bank_account WHERE datec < '__DATE__'",
+	),
+	'invoice'=>array(
+		'@payment',
+		"DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except where fk_facture_source IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except where fk_facture IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except where fk_facture_line IN (select rowid FROM ".MAIN_DB_PREFIX."facturedet as fd WHERE fd.fk_facture IN (select rowid from ".MAIN_DB_PREFIX."facture where datec < '__DATE__'))",
+		"DELETE FROM ".MAIN_DB_PREFIX."facture_rec where datec < '__DATE__'",
+		"DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE fk_facture IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')",
+		"UPDATE ".MAIN_DB_PREFIX."facture SET fk_facture_source = NULL WHERE fk_facture_source IN (select f2.rowid FROM (select * from ".MAIN_DB_PREFIX."facture) as f2 where f2.datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__'",
+	),
+	'accounting'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."accounting_bookkeeping where doc_date < '__DATE__'",
+	),
+	'proposal'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE fk_propal IN (select rowid FROM ".MAIN_DB_PREFIX."propal where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."propal WHERE datec < '__DATE__'",
+	),
+	"supplier_proposal"=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE fk_supplier_proposal IN (select rowid FROM ".MAIN_DB_PREFIX."propal where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."supplier_proposal where datec < '__DATE__'",
+	),
+	'order'=>array(
+		'@shipment',
+		"DELETE FROM ".MAIN_DB_PREFIX."commandedet WHERE fk_commande IN (select rowid FROM ".MAIN_DB_PREFIX."commande where date_creation < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."commande where date_creation < '__DATE__'",
+	),
+	'supplier_order'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande IN (select rowid FROM ".MAIN_DB_PREFIX."commande_fournisseur where date_creation < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur where date_creation < '__DATE__'",
+	),
 	'supplier_invoice'=>array(
 		'@supplier_payment',
-        "DELETE FROM ".MAIN_DB_PREFIX."facture_fourn_det WHERE fk_facture_fourn IN (select rowid FROM ".MAIN_DB_PREFIX."facture_fourn where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."facture_fourn where datec < '__DATE__'",
-    ),
-    'shipment'=>array(
-        '@delivery',
-        "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_batch WHERE fk_expeditiondet IN (select rowid FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__'))",
-        "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__'))",
-        "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."expedition_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__'",
-    ),
-    'delivery'=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."deliverydet WHERE fk_delivery IN (select rowid FROM ".MAIN_DB_PREFIX."delivery where date_creation < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."delivery where date_creation < '__DATE__'",
-    ),
-    'contract'=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."contratdet_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."contratdet WHERE fk_contrat IN (select rowid FROM ".MAIN_DB_PREFIX."contrat where datec < '__DATE__'))",
-        "DELETE FROM ".MAIN_DB_PREFIX."contratdet WHERE fk_contrat IN (select rowid FROM ".MAIN_DB_PREFIX."contrat where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."contrat_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."contrat where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."contrat WHERE datec < '__DATE__'",
-    ),
-    'intervention'=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet WHERE fk_fichinter IN (select rowid FROM ".MAIN_DB_PREFIX."fichinter where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."fichinter where datec < '__DATE__'",
-    ),
-    'stock'=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."stock_mouvement WHERE datem < '__DATE__'",
-    ),
-    'product'=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."categorie_product WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."product_lang WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."product_price_by_qty WHERE fk_product_price IN (select rowid FROM ".MAIN_DB_PREFIX."product_price where fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__'))",
-        "DELETE FROM ".MAIN_DB_PREFIX."product_price WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."product_batch WHERE fk_product_stock IN (select rowid FROM ".MAIN_DB_PREFIX."product_stock where fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__'))",
-    	"DELETE FROM ".MAIN_DB_PREFIX."product_stock WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."product_lot WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')",
-    	"DELETE FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__'",
-    ),
-    'project'=>array(
-        // TODO set fk_project to null on object that refer to project
-        "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time WHERE fk_task IN (select rowid FROM ".MAIN_DB_PREFIX."projet_task WHERE fk_projet IN (select rowid FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__'))",
-        "DELETE FROM ".MAIN_DB_PREFIX."projet_task WHERE fk_projet IN (select rowid FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__'",
-    ),
-    'contact'=>array(
-        "DELETE FROM ".MAIN_DB_PREFIX."categorie_contact WHERE fk_socpeople IN (select rowid FROM ".MAIN_DB_PREFIX."socpeople where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."socpeople where datec < '__DATE__'",
-    ),
-    'thirdparty'=>array(
-        '@contact',
-        "DELETE FROM ".MAIN_DB_PREFIX."cabinetmed_cons WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')",
-        "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = NULL WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."categorie_fournisseur WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."categorie_societe WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')",
-        "DELETE FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')",
-    	"DELETE FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__'",
-    )
+		"DELETE FROM ".MAIN_DB_PREFIX."facture_fourn_det WHERE fk_facture_fourn IN (select rowid FROM ".MAIN_DB_PREFIX."facture_fourn where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."facture_fourn where datec < '__DATE__'",
+	),
+	'shipment'=>array(
+		'@delivery',
+		"DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_batch WHERE fk_expeditiondet IN (select rowid FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__'))",
+		"DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__'))",
+		"DELETE FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."expedition_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__'",
+	),
+	'delivery'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."deliverydet WHERE fk_delivery IN (select rowid FROM ".MAIN_DB_PREFIX."delivery where date_creation < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."delivery where date_creation < '__DATE__'",
+	),
+	'contract'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."contratdet_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."contratdet WHERE fk_contrat IN (select rowid FROM ".MAIN_DB_PREFIX."contrat where datec < '__DATE__'))",
+		"DELETE FROM ".MAIN_DB_PREFIX."contratdet WHERE fk_contrat IN (select rowid FROM ".MAIN_DB_PREFIX."contrat where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."contrat_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."contrat where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."contrat WHERE datec < '__DATE__'",
+	),
+	'intervention'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."fichinterdet WHERE fk_fichinter IN (select rowid FROM ".MAIN_DB_PREFIX."fichinter where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."fichinter where datec < '__DATE__'",
+	),
+	'stock'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."stock_mouvement WHERE datem < '__DATE__'",
+	),
+	'product'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."categorie_product WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."product_lang WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."product_price_by_qty WHERE fk_product_price IN (select rowid FROM ".MAIN_DB_PREFIX."product_price where fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__'))",
+		"DELETE FROM ".MAIN_DB_PREFIX."product_price WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."product_batch WHERE fk_product_stock IN (select rowid FROM ".MAIN_DB_PREFIX."product_stock where fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__'))",
+		"DELETE FROM ".MAIN_DB_PREFIX."product_stock WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."product_lot WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__'",
+	),
+	'project'=>array(
+		// TODO set fk_project to null on object that refer to project
+		"DELETE FROM ".MAIN_DB_PREFIX."projet_task_time WHERE fk_task IN (select rowid FROM ".MAIN_DB_PREFIX."projet_task WHERE fk_projet IN (select rowid FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__'))",
+		"DELETE FROM ".MAIN_DB_PREFIX."projet_task WHERE fk_projet IN (select rowid FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__'",
+	),
+	'contact'=>array(
+		"DELETE FROM ".MAIN_DB_PREFIX."categorie_contact WHERE fk_socpeople IN (select rowid FROM ".MAIN_DB_PREFIX."socpeople where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."socpeople where datec < '__DATE__'",
+	),
+	'thirdparty'=>array(
+		'@contact',
+		"DELETE FROM ".MAIN_DB_PREFIX."cabinetmed_cons WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')",
+		"UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = NULL WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."categorie_fournisseur WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."categorie_societe WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')",
+		"DELETE FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__'",
+	)
 );
 
 
@@ -183,44 +183,42 @@ $option = $argv[2];
 $date = $argv[3];
 
 if (empty($mode) || ! in_array($mode, array('test','confirm'))) {
-    print "Usage:  $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n";
-    print "\n";
-    print "option can be ".implode(',', array_keys($sqls))."\n";
-    exit(-1);
+	print "Usage:  $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n";
+	print "\n";
+	print "option can be ".implode(',', array_keys($sqls))."\n";
+	exit(-1);
 }
-if (empty($option))
-{
-    print "Usage:  $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n";
-    print "\n";
-    print "option must be defined with a value in list ".implode(',', array_keys($sqls))."\n";
-    exit(-1);
+if (empty($option)) {
+	print "Usage:  $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n";
+	print "\n";
+	print "option must be defined with a value in list ".implode(',', array_keys($sqls))."\n";
+	exit(-1);
 }
-if ($option != 'all')
-{
-    $listofoptions=explode(',', $option);
-    foreach ($listofoptions as $cursoroption)
-    {
-        if (! in_array($cursoroption, array_keys($sqls))) {
-            print "Usage:  $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n";
-            print "\n";
-            print "option '".$cursoroption."' must be in list ".implode(',', array_keys($sqls))."\n";
-            exit(-1);
-        }
-    }
+if ($option != 'all') {
+	$listofoptions=explode(',', $option);
+	foreach ($listofoptions as $cursoroption) {
+		if (! in_array($cursoroption, array_keys($sqls))) {
+			print "Usage:  $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n";
+			print "\n";
+			print "option '".$cursoroption."' must be in list ".implode(',', array_keys($sqls))."\n";
+			exit(-1);
+		}
+	}
 }
 
 if (empty($date) || (! preg_match('/\d\d\d\d\-\d\d\-\d\d$/', $date) && $date != 'all')) {
-    print "Usage:  $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n";
-    print "\n";
-    print "date can be 'all' or 'YYYY-MM-DD' to delete record before YYYY-MM-DD\n";
-    exit(-1);
+	print "Usage:  $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n";
+	print "\n";
+	print "date can be 'all' or 'YYYY-MM-DD' to delete record before YYYY-MM-DD\n";
+	exit(-1);
 }
 
-if ($date == 'all') $date = '2199-01-01';
+if ($date == 'all') {
+	$date = '2199-01-01';
+}
 
 // Replace database handler
-if (! empty($argv[4]))
-{
+if (! empty($argv[4])) {
 	$db->close();
 	unset($db);
 	$db=getDoliDBInstance($argv[4], $argv[5], $argv[6], $argv[7], $argv[8], $argv[9]);
@@ -229,8 +227,7 @@ if (! empty($argv[4]))
 
 //var_dump($user->db->database_name);
 $ret=$user->fetch('', 'admin');
-if (! $ret > 0)
-{
+if (! $ret > 0) {
 	print 'An admin user with login "admin" must exists to use this script.'."\n";
 	exit;
 }
@@ -245,10 +242,9 @@ print "Database port = ".$db->database_port."\n";
 print "User = ".$db->database_user."\n";
 print "\n";
 
-if (! $confirmed)
-{
-    print "Hit Enter to continue or CTRL+C to stop...\n";
-    $input = trim(fgets(STDIN));
+if (! $confirmed) {
+	print "Hit Enter to continue or CTRL+C to stop...\n";
+	$input = trim(fgets(STDIN));
 }
 
 
@@ -261,73 +257,71 @@ if (! $confirmed)
  */
 function processfamily($family, $date)
 {
-    global $db, $sqls;
-
-    $error=0;
-    foreach ($sqls[$family] as $sql)
-    {
-        if (preg_match('/^@/', $sql))
-        {
-            $newfamily=preg_replace('/@/', '', $sql);
-            processfamily($newfamily, $date);
-            continue;
-        }
-
-        $sql = preg_replace('/__DATE__/', $date, $sql);
-
-        print "Run sql: ".$sql."\n";
-
-        $resql=$db->query($sql);
-        if (! $resql)
-        {
-            if ($db->errno() != 'DB_ERROR_NOSUCHTABLE')
-            {
-                $error++;
-            }
-        }
-
-        if ($error)
-        {
-            print $db->lasterror();
-            $error++;
-            break;
-        }
-    }
-
-    if ($error) return -1;
-    else return 1;
+	global $db, $sqls;
+
+	$error=0;
+	foreach ($sqls[$family] as $sql) {
+		if (preg_match('/^@/', $sql)) {
+			$newfamily=preg_replace('/@/', '', $sql);
+			processfamily($newfamily, $date);
+			continue;
+		}
+
+		$sql = preg_replace('/__DATE__/', $date, $sql);
+
+		print "Run sql: ".$sql."\n";
+
+		$resql=$db->query($sql);
+		if (! $resql) {
+			if ($db->errno() != 'DB_ERROR_NOSUCHTABLE') {
+				$error++;
+			}
+		}
+
+		if ($error) {
+			print $db->lasterror();
+			$error++;
+			break;
+		}
+	}
+
+	if ($error) {
+		return -1;
+	} else {
+		return 1;
+	}
 }
 
 
 $db->begin();
 
 $listofoptions=explode(',', $option);
-foreach ($listofoptions as $cursoroption)
-{
-    $oldfamily='';
-    foreach ($sqls as $family => $familysql)
-    {
-        if ($cursoroption && $cursoroption != 'all' && $cursoroption != $family) continue;
-
-        if ($family != $oldfamily) print "Process action for family ".$family."\n";
-        $oldfamily = $family;
-
-        $result=processfamily($family, $date);
-        if ($result < 0)
-        {
-            $error++;
-            break;
-        }
-    }
+foreach ($listofoptions as $cursoroption) {
+	$oldfamily='';
+	foreach ($sqls as $family => $familysql) {
+		if ($cursoroption && $cursoroption != 'all' && $cursoroption != $family) {
+			continue;
+		}
+
+		if ($family != $oldfamily) {
+			print "Process action for family ".$family."\n";
+		}
+		$oldfamily = $family;
+
+		$result=processfamily($family, $date);
+		if ($result < 0) {
+			$error++;
+			break;
+		}
+	}
 }
 
-if ($error || $mode != 'confirm')
-{
-    print "\nRollback any changes.\n";
-    $db->rollback();
+if ($error || $mode != 'confirm') {
+	print "\nRollback any changes.\n";
+	$db->rollback();
 } else {
-    print "Commit all changes.\n";
-    $db->commit();
+	print "Commit all changes.\n";
+	$db->commit();
 }
 
 $db->close();

+ 36 - 20
dev/tools/dolibarr-postgres2mysql.php

@@ -48,8 +48,9 @@ if (! ($argv[1] && $argv[2])) {
 	echo "Usage: php pg2mysql_cli.php <inputfilename> <outputfilename> [engine]\n";
 	exit();
 } else {
-	if (isset($argv[3]))
+	if (isset($argv[3])) {
 		$config['engine'] = $argv[3];
+	}
 	pg2mysql_large($argv[1], $argv[2]);
 
 	echo <<<XHTML
@@ -74,14 +75,18 @@ function getfieldname($l)
 	// first check if its in nice quotes for us
 	$regs = array();
 	if (preg_match("/`(.*)`/", $l, $regs)) {
-		if ($regs[1])
+		if ($regs[1]) {
 			return $regs[1];
-		else return null;
-	} // if its not in quotes, then it should (we hope!) be the first "word" on the line, up to the first space.
-	elseif (preg_match("/([^\ ]*)/", trim($l), $regs)) {
-		if ($regs[1])
+		} else {
+			return null;
+		}
+	} elseif (preg_match("/([^\ ]*)/", trim($l), $regs)) {
+		// if its not in quotes, then it should (we hope!) be the first "word" on the line, up to the first space.
+		if ($regs[1]) {
 			return $regs[1];
-		else return null;
+		} else {
+			return null;
+		}
 	}
 }
 
@@ -94,13 +99,15 @@ function getfieldname($l)
  */
 function formatsize($s)
 {
-	if ($s < pow(2, 14))
+	if ($s < pow(2, 14)) {
 		return "{$s}B";
-	elseif ($s < pow(2, 20))
+	} elseif ($s < pow(2, 20)) {
 		return sprintf("%.1f", round($s / 1024, 1)) . "K";
-	elseif ($s < pow(2, 30))
+	} elseif ($s < pow(2, 30)) {
 		return sprintf("%.1f", round($s / 1024 / 1024, 1)) . "M";
-	else return sprintf("%.1f", round($s / 1024 / 1024 / 1024, 1)) . "G";
+	} else {
+		return sprintf("%.1f", round($s / 1024 / 1024 / 1024, 1)) . "G";
+	}
 }
 
 /**
@@ -141,9 +148,11 @@ function pg2mysql_large($infilename, $outfilename)
 		$c = substr_count($instr, "'");
 		// we have an odd number of ' marks
 		if ($c % 2 != 0) {
-			if ($inquotes)
+			if ($inquotes) {
 				$inquotes = false;
-			else $inquotes = true;
+			} else {
+				$inquotes = true;
+			}
 		}
 
 		if ($linenum % 10000 == 0) {
@@ -323,9 +332,11 @@ function pg2mysql(&$input, &$arrayofprimaryalreadyintabledef, $header = true)
 			$line = str_replace(" bool DEFAULT false", " bool DEFAULT 0", $line);
 			if (preg_match("/ character varying\(([0-9]*)\)/", $line, $regs)) {
 				$num = $regs[1];
-				if ($num <= 255)
+				if ($num <= 255) {
 					$line = preg_replace("/ character varying\([0-9]*\)/", " varchar($num)", $line);
-				else $line = preg_replace("/ character varying\([0-9]*\)/", " text", $line);
+				} else {
+					$line = preg_replace("/ character varying\([0-9]*\)/", " text", $line);
+				}
 			}
 			// character varying with no size, we will default to varchar(255)
 			if (preg_match("/ character varying/", $line)) {
@@ -345,9 +356,11 @@ function pg2mysql(&$input, &$arrayofprimaryalreadyintabledef, $header = true)
 			$line = preg_replace("/::.*$/", "\n", $line);
 			if (preg_match("/character\(([0-9]*)\)/", $line, $regs)) {
 				$num = $regs[1];
-				if ($num <= 255)
+				if ($num <= 255) {
 					$line = preg_replace("/ character\([0-9]*\)/", " varchar($num)", $line);
-				else $line = preg_replace("/ character\([0-9]*\)/", " text", $line);
+				} else {
+					$line = preg_replace("/ character\([0-9]*\)/", " text", $line);
+				}
 			}
 			// timestamps
 			$line = str_replace(" timestamp with time zone", " datetime", $line);
@@ -457,9 +470,11 @@ function pg2mysql(&$input, &$arrayofprimaryalreadyintabledef, $header = true)
 					$c = substr_count($line, "'");
 					// we have an odd number of ' marks
 					if ($c % 2 != 0) {
-						if ($inquotes)
+						if ($inquotes) {
 							$inquotes = false;
-						else $inquotes = true;
+						} else {
+							$inquotes = true;
+						}
 						// echo "inquotes=$inquotes\n";
 					}
 				} while (substr($lines[$linenumber], - 3, - 1) != ");" || $inquotes);
@@ -524,8 +539,9 @@ function pg2mysql(&$input, &$arrayofprimaryalreadyintabledef, $header = true)
 			}
 		}
 
-		if (substr($line, 0, 13) == 'DROP DATABASE')
+		if (substr($line, 0, 13) == 'DROP DATABASE') {
 			$output .= $line;
+		}
 
 		if (substr($line, 0, 15) == 'CREATE DATABASE') {
 			$matches = array();

+ 1 - 0
dev/tools/test/namespacemig/bbb.php

@@ -4,6 +4,7 @@
 
 use Dolibarr\Aaa as Aaa;
 use function Dolibarr\faaa as faaa;	// Need php 5.6+
+
 //use const Dolibarr\AAA;
 
 //use Bbb as Bbb;

+ 2 - 2
dev/tools/test/namespacemig/main.inc.php

@@ -1,7 +1,7 @@
 <?php
 
 /*spl_autoload_register(function ($class_name) {
-    var_dump('class='.$class_name);
-    require $class_name;
+	var_dump('class='.$class_name);
+	require $class_name;
 });
 */

+ 4 - 3
dev/tools/test/testperf.php

@@ -3,10 +3,11 @@
 $a = microtime(true);
 
 $i = 0;
-while ($i < 1000000)
-{
+while ($i < 1000000) {
 	$key = '1234567890111213141516171819'.$i;
-	if ($i == 1000) $key = 'MAIN_MODULE_AAAAAiiiiiiiiiiiiiiiiiiiiiiiiiiiii';
+	if ($i == 1000) {
+		$key = 'MAIN_MODULE_AAAAAiiiiiiiiiiiiiiiiiiiiiiiiiiiii';
+	}
 
 	//if (preg_match('/^MAIN_MODULE_/', $key)) {
 	//if (substr($key, 0, 12) == 'MAIN_MODULE_') {

+ 15 - 15
dev/tools/test/testtcpdf.php

@@ -38,25 +38,25 @@ $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8',
 
 /*
   The permission array is composed of values taken from the following ones (specify the ones you want to block):
-    - print : Print the document;
-    - modify : Modify the contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble';
-    - copy : Copy or otherwise extract text and graphics from the document;
-    - annot-forms : Add or modify text annotations, fill in interactive form fields, and, if 'modify' is also set, create or modify interactive form fields (including signature fields);
-    - fill-forms : Fill in existing interactive form fields (including signature fields), even if 'annot-forms' is not specified;
-    - extract : Extract text and graphics (in support of accessibility to users with disabilities or for other purposes);
-    - assemble : Assemble the document (insert, rotate, or delete pages and create bookmarks or thumbnail images), even if 'modify' is not set;
-    - print-high : Print the document to a representation from which a faithful digital copy of the PDF content could be generated. When this is not set, printing is limited to a low-level representation of the appearance, possibly of degraded quality.
-    - owner : (inverted logic - only for public-key) when set permits change of encryption and enables all other permissions.
+	- print : Print the document;
+	- modify : Modify the contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble';
+	- copy : Copy or otherwise extract text and graphics from the document;
+	- annot-forms : Add or modify text annotations, fill in interactive form fields, and, if 'modify' is also set, create or modify interactive form fields (including signature fields);
+	- fill-forms : Fill in existing interactive form fields (including signature fields), even if 'annot-forms' is not specified;
+	- extract : Extract text and graphics (in support of accessibility to users with disabilities or for other purposes);
+	- assemble : Assemble the document (insert, rotate, or delete pages and create bookmarks or thumbnail images), even if 'modify' is not set;
+	- print-high : Print the document to a representation from which a faithful digital copy of the PDF content could be generated. When this is not set, printing is limited to a low-level representation of the appearance, possibly of degraded quality.
+	- owner : (inverted logic - only for public-key) when set permits change of encryption and enables all other permissions.
 
  If you don't set any password, the document will open as usual.
  If you set a user password, the PDF viewer will ask for it before displaying the document.
  The master (owner) password, if different from the user one, can be used to get full document access.
 
  Possible encryption modes are:
-     0 = RSA 40 bit
-     1 = RSA 128 bit
-     2 = AES 128 bit
-     3 = AES 256 bit
+	 0 = RSA 40 bit
+	 1 = RSA 128 bit
+	 2 = AES 128 bit
+	 3 = AES 256 bit
 
  NOTES:
  - To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
@@ -89,8 +89,8 @@ $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
 $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 016', PDF_HEADER_STRING);
 
 // set header and footer fonts
-$pdf->setHeaderFont(Array('helvetica', '', PDF_FONT_SIZE_MAIN));
-$pdf->setFooterFont(Array('helvetica', '', PDF_FONT_SIZE_DATA));
+$pdf->setHeaderFont(array('helvetica', '', PDF_FONT_SIZE_MAIN));
+$pdf->setFooterFont(array('helvetica', '', PDF_FONT_SIZE_DATA));
 
 // set default monospaced font
 $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

+ 2 - 2
dev/tools/test/testutf.php

@@ -64,8 +64,8 @@ $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
 $pdf->SetHeaderData('', PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 038', PDF_HEADER_STRING);
 
 // set header and footer fonts
-$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
-$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
+$pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
+$pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
 
 // set default monospaced font
 $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

+ 80 - 62
dev/translation/autotranslator.class.php

@@ -40,18 +40,18 @@ class autoTranslator
 	const DIR_SEPARATOR = '/';
 
 
-    /**
-     * Constructor
-     *
-     * @param   string $_destlang       Destination lang
-     * @param   string $_refLang        Ref lang
-     * @param   string $_langDir        Dir lang
-     * @param   string $_limittofile    Limit to file
-     * @param   string $_apikey         Api key
-     * @return void
-     */
-    public function __construct($_destlang, $_refLang, $_langDir, $_limittofile, $_apikey)
-    {
+	/**
+	 * Constructor
+	 *
+	 * @param   string $_destlang       Destination lang
+	 * @param   string $_refLang        Ref lang
+	 * @param   string $_langDir        Dir lang
+	 * @param   string $_limittofile    Limit to file
+	 * @param   string $_apikey         Api key
+	 * @return void
+	 */
+	public function __construct($_destlang, $_refLang, $_langDir, $_limittofile, $_apikey)
+	{
 
 		// Set enviorment variables
 		$this->_destlang = $_destlang;
@@ -59,7 +59,7 @@ class autoTranslator
 		$this->_langDir = $_langDir.self::DIR_SEPARATOR;
 		$this->_time = date('Y-m-d H:i:s');
 		$this->_limittofile = $_limittofile;
-        $this->_apikey = $_apikey;
+		$this->_apikey = $_apikey;
 
 		// Translate
 		//ini_set('default_charset','UTF-8');
@@ -77,9 +77,10 @@ class autoTranslator
 
 		$files = $this->getTranslationFilesArray($this->_refLang);
 		$counter = 1;
-		foreach ($files as $file)
-		{
-			if ($this->_limittofile && $this->_limittofile != $file) continue;
+		foreach ($files as $file) {
+			if ($this->_limittofile && $this->_limittofile != $file) {
+				continue;
+			}
 			$counter++;
 			$fileContent = null;
 			$refPath = $this->_langDir.$this->_refLang.self::DIR_SEPARATOR.$file;
@@ -88,54 +89,66 @@ class autoTranslator
 
 			// Define target dirs
 			$targetlangs=array($this->_destlang);
-			if ($this->_destlang == 'all')
-			{
+			if ($this->_destlang == 'all') {
 				$targetlangs=array();
 
 				// If we must process all languages
 				$arraytmp=dol_dir_list($this->_langDir, 'directories', 0);
-				foreach ($arraytmp as $dirtmp)
-				{
-					if ($dirtmp['name'] === $this->_refLang) continue;	// We discard source language
+				foreach ($arraytmp as $dirtmp) {
+					if ($dirtmp['name'] === $this->_refLang) {
+						continue;	// We discard source language
+					}
 					$tmppart=explode('_', $dirtmp['name']);
-					if (preg_match('/^en/i', $dirtmp['name']))  continue;	// We discard en_* languages
-					if (preg_match('/^fr/i', $dirtmp['name']))  continue;	// We discard fr_* languages
-					if (preg_match('/^es/i', $dirtmp['name']))  continue;	// We discard es_* languages
-					if (preg_match('/ca_ES/i', $dirtmp['name']))  continue;	// We discard es_CA language
-					if (preg_match('/pt_BR/i', $dirtmp['name']))  continue;	// We discard pt_BR language
-                    if (preg_match('/nl_BE/i', $dirtmp['name']))  continue;  // We discard nl_BE language
-					if (preg_match('/^\./i', $dirtmp['name']))  continue;	// We discard files .*
-					if (preg_match('/^CVS/i', $dirtmp['name']))  continue;	// We discard CVS
+					if (preg_match('/^en/i', $dirtmp['name'])) {
+						continue;	// We discard en_* languages
+					}
+					if (preg_match('/^fr/i', $dirtmp['name'])) {
+						continue;	// We discard fr_* languages
+					}
+					if (preg_match('/^es/i', $dirtmp['name'])) {
+						continue;	// We discard es_* languages
+					}
+					if (preg_match('/ca_ES/i', $dirtmp['name'])) {
+						continue;	// We discard es_CA language
+					}
+					if (preg_match('/pt_BR/i', $dirtmp['name'])) {
+						continue;	// We discard pt_BR language
+					}
+					if (preg_match('/nl_BE/i', $dirtmp['name'])) {
+						continue;  // We discard nl_BE language
+					}
+					if (preg_match('/^\./i', $dirtmp['name'])) {
+						continue;	// We discard files .*
+					}
+					if (preg_match('/^CVS/i', $dirtmp['name'])) {
+						continue;	// We discard CVS
+					}
 					$targetlangs[]=$dirtmp['name'];
 				}
 				//var_dump($targetlangs);
 			}
 
 			// Process translation of source file for each target languages
-			foreach ($targetlangs as $my_destlang)
-			{
+			foreach ($targetlangs as $my_destlang) {
 				$this->_translatedFiles = array();
 
 				$destPath = $this->_langDir.$my_destlang.self::DIR_SEPARATOR.$file;
 				// Check destination file presence
-				if (! file_exists($destPath))
-				{
+				if (! file_exists($destPath)) {
 					// No file present, we generate file
 					echo "File not found: " . $destPath . ". We generate it.<br>\n";
 					$this->createTranslationFile($destPath, $my_destlang);
-				}
-				else {
+				} else {
 					echo "Updating file: " . $destPath . "<br>\n";
 				}
 
 				// Translate lines
 				$fileContentDest = file($destPath, FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
 				$newlines=0;
-				foreach ($fileContent as $line){
+				foreach ($fileContent as $line) {
 					$key = $this->getLineKey($line);
 					$value = $this->getLineValue($line);
-					if ($key && $value)
-					{
+					if ($key && $value) {
 						$newlines+=$this->translateFileLine($fileContentDest, $file, $key, $value, $my_destlang);
 					}
 				}
@@ -159,8 +172,7 @@ class autoTranslator
 	{
 		$this->_time_end = date('Y-m-d H:i:s');
 
-		if (isset($this->_translatedFiles[$file]) && count($this->_translatedFiles[$file])>0)
-		{
+		if (isset($this->_translatedFiles[$file]) && count($this->_translatedFiles[$file])>0) {
 			$fp = fopen($destPath, 'a');
 			fwrite($fp, "\n");
 			fwrite($fp, "\n");
@@ -213,27 +225,31 @@ class autoTranslator
 			$destValue = $this->getLineValue($line);
 			// If translated return
 			//print "destKey=".$destKey."\n";
-			if ( trim($destKey) == trim($key) )
-			{	// Found already existing translation (key already exits in dest file)
+			if (trim($destKey) == trim($key)) {	// Found already existing translation (key already exits in dest file)
 				return 0;
 			}
 		}
 
 		if ($key == 'CHARSET') {
-            $val=$this->_outputpagecode;
-        } elseif (preg_match('/^Format/', $key)) {
-            $val=$value;
-        } elseif ($value=='-') {
-            $val=$value;
-        } else {
+			$val=$this->_outputpagecode;
+		} elseif (preg_match('/^Format/', $key)) {
+			$val=$value;
+		} elseif ($value=='-') {
+			$val=$value;
+		} else {
 			// If not translated then translate
-			if ($this->_outputpagecode == 'UTF-8') $val=$this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2));
-			else $val=utf8_decode($this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2)));
+			if ($this->_outputpagecode == 'UTF-8') {
+				$val=$this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2));
+			} else {
+				$val=utf8_decode($this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2)));
+			}
 		}
 
 		$val=trim($val);
 
-		if (empty($val)) return 0;
+		if (empty($val)) {
+			return 0;
+		}
 
 		$this->_translatedFiles[$file][] = $key . '=' . $val ;
 		return 1;
@@ -293,9 +309,13 @@ class autoTranslator
 	{
 		// We want to be sure that src_lang and dest_lang are using 2 chars only
 		$tmp=explode('_', $src_lang);
-		if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) $src_lang=$tmp[0];
+		if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) {
+			$src_lang=$tmp[0];
+		}
 		$tmp=explode('_', $dest_lang);
-		if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) $dest_lang=$tmp[0];
+		if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) {
+			$dest_lang=$tmp[0];
+		}
 
 		//setting language pair
 		$lang_pair = $src_lang.'|'.$dest_lang;
@@ -306,17 +326,16 @@ class autoTranslator
 		// Define GET URL v1
 		//$url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=".urlencode($src_text_to_translate)."&langpair=".urlencode($lang_pair);
 		// Example: http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=Setup%20area&langpair=en_US|fr_FR
-        // Define GET URL v2
+		// Define GET URL v2
 		$url = "https://www.googleapis.com/language/translate/v2?key=".$this->_apikey."&q=".urlencode($src_text_to_translate)."&source=".urlencode($src_lang)."&target=".urlencode($dest_lang);
 		// Example: https://www.googleapis.com/language/translate/v2?key=_apikey&q=Setup%20area&source=en_US&target=fr_FR
 
 		// Send request
 		//print "Url to translate: ".$url."\n";
 
-		if (! function_exists("curl_init"))
-		{
-		      print "Error, your PHP does not support curl functions.\n";
-		      die();
+		if (! function_exists("curl_init")) {
+			  print "Error, your PHP does not support curl functions.\n";
+			  die();
 		}
 
 		$ch = curl_init();
@@ -331,9 +350,8 @@ class autoTranslator
 		$json = json_decode($body, true);
 
 		if ((! empty($json['responseStatus']) && $json['responseStatus'] != 200)
-		|| count($json['data']['translations']) == 0)
-		{
-		    print "Error: ".$json['responseStatus']." ".$url."\n";
+		|| count($json['data']['translations']) == 0) {
+			print "Error: ".$json['responseStatus']." ".$url."\n";
 			return false;
 		}
 
@@ -345,5 +363,5 @@ class autoTranslator
 		//print "OK ".join('',$src_texts).' => '.$rep."\n";
 
 		return $rep;
-    }
+	}
 }

+ 10 - 14
dev/translation/autotranslator.php

@@ -32,8 +32,8 @@ $path=dirname(__FILE__).'/';
 
 // Test if batch mode
 if (substr($sapi_type, 0, 3) == 'cgi') {
-    echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
-    exit;
+	echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
+	exit;
 }
 
 // Include Dolibarr environment
@@ -56,10 +56,10 @@ $dir=DOL_DOCUMENT_ROOT."/langs";
 
 // Check parameters
 if (! isset($argv[3])) {
-    print "Usage:   ".$script_file."  lang_code_src lang_code_dest|all APIKEY [langfile.lang]\n";
-    print "Example: ".$script_file."  en_US         pt_PT              123456\n";
-    print "Rem:     lang_code to use can be found on https://translate.google.com\n";
-    exit;
+	print "Usage:   ".$script_file."  lang_code_src lang_code_dest|all APIKEY [langfile.lang]\n";
+	print "Example: ".$script_file."  en_US         pt_PT              123456\n";
+	print "Rem:     lang_code to use can be found on https://translate.google.com\n";
+	exit;
 }
 
 // Show parameters
@@ -67,21 +67,17 @@ print 'Argument 1='.$argv[1]."\n";
 print 'Argument 2='.$argv[2]."\n";
 print 'Argument 3='.$argv[3]."\n";
 $file='';
-if (isset($argv[4]))
-{
+if (isset($argv[4])) {
 	$file=$argv[4];
 	print 'Argument 4='.$argv[4]."\n";
 }
 print 'Files will be generated/updated in directory '.$dir."\n";
 
-if ($argv[2] != 'all')
-{
-	if (! is_dir($dir.'/'.$argv[2]))
-	{
+if ($argv[2] != 'all') {
+	if (! is_dir($dir.'/'.$argv[2])) {
 		print 'Create directory '.$dir.'/'.$argv[2]."\n";
 		$result=mkdir($dir.'/'.$argv[2]);
-		if (! $result)
-		{
+		if (! $result) {
 			$db->close();
 			return -1;
 		}

+ 401 - 198
dev/translation/sanity_check_en_langfiles.php

@@ -25,18 +25,16 @@ $path=dirname(__FILE__).'/';
 $web=0;
 
 // Test if batch mode
-if (substr($sapi_type, 0, 3) == 'cgi')
-{
-    $web=1;
+if (substr($sapi_type, 0, 3) == 'cgi') {
+	$web=1;
 }
 
 
-if ($web)
-{
-    echo "<html>";
-    echo "<head>";
+if ($web) {
+	echo "<html>";
+	echo "<head>";
 
-    echo "<STYLE type=\"text/css\">
+	echo "<STYLE type=\"text/css\">
 
     table {
     	background: #f5f5f5;
@@ -83,13 +81,17 @@ if ($web)
 
     </STYLE>";
 
-    echo "<body>";
+	echo "<body>";
 }
 
 echo "If you call this with argument \"unused=true\" it searches for the translation strings that exist in en_US but are never used.\n";
-if ($web) print "<br>";
+if ($web) {
+	print "<br>";
+}
 echo "IMPORTANT: that can take quite a lot of time (up to 10 minutes), you need to tune the max_execution_time on your php.ini accordingly.\n";
-if ($web) print "<br>";
+if ($web) {
+	print "<br>";
+}
 
 
 
@@ -105,8 +107,7 @@ $workdir = $htdocs."langs/en_US/";
 
 
 $files = scandir($workdir);
-if (empty($files))
-{
+if (empty($files)) {
 	echo "Can't scan workdir = ".$workdir;
 	exit;
 }
@@ -115,18 +116,17 @@ $dups=array();
 $exludefiles = array('.','..','README');
 $files = array_diff($files, $exludefiles);
 // To force a file: $files=array('myfile.lang');
-if (isset($argv[2]))
-{
-    $files = array($argv[2]);
+if (isset($argv[2])) {
+	$files = array($argv[2]);
 }
 $langstrings_3d = array();
 $langstrings_full = array();
-foreach ($files AS $file) {
+foreach ($files as $file) {
 	$path_file = pathinfo($file);
 	// we're only interested in .lang files
 	if ($path_file['extension']=='lang') {
 		$content = file($workdir.$file);
-		foreach ($content AS $line => $row) {
+		foreach ($content as $line => $row) {
 			// don't want comment lines
 			if (substr($row, 0, 1) !== '#') {
 				// don't want lines without the separator (why should those even be here, anyway...)
@@ -142,29 +142,29 @@ foreach ($files AS $file) {
 	}
 }
 
-foreach ($langstrings_3d AS $filename => $file)
-{
-	foreach ($file AS $linenum => $value)
-	{
+foreach ($langstrings_3d as $filename => $file) {
+	foreach ($file as $linenum => $value) {
 		$keys = array_keys($langstrings_full, $value);
-		if (count($keys)>1)
-		{
-			foreach ($keys AS $key) {
+		if (count($keys)>1) {
+			foreach ($keys as $key) {
 				$dups[$value][$filename][$linenum] = trim($langstrings_3dtrans[$filename][$linenum]);
 			}
 		}
 	}
 }
 
-if ($web) print "<h2>";
+if ($web) {
+	print "<h2>";
+}
 print "Duplicate strings in lang files in $workdir - ".count($dups)." found\n";
-if ($web) print "</h2>";
+if ($web) {
+	print "</h2>";
+}
 
-if ($web)
-{
-    echo '<table border_bottom="1">'."\n";
-    echo "<thead><tr><th align=\"center\">#</th><th>String</th><th>File and lines</th></thead>\n";
-    echo "<tbody>\n";
+if ($web) {
+	echo '<table border_bottom="1">'."\n";
+	echo "<thead><tr><th align=\"center\">#</th><th>String</th><th>File and lines</th></thead>\n";
+	echo "<tbody>\n";
 }
 
 $sduplicateinsamefile='';
@@ -173,216 +173,419 @@ $sininstallandadmin='';
 $sother='';
 
 $count = 0;
-foreach ($dups as $string => $pages)
-{
+foreach ($dups as $string => $pages) {
 	$count++;
 	$s='';
 
 	// Keyword $string
-	if ($web) $s.="<tr>";
-	if ($web) $s.="<td align=\"center\">";
-	if ($web) $s.=$count;
-	if ($web) $s.="</td>";
-	if ($web) $s.="<td>";
+	if ($web) {
+		$s.="<tr>";
+	}
+	if ($web) {
+		$s.="<td align=\"center\">";
+	}
+	if ($web) {
+		$s.=$count;
+	}
+	if ($web) {
+		$s.="</td>";
+	}
+	if ($web) {
+		$s.="<td>";
+	}
 	$s.=$string;
-	if ($web) $s.="</td>";
-	if ($web) $s.="<td>";
-	if (! $web) $s.= ' : ';
+	if ($web) {
+		$s.="</td>";
+	}
+	if ($web) {
+		$s.="<td>";
+	}
+	if (! $web) {
+		$s.= ' : ';
+	}
 
 	// Loop on each files keyword was found
-    $duplicateinsamefile=0;
+	$duplicateinsamefile=0;
 	$inmain=0;
-    $inadmin=0;
-	foreach ($pages AS $file => $lines)
-	{
-        if ($file == 'main.lang') { $inmain=1; $inadmin=0; }
-        if ($file == 'admin.lang' && ! $inmain) { $inadmin=1; }
+	$inadmin=0;
+	foreach ($pages as $file => $lines) {
+		if ($file == 'main.lang') {
+			$inmain=1; $inadmin=0;
+		}
+		if ($file == 'admin.lang' && ! $inmain) {
+			$inadmin=1;
+		}
 
-	    $s.=$file." ";
+		$s.=$file." ";
 
-	    // Loop on each line keword was found into file.
-	    $listoffilesforthisentry=array();
-	    foreach ($lines as $line => $translatedvalue)
-		{
-            if (! empty($listoffilesforthisentry[$file])) $duplicateinsamefile=1;
-            $listoffilesforthisentry[$file]=1;
+		// Loop on each line keword was found into file.
+		$listoffilesforthisentry=array();
+		foreach ($lines as $line => $translatedvalue) {
+			if (! empty($listoffilesforthisentry[$file])) {
+				$duplicateinsamefile=1;
+			}
+			$listoffilesforthisentry[$file]=1;
 
 			$s.= "(".$line." - ".htmlentities($translatedvalue).") ";
 		}
-		if ($web) $s.="<br>";
+		if ($web) {
+			$s.="<br>";
+		}
+	}
+	if ($web) {
+		$s.="</td></tr>";
 	}
-	if ($web) $s.="</td></tr>";
 	$s.="\n";
 
-	if ($duplicateinsamefile) $sduplicateinsamefile .= $s;
-	elseif ($inmain) $sinmainandother .= $s;
-	elseif ($inadmin) $sininstallandadmin .= $s;
-	else $sother .= $s;
+	if ($duplicateinsamefile) {
+		$sduplicateinsamefile .= $s;
+	} elseif ($inmain) {
+		$sinmainandother .= $s;
+	} elseif ($inadmin) {
+		$sininstallandadmin .= $s;
+	} else {
+		$sother .= $s;
+	}
 }
 
-if (! $web) print "\n***** Entries duplicated in same file\n";
+if (! $web) {
+	print "\n***** Entries duplicated in same file\n";
+}
 print $sduplicateinsamefile;
-if (! $web && empty($sduplicateinsamefile)) print "None\n";
-if (! $web) print "\n";
+if (! $web && empty($sduplicateinsamefile)) {
+	print "None\n";
+}
+if (! $web) {
+	print "\n";
+}
 
-if (! $web) print "***** Entries in main and another (keep only entry in main)\n";
+if (! $web) {
+	print "***** Entries in main and another (keep only entry in main)\n";
+}
 print $sinmainandother;
-if (! $web && empty($sinmainandother)) print "None\n";
-if (! $web) print "\n";
+if (! $web && empty($sinmainandother)) {
+	print "None\n";
+}
+if (! $web) {
+	print "\n";
+}
 
-if (! $web) print "***** Entries in admin and another\n";
+if (! $web) {
+	print "***** Entries in admin and another\n";
+}
 print $sininstallandadmin;
-if (! $web && empty($sininstallandadmin)) print "None\n";
-if (! $web) print "\n";
+if (! $web && empty($sininstallandadmin)) {
+	print "None\n";
+}
+if (! $web) {
+	print "\n";
+}
 
-if (! $web) print "***** Other\n";
+if (! $web) {
+	print "***** Other\n";
+}
 print $sother;
-if (! $web && empty($sother)) print "None\n";
-if (! $web) print "\n";
+if (! $web && empty($sother)) {
+	print "None\n";
+}
+if (! $web) {
+	print "\n";
+}
 
-if ($web)
-{
-    echo "</tbody>\n";
-    echo "</table>\n";
+if ($web) {
+	echo "</tbody>\n";
+	echo "</table>\n";
 }
 
 
 // STEP 2 - Search key not used
 
-if ((! empty($_REQUEST['unused']) && $_REQUEST['unused'] == 'true') || (isset($argv[1]) && $argv[1]=='unused=true'))
-{
-    print "***** Strings in en_US that are never used:\n";
-
-    $unused=array();
-	foreach ($langstrings_dist AS $value => $line)
-	{
-    	$qualifiedforclean=1;
-	    // Check if we must keep this key to be into file for removal
-	    if (preg_match('/^Module\d+/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^Permission\d+/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^PermissionAdvanced\d+/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^ProfId\d+/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^Delays_/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^BarcodeDesc/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^Extrafield/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^LocalTax/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^Country/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^Civility/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^Currency/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^DemandReasonTypeSRC/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^PaperFormat/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^Duration/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^AmountLT/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^TotalLT/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^Month/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^MonthShort/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^Day\d/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^Short/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^ExportDataset_/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^ImportDataset_/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^ActionAC_/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^TypeLocaltax/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^StatusProspect/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^PL_/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^TE_/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^JuridicalStatus/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^CalcMode/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^newLT/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^LT[0-9]/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^TypeContact_contrat_/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^ErrorPriceExpression/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^Language_/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^DescADHERENT_/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^SubmitTranslation/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^ModuleCompanyCode/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/InDolibarr$/', $value)) $qualifiedforclean=0;
-	    // admin.lang
-	    if (preg_match('/^DAV_ALLOW_PUBLIC_DIR/i', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^DAV_ALLOW_ECM_DIR/i', $value)) $qualifiedforclean=0;
-	    // boxes.lang
-	    if (preg_match('/^BoxTitleLast/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^BoxTitleLatest/', $value)) $qualifiedforclean=0;
-	    // install.lang
-	    if (preg_match('/^KeepDefaultValues/', $value)) $qualifiedforclean=0;
+if ((! empty($_REQUEST['unused']) && $_REQUEST['unused'] == 'true') || (isset($argv[1]) && $argv[1]=='unused=true')) {
+	print "***** Strings in en_US that are never used:\n";
+
+	$unused=array();
+	foreach ($langstrings_dist as $value => $line) {
+		$qualifiedforclean=1;
+		// Check if we must keep this key to be into file for removal
+		if (preg_match('/^Module\d+/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^Permission\d+/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^PermissionAdvanced\d+/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^ProfId\d+/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^Delays_/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^BarcodeDesc/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^Extrafield/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^LocalTax/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^Country/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^Civility/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^Currency/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^DemandReasonTypeSRC/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^PaperFormat/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^Duration/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^AmountLT/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^TotalLT/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^Month/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^MonthShort/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^Day\d/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^Short/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^ExportDataset_/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^ImportDataset_/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^ActionAC_/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^TypeLocaltax/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^StatusProspect/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^PL_/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^TE_/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^JuridicalStatus/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^CalcMode/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^newLT/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^LT[0-9]/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^TypeContact_contrat_/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^ErrorPriceExpression/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^Language_/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^DescADHERENT_/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^SubmitTranslation/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^ModuleCompanyCode/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/InDolibarr$/', $value)) {
+			$qualifiedforclean=0;
+		}
+		// admin.lang
+		if (preg_match('/^DAV_ALLOW_PUBLIC_DIR/i', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^DAV_ALLOW_ECM_DIR/i', $value)) {
+			$qualifiedforclean=0;
+		}
+		// boxes.lang
+		if (preg_match('/^BoxTitleLast/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^BoxTitleLatest/', $value)) {
+			$qualifiedforclean=0;
+		}
+		// install.lang
+		if (preg_match('/^KeepDefaultValues/', $value)) {
+			$qualifiedforclean=0;
+		}
 		// mail.lang
-	    if (preg_match('/MailingModuleDesc/i', $value)) $qualifiedforclean=0;
-	    // main.lang
-	    if (preg_match('/^Duration/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^FormatDate/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^DateFormat/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^.b$/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^.*Bytes$/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^NoteSomeFeaturesAreDisabled/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^(DoTest|Under|Limits|Cards|CurrentValue|DateLimit|DateAndHour|NbOfLines|NbOfObjects|NbOfReferes|TotalTTCShort|VATs)/', $value)) $qualifiedforclean=0;
+		if (preg_match('/MailingModuleDesc/i', $value)) {
+			$qualifiedforclean=0;
+		}
+		// main.lang
+		if (preg_match('/^Duration/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^FormatDate/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^DateFormat/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^.b$/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^.*Bytes$/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^NoteSomeFeaturesAreDisabled/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^(DoTest|Under|Limits|Cards|CurrentValue|DateLimit|DateAndHour|NbOfLines|NbOfObjects|NbOfReferes|TotalTTCShort|VATs)/', $value)) {
+			$qualifiedforclean=0;
+		}
 		// modulebuilder
-		if (preg_match('/^ModuleBuilderDesc/', $value)) $qualifiedforclean=0;
-	    // orders
-	    if (preg_match('/^OrderSource/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^TypeContact_/', $value)) $qualifiedforclean=0;
-        // other.lang
-	    if (preg_match('/^Notify_/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^PredefinedMail/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^DemoCompany/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^WeightUnit/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^LengthUnit/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^SurfaceUnit/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^VolumeUnit/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^SizeUnit/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/^EMailText/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/ById$/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/ByLogin$/', $value)) $qualifiedforclean=0;
-	    // printing
-	    if (preg_match('/PrintingDriverDesc$/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/PrintTestDesc$/', $value)) $qualifiedforclean=0;
-	    // products
-	    if (preg_match('/GlobalVariableUpdaterType$/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/GlobalVariableUpdaterHelp$/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/OppStatus/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/AvailabilityType/', $value)) $qualifiedforclean=0;
-	    if (preg_match('/CardProduct/', $value)) $qualifiedforclean=0;
-
-	    if (preg_match('/sms/i', $value)) $qualifiedforclean=0;
-	    if (preg_match('/TF_/i', $value)) $qualifiedforclean=0;
-	    if (preg_match('/WithBankUsing/i', $value)) $qualifiedforclean=0;
-	    if (preg_match('/descWORKFLOW_/i', $value)) $qualifiedforclean=0;
-
-	    if (! $qualifiedforclean)
-	    {
-            continue;
-	    }
-
-	    //$search = '\'trans("'.$value.'")\'';
-	    $search = '-e "\''.$value.'\'" -e \'"'.$value.'"\' -e "('.$value.')" -e "('.$value.',"';
+		if (preg_match('/^ModuleBuilderDesc/', $value)) {
+			$qualifiedforclean=0;
+		}
+		// orders
+		if (preg_match('/^OrderSource/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^TypeContact_/', $value)) {
+			$qualifiedforclean=0;
+		}
+		// other.lang
+		if (preg_match('/^Notify_/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^PredefinedMail/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^DemoCompany/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^WeightUnit/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^LengthUnit/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^SurfaceUnit/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^VolumeUnit/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^SizeUnit/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/^EMailText/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/ById$/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/ByLogin$/', $value)) {
+			$qualifiedforclean=0;
+		}
+		// printing
+		if (preg_match('/PrintingDriverDesc$/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/PrintTestDesc$/', $value)) {
+			$qualifiedforclean=0;
+		}
+		// products
+		if (preg_match('/GlobalVariableUpdaterType$/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/GlobalVariableUpdaterHelp$/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/OppStatus/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/AvailabilityType/', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/CardProduct/', $value)) {
+			$qualifiedforclean=0;
+		}
+
+		if (preg_match('/sms/i', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/TF_/i', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/WithBankUsing/i', $value)) {
+			$qualifiedforclean=0;
+		}
+		if (preg_match('/descWORKFLOW_/i', $value)) {
+			$qualifiedforclean=0;
+		}
+
+		if (! $qualifiedforclean) {
+			continue;
+		}
+
+		//$search = '\'trans("'.$value.'")\'';
+		$search = '-e "\''.$value.'\'" -e \'"'.$value.'"\' -e "('.$value.')" -e "('.$value.',"';
 		$string =  'grep -R -m 1 -F --exclude=includes/* --include=*.php '.$search.' '.$htdocs.'* '.$scripts.'*';
 		//print $string."<br>\n";
 		exec($string, $output);
 		if (empty($output)) {
-   			$unused[$value] = $line;
-       		echo $line;        // $trad contains the \n
-		}
-		else {
-		    unset($output);
-		    //print 'X'.$output.'Y';
+			$unused[$value] = $line;
+			echo $line;        // $trad contains the \n
+		} else {
+			unset($output);
+			//print 'X'.$output.'Y';
 		}
 	}
 
-	if (empty($unused)) print "No string not used found.\n";
-	else {
-        $filetosave='/tmp/'.($argv[2]?$argv[2]:"").'notused.lang';
-        print "Strings in en_US that are never used are saved into file ".$filetosave.":\n";
-        file_put_contents($filetosave, implode("", $unused));
-        print "To remove from original file, run command :\n";
-        if (($argv[2]?$argv[2]:"")) print 'cd htdocs/langs/en_US; mv '.($argv[2]?$argv[2]:"")." ".($argv[2]?$argv[2]:"").".tmp; ";
-        print "diff ".($argv[2]?$argv[2]:"").".tmp ".$filetosave." | grep \< | cut  -b 3- > ".($argv[2]?$argv[2]:"");
-        if (($argv[2]?$argv[2]:"")) print "; rm ".($argv[2]?$argv[2]:"").".tmp;\n";
+	if (empty($unused)) {
+		print "No string not used found.\n";
+	} else {
+		$filetosave='/tmp/'.($argv[2]?$argv[2]:"").'notused.lang';
+		print "Strings in en_US that are never used are saved into file ".$filetosave.":\n";
+		file_put_contents($filetosave, implode("", $unused));
+		print "To remove from original file, run command :\n";
+		if (($argv[2]?$argv[2]:"")) {
+			print 'cd htdocs/langs/en_US; mv '.($argv[2]?$argv[2]:"")." ".($argv[2]?$argv[2]:"").".tmp; ";
+		}
+		print "diff ".($argv[2]?$argv[2]:"").".tmp ".$filetosave." | grep \< | cut  -b 3- > ".($argv[2]?$argv[2]:"");
+		if (($argv[2]?$argv[2]:"")) {
+			print "; rm ".($argv[2]?$argv[2]:"").".tmp;\n";
+		}
 	}
 }
 
 echo "\n";
-if ($web)
-{
-    echo "</body>\n";
-    echo "</html>\n";
+if ($web) {
+	echo "</body>\n";
+	echo "</html>\n";
 }
 
 exit;

+ 42 - 62
dev/translation/strip_language_file.php

@@ -63,8 +63,7 @@ $lSecondary = isset($argv[2])?$argv[2]:'';
 $lEnglish = 'en_US';
 $filesToProcess = isset($argv[3])?$argv[3]:'';
 
-if (empty($lPrimary) || empty($lSecondary) || empty($filesToProcess))
-{
+if (empty($lPrimary) || empty($lSecondary) || empty($filesToProcess)) {
 	$rc = 1;
 	$msg = '***** Script to clean language files *****'."\n";
 	$msg.= 'Usage: ./dev/translation/strip_language_file.php xx_XX xx_YY [file.lang|all]'."\n";
@@ -77,8 +76,7 @@ $aSecondary = array();
 $aEnglish = array();
 
 // Define array $filesToProcess
-if ($filesToProcess == 'all')
-{
+if ($filesToProcess == 'all') {
 	$dir = new DirectoryIterator('htdocs/langs/'.$lPrimary);
 	while ($dir->valid()) {
 		if (!$dir->isDot() && $dir->isFile() && ! preg_match('/^\./', $dir->getFilename())) {
@@ -87,15 +85,15 @@ if ($filesToProcess == 'all')
 		$dir->next();
 	}
 	$filesToProcess=$files;
+} else {
+	$filesToProcess=explode(',', $filesToProcess);
 }
-else $filesToProcess=explode(',', $filesToProcess);
 
 // Arguments should be OK here.
 
 
 // Loop on each file
-foreach ($filesToProcess as $fileToProcess)
-{
+foreach ($filesToProcess as $fileToProcess) {
 	$lPrimaryFile = 'htdocs/langs/'.$lPrimary.'/'.$fileToProcess;
 	$lSecondaryFile = 'htdocs/langs/'.$lSecondary.'/'.$fileToProcess;
 	$lEnglishFile = 'htdocs/langs/'.$lEnglish.'/'.$fileToProcess;
@@ -103,21 +101,21 @@ foreach ($filesToProcess as $fileToProcess)
 
 	print "---- Process language file ".$lSecondaryFile."\n";
 
-	if ( ! is_readable($lPrimaryFile) ) {
+	if (! is_readable($lPrimaryFile)) {
 		$rc = 2;
 		$msg = "Cannot read primary language file $lPrimaryFile.";
 		print $msg . " (rc=$rc).\n";
 		exit($rc);
 	}
 
-	if ( ! is_readable($lSecondaryFile) ) {
+	if (! is_readable($lSecondaryFile)) {
 		$rc = 3;
 		$msg = "Cannot read secondary language file $lSecondaryFile. We discard this file.";
 		print $msg . "\n";
 		continue;
 	}
 
-	if ( ! is_readable($lEnglishFile) ) {
+	if (! is_readable($lEnglishFile)) {
 		$rc = 3;
 		$msg = "Cannot read english language file $lEnglishFile. We discard this file.";
 		print $msg . "\n";
@@ -126,25 +124,23 @@ foreach ($filesToProcess as $fileToProcess)
 
 	// Start reading and parsing Secondary
 
-	if ( $handle = fopen($lSecondaryFile, 'r') )
-	{
+	if ($handle = fopen($lSecondaryFile, 'r')) {
 		print "Read Secondary File $lSecondaryFile:\n";
 		$cnt = 0;
-		while (($line = fgets($handle)) !== false)
-		{
+		while (($line = fgets($handle)) !== false) {
 			$cnt++;
 
 			// strip comments
-			if ( preg_match("/^\w*#/", $line) ) {
+			if (preg_match("/^\w*#/", $line)) {
 				continue;
 			}
 			// strip empty lines
-			if ( preg_match("/^\w*$/", $line) ) {
+			if (preg_match("/^\w*$/", $line)) {
 				continue;
 			}
 
 			$a = mb_split('=', trim($line), 2);
-			if ( count($a) != 2 ) {
+			if (count($a) != 2) {
 				print "ERROR in file $lSecondaryFile, line $cnt: " . trim($line) . "\n";
 				continue;
 			}
@@ -152,29 +148,27 @@ foreach ($filesToProcess as $fileToProcess)
 			list($key, $value) = $a;
 
 			// key is redundant
-			if ( array_key_exists($key, $aSecondary) ) {
+			if (array_key_exists($key, $aSecondary)) {
 				print "Key $key is redundant in file $lSecondaryFile (line: $cnt).\n";
 				continue;
 			}
 
 			// String has no value
-			if ( $value == '' ) {
+			if ($value == '') {
 				print "Key $key has no value in file $lSecondaryFile (line: $cnt).\n";
 				continue;
 			}
 
 			$aSecondary[$key] = trim($value);
 		}
-		if ( ! feof($handle) )
-		{
+		if (! feof($handle)) {
 			$rc = 5;
 			$msg = "Unexpected fgets() fail";
 			print $msg . " (rc=$rc).\n";
 			exit($rc);
 		}
 		fclose($handle);
-	}
-	else {
+	} else {
 		$rc = 6;
 		$msg = "Cannot open file $lSecondaryFile";
 		print $msg . " (rc=$rc).\n";
@@ -184,25 +178,23 @@ foreach ($filesToProcess as $fileToProcess)
 
 	// Start reading and parsing English
 
-	if ( $handle = fopen($lEnglishFile, 'r') )
-	{
+	if ($handle = fopen($lEnglishFile, 'r')) {
 		print "Read English File $lEnglishFile:\n";
 		$cnt = 0;
-		while (($line = fgets($handle)) !== false)
-		{
+		while (($line = fgets($handle)) !== false) {
 			$cnt++;
 
 			// strip comments
-			if ( preg_match("/^\w*#/", $line) ) {
+			if (preg_match("/^\w*#/", $line)) {
 				continue;
 			}
 			// strip empty lines
-			if ( preg_match("/^\w*$/", $line) ) {
+			if (preg_match("/^\w*$/", $line)) {
 				continue;
 			}
 
 			$a = mb_split('=', trim($line), 2);
-			if ( count($a) != 2 ) {
+			if (count($a) != 2) {
 				print "ERROR in file $lEnglishFile, line $cnt: " . trim($line) . "\n";
 				continue;
 			}
@@ -210,29 +202,27 @@ foreach ($filesToProcess as $fileToProcess)
 			list($key, $value) = $a;
 
 			// key is redundant
-			if ( array_key_exists($key, $aEnglish) ) {
+			if (array_key_exists($key, $aEnglish)) {
 				print "Key $key is redundant in file $lEnglishFile (line: $cnt).\n";
 				continue;
 			}
 
 			// String has no value
-			if ( $value == '' ) {
+			if ($value == '') {
 				print "Key $key has no value in file $lEnglishFile (line: $cnt).\n";
 				continue;
 			}
 
 			$aEnglish[$key] = trim($value);
 		}
-		if ( ! feof($handle) )
-		{
+		if (! feof($handle)) {
 			$rc = 5;
 			$msg = "Unexpected fgets() fail";
 			print $msg . " (rc=$rc).\n";
 			exit($rc);
 		}
 		fclose($handle);
-	}
-	else {
+	} else {
 		$rc = 6;
 		$msg = "Cannot open file $lEnglishFile";
 		print $msg . " (rc=$rc).\n";
@@ -246,10 +236,8 @@ foreach ($filesToProcess as $fileToProcess)
 	$arrayofkeytoalwayskeep=array('DIRECTION','FONTFORPDF','FONTSIZEFORPDF','SeparatorDecimal','SeparatorThousand');
 
 
-	if ( $handle = fopen($lPrimaryFile, 'r') )
-	{
-		if ( ! $oh = fopen($output, 'w') )
-		{
+	if ($handle = fopen($lPrimaryFile, 'r')) {
+		if (! $oh = fopen($output, 'w')) {
 			print "ERROR in writing to file ".$output."\n";
 			exit;
 		}
@@ -259,21 +247,20 @@ foreach ($filesToProcess as $fileToProcess)
 		fwrite($oh, "# Dolibarr language file - Source file is en_US - ".(preg_replace('/\.lang$/', '', $fileToProcess))."\n");
 
 		$cnt = 0;
-		while (($line = fgets($handle)) !== false)
-		{
+		while (($line = fgets($handle)) !== false) {
 			$cnt++;
 
 			// strip comments
-			if ( preg_match("/^\w*#/", $line) ) {
+			if (preg_match("/^\w*#/", $line)) {
 				continue;
 			}
 			// strip empty lines
-			if ( preg_match("/^\w*$/", $line) ) {
+			if (preg_match("/^\w*$/", $line)) {
 				continue;
 			}
 
 			$a = mb_split('=', trim($line), 2);
-			if ( count($a) != 2 ) {
+			if (count($a) != 2) {
 				print "ERROR in file $lPrimaryFile, line $cnt: " . trim($line) . "\n";
 				continue;
 			}
@@ -281,17 +268,16 @@ foreach ($filesToProcess as $fileToProcess)
 			list($key, $value) = $a;
 
 			// key is redundant
-			if ( array_key_exists($key, $aPrimary) ) {
+			if (array_key_exists($key, $aPrimary)) {
 				print "Key $key is redundant in file $lPrimaryFile (line: $cnt) - Already found into ".$fileFirstFound[$key]." (line: ".$lineFirstFound[$key].").\n";
 				continue;
-			}
-			else {
+			} else {
 				$fileFirstFound[$key] = $fileToProcess;
 				$lineFirstFound[$key] = $cnt;
 			}
 
 			// String has no value
-			if ( $value == '' ) {
+			if ($value == '') {
 				print "Key $key has no value in file $lPrimaryFile (line: $cnt).\n";
 				continue;
 			}
@@ -305,28 +291,23 @@ foreach ($filesToProcess as $fileToProcess)
 			//print "Found primary key = ".$key."\n";
 
 			// Key not in other file
-			if (in_array($key, $arrayofkeytoalwayskeep) || preg_match('/^FormatDate/', $key) || preg_match('/^FormatHour/', $key))
-			{
+			if (in_array($key, $arrayofkeytoalwayskeep) || preg_match('/^FormatDate/', $key) || preg_match('/^FormatHour/', $key)) {
 				//print "Key $key is a key we always want to see into secondary file (line: $cnt).\n";
-			}
-			elseif ( ! array_key_exists($key, $aSecondary))
-			{
+			} elseif (! array_key_exists($key, $aSecondary)) {
 				//print "Key $key does NOT exist in secondary language (line: $cnt).\n";
 				continue;
 			}
 
 			// String exists in both files and value into alternative language differs from main language but also from english files
-			if (
-				(! empty($aSecondary[$key]) && $aSecondary[$key] != $aPrimary[$key]
-			    && ! empty($aEnglish[$key]) && $aSecondary[$key] != $aEnglish[$key])
+			if ((! empty($aSecondary[$key]) && $aSecondary[$key] != $aPrimary[$key]
+				&& ! empty($aEnglish[$key]) && $aSecondary[$key] != $aEnglish[$key])
 				|| in_array($key, $arrayofkeytoalwayskeep) || preg_match('/^FormatDate/', $key) || preg_match('/^FormatHour/', $key)
-				)
-			{
+				) {
 				//print "Key $key differs (aSecondary=".$aSecondary[$key].", aPrimary=".$aPrimary[$key].", aEnglish=".$aEnglish[$key].") so we add it into new secondary language (line: $cnt).\n";
 				fwrite($oh, $key."=".(empty($aSecondary[$key])?$aPrimary[$key]:$aSecondary[$key])."\n");
 			}
 		}
-		if ( ! feof($handle) ) {
+		if (! feof($handle)) {
 			$rc = 7;
 			$msg = "Unexpected fgets() fail";
 			print $msg . " (rc=$rc).\n";
@@ -334,8 +315,7 @@ foreach ($filesToProcess as $fileToProcess)
 		}
 		fclose($oh);
 		fclose($handle);
-	}
-	else {
+	} else {
 		$rc = 8;
 		$msg = "Cannot open file $lPrimaryFile";
 		print $msg . " (rc=$rc).\n";