Completed
Branch develop (c022b0)
by
unknown
40:00
created

upgrade2.php ➔ migrate_usergroup_rights_entity()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 67
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 35
nc 5
nop 3
dl 0
loc 67
rs 8.5896
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

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