Completed
Branch develop (7c46ac)
by
unknown
30:59
created

upgrade2.php ➔ migrate_user_photospath()   C

Complexity

Conditions 13
Paths 2

Size

Total Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
nc 2
nop 0
dl 0
loc 65
rs 6.0569
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2005       Marc Barilley / Ocebo   <[email protected]>
3
 * Copyright (C) 2005-2018  Laurent Destailleur     <[email protected]>
4
 * Copyright (C) 2005-2011  Regis Houssin           <[email protected]>
5
 * Copyright (C) 2010       Juanjo Menent           <[email protected]>
6
 * Copyright (C) 2015-2016  Raphaël Doursenaud      <[email protected]>
7
 *
8
 * This program is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20
 *
21
 * Upgrade2 scripts can be ran from command line with syntax:
22
 *
23
 * cd htdocs/install
24
 * php upgrade.php 3.4.0 3.5.0 [dirmodule|ignoredbversion]
25
 * php upgrade2.php 3.4.0 3.5.0 [MAIN_MODULE_NAME1_TO_ENABLE,MAIN_MODULE_NAME2_TO_ENABLE]
26
 *
27
 * And for final step:
28
 * php step5.php 3.4.0 3.5.0
29
 *
30
 * Return code is 0 if OK, >0 if error
31
 *
32
 * Note: To just enable a module from command line, use this syntax:
33
 * php upgrade2.php 0.0.0 0.0.0 [MAIN_MODULE_NAME1_TO_ENABLE,MAIN_MODULE_NAME2_TO_ENABLE]
34
 */
35
36
/**
37
 *	\file       htdocs/install/upgrade2.php
38
 *	\brief      Upgrade some data
39
 */
40
41
include_once 'inc.php';
42
if (! file_exists($conffile))
43
{
44
    print 'Error: Dolibarr config file was not found. This may means that Dolibarr is not installed yet. Please call the page "/install/index.php" instead of "/install/upgrade.php").';
45
}
46
require_once $conffile;
47
require_once $dolibarr_main_document_root . '/compta/facture/class/facture.class.php';
48
require_once $dolibarr_main_document_root . '/comm/propal/class/propal.class.php';
49
require_once $dolibarr_main_document_root . '/contrat/class/contrat.class.php';
50
require_once $dolibarr_main_document_root . '/commande/class/commande.class.php';
51
require_once $dolibarr_main_document_root . '/fourn/class/fournisseur.commande.class.php';
52
require_once $dolibarr_main_document_root . '/core/lib/price.lib.php';
53
require_once $dolibarr_main_document_root . '/core/class/menubase.class.php';
54
require_once $dolibarr_main_document_root . '/core/lib/files.lib.php';
55
56
global $langs;
57
58
$grant_query='';
59
$step = 2;
60
$error = 0;
61
62
63
// Cette page peut etre longue. On augmente le delai autorise.
64
// Ne fonctionne que si on est pas en safe_mode.
65
$err=error_reporting();
66
error_reporting(0);
67
@set_time_limit(300);
68
error_reporting($err);
69
70
$setuplang=GETPOST("selectlang",'aZ09',3)?GETPOST("selectlang",'aZ09',3):'auto';
71
$langs->setDefaultLang($setuplang);
72
$versionfrom=GETPOST("versionfrom",'alpha',3)?GETPOST("versionfrom",'alpha',3):(empty($argv[1])?'':$argv[1]);
73
$versionto=GETPOST("versionto",'alpha',3)?GETPOST("versionto",'alpha',3):(empty($argv[2])?'':$argv[2]);
74
$enablemodules=GETPOST("enablemodules",'alpha',3)?GETPOST("enablemodules",'alpha',3):(empty($argv[3])?'':$argv[3]);
75
76
$langs->loadLangs(array("admin", "install", "bills", "suppliers"));
77
78
if ($dolibarr_main_db_type == 'mysqli') $choix=1;
79
if ($dolibarr_main_db_type == 'pgsql')  $choix=2;
80
if ($dolibarr_main_db_type == 'mssql')  $choix=3;
81
82
83
dolibarr_install_syslog("--- upgrade2: entering upgrade2.php page ".$versionfrom." ".$versionto." ".$enablemodules);
84
if (! is_object($conf)) dolibarr_install_syslog("upgrade2: conf file not initialized", LOG_ERR);
85
86
87
88
/*
89
 * View
90
 */
91
92
if ((! $versionfrom || preg_match('/version/', $versionfrom)) && (! $versionto || preg_match('/version/', $versionto)))
93
{
94
	print 'Error: Parameter versionfrom or versionto missing or having a bad format.'."\n";
95
	print 'Upgrade must be ran from command line with parameters or called from page install/index.php (like a first install)'."\n";
96
	// Test if batch mode
97
	$sapi_type = php_sapi_name();
98
	$script_file = basename(__FILE__);
99
	$path=dirname(__FILE__).'/';
100
	if (substr($sapi_type, 0, 3) == 'cli')
101
	{
102
		print 'Syntax from command line: '.$script_file." x.y.z a.b.c [MAIN_MODULE_NAME1_TO_ENABLE,MAIN_MODULE_NAME2_TO_ENABLE...]\n";
103
	}
104
	exit;
105
}
106
107
pHeader('','step5',GETPOST('action','aZ09')?GETPOST('action','aZ09'):'upgrade','versionfrom='.$versionfrom.'&versionto='.$versionto);
108
109
110
if (! GETPOST('action','aZ09') || preg_match('/upgrade/i',GETPOST('action','aZ09')))
111
{
112
    print '<h3><img class="valigntextbottom" src="../theme/common/octicons/build/svg/database.svg" width="20" alt="Database"> '.$langs->trans('DataMigration').'</h3>';
113
114
    print '<table cellspacing="0" cellpadding="1" border="0" width="100%">';
115
116
    // If password is encoded, we decode it
117
    if (preg_match('/crypted:/i',$dolibarr_main_db_pass) || ! empty($dolibarr_main_db_encrypted_pass))
118
    {
119
        require_once $dolibarr_main_document_root.'/core/lib/security.lib.php';
120
        if (preg_match('/crypted:/i',$dolibarr_main_db_pass))
121
        {
122
            $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass);
123
            $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass);
124
            $dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass;	// We need to set this as it is used to know the password was initially crypted
125
        }
126
        else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass);
127
    }
128
129
    // $conf is already instancied inside inc.php
130
    $conf->db->type = $dolibarr_main_db_type;
131
    $conf->db->host = $dolibarr_main_db_host;
132
    $conf->db->port = $dolibarr_main_db_port;
133
    $conf->db->name = $dolibarr_main_db_name;
134
    $conf->db->user = $dolibarr_main_db_user;
135
    $conf->db->pass = $dolibarr_main_db_pass;
136
137
    $db=getDoliDBInstance($conf->db->type,$conf->db->host,$conf->db->user,$conf->db->pass,$conf->db->name,$conf->db->port);
138
139
    // Create the global $hookmanager object
140
    include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
141
    $hookmanager=new HookManager($db);
142
    $hookmanager->initHooks(array('upgrade'));
143
144
    if (!$db->connected)
145
    {
146
        print '<tr><td colspan="4">'.$langs->trans("ErrorFailedToConnectToDatabase",$conf->db->name).'</td><td align="right">'.$langs->trans('Error').'</td></tr>';
147
        dolibarr_install_syslog('upgrade2: failed to connect to database :' . $conf->db->name . ' on ' . $conf->db->host . ' for user ' . $conf->db->user, LOG_ERR);
148
        $error++;
149
    }
150
151
    if (! $error)
152
    {
153
        if($db->database_selected)
154
        {
155
            dolibarr_install_syslog('upgrade2: database connection successful :' . $dolibarr_main_db_name);
156
        }
157
        else
158
        {
159
            $error++;
160
        }
161
    }
162
163
    if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption=0;
164
    $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption;
165
    if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey='';
166
    $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey;
167
168
    // Chargement config
169
    if (! $error)
170
    {
171
    	$conf->setValues($db);
172
    	// Reset forced setup after the setValues
173
    	if (defined('SYSLOG_FILE')) $conf->global->SYSLOG_FILE=constant('SYSLOG_FILE');
174
    	$conf->global->MAIN_ENABLE_LOG_TO_HTML = 1;
175
    }
176
177
178
    /***************************************************************************************
179
     *
180
     * Migration des donnees
181
     *
182
     ***************************************************************************************/
183
    $db->begin();
184
185
    if (! $error)
186
    {
187
        // Current version is $conf->global->MAIN_VERSION_LAST_UPGRADE
188
        // Version to install is DOL_VERSION
189
        $dolibarrlastupgradeversionarray=preg_split('/[\.-]/',isset($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_UPGRADE:$conf->global->MAIN_VERSION_LAST_INSTALL);
190
191
        // Chaque action de migration doit renvoyer une ligne sur 4 colonnes avec
192
        // dans la 1ere colonne, la description de l'action a faire
193
        // dans la 4eme colonne, le texte 'OK' si fait ou 'AlreadyDone' si rien n'est fait ou 'Error'
194
195
        $versiontoarray=explode('.',$versionto);
196
        $versionranarray=explode('.',DOL_VERSION);
197
198
199
        // Force to execute this at begin to avoid the new core code into Dolibarr to be broken.
200
        $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN birth date';
201
        $db->query($sql, 1);
202
        $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN dateemployment date';
203
        $db->query($sql, 1);
204
        $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN dateemploymentend date';
205
        $db->query($sql, 1);
206
        $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN default_range integer';
207
        $db->query($sql, 1);
208
        $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN default_c_exp_tax_cat integer';
209
        $db->query($sql, 1);
210
        $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN langs varchar(24)';
211
        $db->query($sql, 1);
212
        $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN fieldcomputed text';
213
        $db->query($sql, 1);
214
        $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN fielddefault varchar(255)';
215
        $db->query($sql, 1);
216
        $sql = 'ALTER TABLE '.MAIN_DB_PREFIX."extrafields ADD COLUMN enabled varchar(255) DEFAULT '1'";
217
        $db->query($sql, 1);
218
        $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN help text';
219
        $db->query($sql, 1);
220
        $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user_rights ADD COLUMN entity integer DEFAULT 1 NOT NULL';
221
        $db->query($sql, 1);
222
223
224
        $afterversionarray=explode('.','2.0.0');
225
        $beforeversionarray=explode('.','2.7.9');
226
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
227
        {
228
            // Script pour V2 -> V2.1
229
            migrate_paiements($db,$langs,$conf);
230
231
            migrate_contracts_det($db,$langs,$conf);
232
233
            migrate_contracts_date1($db,$langs,$conf);
234
235
            migrate_contracts_date2($db,$langs,$conf);
236
237
            migrate_contracts_date3($db,$langs,$conf);
238
239
            migrate_contracts_open($db,$langs,$conf);
240
241
            migrate_modeles($db,$langs,$conf);
242
243
            migrate_price_propal($db,$langs,$conf);
244
245
            migrate_price_commande($db,$langs,$conf);
246
247
            migrate_price_commande_fournisseur($db,$langs,$conf);
248
249
            migrate_price_contrat($db,$langs,$conf);
250
251
            migrate_paiementfourn_facturefourn($db,$langs,$conf);
252
253
254
            // Script pour V2.1 -> V2.2
255
            migrate_paiements_orphelins_1($db,$langs,$conf);
256
257
            migrate_paiements_orphelins_2($db,$langs,$conf);
258
259
            migrate_links_transfert($db,$langs,$conf);
260
261
262
            // Script pour V2.2 -> V2.4
263
            migrate_commande_expedition($db,$langs,$conf);
264
265
            migrate_commande_livraison($db,$langs,$conf);
266
267
            migrate_detail_livraison($db,$langs,$conf);
268
269
270
            // Script pour V2.5 -> V2.6
271
            migrate_stocks($db,$langs,$conf);
272
273
274
            // Script pour V2.6 -> V2.7
275
            migrate_menus($db,$langs,$conf);
276
277
            migrate_commande_deliveryaddress($db,$langs,$conf);
278
279
            migrate_restore_missing_links($db,$langs,$conf);
280
281
            migrate_rename_directories($db,$langs,$conf,'/compta','/banque');
282
283
            migrate_rename_directories($db,$langs,$conf,'/societe','/mycompany');
284
        }
285
286
        // Script for 2.8
287
        $afterversionarray=explode('.','2.7.9');
288
        $beforeversionarray=explode('.','2.8.9');
289
        //print $versionto.' '.versioncompare($versiontoarray,$afterversionarray).' '.versioncompare($versiontoarray,$beforeversionarray);
290
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
291
        {
292
            migrate_price_facture($db,$langs,$conf);     // Code of this function works for 2.8+ because need a field tva_tx
293
294
            migrate_relationship_tables($db,$langs,$conf,'co_exp','fk_commande','commande','fk_expedition','shipping');
295
296
            migrate_relationship_tables($db,$langs,$conf,'pr_exp','fk_propal','propal','fk_expedition','shipping');
297
298
            migrate_relationship_tables($db,$langs,$conf,'pr_liv','fk_propal','propal','fk_livraison','delivery');
299
300
            migrate_relationship_tables($db,$langs,$conf,'co_liv','fk_commande','commande','fk_livraison','delivery');
301
302
            migrate_relationship_tables($db,$langs,$conf,'co_pr','fk_propale','propal','fk_commande','commande');
303
304
            migrate_relationship_tables($db,$langs,$conf,'fa_pr','fk_propal','propal','fk_facture','facture');
305
306
            migrate_relationship_tables($db,$langs,$conf,'co_fa','fk_commande','commande','fk_facture','facture');
307
308
            migrate_project_user_resp($db,$langs,$conf);
309
310
            migrate_project_task_actors($db,$langs,$conf);
311
        }
312
313
        // Script for 2.9
314
        $afterversionarray=explode('.','2.8.9');
315
        $beforeversionarray=explode('.','2.9.9');
316
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
317
        {
318
            migrate_project_task_time($db,$langs,$conf);
319
320
            migrate_customerorder_shipping($db,$langs,$conf);
321
322
            migrate_shipping_delivery($db,$langs,$conf);
323
324
            migrate_shipping_delivery2($db,$langs,$conf);
325
        }
326
327
        // Script for 3.0
328
        $afterversionarray=explode('.','2.9.9');
329
        $beforeversionarray=explode('.','3.0.9');
330
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
331
        {
332
            // No particular code
333
        }
334
335
        // Script for 3.1
336
        $afterversionarray=explode('.','3.0.9');
337
        $beforeversionarray=explode('.','3.1.9');
338
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
339
        {
340
            migrate_rename_directories($db,$langs,$conf,'/rss','/externalrss');
341
342
            migrate_actioncomm_element($db,$langs,$conf);
343
        }
344
345
        // Script for 3.2
346
        $afterversionarray=explode('.','3.1.9');
347
        $beforeversionarray=explode('.','3.2.9');
348
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
349
        {
350
            migrate_price_contrat($db,$langs,$conf);
351
352
        	migrate_mode_reglement($db,$langs,$conf);
353
354
        	migrate_clean_association($db,$langs,$conf);
0 ignored issues
show
Bug introduced by
The call to migrate_clean_association() misses a required argument $versionto.

This check looks for function calls that miss required arguments.

Loading history...
355
        }
356
357
        // Script for 3.3
358
        $afterversionarray=explode('.','3.2.9');
359
        $beforeversionarray=explode('.','3.3.9');
360
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
361
        {
362
        	migrate_categorie_association($db,$langs,$conf);
363
        }
364
365
		// Script for 3.4
366
		// No specific scripts
367
368
        // Tasks to do always and only into last targeted version
369
        $afterversionarray=explode('.','3.6.9');	// target is after this
370
        $beforeversionarray=explode('.','3.7.9');	// target is before this
371
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
372
        {
373
       	    migrate_event_assignement($db,$langs,$conf);
374
        }
375
376
        // Scripts for 3.9
377
        $afterversionarray=explode('.','3.7.9');
378
        $beforeversionarray=explode('.','3.8.9');
379
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
380
        {
381
        	// No particular code
382
        }
383
384
        // Scripts for 4.0
385
        $afterversionarray=explode('.','3.9.9');
386
        $beforeversionarray=explode('.','4.0.9');
387
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
388
        {
389
            migrate_rename_directories($db,$langs,$conf,'/fckeditor','/medias');
390
        }
391
392
        // Scripts for 5.0
393
        $afterversionarray=explode('.','4.0.9');
394
        $beforeversionarray=explode('.','5.0.9');
395
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
396
        {
397
            // Migrate to add entity value into llx_societe_remise
398
            migrate_remise_entity($db,$langs,$conf);
399
400
            // Migrate to add entity value into llx_societe_remise_except
401
            migrate_remise_except_entity($db,$langs,$conf);
402
        }
403
404
        // Scripts for 6.0
405
        $afterversionarray=explode('.','5.0.9');
406
        $beforeversionarray=explode('.','6.0.9');
407
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
408
        {
409
        	if (! empty($conf->multicompany->enabled))
410
        	{
411
        		global $multicompany_transverse_mode;
412
413
        		// Only if the transverse mode is not used
414
        		if (empty($multicompany_transverse_mode))
415
        		{
416
        			// Migrate to add entity value into llx_user_rights
417
        			migrate_user_rights_entity($db, $langs, $conf);
418
419
        			// Migrate to add entity value into llx_usergroup_rights
420
        			migrate_usergroup_rights_entity($db, $langs, $conf);
421
        		}
422
        	}
423
        }
424
425
        // Scripts for 7.0
426
        $afterversionarray=explode('.','6.0.9');
427
        $beforeversionarray=explode('.','7.0.9');
428
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
429
        {
430
            // Migrate contact association
431
        	migrate_event_assignement_contact($db,$langs,$conf);
432
433
        	migrate_reset_blocked_log($db,$langs,$conf);
434
        }
435
436
        // Scripts for 8.0
437
        $afterversionarray=explode('.','7.0.9');
438
        $beforeversionarray=explode('.','8.0.9');
439
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
440
        {
441
        	migrate_rename_directories($db,$langs,$conf,'/contracts','/contract');
442
        }
443
444
        // Scripts for 9.0
445
        $afterversionarray=explode('.','8.0.9');
446
        $beforeversionarray=explode('.','9.0.9');
447
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
448
        {
449
        	migrate_user_photospath();
450
        }
451
    }
452
453
	// Code executed only if migration is LAST ONE. Must always be done.
454
	if (versioncompare($versiontoarray,$versionranarray) >= 0 || versioncompare($versiontoarray,$versionranarray) <= -3)
455
	{
456
		// Reload modules (this must be always done and only into last targeted version, because code to reload module may need table structure of last version)
457
		$listofmodule=array(
458
			'MAIN_MODULE_ACCOUNTING'=>'newboxdefonly',
459
			'MAIN_MODULE_AGENDA'=>'newboxdefonly',
460
			'MAIN_MODULE_BARCODE'=>'newboxdefonly',
461
			'MAIN_MODULE_CRON'=>'newboxdefonly',
462
			'MAIN_MODULE_COMMANDE'=>'newboxdefonly',
463
			'MAIN_MODULE_DEPLACEMENT'=>'newboxdefonly',
464
			'MAIN_MODULE_DON'=>'newboxdefonly',
465
			'MAIN_MODULE_ECM'=>'newboxdefonly',
466
			'MAIN_MODULE_FACTURE'=>'newboxdefonly',
467
			'MAIN_MODULE_FOURNISSEUR'=>'newboxdefonly',
468
			'MAIN_MODULE_HOLIDAY'=>'newboxdefonly',
469
			'MAIN_MODULE_OPENSURVEY'=>'newboxdefonly',
470
			'MAIN_MODULE_PAYBOX'=>'newboxdefonly',
471
			'MAIN_MODULE_PRINTING'=>'newboxdefonly',
472
			'MAIN_MODULE_PRODUIT'=>'newboxdefonly',
473
			'MAIN_MODULE_SALARIES'=>'newboxdefonly',
474
			'MAIN_MODULE_SYSLOG'=>'newboxdefonly',
475
			'MAIN_MODULE_SOCIETE'=>'newboxdefonly',
476
			'MAIN_MODULE_SERVICE'=>'newboxdefonly',
477
			'MAIN_MODULE_USER'=>'newboxdefonly',		//This one must be always done and only into last targeted version)
478
			'MAIN_MODULE_VARIANTS'=>'newboxdefonly',
479
			'MAIN_MODULE_WEBSITE'=>'newboxdefonly',
480
		);
481
		migrate_reload_modules($db,$langs,$conf,$listofmodule);
482
483
		// Reload menus (this must be always and only into last targeted version)
484
		migrate_reload_menu($db,$langs,$conf,$versionto);
485
	}
486
487
    // Can force activation of some module during migration with parameter 'enablemodules=MAIN_MODULE_XXX,MAIN_MODULE_YYY,...'
488
    // In most cases (online install or upgrade) $enablemodules is empty. Can be forced when ran from command line.
489
    if (! $error && $enablemodules)
490
    {
491
        // Reload modules (this must be always done and only into last targeted version)
492
        $listofmodules=array();
493
        $enablemodules=preg_replace('/enablemodules=/','',$enablemodules);
494
        $tmplistofmodules=explode(',', $enablemodules);
495
        foreach($tmplistofmodules as $value)
496
        {
497
            $listofmodules[$value]='forceactivate';
498
        }
499
        migrate_reload_modules($db,$langs,$conf,$listofmodules,1);
500
    }
501
502
503
    // Can call a dedicated external upgrade process
504
    if (! $error)
505
    {
506
        $parameters=array('versionfrom'=>$versionfrom, 'versionto='.$versionto);
507
        $object=new stdClass();
508
        $action="upgrade";
509
        $reshook=$hookmanager->executeHooks('doUpgrade2',$parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
510
        if ($hookmanager->resNbOfHooks > 0)
511
        {
512
            if ($reshook < 0)
513
            {
514
                print '<tr><td colspan="4">';
515
                print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: ';
516
                print $hookmanager->error;
517
                print "<!-- (".$reshook.") -->";
518
                print '</td></tr>';
519
            }
520
            else
521
            {
522
                print '<tr><td colspan="4">';
523
                print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: OK';
524
                print "<!-- (".$reshook.") -->";
525
                print '</td></tr>';
526
            }
527
        }
528
        else
529
        {
530
            //if (! empty($conf->modules))
531
            if (! empty($conf->modules_parts['hooks']))     // If there is at least one module with one hook, we show message to say nothing was done
532
            {
533
                print '<tr><td colspan="4">';
534
                print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: '.$langs->trans("None");
535
                print '</td></tr>';
536
            }
537
        }
538
    }
539
540
    print '</table>';
541
542
    // We always commit.
543
    // Process is designed so we can run it several times whatever is situation.
544
    $db->commit();
545
    $db->close();
546
547
548
    // Copy directory medias
549
    $srcroot=DOL_DOCUMENT_ROOT.'/install/medias';
550
    $destroot=DOL_DATA_ROOT.'/medias';
551
    dolCopyDir($srcroot, $destroot, 0, 0);
552
553
554
    // Actions for all versions (no database change but delete some files and directories)
555
    migrate_delete_old_files($db, $langs, $conf);
556
    migrate_delete_old_dir($db, $langs, $conf);
557
    // Actions for all versions (no database change but create some directories)
558
    dol_mkdir(DOL_DATA_ROOT.'/bank');
559
    // Actions for all versions (no database change but rename some directories)
560
    migrate_rename_directories($db, $langs, $conf, '/banque/bordereau', '/bank/checkdeposits');
561
562
    print '<div><br>'.$langs->trans("MigrationFinished").'</div>';
563
}
564
else
565
{
566
    print '<div class="error">'.$langs->trans('ErrorWrongParameters').'</div>';
567
    $error++;
568
}
569
570
$ret=0;
571
if ($error && isset($argv[1])) $ret=1;
572
dolibarr_install_syslog("Exit ".$ret);
573
574
dolibarr_install_syslog("--- upgrade2: end");
575
pFooter($error?2:0,$setuplang);
576
577
if ($db->connected) $db->close();
578
579
// Return code if ran from command line
580
if ($ret) exit($ret);
581
582
583
584
/**
585
 * Reporte liens vers une facture de paiements sur table de jointure (lien n-n paiements factures)
586
 *
587
 * @param	DoliDB		$db		Database handler
588
 * @param	Translate	$langs	Object langs
589
 * @param	Conf		$conf	Object conf
590
 * @return	void
591
 */
592
function migrate_paiements($db,$langs,$conf)
593
{
594
    print '<tr><td colspan="4">';
595
596
    print '<br>';
597
    print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
598
599
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement","fk_facture");
600
    $obj = $db->fetch_object($result);
601
    if ($obj)
602
    {
603
        $sql = "SELECT p.rowid, p.fk_facture, p.amount";
604
        $sql .= " FROM ".MAIN_DB_PREFIX."paiement as p";
605
        $sql .= " WHERE p.fk_facture > 0";
606
607
        $resql = $db->query($sql);
608
609
        dolibarr_install_syslog("upgrade2::migrate_paiements");
610
        if ($resql)
611
        {
612
            $i = 0;
613
            $row = array();
614
            $num = $db->num_rows($resql);
615
616
            while ($i < $num)
617
            {
618
                $obj = $db->fetch_object($resql);
619
                $row[$i][0] = $obj->rowid ;
620
                $row[$i][1] = $obj->fk_facture;
621
                $row[$i][2] = $obj->amount;
622
                $i++;
623
            }
624
        }
625
        else
626
        {
627
            dol_print_error($db);
628
        }
629
630
        if ($num)
631
        {
632
            print $langs->trans('MigrationPaymentsNumberToUpdate', $num)."<br>\n";
0 ignored issues
show
Bug introduced by
The variable $num does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
633
            if ($db->begin())
634
            {
635
                $res = 0;
636
                $num=count($row);
0 ignored issues
show
Bug introduced by
The variable $row does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
637
                for ($i = 0; $i < $num; $i++)
638
                {
639
                    $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
640
                    $sql.= " VALUES (".$row[$i][1].",".$row[$i][0].",".$row[$i][2].")";
641
642
                    $res += $db->query($sql);
643
644
                    $sql = "UPDATE ".MAIN_DB_PREFIX."paiement SET fk_facture = 0 WHERE rowid = ".$row[$i][0];
645
646
                    $res += $db->query($sql);
647
648
                    print $langs->trans('MigrationProcessPaymentUpdate', $row[$i][0])."<br>\n";
649
                }
650
            }
651
652
            if ($res == (2 * count($row)))
0 ignored issues
show
Bug introduced by
The variable $res does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
653
            {
654
                $db->commit();
655
                print $langs->trans('MigrationSuccessfullUpdate')."<br>";
656
            }
657
            else
658
            {
659
                $db->rollback();
660
                print $langs->trans('MigrationUpdateFailed').'<br>';
661
            }
662
        }
663
        else
664
        {
665
            print $langs->trans('MigrationPaymentsNothingToUpdate')."<br>\n";
666
        }
667
    }
668
    else
669
    {
670
        print $langs->trans('MigrationPaymentsNothingToUpdate')."<br>\n";
671
    }
672
673
    print '</td></tr>';
674
}
675
676
/**
677
 * Corrige paiement orphelins (liens paumes suite a bugs)
678
 * Pour verifier s'il reste des orphelins:
679
 * select * from llx_paiement as p left join llx_paiement_facture as pf on pf.fk_paiement=p.rowid WHERE pf.rowid IS NULL AND (p.fk_facture = 0 OR p.fk_facture IS NULL)
680
 *
681
 * @param	DoliDB		$db		Database handler
682
 * @param	Translate	$langs	Object langs
683
 * @param	Conf		$conf	Object conf
684
 * @return	void
685
 */
686
function migrate_paiements_orphelins_1($db,$langs,$conf)
687
{
688
    print '<tr><td colspan="4">';
689
690
    print '<br>';
691
    print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
692
693
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement","fk_facture");
694
    $obj = $db->fetch_object($result);
695
    if ($obj)
696
    {
697
        // Tous les enregistrements qui sortent de cette requete devrait avoir un pere dans llx_paiement_facture
698
        $sql = "SELECT distinct p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,";
699
        $sql.= " bu2.url_id as socid";
700
        $sql.= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)";
701
        $sql.= " LEFT JOIN llx_paiement_facture as pf ON pf.fk_paiement = p.rowid";
702
        $sql.= " LEFT JOIN llx_bank_url as bu2 ON (bu.fk_bank=bu2.fk_bank AND bu2.type = 'company')";
703
        $sql.= " WHERE pf.rowid IS NULL AND (p.rowid=bu.url_id AND bu.type='payment') AND bu.fk_bank = b.rowid";
704
        $sql.= " AND b.rappro = 1";
705
        $sql.= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)";
706
707
        $resql = $db->query($sql);
708
709
        dolibarr_install_syslog("upgrade2::migrate_paiements_orphelins_1");
710
        $row = array();
711
        if ($resql)
712
        {
713
            $i = $j = 0;
714
            $num = $db->num_rows($resql);
715
716
            while ($i < $num)
717
            {
718
                $obj = $db->fetch_object($resql);
719
                if ($obj->pamount == $obj->bamount && $obj->socid)	// Pour etre sur d'avoir bon cas
720
                {
721
                    $row[$j]['paymentid'] = $obj->rowid ;		// paymentid
722
                    $row[$j]['pamount'] = $obj->pamount;
723
                    $row[$j]['fk_bank'] = $obj->fk_bank;
724
                    $row[$j]['bamount'] = $obj->bamount;
725
                    $row[$j]['socid'] = $obj->socid;
726
                    $row[$j]['datec'] = $obj->datec;
727
                    $j++;
728
                }
729
                $i++;
730
            }
731
        }
732
        else
733
        {
734
            dol_print_error($db);
735
        }
736
737
        if (count($row))
738
        {
739
            print $langs->trans('OrphelinsPaymentsDetectedByMethod', 1).': '.count($row)."<br>\n";
740
            $db->begin();
741
742
            $res = 0;
743
            $num=count($row);
744
            for ($i = 0; $i < $num; $i++)
745
            {
746
                if ($conf->global->MAIN_FEATURES_LEVEL == 2) print '* '.$row[$i]['datec'].' paymentid='.$row[$i]['paymentid'].' pamount='.$row[$i]['pamount'].' fk_bank='.$row[$i]['fk_bank'].' bamount='.$row[$i]['bamount'].' socid='.$row[$i]['socid'].'<br>';
747
748
                // On cherche facture sans lien paiement et du meme montant et pour meme societe.
749
                $sql=" SELECT distinct f.rowid from ".MAIN_DB_PREFIX."facture as f";
750
                $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
751
                $sql.=" WHERE f.fk_statut in (2,3) AND fk_soc = ".$row[$i]['socid']." AND total_ttc = ".$row[$i]['pamount'];
752
                $sql.=" AND pf.fk_facture IS NULL";
753
                $sql.=" ORDER BY f.fk_statut";
754
                //print $sql.'<br>';
755
                $resql=$db->query($sql);
756
                if ($resql)
757
                {
758
                    $num = $db->num_rows($resql);
759
                    //print 'Nb of invoice found for this amount and company :'.$num.'<br>';
760
                    if ($num >= 1)
761
                    {
762
                        $obj=$db->fetch_object($resql);
763
                        $facid=$obj->rowid;
764
765
                        $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
766
                        $sql.= " VALUES (".$facid.",".$row[$i]['paymentid'].",".$row[$i]['pamount'].")";
767
768
                        $res += $db->query($sql);
769
770
                        print $langs->trans('MigrationProcessPaymentUpdate', 'facid='.$facid.'-paymentid='.$row[$i]['paymentid'].'-amount='.$row[$i]['pamount'])."<br>\n";
771
                    }
772
                }
773
                else
774
                {
775
                    print 'ERROR';
776
                }
777
            }
778
779
            if ($res > 0)
780
            {
781
                print $langs->trans('MigrationSuccessfullUpdate')."<br>";
782
            }
783
            else
784
            {
785
                print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
786
            }
787
788
            $db->commit();
789
        }
790
        else
791
        {
792
            print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
793
        }
794
    }
