Completed
Branch develop (59ab9a)
by
unknown
27:43
created

upgrade2.php ➔ migrate_delete_old_files()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 60
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 42
nc 4
nop 3
dl 0
loc 60
rs 8.9618
c 0
b 0
f 0

How to fix   Long Method   

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-2012  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
 * Upgrade scripts can be ran from command line with syntax:
22
 *
23
 * cd htdocs/install
24
 * php upgrade.php 3.4.0 3.5.0
25
 * php upgrade2.php 3.4.0 3.5.0
26
 *
27
 * Return code is 0 if OK, >0 if error
28
 */
29
30
/**
31
 *	\file       htdocs/install/upgrade2.php
32
 *	\brief      Upgrade some data
33
 */
34
35
include_once 'inc.php';
36
if (! file_exists($conffile))
37
{
38
    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").';
39
}
40
require_once $conffile;
41
require_once $dolibarr_main_document_root . '/compta/facture/class/facture.class.php';
42
require_once $dolibarr_main_document_root . '/comm/propal/class/propal.class.php';
43
require_once $dolibarr_main_document_root . '/contrat/class/contrat.class.php';
44
require_once $dolibarr_main_document_root . '/commande/class/commande.class.php';
45
require_once $dolibarr_main_document_root . '/fourn/class/fournisseur.commande.class.php';
46
require_once $dolibarr_main_document_root . '/core/lib/price.lib.php';
47
require_once $dolibarr_main_document_root . '/core/class/menubase.class.php';
48
require_once $dolibarr_main_document_root . '/core/lib/files.lib.php';
49
50
global $langs;
51
52
$grant_query='';
53
$step = 2;
54
$error = 0;
55
56
57
// Cette page peut etre longue. On augmente le delai autorise.
58
// Ne fonctionne que si on est pas en safe_mode.
59
$err=error_reporting();
60
error_reporting(0);
61
@set_time_limit(300);
62
error_reporting($err);
63
64
$setuplang=GETPOST("selectlang",'',3)?GETPOST("selectlang",'',3):'auto';
65
$langs->setDefaultLang($setuplang);
66
$versionfrom=GETPOST("versionfrom",'',3)?GETPOST("versionfrom",'',3):(empty($argv[1])?'':$argv[1]);
67
$versionto=GETPOST("versionto",'',3)?GETPOST("versionto",'',3):(empty($argv[2])?'':$argv[2]);
68
$enablemodules=GETPOST("enablemodules",'',3)?GETPOST("enablemodules",'',3):(empty($argv[3])?'':$argv[3]);
69
70
$langs->load('admin');
71
$langs->load('install');
72
$langs->load("bills");
73
$langs->load("suppliers");
74
75
if ($dolibarr_main_db_type == 'mysqli') $choix=1;
76
if ($dolibarr_main_db_type == 'pgsql')  $choix=2;
77
if ($dolibarr_main_db_type == 'mssql')  $choix=3;
78
79
80
dolibarr_install_syslog("--- upgrade2: entering upgrade2.php page");
81
if (! is_object($conf)) dolibarr_install_syslog("upgrade2: conf file not initialized", LOG_ERR);
82
83
84
85
/*
86
 * View
87
 */
88
89
if ((! $versionfrom || preg_match('/version/', $versionfrom)) && (! $versionto || preg_match('/version/', $versionto)))
90
{
91
	print 'Error: Parameter versionfrom or versionto missing or having a bad format.'."\n";
92
	print 'Upgrade must be ran from cmmand line with parameters or called from page install/index.php (like a first install) instead of page install/upgrade.php'."\n";
93
	// Test if batch mode
94
	$sapi_type = php_sapi_name();
95
	$script_file = basename(__FILE__);
96
	$path=dirname(__FILE__).'/';
97
	if (substr($sapi_type, 0, 3) == 'cli')
98
	{
99
		print 'Syntax from command line: '.$script_file." x.y.z a.b.c\n";
100
	}
101
	exit;
102
}
103
104
pHeader('','step5',GETPOST('action','aZ09')?GETPOST('action','aZ09'):'upgrade','versionfrom='.$versionfrom.'&versionto='.$versionto);
105
106
107
if (! GETPOST('action','aZ09') || preg_match('/upgrade/i',GETPOST('action','aZ09')))
108
{
109
    print '<h3>'.$langs->trans('DataMigration').'</h3>';
110
111
    print '<table cellspacing="0" cellpadding="1" border="0" width="100%">';
112
113
    // If password is encoded, we decode it
114
    if (preg_match('/crypted:/i',$dolibarr_main_db_pass) || ! empty($dolibarr_main_db_encrypted_pass))
115
    {
116
        require_once $dolibarr_main_document_root.'/core/lib/security.lib.php';
117
        if (preg_match('/crypted:/i',$dolibarr_main_db_pass))
118
        {
119
            $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass);
120
            $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass);
121
            $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
122
        }
123
        else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass);
124
    }
125
126
    // $conf is already instancied inside inc.php
127
    $conf->db->type = $dolibarr_main_db_type;
128
    $conf->db->host = $dolibarr_main_db_host;
129
    $conf->db->port = $dolibarr_main_db_port;
130
    $conf->db->name = $dolibarr_main_db_name;
131
    $conf->db->user = $dolibarr_main_db_user;
132
    $conf->db->pass = $dolibarr_main_db_pass;
133
134
    $db=getDoliDBInstance($conf->db->type,$conf->db->host,$conf->db->user,$conf->db->pass,$conf->db->name,$conf->db->port);
135
136
    // Create the global $hookmanager object
137
    include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
138
    $hookmanager=new HookManager($db);
139
140
    if (!$db->connected)
141
    {
142
        print '<tr><td colspan="4">'.$langs->trans("ErrorFailedToConnectToDatabase",$conf->db->name).'</td><td align="right">'.$langs->trans('Error').'</td></tr>';
143
        dolibarr_install_syslog('upgrade2: failed to connect to database :' . $conf->db->name . ' on ' . $conf->db->host . ' for user ' . $conf->db->user, LOG_ERR);
144
        $error++;
145
    }
146
147
    if (! $error)
148
    {
149
        if($db->database_selected)
150
        {
151
            dolibarr_install_syslog('upgrade2: database connection successful :' . $dolibarr_main_db_name);
152
        }
153
        else
154
        {
155
            $error++;
156
        }
157
    }
158
159
    if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption=0;
160
    $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption;
161
    if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey='';
162
    $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey;
163
164
    // Chargement config
165
    if (! $error) $conf->setValues($db);
166
167
168
    /***************************************************************************************
169
     *
170
     * Migration des donnees
171
     *
172
     ***************************************************************************************/
173
    if (! $error)
174
    {
175
        // Current version is $conf->global->MAIN_VERSION_LAST_UPGRADE
176
        // Version to install is DOL_VERSION
177
        $dolibarrlastupgradeversionarray=preg_split('/[\.-]/',isset($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_UPGRADE:$conf->global->MAIN_VERSION_LAST_INSTALL);
178
179
        $db->begin();
180
181
        // Chaque action de migration doit renvoyer une ligne sur 4 colonnes avec
182
        // dans la 1ere colonne, la description de l'action a faire
183
        // dans la 4eme colonne, le texte 'OK' si fait ou 'AlreadyDone' si rien n'est fait ou 'Error'
184
185
        $versiontoarray=explode('.',$versionto);
186
187
        $afterversionarray=explode('.','2.0.0');
188
        $beforeversionarray=explode('.','2.7.9');
189
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
190
        {
191
            // Script pour V2 -> V2.1
192
            migrate_paiements($db,$langs,$conf);
193
194
            migrate_contracts_det($db,$langs,$conf);
195
196
            migrate_contracts_date1($db,$langs,$conf);
197
198
            migrate_contracts_date2($db,$langs,$conf);
199
200
            migrate_contracts_date3($db,$langs,$conf);
201
202
            migrate_contracts_open($db,$langs,$conf);
203
204
            migrate_modeles($db,$langs,$conf);
205
206
            migrate_price_propal($db,$langs,$conf);
207
208
            migrate_price_commande($db,$langs,$conf);
209
210
            migrate_price_commande_fournisseur($db,$langs,$conf);
211
212
            migrate_price_contrat($db,$langs,$conf);
213
214
            migrate_paiementfourn_facturefourn($db,$langs,$conf);
215
216
217
            // Script pour V2.1 -> V2.2
218
            migrate_paiements_orphelins_1($db,$langs,$conf);
219
220
            migrate_paiements_orphelins_2($db,$langs,$conf);
221
222
            migrate_links_transfert($db,$langs,$conf);
223
224
225
            // Script pour V2.2 -> V2.4
226
            migrate_commande_expedition($db,$langs,$conf);
227
228
            migrate_commande_livraison($db,$langs,$conf);
229
230
            migrate_detail_livraison($db,$langs,$conf);
231
232
233
            // Script pour V2.5 -> V2.6
234
            migrate_stocks($db,$langs,$conf);
235
236
237
            // Script pour V2.6 -> V2.7
238
            migrate_menus($db,$langs,$conf);
239
240
            migrate_commande_deliveryaddress($db,$langs,$conf);
241
242
            migrate_restore_missing_links($db,$langs,$conf);
243
244
            migrate_directories($db,$langs,$conf,'/compta','/banque');
245
246
            migrate_directories($db,$langs,$conf,'/societe','/mycompany');
247
248
            // Reload modules
249
            migrate_reload_modules($db,$langs,$conf);
250
251
            // Reload menus
252
            migrate_reload_menu($db,$langs,$conf,$versionto);
253
        }
254
255
        // Script for VX (X<2.8) -> V2.8
256
        $afterversionarray=explode('.','2.7.9');
257
        $beforeversionarray=explode('.','2.8.9');
258
        //print $versionto.' '.versioncompare($versiontoarray,$afterversionarray).' '.versioncompare($versiontoarray,$beforeversionarray);
259
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
260
        {
261
            migrate_price_facture($db,$langs,$conf);     // Code of this function works for 2.8+ because need a field tva_tx
262
263
            migrate_relationship_tables($db,$langs,$conf,'co_exp','fk_commande','commande','fk_expedition','shipping');
264
265
            migrate_relationship_tables($db,$langs,$conf,'pr_exp','fk_propal','propal','fk_expedition','shipping');
266
267
            migrate_relationship_tables($db,$langs,$conf,'pr_liv','fk_propal','propal','fk_livraison','delivery');
268
269
            migrate_relationship_tables($db,$langs,$conf,'co_liv','fk_commande','commande','fk_livraison','delivery');
270
271
            migrate_relationship_tables($db,$langs,$conf,'co_pr','fk_propale','propal','fk_commande','commande');
272
273
            migrate_relationship_tables($db,$langs,$conf,'fa_pr','fk_propal','propal','fk_facture','facture');
274
275
            migrate_relationship_tables($db,$langs,$conf,'co_fa','fk_commande','commande','fk_facture','facture');
276
277
            migrate_project_user_resp($db,$langs,$conf);
278
279
            migrate_project_task_actors($db,$langs,$conf);
280
281
            // Reload modules
282
            migrate_reload_modules($db,$langs,$conf);
283
284
            // Reload menus
285
            migrate_reload_menu($db,$langs,$conf,$versionto);
286
        }
287
288
        // Script for VX (X<2.9) -> V2.9
289
        $afterversionarray=explode('.','2.8.9');
290
        $beforeversionarray=explode('.','2.9.9');
291
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
292
        {
293
            migrate_project_task_time($db,$langs,$conf);
294
295
            migrate_customerorder_shipping($db,$langs,$conf);
296
297
            migrate_shipping_delivery($db,$langs,$conf);
298
299
            migrate_shipping_delivery2($db,$langs,$conf);
300
301
            // Reload modules
302
            migrate_reload_modules($db,$langs,$conf);
303
304
            // Reload menus
305
            migrate_reload_menu($db,$langs,$conf,$versionto);
306
        }
307
308
        // Script for VX (X<3.0) -> V3.0
309
        $afterversionarray=explode('.','2.9.9');
310
        $beforeversionarray=explode('.','3.0.9');
311
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
312
        {
313
            // Reload modules
314
            migrate_reload_modules($db,$langs,$conf);
315
316
            // Reload menus
317
            migrate_reload_menu($db,$langs,$conf,$versionto);
318
        }
319
320
        // Script for VX (X<3.1) -> V3.1
321
        $afterversionarray=explode('.','3.0.9');
322
        $beforeversionarray=explode('.','3.1.9');
323
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
324
        {
325
            migrate_directories($db,$langs,$conf,'/rss','/externalrss');
326
327
            migrate_actioncomm_element($db,$langs,$conf);
328
329
            // Reload modules
330
            migrate_reload_modules($db,$langs,$conf);
331
332
            // Reload menus
333
            migrate_reload_menu($db,$langs,$conf,$versionto);
334
        }
335
336
        // Script for VX (X<3.2) -> V3.2
337
        $afterversionarray=explode('.','3.1.9');
338
        $beforeversionarray=explode('.','3.2.9');
339
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
340
        {
341
            migrate_price_contrat($db,$langs,$conf);
342
343
        	migrate_mode_reglement($db,$langs,$conf);
344
345
            // Reload modules
346
            migrate_reload_modules($db,$langs,$conf);
347
348
            // Reload menus
349
            migrate_reload_menu($db,$langs,$conf,$versionto);
350
        }
351
352
        // Script for VX (X<3.3) -> V3.3
353
        $afterversionarray=explode('.','3.2.9');
354
        $beforeversionarray=explode('.','3.3.9');
355
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
356
        {
357
        	migrate_categorie_association($db,$langs,$conf);
358
        }
359
360
		// Script for VX (X<3.4) -> V3.4
361
		// No specific scripts
362
363
        // Tasks to do always and only into last targeted version
364
        $afterversionarray=explode('.','3.6.9');	// target is after this
365
        $beforeversionarray=explode('.','3.7.9');	// target is before this
366
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
367
        {
368
       	    migrate_event_assignement($db,$langs,$conf);
369
        }
370
371
        // Scripts for last version
372
        $afterversionarray=explode('.','3.7.9');
373
        $beforeversionarray=explode('.','3.8.9');
374
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
375
        {
376
        	// Reload modules (this must be always and only into last targeted version)
377
			$listofmodule=array(
378
				    	'MAIN_MODULE_AGENDA'=>'newboxdefonly',
379
						'MAIN_MODULE_BARCODE'=>'newboxdefonly',
380
						'MAIN_MODULE_CRON'=>'newboxdefonly',
381
				    	'MAIN_MODULE_COMMANDE'=>'newboxdefonly',
382
				    	'MAIN_MODULE_DEPLACEMENT'=>'newboxdefonly',
383
				    	'MAIN_MODULE_DON'=>'newboxdefonly',
384
				    	'MAIN_MODULE_ECM'=>'newboxdefonly',
385
				    	'MAIN_MODULE_FACTURE'=>'newboxdefonly',
386
				    	'MAIN_MODULE_FOURNISSEUR'=>'newboxdefonly',
387
						'MAIN_MODULE_HOLIDAY'=>'newboxdefonly',
388
						'MAIN_MODULE_OPENSURVEY'=>'newboxdefonly',
389
						'MAIN_MODULE_PAYBOX'=>'newboxdefonly',
390
						'MAIN_MODULE_PRODUIT'=>'newboxdefonly',
391
						'MAIN_MODULE_SOCIETE'=>'newboxdefonly',
392
				    	'MAIN_MODULE_SERVICE'=>'newboxdefonly',
393
						'MAIN_MODULE_USER'=>'newboxdefonly'
394
			);
395
        	migrate_reload_modules($db,$langs,$conf,$listofmodule);
396
397
        	// Reload menus (this must be always and only into last targeted version)
398
        	migrate_reload_menu($db,$langs,$conf,$versionto);
399
        }
400
401
        // Scripts for last version
402
        $afterversionarray=explode('.','3.9.9');
403
        $beforeversionarray=explode('.','4.0.9');
404
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
405
        {
406
            migrate_directories($db,$langs,$conf,'/fckeditor','/medias');
407
        }
408
409
        // Scripts for last version
410
        $afterversionarray=explode('.','4.0.9');
411
        $beforeversionarray=explode('.','5.0.9');
412
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
413
        {
414
            // Migrate to add entity value into llx_societe_remise
415
            migrate_remise_entity($db,$langs,$conf);
416
        
417
            // Migrate to add entity value into llx_societe_remise_except
418
            migrate_remise_except_entity($db,$langs,$conf);
419
        
420
            // Reload modules (this must be always and only into last targeted version)
421
            $listofmodule=array(
422
                'MAIN_MODULE_ACCOUNTING'=>'newboxdefonly',
423
                'MAIN_MODULE_BARCODE'=>'newboxdefonly',
424
                'MAIN_MODULE_CRON'=>'newboxdefonly',
425
                'MAIN_MODULE_FACTURE'=>'newboxdefonly',
426
                'MAIN_MODULE_PRINTING'=>'newboxdefonly',
427
            );
428
            migrate_reload_modules($db,$langs,$conf,$listofmodule);
429
        
430
            // Reload menus (this must be always and only into last targeted version)
431
            migrate_reload_menu($db,$langs,$conf,$versionto);
432
        }
433
        
434
        // Scripts for last version
435
        $afterversionarray=explode('.','5.0.9');
436
        $beforeversionarray=explode('.','6.0.9');
437
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
438
        {
439
            // Reload modules (this must be always and only into last targeted version)
440
            $listofmodule=array(
441
                'MAIN_MODULE_USER'=>'newboxdefonly',
442
            );
443
            migrate_reload_modules($db,$langs,$conf,$listofmodule);
444
        
445
            // Reload menus (this must be always and only into last targeted version)
446
            migrate_reload_menu($db,$langs,$conf,$versionto);
447
        }
448
        
449
        // Can force activation of some module during migration with third paramater = MAIN_MODULE_XXX,MAIN_MODULE_YYY,...
450
        if ($enablemodules)
451
        {
452
            // Reload modules (this must be always and only into last targeted version)
453
            $listofmodules=array();
454
            $tmplistofmodules=explode(',', $enablemodules);
455
            foreach($tmplistofmodules as $value)
456
            {
457
                $listofmodules[$value]='newboxdefonly';
458
            }
459
            migrate_reload_modules($db,$langs,$conf,$listofmodules,1);
460
        }
461
462
463
        print '<tr><td colspan="4"><br>'.$langs->trans("MigrationFinished").'</td></tr>';
464
465
        // On commit dans tous les cas.
466
        // La procedure etant concue pour pouvoir passer plusieurs fois quelquesoit la situation.
467
        $db->commit();
468
        $db->close();
469
470
471
        // Actions for all versions (not in database)
472
        migrate_delete_old_files($db, $langs, $conf);
473
        migrate_delete_old_dir($db, $langs, $conf);
474
        
475
        
476
        dol_mkdir(DOL_DATA_ROOT.'/bank');
477
        migrate_directories($db, $langs, $conf, '/banque/bordereau', '/bank/checkdeposits');
478
    }
479
480
    print '</table>';
481
}
482
else
483
{
484
    print '<div class="error">'.$langs->trans('ErrorWrongParameters').'</div>';
485
    $error++;
486
}
487
488
$ret=0;
489
if ($error && isset($argv[1])) $ret=1;
490
dol_syslog("Exit ".$ret);
491
492
dolibarr_install_syslog("--- upgrade2: end");
493
pFooter($error?2:0,$setuplang);
494
495
if ($db->connected) $db->close();
496
497
// Return code if ran from command line
498
if ($ret) exit($ret);
499
500
501
502
/**
503
 * Reporte liens vers une facture de paiements sur table de jointure (lien n-n paiements factures)
504
 *
505
 * @param	DoliDB		$db		Database handler
506
 * @param	Translate	$langs	Object langs
507
 * @param	Conf		$conf	Object conf
508
 * @return	void
509
 */
