Completed
Branch develop (fcf50c)
by
unknown
32:54
created

upgrade2.php ➔ migrate_reset_blocked_log()   D

Complexity

Conditions 10
Paths 5

Size

Total Lines 110
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 60
nc 5
nop 3
dl 0
loc 110
rs 4.8196
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2005       Marc Barilley / Ocebo   <[email protected]>
3
 * Copyright (C) 2005-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 [MODULE_NAME1_TO_ENABLE,MODULE_NAME2_TO_ENABLE]
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",'aZ09',3)?GETPOST("selectlang",'aZ09',3):'auto';
65
$langs->setDefaultLang($setuplang);
66
$versionfrom=GETPOST("versionfrom",'alpha',3)?GETPOST("versionfrom",'alpha',3):(empty($argv[1])?'':$argv[1]);
67
$versionto=GETPOST("versionto",'alpha',3)?GETPOST("versionto",'alpha',3):(empty($argv[2])?'':$argv[2]);
68
$enablemodules=GETPOST("enablemodules",'alpha',3)?GETPOST("enablemodules",'alpha',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 command 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><img class="valigntextbottom" src="../theme/common/octicons/lib/svg/database.svg" width="20" alt="Database"> '.$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
    $hookmanager->initHooks(array('upgrade'));
140
141
    if (!$db->connected)
142
    {
143
        print '<tr><td colspan="4">'.$langs->trans("ErrorFailedToConnectToDatabase",$conf->db->name).'</td><td align="right">'.$langs->trans('Error').'</td></tr>';
144
        dolibarr_install_syslog('upgrade2: failed to connect to database :' . $conf->db->name . ' on ' . $conf->db->host . ' for user ' . $conf->db->user, LOG_ERR);
145
        $error++;
146
    }
147
148
    if (! $error)
149
    {
150
        if($db->database_selected)
151
        {
152
            dolibarr_install_syslog('upgrade2: database connection successful :' . $dolibarr_main_db_name);
153
        }
154
        else
155
        {
156
            $error++;
157
        }
158
    }
159
160
    if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption=0;
161
    $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption;
162
    if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey='';
163
    $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey;
164
165
    // Chargement config
166
    if (! $error) $conf->setValues($db);
167
168
169
    /***************************************************************************************
170
     *
171
     * Migration des donnees
172
     *
173
     ***************************************************************************************/
174
    $db->begin();
175
176
    if (! $error)
177
    {
178
        // Current version is $conf->global->MAIN_VERSION_LAST_UPGRADE
179
        // Version to install is DOL_VERSION
180
        $dolibarrlastupgradeversionarray=preg_split('/[\.-]/',isset($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_UPGRADE:$conf->global->MAIN_VERSION_LAST_INSTALL);
181
182
        // Chaque action de migration doit renvoyer une ligne sur 4 colonnes avec
183
        // dans la 1ere colonne, la description de l'action a faire
184
        // dans la 4eme colonne, le texte 'OK' si fait ou 'AlreadyDone' si rien n'est fait ou 'Error'
185
186
        $versiontoarray=explode('.',$versionto);
187
        $versionranarray=explode('.',DOL_VERSION);
188
189
        $afterversionarray=explode('.','2.0.0');
190
        $beforeversionarray=explode('.','2.7.9');
191
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
192
        {
193
            // Script pour V2 -> V2.1
194
            migrate_paiements($db,$langs,$conf);
195
196
            migrate_contracts_det($db,$langs,$conf);
197
198
            migrate_contracts_date1($db,$langs,$conf);
199
200
            migrate_contracts_date2($db,$langs,$conf);
201
202
            migrate_contracts_date3($db,$langs,$conf);
203
204
            migrate_contracts_open($db,$langs,$conf);
205
206
            migrate_modeles($db,$langs,$conf);
207
208
            migrate_price_propal($db,$langs,$conf);
209
210
            migrate_price_commande($db,$langs,$conf);
211
212
            migrate_price_commande_fournisseur($db,$langs,$conf);
213
214
            migrate_price_contrat($db,$langs,$conf);
215
216
            migrate_paiementfourn_facturefourn($db,$langs,$conf);
217
218
219
            // Script pour V2.1 -> V2.2
220
            migrate_paiements_orphelins_1($db,$langs,$conf);
221
222
            migrate_paiements_orphelins_2($db,$langs,$conf);
223
224
            migrate_links_transfert($db,$langs,$conf);
225
226
227
            // Script pour V2.2 -> V2.4
228
            migrate_commande_expedition($db,$langs,$conf);
229
230
            migrate_commande_livraison($db,$langs,$conf);
231
232
            migrate_detail_livraison($db,$langs,$conf);
233
234
235
            // Script pour V2.5 -> V2.6
236
            migrate_stocks($db,$langs,$conf);
237
238
239
            // Script pour V2.6 -> V2.7
240
            migrate_menus($db,$langs,$conf);
241
242
            migrate_commande_deliveryaddress($db,$langs,$conf);
243
244
            migrate_restore_missing_links($db,$langs,$conf);
245
246
            migrate_rename_directories($db,$langs,$conf,'/compta','/banque');
247
248
            migrate_rename_directories($db,$langs,$conf,'/societe','/mycompany');
249
        }
250
251
        // Script for VX (X<2.8) -> V2.8
252
        $afterversionarray=explode('.','2.7.9');
253
        $beforeversionarray=explode('.','2.8.9');
254
        //print $versionto.' '.versioncompare($versiontoarray,$afterversionarray).' '.versioncompare($versiontoarray,$beforeversionarray);
255
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
256
        {
257
            migrate_price_facture($db,$langs,$conf);     // Code of this function works for 2.8+ because need a field tva_tx
258
259
            migrate_relationship_tables($db,$langs,$conf,'co_exp','fk_commande','commande','fk_expedition','shipping');
260
261
            migrate_relationship_tables($db,$langs,$conf,'pr_exp','fk_propal','propal','fk_expedition','shipping');
262
263
            migrate_relationship_tables($db,$langs,$conf,'pr_liv','fk_propal','propal','fk_livraison','delivery');
264
265
            migrate_relationship_tables($db,$langs,$conf,'co_liv','fk_commande','commande','fk_livraison','delivery');
266
267
            migrate_relationship_tables($db,$langs,$conf,'co_pr','fk_propale','propal','fk_commande','commande');
268
269
            migrate_relationship_tables($db,$langs,$conf,'fa_pr','fk_propal','propal','fk_facture','facture');
270
271
            migrate_relationship_tables($db,$langs,$conf,'co_fa','fk_commande','commande','fk_facture','facture');
272
273
            migrate_project_user_resp($db,$langs,$conf);
274
275
            migrate_project_task_actors($db,$langs,$conf);
276
        }
277
278
        // Script for VX (X<2.9) -> V2.9
279
        $afterversionarray=explode('.','2.8.9');
280
        $beforeversionarray=explode('.','2.9.9');
281
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
282
        {
283
            migrate_project_task_time($db,$langs,$conf);
284
285
            migrate_customerorder_shipping($db,$langs,$conf);
286
287
            migrate_shipping_delivery($db,$langs,$conf);
288
289
            migrate_shipping_delivery2($db,$langs,$conf);
290
        }
291
292
        // Script for VX (X<3.0) -> V3.0
293
        $afterversionarray=explode('.','2.9.9');
294
        $beforeversionarray=explode('.','3.0.9');
295
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
296
        {
297
            // No particular code
298
        }
299
300
        // Script for VX (X<3.1) -> V3.1
301
        $afterversionarray=explode('.','3.0.9');
302
        $beforeversionarray=explode('.','3.1.9');
303
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
304
        {
305
            migrate_rename_directories($db,$langs,$conf,'/rss','/externalrss');
306
307
            migrate_actioncomm_element($db,$langs,$conf);
308
        }
309
310
        // Script for VX (X<3.2) -> V3.2
311
        $afterversionarray=explode('.','3.1.9');
312
        $beforeversionarray=explode('.','3.2.9');
313
        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
314
        {
315
            migrate_price_contrat($db,$langs,$conf);
316
317
        	migrate_mode_reglement($db,$langs,$conf);
318
319
        	migrate_clean_association($db,$langs,$conf);
0 ignored issues
show
Bug introduced by
The call to migrate_clean_association() misses a required argument $versionto.

This check looks for function calls that miss required arguments.

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