795
    else
796
    {
797
        print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
798
    }
799
800
    print '</td></tr>';
801
}
802
803
/**
804
 * Corrige paiement orphelins (liens paumes suite a bugs)
805
 * Pour verifier s'il reste des orphelins:
806
 * select * from llx_paiement as p left join llx_paiement_facture as pf on pf.fk_paiement=p.rowid WHERE pf.rowid IS NULL AND (p.fk_facture = 0 OR p.fk_facture IS NULL)
807
 *
808
 * @param	DoliDB		$db		Database handler
809
 * @param	Translate	$langs	Object langs
810
 * @param	Conf		$conf	Object conf
811
 * @return	void
812
 */
813
function migrate_paiements_orphelins_2($db,$langs,$conf)
814
{
815
    print '<tr><td colspan="4">';
816
817
    print '<br>';
818
    print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
819
820
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement","fk_facture");
821
    $obj = $db->fetch_object($result);
822
    if ($obj)
823
    {
824
        // Tous les enregistrements qui sortent de cette requete devrait avoir un pere dans llx_paiement_facture
825
        $sql = "SELECT distinct p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,";
826
        $sql.= " bu2.url_id as socid";
827
        $sql.= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)";
828
        $sql.= " LEFT JOIN llx_paiement_facture as pf ON pf.fk_paiement = p.rowid";
829
        $sql.= " LEFT JOIN llx_bank_url as bu2 ON (bu.fk_bank = bu2.fk_bank AND bu2.type = 'company')";
830
        $sql.= " WHERE pf.rowid IS NULL AND (p.fk_bank = bu.fk_bank AND bu.type = 'payment') AND bu.fk_bank = b.rowid";
831
        $sql.= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)";
832
833
        $resql = $db->query($sql);
834
835
        dolibarr_install_syslog("upgrade2::migrate_paiements_orphelins_2");
836
        $row = array();
837
        if ($resql)
838
        {
839
            $i = $j = 0;
840
            $num = $db->num_rows($resql);
841
842
            while ($i < $num)
843
            {
844
                $obj = $db->fetch_object($resql);
845
                if ($obj->pamount == $obj->bamount && $obj->socid)	// Pour etre sur d'avoir bon cas
846
                {
847
                    $row[$j]['paymentid'] = $obj->rowid ;		// paymentid
848
                    $row[$j]['pamount'] = $obj->pamount;
849
                    $row[$j]['fk_bank'] = $obj->fk_bank;
850
                    $row[$j]['bamount'] = $obj->bamount;
851
                    $row[$j]['socid'] = $obj->socid;
852
                    $row[$j]['datec'] = $obj->datec;
853
                    $j++;
854
                }
855
                $i++;
856
            }
857
        }
858
        else
859
        {
860
            dol_print_error($db);
861
        }
862
863
        $nberr=0;
864
865
        $num=count($row);
866
        if ($num)
867
        {
868
            print $langs->trans('OrphelinsPaymentsDetectedByMethod', 2).': '.count($row)."<br>\n";
869
            $db->begin();
870
871
            $res = 0;
872
            for ($i = 0; $i < $num; $i++)
873
            {
874
                if ($conf->global->MAIN_FEATURES_LEVEL == 2) print '* '.$row[$i]['datec'].' paymentid='.$row[$i]['paymentid'].' '.$row[$i]['pamount'].' fk_bank='.$row[$i]['fk_bank'].' '.$row[$i]['bamount'].' socid='.$row[$i]['socid'].'<br>';
875
876
                // On cherche facture sans lien paiement et du meme montant et pour meme societe.
877
                $sql=" SELECT distinct f.rowid from ".MAIN_DB_PREFIX."facture as f";
878
                $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
879
                $sql.=" WHERE f.fk_statut in (2,3) AND fk_soc = ".$row[$i]['socid']." AND total_ttc = ".$row[$i]['pamount'];
880
                $sql.=" AND pf.fk_facture IS NULL";
881
                $sql.=" ORDER BY f.fk_statut";
882
                //print $sql.'<br>';
883
                $resql=$db->query($sql);
884
                if ($resql)
885
                {
886
                    $num = $db->num_rows($resql);
887
                    //print 'Nb of invoice found for this amount and company :'.$num.'<br>';
888
                    if ($num >= 1)
889
                    {
890
                        $obj=$db->fetch_object($resql);
891
                        $facid=$obj->rowid;
892
893
                        $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
894
                        $sql.= " VALUES (".$facid.",".$row[$i]['paymentid'].",".$row[$i]['pamount'].")";
895
                        $res += $db->query($sql);
896
897
                        print $langs->trans('MigrationProcessPaymentUpdate', 'facid='.$facid.'-paymentid='.$row[$i]['paymentid'].'-amount='.$row[$i]['pamount'])."<br>\n";
898
                    }
899
                }
900
                else
901
                {
902
                    print 'ERROR';
903
                    $nberr++;
904
                }
905
            }
906
907
            if ($res > 0)
908
            {
909
                print $langs->trans('MigrationSuccessfullUpdate')."<br>";
910
            }
911
            else
912
            {
913
                print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
914
            }
915
916
            $db->commit();
917
        }
918
        else
919
        {
920
            print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
921
        }
922
923
        // Delete obsolete fields fk_facture
924
        $db->begin();
925
926
        $sql = "ALTER TABLE ".MAIN_DB_PREFIX."paiement DROP COLUMN fk_facture";
927
        $db->query($sql);
928
929
        if (!$nberr)
930
        {
931
            $db->commit();
932
        }
933
        else
934
        {
935
            print 'ERROR';
936
            $db->rollback();
937
        }
938
    }
939
    else
940
    {
941
        print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
942
    }
943
944
    print '</td></tr>';
945
}
946
947
948
/**
949
 * Mise a jour des contrats (gestion du contrat + detail de contrat)
950
 *
951
 * @param	DoliDB		$db		Database handler
952
 * @param	Translate	$langs	Object langs
953
 * @param	Conf		$conf	Object conf
954
 * @return	void
955
 */