510
function migrate_paiements($db,$langs,$conf)
511
{
512
    print '<tr><td colspan="4">';
513
514
    print '<br>';
515
    print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
516
517
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement","fk_facture");
518
    $obj = $db->fetch_object($result);
519
    if ($obj)
520
    {
521
        $sql = "SELECT p.rowid, p.fk_facture, p.amount";
522
        $sql .= " FROM ".MAIN_DB_PREFIX."paiement as p";
523
        $sql .= " WHERE p.fk_facture > 0";
524
525
        $resql = $db->query($sql);
526
527
        dolibarr_install_syslog("upgrade2::migrate_paiements");
528
        if ($resql)
529
        {
530
            $i = 0;
531
            $row = array();
532
            $num = $db->num_rows($resql);
533
534
            while ($i < $num)
535
            {
536
                $obj = $db->fetch_object($resql);
537
                $row[$i][0] = $obj->rowid ;
538
                $row[$i][1] = $obj->fk_facture;
539
                $row[$i][2] = $obj->amount;
540
                $i++;
541
            }
542
        }
543
        else
544
        {
545
            dol_print_error($db);
546
        }
547
548
        if ($num)
549
        {
550
            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...
551
            if ($db->begin())
552
            {
553
                $res = 0;
554
                $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...
555
                for ($i = 0; $i < $num; $i++)
556
                {
557
                    $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
558
                    $sql.= " VALUES (".$row[$i][1].",".$row[$i][0].",".$row[$i][2].")";
559
560
                    $res += $db->query($sql);
561
562
                    $sql = "UPDATE ".MAIN_DB_PREFIX."paiement SET fk_facture = 0 WHERE rowid = ".$row[$i][0];
563
564
                    $res += $db->query($sql);
565
566
                    print $langs->trans('MigrationProcessPaymentUpdate', $row[$i][0])."<br>\n";
567
                }
568
            }
569
570
            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...
571
            {
572
                $db->commit();
573
                print $langs->trans('MigrationSuccessfullUpdate')."<br>";
574
            }
575
            else
576
            {
577
                $db->rollback();
578
                print $langs->trans('MigrationUpdateFailed').'<br>';
579
            }
580
        }
581
        else
582
        {
583
            print $langs->trans('MigrationPaymentsNothingToUpdate')."<br>\n";
584
        }
585
    }
586
    else
587
    {
588
        print $langs->trans('MigrationPaymentsNothingToUpdate')."<br>\n";
589
    }
590
591
    print '</td></tr>';
592
}
593
594
/**
595
 * Corrige paiement orphelins (liens paumes suite a bugs)
596
 * Pour verifier s'il reste des orphelins:
597
 * 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)
598
 *
599
 * @param	DoliDB		$db		Database handler
600
 * @param	Translate	$langs	Object langs
601
 * @param	Conf		$conf	Object conf
602
 * @return	void
603
 */
604
function migrate_paiements_orphelins_1($db,$langs,$conf)
605
{
606
    print '<tr><td colspan="4">';
607
608
    print '<br>';
609
    print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
610
611
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement","fk_facture");
612
    $obj = $db->fetch_object($result);
613
    if ($obj)
614
    {
615
        // Tous les enregistrements qui sortent de cette requete devrait avoir un pere dans llx_paiement_facture
616
        $sql = "SELECT distinct p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,";
617
        $sql.= " bu2.url_id as socid";
618
        $sql.= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)";
619
        $sql.= " LEFT JOIN llx_paiement_facture as pf ON pf.fk_paiement = p.rowid";
620
        $sql.= " LEFT JOIN llx_bank_url as bu2 ON (bu.fk_bank=bu2.fk_bank AND bu2.type = 'company')";
621
        $sql.= " WHERE pf.rowid IS NULL AND (p.rowid=bu.url_id AND bu.type='payment') AND bu.fk_bank = b.rowid";
622
        $sql.= " AND b.rappro = 1";
623
        $sql.= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)";
624
625
        $resql = $db->query($sql);
626
627
        dolibarr_install_syslog("upgrade2::migrate_paiements_orphelins_1");
628
        $row = array();
629
        if ($resql)
630
        {
631
            $i = $j = 0;
632
            $num = $db->num_rows($resql);
633
634
            while ($i < $num)
635
            {
636
                $obj = $db->fetch_object($resql);
637
                if ($obj->pamount == $obj->bamount && $obj->socid)	// Pour etre sur d'avoir bon cas
638
                {
639
                    $row[$j]['paymentid'] = $obj->rowid ;		// paymentid
640
                    $row[$j]['pamount'] = $obj->pamount;
641
                    $row[$j]['fk_bank'] = $obj->fk_bank;
642
                    $row[$j]['bamount'] = $obj->bamount;
643
                    $row[$j]['socid'] = $obj->socid;
644
                    $row[$j]['datec'] = $obj->datec;
645
                    $j++;
646
                }
647
                $i++;
648
            }
649
        }
650
        else
651
        {
652
            dol_print_error($db);
653
        }
654
655
        if (count($row))
656
        {
657
            print $langs->trans('OrphelinsPaymentsDetectedByMethod', 1).': '.count($row)."<br>\n";
658
            $db->begin();
659
660
            $res = 0;
661
            $num=count($row);
662
            for ($i = 0; $i < $num; $i++)
663
            {
664
                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>';
665
666
                // On cherche facture sans lien paiement et du meme montant et pour meme societe.
667
                $sql=" SELECT distinct f.rowid from ".MAIN_DB_PREFIX."facture as f";
668
                $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
669
                $sql.=" WHERE f.fk_statut in (2,3) AND fk_soc = ".$row[$i]['socid']." AND total_ttc = ".$row[$i]['pamount'];
670
                $sql.=" AND pf.fk_facture IS NULL";
671
                $sql.=" ORDER BY f.fk_statut";
672
                //print $sql.'<br>';
673
                $resql=$db->query($sql);
674
                if ($resql)
675
                {
676
                    $num = $db->num_rows($resql);
677
                    //print 'Nb of invoice found for this amount and company :'.$num.'<br>';
678
                    if ($num >= 1)
679
                    {
680
                        $obj=$db->fetch_object($resql);
681
                        $facid=$obj->rowid;
682
683
                        $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
684
                        $sql.= " VALUES (".$facid.",".$row[$i]['paymentid'].",".$row[$i]['pamount'].")";
685
686
                        $res += $db->query($sql);
687
688
                        print $langs->trans('MigrationProcessPaymentUpdate', 'facid='.$facid.'-paymentid='.$row[$i]['paymentid'].'-amount='.$row[$i]['pamount'])."<br>\n";
689
                    }
690
                }
691
                else
692
                {
693
                    print 'ERROR';
694
                }
695
            }
696
697
            if ($res > 0)
698
            {
699
                print $langs->trans('MigrationSuccessfullUpdate')."<br>";
700
            }
701
            else
702
            {
703
                print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
704
            }
705
706
            $db->commit();
707
        }
708
        else
709
        {
710
            print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
711
        }
712
    }
713
    else
714
    {
715
        print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
716
    }
717
718
    print '</td></tr>';
719
}
720
721
/**
722
 * Corrige paiement orphelins (liens paumes suite a bugs)
723
 * Pour verifier s'il reste des orphelins:
724
 * 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)
725
 *
726
 * @param	DoliDB		$db		Database handler
727
 * @param	Translate	$langs	Object langs
728
 * @param	Conf		$conf	Object conf
729
 * @return	void
730
 */
731
function migrate_paiements_orphelins_2($db,$langs,$conf)
732
{
733
    print '<tr><td colspan="4">';
734
735
    print '<br>';
736
    print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
737
738
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement","fk_facture");
739
    $obj = $db->fetch_object($result);
740
    if ($obj)
741
    {
742
        // Tous les enregistrements qui sortent de cette requete devrait avoir un pere dans llx_paiement_facture
743
        $sql = "SELECT distinct p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,";
744
        $sql.= " bu2.url_id as socid";
745
        $sql.= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)";
746
        $sql.= " LEFT JOIN llx_paiement_facture as pf ON pf.fk_paiement = p.rowid";
747
        $sql.= " LEFT JOIN llx_bank_url as bu2 ON (bu.fk_bank = bu2.fk_bank AND bu2.type = 'company')";
748
        $sql.= " WHERE pf.rowid IS NULL AND (p.fk_bank = bu.fk_bank AND bu.type = 'payment') AND bu.fk_bank = b.rowid";
749
        $sql.= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)";
750
751
        $resql = $db->query($sql);
752
753
        dolibarr_install_syslog("upgrade2::migrate_paiements_orphelins_2");
754
        $row = array();
755
        if ($resql)
756
        {
757
            $i = $j = 0;
758
            $num = $db->num_rows($resql);
759
760
            while ($i < $num)
761
            {
762
                $obj = $db->fetch_object($resql);
763
                if ($obj->pamount == $obj->bamount && $obj->socid)	// Pour etre sur d'avoir bon cas
764
                {
765
                    $row[$j]['paymentid'] = $obj->rowid ;		// paymentid
766
                    $row[$j]['pamount'] = $obj->pamount;
767
                    $row[$j]['fk_bank'] = $obj->fk_bank;
768
                    $row[$j]['bamount'] = $obj->bamount;
769
                    $row[$j]['socid'] = $obj->socid;
770
                    $row[$j]['datec'] = $obj->datec;
771
                    $j++;
772
                }
773
                $i++;
774
            }
775
        }
776
        else
777
        {
778
            dol_print_error($db);
779
        }
780
781
        $nberr=0;
782
783
        $num=count($row);
784
        if ($num)
785
        {
786
            print $langs->trans('OrphelinsPaymentsDetectedByMethod', 2).': '.count($row)."<br>\n";
787
            $db->begin();
788
789
            $res = 0;
790
            for ($i = 0; $i < $num; $i++)
791
            {
792
                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>';
793
794
                // On cherche facture sans lien paiement et du meme montant et pour meme societe.
795
                $sql=" SELECT distinct f.rowid from ".MAIN_DB_PREFIX."facture as f";
796
                $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
797
                $sql.=" WHERE f.fk_statut in (2,3) AND fk_soc = ".$row[$i]['socid']." AND total_ttc = ".$row[$i]['pamount'];
798
                $sql.=" AND pf.fk_facture IS NULL";
799
                $sql.=" ORDER BY f.fk_statut";
800
                //print $sql.'<br>';
801
                $resql=$db->query($sql);
802
                if ($resql)
803
                {
804
                    $num = $db->num_rows($resql);
805
                    //print 'Nb of invoice found for this amount and company :'.$num.'<br>';
806
                    if ($num >= 1)
807
                    {
808
                        $obj=$db->fetch_object($resql);
809
                        $facid=$obj->rowid;
810
811
                        $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
812
                        $sql.= " VALUES (".$facid.",".$row[$i]['paymentid'].",".$row[$i]['pamount'].")";
813
                        $res += $db->query($sql);
814
815
                        print $langs->trans('MigrationProcessPaymentUpdate', 'facid='.$facid.'-paymentid='.$row[$i]['paymentid'].'-amount='.$row[$i]['pamount'])."<br>\n";
816
                    }
817
                }
818
                else
819
                {
820
                    print 'ERROR';
821
                    $nberr++;
822
                }
823
            }
824
825
            if ($res > 0)
826
            {
827
                print $langs->trans('MigrationSuccessfullUpdate')."<br>";
828
            }
829
            else
830
            {
831
                print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
832
            }
833
834
            $db->commit();
835
        }
836
        else
837
        {
838
            print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
839
        }
840
841
        // Delete obsolete fields fk_facture
842
        $db->begin();
843
844
        $sql = "ALTER TABLE ".MAIN_DB_PREFIX."paiement DROP COLUMN fk_facture";
845
        $db->query($sql);
846
847
        if (!$nberr)
848
        {
849
            $db->commit();
850
        }
851
        else
852
        {
853
            print 'ERROR';
854
            $db->rollback();
855
        }
856
    }
857
    else
858
    {
859
        print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
860
    }
861
862
    print '</td></tr>';
863
}
864
865
866
/**
867
 * Mise a jour des contrats (gestion du contrat + detail de contrat)
868
 *
869
 * @param	DoliDB		$db		Database handler
870
 * @param	Translate	$langs	Object langs
871
 * @param	Conf		$conf	Object conf
872
 * @return	void
873
 */