956
function migrate_contracts_det($db,$langs,$conf)
957
{
958
    print '<tr><td colspan="4">';
959
960
    $nberr=0;
961
962
    print '<br>';
963
    print '<b>'.$langs->trans('MigrationContractsUpdate')."</b><br>\n";
964
965
    $sql = "SELECT c.rowid as cref, c.date_contrat, c.statut, c.mise_en_service, c.fin_validite, c.date_cloture, c.fk_product, c.fk_facture, c.fk_user_author,";
966
    $sql.= " p.ref, p.label, p.description, p.price, p.tva_tx, p.duration, cd.rowid";
967
    $sql.= " FROM ".MAIN_DB_PREFIX."contrat as c";
968
    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p";
969
    $sql.= " ON c.fk_product = p.rowid";
970
    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd";
971
    $sql.= " ON c.rowid=cd.fk_contrat";
972
    $sql.= " WHERE cd.rowid IS NULL AND p.rowid IS NOT NULL";
973
    $resql = $db->query($sql);
974
975
    dolibarr_install_syslog("upgrade2::migrate_contracts_det");
976
    if ($resql)
977
    {
978
        $i = 0;
979
        $row = array();
980
        $num = $db->num_rows($resql);
981
982
        if ($num)
983
        {
984
            print $langs->trans('MigrationContractsNumberToUpdate', $num)."<br>\n";
985
            $db->begin();
986
987
            while ($i < $num)
988
            {
989
                $obj = $db->fetch_object($resql);
990
991
                $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet (";
992
                $sql.= "fk_contrat, fk_product, statut, label, description,";
993
                $sql.= "date_ouverture_prevue, date_ouverture, date_fin_validite, tva_tx, qty,";
994
                $sql.= "subprice, price_ht, fk_user_author, fk_user_ouverture)";
995
                $sql.= " VALUES (";
996
                $sql.= $obj->cref.",".($obj->fk_product?$obj->fk_product:0).",";
997
                $sql.= ($obj->mise_en_service?"4":"0").",";
998
                $sql.= "'".$db->escape($obj->label)."', null,";
999
                $sql.= ($obj->mise_en_service?"'".$obj->mise_en_service."'":($obj->date_contrat?"'".$obj->date_contrat."'":"null")).",";
1000
                $sql.= ($obj->mise_en_service?"'".$obj->mise_en_service."'":"null").",";
1001
                $sql.= ($obj->fin_validite?"'".$obj->fin_validite."'":"null").",";
1002
                $sql.= "'".$obj->tva_tx."', 1,";
1003
                $sql.= "'".$obj->price."', '".$obj->price."',".$obj->fk_user_author.",";
1004
                $sql.= ($obj->mise_en_service?$obj->fk_user_author:"null");
1005
                $sql.= ")";
1006
1007
                if ($db->query($sql))
1008
                {
1009
                    print $langs->trans('MigrationContractsLineCreation', $obj->cref)."<br>\n";
1010
                }
1011
                else
1012
                {
1013
                    dol_print_error($db);
1014
                    $nberr++;
1015
                }
1016
1017
                $i++;
1018
            }
1019
1020
            if (! $nberr)
1021
            {
1022
                //      $db->rollback();
1023
                $db->commit();
1024
                print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1025
            }
1026
            else
1027
            {
1028
                $db->rollback();
1029
                print $langs->trans('MigrationUpdateFailed').'<br>';
1030
            }
1031
        }
1032
        else
1033
        {
1034
            print $langs->trans('MigrationContractsNothingToUpdate')."<br>\n";
1035
        }
1036
    }
1037
    else
1038
    {
1039
        print $langs->trans('MigrationContractsFieldDontExist')."<br>\n";
1040
        //    dol_print_error($db);
1041
    }
1042
1043
    print '</td></tr>';
1044
}
1045
1046
/**
1047
 * Function to migrate links into llx_bank_url
1048
 *
1049
 * @param	DoliDB		$db		Database handler
1050
 * @param	Translate	$langs	Object langs
1051
 * @param	Conf		$conf	Object conf
1052
 * @return	void
1053
 */
1054
function migrate_links_transfert($db,$langs,$conf)
1055
{
1056
    print '<tr><td colspan="4">';
1057
1058
    $nberr=0;
1059
1060
    print '<br>';
1061
    print '<b>'.$langs->trans('MigrationBankTransfertsUpdate')."</b><br>\n";
1062
1063
    $sql = "SELECT ba.rowid as barowid, bb.rowid as bbrowid";
1064
    $sql.= " FROM ".MAIN_DB_PREFIX."bank as bb, ".MAIN_DB_PREFIX."bank as ba";
1065
    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON bu.fk_bank = ba.rowid";
1066
    $sql.= " WHERE ba.amount = -bb.amount AND ba.fk_account <> bb.fk_account";
1067
    $sql.= " AND ba.datev = bb.datev AND ba.datec = bb.datec";
1068
    $sql.= " AND bu.fk_bank IS NULL";
1069
    $resql = $db->query($sql);
1070
1071
    dolibarr_install_syslog("upgrade2::migrate_links_transfert");
1072
    if ($resql)
1073
    {
1074
        $i = 0;
1075
        $row = array();
1076
        $num = $db->num_rows($resql);
1077
1078
        if ($num)
1079
        {
1080
            print $langs->trans('MigrationBankTransfertsToUpdate', $num)."<br>\n";
1081
            $db->begin();
1082
1083
            while ($i < $num)
1084
            {
1085
                $obj = $db->fetch_object($resql);
1086
1087
                $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url (";
1088
                $sql.= "fk_bank, url_id, url, label, type";
1089
                $sql.= ")";
1090
                $sql.= " VALUES (";
1091
                $sql.= $obj->barowid.",".$obj->bbrowid.", '/compta/bank/ligne.php?rowid=', '(banktransfert)', 'banktransfert'";
1092
                $sql.= ")";
1093
1094
                print $sql.'<br>';
1095
                dolibarr_install_syslog("migrate_links_transfert");
1096
1097
                if (! $db->query($sql))
1098
                {
1099
                    dol_print_error($db);
1100
                    $nberr++;
1101
                }
1102
1103
                $i++;
1104
            }
1105
1106
            if (! $nberr)
1107
            {
1108
                //      $db->rollback();
1109
                $db->commit();
1110
                print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1111
            }
1112
            else
1113
            {
1114
                $db->rollback();
1115
                print $langs->trans('MigrationUpdateFailed').'<br>';
1116
            }
1117
        }
1118
        else {
1119
            print $langs->trans('MigrationBankTransfertsNothingToUpdate')."<br>\n";
1120
        }
1121
    }
1122
    else
1123
    {
1124
        dol_print_error($db);
1125
    }
1126
1127
    print '</td></tr>';
1128
}
1129
1130
/**
1131
 * Mise a jour des date de contrats non renseignees
1132
 *
1133
 * @param	DoliDB		$db		Database handler
1134
 * @param	Translate	$langs	Object langs
1135
 * @param	Conf		$conf	Object conf
1136
 * @return	void
1137
 */
1138
function migrate_contracts_date1($db,$langs,$conf)
1139
{
1140
    print '<tr><td colspan="4">';
1141
1142
    print '<br>';
1143
    print '<b>'.$langs->trans('MigrationContractsEmptyDatesUpdate')."</b><br>\n";
1144
1145
    $sql="update llx_contrat set date_contrat=tms where date_contrat is null";
1146
    dolibarr_install_syslog("upgrade2::migrate_contracts_date1");
1147
    $resql = $db->query($sql);
1148
    if (! $resql) dol_print_error($db);
1149
    if ($db->affected_rows($resql) > 0)
1150
    print $langs->trans('MigrationContractsEmptyDatesUpdateSuccess')."<br>\n";
1151
    else
1152
    print $langs->trans('MigrationContractsEmptyDatesNothingToUpdate')."<br>\n";
1153
1154
    $sql="update llx_contrat set datec=tms where datec is null";
1155
    dolibarr_install_syslog("upgrade2::migrate_contracts_date1");
1156
    $resql = $db->query($sql);
1157
    if (! $resql) dol_print_error($db);
1158
    if ($db->affected_rows($resql) > 0)
1159
    print $langs->trans('MigrationContractsEmptyCreationDatesUpdateSuccess')."<br>\n";
1160
    else
1161
    print $langs->trans('MigrationContractsEmptyCreationDatesNothingToUpdate')."<br>\n";
1162
1163
    print '</td></tr>';
1164
}
1165
1166
/*
1167
 * Mise a jour date contrat avec date min effective mise en service si inferieur
1168
 */
1169
function migrate_contracts_date2($db,$langs,$conf)
1170
{
1171
    print '<tr><td colspan="4">';
1172
1173
    $nberr=0;
1174
1175
    print '<br>';
1176
    print '<b>'.$langs->trans('MigrationContractsInvalidDatesUpdate')."</b><br>\n";
1177
1178
    $sql = "SELECT c.rowid as cref, c.datec, c.date_contrat, MIN(cd.date_ouverture) as datemin";
1179
    $sql.= " FROM ".MAIN_DB_PREFIX."contrat as c,";
1180
    $sql.= " ".MAIN_DB_PREFIX."contratdet as cd";
1181
    $sql.= " WHERE c.rowid=cd.fk_contrat AND cd.date_ouverture IS NOT NULL";
1182
    $sql.= " GROUP BY c.rowid, c.date_contrat";
1183
    $resql = $db->query($sql);
1184
1185
    dolibarr_install_syslog("upgrade2::migrate_contracts_date2");
1186
    if ($resql)
1187
    {
1188
        $i = 0;
1189
        $row = array();
1190
        $num = $db->num_rows($resql);
1191
1192
        if ($num)
1193
        {
1194
            $nbcontratsmodifie=0;
1195
            $db->begin();
1196
1197
            while ($i < $num)
1198
            {
1199
                $obj = $db->fetch_object($resql);
1200
                if ($obj->date_contrat > $obj->datemin)
1201
                {
1202
                    print $langs->trans('MigrationContractsInvalidDateFix', $obj->cref, $obj->date_contrat, $obj->datemin)."<br>\n";
1203
                    $sql ="UPDATE ".MAIN_DB_PREFIX."contrat";
1204
                    $sql.=" SET date_contrat='".$obj->datemin."'";
1205
                    $sql.=" WHERE rowid=".$obj->cref;
1206
                    $resql2=$db->query($sql);
1207
                    if (! $resql2) dol_print_error($db);
1208
1209
                    $nbcontratsmodifie++;
1210
                }
1211
                $i++;
1212
            }
1213
1214
            $db->commit();
1215
1216
            if ($nbcontratsmodifie)
1217
            print $langs->trans('MigrationContractsInvalidDatesNumber', $nbcontratsmodifie)."<br>\n";
1218
            else
1219
            print  $langs->trans('MigrationContractsInvalidDatesNothingToUpdate')."<br>\n";
1220
        }
1221
    }
1222
    else
1223
    {
1224
        dol_print_error($db);
1225
    }
1226
1227
    print '</td></tr>';
1228
}
1229
1230
/**
1231
 * Mise a jour des dates de creation de contrat
1232
 *
1233
 * @param	DoliDB		$db		Database handler
1234
 * @param	Translate	$langs	Object langs
1235
 * @param	Conf		$conf	Object conf
1236
 * @return	void
1237
 */
1238
function migrate_contracts_date3($db,$langs,$conf)
1239
{
1240
    print '<tr><td colspan="4">';
1241
1242
    print '<br>';
1243
    print '<b>'.$langs->trans('MigrationContractsIncoherentCreationDateUpdate')."</b><br>\n";
1244
1245
    $sql="update llx_contrat set datec=date_contrat where datec is null or datec > date_contrat";
1246
    dolibarr_install_syslog("upgrade2::migrate_contracts_date3");
1247
    $resql = $db->query($sql);
1248
    if (! $resql) dol_print_error($db);
1249
    if ($db->affected_rows($resql) > 0)
1250
    print $langs->trans('MigrationContractsIncoherentCreationDateUpdateSuccess')."<br>\n";
1251
    else
1252
    print $langs->trans('MigrationContractsIncoherentCreationDateNothingToUpdate')."<br>\n";
1253
1254
    print '</td></tr>';
1255
}
1256
1257
/**
1258
 * Reouverture des contrats qui ont au moins une ligne non fermee
1259
 *
1260
 * @param	DoliDB		$db		Database handler
1261
 * @param	Translate	$langs	Object langs
1262
 * @param	Conf		$conf	Object conf
1263
 * @return	void
1264
 */
1265
function migrate_contracts_open($db,$langs,$conf)
1266
{
1267
    print '<tr><td colspan="4">';
1268
1269
    print '<br>';
1270
    print '<b>'.$langs->trans('MigrationReopeningContracts')."</b><br>\n";
1271
1272
    $sql = "SELECT c.rowid as cref FROM llx_contrat as c, llx_contratdet as cd";
1273
    $sql.= " WHERE cd.statut = 4 AND c.statut=2 AND c.rowid=cd.fk_contrat";
1274
    dolibarr_install_syslog("upgrade2::migrate_contracts_open");
1275
    $resql = $db->query($sql);
1276
    if (! $resql) dol_print_error($db);
1277
    if ($db->affected_rows($resql) > 0) {
1278
        $i = 0;
1279
        $row = array();
1280
        $num = $db->num_rows($resql);
1281
1282
        if ($num)
1283
        {
1284
            $nbcontratsmodifie=0;
1285
            $db->begin();
1286
1287
            while ($i < $num)
1288
            {
1289
                $obj = $db->fetch_object($resql);
1290
1291
                print $langs->trans('MigrationReopenThisContract', $obj->cref)."<br>\n";
1292
                $sql ="UPDATE ".MAIN_DB_PREFIX."contrat";
1293
                $sql.=" SET statut=1";
1294
                $sql.=" WHERE rowid=".$obj->cref;
1295
                $resql2=$db->query($sql);
1296
                if (! $resql2) dol_print_error($db);
1297
1298
                $nbcontratsmodifie++;
1299
1300
                $i++;
1301
            }
1302
1303
            $db->commit();
1304
1305
            if ($nbcontratsmodifie)
1306
            print $langs->trans('MigrationReopenedContractsNumber', $nbcontratsmodifie)."<br>\n";
1307
            else
1308
            print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n";
1309
        }
1310
    }
1311
    else print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n";
1312
1313
    print '</td></tr>';
1314
}
1315
1316
/**
1317
 * Factures fournisseurs
1318
 *
1319
 * @param	DoliDB		$db		Database handler
1320
 * @param	Translate	$langs	Object langs
1321
 * @param	Conf		$conf	Object conf
1322
 * @return	void
1323
 */
1324
function migrate_paiementfourn_facturefourn($db,$langs,$conf)
1325
{
1326
    global $bc;
1327
1328
    print '<tr><td colspan="4">';
1329
    print '<br>';
1330
    print '<b>'.$langs->trans('SuppliersInvoices')."</b><br>\n";
1331
    print '</td></tr>';
1332
1333
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiementfourn","fk_facture_fourn");
1334
    $obj = $db->fetch_object($result);
1335
    if ($obj)
1336
    {
1337
        $error=0;
1338
        $nb=0;
1339
1340
        $select_sql = 'SELECT rowid, fk_facture_fourn, amount';
1341
        $select_sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn';
1342
        $select_sql.= ' WHERE fk_facture_fourn IS NOT NULL';
1343
1344
        dolibarr_install_syslog("upgrade2::migrate_paiementfourn_facturefourn");
1345
        $select_resql = $db->query($select_sql);
1346
        if ($select_resql)
1347
        {
1348
            $select_num = $db->num_rows($select_resql);
1349
            $i=0;
1350
            $var = true;
1351
1352
            // Pour chaque paiement fournisseur, on insere une ligne dans paiementfourn_facturefourn
1353
            while (($i < $select_num) && (! $error))
1354
            {
1355
                $var = !$var;
1356
                $select_obj = $db->fetch_object($select_resql);
1357
1358
                // Verifier si la ligne est deja dans la nouvelle table. On ne veut pas inserer de doublons.
1359
                $check_sql = 'SELECT fk_paiementfourn, fk_facturefourn';
1360
                $check_sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn';
1361
                $check_sql.= ' WHERE fk_paiementfourn = '.$select_obj->rowid.' AND fk_facturefourn = '.$select_obj->fk_facture_fourn;
1362
                $check_resql = $db->query($check_sql);
1363
                if ($check_resql)
1364
                {
1365
                    $check_num = $db->num_rows($check_resql);
1366
                    if ($check_num == 0)
1367
                    {
1368
                        $db->begin();
1369
1370
                        if ($nb == 0)
1371
                        {
1372
                            print '<tr><td colspan="4" class="nowrap"><b>'.$langs->trans('SuppliersInvoices').'</b></td></tr>';
1373
                            print '<tr><td>fk_paiementfourn</td><td>fk_facturefourn</td><td>'.$langs->trans('Amount').'</td><td>&nbsp;</td></tr>';
1374
                        }
1375
1376
                        print '<tr class="oddeven">';
1377
                        print '<td>'.$select_obj->rowid.'</td><td>'.$select_obj->fk_facture_fourn.'</td><td>'.$select_obj->amount.'</td>';
1378
1379
                        $insert_sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiementfourn_facturefourn SET ';
1380
                        $insert_sql.= ' fk_paiementfourn = \''.$select_obj->rowid.'\',';
1381
                        $insert_sql.= ' fk_facturefourn  = \''.$select_obj->fk_facture_fourn.'\',';
1382
                        $insert_sql.= ' amount           = \''.$select_obj->amount.'\'';
1383
                        $insert_resql = $db->query($insert_sql);
1384
1385
                        if ($insert_resql)
1386
                        {
1387
                            $nb++;
1388
                            print '<td><span style="color:green">'.$langs->trans("OK").'</span></td>';
1389
                        }
1390
                        else
1391
                        {
1392
                            print '<td><span style="color:red">Error on insert</span></td>';
1393
                            $error++;
1394
                        }
1395
                        print '</tr>';
1396
                    }
1397
                }
1398
                else
1399
                {
1400
                    $error++;
1401
                }
1402
                $i++;
1403
            }
1404
        }
1405
        else
1406
        {
1407
            $error++;
1408
        }
1409
1410
        if (!$error)
1411
        {
1412
            if (!$nb)
1413
            {
1414
                print '<tr><td>'.$langs->trans("AlreadyDone").'</td></tr>';
1415
            }
1416
            $db->commit();
1417
1418
            $sql = "ALTER TABLE ".MAIN_DB_PREFIX."paiementfourn DROP COLUMN fk_facture_fourn";
1419
            $db->query($sql);
1420
        }
1421
        else
1422
        {
1423
            print '<tr><td>'.$langs->trans("Error").'</td></tr>';
1424
            $db->rollback();
1425
        }
1426
    }
1427
    else
1428
    {
1429
        print '<tr><td>'.$langs->trans("AlreadyDone").'</td></tr>';
1430
    }
1431
}
1432
1433
/**
1434
 * Mise a jour des totaux lignes de facture
1435
 *
1436
 * @param	DoliDB		$db		Database handler
1437
 * @param	Translate	$langs	Object langs
1438
 * @param	Conf		$conf	Object conf
1439
 * @return	void
1440
 */
1441
function migrate_price_facture($db,$langs,$conf)
1442
{
1443
    $err=0;
1444
1445
    $tmpmysoc=new Societe($db);
1446
    $tmpmysoc->setMysoc($conf);
1447
1448
    $db->begin();
1449
1450
    print '<tr><td colspan="4">';
1451
1452
    print '<br>';
1453
    print '<b>'.$langs->trans('MigrationInvoice')."</b><br>\n";
1454
1455
    // Liste des lignes facture non a jour
1456
    $sql = "SELECT fd.rowid, fd.qty, fd.subprice, fd.remise_percent, fd.tva_tx as vatrate, fd.total_ttc, fd.info_bits,";
1457
    $sql.= " f.rowid as facid, f.remise_percent as remise_percent_global, f.total_ttc as total_ttc_f";
1458
    $sql.= " FROM ".MAIN_DB_PREFIX."facturedet as fd, ".MAIN_DB_PREFIX."facture as f";
1459
    $sql.= " WHERE fd.fk_facture = f.rowid";
1460
    $sql.= " AND (((fd.total_ttc = 0 AND fd.remise_percent != 100) or fd.total_ttc IS NULL) or f.total_ttc IS NULL)";
1461
    //print $sql;
1462
1463
    dolibarr_install_syslog("upgrade2::migrate_price_facture");
1464
    $resql=$db->query($sql);
1465
    if ($resql)
1466
    {
1467
        $num = $db->num_rows($resql);
1468
        $i = 0;
1469
        if ($num)
1470
        {
1471
            while ($i < $num)
1472
            {
1473
                $obj = $db->fetch_object($resql);
1474
1475
                $rowid = $obj->rowid;
1476
                $qty = $obj->qty;
1477
                $pu = $obj->subprice;
1478
                $vatrate = $obj->vatrate;
1479
                $remise_percent = $obj->remise_percent;
1480
                $remise_percent_global = $obj->remise_percent_global;
1481
                $total_ttc_f = $obj->total_ttc_f;
1482
                $info_bits = $obj->info_bits;
1483
1484
                // On met a jour les 3 nouveaux champs
1485
                $facligne= new FactureLigne($db);
1486
                $facligne->fetch($rowid);
1487
1488
                $result=calcul_price_total($qty,$pu,$remise_percent,$vatrate, 0, 0,$remise_percent_global,'HT',$info_bits,$facligne->product_type,$tmpmysoc);
1489
                $total_ht  = $result[0];
1490
                $total_tva = $result[1];
1491
                $total_ttc = $result[2];
1492
1493
                $facligne->total_ht  = $total_ht;
1494
                $facligne->total_tva = $total_tva;
1495
                $facligne->total_ttc = $total_ttc;
1496
1497
                dolibarr_install_syslog("upgrade2: line " . $rowid . ": facid=" . $obj->facid . " pu=" . $pu ." qty=" . $qty . " vatrate=" . $vatrate . " remise_percent=" . $remise_percent . " remise_global=" . $remise_percent_global . " -> " . $total_ht . ", " . $total_tva . ", " . $total_ttc);
1498
                print ". ";
1499
                $facligne->update_total();
1500
1501
1502
                /* On touche a facture mere uniquement si total_ttc = 0 */
1503
                if (! $total_ttc_f)
1504
                {
1505
                    $facture = new Facture($db);
1506
                    $facture->id=$obj->facid;
1507
1508
                    if ( $facture->fetch($facture->id) >= 0)
1509
                    {
1510
                        if ( $facture->update_price() > 0 )
1511
                        {
1512
                            //print $facture->id;
1513
                        }
1514
                        else
1515
                        {
1516
                            print "Error id=".$facture->id;
1517
                            $err++;
1518
                        }
1519
                    }
1520
                    else
1521
                    {
1522
                        print "Error #3";
1523
                        $err++;
1524
                    }
1525
                }
1526
                print " ";
1527
1528
                $i++;
1529
            }
1530
        }
1531
        else
1532
        {
1533
            print $langs->trans("AlreadyDone");
1534
        }
1535
        $db->free($resql);
1536
1537
        $db->commit();
1538
    }
1539
    else
1540
    {
1541
        print "Error #1 ".$db->error();
1542
        $err++;
1543
1544
        $db->rollback();
1545
    }
1546
1547
    print '<br>';
1548
1549
    print '</td></tr>';
1550
}
1551
1552
/**
1553
 * Mise a jour des totaux lignes de propal
1554
 *
1555
 * @param	DoliDB		$db		Database handler
1556
 * @param	Translate	$langs	Object langs
1557
 * @param	Conf		$conf	Object conf
1558
 * @return	void
1559
 */
1560
function migrate_price_propal($db,$langs,$conf)
1561
{
1562
   	$tmpmysoc=new Societe($db);
1563
	$tmpmysoc->setMysoc($conf);
1564
1565
    $db->begin();
1566
1567
    print '<tr><td colspan="4">';
1568
1569
    print '<br>';
1570
    print '<b>'.$langs->trans('MigrationProposal')."</b><br>\n";
1571
1572
    // Liste des lignes propal non a jour
1573
    $sql = "SELECT pd.rowid, pd.qty, pd.subprice, pd.remise_percent, pd.tva_tx as vatrate, pd.info_bits,";
1574
    $sql.= " p.rowid as propalid, p.remise_percent as remise_percent_global";
1575
    $sql.= " FROM ".MAIN_DB_PREFIX."propaldet as pd, ".MAIN_DB_PREFIX."propal as p";
1576
    $sql.= " WHERE pd.fk_propal = p.rowid";
1577
    $sql.= " AND ((pd.total_ttc = 0 AND pd.remise_percent != 100) or pd.total_ttc IS NULL)";
1578
1579
    dolibarr_install_syslog("upgrade2::migrate_price_propal");
1580
    $resql=$db->query($sql);
1581
    if ($resql)
1582
    {
1583
        $num = $db->num_rows($resql);
1584
        $i = 0;
1585
        if ($num)
1586
        {
1587
            while ($i < $num)
1588
            {
1589
                $obj = $db->fetch_object($resql);
1590
1591
                $rowid = $obj->rowid;
1592
                $qty = $obj->qty;
1593
                $pu = $obj->subprice;
1594
                $vatrate = $obj->vatrate;
1595
                $remise_percent = $obj->remise_percent;
1596
                $remise_percent_global = $obj->remise_percent_global;
1597
                $info_bits = $obj->info_bits;
1598
1599
                // On met a jour les 3 nouveaux champs
1600
                $propalligne= new PropaleLigne($db);
1601
                $propalligne->fetch($rowid);
1602
1603
                $result=calcul_price_total($qty,$pu,$remise_percent,$vatrate,0,0,$remise_percent_global,'HT',$info_bits,$propalligne->product_type,$tmpmysoc);
1604
                $total_ht  = $result[0];
1605
                $total_tva = $result[1];
1606
                $total_ttc = $result[2];
1607
1608
                $propalligne->total_ht  = $total_ht;
1609
                $propalligne->total_tva = $total_tva;
1610
                $propalligne->total_ttc = $total_ttc;
1611
1612
                dolibarr_install_syslog("upgrade2: Line " . $rowid . ": propalid=" . $obj->rowid . " pu=" . $pu . " qty=" . $qty . " vatrate=" . $vatrate . " remise_percent=" . $remise_percent . " remise_global=" . $remise_percent_global . " -> " . $total_ht . ", " . $total_tva. ", " . $total_ttc);
1613
                print ". ";
1614
                $propalligne->update_total();
1615
1616
1617
                /* On touche pas a propal mere
1618
                 $propal = new Propal($db);
1619
                 $propal->id=$obj->rowid;
1620
                 if ( $propal->fetch($propal->id) >= 0 )
1621
                 {
1622
                 if ( $propal->update_price() > 0 )
1623
                 {
1624
                 print ". ";
1625
                 }
1626
                 else
1627
                 {
1628
                 print "Error id=".$propal->id;
1629
                 }
1630
                 }
1631
                 else
1632
                 {
1633
                 print "Error #3";
1634
                 }
1635
                 */
1636
                $i++;
1637
            }
1638
        }
1639
        else
1640
        {
1641
            print $langs->trans("AlreadyDone");
1642
        }
1643
1644
        $db->free($resql);
1645
1646
        $db->commit();
1647
    }
1648
    else
1649
    {
1650
        print "Error #1 ".$db->error();
1651
1652
        $db->rollback();
1653
    }
1654
1655
    print '<br>';
1656
1657
    print '</td></tr>';
1658
}
1659
1660
/**
1661
 * Update total of contract lines
1662
 *
1663
 * @param	DoliDB		$db		Database handler
1664
 * @param	Translate	$langs	Object langs
1665
 * @param	Conf		$conf	Object conf
1666
 * @return	void
1667
 */
1668
function migrate_price_contrat($db,$langs,$conf)
1669
{
1670
    $db->begin();
1671
1672
   	$tmpmysoc=new Societe($db);
1673
	$tmpmysoc->setMysoc($conf);
1674
    if (empty($tmpmysoc->country_id)) $tmpmysoc->country_id=0;	// Ti not have this set to '' or will make sql syntax error.
1675
1676
    print '<tr><td colspan="4">';
1677
1678
    print '<br>';
1679
    print '<b>'.$langs->trans('MigrationContract')."</b><br>\n";
1680
1681
    // Liste des lignes contrat non a jour
1682
    $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
1683
    $sql.= " c.rowid as contratid";
1684
    $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c";
1685
    $sql.= " WHERE cd.fk_contrat = c.rowid";
1686
    $sql.= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100 AND cd.subprice > 0) or cd.total_ttc IS NULL)";
1687
1688
    dolibarr_install_syslog("upgrade2::migrate_price_contrat");
1689
    $resql=$db->query($sql);
1690
    if ($resql)
1691
    {
1692
        $num = $db->num_rows($resql);
1693
        $i = 0;
1694
        if ($num)
1695
        {
1696
            while ($i < $num)
1697
            {
1698
                $obj = $db->fetch_object($resql);
1699
1700
                $rowid = $obj->rowid;
1701
                $qty = $obj->qty;
1702
                $pu = $obj->subprice;
1703
                $vatrate = $obj->vatrate;
1704
                $remise_percent = $obj->remise_percent;
1705
                $info_bits = $obj->info_bits;
1706
1707
                // On met a jour les 3 nouveaux champs
1708
                $contratligne= new ContratLigne($db);
1709
                //$contratligne->fetch($rowid); Non requis car le update_total ne met a jour que chp redefinis
1710
                $contratligne->fetch($rowid);
1711
1712
                $result=calcul_price_total($qty,$pu,$remise_percent,$vatrate,0,0,0,'HT',$info_bits,$contratligne->product_type,$tmpmysoc);
1713
                $total_ht  = $result[0];
1714
                $total_tva = $result[1];
1715
                $total_ttc = $result[2];
1716
1717
                $contratligne->total_ht  = $total_ht;
1718
                $contratligne->total_tva = $total_tva;
1719
                $contratligne->total_ttc = $total_ttc;
1720
1721
                dolibarr_install_syslog("upgrade2: Line " . $rowid . ": contratdetid=" . $obj->rowid . " pu=" . $pu . " qty=" . $qty . " vatrate=" . $vatrate . " remise_percent=" . $remise_percent. "  -> " . $total_ht . ", " . $total_tva. " , " . $total_ttc);
1722
                print ". ";
1723
                $contratligne->update_total();
1724
1725
                $i++;
1726
            }
1727
        }
1728
        else
1729
        {
1730
            print $langs->trans("AlreadyDone");
1731
        }
1732
1733
        $db->free($resql);
1734
1735
        $db->commit();
1736
    }
1737
    else
1738
    {
1739
        print "Error #1 ".$db->error();
1740
1741
        $db->rollback();
1742
    }
1743
1744
    print '<br>';
1745
1746
    print '</td></tr>';
1747
}
1748
1749
/**
1750
 * Mise a jour des totaux lignes de commande
1751
 *
1752
 * @param	DoliDB		$db		Database handler
1753
 * @param	Translate	$langs	Object langs
1754
 * @param	Conf		$conf	Object conf
1755
 * @return	void
1756
 */
1757
function migrate_price_commande($db,$langs,$conf)
1758
{
1759
    $db->begin();
1760
1761
    $tmpmysoc=new Societe($db);
1762
    $tmpmysoc->setMysoc($conf);
1763
1764
    print '<tr><td colspan="4">';
1765
1766
    print '<br>';
1767
    print '<b>'.$langs->trans('MigrationOrder')."</b><br>\n";
1768
1769
    // Liste des lignes commande non a jour
1770
    $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
1771
    $sql.= " c.rowid as commandeid, c.remise_percent as remise_percent_global";
1772
    $sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."commande as c";
1773
    $sql.= " WHERE cd.fk_commande = c.rowid";
1774
    $sql.= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)";
1775
1776
    dolibarr_install_syslog("upgrade2::migrate_price_commande");
1777
    $resql=$db->query($sql);
1778
    if ($resql)
1779
    {
1780
        $num = $db->num_rows($resql);
1781
        $i = 0;
1782
        if ($num)
1783
        {
1784
            while ($i < $num)
1785
            {
1786
                $obj = $db->fetch_object($resql);
1787
1788
                $rowid = $obj->rowid;
1789
                $qty = $obj->qty;
1790
                $pu = $obj->subprice;
1791
                $vatrate = $obj->vatrate;
1792
                $remise_percent = $obj->remise_percent;
1793
                $remise_percent_global = $obj->remise_percent_global;
1794
                $info_bits = $obj->info_bits;
1795
1796
                // On met a jour les 3 nouveaux champs
1797
                $commandeligne= new OrderLine($db);
1798
                $commandeligne->fetch($rowid);
1799
1800
                $result=calcul_price_total($qty,$pu,$remise_percent,$vatrate,0,0,$remise_percent_global,'HT',$info_bits,$commandeligne->product_type,$tmpmysoc);
1801
                $total_ht  = $result[0];
1802
                $total_tva = $result[1];
1803
                $total_ttc = $result[2];
1804
1805
                $commandeligne->total_ht  = $total_ht;
1806
                $commandeligne->total_tva = $total_tva;
1807
                $commandeligne->total_ttc = $total_ttc;
1808
1809
                dolibarr_install_syslog("upgrade2: Line " . $rowid . " : commandeid=" . $obj->rowid . " pu=" . $pu . " qty=" . $qty . " vatrate=" . $vatrate . " remise_percent=" . $remise_percent . " remise_global=" . $remise_percent_global. "  -> " . $total_ht . ", " . $total_tva . ", " . $total_ttc);
1810
                print ". ";
1811
                $commandeligne->update_total();
1812
1813
                /* On touche pas a facture mere
1814
                 $commande = new Commande($db);
1815
                 $commande->id = $obj->rowid;
1816
                 if ( $commande->fetch($commande->id) >= 0 )
1817
                 {
1818
                 if ( $commande->update_price() > 0 )
1819
                 {
1820
                 print ". ";
1821
                 }
1822
                 else
1823
                 {
1824
                 print "Error id=".$commande->id;
1825
                 }
1826
                 }
1827
                 else
1828
                 {
1829
                 print "Error #3";
1830
                 }
1831
                 */
1832
                $i++;
1833
            }
1834
        }
1835
        else
1836
        {
1837
            print $langs->trans("AlreadyDone");
1838
        }
1839
1840
        $db->free($resql);
1841
1842
        /*
1843
         $sql = "DELETE FROM ".MAIN_DB_PREFIX."commandedet";
1844
         $sql.= " WHERE price = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0 AND remise_percent = 0";
1845
         $resql=$db->query($sql);
1846
         if (! $resql)
1847
         {
1848
         dol_print_error($db);
1849
         }
1850
         */
1851
1852
        $db->commit();
1853
    }
1854
    else
1855
    {
1856
        print "Error #1 ".$db->error();
1857
1858
        $db->rollback();
1859
    }
1860
1861
    print '<br>';
1862
1863
    print '</td></tr>';
1864
}
1865
1866
/**
1867
 * Mise a jour des totaux lignes de commande fournisseur
1868
 *
1869
 * @param	DoliDB		$db		Database handler
1870
 * @param	Translate	$langs	Object langs
1871
 * @param	Conf		$conf	Object conf
1872
 * @return	void
1873
 */
1874
function migrate_price_commande_fournisseur($db,$langs,$conf)
1875
{
1876
    $db->begin();
1877
1878
    $tmpmysoc=new Societe($db);
1879
    $tmpmysoc->setMysoc($conf);
1880
1881
    print '<tr><td colspan="4">';
1882
1883
    print '<br>';
1884
    print '<b>'.$langs->trans('MigrationSupplierOrder')."</b><br>\n";
1885
1886
    // Liste des lignes commande non a jour
1887
    $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
1888
    $sql.= " c.rowid as commandeid, c.remise_percent as remise_percent_global";
1889
    $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd, ".MAIN_DB_PREFIX."commande_fournisseur as c";
1890
    $sql.= " WHERE cd.fk_commande = c.rowid";
1891
    $sql.= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)";
1892
1893
    dolibarr_install_syslog("upgrade2::migrate_price_commande_fournisseur");
1894
    $resql=$db->query($sql);
1895
    if ($resql)
1896
    {
1897
        $num = $db->num_rows($resql);
1898
        $i = 0;
1899
        if ($num)
1900
        {
1901
            while ($i < $num)
1902
            {
1903
                $obj = $db->fetch_object($resql);
1904
1905
                $rowid = $obj->rowid;
1906
                $qty = $obj->qty;
1907
                $pu = $obj->subprice;
1908
                $vatrate = $obj->vatrate;
1909
                $remise_percent = $obj->remise_percent;
1910
                $remise_percent_global = $obj->remise_percent_global;
1911
                $info_bits = $obj->info_bits;
1912
1913
                // On met a jour les 3 nouveaux champs
1914
                $commandeligne= new CommandeFournisseurLigne($db);
1915
                $commandeligne->fetch($rowid);
1916
1917
                $result=calcul_price_total($qty,$pu,$remise_percent,$vatrate,0,0,$remise_percent_global,'HT',$info_bits,$commandeligne->product_type,$tmpsoc);
0 ignored issues
show
Bug introduced by
The variable $tmpsoc does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1918
                $total_ht  = $result[0];
1919
                $total_tva = $result[1];
1920
                $total_ttc = $result[2];
1921
1922
                $commandeligne->total_ht  = $total_ht;
1923
                $commandeligne->total_tva = $total_tva;
1924
                $commandeligne->total_ttc = $total_ttc;
1925
1926
                dolibarr_install_syslog("upgrade2: Line " . $rowid . ": commandeid=" . $obj->rowid . " pu=" . $pu . "  qty=" . $qty . " vatrate=" . $vatrate . " remise_percent=" . $remise_percent . " remise_global=" . $remise_percent_global . " -> " . $total_ht . ", " . $total_tva . ", " . $total_ttc);
1927
                print ". ";
1928
                $commandeligne->update_total();
0 ignored issues
show
Bug introduced by
The method update_total() does not exist on CommandeFournisseurLigne. Did you maybe mean update()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
1929
1930
                /* On touche pas a facture mere
1931
                 $commande = new Commande($db);
1932
                 $commande->id = $obj->rowid;
1933
                 if ( $commande->fetch($commande->id) >= 0 )
1934
                 {
1935
                 if ( $commande->update_price() > 0 )
1936
                 {
1937
                 print ". ";
1938
                 }
1939
                 else
1940
                 {
1941
                 print "Error id=".$commande->id;
1942
                 }
1943
                 }
1944
                 else
1945
                 {
1946
                 print "Error #3";
1947
                 }
1948
                 */
1949
                $i++;
1950
            }
1951
        }
1952
        else
1953
        {
1954
            print $langs->trans("AlreadyDone");
1955
        }
1956
1957
        $db->free($resql);
1958
1959
        /*
1960
         $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet";
1961
         $sql.= " WHERE subprice = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0";
1962
         $resql=$db->query($sql);
1963
         if (! $resql)
1964
         {
1965
         dol_print_error($db);
1966
         }
1967
         */
1968
1969
        $db->commit();
1970
    }
1971
    else
1972
    {
1973
        print "Error #1 ".$db->error();
1974
1975
        $db->rollback();
1976
    }
1977
1978
    print '<br>';
1979
1980
    print '</td></tr>';
1981
}
1982
1983
/**
1984
 * Mise a jour des modeles selectionnes
1985
 *
1986
 * @param	DoliDB		$db		Database handler
1987
 * @param	Translate	$langs	Object langs
1988
 * @param	Conf		$conf	Object conf
1989
 * @return	void
1990
 */
1991
function migrate_modeles($db,$langs,$conf)
1992
{
1993
    //print '<br>';
1994
    //print '<b>'.$langs->trans('UpdateModelsTable')."</b><br>\n";
1995
1996
    dolibarr_install_syslog("upgrade2::migrate_modeles");
1997
1998
    if (! empty($conf->facture->enabled))
1999
    {
2000
        include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
2001
        $modellist=ModelePDFFactures::liste_modeles($db);
2002
        if (count($modellist)==0)
2003
        {
2004
            // Aucun model par defaut.
2005
            $sql=" insert into llx_document_model(nom,type) values('crabe','invoice')";
2006
            $resql = $db->query($sql);
2007
            if (! $resql) dol_print_error($db);
2008
        }
2009
    }
2010
2011
    if (! empty($conf->commande->enabled))
2012
    {
2013
        include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
2014
        $modellist=ModelePDFCommandes::liste_modeles($db);
2015
        if (count($modellist)==0)
2016
        {
2017
            // Aucun model par defaut.
2018
            $sql=" insert into llx_document_model(nom,type) values('einstein','order')";
2019
            $resql = $db->query($sql);
2020
            if (! $resql) dol_print_error($db);
2021
        }
2022
    }
2023
2024
    if (! empty($conf->expedition->enabled))
2025
    {
2026
        include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
2027
        $modellist=ModelePDFExpedition::liste_modeles($db);
2028
        if (count($modellist)==0)
2029
        {
2030
            // Aucun model par defaut.
2031
            $sql=" insert into llx_document_model(nom,type) values('rouget','shipping')";
2032
            $resql = $db->query($sql);
2033
            if (! $resql) dol_print_error($db);
2034
        }
2035
    }
2036
2037
    //print $langs->trans("AlreadyDone");
2038
}
2039
2040
2041
/**
2042
 * Correspondance des expeditions et des commandes clients dans la table llx_co_exp
2043
 *
2044
 * @param	DoliDB		$db		Database handler
2045
 * @param	Translate	$langs	Object langs
2046
 * @param	Conf		$conf	Object conf
2047
 * @return	void
2048
 */
2049
function migrate_commande_expedition($db,$langs,$conf)
2050
{
2051
    dolibarr_install_syslog("upgrade2::migrate_commande_expedition");
2052
2053
    print '<tr><td colspan="4">';
2054
2055
    print '<br>';
2056
    print '<b>'.$langs->trans('MigrationShipmentOrderMatching')."</b><br>\n";
2057
2058
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."expedition","fk_commande");
2059
    $obj = $db->fetch_object($result);
2060
    if ($obj)
2061
    {
2062
        $error = 0;
2063
2064
        $db->begin();
2065
2066
        $sql = "SELECT e.rowid, e.fk_commande FROM ".MAIN_DB_PREFIX."expedition as e";
2067
        $resql = $db->query($sql);
2068
        if ($resql)
2069
        {
2070
            $i = 0;
2071
            $num = $db->num_rows($resql);
2072
2073
            if ($num)
2074
            {
2075
                while ($i < $num)
2076
                {
2077
                    $obj = $db->fetch_object($resql);
2078
2079
                    $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_exp (fk_expedition,fk_commande)";
2080
                    $sql.= " VALUES (".$obj->rowid.",".$obj->fk_commande.")";
2081
                    $resql2=$db->query($sql);
2082
2083
                    if (!$resql2)
2084
                    {
2085
                        $error++;
2086
                        dol_print_error($db);
2087
                    }
2088
                    print ". ";
2089
                    $i++;
2090
                }
2091
            }
2092
2093
            if ($error == 0)
2094
            {
2095
                $db->commit();
2096
                $sql = "ALTER TABLE ".MAIN_DB_PREFIX."expedition DROP COLUMN fk_commande";
2097
                print $langs->trans('FieldRenamed')."<br>\n";
2098
                $db->query($sql);
2099
            }
2100
            else
2101
            {
2102
                $db->rollback();
2103
            }
2104
        }
2105
        else
2106
        {
2107
            dol_print_error($db);
2108
            $db->rollback();
2109
        }
2110
    }
2111
    else
2112
    {
2113
        print $langs->trans('AlreadyDone')."<br>\n";
2114
    }
2115
    print '</td></tr>';
2116
}
2117
2118
/**
2119
 * Correspondance des livraisons et des commandes clients dans la table llx_co_liv
2120
 *
2121
 * @param	DoliDB		$db		Database handler
2122
 * @param	Translate	$langs	Object langs
2123
 * @param	Conf		$conf	Object conf
2124
 * @return	void
2125
 */
2126
function migrate_commande_livraison($db,$langs,$conf)
2127
{
2128
    dolibarr_install_syslog("upgrade2::migrate_commande_livraison");
2129
2130
    print '<tr><td colspan="4">';
2131
2132
    print '<br>';
2133
    print '<b>'.$langs->trans('MigrationDeliveryOrderMatching')."</b><br>\n";
2134
2135
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraison","fk_commande");
2136
    $obj = $db->fetch_object($result);
2137
    if ($obj)
2138
    {
2139
        $error = 0;
2140
2141
        $db->begin();
2142
2143
        $sql = "SELECT l.rowid, l.fk_commande";
2144
        $sql.= ", c.ref_client, c.date_livraison";
2145
        $sql.= " FROM ".MAIN_DB_PREFIX."livraison as l, ".MAIN_DB_PREFIX."commande as c";
2146
        $sql.= " WHERE c.rowid = l.fk_commande";
2147
        $resql = $db->query($sql);
2148
        if ($resql)
2149
        {
2150
            $i = 0;
2151
            $num = $db->num_rows($resql);
2152
2153
            if ($num)
2154
            {
2155
                while ($i < $num)
2156
                {
2157
                    $obj = $db->fetch_object($resql);
2158
2159
                    $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_liv (fk_livraison,fk_commande)";
2160
                    $sql.= " VALUES (".$obj->rowid.",".$obj->fk_commande.")";
2161
                    $resql2=$db->query($sql);
2162
2163
                    if ($resql2)
2164
                    {
2165
                        $sqlu = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
2166
                        $sqlu.= " ref_client='".$obj->ref_client."'";
2167
                        $sqlu.= ", date_livraison='".$obj->date_livraison."'";
2168
                        $sqlu.= " WHERE rowid = ".$obj->rowid;
2169
                        $resql3=$db->query($sqlu);
2170
                        if (!$resql3)
2171
                        {
2172
                            $error++;
2173
                            dol_print_error($db);
2174
                        }
2175
                    }
2176
                    else
2177
                    {
2178
                        $error++;
2179
                        dol_print_error($db);
2180
                    }
2181
                    print ". ";
2182
                    $i++;
2183
                }
2184
            }
2185
2186
            if ($error == 0)
2187
            {
2188
                $db->commit();
2189
                $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraison DROP COLUMN fk_commande";
2190
                print $langs->trans('FieldRenamed')."<br>\n";
2191
                $db->query($sql);
2192
            }
2193
            else
2194
            {
2195
                $db->rollback();
2196
            }
2197
        }
2198
        else
2199
        {
2200
            dol_print_error($db);
2201
            $db->rollback();
2202
        }
2203
    }
2204
    else
2205
    {
2206
        print $langs->trans('AlreadyDone')."<br>\n";
2207
    }
2208
    print '</td></tr>';
2209
}
2210
2211
/**
2212
 * Migration des details commandes dans les details livraisons
2213
 *
2214
 * @param	DoliDB		$db		Database handler
2215
 * @param	Translate	$langs	Object langs
2216
 * @param	Conf		$conf	Object conf
2217
 * @return	void
2218
 */
2219
function migrate_detail_livraison($db,$langs,$conf)
2220
{
2221
    dolibarr_install_syslog("upgrade2::migrate_detail_livraison");
2222
2223
    print '<tr><td colspan="4">';
2224
2225
    print '<br>';
2226
    print '<b>'.$langs->trans('MigrationDeliveryDetail')."</b><br>\n";
2227
2228
    // This is done if field fk_commande_ligne exists.
2229
    // If not this means migration was already done.
2230
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraisondet","fk_commande_ligne");
2231
    $obj = $db->fetch_object($result);
2232
    if ($obj)
2233
    {
2234
        $error = 0;
2235
2236
        $db->begin();
2237
2238
        $sql = "SELECT cd.rowid, cd.fk_product, cd.description, cd.subprice, cd.total_ht";
2239
        $sql.= ", ld.fk_livraison";
2240
        $sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."livraisondet as ld";
2241
        $sql.= " WHERE ld.fk_commande_ligne = cd.rowid";
2242
        $resql = $db->query($sql);
2243
        if ($resql)
2244
        {
2245
            $i = 0;
2246
            $num = $db->num_rows($resql);
2247
2248
            if ($num)
2249
            {
2250
                while ($i < $num)
2251
                {
2252
                    $obj = $db->fetch_object($resql);
2253
2254
                    $sql = "UPDATE ".MAIN_DB_PREFIX."livraisondet SET";
2255
                    $sql.= " fk_product=".$obj->fk_product;
2256
                    $sql.= ",description='".$db->escape($obj->description)."'";
2257
                    $sql.= ",subprice='".$obj->subprice."'";
2258
                    $sql.= ",total_ht='".$obj->total_ht."'";
2259
                    $sql.= " WHERE fk_commande_ligne = ".$obj->rowid;
2260
                    $resql2=$db->query($sql);
2261
2262
                    if ($resql2)
2263
                    {
2264
                        $sql = "SELECT total_ht";
2265
                        $sql.= " FROM ".MAIN_DB_PREFIX."livraison";
2266
                        $sql.= " WHERE rowid = ".$obj->fk_livraison;
2267
                        $resql3=$db->query($sql);
2268
2269
                        if ($resql3)
2270
                        {
2271
                            $obju = $db->fetch_object($resql3);
2272
                            $total_ht = $obju->total_ht + $obj->total_ht;
2273
2274
                            $sqlu = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
2275
                            $sqlu.= " total_ht='".$total_ht."'";
2276
                            $sqlu.= " WHERE rowid=".$obj->fk_livraison;
2277
                            $resql4=$db->query($sqlu);
2278
                            if (!$resql4)
2279
                            {
2280
                                $error++;
2281
                                dol_print_error($db);
2282
                            }
2283
                        }
2284
                        else
2285
                        {
2286
                            $error++;
2287
                            dol_print_error($db);
2288
                        }
2289
                    }
2290
                    else
2291
                    {
2292
                        $error++;
2293
                        dol_print_error($db);
2294
                    }
2295
                    print ". ";
2296
                    $i++;
2297
                }
2298
            }
2299
2300
            if ($error == 0)
2301
            {
2302
                $db->commit();
2303
                $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraisondet CHANGE fk_commande_ligne fk_origin_line integer";
2304
                print $langs->trans('FieldRenamed')."<br>\n";
2305
                $db->query($sql);
2306
            }
2307
            else
2308
            {
2309
                $db->rollback();
2310
            }
2311
        }
2312
        else
2313
        {
2314
            dol_print_error($db);
2315
            $db->rollback();
2316
        }
2317
    }
2318
    else
2319
    {
2320
        $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraisondet","fk_origin_line");
2321
        $obj = $db->fetch_object($result);
2322
        if (!$obj)
2323
        {
2324
            $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraisondet ADD COLUMN fk_origin_line integer after fk_livraison";
2325
            $db->query($sql);
2326
        }
2327
        print $langs->trans('AlreadyDone')."<br>\n";
2328
    }
2329
    print '</td></tr>';
2330
}
2331
2332
/**
2333
 * Migration du champ stock dans produits
2334
 *
2335
 * @param	DoliDB		$db		Database handler
2336
 * @param	Translate	$langs	Object langs
2337
 * @param	Conf		$conf	Object conf
2338
 * @return	void
2339
 */