874
function migrate_contracts_det($db,$langs,$conf)
875
{
876
    print '<tr><td colspan="4">';
877
878
    $nberr=0;
879
880
    print '<br>';
881
    print '<b>'.$langs->trans('MigrationContractsUpdate')."</b><br>\n";
882
883
    $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,";
884
    $sql.= " p.ref, p.label, p.description, p.price, p.tva_tx, p.duration, cd.rowid";
885
    $sql.= " FROM ".MAIN_DB_PREFIX."contrat as c";
886
    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p";
887
    $sql.= " ON c.fk_product = p.rowid";
888
    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd";
889
    $sql.= " ON c.rowid=cd.fk_contrat";
890
    $sql.= " WHERE cd.rowid IS NULL AND p.rowid IS NOT NULL";
891
    $resql = $db->query($sql);
892
893
    dolibarr_install_syslog("upgrade2::migrate_contracts_det");
894
    if ($resql)
895
    {
896
        $i = 0;
897
        $row = array();
898
        $num = $db->num_rows($resql);
899
900
        if ($num)
901
        {
902
            print $langs->trans('MigrationContractsNumberToUpdate', $num)."<br>\n";
903
            $db->begin();
904
905
            while ($i < $num)
906
            {
907
                $obj = $db->fetch_object($resql);
908
909
                $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet (";
910
                $sql.= "fk_contrat, fk_product, statut, label, description,";
911
                $sql.= "date_ouverture_prevue, date_ouverture, date_fin_validite, tva_tx, qty,";
912
                $sql.= "subprice, price_ht, fk_user_author, fk_user_ouverture)";
913
                $sql.= " VALUES (";
914
                $sql.= $obj->cref.",".($obj->fk_product?$obj->fk_product:0).",";
915
                $sql.= ($obj->mise_en_service?"4":"0").",";
916
                $sql.= "'".$db->escape($obj->label)."', null,";
917
                $sql.= ($obj->mise_en_service?"'".$obj->mise_en_service."'":($obj->date_contrat?"'".$obj->date_contrat."'":"null")).",";
918
                $sql.= ($obj->mise_en_service?"'".$obj->mise_en_service."'":"null").",";
919
                $sql.= ($obj->fin_validite?"'".$obj->fin_validite."'":"null").",";
920
                $sql.= "'".$obj->tva_tx."', 1,";
921
                $sql.= "'".$obj->price."', '".$obj->price."',".$obj->fk_user_author.",";
922
                $sql.= ($obj->mise_en_service?$obj->fk_user_author:"null");
923
                $sql.= ")";
924
925
                if ($db->query($sql))
926
                {
927
                    print $langs->trans('MigrationContractsLineCreation', $obj->cref)."<br>\n";
928
                }
929
                else
930
                {
931
                    dol_print_error($db);
932
                    $nberr++;
933
                }
934
935
                $i++;
936
            }
937
938
            if (! $nberr)
939
            {
940
                //      $db->rollback();
941
                $db->commit();
942
                print $langs->trans('MigrationSuccessfullUpdate')."<br>";
943
            }
944
            else
945
            {
946
                $db->rollback();
947
                print $langs->trans('MigrationUpdateFailed').'<br>';
948
            }
949
        }
950
        else
951
        {
952
            print $langs->trans('MigrationContractsNothingToUpdate')."<br>\n";
953
        }
954
    }
955
    else
956
    {
957
        print $langs->trans('MigrationContractsFieldDontExist')."<br>\n";
958
        //    dol_print_error($db);
959
    }
960
961
    print '</td></tr>';
962
}
963
964
/**
965
 * Function to migrate links into llx_bank_url
966
 *
967
 * @param	DoliDB		$db		Database handler
968
 * @param	Translate	$langs	Object langs
969
 * @param	Conf		$conf	Object conf
970
 * @return	void
971
 */
972
function migrate_links_transfert($db,$langs,$conf)
973
{
974
    print '<tr><td colspan="4">';
975
976
    $nberr=0;
977
978
    print '<br>';
979
    print '<b>'.$langs->trans('MigrationBankTransfertsUpdate')."</b><br>\n";
980
981
    $sql = "SELECT ba.rowid as barowid, bb.rowid as bbrowid";
982
    $sql.= " FROM ".MAIN_DB_PREFIX."bank as bb, ".MAIN_DB_PREFIX."bank as ba";
983
    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON bu.fk_bank = ba.rowid";
984
    $sql.= " WHERE ba.amount = -bb.amount AND ba.fk_account <> bb.fk_account";
985
    $sql.= " AND ba.datev = bb.datev AND ba.datec = bb.datec";
986
    $sql.= " AND bu.fk_bank IS NULL";
987
    $resql = $db->query($sql);
988
989
    dolibarr_install_syslog("upgrade2::migrate_links_transfert");
990
    if ($resql)
991
    {
992
        $i = 0;
993
        $row = array();
994
        $num = $db->num_rows($resql);
995
996
        if ($num)
997
        {
998
            print $langs->trans('MigrationBankTransfertsToUpdate', $num)."<br>\n";
999
            $db->begin();
1000
1001
            while ($i < $num)
1002
            {
1003
                $obj = $db->fetch_object($resql);
1004
1005
                $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url (";
1006
                $sql.= "fk_bank, url_id, url, label, type";
1007
                $sql.= ")";
1008
                $sql.= " VALUES (";
1009
                $sql.= $obj->barowid.",".$obj->bbrowid.", '/compta/bank/ligne.php?rowid=', '(banktransfert)', 'banktransfert'";
1010
                $sql.= ")";
1011
1012
                print $sql.'<br>';
1013
                dolibarr_install_syslog("migrate_links_transfert");
1014
1015
                if (! $db->query($sql))
1016
                {
1017
                    dol_print_error($db);
1018
                    $nberr++;
1019
                }
1020
1021
                $i++;
1022
            }
1023
1024
            if (! $nberr)
1025
            {
1026
                //      $db->rollback();
1027
                $db->commit();
1028
                print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1029
            }
1030
            else
1031
            {
1032
                $db->rollback();
1033
                print $langs->trans('MigrationUpdateFailed').'<br>';
1034
            }
1035
        }
1036
        else {
1037
            print $langs->trans('MigrationBankTransfertsNothingToUpdate')."<br>\n";
1038
        }
1039
    }
1040
    else
1041
    {
1042
        dol_print_error($db);
1043
    }
1044
1045
    print '</td></tr>';
1046
}
1047
1048
/**
1049
 * Mise a jour des date de contrats non renseignees
1050
 *
1051
 * @param	DoliDB		$db		Database handler
1052
 * @param	Translate	$langs	Object langs
1053
 * @param	Conf		$conf	Object conf
1054
 * @return	void
1055
 */
1056
function migrate_contracts_date1($db,$langs,$conf)
1057
{
1058
    print '<tr><td colspan="4">';
1059
1060
    print '<br>';
1061
    print '<b>'.$langs->trans('MigrationContractsEmptyDatesUpdate')."</b><br>\n";
1062
1063
    $sql="update llx_contrat set date_contrat=tms where date_contrat is null";
1064
    dolibarr_install_syslog("upgrade2::migrate_contracts_date1");
1065
    $resql = $db->query($sql);
1066
    if (! $resql) dol_print_error($db);
1067
    if ($db->affected_rows($resql) > 0)
1068
    print $langs->trans('MigrationContractsEmptyDatesUpdateSuccess')."<br>\n";
1069
    else
1070
    print $langs->trans('MigrationContractsEmptyDatesNothingToUpdate')."<br>\n";
1071
1072
    $sql="update llx_contrat set datec=tms where datec is null";
1073
    dolibarr_install_syslog("upgrade2::migrate_contracts_date1");
1074
    $resql = $db->query($sql);
1075
    if (! $resql) dol_print_error($db);
1076
    if ($db->affected_rows($resql) > 0)
1077
    print $langs->trans('MigrationContractsEmptyCreationDatesUpdateSuccess')."<br>\n";
1078
    else
1079
    print $langs->trans('MigrationContractsEmptyCreationDatesNothingToUpdate')."<br>\n";
1080
1081
    print '</td></tr>';
1082
}
1083
1084
/*
1085
 * Mise a jour date contrat avec date min effective mise en service si inferieur
1086
 */
1087
function migrate_contracts_date2($db,$langs,$conf)
1088
{
1089
    print '<tr><td colspan="4">';
1090
1091
    $nberr=0;
1092
1093
    print '<br>';
1094
    print '<b>'.$langs->trans('MigrationContractsInvalidDatesUpdate')."</b><br>\n";
1095
1096
    $sql = "SELECT c.rowid as cref, c.datec, c.date_contrat, MIN(cd.date_ouverture) as datemin";
1097
    $sql.= " FROM ".MAIN_DB_PREFIX."contrat as c,";
1098
    $sql.= " ".MAIN_DB_PREFIX."contratdet as cd";
1099
    $sql.= " WHERE c.rowid=cd.fk_contrat AND cd.date_ouverture IS NOT NULL";
1100
    $sql.= " GROUP BY c.rowid, c.date_contrat";
1101
    $resql = $db->query($sql);
1102
1103
    dolibarr_install_syslog("upgrade2::migrate_contracts_date2");
1104
    if ($resql)
1105
    {
1106
        $i = 0;
1107
        $row = array();
1108
        $num = $db->num_rows($resql);
1109
1110
        if ($num)
1111
        {
1112
            $nbcontratsmodifie=0;
1113
            $db->begin();
1114
1115
            while ($i < $num)
1116
            {
1117
                $obj = $db->fetch_object($resql);
1118
                if ($obj->date_contrat > $obj->datemin)
1119
                {
1120
                    print $langs->trans('MigrationContractsInvalidDateFix', $obj->cref, $obj->date_contrat, $obj->datemin)."<br>\n";
1121
                    $sql ="UPDATE ".MAIN_DB_PREFIX."contrat";
1122
                    $sql.=" SET date_contrat='".$obj->datemin."'";
1123
                    $sql.=" WHERE rowid=".$obj->cref;
1124
                    $resql2=$db->query($sql);
1125
                    if (! $resql2) dol_print_error($db);
1126
1127
                    $nbcontratsmodifie++;
1128
                }
1129
                $i++;
1130
            }
1131
1132
            $db->commit();
1133
1134
            if ($nbcontratsmodifie)
1135
            print $langs->trans('MigrationContractsInvalidDatesNumber', $nbcontratsmodifie)."<br>\n";
1136
            else
1137
            print  $langs->trans('MigrationContractsInvalidDatesNothingToUpdate')."<br>\n";
1138
        }
1139
    }
1140
    else
1141
    {
1142
        dol_print_error($db);
1143
    }
1144
1145
    print '</td></tr>';
1146
}
1147
1148
/**
1149
 * Mise a jour des dates de creation de contrat
1150
 *
1151
 * @param	DoliDB		$db		Database handler
1152
 * @param	Translate	$langs	Object langs
1153
 * @param	Conf		$conf	Object conf
1154
 * @return	void
1155
 */
1156
function migrate_contracts_date3($db,$langs,$conf)
1157
{
1158
    print '<tr><td colspan="4">';
1159
1160
    print '<br>';
1161
    print '<b>'.$langs->trans('MigrationContractsIncoherentCreationDateUpdate')."</b><br>\n";
1162
1163
    $sql="update llx_contrat set datec=date_contrat where datec is null or datec > date_contrat";
1164
    dolibarr_install_syslog("upgrade2::migrate_contracts_date3");
1165
    $resql = $db->query($sql);
1166
    if (! $resql) dol_print_error($db);
1167
    if ($db->affected_rows($resql) > 0)
1168
    print $langs->trans('MigrationContractsIncoherentCreationDateUpdateSuccess')."<br>\n";
1169
    else
1170
    print $langs->trans('MigrationContractsIncoherentCreationDateNothingToUpdate')."<br>\n";
1171
1172
    print '</td></tr>';
1173
}
1174
1175
/**
1176
 * Reouverture des contrats qui ont au moins une ligne non fermee
1177
 *
1178
 * @param	DoliDB		$db		Database handler
1179
 * @param	Translate	$langs	Object langs
1180
 * @param	Conf		$conf	Object conf
1181
 * @return	void
1182
 */
1183
function migrate_contracts_open($db,$langs,$conf)
1184
{
1185
    print '<tr><td colspan="4">';
1186
1187
    print '<br>';
1188
    print '<b>'.$langs->trans('MigrationReopeningContracts')."</b><br>\n";
1189
1190
    $sql = "SELECT c.rowid as cref FROM llx_contrat as c, llx_contratdet as cd";
1191
    $sql.= " WHERE cd.statut = 4 AND c.statut=2 AND c.rowid=cd.fk_contrat";
1192
    dolibarr_install_syslog("upgrade2::migrate_contracts_open");
1193
    $resql = $db->query($sql);
1194
    if (! $resql) dol_print_error($db);
1195
    if ($db->affected_rows($resql) > 0) {
1196
        $i = 0;
1197
        $row = array();
1198
        $num = $db->num_rows($resql);
1199
1200
        if ($num)
1201
        {
1202
            $nbcontratsmodifie=0;
1203
            $db->begin();
1204
1205
            while ($i < $num)
1206
            {
1207
                $obj = $db->fetch_object($resql);
1208
1209
                print $langs->trans('MigrationReopenThisContract', $obj->cref)."<br>\n";
1210
                $sql ="UPDATE ".MAIN_DB_PREFIX."contrat";
1211
                $sql.=" SET statut=1";
1212
                $sql.=" WHERE rowid=".$obj->cref;
1213
                $resql2=$db->query($sql);
1214
                if (! $resql2) dol_print_error($db);
1215
1216
                $nbcontratsmodifie++;
1217
1218
                $i++;
1219
            }
1220
1221
            $db->commit();
1222
1223
            if ($nbcontratsmodifie)
1224
            print $langs->trans('MigrationReopenedContractsNumber', $nbcontratsmodifie)."<br>\n";
1225
            else
1226
            print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n";
1227
        }
1228
    }
1229
    else print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n";
1230
1231
    print '</td></tr>';
1232
}
1233
1234
/**
1235
 * Factures fournisseurs
1236
 *
1237
 * @param	DoliDB		$db		Database handler
1238
 * @param	Translate	$langs	Object langs
1239
 * @param	Conf		$conf	Object conf
1240
 * @return	void
1241
 */
1242
function migrate_paiementfourn_facturefourn($db,$langs,$conf)
1243
{
1244
    global $bc;
1245
1246
    print '<tr><td colspan="4">';
1247
    print '<br>';
1248
    print '<b>'.$langs->trans('SuppliersInvoices')."</b><br>\n";
1249
    print '</td></tr>';
1250
1251
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiementfourn","fk_facture_fourn");
1252
    $obj = $db->fetch_object($result);
1253
    if ($obj)
1254
    {
1255
        $error=0;
1256
        $nb=0;
1257
1258
        $select_sql = 'SELECT rowid, fk_facture_fourn, amount';
1259
        $select_sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn';
1260
        $select_sql.= ' WHERE fk_facture_fourn IS NOT NULL';
1261
1262
        dolibarr_install_syslog("upgrade2::migrate_paiementfourn_facturefourn");
1263
        $select_resql = $db->query($select_sql);
1264
        if ($select_resql)
1265
        {
1266
            $select_num = $db->num_rows($select_resql);
1267
            $i=0;
1268
            $var = true;
1269
1270
            // Pour chaque paiement fournisseur, on insere une ligne dans paiementfourn_facturefourn
1271
            while (($i < $select_num) && (! $error))
1272
            {
1273
                $var = !$var;
1274
                $select_obj = $db->fetch_object($select_resql);
1275
1276
                // Verifier si la ligne est deja dans la nouvelle table. On ne veut pas inserer de doublons.
1277
                $check_sql = 'SELECT fk_paiementfourn, fk_facturefourn';
1278
                $check_sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn';
1279
                $check_sql.= ' WHERE fk_paiementfourn = '.$select_obj->rowid.' AND fk_facturefourn = '.$select_obj->fk_facture_fourn;
1280
                $check_resql = $db->query($check_sql);
1281
                if ($check_resql)
1282
                {
1283
                    $check_num = $db->num_rows($check_resql);
1284
                    if ($check_num == 0)
1285
                    {
1286
                        $db->begin();
1287
1288
                        if ($nb == 0)
1289
                        {
1290
                            print '<tr><td colspan="4" class="nowrap"><b>'.$langs->trans('SuppliersInvoices').'</b></td></tr>';
1291
                            print '<tr><td>fk_paiementfourn</td><td>fk_facturefourn</td><td>'.$langs->trans('Amount').'</td><td>&nbsp;</td></tr>';
1292
                        }
1293
1294
                        print '<tr class="oddeven">';
1295
                        print '<td>'.$select_obj->rowid.'</td><td>'.$select_obj->fk_facture_fourn.'</td><td>'.$select_obj->amount.'</td>';
1296
1297
                        $insert_sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiementfourn_facturefourn SET ';
1298
                        $insert_sql.= ' fk_paiementfourn = \''.$select_obj->rowid.'\',';
1299
                        $insert_sql.= ' fk_facturefourn  = \''.$select_obj->fk_facture_fourn.'\',';
1300
                        $insert_sql.= ' amount           = \''.$select_obj->amount.'\'';
1301
                        $insert_resql = $db->query($insert_sql);
1302
1303
                        if ($insert_resql)
1304
                        {
1305
                            $nb++;
1306
                            print '<td><span style="color:green">'.$langs->trans("OK").'</span></td>';
1307
                        }
1308
                        else
1309
                        {
1310
                            print '<td><span style="color:red">Error on insert</span></td>';
1311
                            $error++;
1312
                        }
1313
                        print '</tr>';
1314
                    }
1315
                }
1316
                else
1317
                {
1318
                    $error++;
1319
                }
1320
                $i++;
1321
            }
1322
        }
1323
        else
1324
        {
1325
            $error++;
1326
        }
1327
1328
        if (!$error)
1329
        {
1330
            if (!$nb)
1331
            {
1332
                print '<tr><td>'.$langs->trans("AlreadyDone").'</td></tr>';
1333
            }
1334
            $db->commit();
1335
1336
            $sql = "ALTER TABLE ".MAIN_DB_PREFIX."paiementfourn DROP COLUMN fk_facture_fourn";
1337
            $db->query($sql);
1338
        }
1339
        else
1340
        {
1341
            print '<tr><td>'.$langs->trans("Error").'</td></tr>';
1342
            $db->rollback();
1343
        }
1344
    }
1345
    else
1346
    {
1347
        print '<tr><td>'.$langs->trans("AlreadyDone").'</td></tr>';
1348
    }
1349
}
1350
1351
/**
1352
 * Mise a jour des totaux lignes de facture
1353
 *
1354
 * @param	DoliDB		$db		Database handler
1355
 * @param	Translate	$langs	Object langs
1356
 * @param	Conf		$conf	Object conf
1357
 * @return	void
1358
 */
1359
function migrate_price_facture($db,$langs,$conf)
1360
{
1361
    $err=0;
1362
1363
    $tmpmysoc=new Societe($db);
1364
    $tmpmysoc->setMysoc($conf);
1365
1366
    $db->begin();
1367
1368
    print '<tr><td colspan="4">';
1369
1370
    print '<br>';
1371
    print '<b>'.$langs->trans('MigrationInvoice')."</b><br>\n";
1372
1373
    // Liste des lignes facture non a jour
1374
    $sql = "SELECT fd.rowid, fd.qty, fd.subprice, fd.remise_percent, fd.tva_tx as vatrate, fd.total_ttc, fd.info_bits,";
1375
    $sql.= " f.rowid as facid, f.remise_percent as remise_percent_global, f.total_ttc as total_ttc_f";
1376
    $sql.= " FROM ".MAIN_DB_PREFIX."facturedet as fd, ".MAIN_DB_PREFIX."facture as f";
1377
    $sql.= " WHERE fd.fk_facture = f.rowid";
1378
    $sql.= " AND (((fd.total_ttc = 0 AND fd.remise_percent != 100) or fd.total_ttc IS NULL) or f.total_ttc IS NULL)";
1379
    //print $sql;
1380
1381
    dolibarr_install_syslog("upgrade2::migrate_price_facture");
1382
    $resql=$db->query($sql);
1383
    if ($resql)
1384
    {
1385
        $num = $db->num_rows($resql);
1386
        $i = 0;
1387
        if ($num)
1388
        {
1389
            while ($i < $num)
1390
            {
1391
                $obj = $db->fetch_object($resql);
1392
1393
                $rowid = $obj->rowid;
1394
                $qty = $obj->qty;
1395
                $pu = $obj->subprice;
1396
                $vatrate = $obj->vatrate;
1397
                $remise_percent = $obj->remise_percent;
1398
                $remise_percent_global = $obj->remise_percent_global;
1399
                $total_ttc_f = $obj->total_ttc_f;
1400
                $info_bits = $obj->info_bits;
1401
1402
                // On met a jour les 3 nouveaux champs
1403
                $facligne= new FactureLigne($db);
1404
                $facligne->fetch($rowid);
1405
1406
                $result=calcul_price_total($qty,$pu,$remise_percent,$vatrate, 0, 0,$remise_percent_global,'HT',$info_bits,$facligne->product_type,$tmpmysoc);
1407
                $total_ht  = $result[0];
1408
                $total_tva = $result[1];
1409
                $total_ttc = $result[2];
1410
1411
                $facligne->total_ht  = $total_ht;
1412
                $facligne->total_tva = $total_tva;
1413
                $facligne->total_ttc = $total_ttc;
1414
1415
                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);
1416
                print ". ";
1417
                $facligne->update_total();
1418
1419
1420
                /* On touche a facture mere uniquement si total_ttc = 0 */
1421
                if (! $total_ttc_f)
1422
                {
1423
                    $facture = new Facture($db);
1424
                    $facture->id=$obj->facid;
1425
1426
                    if ( $facture->fetch($facture->id) >= 0)
1427
                    {
1428
                        if ( $facture->update_price() > 0 )
1429
                        {
1430
                            //print $facture->id;
1431
                        }
1432
                        else
1433
                        {
1434
                            print "Error id=".$facture->id;
1435
                            $err++;
1436
                        }
1437
                    }
1438
                    else
1439
                    {
1440
                        print "Error #3";
1441
                        $err++;
1442
                    }
1443
                }
1444
                print " ";
1445
1446
                $i++;
1447
            }
1448
        }
1449
        else
1450
        {
1451
            print $langs->trans("AlreadyDone");
1452
        }
1453
        $db->free($resql);
1454
1455
        $db->commit();
1456
    }
1457
    else
1458
    {
1459
        print "Error #1 ".$db->error();
1460
        $err++;
1461
1462
        $db->rollback();
1463
    }
1464
1465
    print '<br>';
1466
1467
    print '</td></tr>';
1468
}
1469
1470
/**
1471
 * Mise a jour des totaux lignes de propal
1472
 *
1473
 * @param	DoliDB		$db		Database handler
1474
 * @param	Translate	$langs	Object langs
1475
 * @param	Conf		$conf	Object conf
1476
 * @return	void
1477
 */
1478
function migrate_price_propal($db,$langs,$conf)
1479
{
1480
   	$tmpmysoc=new Societe($db);
1481
	$tmpmysoc->setMysoc($conf);
1482
1483
    $db->begin();
1484
1485
    print '<tr><td colspan="4">';
1486
1487
    print '<br>';
1488
    print '<b>'.$langs->trans('MigrationProposal')."</b><br>\n";
1489
1490
    // Liste des lignes propal non a jour
1491
    $sql = "SELECT pd.rowid, pd.qty, pd.subprice, pd.remise_percent, pd.tva_tx as vatrate, pd.info_bits,";
1492
    $sql.= " p.rowid as propalid, p.remise_percent as remise_percent_global";
1493
    $sql.= " FROM ".MAIN_DB_PREFIX."propaldet as pd, ".MAIN_DB_PREFIX."propal as p";
1494
    $sql.= " WHERE pd.fk_propal = p.rowid";
1495
    $sql.= " AND ((pd.total_ttc = 0 AND pd.remise_percent != 100) or pd.total_ttc IS NULL)";
1496
1497
    dolibarr_install_syslog("upgrade2::migrate_price_propal");
1498
    $resql=$db->query($sql);
1499
    if ($resql)
1500
    {
1501
        $num = $db->num_rows($resql);
1502
        $i = 0;
1503
        if ($num)
1504
        {
1505
            while ($i < $num)
1506
            {
1507
                $obj = $db->fetch_object($resql);
1508
1509
                $rowid = $obj->rowid;
1510
                $qty = $obj->qty;
1511
                $pu = $obj->subprice;
1512
                $vatrate = $obj->vatrate;
1513
                $remise_percent = $obj->remise_percent;
1514
                $remise_percent_global = $obj->remise_percent_global;
1515
                $info_bits = $obj->info_bits;
1516
1517
                // On met a jour les 3 nouveaux champs
1518
                $propalligne= new PropaleLigne($db);
1519
                $propalligne->fetch($rowid);
1520
1521
                $result=calcul_price_total($qty,$pu,$remise_percent,$vatrate,0,0,$remise_percent_global,'HT',$info_bits,$propalligne->product_type,$tmpmysoc);
1522
                $total_ht  = $result[0];
1523
                $total_tva = $result[1];
1524
                $total_ttc = $result[2];
1525
1526
                $propalligne->total_ht  = $total_ht;
1527
                $propalligne->total_tva = $total_tva;
1528
                $propalligne->total_ttc = $total_ttc;
1529
1530
                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);
1531
                print ". ";
1532
                $propalligne->update_total();
1533
1534
1535
                /* On touche pas a propal mere
1536
                 $propal = new Propal($db);
1537
                 $propal->id=$obj->rowid;
1538
                 if ( $propal->fetch($propal->id) >= 0 )
1539
                 {
1540
                 if ( $propal->update_price() > 0 )
1541
                 {
1542
                 print ". ";
1543
                 }
1544
                 else
1545
                 {
1546
                 print "Error id=".$propal->id;
1547
                 }
1548
                 }
1549
                 else
1550
                 {
1551
                 print "Error #3";
1552
                 }
1553
                 */
1554
                $i++;
1555
            }
1556
        }
1557
        else
1558
        {
1559
            print $langs->trans("AlreadyDone");
1560
        }
1561
1562
        $db->free($resql);
1563
1564
        $db->commit();
1565
    }
1566
    else
1567
    {
1568
        print "Error #1 ".$db->error();
1569
1570
        $db->rollback();
1571
    }
1572
1573
    print '<br>';
1574
1575
    print '</td></tr>';
1576
}
1577
1578
/**
1579
 * Update total of contract lines
1580
 *
1581
 * @param	DoliDB		$db		Database handler
1582
 * @param	Translate	$langs	Object langs
1583
 * @param	Conf		$conf	Object conf
1584
 * @return	void
1585
 */