2340
function migrate_stocks($db,$langs,$conf)
2341
{
2342
    dolibarr_install_syslog("upgrade2::migrate_stocks");
2343
2344
    print '<tr><td colspan="4">';
2345
2346
    print '<br>';
2347
    print '<b>'.$langs->trans('MigrationStockDetail')."</b><br>\n";
2348
2349
    $error = 0;
2350
2351
    $db->begin();
2352
2353
    $sql = "SELECT SUM(reel) as total, fk_product";
2354
    $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
2355
    $sql.= " GROUP BY fk_product";
2356
    $resql = $db->query($sql);
2357
    if ($resql)
2358
    {
2359
        $i = 0;
2360
        $num = $db->num_rows($resql);
2361
2362
        if ($num)
2363
        {
2364
            while ($i < $num)
2365
            {
2366
                $obj = $db->fetch_object($resql);
2367
2368
                $sql = "UPDATE ".MAIN_DB_PREFIX."product SET";
2369
                $sql.= " stock = '".$obj->total."'";
2370
                $sql.= " WHERE rowid=".$obj->fk_product;
2371
2372
                $resql2=$db->query($sql);
2373
                if ($resql2)
2374
                {
2375
2376
                }
2377
                else
2378
                {
2379
                    $error++;
2380
                    dol_print_error($db);
2381
                }
2382
                print ". ";
2383
                $i++;
2384
            }
2385
        }
2386
2387
        if ($error == 0)
2388
        {
2389
            $db->commit();
2390
        }
2391
        else
2392
        {
2393
            $db->rollback();
2394
        }
2395
    }
2396
    else
2397
    {
2398
        dol_print_error($db);
2399
        $db->rollback();
2400
    }
2401
2402
    print '</td></tr>';
2403
}
2404
2405
/**
2406
 * Migration of menus (use only 1 table instead of 3)
2407
 * 2.6 -> 2.7
2408
 *
2409
 * @param	DoliDB		$db		Database handler
2410
 * @param	Translate	$langs	Object langs
2411
 * @param	Conf		$conf	Object conf
2412
 * @return	void
2413
 */
2414
function migrate_menus($db,$langs,$conf)
2415
{
2416
    dolibarr_install_syslog("upgrade2::migrate_menus");
2417
2418
    print '<tr><td colspan="4">';
2419
2420
    print '<br>';
2421
    print '<b>'.$langs->trans('MigrationMenusDetail')."</b><br>\n";
2422
2423
    $error = 0;
2424
2425
    if ($db->DDLInfoTable(MAIN_DB_PREFIX."menu_constraint"))
2426
    {
2427
        $db->begin();
2428
2429
        $sql = "SELECT m.rowid, mc.action";
2430
        $sql.= " FROM ".MAIN_DB_PREFIX."menu_constraint as mc, ".MAIN_DB_PREFIX."menu_const as md, ".MAIN_DB_PREFIX."menu as m";
2431
        $sql.= " WHERE md.fk_menu = m.rowid AND md.fk_constraint = mc.rowid";
2432
        $sql.= " AND m.enabled = '1'";
2433
        $resql = $db->query($sql);
2434
        if ($resql)
2435
        {
2436
            $i = 0;
2437
            $num = $db->num_rows($resql);
2438
            if ($num)
2439
            {
2440
                while ($i < $num)
2441
                {
2442
                    $obj = $db->fetch_object($resql);
2443
2444
                    $sql = "UPDATE ".MAIN_DB_PREFIX."menu SET";
2445
                    $sql.= " enabled = '".$obj->action."'";
2446
                    $sql.= " WHERE rowid=".$obj->rowid;
2447
                    $sql.= " AND enabled = '1'";
2448
2449
                    $resql2=$db->query($sql);
2450
                    if ($resql2)
2451
                    {
2452
2453
                    }
2454
                    else
2455
                    {
2456
                        $error++;
2457
                        dol_print_error($db);
2458
                    }
2459
                    print ". ";
2460
                    $i++;
2461
                }
2462
            }
2463
2464
            if ($error == 0)
2465
            {
2466
                $db->commit();
2467
            }
2468
            else
2469
            {
2470
                $db->rollback();
2471
            }
2472
        }
2473
        else
2474
        {
2475
            dol_print_error($db);
2476
            $db->rollback();
2477
        }
2478
    }
2479
    else
2480
    {
2481
        print $langs->trans('AlreadyDone')."<br>\n";
2482
    }
2483
2484
    print '</td></tr>';
2485
}
2486
2487
/**
2488
 * Migration du champ fk_adresse_livraison dans expedition
2489
 * 2.6 -> 2.7
2490
 *
2491
 * @param	DoliDB		$db		Database handler
2492
 * @param	Translate	$langs	Object langs
2493
 * @param	Conf		$conf	Object conf
2494
 * @return	void
2495
 */
2496
function migrate_commande_deliveryaddress($db,$langs,$conf)
2497
{
2498
    dolibarr_install_syslog("upgrade2::migrate_commande_deliveryaddress");
2499
2500
    print '<tr><td colspan="4">';
2501
2502
    print '<br>';
2503
    print '<b>'.$langs->trans('MigrationDeliveryAddress')."</b><br>\n";
2504
2505
    $error = 0;
2506
2507
    if ($db->DDLInfoTable(MAIN_DB_PREFIX."co_exp"))
2508
    {
2509
        $db->begin();
2510
2511
        $sql = "SELECT c.fk_adresse_livraison, ce.fk_expedition";
2512
        $sql.= " FROM ".MAIN_DB_PREFIX."commande as c";
2513
        $sql.= ", ".MAIN_DB_PREFIX."co_exp as ce";
2514
        $sql.= " WHERE c.rowid = ce.fk_commande";
2515
        $sql.= " AND c.fk_adresse_livraison IS NOT NULL AND c.fk_adresse_livraison != 0";
2516
2517
        $resql = $db->query($sql);
2518
        if ($resql)
2519
        {
2520
            $i = 0;
2521
            $num = $db->num_rows($resql);
2522
2523
            if ($num)
2524
            {
2525
                while ($i < $num)
2526
                {
2527
                    $obj = $db->fetch_object($resql);
2528
2529
                    $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
2530
                    $sql.= " fk_adresse_livraison = '".$obj->fk_adresse_livraison."'";
2531
                    $sql.= " WHERE rowid=".$obj->fk_expedition;
2532
2533
                    $resql2=$db->query($sql);
2534
                    if (!$resql2)
2535
                    {
2536
                        $error++;
2537
                        dol_print_error($db);
2538
                    }
2539
                    print ". ";
2540
                    $i++;
2541
                }
2542
            }
2543
            else
2544
            {
2545
                print $langs->trans('AlreadyDone')."<br>\n";
2546
            }
2547
2548
            if ($error == 0)
2549
            {
2550
                $db->commit();
2551
            }
2552
            else
2553
            {
2554
                $db->rollback();
2555
            }
2556
        }
2557
        else
2558
        {
2559
            dol_print_error($db);
2560
            $db->rollback();
2561
        }
2562
    }
2563
    else
2564
    {
2565
        print $langs->trans('AlreadyDone')."<br>\n";
2566
    }
2567
2568
    print '</td></tr>';
2569
}
2570
2571
/**
2572
 * Migration du champ fk_remise_except dans llx_facturedet doit correspondre a
2573
 * lien dans llx_societe_remise_except vers llx_facturedet
2574
 *
2575
 * @param	DoliDB		$db		Database handler
2576
 * @param	Translate	$langs	Object langs
2577
 * @param	Conf		$conf	Object conf
2578
 * @return	integer|null
2579
 */
2580
function migrate_restore_missing_links($db,$langs,$conf)
2581
{
2582
    dolibarr_install_syslog("upgrade2::migrate_restore_missing_links");
2583
2584
    if (($db->type == 'mysql' || $db->type == 'mysqli'))
2585
    {
2586
        if (versioncompare($db->getVersionArray(),array(4,0)) < 0)
2587
        {
2588
            dolibarr_install_syslog("upgrade2::migrate_restore_missing_links Version of database too old to make this migrate action");
2589
            return 0;
2590
        }
2591
    }
2592
    print '<tr><td colspan="4">';
2593
2594
    print '<br>';
2595
    print '<b>'.$langs->trans('MigrationFixData')."</b> (1)<br>\n";
2596
2597
    $error = 0;
2598
2599
2600
    // Restore missing link for this cross foreign key (link 1 <=> 1). Direction 1.
2601
    $table1='facturedet'; $field1='fk_remise_except';
2602
    $table2='societe_remise_except'; $field2='fk_facture_line';
2603
2604
    $db->begin();
2605
2606
    $sql = "SELECT t1.rowid, t1.".$field1." as field";
2607
    $sql.= " FROM ".MAIN_DB_PREFIX.$table1." as t1";
2608
    $sql.= " WHERE t1.".$field1." IS NOT NULL AND t1.".$field1." NOT IN";
2609
    $sql.= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$table2." as t2";
2610
    $sql.= " WHERE t1.rowid = t2.".$field2.")";
2611
2612
    dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 1");
2613
    $resql = $db->query($sql);
2614
    if ($resql)
2615
    {
2616
        $i = 0;
2617
        $num = $db->num_rows($resql);
2618
2619
        if ($num)
2620
        {
2621
            while ($i < $num)
2622
            {
2623
                $obj = $db->fetch_object($resql);
2624
2625
                print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.<br>';
2626
                $sql = "UPDATE ".MAIN_DB_PREFIX.$table2." SET";
2627
                $sql.= " ".$field2." = '".$obj->rowid."'";
2628
                $sql.= " WHERE rowid=".$obj->field;
2629
2630
                $resql2=$db->query($sql);
2631
                if (! $resql2)
2632
                {
2633
                    $error++;
2634
                    dol_print_error($db);
2635
                }
2636
                //print ". ";
2637
                $i++;
2638
            }
2639
        }
2640
        else print $langs->trans('AlreadyDone')."<br>\n";
2641
2642
        if ($error == 0)
2643
        {
2644
            $db->commit();
2645
        }
2646
        else
2647
        {
2648
            $db->rollback();
2649
        }
2650
    }
2651
    else
2652
    {
2653
        dol_print_error($db);
2654
        $db->rollback();
2655
    }
2656
2657
    print '</td></tr>';
2658
2659
2660
    print '<tr><td colspan="4">';
2661
2662
    print '<br>';
2663
    print '<b>'.$langs->trans('MigrationFixData')."</b> (2)<br>\n";
2664
2665
    // Restore missing link for this cross foreign key (link 1 <=> 1). Direction 2.
2666
    $table2='facturedet'; $field2='fk_remise_except';
2667
    $table1='societe_remise_except'; $field1='fk_facture_line';
2668
2669
    $db->begin();
2670
2671
    $sql = "SELECT t1.rowid, t1.".$field1." as field";
2672
    $sql.= " FROM ".MAIN_DB_PREFIX.$table1." as t1";
2673
    $sql.= " WHERE t1.".$field1." IS NOT NULL AND t1.".$field1." NOT IN";
2674
    $sql.= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$table2." as t2";
2675
    $sql.= " WHERE t1.rowid = t2.".$field2.")";
2676
2677
    dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 2");
2678
    $resql = $db->query($sql);
2679
    if ($resql)
2680
    {
2681
        $i = 0;
2682
        $num = $db->num_rows($resql);
2683
2684
        if ($num)
2685
        {
2686
            while ($i < $num)
2687
            {
2688
                $obj = $db->fetch_object($resql);
2689
2690
                print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.<br>';
2691
                $sql = "UPDATE ".MAIN_DB_PREFIX.$table2." SET";
2692
                $sql.= " ".$field2." = '".$obj->rowid."'";
2693
                $sql.= " WHERE rowid=".$obj->field;
2694
2695
                $resql2=$db->query($sql);
2696
                if (! $resql2)
2697
                {
2698
                    $error++;
2699
                    dol_print_error($db);
2700
                }
2701
                //print ". ";
2702
                $i++;
2703
            }
2704
        }
2705
        else
2706
        {
2707
            print $langs->trans('AlreadyDone')."<br>\n";
2708
        }
2709
2710
        if ($error == 0)
2711
        {
2712
            $db->commit();
2713
        }
2714
        else
2715
        {
2716
            $db->rollback();
2717
        }
2718
    }
2719
    else
2720
    {
2721
        dol_print_error($db);
2722
        $db->rollback();
2723
    }
2724
2725
    print '</td></tr>';
2726
}
2727
2728
/**
2729
 * Migration du champ fk_user_resp de llx_projet vers llx_element_contact
2730
 *
2731
 * @param	DoliDB		$db		Database handler
2732
 * @param	Translate	$langs	Object langs
2733
 * @param	Conf		$conf	Object conf
2734
 * @return	void
2735
 */
2736
function migrate_project_user_resp($db,$langs,$conf)
2737
{
2738
    dolibarr_install_syslog("upgrade2::migrate_project_user_resp");
2739
2740
    print '<tr><td colspan="4">';
2741
2742
    print '<br>';
2743
    print '<b>'.$langs->trans('MigrationProjectUserResp')."</b><br>\n";
2744
2745
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."projet","fk_user_resp");
2746
    $obj = $db->fetch_object($result);
2747
    if ($obj)
2748
    {
2749
        $error = 0;
2750
2751
        $db->begin();
2752
2753
        $sql = "SELECT rowid, fk_user_resp FROM ".MAIN_DB_PREFIX."projet";
2754
        $resql = $db->query($sql);
2755
        if ($resql)
2756
        {
2757
            $i = 0;
2758
            $num = $db->num_rows($resql);
2759
2760
            if ($num)
2761
            {
2762
                while ($i < $num)
2763
                {
2764
                    $obj = $db->fetch_object($resql);
2765
2766
                    $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact (";
2767
                    $sql2.= "datecreate";
2768
                    $sql2.= ", statut";
2769
                    $sql2.= ", element_id";
2770
                    $sql2.= ", fk_c_type_contact";
2771
                    $sql2.= ", fk_socpeople";
2772
                    $sql2.= ") VALUES (";
2773
                    $sql2.= "'".$db->idate(dol_now())."'";
2774
                    $sql2.= ", '4'";
2775
                    $sql2.= ", ".$obj->rowid;
2776
                    $sql2.= ", '160'";
2777
                    $sql2.= ", ".$obj->fk_user_resp;
2778
                    $sql2.= ")";
2779
2780
                    if ($obj->fk_user_resp > 0)
2781
                    {
2782
                        $resql2=$db->query($sql2);
2783
                        if (!$resql2)
2784
                        {
2785
                            $error++;
2786
                            dol_print_error($db);
2787
                        }
2788
                    }
2789
                    print ". ";
2790
2791
                    $i++;
2792
                }
2793
            }
2794
2795
            if ($error == 0)
2796
            {
2797
                $sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."projet DROP COLUMN fk_user_resp";
2798
                if ($db->query($sqlDrop))
2799
                {
2800
                    $db->commit();
2801
                }
2802
                else
2803
                {
2804
                    $db->rollback();
2805
                }
2806
            }
2807
            else
2808
            {
2809
                $db->rollback();
2810
            }
2811
        }
2812
        else
2813
        {
2814
            dol_print_error($db);
2815
            $db->rollback();
2816
        }
2817
    }
2818
    else
2819
    {
2820
        print $langs->trans('AlreadyDone')."<br>\n";
2821
    }
2822
    print '</td></tr>';
2823
}
2824
2825
/**
2826
 * Migration de la table llx_projet_task_actors vers llx_element_contact
2827
 *
2828
 * @param	DoliDB		$db		Database handler
2829
 * @param	Translate	$langs	Object langs
2830
 * @param	Conf		$conf	Object conf
2831
 * @return	void
2832
 */
2833
function migrate_project_task_actors($db,$langs,$conf)
2834
{
2835
    dolibarr_install_syslog("upgrade2::migrate_project_task_actors");
2836
2837
    print '<tr><td colspan="4">';
2838
2839
    print '<br>';
2840
    print '<b>'.$langs->trans('MigrationProjectTaskActors')."</b><br>\n";
2841
2842
    if ($db->DDLInfoTable(MAIN_DB_PREFIX."projet_task_actors"))
2843
    {
2844
        $error = 0;
2845
2846
        $db->begin();
2847
2848
        $sql = "SELECT fk_projet_task, fk_user FROM ".MAIN_DB_PREFIX."projet_task_actors";
2849
        $resql = $db->query($sql);
2850
        if ($resql)
2851
        {
2852
            $i = 0;
2853
            $num = $db->num_rows($resql);
2854
2855
            if ($num)
2856
            {
2857
                while ($i < $num)
2858
                {
2859
                    $obj = $db->fetch_object($resql);
2860
2861
                    $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact (";
2862
                    $sql2.= "datecreate";
2863
                    $sql2.= ", statut";
2864
                    $sql2.= ", element_id";
2865
                    $sql2.= ", fk_c_type_contact";
2866
                    $sql2.= ", fk_socpeople";
2867
                    $sql2.= ") VALUES (";
2868
                    $sql2.= "'".$db->idate(dol_now())."'";
2869
                    $sql2.= ", '4'";
2870
                    $sql2.= ", ".$obj->fk_projet_task;
2871
                    $sql2.= ", '180'";
2872
                    $sql2.= ", ".$obj->fk_user;
2873
                    $sql2.= ")";
2874
2875
                    $resql2=$db->query($sql2);
2876
2877
                    if (!$resql2)
2878
                    {
2879
                        $error++;
2880
                        dol_print_error($db);
2881
                    }
2882
                    print ". ";
2883
                    $i++;
2884
                }
2885
            }
2886
2887
            if ($error == 0)
2888
            {
2889
                $sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX."projet_task_actors";
2890
                if ($db->query($sqlDrop))
2891
                {
2892
                    $db->commit();
2893
                }
2894
                else
2895
                {
2896
                    $db->rollback();
2897
                }
2898
            }
2899
            else
2900
            {
2901
                $db->rollback();
2902
            }
2903
        }
2904
        else
2905
        {
2906
            dol_print_error($db);
2907
            $db->rollback();
2908
        }
2909
    }
2910
    else
2911
    {
2912
        print $langs->trans('AlreadyDone')."<br>\n";
2913
    }
2914
    print '</td></tr>';
2915
}
2916
2917
/**
2918
 * Migration des tables de relation
2919
 *
2920
 * @param	DoliDB		$db				Database handler
2921
 * @param	Translate	$langs			Object langs
2922
 * @param	Conf		$conf			Object conf
2923
 * @param	string		$table			Table name
2924
 * @param	int			$fk_source		Id of element source
2925
 * @param	type		$sourcetype		Type of element source
2926
 * @param	int			$fk_target		Id of element target
2927
 * @param	type		$targettype		Type of element target
2928
 * @return	void
2929
 */
2930
function migrate_relationship_tables($db,$langs,$conf,$table,$fk_source,$sourcetype,$fk_target,$targettype)
2931
{
2932
    print '<tr><td colspan="4">';
2933
2934
    print '<br>';
2935
    print '<b>'.$langs->trans('MigrationRelationshipTables',MAIN_DB_PREFIX.$table)."</b><br>\n";
2936
2937
    $error = 0;
2938
2939
    if ($db->DDLInfoTable(MAIN_DB_PREFIX.$table))
2940
    {
2941
        dolibarr_install_syslog("upgrade2::migrate_relationship_tables table = " . MAIN_DB_PREFIX . $table);
2942
2943
        $db->begin();
2944
2945
        $sqlSelect = "SELECT ".$fk_source.", ".$fk_target;
2946
        $sqlSelect.= " FROM ".MAIN_DB_PREFIX.$table;
2947
2948
        $resql = $db->query($sqlSelect);
2949
        if ($resql)
2950
        {
2951
            $i = 0;
2952
            $num = $db->num_rows($resql);
2953
2954
            if ($num)
2955
            {
2956
                while ($i < $num)
2957
                {
2958
                    $obj = $db->fetch_object($resql);
2959
2960
                    $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
2961
                    $sqlInsert.= "fk_source";
2962
                    $sqlInsert.= ", sourcetype";
2963
                    $sqlInsert.= ", fk_target";
2964
                    $sqlInsert.= ", targettype";
2965
                    $sqlInsert.= ") VALUES (";
2966
                    $sqlInsert.= $obj->$fk_source;
2967
                    $sqlInsert.= ", '".$sourcetype."'";
2968
                    $sqlInsert.= ", ".$obj->$fk_target;
2969
                    $sqlInsert.= ", '".$targettype."'";
2970
                    $sqlInsert.= ")";
2971
2972
                    $result=$db->query($sqlInsert);
2973
                    if (! $result)
2974
                    {
2975
                        $error++;
2976
                        dol_print_error($db);
2977
                    }
2978
                    print ". ";
2979
                    $i++;
2980
                }
2981
            }
2982
            else
2983
            {
2984
                print $langs->trans('AlreadyDone')."<br>\n";
2985
            }
2986
2987
            if ($error == 0)
2988
            {
2989
                $sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX.$table;
2990
                if ($db->query($sqlDrop))
2991
                {
2992
                    $db->commit();
2993
                }
2994
                else
2995
                {
2996
                    $db->rollback();
2997
                }
2998
            }
2999
            else
3000
            {
3001
                $db->rollback();
3002
            }
3003
        }
3004
        else
3005
        {
3006
            dol_print_error($db);
3007
            $db->rollback();
3008
        }
3009
    }
3010
    else
3011
    {
3012
        print $langs->trans('AlreadyDone')."<br>\n";
3013
    }
3014
3015
    print '</td></tr>';
3016
}
3017
3018
/**
3019
 * Migrate duration in seconds
3020
 *
3021
 * @param	DoliDB		$db		Database handler
3022
 * @param	Translate	$langs	Object langs
3023
 * @param	Conf		$conf	Object conf
3024
 * @return	void
3025
 */
3026
function migrate_project_task_time($db,$langs,$conf)
3027
{
3028
    dolibarr_install_syslog("upgrade2::migrate_project_task_time");
3029
3030
    print '<tr><td colspan="4">';
3031
3032
    print '<br>';
3033
    print '<b>'.$langs->trans('MigrationProjectTaskTime')."</b><br>\n";
3034
3035
    $error = 0;
3036
3037
    $db->begin();
3038
3039
    $sql = "SELECT rowid, fk_task, task_duration";
3040
    $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time";
3041
    $resql = $db->query($sql);
3042
    if ($resql)
3043
    {
3044
        $i = 0;
3045
        $num = $db->num_rows($resql);
3046
3047
        if ($num)
3048
        {
3049
            $totaltime = array();
3050
            $oldtime = 0;
3051
3052
            while ($i < $num)
3053
            {
3054
                $obj = $db->fetch_object($resql);
3055
3056
                if ($obj->task_duration > 0)
3057
                {
3058
                    // convert to second
3059
                    // only for int time and float time ex: 1,75 for 1h45
3060
                    list($hour,$min) = explode('.',$obj->task_duration);
3061
                    $hour = $hour*60*60;
3062
                    $min = ($min/100)*60*60;
3063
                    $newtime = $hour+$min;
3064
3065
                    $sql2 = "UPDATE ".MAIN_DB_PREFIX."projet_task_time SET";
3066
                    $sql2.= " task_duration = ".$newtime;
3067
                    $sql2.= " WHERE rowid = ".$obj->rowid;
3068
3069
                    $resql2=$db->query($sql2);
3070
                    if (!$resql2)
3071
                    {
3072
                        $error++;
3073
                        dol_print_error($db);
3074
                    }
3075
                    print ". ";
3076
                    $oldtime++;
3077
                    if (! empty($totaltime[$obj->fk_task])) $totaltime[$obj->fk_task] += $newtime;
3078
                    else $totaltime[$obj->fk_task] = $newtime;
3079
                }
3080
                else
3081
                {
3082
                    if (! empty($totaltime[$obj->fk_task])) $totaltime[$obj->fk_task] += $obj->task_duration;
3083
                    else $totaltime[$obj->fk_task] = $obj->task_duration;
3084
                }
3085
3086
                $i++;
3087
            }
3088
3089
            if ($error == 0)
3090
            {
3091
                if ($oldtime > 0)
3092
                {
3093
                    foreach($totaltime as $taskid => $total_duration)
3094
                    {
3095
                        $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET";
3096
                        $sql.= " duration_effective = ".$total_duration;
3097
                        $sql.= " WHERE rowid = ".$taskid;
3098
3099
                        $resql=$db->query($sql);
3100
                        if (!$resql)
3101
                        {
3102
                            $error++;
3103
                            dol_print_error($db);
3104
                        }
3105
                    }
3106
                }
3107
                else
3108
                {
3109
                    print $langs->trans('AlreadyDone')."<br>\n";
3110
                }
3111
            }
3112
            else
3113
            {
3114
                dol_print_error($db);
3115
            }
3116
        }
3117
        else
3118
        {
3119
            print $langs->trans('AlreadyDone')."<br>\n";
3120
        }
3121
    }
3122
    else
3123
    {
3124
        dol_print_error($db);
3125
    }
3126
3127
    if ($error == 0)
3128
    {
3129
        $db->commit();
3130
    }
3131
    else
3132
    {
3133
        $db->rollback();
3134
    }
3135
3136
    print '</td></tr>';
3137
}
3138
3139
/**
3140
 * Migrate order ref_customer and date_delivery fields to llx_expedition
3141
 *
3142
 * @param	DoliDB		$db		Database handler
3143
 * @param	Translate	$langs	Object langs
3144
 * @param	Conf		$conf	Object conf
3145
 * @return	void
3146
 */
3147
function migrate_customerorder_shipping($db,$langs,$conf)
3148
{
3149
    print '<tr><td colspan="4">';
3150
3151
    print '<br>';
3152
    print '<b>'.$langs->trans('MigrationCustomerOrderShipping')."</b><br>\n";
3153
3154
    $error = 0;
3155
3156
    $result1 = $db->DDLDescTable(MAIN_DB_PREFIX."expedition","ref_customer");
3157
    $result2 = $db->DDLDescTable(MAIN_DB_PREFIX."expedition","date_delivery");
3158
    $obj1 = $db->fetch_object($result1);
3159
    $obj2 = $db->fetch_object($result2);
3160
    if (!$obj1 && !$obj2)
3161
    {
3162
        dolibarr_install_syslog("upgrade2::migrate_customerorder_shipping");
3163
3164
        $db->begin();
3165
3166
        $sqlAdd1 = "ALTER TABLE ".MAIN_DB_PREFIX."expedition ADD COLUMN ref_customer varchar(30) AFTER entity";
3167
        $sqlAdd2 = "ALTER TABLE ".MAIN_DB_PREFIX."expedition ADD COLUMN date_delivery date DEFAULT NULL AFTER date_expedition";
3168
3169
        if ($db->query($sqlAdd1) && $db->query($sqlAdd2))
3170
        {
3171
            $sqlSelect = "SELECT e.rowid as shipping_id, c.ref_client, c.date_livraison";
3172
            $sqlSelect.= " FROM ".MAIN_DB_PREFIX."expedition as e";
3173
            $sqlSelect.= ", ".MAIN_DB_PREFIX."element_element as el";
3174
            $sqlSelect.= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON c.rowid = el.fk_source AND el.sourcetype = 'commande'";
3175
            $sqlSelect.= " WHERE e.rowid = el.fk_target";
3176
            $sqlSelect.= " AND el.targettype = 'shipping'";
3177
3178
            $resql = $db->query($sqlSelect);
3179
            if ($resql)
3180
            {
3181
                $i = 0;
3182
                $num = $db->num_rows($resql);
3183
3184
                if ($num)
3185
                {
3186
                    while ($i < $num)
3187
                    {
3188
                        $obj = $db->fetch_object($resql);
3189
3190
                        $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
3191
                        $sqlUpdate.= " ref_customer = '".$obj->ref_client."'";
3192
                        $sqlUpdate.= ", date_delivery = '".($obj->date_livraison?$obj->date_livraison:'null')."'";
3193
                        $sqlUpdate.= " WHERE rowid = ".$obj->shipping_id;
3194
3195
                        $result=$db->query($sqlUpdate);
3196
                        if (! $result)
3197
                        {
3198
                            $error++;
3199
                            dol_print_error($db);
3200
                        }
3201
                        print ". ";
3202
                        $i++;
3203
                    }
3204
                }
3205
                else
3206
                {
3207
                    print $langs->trans('AlreadyDone')."<br>\n";
3208
                }
3209
3210
                if ($error == 0)
3211
                {
3212
                    $db->commit();
3213
                }
3214
                else
3215
                {
3216
                    dol_print_error($db);
3217
                    $db->rollback();
3218
                }
3219
            }
3220
            else
3221
            {
3222
                dol_print_error($db);
3223
                $db->rollback();
3224
            }
3225
        }
3226
        else
3227
        {
3228
            dol_print_error($db);
3229
            $db->rollback();
3230
        }
3231
    }
3232
    else
3233
    {
3234
        print $langs->trans('AlreadyDone')."<br>\n";
3235
    }
3236
3237
    print '</td></tr>';
3238
}
3239
3240
/**
3241
 * Migrate link stored into fk_expedition into llx_element_element
3242
 *
3243
 * @param	DoliDB		$db		Database handler
3244
 * @param	Translate	$langs	Object langs
3245
 * @param	Conf		$conf	Object conf
3246
 * @return	void
3247
 */
3248
function migrate_shipping_delivery($db,$langs,$conf)
3249
{
3250
    print '<tr><td colspan="4">';
3251
3252
    print '<br>';
3253
    print '<b>'.$langs->trans('MigrationShippingDelivery')."</b><br>\n";
3254
3255
    $error = 0;
3256
3257
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraison","fk_expedition");
3258
    $obj = $db->fetch_object($result);
3259
    if ($obj)
3260
    {
3261
        dolibarr_install_syslog("upgrade2::migrate_shipping_delivery");
3262
3263
        $db->begin();
3264
3265
        $sqlSelect = "SELECT rowid, fk_expedition";
3266
        $sqlSelect.= " FROM ".MAIN_DB_PREFIX."livraison";
3267
        $sqlSelect.= " WHERE fk_expedition is not null";
3268
3269
        $resql = $db->query($sqlSelect);
3270
        if ($resql)
3271
        {
3272
            $i = 0;
3273
            $num = $db->num_rows($resql);
3274
3275
            if ($num)
3276
            {
3277
                while ($i < $num)
3278
                {
3279
                    $obj = $db->fetch_object($resql);
3280
3281
                    $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
3282
                    $sqlInsert.= "fk_source";
3283
                    $sqlInsert.= ", sourcetype";
3284
                    $sqlInsert.= ", fk_target";
3285
                    $sqlInsert.= ", targettype";
3286
                    $sqlInsert.= ") VALUES (";
3287
                    $sqlInsert.= $obj->fk_expedition;
3288
                    $sqlInsert.= ", 'shipping'";
3289
                    $sqlInsert.= ", ".$obj->rowid;
3290
                    $sqlInsert.= ", 'delivery'";
3291
                    $sqlInsert.= ")";
3292
3293
                    $result=$db->query($sqlInsert);
3294
                    if ($result)
3295
                    {
3296
                        $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET fk_expedition = NULL";
3297
                        $sqlUpdate.= " WHERE rowid = ".$obj->rowid;
3298
3299
                        $result=$db->query($sqlUpdate);
3300
                        if (! $result)
3301
                        {
3302
                            $error++;
3303
                            dol_print_error($db);
3304
                        }
3305
                        print ". ";
3306
                    }
3307
                    else
3308
                    {
3309
                        $error++;
3310
                        dol_print_error($db);
3311
                    }
3312
                    $i++;
3313
                }
3314
            }
3315
            else
3316
            {
3317
                print $langs->trans('AlreadyDone')."<br>\n";
3318
            }
3319
3320
            if ($error == 0)
3321
            {
3322
                $sqlDelete = "DELETE FROM ".MAIN_DB_PREFIX."element_element WHERE sourcetype = 'commande' AND targettype = 'delivery'";
3323
                $db->query($sqlDelete);
3324
3325
                $db->commit();
3326
3327
                // DDL commands must not be inside a transaction
3328
                $sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."livraison DROP COLUMN fk_expedition";
3329
                $db->query($sqlDrop);
3330
            }
3331
            else
3332
            {
3333
                dol_print_error($db);
3334
                $db->rollback();
3335
            }
3336
        }
3337
        else
3338
        {
3339
            dol_print_error($db);
3340
            $db->rollback();
3341
        }
3342
    }
3343
    else
3344
    {
3345
        print $langs->trans('AlreadyDone')."<br>\n";
3346
    }
3347
3348
    print '</td></tr>';
3349
}
3350
3351
/**
3352
 * We try to complete field ref_customer and date_delivery that are empty into llx_livraison.
3353
 * We set them with value from llx_expedition.
3354
 *
3355
 * @param	DoliDB		$db		Database handler
3356
 * @param	Translate	$langs	Object langs
3357
 * @param	Conf		$conf	Object conf
3358
 * @return	void
3359
 */
3360
function migrate_shipping_delivery2($db,$langs,$conf)
3361
{
3362
    print '<tr><td colspan="4">';
3363
3364
    print '<br>';
3365
    print '<b>'.$langs->trans('MigrationShippingDelivery2')."</b><br>\n";
3366
3367
    $error = 0;
3368
3369
    dolibarr_install_syslog("upgrade2::migrate_shipping_delivery2");
3370
3371
    $db->begin();
3372
3373
    $sqlSelect = "SELECT l.rowid as delivery_id, e.ref_customer, e.date_delivery";
3374
    $sqlSelect.= " FROM ".MAIN_DB_PREFIX."livraison as l,";
3375
    $sqlSelect.= " ".MAIN_DB_PREFIX."element_element as el,";
3376
    $sqlSelect.= " ".MAIN_DB_PREFIX."expedition as e";
3377
    $sqlSelect.= " WHERE l.rowid = el.fk_target";
3378
    $sqlSelect.= " AND el.targettype = 'delivery'";
3379
    $sqlSelect.= " AND e.rowid = el.fk_source AND el.sourcetype = 'shipping'";
3380
    $sqlSelect.= " AND (e.ref_customer IS NOT NULL OR e.date_delivery IS NOT NULL)";   // Useless to process this record if both are null
3381
    // Add condition to know if we never migrate this record
3382
    $sqlSelect.= " AND (l.ref_customer IS NULL".($db->type!='pgsql'?" or l.ref_customer = ''":"").")";
3383
    $sqlSelect.= " AND (l.date_delivery IS NULL".($db->type!='pgsql'?" or l.date_delivery = ''":"").")";
3384
3385
    $resql = $db->query($sqlSelect);
3386
    if ($resql)
3387
    {
3388
        $i = 0;
3389
        $num = $db->num_rows($resql);
3390
3391
        if ($num)
3392
        {
3393
            while ($i < $num)
3394
            {
3395
                $obj = $db->fetch_object($resql);
3396
3397
                $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
3398
                $sqlUpdate.= " ref_customer = '".$obj->ref_customer."',";
3399
                $sqlUpdate.= " date_delivery = ".($obj->date_delivery?"'".$obj->date_delivery."'":'null');
3400
                $sqlUpdate.= " WHERE rowid = ".$obj->delivery_id;
3401
3402
                $result=$db->query($sqlUpdate);
3403
                if (! $result)
3404
                {
3405
                    $error++;
3406
                    dol_print_error($db);
3407
                }
3408
                print ". ";
3409
                $i++;
3410
            }
3411
        }
3412
        else
3413
        {
3414
            print $langs->trans('AlreadyDone')."<br>\n";
3415
        }
3416
3417
        if ($error == 0)
3418
        {
3419
            $db->commit();
3420
        }
3421
        else
3422
        {
3423
            dol_print_error($db);
3424
            $db->rollback();
3425
        }
3426
    }
3427
    else
3428
    {
3429
        dol_print_error($db);
3430
        $db->rollback();
3431
    }
3432
3433
    print '</td></tr>';
3434
}
3435
3436
/**
3437
 * Migrate link stored into fk_xxxx into fk_element and elementtype
3438
 *
3439
 * @param	DoliDB		$db		Database handler
3440
 * @param	Translate	$langs	Object langs
3441
 * @param	Conf		$conf	Object conf
3442
 * @return	void
3443
 */
3444
function migrate_actioncomm_element($db,$langs,$conf)
3445
{
3446
	print '<tr><td colspan="4">';
3447
3448
	print '<br>';
3449
	print '<b>'.$langs->trans('MigrationActioncommElement')."</b><br>\n";
3450
3451
	$elements = array(
3452
		'propal' => 'propalrowid',
3453
		'order' => 'fk_commande',
3454
		'invoice' => 'fk_facture',
3455
		'contract' => 'fk_contract',
3456
		'order_supplier' => 'fk_supplier_order',
3457
		'invoice_supplier' => 'fk_supplier_invoice'
3458
	);
3459
3460
	foreach($elements as $type => $field)
3461
	{
3462
		$result = $db->DDLDescTable(MAIN_DB_PREFIX."actioncomm",$field);
3463
		$obj = $db->fetch_object($result);
3464
		if ($obj)
3465
		{
3466
			dolibarr_install_syslog("upgrade2::migrate_actioncomm_element field=" . $field);
3467
3468
			$db->begin();
3469
3470
			$sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm SET ";
3471
			$sql.= "fk_element = ".$field.", elementtype = '".$type."'";
3472
			$sql.= " WHERE ".$field." IS NOT NULL";
3473
			$sql.= " AND fk_element IS NULL";
3474
			$sql.= " AND elementtype IS NULL";
3475
3476
			$resql = $db->query($sql);
3477
			if ($resql)
3478
			{
3479
				$db->commit();
3480
3481
				// DDL commands must not be inside a transaction
3482
				// We will drop at next version because a migrate should be runnable several times if it fails.
3483
				//$sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."actioncomm DROP COLUMN ".$field;
3484
				//$db->query($sqlDrop);
3485
				//print ". ";
3486
			}
3487
			else
3488
			{
3489
				dol_print_error($db);
3490
				$db->rollback();
3491
			}
3492
		}
3493
		else
3494
		{
3495
			print $langs->trans('AlreadyDone')."<br>\n";
3496
		}
3497
	}
3498
3499
	print '</td></tr>';
3500
}
3501
3502
/**
3503
 * Migrate link stored into fk_mode_reglement
3504
 *
3505
 * @param	DoliDB		$db		Database handler
3506
 * @param	Translate	$langs	Object langs
3507
 * @param	Conf		$conf	Object conf
3508
 * @return	void
3509
 */
3510
function migrate_mode_reglement($db,$langs,$conf)
3511
{
3512
	print '<tr><td colspan="4">';
3513
3514
	print '<br>';
3515
	print '<b>'.$langs->trans('MigrationPaymentMode')."</b><br>\n";
3516
3517
	$elements = array(
3518
		'old_id' => array(5,8,9,10,11),
3519
		'new_id' => array(50,51,52,53,54),
3520
		'code' => array('VAD','TRA','LCR','FAC','PRO'),
3521
		'tables' => array('commande_fournisseur','commande','facture_rec','facture','propal')
3522
	);
3523
	$count=0;
3524
3525
	foreach($elements['old_id'] as $key => $old_id)
3526
	{
3527
		$error=0;
3528
3529
		dolibarr_install_syslog("upgrade2::migrate_mode_reglement code=" . $elements['code'][$key]);
3530
3531
		$sqlSelect = "SELECT id";
3532
		$sqlSelect.= " FROM ".MAIN_DB_PREFIX."c_paiement";
3533
		$sqlSelect.= " WHERE id = ".$old_id;
3534
		$sqlSelect.= " AND code = '".$elements['code'][$key]."'";
3535
3536
		$resql = $db->query($sqlSelect);
3537
		if ($resql)
3538
		{
3539
			$num = $db->num_rows($resql);
3540
			if ($num)
3541
			{
3542
				$count++;
3543
3544
				$db->begin();
3545
3546
				$sqla = "UPDATE ".MAIN_DB_PREFIX."paiement SET ";
3547
				$sqla.= "fk_paiement = ".$elements['new_id'][$key];
3548
				$sqla.= " WHERE fk_paiement = ".$old_id;
3549
				$sqla.= " AND fk_paiement IN (SELECT id FROM ".MAIN_DB_PREFIX."c_paiement WHERE id = ".$old_id." AND code = '".$elements['code'][$key]."')";
3550
				$resqla = $db->query($sqla);
3551
3552
				$sql = "UPDATE ".MAIN_DB_PREFIX."c_paiement SET ";
3553
				$sql.= "id = ".$elements['new_id'][$key];
3554
				$sql.= " WHERE id = ".$old_id;
3555
				$sql.= " AND code = '".$elements['code'][$key]."'";
3556
				$resql = $db->query($sql);
3557
3558
				if ($resqla && $resql)
3559
				{
3560
					foreach($elements['tables'] as $table)
3561
					{
3562
						$sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
3563
						$sql.= "fk_mode_reglement = ".$elements['new_id'][$key];
3564
						$sql.= " WHERE fk_mode_reglement = ".$old_id;
3565
3566
						$resql = $db->query($sql);
3567
						if (! $resql)
3568
						{
3569
							dol_print_error($db);
3570
							$error++;
3571
						}
3572
						print ". ";
3573
					}
3574
3575
					if (! $error)
3576
					{
3577
						$db->commit();
3578
					}
3579
					else
3580
					{
3581
						dol_print_error($db);
3582
						$db->rollback();
3583
					}
3584
				}
3585
				else
3586
				{
3587
					dol_print_error($db);
3588
					$db->rollback();
3589
				}
3590
			}
3591
		}
3592
	}
3593
3594
	if ($count == 0) print $langs->trans('AlreadyDone')."<br>\n";
3595
3596
3597
	print '</td></tr>';
3598
}
3599
3600
3601
/**
3602
 * Delete duplicates in table categorie_association
3603
 *
3604
 * @param	DoliDB		$db			Database handler
3605
 * @param	Translate	$langs		Object langs
3606
 * @param	Conf		$conf		Object conf
3607
 * @param	string		$versionto	Version target
3608
 * @return	void
3609
 */
3610
function migrate_clean_association($db,$langs,$conf,$versionto)
3611
{
3612
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."categorie_association");
3613
    if ($result)	// result defined for version 3.2 or -
3614
    {
3615
        $obj = $db->fetch_object($result);
3616
        if ($obj)	// It table categorie_association exists
3617
        {
3618
            $couples=array();
3619
            $filles=array();
3620
            $sql = "SELECT fk_categorie_mere, fk_categorie_fille";
3621
            $sql.= " FROM ".MAIN_DB_PREFIX."categorie_association";
3622
            dolibarr_install_syslog("upgrade: search duplicate");
3623
            $resql = $db->query($sql);
3624
            if ($resql)
3625
            {
3626
                $num=$db->num_rows($resql);
3627
                while ($obj=$db->fetch_object($resql))
3628
                {
3629
                    if (! isset($filles[$obj->fk_categorie_fille]))	// Only one record as child (a child has only on parent).
3630
                    {
3631
                        if ($obj->fk_categorie_mere != $obj->fk_categorie_fille)
3632
                        {
3633
                            $filles[$obj->fk_categorie_fille]=1;	// Set record for this child
3634
                            $couples[$obj->fk_categorie_mere.'_'.$obj->fk_categorie_fille]=array('mere'=>$obj->fk_categorie_mere, 'fille'=>$obj->fk_categorie_fille);
3635
                        }
3636
                    }
3637
                }
3638
3639
                dolibarr_install_syslog("upgrade: result is num=" . $num . " count(couples)=" . count($couples));
3640
3641
                // If there is duplicates couples or child with two parents
3642
                if (count($couples) > 0 && $num > count($couples))
3643
                {
3644
                    $error=0;
3645
3646
                    $db->begin();
3647
3648
                    // We delete all
3649
                    $sql="DELETE FROM ".MAIN_DB_PREFIX."categorie_association";
3650
                    dolibarr_install_syslog("upgrade: delete association");
3651
                    $resqld=$db->query($sql);
3652
                    if ($resqld)
3653
                    {
3654
                        // And we insert only each record once
3655
                        foreach($couples as $key => $val)
3656
                        {
3657
                            $sql ="INSERT INTO ".MAIN_DB_PREFIX."categorie_association(fk_categorie_mere,fk_categorie_fille)";
3658
                            $sql.=" VALUES(".$val['mere'].", ".$val['fille'].")";
3659
                            dolibarr_install_syslog("upgrade: insert association");
3660
                            $resqli=$db->query($sql);
3661
                            if (! $resqli) $error++;
3662
                        }
3663
                    }
3664
3665
                    if (! $error)
3666
                    {
3667
                        print '<tr><td>'.$langs->trans("MigrationCategorieAssociation").'</td>';
3668
                        print '<td align="right">'.$langs->trans("RemoveDuplicates").' '.$langs->trans("Success").' ('.$num.'=>'.count($couples).')</td></tr>';
3669
                        $db->commit();
3670
                    }
3671
                    else
3672
                    {
3673
                        print '<tr><td>'.$langs->trans("MigrationCategorieAssociation").'</td>';
3674
                        print '<td align="right">'.$langs->trans("RemoveDuplicates").' '.$langs->trans("Failed").'</td></tr>';
3675
                        $db->rollback();
3676
                    }
3677
                }
3678
            }
3679
            else
3680
            {
3681
                print '<tr><td>'.$langs->trans("Error").'</td>';
3682
                print '<td align="right"><div class="error">'.$db->lasterror().'</div></td></tr>';
3683
            }
3684
        }
3685
    }
3686
}
3687
3688
3689
/**
3690
 * Migrate categorie association
3691
 *
3692
 * @param	DoliDB		$db				Database handler
3693
 * @param	Translate	$langs			Object langs
3694
 * @param	Conf		$conf			Object conf
3695
 * @return	void
3696
 */