1586
function migrate_price_contrat($db,$langs,$conf)
1587
{
1588
    $db->begin();
1589
1590
   	$tmpmysoc=new Societe($db);
1591
	$tmpmysoc->setMysoc($conf);
1592
    if (empty($tmpmysoc->country_id)) $tmpmysoc->country_id=0;	// Ti not have this set to '' or will make sql syntax error.
1593
1594
    print '<tr><td colspan="4">';
1595
1596
    print '<br>';
1597
    print '<b>'.$langs->trans('MigrationContract')."</b><br>\n";
1598
1599
    // Liste des lignes contrat non a jour
1600
    $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
1601
    $sql.= " c.rowid as contratid";
1602
    $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c";
1603
    $sql.= " WHERE cd.fk_contrat = c.rowid";
1604
    $sql.= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100 AND cd.subprice > 0) or cd.total_ttc IS NULL)";
1605
1606
    dolibarr_install_syslog("upgrade2::migrate_price_contrat");
1607
    $resql=$db->query($sql);
1608
    if ($resql)
1609
    {
1610
        $num = $db->num_rows($resql);
1611
        $i = 0;
1612
        if ($num)
1613
        {
1614
            while ($i < $num)
1615
            {
1616
                $obj = $db->fetch_object($resql);
1617
1618
                $rowid = $obj->rowid;
1619
                $qty = $obj->qty;
1620
                $pu = $obj->subprice;
1621
                $vatrate = $obj->vatrate;
1622
                $remise_percent = $obj->remise_percent;
1623
                $info_bits = $obj->info_bits;
1624
1625
                // On met a jour les 3 nouveaux champs
1626
                $contratligne= new ContratLigne($db);
1627
                //$contratligne->fetch($rowid); Non requis car le update_total ne met a jour que chp redefinis
1628
                $contratligne->fetch($rowid);
1629
1630
                $result=calcul_price_total($qty,$pu,$remise_percent,$vatrate,0,0,0,'HT',$info_bits,$contratligne->product_type,$tmpmysoc);
1631
                $total_ht  = $result[0];
1632
                $total_tva = $result[1];
1633
                $total_ttc = $result[2];
1634
1635
                $contratligne->total_ht  = $total_ht;
1636
                $contratligne->total_tva = $total_tva;
1637
                $contratligne->total_ttc = $total_ttc;
1638
1639
                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);
1640
                print ". ";
1641
                $contratligne->update_total();
1642
1643
                $i++;
1644
            }
1645
        }
1646
        else
1647
        {
1648
            print $langs->trans("AlreadyDone");
1649
        }
1650
1651
        $db->free($resql);
1652
1653
        $db->commit();
1654
    }
1655
    else
1656
    {
1657
        print "Error #1 ".$db->error();
1658
1659
        $db->rollback();
1660
    }
1661
1662
    print '<br>';
1663
1664
    print '</td></tr>';
1665
}
1666
1667
/**
1668
 * Mise a jour des totaux lignes de commande
1669
 *
1670
 * @param	DoliDB		$db		Database handler
1671
 * @param	Translate	$langs	Object langs
1672
 * @param	Conf		$conf	Object conf
1673
 * @return	void
1674
 */
1675
function migrate_price_commande($db,$langs,$conf)
1676
{
1677
    $db->begin();
1678
1679
    $tmpmysoc=new Societe($db);
1680
    $tmpmysoc->setMysoc($conf);
1681
1682
    print '<tr><td colspan="4">';
1683
1684
    print '<br>';
1685
    print '<b>'.$langs->trans('MigrationOrder')."</b><br>\n";
1686
1687
    // Liste des lignes commande non a jour
1688
    $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
1689
    $sql.= " c.rowid as commandeid, c.remise_percent as remise_percent_global";
1690
    $sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."commande as c";
1691
    $sql.= " WHERE cd.fk_commande = c.rowid";
1692
    $sql.= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)";
1693
1694
    dolibarr_install_syslog("upgrade2::migrate_price_commande");
1695
    $resql=$db->query($sql);
1696
    if ($resql)
1697
    {
1698
        $num = $db->num_rows($resql);
1699
        $i = 0;
1700
        if ($num)
1701
        {
1702
            while ($i < $num)
1703
            {
1704
                $obj = $db->fetch_object($resql);
1705
1706
                $rowid = $obj->rowid;
1707
                $qty = $obj->qty;
1708
                $pu = $obj->subprice;
1709
                $vatrate = $obj->vatrate;
1710
                $remise_percent = $obj->remise_percent;
1711
                $remise_percent_global = $obj->remise_percent_global;
1712
                $info_bits = $obj->info_bits;
1713
1714
                // On met a jour les 3 nouveaux champs
1715
                $commandeligne= new OrderLine($db);
1716
                $commandeligne->fetch($rowid);
1717
1718
                $result=calcul_price_total($qty,$pu,$remise_percent,$vatrate,0,0,$remise_percent_global,'HT',$info_bits,$commandeligne->product_type,$tmpmysoc);
1719
                $total_ht  = $result[0];
1720
                $total_tva = $result[1];
1721
                $total_ttc = $result[2];
1722
1723
                $commandeligne->total_ht  = $total_ht;
1724
                $commandeligne->total_tva = $total_tva;
1725
                $commandeligne->total_ttc = $total_ttc;
1726
1727
                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);
1728
                print ". ";
1729
                $commandeligne->update_total();
1730
1731
                /* On touche pas a facture mere
1732
                 $commande = new Commande($db);
1733
                 $commande->id = $obj->rowid;
1734
                 if ( $commande->fetch($commande->id) >= 0 )
1735
                 {
1736
                 if ( $commande->update_price() > 0 )
1737
                 {
1738
                 print ". ";
1739
                 }
1740
                 else
1741
                 {
1742
                 print "Error id=".$commande->id;
1743
                 }
1744
                 }
1745
                 else
1746
                 {
1747
                 print "Error #3";
1748
                 }
1749
                 */
1750
                $i++;
1751
            }
1752
        }
1753
        else
1754
        {
1755
            print $langs->trans("AlreadyDone");
1756
        }
1757
1758
        $db->free($resql);
1759
1760
        /*
1761
         $sql = "DELETE FROM ".MAIN_DB_PREFIX."commandedet";
1762
         $sql.= " WHERE price = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0 AND remise_percent = 0";
1763
         $resql=$db->query($sql);
1764
         if (! $resql)
1765
         {
1766
         dol_print_error($db);
1767
         }
1768
         */
1769
1770
        $db->commit();
1771
    }
1772
    else
1773
    {
1774
        print "Error #1 ".$db->error();
1775
1776
        $db->rollback();
1777
    }
1778
1779
    print '<br>';
1780
1781
    print '</td></tr>';
1782
}
1783
1784
/**
1785
 * Mise a jour des totaux lignes de commande fournisseur
1786
 *
1787
 * @param	DoliDB		$db		Database handler
1788
 * @param	Translate	$langs	Object langs
1789
 * @param	Conf		$conf	Object conf
1790
 * @return	void
1791
 */
1792
function migrate_price_commande_fournisseur($db,$langs,$conf)
1793
{
1794
    $db->begin();
1795
1796
    $tmpmysoc=new Societe($db);
1797
    $tmpmysoc->setMysoc($conf);
1798
1799
    print '<tr><td colspan="4">';
1800
1801
    print '<br>';
1802
    print '<b>'.$langs->trans('MigrationSupplierOrder')."</b><br>\n";
1803
1804
    // Liste des lignes commande non a jour
1805
    $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
1806
    $sql.= " c.rowid as commandeid, c.remise_percent as remise_percent_global";
1807
    $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd, ".MAIN_DB_PREFIX."commande_fournisseur as c";
1808
    $sql.= " WHERE cd.fk_commande = c.rowid";
1809
    $sql.= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)";
1810
1811
    dolibarr_install_syslog("upgrade2::migrate_price_commande_fournisseur");
1812
    $resql=$db->query($sql);
1813
    if ($resql)
1814
    {
1815
        $num = $db->num_rows($resql);
1816
        $i = 0;
1817
        if ($num)
1818
        {
1819
            while ($i < $num)
1820
            {
1821
                $obj = $db->fetch_object($resql);
1822
1823
                $rowid = $obj->rowid;
1824
                $qty = $obj->qty;
1825
                $pu = $obj->subprice;
1826
                $vatrate = $obj->vatrate;
1827
                $remise_percent = $obj->remise_percent;
1828
                $remise_percent_global = $obj->remise_percent_global;
1829
                $info_bits = $obj->info_bits;
1830
1831
                // On met a jour les 3 nouveaux champs
1832
                $commandeligne= new CommandeFournisseurLigne($db);
1833
                $commandeligne->fetch($rowid);
1834
1835
                $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...
1836
                $total_ht  = $result[0];
1837
                $total_tva = $result[1];
1838
                $total_ttc = $result[2];
1839
1840
                $commandeligne->total_ht  = $total_ht;
1841
                $commandeligne->total_tva = $total_tva;
1842
                $commandeligne->total_ttc = $total_ttc;
1843
1844
                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);
1845
                print ". ";
1846
                $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...
1847
1848
                /* On touche pas a facture mere
1849
                 $commande = new Commande($db);
1850
                 $commande->id = $obj->rowid;
1851
                 if ( $commande->fetch($commande->id) >= 0 )
1852
                 {
1853
                 if ( $commande->update_price() > 0 )
1854
                 {
1855
                 print ". ";
1856
                 }
1857
                 else
1858
                 {
1859
                 print "Error id=".$commande->id;
1860
                 }
1861
                 }
1862
                 else
1863
                 {
1864
                 print "Error #3";
1865
                 }
1866
                 */
1867
                $i++;
1868
            }
1869
        }
1870
        else
1871
        {
1872
            print $langs->trans("AlreadyDone");
1873
        }
1874
1875
        $db->free($resql);
1876
1877
        /*
1878
         $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet";
1879
         $sql.= " WHERE subprice = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0";
1880
         $resql=$db->query($sql);
1881
         if (! $resql)
1882
         {
1883
         dol_print_error($db);
1884
         }
1885
         */
1886
1887
        $db->commit();
1888
    }
1889
    else
1890
    {
1891
        print "Error #1 ".$db->error();
1892
1893
        $db->rollback();
1894
    }
1895
1896
    print '<br>';
1897
1898
    print '</td></tr>';
1899
}
1900
1901
/**
1902
 * Mise a jour des modeles selectionnes
1903
 *
1904
 * @param	DoliDB		$db		Database handler
1905
 * @param	Translate	$langs	Object langs
1906
 * @param	Conf		$conf	Object conf
1907
 * @return	void
1908
 */
1909
function migrate_modeles($db,$langs,$conf)
1910
{
1911
    //print '<br>';
1912
    //print '<b>'.$langs->trans('UpdateModelsTable')."</b><br>\n";
1913
1914
    dolibarr_install_syslog("upgrade2::migrate_modeles");
1915
1916
    if (! empty($conf->facture->enabled))
1917
    {
1918
        include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
1919
        $modellist=ModelePDFFactures::liste_modeles($db);
1920
        if (count($modellist)==0)
1921
        {
1922
            // Aucun model par defaut.
1923
            $sql=" insert into llx_document_model(nom,type) values('crabe','invoice')";
1924
            $resql = $db->query($sql);
1925
            if (! $resql) dol_print_error($db);
1926
        }
1927
    }
1928
1929
    if (! empty($conf->commande->enabled))
1930
    {
1931
        include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
1932
        $modellist=ModelePDFCommandes::liste_modeles($db);
1933
        if (count($modellist)==0)
1934
        {
1935
            // Aucun model par defaut.
1936
            $sql=" insert into llx_document_model(nom,type) values('einstein','order')";
1937
            $resql = $db->query($sql);
1938
            if (! $resql) dol_print_error($db);
1939
        }
1940
    }
1941
1942
    if (! empty($conf->expedition->enabled))
1943
    {
1944
        include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
1945
        $modellist=ModelePDFExpedition::liste_modeles($db);
1946
        if (count($modellist)==0)
1947
        {
1948
            // Aucun model par defaut.
1949
            $sql=" insert into llx_document_model(nom,type) values('rouget','shipping')";
1950
            $resql = $db->query($sql);
1951
            if (! $resql) dol_print_error($db);
1952
        }
1953
    }
1954
1955
    //print $langs->trans("AlreadyDone");
1956
}
1957
1958
1959
/**
1960
 * Correspondance des expeditions et des commandes clients dans la table llx_co_exp
1961
 *
1962
 * @param	DoliDB		$db		Database handler
1963
 * @param	Translate	$langs	Object langs
1964
 * @param	Conf		$conf	Object conf
1965
 * @return	void
1966
 */
1967
function migrate_commande_expedition($db,$langs,$conf)
1968
{
1969
    dolibarr_install_syslog("upgrade2::migrate_commande_expedition");
1970
1971
    print '<tr><td colspan="4">';
1972
1973
    print '<br>';
1974
    print '<b>'.$langs->trans('MigrationShipmentOrderMatching')."</b><br>\n";
1975
1976
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."expedition","fk_commande");
1977
    $obj = $db->fetch_object($result);
1978
    if ($obj)
1979
    {
1980
        $error = 0;
1981
1982
        $db->begin();
1983
1984
        $sql = "SELECT e.rowid, e.fk_commande FROM ".MAIN_DB_PREFIX."expedition as e";
1985
        $resql = $db->query($sql);
1986
        if ($resql)
1987
        {
1988
            $i = 0;
1989
            $num = $db->num_rows($resql);
1990
1991
            if ($num)
1992
            {
1993
                while ($i < $num)
1994
                {
1995
                    $obj = $db->fetch_object($resql);
1996
1997
                    $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_exp (fk_expedition,fk_commande)";
1998
                    $sql.= " VALUES (".$obj->rowid.",".$obj->fk_commande.")";
1999
                    $resql2=$db->query($sql);
2000
2001
                    if (!$resql2)
2002
                    {
2003
                        $error++;
2004
                        dol_print_error($db);
2005
                    }
2006
                    print ". ";
2007
                    $i++;
2008
                }
2009
            }
2010
2011
            if ($error == 0)
2012
            {
2013
                $db->commit();
2014
                $sql = "ALTER TABLE ".MAIN_DB_PREFIX."expedition DROP COLUMN fk_commande";
2015
                print $langs->trans('FieldRenamed')."<br>\n";
2016
                $db->query($sql);
2017
            }
2018
            else
2019
            {
2020
                $db->rollback();
2021
            }
2022
        }
2023
        else
2024
        {
2025
            dol_print_error($db);
2026
            $db->rollback();
2027
        }
2028
    }
2029
    else
2030
    {
2031
        print $langs->trans('AlreadyDone')."<br>\n";
2032
    }
2033
    print '</td></tr>';
2034
}
2035
2036
/**
2037
 * Correspondance des livraisons et des commandes clients dans la table llx_co_liv
2038
 *
2039
 * @param	DoliDB		$db		Database handler
2040
 * @param	Translate	$langs	Object langs
2041
 * @param	Conf		$conf	Object conf
2042
 * @return	void
2043
 */
2044
function migrate_commande_livraison($db,$langs,$conf)
2045
{
2046
    dolibarr_install_syslog("upgrade2::migrate_commande_livraison");
2047
2048
    print '<tr><td colspan="4">';
2049
2050
    print '<br>';
2051
    print '<b>'.$langs->trans('MigrationDeliveryOrderMatching')."</b><br>\n";
2052
2053
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraison","fk_commande");
2054
    $obj = $db->fetch_object($result);
2055
    if ($obj)
2056
    {
2057
        $error = 0;
2058
2059
        $db->begin();
2060
2061
        $sql = "SELECT l.rowid, l.fk_commande";
2062
        $sql.= ", c.ref_client, c.date_livraison";
2063
        $sql.= " FROM ".MAIN_DB_PREFIX."livraison as l, ".MAIN_DB_PREFIX."commande as c";
2064
        $sql.= " WHERE c.rowid = l.fk_commande";
2065
        $resql = $db->query($sql);
2066
        if ($resql)
2067
        {
2068
            $i = 0;
2069
            $num = $db->num_rows($resql);
2070
2071
            if ($num)
2072
            {
2073
                while ($i < $num)
2074
                {
2075
                    $obj = $db->fetch_object($resql);
2076
2077
                    $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_liv (fk_livraison,fk_commande)";
2078
                    $sql.= " VALUES (".$obj->rowid.",".$obj->fk_commande.")";
2079
                    $resql2=$db->query($sql);
2080
2081
                    if ($resql2)
2082
                    {
2083
                        $sqlu = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
2084
                        $sqlu.= " ref_client='".$obj->ref_client."'";
2085
                        $sqlu.= ", date_livraison='".$obj->date_livraison."'";
2086
                        $sqlu.= " WHERE rowid = ".$obj->rowid;
2087
                        $resql3=$db->query($sqlu);
2088
                        if (!$resql3)
2089
                        {
2090
                            $error++;
2091
                            dol_print_error($db);
2092
                        }
2093
                    }
2094
                    else
2095
                    {
2096
                        $error++;
2097
                        dol_print_error($db);
2098
                    }
2099
                    print ". ";
2100
                    $i++;
2101
                }
2102
            }
2103
2104
            if ($error == 0)
2105
            {
2106
                $db->commit();
2107
                $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraison DROP COLUMN fk_commande";
2108
                print $langs->trans('FieldRenamed')."<br>\n";
2109
                $db->query($sql);
2110
            }
2111
            else
2112
            {
2113
                $db->rollback();
2114
            }
2115
        }
2116
        else
2117
        {
2118
            dol_print_error($db);
2119
            $db->rollback();
2120
        }
2121
    }
2122
    else
2123
    {
2124
        print $langs->trans('AlreadyDone')."<br>\n";
2125
    }
2126
    print '</td></tr>';
2127
}
2128
2129
/**
2130
 * Migration des details commandes dans les details livraisons
2131
 *
2132
 * @param	DoliDB		$db		Database handler
2133
 * @param	Translate	$langs	Object langs
2134
 * @param	Conf		$conf	Object conf
2135
 * @return	void
2136
 */