3697
function migrate_categorie_association($db,$langs,$conf)
3698
{
3699
	print '<tr><td colspan="4">';
3700
3701
	print '<br>';
3702
	print '<b>'.$langs->trans('MigrationCategorieAssociation')."</b><br>\n";
3703
3704
	$error = 0;
3705
3706
	if ($db->DDLInfoTable(MAIN_DB_PREFIX."categorie_association"))
3707
	{
3708
		dolibarr_install_syslog("upgrade2::migrate_categorie_association");
3709
3710
		$db->begin();
3711
3712
		$sqlSelect = "SELECT fk_categorie_mere, fk_categorie_fille";
3713
		$sqlSelect.= " FROM ".MAIN_DB_PREFIX."categorie_association";
3714
3715
		$resql = $db->query($sqlSelect);
3716
		if ($resql)
3717
		{
3718
			$i = 0;
3719
			$num = $db->num_rows($resql);
3720
3721
			if ($num)
3722
			{
3723
				while ($i < $num)
3724
				{
3725
					$obj = $db->fetch_object($resql);
3726
3727
					$sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."categorie SET ";
3728
					$sqlUpdate.= "fk_parent = ".$obj->fk_categorie_mere;
3729
					$sqlUpdate.= " WHERE rowid = ".$obj->fk_categorie_fille;
3730
3731
					$result=$db->query($sqlUpdate);
3732
					if (! $result)
3733
					{
3734
						$error++;
3735
						dol_print_error($db);
3736
					}
3737
					print ". ";
3738
					$i++;
3739
				}
3740
			}
3741
			else
3742
			{
3743
				print $langs->trans('AlreadyDone')."<br>\n";
3744
			}
3745
3746
			if (! $error)
3747
			{
3748
				// TODO DROP table in the next release
3749
				/*
3750
				$sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX."categorie_association";
3751
				if ($db->query($sqlDrop))
3752
				{
3753
					$db->commit();
3754
				}
3755
				else
3756
				{
3757
					$db->rollback();
3758
				}
3759
				*/
3760
3761
				$db->commit();
3762
			}
3763
			else
3764
			{
3765
				$db->rollback();
3766
			}
3767
		}
3768
		else
3769
		{
3770
			dol_print_error($db);
3771
			$db->rollback();
3772
		}
3773
	}
3774
	else
3775
	{
3776
		print $langs->trans('AlreadyDone')."<br>\n";
3777
	}
3778
3779
	print '</td></tr>';
3780
}
3781
3782
/**
3783
 * Migrate event assignement to owner
3784
 *
3785
 * @param	DoliDB		$db				Database handler
3786
 * @param	Translate	$langs			Object langs
3787
 * @param	Conf		$conf			Object conf
3788
 * @return	void
3789
 */
3790
function migrate_event_assignement($db,$langs,$conf)
3791
{
3792
	print '<tr><td colspan="4">';
3793
3794
	print '<br>';
3795
	print '<b>'.$langs->trans('MigrationEvents')."</b><br>\n";
3796
3797
	$error = 0;
3798
3799
	dolibarr_install_syslog("upgrade2::migrate_event_assignement");
3800
3801
	$db->begin();
3802
3803
	$sqlSelect = "SELECT a.id, a.fk_user_action";
3804
	$sqlSelect.= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
3805
	$sqlSelect.= " LEFT JOIN ".MAIN_DB_PREFIX."actioncomm_resources as ar ON ar.fk_actioncomm = a.id AND ar.element_type = 'user' AND ar.fk_element = a.fk_user_action";
3806
	$sqlSelect.= " WHERE fk_user_action > 0 AND fk_user_action NOT IN (SELECT fk_element FROM ".MAIN_DB_PREFIX."actioncomm_resources as ar WHERE ar.fk_actioncomm = a.id AND ar.element_type = 'user')";
3807
	$sqlSelect.= " ORDER BY a.id";
3808
	//print $sqlSelect;
3809
3810
	$resql = $db->query($sqlSelect);
3811
	if ($resql)
3812
	{
3813
		$i = 0;
3814
		$num = $db->num_rows($resql);
3815
3816
		if ($num)
3817
		{
3818
			while ($i < $num)
3819
			{
3820
				$obj = $db->fetch_object($resql);
3821
3822
				$sqlUpdate = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element) ";
3823
				$sqlUpdate.= "VALUES(".$obj->id.", 'user', ".$obj->fk_user_action.")";
3824
3825
				$result=$db->query($sqlUpdate);
3826
				if (! $result)
3827
				{
3828
					$error++;
3829
					dol_print_error($db);
3830
				}
3831
				print ". ";
3832
				$i++;
3833
			}
3834
		}
3835
		else
3836
		{
3837
			print $langs->trans('AlreadyDone')."<br>\n";
3838
		}
3839
3840
		if (! $error)
3841
		{
3842
			$db->commit();
3843
		}
3844
		else
3845
		{
3846
			$db->rollback();
3847
		}
3848
	}
3849
	else
3850
	{
3851
		dol_print_error($db);
3852
		$db->rollback();
3853
	}
3854
3855
3856
	print '</td></tr>';
3857
}
3858
3859
/**
3860
 * Migrate event assignement to owner
3861
 *
3862
 * @param	DoliDB		$db				Database handler
3863
 * @param	Translate	$langs			Object langs
3864
 * @param	Conf		$conf			Object conf
3865
 * @return	void
3866
 */
3867
function migrate_event_assignement_contact($db,$langs,$conf)
3868
{
3869
	print '<tr><td colspan="4">';
3870
3871
	print '<br>';
3872
	print '<b>'.$langs->trans('MigrationEventsContact')."</b><br>\n";
3873
3874
	$error = 0;
3875
3876
	dolibarr_install_syslog("upgrade2::migrate_event_assignement");
3877
3878
	$db->begin();
3879
3880
	$sqlSelect = "SELECT a.id, a.fk_contact";
3881
	$sqlSelect.= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
3882
	$sqlSelect.= " LEFT JOIN ".MAIN_DB_PREFIX."actioncomm_resources as ar ON ar.fk_actioncomm = a.id AND ar.element_type = 'socpeople' AND ar.fk_element = a.fk_contact";
3883
	$sqlSelect.= " WHERE fk_contact > 0 AND fk_contact NOT IN (SELECT fk_element FROM ".MAIN_DB_PREFIX."actioncomm_resources as ar WHERE ar.fk_actioncomm = a.id AND ar.element_type = 'socpeople')";
3884
	$sqlSelect.= " ORDER BY a.id";
3885
	//print $sqlSelect;
3886
3887
	$resql = $db->query($sqlSelect);
3888
	if ($resql)
3889
	{
3890
		$i = 0;
3891
		$num = $db->num_rows($resql);
3892
3893
		if ($num)
3894
		{
3895
			while ($i < $num)
3896
			{
3897
				$obj = $db->fetch_object($resql);
3898
3899
				$sqlUpdate = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element) ";
3900
				$sqlUpdate.= "VALUES(".$obj->id.", 'socpeople', ".$obj->fk_contact.")";
3901
3902
				$result=$db->query($sqlUpdate);
3903
				if (! $result)
3904
				{
3905
					$error++;
3906
					dol_print_error($db);
3907
				}
3908
				print ". ";
3909
				$i++;
3910
			}
3911
		}
3912
		else
3913
		{
3914
			print $langs->trans('AlreadyDone')."<br>\n";
3915
		}
3916
3917
		if (! $error)
3918
		{
3919
			$db->commit();
3920
		}
3921
		else
3922
		{
3923
			$db->rollback();
3924
		}
3925
	}
3926
	else
3927
	{
3928
		dol_print_error($db);
3929
		$db->rollback();
3930
	}
3931
3932
3933
	print '</td></tr>';
3934
}
3935
3936
3937
/**
3938
 * Migrate to reset the blocked log for V7+ algorithm
3939
 *
3940
 * @param	DoliDB		$db				Database handler
3941
 * @param	Translate	$langs			Object langs
3942
 * @param	Conf		$conf			Object conf
3943
 * @return	void
3944
 */
3945
function migrate_reset_blocked_log($db,$langs,$conf)
3946
{
3947
	global $user;
3948
3949
	require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php';
3950
3951
	print '<tr><td colspan="4">';
3952
3953
	print '<br>';
3954
	print '<b>'.$langs->trans('MigrationResetBlockedLog')."</b><br>\n";
3955
3956
	$error = 0;
3957
3958
	dolibarr_install_syslog("upgrade2::migrate_reset_blocked_log");
3959
3960
	$db->begin();
3961
3962
	$sqlSelect = "SELECT DISTINCT entity";
3963
	$sqlSelect.= " FROM ".MAIN_DB_PREFIX."blockedlog";
3964
3965
	//print $sqlSelect;
3966
3967
	$resql = $db->query($sqlSelect);
3968
	if ($resql)
3969
	{
3970
		$i = 0;
3971
		$num = $db->num_rows($resql);
3972
3973
		if ($num)
3974
		{
3975
			while ($i < $num)
3976
			{
3977
				$obj = $db->fetch_object($resql);
3978
3979
				print 'Process entity '.$obj->entity;
3980
3981
				$sqlSearch = "SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."blockedlog WHERE action = 'MODULE_SET' and entity = ".$obj->entity;
3982
				$resqlSearch = $db->query($sqlSearch);
3983
				if ($resqlSearch)
3984
				{
3985
					$objSearch = $db->fetch_object($resqlSearch);
3986
					//var_dump($objSearch);
3987
					if ($objSearch && $objSearch->nb == 0)
3988
					{
3989
						print ' - Record for entity must be reset...';
3990
3991
						$sqlUpdate = "DELETE FROM ".MAIN_DB_PREFIX."blockedlog";
3992
						$sqlUpdate.= " WHERE entity = " . $obj->entity;
3993
						$resqlUpdate=$db->query($sqlUpdate);
3994
						if (! $resqlUpdate)
3995
						{
3996
							$error++;
3997
							dol_print_error($db);
3998
						}
3999
						else
4000
						{
4001
							// Add set line
4002
							$object=new stdClass();
4003
							$object->id = 1;
4004
							$object->element = 'module';
4005
							$object->ref = 'systemevent';
4006
							$object->entity = $obj->entity;
4007
							$object->date = dol_now();
4008
4009
							$b=new BlockedLog($db);
4010
							$b->setObjectData($object, 'MODULE_SET', 0);
4011
4012
							$res = $b->create($user);
4013
							if ($res<=0) {
4014
								$error++;
4015
							}
4016
						}
4017
					}
4018
					else
4019
					{
4020
						print ' - '.$langs->trans('AlreadyInV7').'<br>';
4021
					}
4022
				}
4023
				else
4024
				{
4025
					dol_print_error($db);
4026
				}
4027
4028
				$i++;
4029
			}
4030
		}
4031
		else
4032
		{
4033
			print $langs->trans('NothingToDo')."<br>\n";
4034
		}
4035
4036
		if (! $error)
4037
		{
4038
			$db->commit();
4039
		}
4040
		else
4041
		{
4042
			$db->rollback();
4043
		}
4044
	}
4045
	else
4046
	{
4047
		dol_print_error($db);
4048
		$db->rollback();
4049
	}
4050
4051
	print '</td></tr>';
4052
}
4053
4054
4055
/**
4056
 * Migrate to add entity value into llx_societe_remise
4057
 *
4058
 * @param	DoliDB		$db				Database handler
4059
 * @param	Translate	$langs			Object langs
4060
 * @param	Conf		$conf			Object conf
4061
 * @return	void
4062
 */
4063
function migrate_remise_entity($db,$langs,$conf)
4064
{
4065
	print '<tr><td colspan="4">';
4066
4067
	print '<br>';
4068
	print '<b>'.$langs->trans('MigrationRemiseEntity')."</b><br>\n";
4069
4070
	$error = 0;
4071
4072
	dolibarr_install_syslog("upgrade2::migrate_remise_entity");
4073
4074
	$db->begin();
4075
4076
	$sqlSelect = "SELECT sr.rowid, s.entity";
4077
	$sqlSelect.= " FROM ".MAIN_DB_PREFIX."societe_remise as sr, ".MAIN_DB_PREFIX."societe as s";
4078
	$sqlSelect.= " WHERE sr.fk_soc = s.rowid and sr.entity != s.entity";
4079
4080
	//print $sqlSelect;
4081
4082
	$resql = $db->query($sqlSelect);
4083
	if ($resql)
4084
	{
4085
		$i = 0;
4086
		$num = $db->num_rows($resql);
4087
4088
		if ($num)
4089
		{
4090
			while ($i < $num)
4091
			{
4092
				$obj = $db->fetch_object($resql);
4093
4094
				$sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise SET";
4095
				$sqlUpdate.= " entity = " . $obj->entity;
4096
				$sqlUpdate.= " WHERE rowid = " . $obj->rowid;
4097
4098
				$result=$db->query($sqlUpdate);
4099
				if (! $result)
4100
				{
4101
					$error++;
4102
					dol_print_error($db);
4103
				}
4104
4105
				print ". ";
4106
				$i++;
4107
			}
4108
		}
4109
		else
4110
		{
4111
			print $langs->trans('AlreadyDone')."<br>\n";
4112
		}
4113
4114
		if (! $error)
4115
		{
4116
			$db->commit();
4117
		}
4118
		else
4119
		{
4120
			$db->rollback();
4121
		}
4122
	}
4123
	else
4124
	{
4125
		dol_print_error($db);
4126
		$db->rollback();
4127
	}
4128
4129
	print '</td></tr>';
4130
}
4131
4132
/**
4133
 * Migrate to add entity value into llx_societe_remise_except
4134
 *
4135
 * @param	DoliDB		$db				Database handler
4136
 * @param	Translate	$langs			Object langs
4137
 * @param	Conf		$conf			Object conf
4138
 * @return	void
4139
 */
4140
function migrate_remise_except_entity($db,$langs,$conf)
4141
{
4142
	print '<tr><td colspan="4">';
4143
4144
	print '<br>';
4145
	print '<b>'.$langs->trans('MigrationRemiseExceptEntity')."</b><br>\n";
4146
4147
	$error = 0;
4148
4149
	dolibarr_install_syslog("upgrade2::migrate_remise_except_entity");
4150
4151
	$db->begin();
4152
4153
	$sqlSelect = "SELECT sr.rowid, sr.fk_soc, sr.fk_facture_source, sr.fk_facture, sr.fk_facture_line";
4154
	$sqlSelect.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr";
4155
	//print $sqlSelect;
4156
4157
	$resql = $db->query($sqlSelect);
4158
	if ($resql)
4159
	{
4160
		$i = 0;
4161
		$num = $db->num_rows($resql);
4162
4163
		if ($num)
4164
		{
4165
			while ($i < $num)
4166
			{
4167
				$obj = $db->fetch_object($resql);
4168
4169
				if (!empty($obj->fk_facture_source) || !empty($obj->fk_facture))
4170
				{
4171
					$fk_facture = (!empty($obj->fk_facture_source) ? $obj->fk_facture_source : $obj->fk_facture);
4172
4173
					$sqlSelect2 = "SELECT f.entity";
4174
					$sqlSelect2.= " FROM ".MAIN_DB_PREFIX."facture as f";
4175
					$sqlSelect2.= " WHERE f.rowid = " . $fk_facture;
4176
				}
4177
				else if (!empty($obj->fk_facture_line))
4178
				{
4179
					$sqlSelect2 = "SELECT f.entity";
4180
					$sqlSelect2.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as fd";
4181
					$sqlSelect2.= " WHERE fd.rowid = " . $obj->fk_facture_line;
4182
					$sqlSelect2.= " AND fd.fk_facture = f.rowid";
4183
				}
4184
				else
4185
				{
4186
					$sqlSelect2 = "SELECT s.entity";
4187
					$sqlSelect2.= " FROM ".MAIN_DB_PREFIX."societe as s";
4188
					$sqlSelect2.= " WHERE s.rowid = " . $obj->fk_soc;
4189
				}
4190
4191
				$resql2 = $db->query($sqlSelect2);
4192
				if ($resql2)
4193
				{
4194
					if ($db->num_rows($resql2) > 0)
4195
					{
4196
						$obj2 = $db->fetch_object($resql2);
4197
4198
						$sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except SET";
4199
						$sqlUpdate.= " entity = " . $obj2->entity;
4200
						$sqlUpdate.= " WHERE rowid = " . $obj->rowid;
4201
4202
						$result=$db->query($sqlUpdate);
4203
						if (! $result)
4204
						{
4205
							$error++;
4206
							dol_print_error($db);
4207
						}
4208
					}
4209
				}
4210
				else
4211
				{
4212
					$error++;
4213
					dol_print_error($db);
4214
				}
4215
4216
				print ". ";
4217
				$i++;
4218
			}
4219
		}
4220
		else
4221
		{
4222
			print $langs->trans('AlreadyDone')."<br>\n";
4223
		}
4224
4225
		if (! $error)
4226
		{
4227
			$db->commit();
4228
		}
4229
		else
4230
		{
4231
			$db->rollback();
4232
		}
4233
	}
4234
	else
4235
	{
4236
		dol_print_error($db);
4237
		$db->rollback();
4238
	}
4239
4240
4241
	print '</td></tr>';
4242
}
4243
4244
/**
4245
 * Migrate to add entity value into llx_user_rights
4246
 *
4247
 * @param	DoliDB		$db				Database handler
4248
 * @param	Translate	$langs			Object langs
4249
 * @param	Conf		$conf			Object conf
4250
 * @return	void
4251
 */
4252
function migrate_user_rights_entity($db,$langs,$conf)
4253
{
4254
	print '<tr><td colspan="4">';
4255
4256
	print '<b>'.$langs->trans('MigrationUserRightsEntity')."</b><br>\n";
4257
4258
	$error = 0;
4259
4260
	dolibarr_install_syslog("upgrade2::migrate_user_rights_entity");
4261
4262
	$db->begin();
4263
4264
	$sqlSelect = "SELECT u.rowid, u.entity";
4265
	$sqlSelect.= " FROM ".MAIN_DB_PREFIX."user as u";
4266
	$sqlSelect.= " WHERE u.entity > 1";
4267
	//print $sqlSelect;
4268
4269
	$resql = $db->query($sqlSelect);
4270
	if ($resql)
4271
	{
4272
		$i = 0;
4273
		$num = $db->num_rows($resql);
4274
4275
		if ($num)
4276
		{
4277
			while ($i < $num)
4278
			{
4279
				$obj = $db->fetch_object($resql);
4280
4281
				$sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."user_rights SET";
4282
				$sqlUpdate.= " entity = " . $obj->entity;
4283
				$sqlUpdate.= " WHERE fk_user = " . $obj->rowid;
4284
4285
				$result=$db->query($sqlUpdate);
4286
				if (! $result)
4287
				{
4288
					$error++;
4289
					dol_print_error($db);
4290
				}
4291
4292
				print ". ";
4293
				$i++;
4294
			}
4295
		}
4296
		else
4297
		{
4298
			print $langs->trans('AlreadyDone')."<br>\n";
4299
		}
4300
4301
		if (! $error)
4302
		{
4303
			$db->commit();
4304
		}
4305
		else
4306
		{
4307
			$db->rollback();
4308
		}
4309
	}
4310
	else
4311
	{
4312
		dol_print_error($db);
4313
		$db->rollback();
4314
	}
4315
4316
4317
	print '</td></tr>';
4318
}
4319
4320
/**
4321
 * Migrate to add entity value into llx_usergroup_rights
4322
 *
4323
 * @param	DoliDB		$db				Database handler
4324
 * @param	Translate	$langs			Object langs
4325
 * @param	Conf		$conf			Object conf
4326
 * @return	void
4327
 */
4328
function migrate_usergroup_rights_entity($db,$langs,$conf)
4329
{
4330
	print '<tr><td colspan="4">';
4331
4332
	print '<b>'.$langs->trans('MigrationUserGroupRightsEntity')."</b><br>\n";
4333
4334
	$error = 0;
4335
4336
	dolibarr_install_syslog("upgrade2::migrate_usergroup_rights_entity");
4337
4338
	$db->begin();
4339
4340
	$sqlSelect = "SELECT u.rowid, u.entity";
4341
	$sqlSelect.= " FROM ".MAIN_DB_PREFIX."usergroup as u";
4342
	$sqlSelect.= " WHERE u.entity > 1";
4343
	//print $sqlSelect;
4344
4345
	$resql = $db->query($sqlSelect);
4346
	if ($resql)
4347
	{
4348
		$i = 0;
4349
		$num = $db->num_rows($resql);
4350
4351
		if ($num)
4352
		{
4353
			while ($i < $num)
4354
			{
4355
				$obj = $db->fetch_object($resql);
4356
4357
				$sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."usergroup_rights SET";
4358
				$sqlUpdate.= " entity = " . $obj->entity;
4359
				$sqlUpdate.= " WHERE fk_usergroup = " . $obj->rowid;
4360
4361
				$result=$db->query($sqlUpdate);
4362
				if (! $result)
4363
				{
4364
					$error++;
4365
					dol_print_error($db);
4366
				}
4367
4368
				print ". ";
4369
				$i++;
4370
			}
4371
		}
4372
		else
4373
		{
4374
			print $langs->trans('AlreadyDone')."<br>\n";
4375
		}
4376
4377
		if (! $error)
4378
		{
4379
			$db->commit();
4380
		}
4381
		else
4382
		{
4383
			$db->rollback();
4384
		}
4385
	}
4386
	else
4387
	{
4388
		dol_print_error($db);
4389
		$db->rollback();
4390
	}
4391
4392
4393
	print '</td></tr>';
4394
}
4395
4396
/**
4397
 * Migration directory
4398
 *
4399
 * @param	DoliDB		$db			Database handler
4400
 * @param	Translate	$langs		Object langs
4401
 * @param	Conf		$conf		Object conf
4402
 * @param	string		$oldname	Old name (relative to DOL_DATA_ROOT)
4403
 * @param	string		$newname	New name (relative to DOL_DATA_ROOT)
4404
 * @return	void
4405
 */
4406
function migrate_rename_directories($db,$langs,$conf,$oldname,$newname)
4407
{
4408
    dolibarr_install_syslog("upgrade2::migrate_rename_directories");
4409
4410
    if (is_dir(DOL_DATA_ROOT.$oldname) && ! file_exists(DOL_DATA_ROOT.$newname))
4411
    {
4412
        dolibarr_install_syslog("upgrade2::migrate_rename_directories move " . DOL_DATA_ROOT . $oldname . ' into ' . DOL_DATA_ROOT . $newname);
4413
        @rename(DOL_DATA_ROOT.$oldname,DOL_DATA_ROOT.$newname);
4414
    }
4415
}
4416
4417
4418
/**
4419
 * Delete deprecated files
4420
 *
4421
 * @param	DoliDB		$db			Database handler
4422
 * @param	Translate	$langs		Object langs
4423
 * @param	Conf		$conf		Object conf
4424
 * @return	void
4425
 */
4426
function migrate_delete_old_files($db,$langs,$conf)
4427
{
4428
	$result=true;
4429
4430
	dolibarr_install_syslog("upgrade2::migrate_delete_old_files");
4431
4432
	// List of files to delete
4433
	$filetodeletearray=array(
4434
		DOL_DOCUMENT_ROOT.'/core/triggers/interface_demo.class.php',
4435
		DOL_DOCUMENT_ROOT.'/core/menus/barre_left/default.php',
4436
		DOL_DOCUMENT_ROOT.'/core/menus/barre_top/default.php',
4437
		DOL_DOCUMENT_ROOT.'/core/modules/modComptabiliteExpert.class.php',
4438
		DOL_DOCUMENT_ROOT.'/core/modules/modCommercial.class.php',
4439
		DOL_DOCUMENT_ROOT.'/core/modules/modProduit.class.php',
4440
		DOL_DOCUMENT_ROOT.'/core/modules/modSkype.class.php',
4441
		DOL_DOCUMENT_ROOT.'/phenix/inc/triggers/interface_modPhenix_Phenixsynchro.class.php',
4442
		DOL_DOCUMENT_ROOT.'/webcalendar/inc/triggers/interface_modWebcalendar_webcalsynchro.class.php',
4443
		DOL_DOCUMENT_ROOT.'/core/triggers/interface_modWebcalendar_Webcalsynchro.class.php',
4444
		DOL_DOCUMENT_ROOT.'/core/triggers/interface_modCommande_Ecotax.class.php',
4445
		DOL_DOCUMENT_ROOT.'/core/triggers/interface_modCommande_fraisport.class.php',
4446
		DOL_DOCUMENT_ROOT.'/core/triggers/interface_modPropale_PropalWorkflow.class.php',
4447
		DOL_DOCUMENT_ROOT.'/core/menus/smartphone/iphone.lib.php',
4448
		DOL_DOCUMENT_ROOT.'/core/menus/smartphone/iphone_backoffice.php',
4449
		DOL_DOCUMENT_ROOT.'/core/menus/smartphone/iphone_frontoffice.php',
4450
		DOL_DOCUMENT_ROOT.'/core/menus/standard/auguria_backoffice.php',
4451
		DOL_DOCUMENT_ROOT.'/core/menus/standard/auguria_frontoffice.php',
4452
		DOL_DOCUMENT_ROOT.'/core/menus/standard/eldy_backoffice.php',
4453
		DOL_DOCUMENT_ROOT.'/core/menus/standard/eldy_frontoffice.php',
4454
		DOL_DOCUMENT_ROOT.'/core/modules/mailings/contacts2.modules.php',
4455
		DOL_DOCUMENT_ROOT.'/core/modules/mailings/contacts3.modules.php',
4456
		DOL_DOCUMENT_ROOT.'/core/modules/mailings/contacts4.modules.php',
4457
		DOL_DOCUMENT_ROOT.'/core/modules/mailings/framboise.modules.php',
4458
		DOL_DOCUMENT_ROOT.'/core/modules/mailings/dolibarr_services_expired.modules.php',
4459
		DOL_DOCUMENT_ROOT.'/core/modules/mailings/peche.modules.php',
4460
		DOL_DOCUMENT_ROOT.'/core/modules/mailings/poire.modules.php',
4461
		DOL_DOCUMENT_ROOT.'/core/modules/mailings/kiwi.modules.php',
4462
		DOL_DOCUMENT_ROOT.'/core/modules/facture/pdf_crabe.modules.php',
4463
		DOL_DOCUMENT_ROOT.'/core/modules/facture/pdf_oursin.modules.php',
4464
4465
		DOL_DOCUMENT_ROOT.'/compta/facture/class/api_invoice.class.php',
4466
		DOL_DOCUMENT_ROOT.'/commande/class/api_commande.class.php',
4467
		DOL_DOCUMENT_ROOT.'/user/class/api_user.class.php',
4468
		DOL_DOCUMENT_ROOT.'/product/class/api_product.class.php',
4469
		DOL_DOCUMENT_ROOT.'/societe/class/api_contact.class.php',
4470
		DOL_DOCUMENT_ROOT.'/societe/class/api_thirdparty.class.php',
4471
		DOL_DOCUMENT_ROOT.'/support/online.php'
4472
    );
4473
4474
    foreach ($filetodeletearray as $filetodelete)
4475
    {
4476
        //print '<b>'.$filetodelete."</b><br>\n";
4477
        $result=1;
4478
        if (file_exists($filetodelete))
4479
        {
4480
            $result=dol_delete_file($filetodelete,0,0,0,null,true);
4481
            if (! $result)
4482
            {
4483
                $langs->load("errors");
4484
                print '<div class="error">'.$langs->trans("Error").': '.$langs->trans("ErrorFailToDeleteFile",$filetodelete);
4485
                print ' '.$langs->trans("RemoveItManuallyAndPressF5ToContinue").'</div>';
4486
            }
4487
            else
4488
			{
4489
                //print $langs->trans("FileWasRemoved",$filetodelete);
4490
            }
4491
        }
4492
    }
4493
    return $result;
4494
}
4495
4496
/**
4497
 * Remove deprecated directories
4498
 *
4499
 * @param	DoliDB		$db			Database handler
4500
 * @param	Translate	$langs		Object langs
4501
 * @param	Conf		$conf		Object conf
4502
 * @return	void
4503
 */
4504
function migrate_delete_old_dir($db,$langs,$conf)
4505
{
4506
    $result=true;
4507
4508
    dolibarr_install_syslog("upgrade2::migrate_delete_old_dir");
4509
4510
    // List of files to delete
4511
    $filetodeletearray=array(
4512
    DOL_DOCUMENT_ROOT.'/core/modules/facture/terre',
4513
    DOL_DOCUMENT_ROOT.'/core/modules/facture/mercure'
4514
    );
4515
4516
    foreach ($filetodeletearray as $filetodelete)
4517
    {
4518
        //print '<b>'.$filetodelete."</b><br>\n";
4519
        if (file_exists($filetodelete))
4520
        {
4521
            $result=dol_delete_dir_recursive($filetodelete);
4522
        }
4523
        if (! $result)
4524
        {
4525
            $langs->load("errors");
4526
            print '<div class="error">'.$langs->trans("Error").': '.$langs->trans("ErrorFailToDeleteDir",$filetodelete);
4527
            print ' '.$langs->trans("RemoveItManuallyAndPressF5ToContinue").'</div>';
4528
        }
4529
    }
4530
    return $result;
4531
}
4532
4533
4534
/**
4535
 * Disable/Reenable features modules.
4536
 * We must do this when internal menu of module or permissions has changed
4537
 * or when triggers have moved.
4538
 *
4539
 * @param	DoliDB		$db				Database handler
4540
 * @param	Translate	$langs			Object langs
4541
 * @param	Conf		$conf			Object conf
4542
 * @param	array		$listofmodule	List of modules
4543
 * @param   int         $force          1=Reload module even if not already loaded
4544
 * @return	void
4545
 */
4546
function migrate_reload_modules($db, $langs, $conf, $listofmodule=array(), $force=0)
4547
{
4548
	if (count($listofmodule) == 0) return;
4549
4550
	dolibarr_install_syslog("upgrade2::migrate_reload_modules force=".$force.", listofmodule=".join(',', array_keys($listofmodule)));
4551
4552
	foreach($listofmodule as $moduletoreload => $reloadmode)	// reloadmodule can be 'noboxes', 'newboxdefonly', 'forceactivate'
4553
	{
4554
		if (empty($moduletoreload) || (empty($conf->global->$moduletoreload) && ! $force)) continue; // Discard reload if module not enabled
4555
4556
		$mod=null;
4557
4558
		if ($moduletoreload == 'MAIN_MODULE_AGENDA')
4559
		{
4560
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Agenda module");
4561
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modAgenda.class.php';
4562
			if ($res) {
4563
				$mod=new modAgenda($db);
4564
				$mod->remove('noboxes');
4565
				$mod->init($reloadmode);
4566
			}
4567
		}
4568
		elseif ($moduletoreload == 'MAIN_MODULE_API')
4569
		{
4570
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Rest API module");
4571
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modApi.class.php';
4572
			if ($res) {
4573
				$mod=new modApi($db);
4574
				//$mod->remove('noboxes');
4575
				$mod->init($reloadmode);
4576
			}
4577
		}
4578
		elseif ($moduletoreload == 'MAIN_MODULE_BARCODE')
4579
		{
4580
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Barcode module");
4581
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modBarcode.class.php';
4582
			if ($res) {
4583
				$mod=new modBarcode($db);
4584
				$mod->remove('noboxes');
4585
				$mod->init($reloadmode);
4586
			}
4587
		}
4588
		elseif ($moduletoreload == 'MAIN_MODULE_CRON')
4589
		{
4590
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Cron module");
4591
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modCron.class.php';
4592
			if ($res) {
4593
				$mod=new modCron($db);
4594
				$mod->remove('noboxes');
4595
				$mod->init($reloadmode);
4596
			}
4597
		}
4598
		elseif ($moduletoreload == 'MAIN_MODULE_SOCIETE')
4599
		{
4600
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Societe module");
4601
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modSociete.class.php';
4602
			if ($res) {
4603
				$mod=new modSociete($db);
4604
				$mod->remove('noboxes');
4605
				$mod->init($reloadmode);
4606
			}
4607
		}
4608
		elseif ($moduletoreload == 'MAIN_MODULE_PRODUIT')    // Permission has changed into 2.7
4609
		{
4610
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Produit module");
4611
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modProduct.class.php';
4612
			if ($res) {
4613
				$mod=new modProduct($db);
4614
				//$mod->remove('noboxes');
4615
				$mod->init($reloadmode);
4616
			}
4617
		}
4618
		elseif ($moduletoreload == 'MAIN_MODULE_SERVICE')    // Permission has changed into 2.7
4619
		{
4620
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Service module");
4621
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modService.class.php';
4622
			if ($res) {
4623
				$mod=new modService($db);
4624
				//$mod->remove('noboxes');
4625
				$mod->init($reloadmode);
4626
			}
4627
		}
4628
		elseif ($moduletoreload == 'MAIN_MODULE_COMMANDE')   // Permission has changed into 2.9
4629
		{
4630
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Commande module");
4631
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modCommande.class.php';
4632
			if ($res) {
4633
				$mod=new modCommande($db);
4634
				//$mod->remove('noboxes');
4635
				$mod->init($reloadmode);
4636
			}
4637
		}
4638
		elseif ($moduletoreload == 'MAIN_MODULE_FACTURE')    // Permission has changed into 2.9
4639
		{
4640
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Facture module");
4641
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modFacture.class.php';
4642
			if ($res) {
4643
				$mod=new modFacture($db);
4644
				//$mod->remove('noboxes');
4645
				$mod->init($reloadmode);
4646
			}
4647
		}
4648
		elseif ($moduletoreload == 'MAIN_MODULE_FOURNISSEUR')    // Permission has changed into 2.9
4649
		{
4650
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Fournisseur module");
4651
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modFournisseur.class.php';
4652
			if ($res) {
4653
				$mod=new modFournisseur($db);
4654
				//$mod->remove('noboxes');
4655
				$mod->init($reloadmode);
4656
			}
4657
		}
4658
		elseif ($moduletoreload == 'MAIN_MODULE_HOLIDAY')    // Permission and tabs has changed into 3.8
4659
		{
4660
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Leave Request module");
4661
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modHoliday.class.php';
4662
			if ($res) {
4663
				$mod=new modHoliday($db);
4664
				$mod->remove('noboxes');
4665
				$mod->init($reloadmode);
4666
			}
4667
		}
4668
		elseif ($moduletoreload == 'MAIN_MODULE_DEPLACEMENT')    // Permission has changed into 3.0
4669
		{
4670
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Deplacement module");
4671
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modDeplacement.class.php';
4672
			if ($res) {
4673
				$mod=new modDeplacement($db);
4674
				//$mod->remove('noboxes');
4675
				$mod->init($reloadmode);
4676
			}
4677
		}
4678
		elseif ($moduletoreload == 'MAIN_MODULE_DON')    // Permission has changed into 3.0
4679
		{
4680
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Don module");
4681
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modDon.class.php';
4682
			if ($res) {
4683
				$mod=new modDon($db);
4684
				//$mod->remove('noboxes');
4685
				$mod->init($reloadmode);
4686
			}
4687
		}
4688
		elseif ($moduletoreload == 'MAIN_MODULE_ECM')    // Permission has changed into 3.0 and 3.1
4689
		{
4690
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate ECM module");
4691
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modECM.class.php';
4692
			if ($res) {
4693
				$mod=new modECM($db);
4694
				$mod->remove('noboxes');	// We need to remove because a permission id has been removed
4695
				$mod->init($reloadmode);
4696
			}
4697
		}
4698
		elseif ($moduletoreload == 'MAIN_MODULE_PAYBOX')    // Permission has changed into 3.0
4699
		{
4700
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Paybox module");
4701
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modPaybox.class.php';
4702
			if ($res) {
4703
				$mod=new modPaybox($db);
4704
				$mod->remove('noboxes');  // We need to remove because id of module has changed
4705
				$mod->init($reloadmode);
4706
			}
4707
		}
4708
		elseif ($moduletoreload == 'MAIN_MODULE_SUPPLIERPROPOSAL')		// Module after 3.5
4709
		{
4710
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Supplier Proposal module");
4711
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modSupplierProposal.class.php';
4712
			if ($res) {
4713
				$mod=new modSupplierProposal($db);
4714
				$mod->remove('noboxes');  // We need to remove because id of module has changed
4715
				$mod->init($reloadmode);
4716
			}
4717
		}
4718
		elseif ($moduletoreload == 'MAIN_MODULE_OPENSURVEY')    // Permission has changed into 3.0
4719
		{
4720
			dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Opensurvey module");
4721
			$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modOpenSurvey.class.php';
4722
			if ($res) {
4723
				$mod=new modOpenSurvey($db);
4724
				$mod->remove('noboxes');  // We need to remove because menu entries has changed
4725
				$mod->init($reloadmode);
4726
			}
4727
		}
4728
		else
4729
		{
4730
			$tmp = preg_match('/MAIN_MODULE_([a-zA-Z0-9]+)/', $moduletoreload, $reg);
4731
			if (! empty($reg[1]))
4732
			{
4733
				if (strtoupper($moduletoreload) == $moduletoreload)	// If key is un uppercase
4734
				{
4735
					$moduletoreloadshort = ucfirst(strtolower($reg[1]));
4736
				}
4737
				else												// If key is a mix of up and low case
4738
				{
4739
					$moduletoreloadshort = $reg[1];
4740
				}
4741
				dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate module ".$moduletoreloadshort." with mode ".$reloadmode);
4742
				$res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/mod'.$moduletoreloadshort.'.class.php';
4743
				if ($res) {
4744
					$classname = 'mod'.$moduletoreloadshort;
4745
					$mod=new $classname($db);
4746
					//$mod->remove('noboxes');
4747
					$mod->init($reloadmode);
4748
				}
4749
				else
4750
				{
4751
					dolibarr_install_syslog('Failed to include '.DOL_DOCUMENT_ROOT.'/core/modules/mod'.$moduletoreloadshort.'.class.php');
4752
4753
					$res=@dol_include_once(strtolower($moduletoreloadshort).'/core/modules/mod'.$moduletoreloadshort.'.class.php');
4754
					if ($res) {
4755
						$classname = 'mod'.$moduletoreloadshort;
4756
						$mod=new $classname($db);
4757
						//$mod->remove('noboxes');
4758
						$mod->init($reloadmode);
4759
					}
4760
					else
4761
					{
4762
						dolibarr_install_syslog('Failed to include '.strtolower($moduletoreloadshort).'/core/modules/mod'.$moduletoreloadshort.'.class.php');
4763
					}
4764
				}
4765
			}
4766
			else
4767
			{
4768
				dolibarr_install_syslog("Error, can't find module with name ".$moduletoreload, LOG_WARNING);
4769
				print "Error, can't find module with name ".$moduletoreload;
4770
			}
4771
		}
4772
4773
		if (! empty($mod) && is_object($mod))
4774
		{
4775
			print '<tr><td colspan="4">';
4776
			print '<b>'.$langs->trans('Upgrade').'</b>: ';
4777
			print $langs->trans('MigrationReloadModule').' '.$mod->getName();  // We keep getName outside of trans because getName is already encoded/translated
4778
			print "<!-- (".$reloadmode.") -->";
4779
			print "<br>\n";
4780
			print '</td></tr>';
4781
		}
4782
	}
4783
}
4784
4785
4786
4787
/**
4788
 * Reload menu if dynamic menus, if modified by version
4789
 *
4790
 * @param	DoliDB		$db			Database handler
4791
 * @param	Translate	$langs		Object langs
4792
 * @param	Conf		$conf		Object conf
4793
 * @param	string		$versionto	Version target
4794
 * @return	void
4795
 */
4796
function migrate_reload_menu($db,$langs,$conf,$versionto)
4797
{
4798
    global $conf;
4799
    dolibarr_install_syslog("upgrade2::migrate_reload_menu");
4800
4801
    // Define list of menu handlers to initialize
4802
    $listofmenuhandler=array();
4803
    if ($conf->global->MAIN_MENU_STANDARD == 'auguria_menu' || $conf->global->MAIN_MENU_SMARTPHONE == 'auguria_menu'
4804
    	|| $conf->global->MAIN_MENUFRONT_STANDARD == 'auguria_menu' || $conf->global->MAIN_MENUFRONT_SMARTPHONE == 'auguria_menu')
4805
    {
4806
    	$listofmenuhandler['auguria']=1;   // We set here only dynamic menu handlers
4807
    }
4808
4809
    foreach ($listofmenuhandler as $key => $val)
4810
    {
4811
        print '<tr><td colspan="4">';
4812
4813
        //print "x".$key;
4814
        print '<br>';
4815
        print '<b>'.$langs->trans('Upgrade').'</b>: '.$langs->trans('MenuHandler')." ".$key."<br>\n";
4816
4817
        // Load sql ini_menu_handler.sql file
4818
        $dir = DOL_DOCUMENT_ROOT."/core/menus/";
4819
        $file='init_menu_'.$key.'.sql';
4820
        if (file_exists($dir.$file))
4821
        {
4822
            $result=run_sql($dir.$file,1,'',1,$key);
4823
        }
4824
4825
        print '</td></tr>';
4826
    }
4827
}
4828
4829
/**
4830
 * Migrate file from old path to new one for users
4831
 *
4832
 * @return	void
4833
 */
4834
function migrate_user_photospath()
4835
{
4836
	global $conf, $db, $langs;
4837
	
4838
	print '<tr><td colspan="4">';
4839
4840
	print '<b>'.$langs->trans('MigrationUserPhotoPath')."</b><br>\n";
4841
	
4842
	include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4843
	$fuser = new User($db);
4844
4845
	$sql = "SELECT rowid as uid from ".MAIN_DB_PREFIX."user";	// Get list of all users
4846
	$resql = $db->query($sql);
4847
	if ($resql)
4848
	{
4849
		while ($obj = $db->fetch_object($resql))
4850
		{
4851
			$fuser->fetch($obj->uid);
4852
			//echo '<hr>'.$fuser->id.' -> '.$fuser->entity;
4853
			$entity = (!empty($fuser->entity)) ? $fuser->entity : 1;
4854
			$dir = $conf->user->multidir_output[$entity];
4855
			$origin = $dir .'/'. get_exdir($fuser->id,2,0,0,$fuser,'user');
4856
			$destin = $dir.'/'.$fuser->id;
4857
		
4858
			$error = 0;
4859
		
4860
			$origin_osencoded=dol_osencode($origin);
4861
			$destin_osencoded=dol_osencode($destin);
4862
			dol_mkdir($destin);
4863
			//echo '<hr>'.$origin.' -> '.$destin;
4864
			if (dol_is_dir($origin))
4865
			{
4866
				$handle=opendir($origin_osencoded);
4867
		        if (is_resource($handle))
4868
		        {
4869
		        	while (($file = readdir($handle)) !== false)
4870
		    		{
4871
		     			if ($file != '.' && $file != '..' && is_dir($origin_osencoded.'/'.$file))
4872
		    			{
4873
		    				$thumbs = opendir($origin_osencoded.'/'.$file);
4874
		    				if (is_resource($thumbs))
4875
		        			{
4876
			     				dol_mkdir($destin.'/'.$file);
4877
			     				while (($thumb = readdir($thumbs)) !== false)
4878
				    			{
4879
				    				dol_move($origin.'/'.$file.'/'.$thumb, $destin.'/'.$file.'/'.$thumb);
4880
				    			}
4881
		//		    			dol_delete_dir($origin.'/'.$file);
4882
		        			}
4883
		    			}
4884
		    			else
4885
		    			{
4886
		    				if (dol_is_file($origin.'/'.$file) )
4887
		    				{
4888
		    					dol_move($origin.'/'.$file, $destin.'/'.$file);
4889
		    				}
4890
		    			}
4891
		    		}
4892
		        }
4893
			}
4894
		}
4895
	}
4896
4897
	print '</td></tr>';
4898
}
4899
4900
4901
/* A faire egalement: Modif statut paye et fk_facture des factures payes completement
4902
4903
On recherche facture incorrecte:
4904
select f.rowid, f.total_ttc as t1, sum(pf.amount) as t2 from llx_facture as f, llx_paiement_facture as pf where pf.fk_facture=f.rowid and f.fk_statut in(2,3) and paye=0 and close_code is null group by f.rowid
4905
having  f.total_ttc = sum(pf.amount)
4906
4907
On les corrige:
4908
update llx_facture set paye=1, fk_statut=2 where close_code is null
4909
and rowid in (...)
4910
*/
4911
4912