2137
function migrate_detail_livraison($db,$langs,$conf)
2138
{
2139
    dolibarr_install_syslog("upgrade2::migrate_detail_livraison");
2140
2141
    print '<tr><td colspan="4">';
2142
2143
    print '<br>';
2144
    print '<b>'.$langs->trans('MigrationDeliveryDetail')."</b><br>\n";
2145
2146
    // This is done if field fk_commande_ligne exists.
2147
    // If not this means migration was already done.
2148
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraisondet","fk_commande_ligne");
2149
    $obj = $db->fetch_object($result);
2150
    if ($obj)
2151
    {
2152
        $error = 0;
2153
2154
        $db->begin();
2155
2156
        $sql = "SELECT cd.rowid, cd.fk_product, cd.description, cd.subprice, cd.total_ht";
2157
        $sql.= ", ld.fk_livraison";
2158
        $sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."livraisondet as ld";
2159
        $sql.= " WHERE ld.fk_commande_ligne = cd.rowid";
2160
        $resql = $db->query($sql);
2161
        if ($resql)
2162
        {
2163
            $i = 0;
2164
            $num = $db->num_rows($resql);
2165
2166
            if ($num)
2167
            {
2168
                while ($i < $num)
2169
                {
2170
                    $obj = $db->fetch_object($resql);
2171
2172
                    $sql = "UPDATE ".MAIN_DB_PREFIX."livraisondet SET";
2173
                    $sql.= " fk_product=".$obj->fk_product;
2174
                    $sql.= ",description='".$db->escape($obj->description)."'";
2175
                    $sql.= ",subprice='".$obj->subprice."'";
2176
                    $sql.= ",total_ht='".$obj->total_ht."'";
2177
                    $sql.= " WHERE fk_commande_ligne = ".$obj->rowid;
2178
                    $resql2=$db->query($sql);
2179
2180
                    if ($resql2)
2181
                    {
2182
                        $sql = "SELECT total_ht";
2183
                        $sql.= " FROM ".MAIN_DB_PREFIX."livraison";
2184
                        $sql.= " WHERE rowid = ".$obj->fk_livraison;
2185
                        $resql3=$db->query($sql);
2186
2187
                        if ($resql3)
2188
                        {
2189
                            $obju = $db->fetch_object($resql3);
2190
                            $total_ht = $obju->total_ht + $obj->total_ht;
2191
2192
                            $sqlu = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
2193
                            $sqlu.= " total_ht='".$total_ht."'";
2194
                            $sqlu.= " WHERE rowid=".$obj->fk_livraison;
2195
                            $resql4=$db->query($sqlu);
2196
                            if (!$resql4)
2197
                            {
2198
                                $error++;
2199
                                dol_print_error($db);
2200
                            }
2201
                        }
2202
                        else
2203
                        {
2204
                            $error++;
2205
                            dol_print_error($db);
2206
                        }
2207
                    }
2208
                    else
2209
                    {
2210
                        $error++;
2211
                        dol_print_error($db);
2212
                    }
2213
                    print ". ";
2214
                    $i++;
2215
                }
2216
2217
            }
2218
2219
            if ($error == 0)
2220
            {
2221
                $db->commit();
2222
                $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraisondet CHANGE fk_commande_ligne fk_origin_line integer";
2223
                print $langs->trans('FieldRenamed')."<br>\n";
2224
                $db->query($sql);
2225
            }
2226
            else
2227
            {
2228
                $db->rollback();
2229
            }
2230
        }
2231
        else
2232
        {
2233
            dol_print_error($db);
2234
            $db->rollback();
2235
        }
2236
    }
2237
    else
2238
    {
2239
        $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraisondet","fk_origin_line");
2240
        $obj = $db->fetch_object($result);
2241
        if (!$obj)
2242
        {
2243
            $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraisondet ADD COLUMN fk_origin_line integer after fk_livraison";
2244
            $db->query($sql);
2245
        }
2246
        print $langs->trans('AlreadyDone')."<br>\n";
2247
    }
2248
    print '</td></tr>';
2249
}
2250
2251
/**
2252
 * Migration du champ stock dans produits
2253
 *
2254
 * @param	DoliDB		$db		Database handler
2255
 * @param	Translate	$langs	Object langs
2256
 * @param	Conf		$conf	Object conf
2257
 * @return	void
2258
 */
2259
function migrate_stocks($db,$langs,$conf)
2260
{
2261
    dolibarr_install_syslog("upgrade2::migrate_stocks");
2262
2263
    print '<tr><td colspan="4">';
2264
2265
    print '<br>';
2266
    print '<b>'.$langs->trans('MigrationStockDetail')."</b><br>\n";
2267
2268
    $error = 0;
2269
2270
    $db->begin();
2271
2272
    $sql = "SELECT SUM(reel) as total, fk_product";
2273
    $sql.= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
2274
    $sql.= " GROUP BY fk_product";
2275
    $resql = $db->query($sql);
2276
    if ($resql)
2277
    {
2278
        $i = 0;
2279
        $num = $db->num_rows($resql);
2280
2281
        if ($num)
2282
        {
2283
            while ($i < $num)
2284
            {
2285
                $obj = $db->fetch_object($resql);
2286
2287
                $sql = "UPDATE ".MAIN_DB_PREFIX."product SET";
2288
                $sql.= " stock = '".$obj->total."'";
2289
                $sql.= " WHERE rowid=".$obj->fk_product;
2290
2291
                $resql2=$db->query($sql);
2292
                if ($resql2)
2293
                {
2294
2295
                }
2296
                else
2297
                {
2298
                    $error++;
2299
                    dol_print_error($db);
2300
                }
2301
                print ". ";
2302
                $i++;
2303
            }
2304
2305
        }
2306
2307
        if ($error == 0)
2308
        {
2309
            $db->commit();
2310
        }
2311
        else
2312
        {
2313
            $db->rollback();
2314
        }
2315
    }
2316
    else
2317
    {
2318
        dol_print_error($db);
2319
        $db->rollback();
2320
    }
2321
2322
    print '</td></tr>';
2323
}
2324
2325
/**
2326
 * Migration of menus (use only 1 table instead of 3)
2327
 * 2.6 -> 2.7
2328
 *
2329
 * @param	DoliDB		$db		Database handler
2330
 * @param	Translate	$langs	Object langs
2331
 * @param	Conf		$conf	Object conf
2332
 * @return	void
2333
 */
2334
function migrate_menus($db,$langs,$conf)
2335
{
2336
    dolibarr_install_syslog("upgrade2::migrate_menus");
2337
2338
    print '<tr><td colspan="4">';
2339
2340
    print '<br>';
2341
    print '<b>'.$langs->trans('MigrationMenusDetail')."</b><br>\n";
2342
2343
    $error = 0;
2344
2345
    if ($db->DDLInfoTable(MAIN_DB_PREFIX."menu_constraint"))
2346
    {
2347
        $db->begin();
2348
2349
        $sql = "SELECT m.rowid, mc.action";
2350
        $sql.= " FROM ".MAIN_DB_PREFIX."menu_constraint as mc, ".MAIN_DB_PREFIX."menu_const as md, ".MAIN_DB_PREFIX."menu as m";
2351
        $sql.= " WHERE md.fk_menu = m.rowid AND md.fk_constraint = mc.rowid";
2352
        $sql.= " AND m.enabled = '1'";
2353
        $resql = $db->query($sql);
2354
        if ($resql)
2355
        {
2356
            $i = 0;
2357
            $num = $db->num_rows($resql);
2358
            if ($num)
2359
            {
2360
                while ($i < $num)
2361
                {
2362
                    $obj = $db->fetch_object($resql);
2363
2364
                    $sql = "UPDATE ".MAIN_DB_PREFIX."menu SET";
2365
                    $sql.= " enabled = '".$obj->action."'";
2366
                    $sql.= " WHERE rowid=".$obj->rowid;
2367
                    $sql.= " AND enabled = '1'";
2368
2369
                    $resql2=$db->query($sql);
2370
                    if ($resql2)
2371
                    {
2372
2373
                    }
2374
                    else
2375
                    {
2376
                        $error++;
2377
                        dol_print_error($db);
2378
                    }
2379
                    print ". ";
2380
                    $i++;
2381
                }
2382
            }
2383
2384
            if ($error == 0)
2385
            {
2386
                $db->commit();
2387
            }
2388
            else
2389
            {
2390
                $db->rollback();
2391
            }
2392
        }
2393
        else
2394
        {
2395
            dol_print_error($db);
2396
            $db->rollback();
2397
        }
2398
    }
2399
    else
2400
    {
2401
        print $langs->trans('AlreadyDone')."<br>\n";
2402
    }
2403
2404
    print '</td></tr>';
2405
}
2406
2407
/**
2408
 * Migration du champ fk_adresse_livraison dans expedition
2409
 * 2.6 -> 2.7
2410
 *
2411
 * @param	DoliDB		$db		Database handler
2412
 * @param	Translate	$langs	Object langs
2413
 * @param	Conf		$conf	Object conf
2414
 * @return	void
2415
 */
2416
function migrate_commande_deliveryaddress($db,$langs,$conf)
2417
{
2418
    dolibarr_install_syslog("upgrade2::migrate_commande_deliveryaddress");
2419
2420
    print '<tr><td colspan="4">';
2421
2422
    print '<br>';
2423
    print '<b>'.$langs->trans('MigrationDeliveryAddress')."</b><br>\n";
2424
2425
    $error = 0;
2426
2427
    if ($db->DDLInfoTable(MAIN_DB_PREFIX."co_exp"))
2428
    {
2429
        $db->begin();
2430
2431
        $sql = "SELECT c.fk_adresse_livraison, ce.fk_expedition";
2432
        $sql.= " FROM ".MAIN_DB_PREFIX."commande as c";
2433
        $sql.= ", ".MAIN_DB_PREFIX."co_exp as ce";
2434
        $sql.= " WHERE c.rowid = ce.fk_commande";
2435
        $sql.= " AND c.fk_adresse_livraison IS NOT NULL AND c.fk_adresse_livraison != 0";
2436
2437
        $resql = $db->query($sql);
2438
        if ($resql)
2439
        {
2440
            $i = 0;
2441
            $num = $db->num_rows($resql);
2442
2443
            if ($num)
2444
            {
2445
                while ($i < $num)
2446
                {
2447
                    $obj = $db->fetch_object($resql);
2448
2449
                    $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
2450
                    $sql.= " fk_adresse_livraison = '".$obj->fk_adresse_livraison."'";
2451
                    $sql.= " WHERE rowid=".$obj->fk_expedition;
2452
2453
                    $resql2=$db->query($sql);
2454
                    if (!$resql2)
2455
                    {
2456
                        $error++;
2457
                        dol_print_error($db);
2458
                    }
2459
                    print ". ";
2460
                    $i++;
2461
                }
2462
            }
2463
            else
2464
            {
2465
                print $langs->trans('AlreadyDone')."<br>\n";
2466
            }
2467
2468
            if ($error == 0)
2469
            {
2470
                $db->commit();
2471
            }
2472
            else
2473
            {
2474
                $db->rollback();
2475
            }
2476
        }
2477
        else
2478
        {
2479
            dol_print_error($db);
2480
            $db->rollback();
2481
        }
2482
    }
2483
    else
2484
    {
2485
        print $langs->trans('AlreadyDone')."<br>\n";
2486
    }
2487
2488
    print '</td></tr>';
2489
}
2490
2491
/**
2492
 * Migration du champ fk_remise_except dans llx_facturedet doit correspondre a
2493
 * lien dans llx_societe_remise_except vers llx_facturedet
2494
 *
2495
 * @param	DoliDB		$db		Database handler
2496
 * @param	Translate	$langs	Object langs
2497
 * @param	Conf		$conf	Object conf
2498
 * @return	integer|null
2499
 */
2500
function migrate_restore_missing_links($db,$langs,$conf)
2501
{
2502
    dolibarr_install_syslog("upgrade2::migrate_restore_missing_links");
2503
2504
    if (($db->type == 'mysql' || $db->type == 'mysqli'))
2505
    {
2506
        if (versioncompare($db->getVersionArray(),array(4,0)) < 0)
2507
        {
2508
            dolibarr_install_syslog("upgrade2::migrate_restore_missing_links Version of database too old to make this migrate action");
2509
            return 0;
2510
        }
2511
    }
2512
    print '<tr><td colspan="4">';
2513
2514
    print '<br>';
2515
    print '<b>'.$langs->trans('MigrationFixData')."</b> (1)<br>\n";
2516
2517
    $error = 0;
2518
2519
2520
    // Restore missing link for this cross foreign key (link 1 <=> 1). Direction 1.
2521
    $table1='facturedet'; $field1='fk_remise_except';
2522
    $table2='societe_remise_except'; $field2='fk_facture_line';
2523
2524
    $db->begin();
2525
2526
    $sql = "SELECT t1.rowid, t1.".$field1." as field";
2527
    $sql.= " FROM ".MAIN_DB_PREFIX.$table1." as t1";
2528
    $sql.= " WHERE t1.".$field1." IS NOT NULL AND t1.".$field1." NOT IN";
2529
    $sql.= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$table2." as t2";
2530
    $sql.= " WHERE t1.rowid = t2.".$field2.")";
2531
2532
    dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 1");
2533
    $resql = $db->query($sql);
2534
    if ($resql)
2535
    {
2536
        $i = 0;
2537
        $num = $db->num_rows($resql);
2538
2539
        if ($num)
2540
        {
2541
            while ($i < $num)
2542
            {
2543
                $obj = $db->fetch_object($resql);
2544
2545
                print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.<br>';
2546
                $sql = "UPDATE ".MAIN_DB_PREFIX.$table2." SET";
2547
                $sql.= " ".$field2." = '".$obj->rowid."'";
2548
                $sql.= " WHERE rowid=".$obj->field;
2549
2550
                $resql2=$db->query($sql);
2551
                if (! $resql2)
2552
                {
2553
                    $error++;
2554
                    dol_print_error($db);
2555
                }
2556
                //print ". ";
2557
                $i++;
2558
            }
2559
2560
        }
2561
        else print $langs->trans('AlreadyDone')."<br>\n";
2562
2563
        if ($error == 0)
2564
        {
2565
            $db->commit();
2566
        }
2567
        else
2568
        {
2569
            $db->rollback();
2570
        }
2571
    }
2572
    else
2573
    {
2574
        dol_print_error($db);
2575
        $db->rollback();
2576
    }
2577
2578
    print '</td></tr>';
2579
2580
2581
    print '<tr><td colspan="4">';
2582
2583
    print '<br>';
2584
    print '<b>'.$langs->trans('MigrationFixData')."</b> (2)<br>\n";
2585
2586
    // Restore missing link for this cross foreign key (link 1 <=> 1). Direction 2.
2587
    $table2='facturedet'; $field2='fk_remise_except';
2588
    $table1='societe_remise_except'; $field1='fk_facture_line';
2589
2590
    $db->begin();
2591
2592
    $sql = "SELECT t1.rowid, t1.".$field1." as field";
2593
    $sql.= " FROM ".MAIN_DB_PREFIX.$table1." as t1";
2594
    $sql.= " WHERE t1.".$field1." IS NOT NULL AND t1.".$field1." NOT IN";
2595
    $sql.= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$table2." as t2";
2596
    $sql.= " WHERE t1.rowid = t2.".$field2.")";
2597
2598
    dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 2");
2599
    $resql = $db->query($sql);
2600
    if ($resql)
2601
    {
2602
        $i = 0;
2603
        $num = $db->num_rows($resql);
2604
2605
        if ($num)
2606
        {
2607
            while ($i < $num)
2608
            {
2609
                $obj = $db->fetch_object($resql);
2610
2611
                print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.<br>';
2612
                $sql = "UPDATE ".MAIN_DB_PREFIX.$table2." SET";
2613
                $sql.= " ".$field2." = '".$obj->rowid."'";
2614
                $sql.= " WHERE rowid=".$obj->field;
2615
2616
                $resql2=$db->query($sql);
2617
                if (! $resql2)
2618
                {
2619
                    $error++;
2620
                    dol_print_error($db);
2621
                }
2622
                //print ". ";
2623
                $i++;
2624
            }
2625
2626
        }
2627
        else
2628
        {
2629
            print $langs->trans('AlreadyDone')."<br>\n";
2630
        }
2631
2632
        if ($error == 0)
2633
        {
2634
            $db->commit();
2635
        }
2636
        else
2637
        {
2638
            $db->rollback();
2639
        }
2640
    }
2641
    else
2642
    {
2643
        dol_print_error($db);
2644
        $db->rollback();
2645
    }
2646
2647
    print '</td></tr>';
2648
}
2649
2650
/**
2651
 * Migration du champ fk_user_resp de llx_projet vers llx_element_contact
2652
 *
2653
 * @param	DoliDB		$db		Database handler
2654
 * @param	Translate	$langs	Object langs
2655
 * @param	Conf		$conf	Object conf
2656
 * @return	void
2657
 */
2658
function migrate_project_user_resp($db,$langs,$conf)
2659
{
2660
    dolibarr_install_syslog("upgrade2::migrate_project_user_resp");
2661
2662
    print '<tr><td colspan="4">';
2663
2664
    print '<br>';
2665
    print '<b>'.$langs->trans('MigrationProjectUserResp')."</b><br>\n";
2666
2667
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."projet","fk_user_resp");
2668
    $obj = $db->fetch_object($result);
2669
    if ($obj)
2670
    {
2671
        $error = 0;
2672
2673
        $db->begin();
2674
2675
        $sql = "SELECT rowid, fk_user_resp FROM ".MAIN_DB_PREFIX."projet";
2676
        $resql = $db->query($sql);
2677
        if ($resql)
2678
        {
2679
            $i = 0;
2680
            $num = $db->num_rows($resql);
2681
2682
            if ($num)
2683
            {
2684
                while ($i < $num)
2685
                {
2686
                    $obj = $db->fetch_object($resql);
2687
2688
                    $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact (";
2689
                    $sql2.= "datecreate";
2690
                    $sql2.= ", statut";
2691
                    $sql2.= ", element_id";
2692
                    $sql2.= ", fk_c_type_contact";
2693
                    $sql2.= ", fk_socpeople";
2694
                    $sql2.= ") VALUES (";
2695
                    $sql2.= "'".$db->idate(dol_now())."'";
2696
                    $sql2.= ", '4'";
2697
                    $sql2.= ", ".$obj->rowid;
2698
                    $sql2.= ", '160'";
2699
                    $sql2.= ", ".$obj->fk_user_resp;
2700
                    $sql2.= ")";
2701
2702
                    if ($obj->fk_user_resp > 0)
2703
                    {
2704
                        $resql2=$db->query($sql2);
2705
                        if (!$resql2)
2706
                        {
2707
                            $error++;
2708
                            dol_print_error($db);
2709
                        }
2710
                    }
2711
                    print ". ";
2712
2713
                    $i++;
2714
                }
2715
            }
2716
2717
            if ($error == 0)
2718
            {
2719
                $sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."projet DROP COLUMN fk_user_resp";
2720
                if ($db->query($sqlDrop))
2721
                {
2722
                    $db->commit();
2723
                }
2724
                else
2725
                {
2726
                    $db->rollback();
2727
                }
2728
            }
2729
            else
2730
            {
2731
                $db->rollback();
2732
            }
2733
        }
2734
        else
2735
        {
2736
            dol_print_error($db);
2737
            $db->rollback();
2738
        }
2739
    }
2740
    else
2741
    {
2742
        print $langs->trans('AlreadyDone')."<br>\n";
2743
    }
2744
    print '</td></tr>';
2745
}
2746
2747
/**
2748
 * Migration de la table llx_projet_task_actors vers llx_element_contact
2749
 *
2750
 * @param	DoliDB		$db		Database handler
2751
 * @param	Translate	$langs	Object langs
2752
 * @param	Conf		$conf	Object conf
2753
 * @return	void
2754
 */
2755
function migrate_project_task_actors($db,$langs,$conf)
2756
{
2757
    dolibarr_install_syslog("upgrade2::migrate_project_task_actors");
2758
2759
    print '<tr><td colspan="4">';
2760
2761
    print '<br>';
2762
    print '<b>'.$langs->trans('MigrationProjectTaskActors')."</b><br>\n";
2763
2764
    if ($db->DDLInfoTable(MAIN_DB_PREFIX."projet_task_actors"))
2765
    {
2766
        $error = 0;
2767
2768
        $db->begin();
2769
2770
        $sql = "SELECT fk_projet_task, fk_user FROM ".MAIN_DB_PREFIX."projet_task_actors";
2771
        $resql = $db->query($sql);
2772
        if ($resql)
2773
        {
2774
            $i = 0;
2775
            $num = $db->num_rows($resql);
2776
2777
            if ($num)
2778
            {
2779
                while ($i < $num)
2780
                {
2781
                    $obj = $db->fetch_object($resql);
2782
2783
                    $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact (";
2784
                    $sql2.= "datecreate";
2785
                    $sql2.= ", statut";
2786
                    $sql2.= ", element_id";
2787
                    $sql2.= ", fk_c_type_contact";
2788
                    $sql2.= ", fk_socpeople";
2789
                    $sql2.= ") VALUES (";
2790
                    $sql2.= "'".$db->idate(dol_now())."'";
2791
                    $sql2.= ", '4'";
2792
                    $sql2.= ", ".$obj->fk_projet_task;
2793
                    $sql2.= ", '180'";
2794
                    $sql2.= ", ".$obj->fk_user;
2795
                    $sql2.= ")";
2796
2797
                    $resql2=$db->query($sql2);
2798
2799
                    if (!$resql2)
2800
                    {
2801
                        $error++;
2802
                        dol_print_error($db);
2803
                    }
2804
                    print ". ";
2805
                    $i++;
2806
                }
2807
            }
2808
2809
            if ($error == 0)
2810
            {
2811
                $sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX."projet_task_actors";
2812
                if ($db->query($sqlDrop))
2813
                {
2814
                    $db->commit();
2815
                }
2816
                else
2817
                {
2818
                    $db->rollback();
2819
                }
2820
            }
2821
            else
2822
            {
2823
                $db->rollback();
2824
            }
2825
        }
2826
        else
2827
        {
2828
            dol_print_error($db);
2829
            $db->rollback();
2830
        }
2831
    }
2832
    else
2833
    {
2834
        print $langs->trans('AlreadyDone')."<br>\n";
2835
    }
2836
    print '</td></tr>';
2837
}
2838
2839
/**
2840
 * Migration des tables de relation
2841
 *
2842
 * @param	DoliDB		$db				Database handler
2843
 * @param	Translate	$langs			Object langs
2844
 * @param	Conf		$conf			Object conf
2845
 * @param	string		$table			Table name
2846
 * @param	int			$fk_source		Id of element source
2847
 * @param	type		$sourcetype		Type of element source
2848
 * @param	int			$fk_target		Id of element target
2849
 * @param	type		$targettype		Type of element target
2850
 * @return	void
2851
 */
2852
function migrate_relationship_tables($db,$langs,$conf,$table,$fk_source,$sourcetype,$fk_target,$targettype)
2853
{
2854
    print '<tr><td colspan="4">';
2855
2856
    print '<br>';
2857
    print '<b>'.$langs->trans('MigrationRelationshipTables',MAIN_DB_PREFIX.$table)."</b><br>\n";
2858
2859
    $error = 0;
2860
2861
    if ($db->DDLInfoTable(MAIN_DB_PREFIX.$table))
2862
    {
2863
        dolibarr_install_syslog("upgrade2::migrate_relationship_tables table = " . MAIN_DB_PREFIX . $table);
2864
2865
        $db->begin();
2866
2867
        $sqlSelect = "SELECT ".$fk_source.", ".$fk_target;
2868
        $sqlSelect.= " FROM ".MAIN_DB_PREFIX.$table;
2869
2870
        $resql = $db->query($sqlSelect);
2871
        if ($resql)
2872
        {
2873
            $i = 0;
2874
            $num = $db->num_rows($resql);
2875
2876
            if ($num)
2877
            {
2878
                while ($i < $num)
2879
                {
2880
                    $obj = $db->fetch_object($resql);
2881
2882
                    $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
2883
                    $sqlInsert.= "fk_source";
2884
                    $sqlInsert.= ", sourcetype";
2885
                    $sqlInsert.= ", fk_target";
2886
                    $sqlInsert.= ", targettype";
2887
                    $sqlInsert.= ") VALUES (";
2888
                    $sqlInsert.= $obj->$fk_source;
2889
                    $sqlInsert.= ", '".$sourcetype."'";
2890
                    $sqlInsert.= ", ".$obj->$fk_target;
2891
                    $sqlInsert.= ", '".$targettype."'";
2892
                    $sqlInsert.= ")";
2893
2894
                    $result=$db->query($sqlInsert);
2895
                    if (! $result)
2896
                    {
2897
                        $error++;
2898
                        dol_print_error($db);
2899
                    }
2900
                    print ". ";
2901
                    $i++;
2902
                }
2903
            }
2904
            else
2905
            {
2906
                print $langs->trans('AlreadyDone')."<br>\n";
2907
            }
2908
2909
            if ($error == 0)
2910
            {
2911
                $sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX.$table;
2912
                if ($db->query($sqlDrop))
2913
                {
2914
                    $db->commit();
2915
                }
2916
                else
2917
                {
2918
                    $db->rollback();
2919
                }
2920
            }
2921
            else
2922
            {
2923
                $db->rollback();
2924
            }
2925
        }
2926
        else
2927
        {
2928
            dol_print_error($db);
2929
            $db->rollback();
2930
        }
2931
    }
2932
    else
2933
    {
2934
        print $langs->trans('AlreadyDone')."<br>\n";
2935
    }
2936
2937
    print '</td></tr>';
2938
}
2939
2940
/**
2941
 * Migrate duration in seconds
2942
 *
2943
 * @param	DoliDB		$db		Database handler
2944
 * @param	Translate	$langs	Object langs
2945
 * @param	Conf		$conf	Object conf
2946
 * @return	void
2947
 */
2948
function migrate_project_task_time($db,$langs,$conf)
2949
{
2950
    dolibarr_install_syslog("upgrade2::migrate_project_task_time");
2951
2952
    print '<tr><td colspan="4">';
2953
2954
    print '<br>';
2955
    print '<b>'.$langs->trans('MigrationProjectTaskTime')."</b><br>\n";
2956
2957
    $error = 0;
2958
2959
    $db->begin();
2960
2961
    $sql = "SELECT rowid, fk_task, task_duration";
2962
    $sql.= " FROM ".MAIN_DB_PREFIX."projet_task_time";
2963
    $resql = $db->query($sql);
2964
    if ($resql)
2965
    {
2966
        $i = 0;
2967
        $num = $db->num_rows($resql);
2968
2969
        if ($num)
2970
        {
2971
            $totaltime = array();
2972
            $oldtime = 0;
2973
2974
            while ($i < $num)
2975
            {
2976
                $obj = $db->fetch_object($resql);
2977
2978
                if ($obj->task_duration > 0)
2979
                {
2980
                    // convert to second
2981
                    // only for int time and float time ex: 1,75 for 1h45
2982
                    list($hour,$min) = explode('.',$obj->task_duration);
2983
                    $hour = $hour*60*60;
2984
                    $min = ($min/100)*60*60;
2985
                    $newtime = $hour+$min;
2986
2987
                    $sql2 = "UPDATE ".MAIN_DB_PREFIX."projet_task_time SET";
2988
                    $sql2.= " task_duration = ".$newtime;
2989
                    $sql2.= " WHERE rowid = ".$obj->rowid;
2990
2991
                    $resql2=$db->query($sql2);
2992
                    if (!$resql2)
2993
                    {
2994
                        $error++;
2995
                        dol_print_error($db);
2996
                    }
2997
                    print ". ";
2998
                    $oldtime++;
2999
                    if (! empty($totaltime[$obj->fk_task])) $totaltime[$obj->fk_task] += $newtime;
3000
                    else $totaltime[$obj->fk_task] = $newtime;
3001
                }
3002
                else
3003
                {
3004
                    if (! empty($totaltime[$obj->fk_task])) $totaltime[$obj->fk_task] += $obj->task_duration;
3005
                    else $totaltime[$obj->fk_task] = $obj->task_duration;
3006
                }
3007
3008
                $i++;
3009
            }
3010
3011
            if ($error == 0)
3012
            {
3013
                if ($oldtime > 0)
3014
                {
3015
                    foreach($totaltime as $taskid => $total_duration)
3016
                    {
3017
                        $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET";
3018
                        $sql.= " duration_effective = ".$total_duration;
3019
                        $sql.= " WHERE rowid = ".$taskid;
3020
3021
                        $resql=$db->query($sql);
3022
                        if (!$resql)
3023
                        {
3024
                            $error++;
3025
                            dol_print_error($db);
3026
                        }
3027
                    }
3028
                }
3029
                else
3030
                {
3031
                    print $langs->trans('AlreadyDone')."<br>\n";
3032
                }
3033
            }
3034
            else
3035
            {
3036
                dol_print_error($db);
3037
            }
3038
        }
3039
        else
3040
        {
3041
            print $langs->trans('AlreadyDone')."<br>\n";
3042
        }
3043
    }
3044
    else
3045
    {
3046
        dol_print_error($db);
3047
    }
3048
3049
    if ($error == 0)
3050
    {
3051
        $db->commit();
3052
    }
3053
    else
3054
    {
3055
        $db->rollback();
3056
    }
3057
3058
    print '</td></tr>';
3059
}
3060
3061
/**
3062
 * Migrate order ref_customer and date_delivery fields to llx_expedition
3063
 *
3064
 * @param	DoliDB		$db		Database handler
3065
 * @param	Translate	$langs	Object langs
3066
 * @param	Conf		$conf	Object conf
3067
 * @return	void
3068
 */
3069
function migrate_customerorder_shipping($db,$langs,$conf)
3070
{
3071
    print '<tr><td colspan="4">';
3072
3073
    print '<br>';
3074
    print '<b>'.$langs->trans('MigrationCustomerOrderShipping')."</b><br>\n";
3075
3076
    $error = 0;
3077
3078
    $result1 = $db->DDLDescTable(MAIN_DB_PREFIX."expedition","ref_customer");
3079
    $result2 = $db->DDLDescTable(MAIN_DB_PREFIX."expedition","date_delivery");
3080
    $obj1 = $db->fetch_object($result1);
3081
    $obj2 = $db->fetch_object($result2);
3082
    if (!$obj1 && !$obj2)
3083
    {
3084
        dolibarr_install_syslog("upgrade2::migrate_customerorder_shipping");
3085
3086
        $db->begin();
3087
3088
        $sqlAdd1 = "ALTER TABLE ".MAIN_DB_PREFIX."expedition ADD COLUMN ref_customer varchar(30) AFTER entity";
3089
        $sqlAdd2 = "ALTER TABLE ".MAIN_DB_PREFIX."expedition ADD COLUMN date_delivery date DEFAULT NULL AFTER date_expedition";
3090
3091
        if ($db->query($sqlAdd1) && $db->query($sqlAdd2))
3092
        {
3093
            $sqlSelect = "SELECT e.rowid as shipping_id, c.ref_client, c.date_livraison";
3094
            $sqlSelect.= " FROM ".MAIN_DB_PREFIX."expedition as e";
3095
            $sqlSelect.= ", ".MAIN_DB_PREFIX."element_element as el";
3096
            $sqlSelect.= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON c.rowid = el.fk_source AND el.sourcetype = 'commande'";
3097
            $sqlSelect.= " WHERE e.rowid = el.fk_target";
3098
            $sqlSelect.= " AND el.targettype = 'shipping'";
3099
3100
            $resql = $db->query($sqlSelect);
3101
            if ($resql)
3102
            {
3103
                $i = 0;
3104
                $num = $db->num_rows($resql);
3105
3106
                if ($num)
3107
                {
3108
                    while ($i < $num)
3109
                    {
3110
                        $obj = $db->fetch_object($resql);
3111
3112
                        $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
3113
                        $sqlUpdate.= " ref_customer = '".$obj->ref_client."'";
3114
                        $sqlUpdate.= ", date_delivery = '".($obj->date_livraison?$obj->date_livraison:'null')."'";
3115
                        $sqlUpdate.= " WHERE rowid = ".$obj->shipping_id;
3116
3117
                        $result=$db->query($sqlUpdate);
3118
                        if (! $result)
3119
                        {
3120
                            $error++;
3121
                            dol_print_error($db);
3122
                        }
3123
                        print ". ";
3124
                        $i++;
3125
                    }
3126
                }
3127
                else
3128
                {
3129
                    print $langs->trans('AlreadyDone')."<br>\n";
3130
                }
3131
3132
                if ($error == 0)
3133
                {
3134
                    $db->commit();
3135
                }
3136
                else
3137
                {
3138
                    dol_print_error($db);
3139
                    $db->rollback();
3140
                }
3141
            }
3142
            else
3143
            {
3144
                dol_print_error($db);
3145
                $db->rollback();
3146
            }
3147
        }
3148
        else
3149
        {
3150
            dol_print_error($db);
3151
            $db->rollback();
3152
        }
3153
    }
3154
    else
3155
    {
3156
        print $langs->trans('AlreadyDone')."<br>\n";
3157
    }
3158
3159
    print '</td></tr>';
3160
}
3161
3162
/**
3163
 * Migrate link stored into fk_expedition into llx_element_element
3164
 *
3165
 * @param	DoliDB		$db		Database handler
3166
 * @param	Translate	$langs	Object langs
3167
 * @param	Conf		$conf	Object conf
3168
 * @return	void
3169
 */
3170
function migrate_shipping_delivery($db,$langs,$conf)
3171
{
3172
    print '<tr><td colspan="4">';
3173
3174
    print '<br>';
3175
    print '<b>'.$langs->trans('MigrationShippingDelivery')."</b><br>\n";
3176
3177
    $error = 0;
3178
3179
    $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraison","fk_expedition");
3180
    $obj = $db->fetch_object($result);
3181
    if ($obj)
3182
    {
3183
        dolibarr_install_syslog("upgrade2::migrate_shipping_delivery");
3184
3185
        $db->begin();
3186
3187
        $sqlSelect = "SELECT rowid, fk_expedition";
3188
        $sqlSelect.= " FROM ".MAIN_DB_PREFIX."livraison";
3189
        $sqlSelect.= " WHERE fk_expedition is not null";
3190
3191
        $resql = $db->query($sqlSelect);
3192
        if ($resql)
3193
        {
3194
            $i = 0;
3195
            $num = $db->num_rows($resql);
3196
3197
            if ($num)
3198
            {
3199
                while ($i < $num)
3200
                {
3201
                    $obj = $db->fetch_object($resql);
3202
3203
                    $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
3204
                    $sqlInsert.= "fk_source";
3205
                    $sqlInsert.= ", sourcetype";
3206
                    $sqlInsert.= ", fk_target";
3207
                    $sqlInsert.= ", targettype";
3208
                    $sqlInsert.= ") VALUES (";
3209
                    $sqlInsert.= $obj->fk_expedition;
3210
                    $sqlInsert.= ", 'shipping'";
3211
                    $sqlInsert.= ", ".$obj->rowid;
3212
                    $sqlInsert.= ", 'delivery'";
3213
                    $sqlInsert.= ")";
3214
3215
                    $result=$db->query($sqlInsert);
3216
                    if ($result)
3217
                    {
3218
                        $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET fk_expedition = NULL";
3219
                        $sqlUpdate.= " WHERE rowid = ".$obj->rowid;
3220
3221
                        $result=$db->query($sqlUpdate);
3222
                        if (! $result)
3223
                        {
3224
                            $error++;
3225
                            dol_print_error($db);
3226
                        }
3227
                        print ". ";
3228
                    }
3229
                    else
3230
                    {
3231
                        $error++;
3232
                        dol_print_error($db);
3233
                    }
3234
                    $i++;
3235
                }
3236
            }
3237
            else
3238
            {
3239
                print $langs->trans('AlreadyDone')."<br>\n";
3240
            }
3241
3242
            if ($error == 0)
3243
            {
3244
                $sqlDelete = "DELETE FROM ".MAIN_DB_PREFIX."element_element WHERE sourcetype = 'commande' AND targettype = 'delivery'";
3245
                $db->query($sqlDelete);
3246
3247
                $db->commit();
3248
3249
                // DDL commands must not be inside a transaction
3250
                $sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."livraison DROP COLUMN fk_expedition";
3251
                $db->query($sqlDrop);
3252
            }
3253
            else
3254
            {
3255
                dol_print_error($db);
3256
                $db->rollback();
3257
            }
3258
        }
3259
        else
3260
        {
3261
            dol_print_error($db);
3262
            $db->rollback();
3263
        }
3264
    }
3265
    else
3266
    {
3267
        print $langs->trans('AlreadyDone')."<br>\n";
3268
    }
3269
3270
    print '</td></tr>';
3271
}
3272
3273
/**
3274
 * We try to complete field ref_customer and date_delivery that are empty into llx_livraison.
3275
 * We set them with value from llx_expedition.
3276
 *
3277
 * @param	DoliDB		$db		Database handler
3278
 * @param	Translate	$langs	Object langs
3279
 * @param	Conf		$conf	Object conf
3280
 * @return	void
3281
 */
3282
function migrate_shipping_delivery2($db,$langs,$conf)
3283
{
3284
    print '<tr><td colspan="4">';
3285
3286
    print '<br>';
3287
    print '<b>'.$langs->trans('MigrationShippingDelivery2')."</b><br>\n";
3288
3289
    $error = 0;
3290
3291
    dolibarr_install_syslog("upgrade2::migrate_shipping_delivery2");
3292
3293
    $db->begin();
3294
3295
    $sqlSelect = "SELECT l.rowid as delivery_id, e.ref_customer, e.date_delivery";
3296
    $sqlSelect.= " FROM ".MAIN_DB_PREFIX."livraison as l,";
3297
    $sqlSelect.= " ".MAIN_DB_PREFIX."element_element as el,";
3298
    $sqlSelect.= " ".MAIN_DB_PREFIX."expedition as e";
3299
    $sqlSelect.= " WHERE l.rowid = el.fk_target";
3300
    $sqlSelect.= " AND el.targettype = 'delivery'";
3301
    $sqlSelect.= " AND e.rowid = el.fk_source AND el.sourcetype = 'shipping'";
3302
    $sqlSelect.= " AND (e.ref_customer IS NOT NULL OR e.date_delivery IS NOT NULL)";   // Useless to process this record if both are null
3303
    // Add condition to know if we never migrate this record
3304
    $sqlSelect.= " AND (l.ref_customer IS NULL".($db->type!='pgsql'?" or l.ref_customer = ''":"").")";
3305
    $sqlSelect.= " AND (l.date_delivery IS NULL".($db->type!='pgsql'?" or l.date_delivery = ''":"").")";
3306
3307
    $resql = $db->query($sqlSelect);
3308
    if ($resql)
3309
    {
3310
        $i = 0;
3311
        $num = $db->num_rows($resql);
3312
3313
        if ($num)
3314
        {
3315
            while ($i < $num)
3316
            {
3317
                $obj = $db->fetch_object($resql);
3318
3319
                $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
3320
                $sqlUpdate.= " ref_customer = '".$obj->ref_customer."',";
3321
                $sqlUpdate.= " date_delivery = ".($obj->date_delivery?"'".$obj->date_delivery."'":'null');
3322
                $sqlUpdate.= " WHERE rowid = ".$obj->delivery_id;
3323
3324
                $result=$db->query($sqlUpdate);
3325
                if (! $result)
3326
                {
3327
                    $error++;
3328
                    dol_print_error($db);
3329
                }
3330
                print ". ";
3331
                $i++;
3332
            }
3333
        }
3334
        else
3335
        {
3336
            print $langs->trans('AlreadyDone')."<br>\n";
3337
        }
3338
3339
        if ($error == 0)
3340
        {
3341
            $db->commit();
3342
        }
3343
        else
3344
        {
3345
            dol_print_error($db);
3346
            $db->rollback();
3347
        }
3348
    }
3349
    else
3350
    {
3351
        dol_print_error($db);
3352
        $db->rollback();
3353
    }
3354
3355
    print '</td></tr>';
3356
}
3357
3358
/**
3359
 * Migrate link stored into fk_xxxx into fk_element and elementtype
3360
 *
3361
 * @param	DoliDB		$db		Database handler
3362
 * @param	Translate	$langs	Object langs
3363
 * @param	Conf		$conf	Object conf
3364
 * @return	void
3365
 */
3366
function migrate_actioncomm_element($db,$langs,$conf)
3367
{
3368
	print '<tr><td colspan="4">';
3369
3370
	print '<br>';
3371
	print '<b>'.$langs->trans('MigrationActioncommElement')."</b><br>\n";
3372
3373
	$elements = array(
3374
		'propal' => 'propalrowid',
3375
		'order' => 'fk_commande',
3376
		'invoice' => 'fk_facture',
3377
		'contract' => 'fk_contract',
3378
		'order_supplier' => 'fk_supplier_order',
3379
		'invoice_supplier' => 'fk_supplier_invoice'
3380
	);
3381
3382
	foreach($elements as $type => $field)
3383
	{
3384
		$result = $db->DDLDescTable(MAIN_DB_PREFIX."actioncomm",$field);
3385
		$obj = $db->fetch_object($result);
3386
		if ($obj)
3387
		{
3388
			dolibarr_install_syslog("upgrade2::migrate_actioncomm_element field=" . $field);
3389
3390
			$db->begin();
3391
3392
			$sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm SET ";
3393
			$sql.= "fk_element = ".$field.", elementtype = '".$type."'";
3394
			$sql.= " WHERE ".$field." IS NOT NULL";
3395
			$sql.= " AND fk_element IS NULL";
3396
			$sql.= " AND elementtype IS NULL";
3397
3398
			$resql = $db->query($sql);
3399
			if ($resql)
3400
			{
3401
				$db->commit();
3402
3403
				// DDL commands must not be inside a transaction
3404
				// We will drop at next version because a migrate should be runnable several times if it fails.
3405
				//$sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."actioncomm DROP COLUMN ".$field;
3406
				//$db->query($sqlDrop);
3407
				//print ". ";
3408
			}
3409
			else
3410
			{
3411
				dol_print_error($db);
3412
				$db->rollback();
3413
			}
3414
		}
3415
		else
3416
		{
3417
			print $langs->trans('AlreadyDone')."<br>\n";
3418
		}
3419
	}
3420
3421
	print '</td></tr>';
3422
}
3423
3424
/**
3425
 * Migrate link stored into fk_mode_reglement
3426
 *
3427
 * @param	DoliDB		$db		Database handler
3428
 * @param	Translate	$langs	Object langs
3429
 * @param	Conf		$conf	Object conf
3430
 * @return	void
3431
 */
3432
function migrate_mode_reglement($db,$langs,$conf)
3433
{
3434
	print '<tr><td colspan="4">';
3435
3436
	print '<br>';
3437
	print '<b>'.$langs->trans('MigrationPaymentMode')."</b><br>\n";
3438
3439
	$elements = array(
3440
		'old_id' => array(5,8,9,10,11),
3441
		'new_id' => array(50,51,52,53,54),
3442
		'code' => array('VAD','TRA','LCR','FAC','PRO'),
3443
		'tables' => array('commande_fournisseur','commande','facture_rec','facture','propal')
3444
	);
3445
	$count=0;
3446
3447
	foreach($elements['old_id'] as $key => $old_id)
3448
	{
3449
		$error=0;
3450
3451
		dolibarr_install_syslog("upgrade2::migrate_mode_reglement code=" . $elements['code'][$key]);
3452
3453
		$sqlSelect = "SELECT id";
3454
		$sqlSelect.= " FROM ".MAIN_DB_PREFIX."c_paiement";
3455
		$sqlSelect.= " WHERE id = ".$old_id;
3456
		$sqlSelect.= " AND code = '".$elements['code'][$key]."'";
3457
3458
		$resql = $db->query($sqlSelect);
3459
		if ($resql)
3460
		{
3461
			$num = $db->num_rows($resql);
3462
			if ($num)
3463
			{
3464
				$count++;
3465
3466
				$db->begin();
3467
3468
				$sqla = "UPDATE ".MAIN_DB_PREFIX."paiement SET ";
3469
				$sqla.= "fk_paiement = ".$elements['new_id'][$key];
3470
				$sqla.= " WHERE fk_paiement = ".$old_id;
3471
				$sqla.= " AND fk_paiement IN (SELECT id FROM ".MAIN_DB_PREFIX."c_paiement WHERE id = ".$old_id." AND code = '".$elements['code'][$key]."')";
3472
				$resqla = $db->query($sqla);
3473
3474
				$sql = "UPDATE ".MAIN_DB_PREFIX."c_paiement SET ";
3475
				$sql.= "id = ".$elements['new_id'][$key];
3476
				$sql.= " WHERE id = ".$old_id;
3477
				$sql.= " AND code = '".$elements['code'][$key]."'";
3478
				$resql = $db->query($sql);
3479
3480
				if ($resqla && $resql)
3481
				{
3482
					foreach($elements['tables'] as $table)
3483
					{
3484
						$sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
3485
						$sql.= "fk_mode_reglement = ".$elements['new_id'][$key];
3486
						$sql.= " WHERE fk_mode_reglement = ".$old_id;
3487
3488
						$resql = $db->query($sql);
3489
						if (! $resql)
3490
						{
3491
							dol_print_error($db);
3492
							$error++;
3493
						}
3494
						print ". ";
3495
					}
3496
3497
					if (! $error)
3498
					{
3499
						$db->commit();
3500
					}
3501
					else
3502
					{
3503
						dol_print_error($db);
3504
						$db->rollback();
3505
					}
3506
				}
3507
				else
3508
				{
3509
					dol_print_error($db);
3510
					$db->rollback();
3511
				}
3512
			}
3513
		}
3514
	}
3515
3516
	if ($count == 0) print $langs->trans('AlreadyDone')."<br>\n";
3517
3518
3519
	print '</td></tr>';
3520
}
3521
3522
/**
3523
 * Migrate categorie association
3524
 *
3525
 * @param	DoliDB		$db				Database handler
3526
 * @param	Translate	$langs			Object langs
3527
 * @param	Conf		$conf			Object conf
3528
 * @return	void
3529
 */
3530
function migrate_categorie_association($db,$langs,$conf)
3531
{
3532
	print '<tr><td colspan="4">';
3533
3534
	print '<br>';
3535
	print '<b>'.$langs->trans('MigrationCategorieAssociation')."</b><br>\n";
3536
3537
	$error = 0;
3538
3539
	if ($db->DDLInfoTable(MAIN_DB_PREFIX."categorie_association"))
3540
	{
3541
		dolibarr_install_syslog("upgrade2::migrate_categorie_association");
3542
3543
		$db->begin();
3544
3545
		$sqlSelect = "SELECT fk_categorie_mere, fk_categorie_fille";
3546
		$sqlSelect.= " FROM ".MAIN_DB_PREFIX."categorie_association";
3547
3548
		$resql = $db->query($sqlSelect);
3549
		if ($resql)
3550
		{
3551
			$i = 0;
3552
			$num = $db->num_rows($resql);
3553
3554
			if ($num)
3555
			{
3556
				while ($i < $num)
3557
				{
3558
					$obj = $db->fetch_object($resql);
3559
3560
					$sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."categorie SET ";
3561
					$sqlUpdate.= "fk_parent = ".$obj->fk_categorie_mere;
3562
					$sqlUpdate.= " WHERE rowid = ".$obj->fk_categorie_fille;
3563
3564
					$result=$db->query($sqlUpdate);
3565
					if (! $result)
3566
					{
3567
						$error++;
3568
						dol_print_error($db);
3569
					}
3570
					print ". ";
3571
					$i++;
3572
				}
3573
			}
3574
			else
3575
			{
3576
				print $langs->trans('AlreadyDone')."<br>\n";
3577
			}
3578
3579
			if (! $error)
3580
			{
3581
				// TODO DROP table in the next release
3582
				/*
3583
				$sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX."categorie_association";
3584
				if ($db->query($sqlDrop))
3585
				{
3586
					$db->commit();
3587
				}
3588
				else
3589
				{
3590
					$db->rollback();
3591
				}
3592
				*/
3593
3594
				$db->commit();
3595
			}
3596
			else
3597
			{
3598
				$db->rollback();
3599
			}
3600
		}
3601
		else
3602
		{
3603
			dol_print_error($db);
3604
			$db->rollback();
3605
		}
3606
	}
3607
	else
3608
	{
3609
		print $langs->trans('AlreadyDone')."<br>\n";
3610
	}
3611
3612
	print '</td></tr>';
3613
}
3614
3615
/**
3616
 * Migrate event assignement to owner
3617
 *
3618
 * @param	DoliDB		$db				Database handler
3619
 * @param	Translate	$langs			Object langs
3620
 * @param	Conf		$conf			Object conf
3621
 * @return	void
3622
 */
3623
function migrate_event_assignement($db,$langs,$conf)
3624
{
3625
	print '<tr><td colspan="4">';
3626
3627
	print '<br>';
3628
	print '<b>'.$langs->trans('MigrationEvents')."</b><br>\n";
3629
3630
	$error = 0;
3631
3632
	dolibarr_install_syslog("upgrade2::migrate_event_assignement");
3633
3634
	$db->begin();
3635
3636
	$sqlSelect = "SELECT a.id, a.fk_user_action";
3637
	$sqlSelect.= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
3638
	$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";
3639
	$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')";
3640
	$sqlSelect.= " ORDER BY a.id";
3641
	//print $sqlSelect;
3642
3643
	$resql = $db->query($sqlSelect);
3644
	if ($resql)
3645
	{
3646
		$i = 0;
3647
		$num = $db->num_rows($resql);
3648
3649
		if ($num)
3650
		{
3651
			while ($i < $num)
3652
			{
3653
				$obj = $db->fetch_object($resql);
3654
3655
				$sqlUpdate = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element) ";
3656
				$sqlUpdate.= "VALUES(".$obj->id.", 'user', ".$obj->fk_user_action.")";
3657
3658
				$result=$db->query($sqlUpdate);
3659
				if (! $result)
3660
				{
3661
					$error++;
3662
					dol_print_error($db);
3663
				}
3664
				print ". ";
3665
				$i++;
3666
			}
3667
		}
3668
		else
3669
		{
3670
			print $langs->trans('AlreadyDone')."<br>\n";
3671
		}
3672
3673
		if (! $error)
3674
		{
3675
			$db->commit();
3676
		}
3677
		else
3678
		{
3679
			$db->rollback();
3680
		}
3681
	}
3682
	else
3683
	{
3684
		dol_print_error($db);
3685
		$db->rollback();
3686
	}
3687
3688
3689
	print '</td></tr>';
3690
}
3691
3692
/**
3693
 * Migrate to add entity value into llx_societe_remise
3694
 *
3695
 * @param	DoliDB		$db				Database handler
3696
 * @param	Translate	$langs			Object langs
3697
 * @param	Conf		$conf			Object conf
3698
 * @return	void
3699
 */
3700
function migrate_remise_entity($db,$langs,$conf)
3701
{
3702
	print '<tr><td colspan="4">';
3703
3704
	print '<br>';
3705
	print '<b>'.$langs->trans('MigrationRemiseEntity')."</b><br>\n";
3706
3707
	$error = 0;
3708
3709
	dolibarr_install_syslog("upgrade2::migrate_remise_entity");
3710
3711
	$db->begin();
3712
3713
	$sqlSelect = "SELECT sr.rowid, s.entity";
3714
	$sqlSelect.= " FROM ".MAIN_DB_PREFIX."societe_remise as sr, ".MAIN_DB_PREFIX."societe as s";
3715
	$sqlSelect.= " WHERE sr.fk_soc = s.rowid and sr.entity != s.entity";
3716
3717
	//print $sqlSelect;
3718
3719
	$resql = $db->query($sqlSelect);
3720
	if ($resql)
3721
	{
3722
		$i = 0;
3723
		$num = $db->num_rows($resql);
3724
3725
		if ($num)
3726
		{
3727
			while ($i < $num)
3728
			{
3729
				$obj = $db->fetch_object($resql);
3730
3731
				$sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise SET";
3732
				$sqlUpdate.= " entity = " . $obj->entity;
3733
				$sqlUpdate.= " WHERE rowid = " . $obj->rowid;
3734
3735
				$result=$db->query($sqlUpdate);
3736
				if (! $result)
3737
				{
3738
					$error++;
3739
					dol_print_error($db);
3740
				}
3741
3742
				print ". ";
3743
				$i++;
3744
			}
3745
		}
3746
		else
3747
		{
3748
			print $langs->trans('AlreadyDone')."<br>\n";
3749
		}
3750
3751
		if (! $error)
3752
		{
3753
			$db->commit();
3754
		}
3755
		else
3756
		{
3757
			$db->rollback();
3758
		}
3759
	}
3760
	else
3761
	{
3762
		dol_print_error($db);
3763
		$db->rollback();
3764
	}
3765
3766
3767
	print '</td></tr>';
3768
}
3769
3770
/**
3771
 * Migrate to add entity value into llx_societe_remise_except
3772
 *
3773
 * @param	DoliDB		$db				Database handler
3774
 * @param	Translate	$langs			Object langs
3775
 * @param	Conf		$conf			Object conf
3776
 * @return	void
3777
 */
3778
function migrate_remise_except_entity($db,$langs,$conf)
3779
{
3780
	print '<tr><td colspan="4">';
3781
3782
	print '<br>';
3783
	print '<b>'.$langs->trans('MigrationRemiseExceptEntity')."</b><br>\n";
3784
3785
	$error = 0;
3786
3787
	dolibarr_install_syslog("upgrade2::migrate_remise_except_entity");
3788
3789
	$db->begin();
3790
3791
	$sqlSelect = "SELECT sr.rowid, sr.fk_soc, sr.fk_facture_source, sr.fk_facture, sr.fk_facture_line";
3792
	$sqlSelect.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr";
3793
	//print $sqlSelect;
3794
3795
	$resql = $db->query($sqlSelect);
3796
	if ($resql)
3797
	{
3798
		$i = 0;
3799
		$num = $db->num_rows($resql);
3800
3801
		if ($num)
3802
		{
3803
			while ($i < $num)
3804
			{
3805
				$obj = $db->fetch_object($resql);
3806
3807
				if (!empty($obj->fk_facture_source) || !empty($obj->fk_facture))
3808
				{
3809
					$fk_facture = (!empty($obj->fk_facture_source) ? $obj->fk_facture_source : $obj->fk_facture);
3810
3811
					$sqlSelect2 = "SELECT f.entity";
3812
					$sqlSelect2.= " FROM ".MAIN_DB_PREFIX."facture as f";
3813
					$sqlSelect2.= " WHERE f.rowid = " . $fk_facture;
3814
				}
3815
				else if (!empty($obj->fk_facture_line))
3816
				{
3817
					$sqlSelect2 = "SELECT f.entity";
3818
					$sqlSelect2.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as fd";
3819
					$sqlSelect2.= " WHERE fd.rowid = " . $obj->fk_facture_line;
3820
					$sqlSelect2.= " AND fd.fk_facture = f.rowid";
3821
				}
3822
				else
3823
				{
3824
					$sqlSelect2 = "SELECT s.entity";
3825
					$sqlSelect2.= " FROM ".MAIN_DB_PREFIX."societe as s";
3826
					$sqlSelect2.= " WHERE s.rowid = " . $obj->fk_soc;
3827
				}
3828
3829
				$resql2 = $db->query($sqlSelect2);
3830
				if ($resql2)
3831
				{
3832
					if ($db->num_rows($resql2) > 0)
3833
					{
3834
						$obj2 = $db->fetch_object($resql2);
3835
3836
						$sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except SET";
3837
						$sqlUpdate.= " entity = " . $obj2->entity;
3838
						$sqlUpdate.= " WHERE rowid = " . $obj->rowid;
3839
3840
						$result=$db->query($sqlUpdate);
3841
						if (! $result)
3842
						{
3843
							$error++;
3844
							dol_print_error($db);
3845
						}
3846
					}
3847
				}
3848
				else
3849
				{
3850
					$error++;
3851
					dol_print_error($db);
3852
				}
3853
3854
				print ". ";
3855
				$i++;
3856
			}
3857
		}
3858
		else
3859
		{
3860
			print $langs->trans('AlreadyDone')."<br>\n";
3861
		}
3862
3863
		if (! $error)
3864
		{
3865
			$db->commit();
3866
		}
3867
		else
3868
		{
3869
			$db->rollback();
3870
		}
3871
	}
3872
	else
3873
	{
3874
		dol_print_error($db);
3875
		$db->rollback();
3876
	}
3877
3878
3879
	print '</td></tr>';
3880
}
3881
3882
/**
3883
 * Migration directory
3884
 *
3885
 * @param	DoliDB		$db			Database handler
3886
 * @param	Translate	$langs		Object langs
3887
 * @param	Conf		$conf		Object conf
3888
 * @param	string		$oldname	Old name (relative to DOL_DATA_ROOT)
3889
 * @param	string		$newname	New name (relative to DOL_DATA_ROOT)
3890
 * @return	void
3891
 */
3892
function migrate_directories($db,$langs,$conf,$oldname,$newname)
3893
{
3894
    dolibarr_install_syslog("upgrade2::migrate_directories");
3895
3896
    if (is_dir(DOL_DATA_ROOT.$oldname) && ! file_exists(DOL_DATA_ROOT.$newname))
3897
    {
3898
        dolibarr_install_syslog("upgrade2::migrate_directories move " . DOL_DATA_ROOT . $oldname . ' into ' . DOL_DATA_ROOT . $newname);
3899
        @rename(DOL_DATA_ROOT.$oldname,DOL_DATA_ROOT.$newname);
3900
    }
3901
}
3902
3903
3904
/**
3905
 * Delete deprecated files
3906
 *
3907
 * @param	DoliDB		$db			Database handler
3908
 * @param	Translate	$langs		Object langs
3909
 * @param	Conf		$conf		Object conf
3910
 * @return	void
3911
 */
3912
function migrate_delete_old_files($db,$langs,$conf)
3913
{
3914
    $result=true;
3915
3916
    dolibarr_install_syslog("upgrade2::migrate_delete_old_files");
3917
3918
    // List of files to delete
3919
    $filetodeletearray=array(
3920
    DOL_DOCUMENT_ROOT.'/core/triggers/interface_demo.class.php',
3921
    DOL_DOCUMENT_ROOT.'/core/menus/barre_left/default.php',
3922
    DOL_DOCUMENT_ROOT.'/core/menus/barre_top/default.php',
3923
    DOL_DOCUMENT_ROOT.'/core/modules/modComptabiliteExpert.class.php',
3924
    DOL_DOCUMENT_ROOT.'/core/modules/modCommercial.class.php',
3925
    DOL_DOCUMENT_ROOT.'/core/modules/modProduit.class.php',
3926
    DOL_DOCUMENT_ROOT.'/phenix/inc/triggers/interface_modPhenix_Phenixsynchro.class.php',
3927
    DOL_DOCUMENT_ROOT.'/webcalendar/inc/triggers/interface_modWebcalendar_webcalsynchro.class.php',
3928
    DOL_DOCUMENT_ROOT.'/core/triggers/interface_modWebcalendar_Webcalsynchro.class.php',
3929
    DOL_DOCUMENT_ROOT.'/core/triggers/interface_modCommande_Ecotax.class.php',
3930
    DOL_DOCUMENT_ROOT.'/core/triggers/interface_modCommande_fraisport.class.php',
3931
    DOL_DOCUMENT_ROOT.'/core/triggers/interface_modPropale_PropalWorkflow.class.php',
3932
    DOL_DOCUMENT_ROOT.'/core/menus/smartphone/iphone.lib.php',
3933
    DOL_DOCUMENT_ROOT.'/core/menus/smartphone/iphone_backoffice.php',
3934
    DOL_DOCUMENT_ROOT.'/core/menus/smartphone/iphone_frontoffice.php',
3935
    DOL_DOCUMENT_ROOT.'/core/menus/standard/auguria_backoffice.php',
3936
    DOL_DOCUMENT_ROOT.'/core/menus/standard/auguria_frontoffice.php',
3937
    DOL_DOCUMENT_ROOT.'/core/menus/standard/eldy_backoffice.php',
3938
    DOL_DOCUMENT_ROOT.'/core/menus/standard/eldy_frontoffice.php',
3939
    DOL_DOCUMENT_ROOT.'/core/modules/mailings/dolibarr_services_expired.modules.php',
3940
    DOL_DOCUMENT_ROOT.'/core/modules/mailings/peche.modules.php',
3941
    DOL_DOCUMENT_ROOT.'/core/modules/mailings/poire.modules.php',
3942
    DOL_DOCUMENT_ROOT.'/core/modules/mailings/kiwi.modules.php',
3943
    DOL_DOCUMENT_ROOT.'/core/modules/facture/pdf_crabe.modules.php',
3944
    DOL_DOCUMENT_ROOT.'/core/modules/facture/pdf_oursin.modules.php',
3945
    
3946
    DOL_DOCUMENT_ROOT.'/compta/facture/class/api_invoice.class.php',
3947
    DOL_DOCUMENT_ROOT.'/commande/class/api_commande.class.php',
3948
    DOL_DOCUMENT_ROOT.'/user/class/api_user.class.php'
3949
    );
3950
3951
    foreach ($filetodeletearray as $filetodelete)
3952
    {
3953
        //print '<b>'.$filetodelete."</b><br>\n";
3954
        $result=1;
3955
        if (file_exists($filetodelete))
3956
        {
3957
            $result=dol_delete_file($filetodelete);
3958
            if (! $result)
3959
            {
3960
                $langs->load("errors");
3961
                print '<div class="error">'.$langs->trans("Error").': '.$langs->trans("ErrorFailToDeleteFile",$filetodelete);
3962
                print ' '.$langs->trans("RemoveItManuallyAndPressF5ToContinue").'</div>';
3963
            }
3964
            else
3965
			{
3966
                //print $langs->trans("FileWasRemoved",$filetodelete);
3967
            }
3968
        }
3969
    }
3970
    return $result;
3971
}
3972
3973
/**
3974
 * Remove deprecated directories
3975
 *
3976
 * @param	DoliDB		$db			Database handler
3977
 * @param	Translate	$langs		Object langs
3978
 * @param	Conf		$conf		Object conf
3979
 * @return	void
3980
 */
3981
function migrate_delete_old_dir($db,$langs,$conf)
3982
{
3983
    $result=true;
3984
3985
    dolibarr_install_syslog("upgrade2::migrate_delete_old_dir");
3986
3987
    // List of files to delete
3988
    $filetodeletearray=array(
3989
    DOL_DOCUMENT_ROOT.'/core/modules/facture/terre',
3990
    DOL_DOCUMENT_ROOT.'/core/modules/facture/mercure'
3991
    );
3992
3993
    foreach ($filetodeletearray as $filetodelete)
3994
    {
3995
        //print '<b>'.$filetodelete."</b><br>\n";
3996
        if (file_exists($filetodelete))
3997
        {
3998
            $result=dol_delete_dir_recursive($filetodelete);
3999
        }
4000
        if (! $result)
4001
        {
4002
            $langs->load("errors");
4003
            print '<div class="error">'.$langs->trans("Error").': '.$langs->trans("ErrorFailToDeleteDir",$filetodelete);
4004
            print ' '.$langs->trans("RemoveItManuallyAndPressF5ToContinue").'</div>';
4005
        }
4006
    }
4007
    return $result;
4008
}
4009
4010
4011
/**
4012
 * Disable/Reenable features modules.
4013
 * We must do this when internal menu of module or permissions has changed
4014
 * or when triggers have moved.
4015
 *
4016
 * @param	DoliDB		$db				Database handler
4017
 * @param	Translate	$langs			Object langs
4018
 * @param	Conf		$conf			Object conf
4019
 * @param	array		$listofmodule	List of modules
4020
 * @param   int         $force          1=Reload module even if not already loaded
4021
 * @return	void
4022
 */
4023
function migrate_reload_modules($db,$langs,$conf,$listofmodule=array(),$force=0)
4024
{
4025
    dolibarr_install_syslog("upgrade2::migrate_reload_modules force=".$force);
4026
4027
    // If no info is provided, we reload all modules with mode newboxdefonly.
4028
    if (count($listofmodule) == 0)
4029
    {
4030
    	$listofmodule=array(
4031
	    	'MAIN_MODULE_AGENDA'=>'newboxdefonly',
4032
	    	'MAIN_MODULE_SOCIETE'=>'newboxdefonly',
4033
	    	'MAIN_MODULE_PRODUIT'=>'newboxdefonly',
4034
	    	'MAIN_MODULE_SERVICE'=>'newboxdefonly',
4035
	    	'MAIN_MODULE_COMMANDE'=>'newboxdefonly',
4036
	    	'MAIN_MODULE_FACTURE'=>'newboxdefonly',
4037
	    	'MAIN_MODULE_FOURNISSEUR'=>'newboxdefonly',
4038
    		'MAIN_MODULE_HOLIDAY'=>'newboxdefonly',
4039
    		'MAIN_MODULE_USER'=>'newboxdefonly',
4040
	    	'MAIN_MODULE_DEPLACEMENT'=>'newboxdefonly',
4041
	    	'MAIN_MODULE_DON'=>'newboxdefonly',
4042
	    	'MAIN_MODULE_ECM'=>'newboxdefonly',
4043
	    	'MAIN_MODULE_PAYBOX'=>'newboxdefonly',
4044
    		'MAIN_MODULE_OPENSURVEY'=>'newboxdefonly'
4045
    	);
4046
    }
4047
4048
    foreach($listofmodule as $moduletoreload => $reloadmode)
4049
    {
4050
    	if (empty($moduletoreload) || (empty($conf->global->$moduletoreload) && ! $force)) continue; // Discard reload if module not enabled
4051
4052
    	$mod=null;
4053
4054
	    if ($moduletoreload == 'MAIN_MODULE_AGENDA')
4055
	    {
4056
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Agenda module");
4057
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modAgenda.class.php';
4058
	        if ($res) {
4059
	            $mod=new modAgenda($db);
4060
	            $mod->remove('noboxes');
4061
	            $mod->init($reloadmode);
4062
	        }
4063
	    }
4064
        if ($moduletoreload == 'MAIN_MODULE_API')
4065
	    {
4066
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Rest API module");
4067
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modApi.class.php';
4068
	        if ($res) {
4069
	            $mod=new modApi($db);
4070
	            //$mod->remove('noboxes');
4071
	            $mod->init($reloadmode);
4072
	        }
4073
	    }
4074
	    if ($moduletoreload == 'MAIN_MODULE_BARCODE')
4075
    	{
4076
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Barcode module");
4077
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modBarcode.class.php';
4078
	        if ($res) {
4079
	            $mod=new modBarcode($db);
4080
	            $mod->remove('noboxes');
4081
	            $mod->init($reloadmode);
4082
	        }
4083
	    }
4084
	    if ($moduletoreload == 'MAIN_MODULE_CRON')
4085
    	{
4086
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Cron module");
4087
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modCron.class.php';
4088
	        if ($res) {
4089
	            $mod=new modCron($db);
4090
	            $mod->remove('noboxes');
4091
	            $mod->init($reloadmode);
4092
	        }
4093
	    }
4094
	    if ($moduletoreload == 'MAIN_MODULE_SOCIETE')
4095
	    {
4096
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Societe module");
4097
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modSociete.class.php';
4098
	        if ($res) {
4099
	            $mod=new modSociete($db);
4100
	            $mod->remove('noboxes');
4101
	            $mod->init($reloadmode);
4102
	        }
4103
	    }
4104
	    if ($moduletoreload == 'MAIN_MODULE_PRODUIT')    // Permission has changed into 2.7
4105
	    {
4106
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Produit module");
4107
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modProduct.class.php';
4108
	        if ($res) {
4109
	            $mod=new modProduct($db);
4110
	            //$mod->remove('noboxes');
4111
	            $mod->init($reloadmode);
4112
	        }
4113
	    }
4114
	    if ($moduletoreload == 'MAIN_MODULE_SERVICE')    // Permission has changed into 2.7
4115
	    {
4116
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Service module");
4117
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modService.class.php';
4118
	        if ($res) {
4119
	            $mod=new modService($db);
4120
	            //$mod->remove('noboxes');
4121
	            $mod->init($reloadmode);
4122
	        }
4123
	    }
4124
	    if ($moduletoreload == 'MAIN_MODULE_COMMANDE')   // Permission has changed into 2.9
4125
	    {
4126
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Commande module");
4127
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modCommande.class.php';
4128
	        if ($res) {
4129
	            $mod=new modCommande($db);
4130
	            //$mod->remove('noboxes');
4131
	            $mod->init($reloadmode);
4132
	        }
4133
	    }
4134
	    if ($moduletoreload == 'MAIN_MODULE_FACTURE')    // Permission has changed into 2.9
4135
	    {
4136
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Facture module");
4137
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modFacture.class.php';
4138
	        if ($res) {
4139
	            $mod=new modFacture($db);
4140
	            //$mod->remove('noboxes');
4141
	            $mod->init($reloadmode);
4142
	        }
4143
	    }
4144
	    if ($moduletoreload == 'MAIN_MODULE_FOURNISSEUR')    // Permission has changed into 2.9
4145
	    {
4146
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Fournisseur module");
4147
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modFournisseur.class.php';
4148
	        if ($res) {
4149
	            $mod=new modFournisseur($db);
4150
	            //$mod->remove('noboxes');
4151
	            $mod->init($reloadmode);
4152
	        }
4153
	    }
4154
    	if ($moduletoreload == 'MAIN_MODULE_HOLIDAY')    // Permission and tabs has changed into 3.8
4155
	    {
4156
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Leave Request module");
4157
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modHoliday.class.php';
4158
	        if ($res) {
4159
	            $mod=new modHoliday($db);
4160
	            $mod->remove('noboxes');
4161
	            $mod->init($reloadmode);
4162
	        }
4163
	    }
4164
	    if ($moduletoreload == 'MAIN_MODULE_DEPLACEMENT')    // Permission has changed into 3.0
4165
	    {
4166
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Deplacement module");
4167
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modDeplacement.class.php';
4168
	        if ($res) {
4169
	            $mod=new modDeplacement($db);
4170
	            //$mod->remove('noboxes');
4171
	            $mod->init($reloadmode);
4172
	        }
4173
	    }
4174
	    if ($moduletoreload == 'MAIN_MODULE_DON')    // Permission has changed into 3.0
4175
	    {
4176
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Don module");
4177
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modDon.class.php';
4178
	        if ($res) {
4179
	            $mod=new modDon($db);
4180
	            //$mod->remove('noboxes');
4181
	            $mod->init($reloadmode);
4182
	        }
4183
	    }
4184
	    if ($moduletoreload == 'MAIN_MODULE_ECM')    // Permission has changed into 3.0 and 3.1
4185
	    {
4186
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate ECM module");
4187
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modECM.class.php';
4188
	        if ($res) {
4189
	            $mod=new modECM($db);
4190
	            $mod->remove('noboxes');	// We need to remove because a permission id has been removed
4191
	            $mod->init($reloadmode);
4192
	        }
4193
	    }
4194
	    if ($moduletoreload == 'MAIN_MODULE_PAYBOX')    // Permission has changed into 3.0
4195
	    {
4196
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Paybox module");
4197
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modPaybox.class.php';
4198
	        if ($res) {
4199
	            $mod=new modPaybox($db);
4200
	            $mod->remove('noboxes');  // We need to remove because id of module has changed
4201
	            $mod->init($reloadmode);
4202
	        }
4203
	    }
4204
    	if ($moduletoreload == 'MAIN_MODULE_OPENSURVEY')    // Permission has changed into 3.0
4205
	    {
4206
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Opensurvey module");
4207
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modOpenSurvey.class.php';
4208
	        if ($res) {
4209
	            $mod=new modOpenSurvey($db);
4210
	            $mod->remove('noboxes');  // We need to remove because menu entries has changed
4211
	            $mod->init($reloadmode);
4212
	        }
4213
	    }
4214
    	if ($moduletoreload == 'MAIN_MODULE_USER')    // Permission has changed into 3.0
4215
	    {
4216
	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate User module");
4217
	        $res=@include_once DOL_DOCUMENT_ROOT.'/core/modules/modUser.class.php';
4218
	        if ($res) {
4219
	            $mod=new modUser($db);
4220
	            //$mod->remove('noboxes');
4221
	            $mod->init($reloadmode);
4222
	        }
4223
	    }
4224
4225
		if (! empty($mod) && is_object($mod))
4226
		{
4227
    		print '<tr><td colspan="4">';
4228
        	print '<b>'.$langs->trans('Upgrade').'</b>: ';
4229
        	print $langs->trans('MigrationReloadModule').' '.$mod->getName();  // We keep getName outside of trans because getName is already encoded/translated
4230
        	print "<!-- (".$reloadmode.") -->";
4231
        	print "<br>\n";
4232
        	print '</td></tr>';
4233
		}
4234
    }
4235
}
4236
4237
4238
4239
/**
4240
 * Reload menu if dynamic menus, if modified by version
4241
 *
4242
 * @param	DoliDB		$db			Database handler
4243
 * @param	Translate	$langs		Object langs
4244
 * @param	Conf		$conf		Object conf
4245
 * @param	string		$versionto	Version target
4246
 * @return	void
4247
 */
4248
function migrate_reload_menu($db,$langs,$conf,$versionto)
4249
{
4250
    global $conf;
4251
    dolibarr_install_syslog("upgrade2::migrate_reload_menu");
4252
4253
    // Define list of menu handlers to initialize
4254
    $listofmenuhandler=array();
4255
4256
    $versiontoarray=explode('.',$versionto);
4257
4258
    // Migration required when target version is between
4259
    $afterversionarray=explode('.','2.8.9');
4260
    $beforeversionarray=explode('.','2.9.9');
4261
    if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
4262
    {
4263
        $listofmenuhandler['auguria']=1;   // We set here only dynamic menu handlers
4264
    }
4265
4266
    // Migration required when target version is between
4267
    $afterversionarray=explode('.','3.1.9');
4268
    $beforeversionarray=explode('.','3.2.9');
4269
    if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
4270
    {
4271
        $listofmenuhandler['auguria']=1;   // We set here only dynamic menu handlers
4272
    }
4273
4274
    // Migration required when target version is between
4275
    $afterversionarray=explode('.','3.7.9');
4276
    $beforeversionarray=explode('.','4.0.9');
4277
    if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
4278
    {
4279
        $listofmenuhandler['auguria']=1;   // We set here only dynamic menu handlers
4280
    }
4281
4282
    foreach ($listofmenuhandler as $key => $val)
4283
    {
4284
        print '<tr><td colspan="4">';
4285
4286
        //print "x".$key;
4287
        print '<br>';
4288
        print '<b>'.$langs->trans('Upgrade').'</b>: '.$langs->trans('MenuHandler')." ".$key."<br>\n";
4289
4290
        // Load sql ini_menu_handler.sql file
4291
        $dir = DOL_DOCUMENT_ROOT."/core/menus/";
4292
        $file='init_menu_'.$key.'.sql';
4293
        if (file_exists($dir.$file))
4294
        {
4295
            $result=run_sql($dir.$file,1,'',1,$key);
4296
        }
4297
4298
        print '</td></tr>';
4299
    }
4300
}
4301
4302
4303
4304
/* A faire egalement: Modif statut paye et fk_facture des factures payes completement
4305
4306
On recherche facture incorrecte:
4307
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
4308
having  f.total_ttc = sum(pf.amount)
4309
4310
On les corrige:
4311
update llx_facture set paye=1, fk_statut=2 where close_code is null
4312
and rowid in (...)
4313
*/
4314
4315