dolibarr 25.0.0-alpha
upgrade2.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
3 * Copyright (C) 2005-2018 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2011 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2010 Juanjo Menent <jmenent@2byte.es>
6 * Copyright (C) 2015-2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
7 * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
8 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
9 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 *
24 * Upgrade2 scripts can be ran from command line with syntax:
25 *
26 * cd htdocs/install
27 * php upgrade.php 3.4.0 3.5.0 [dirmodule|ignoredbversion]
28 * php upgrade2.php 3.4.0 3.5.0 [MAIN_MODULE_NAME1_TO_ENABLE,MAIN_MODULE_NAME2_TO_ENABLE]
29 *
30 * And for final step:
31 * php step5.php 3.4.0 3.5.0
32 *
33 * Return code is 0 if OK, >0 if error
34 *
35 * Note: To just enable a module from command line, use this syntax:
36 * php upgrade2.php 0.0.0 0.0.0 [MAIN_MODULE_NAME1_TO_ENABLE,MAIN_MODULE_NAME2_TO_ENABLE]
37 */
38
44define('ALLOWED_IF_UPGRADE_UNLOCK_FOUND', 1);
45include_once 'inc.php';
46
51if (!file_exists($conffile)) {
52 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").';
53}
54require_once $conffile;
70'
71@phan-var-force string $dolibarr_main_db_type
72';
73
74require_once $dolibarr_main_document_root.'/compta/facture/class/facture.class.php';
75require_once $dolibarr_main_document_root.'/comm/propal/class/propal.class.php';
76require_once $dolibarr_main_document_root.'/contrat/class/contrat.class.php';
77require_once $dolibarr_main_document_root.'/commande/class/commande.class.php';
78require_once $dolibarr_main_document_root.'/fourn/class/fournisseur.commande.class.php';
79require_once $dolibarr_main_document_root.'/core/lib/price.lib.php';
80require_once $dolibarr_main_document_root.'/core/class/menubase.class.php';
81require_once $dolibarr_main_document_root.'/core/lib/admin.lib.php';
82require_once $dolibarr_main_document_root.'/core/lib/files.lib.php';
83require_once $dolibarr_main_document_root.'/user/class/user.class.php';
84require_once $dolibarr_main_document_root.'/blockedlog/lib/blockedlog.lib.php';
85
86global $langs;
87
88
89$error = 0;
90
91
92// This page can be long. We increase the allowed delay, but this does not work when we are in safe_mode.
93$err = error_reporting();
94error_reporting(0);
95if (getDolGlobalInt('MAIN_OVERRIDE_TIME_LIMIT')) {
96 @set_time_limit(getDolGlobalInt('MAIN_OVERRIDE_TIME_LIMIT'));
97} else {
98 @set_time_limit(600);
99}
100error_reporting($err);
101
102$setuplang = GETPOST("selectlang", 'aZ09', 3) ? GETPOST("selectlang", 'aZ09', 3) : 'auto';
103$langs->setDefaultLang($setuplang);
104$versionfrom = GETPOST("versionfrom", 'alpha', 3) ? GETPOST("versionfrom", 'alpha', 3) : (empty($argv[1]) ? '' : $argv[1]);
105$versionto = GETPOST("versionto", 'alpha', 3) ? GETPOST("versionto", 'alpha', 3) : (empty($argv[2]) ? '' : $argv[2]);
106$enablemodules = GETPOST("enablemodules", 'alpha', 3) ? GETPOST("enablemodules", 'alpha', 3) : (empty($argv[3]) ? '' : $argv[3]);
107
108$langs->loadLangs(array("admin", "install", "bills", "suppliers"));
109
110if ($dolibarr_main_db_type == 'mysqli') {
111 $choix = 1;
112}
113if ($dolibarr_main_db_type == 'pgsql') {
114 $choix = 2;
115}
116if ($dolibarr_main_db_type == 'mssql') {
117 $choix = 3;
118}
119
120
121dolibarr_install_syslog("--- upgrade2: entering upgrade2.php page ".$versionfrom." ".$versionto." ".$enablemodules);
122if (!is_object($conf)) {
123 dolibarr_install_syslog("upgrade2: conf file not initialized", LOG_ERR);
124}
125
126
127
128/*
129 * View
130 */
131
132if ((!$versionfrom || preg_match('/version/', $versionfrom)) && (!$versionto || preg_match('/version/', $versionto))) {
133 print 'Error: Parameter versionfrom or versionto missing or having a bad format.'."\n";
134 print 'Upgrade must be ran from command line with parameters or called from page install/index.php (like a first install)'."\n";
135 // Test if batch mode
136 $sapi_type = php_sapi_name();
137 $script_file = basename(__FILE__);
138 if (substr($sapi_type, 0, 3) == 'cli') {
139 print 'Syntax from command line: '.$script_file." x.y.z a.b.c [MAIN_MODULE_NAME1_TO_ENABLE,MAIN_MODULE_NAME2_TO_ENABLE...]\n";
140 print 'Example, upgrade from 19 to 20: '.$script_file." 19.0.0 20.0.0\n";
141 print 'Example, enable a module only: '.$script_file." 0.0.0 0.0.0 MAIN_MODULE_Adherent\n";
142 print "\n";
143 }
144 exit;
145}
146
147pHeader('', 'step5', GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'upgrade', 'versionfrom='.$versionfrom.'&versionto='.$versionto, '', 'main-inside main-inside-borderbottom');
148
149
150$db = null;
151
152if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ09'))) {
153 print '<h3><img class="valignmiddle inline-block paddingright" src="../public/theme/common/database.svg" width="20" alt="Database"> ';
154 print '<span class="inline-block valignmiddle">'.$langs->trans('DataMigration').'</span></h3>';
155
156 print '<table class="centpercent">';
157
158 // If password is encoded, we decode it
159 if ((!empty($dolibarr_main_db_pass) && preg_match('/(crypted|dolcrypt):/i', (string) $dolibarr_main_db_pass)) || !empty($dolibarr_main_db_encrypted_pass)) {
160 require_once $dolibarr_main_document_root.'/core/lib/security.lib.php';
161 if (!empty($dolibarr_main_db_pass) && preg_match('/crypted:/i', $dolibarr_main_db_pass)) {
162 $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', (string) $dolibarr_main_db_pass);
163 $dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially encrypted
164 $dolibarr_main_db_pass = dol_decode((string) $dolibarr_main_db_pass);
165 } elseif (preg_match('/dolcrypt:/i', (string) $dolibarr_main_db_pass)) {
166 $dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially encrypted
167 $dolibarr_main_db_pass = dolDecrypt((string) $dolibarr_main_db_pass);
168 } else {
169 $dolibarr_main_db_pass = dol_decode((string) $dolibarr_main_db_encrypted_pass);
170 }
171 }
172
173 // $conf is already instantiated inside inc.php
174 $conf->db->type = $dolibarr_main_db_type;
175 $conf->db->host = $dolibarr_main_db_host;
176 $conf->db->port = $dolibarr_main_db_port;
177 $conf->db->name = $dolibarr_main_db_name;
178 $conf->db->user = $dolibarr_main_db_user;
179 $conf->db->pass = $dolibarr_main_db_pass;
180
181 $db = getDoliDBInstance($conf->db->type, $conf->db->host, (string) $conf->db->user, (string) $conf->db->pass, (string) $conf->db->name, (int) $conf->db->port);
182
183 if (!$db->connected) {
184 print '<tr><td colspan="4">'.$langs->trans("ErrorFailedToConnectToDatabase", $conf->db->name).'</td><td class="right">'.$langs->trans('Error').'</td></tr>';
185 dolibarr_install_syslog('upgrade2: failed to connect to database :'.(string) $conf->db->name.' on '.(string) $conf->db->host.' for user '.(string) $conf->db->user, LOG_ERR);
186 $error++;
187 }
188
189 if (!$error) {
190 if ($db->database_selected) {
191 dolibarr_install_syslog('upgrade2: database connection successful :'.$dolibarr_main_db_name);
192 } else {
193 $error++;
194 }
195 }
196
197 if (empty($dolibarr_main_db_encryption)) {
198 $dolibarr_main_db_encryption = 0;
199 }
200 $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption;
201 if (empty($dolibarr_main_db_cryptkey)) {
202 $dolibarr_main_db_cryptkey = '';
203 }
204 $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey;
205
206 // Load global conf
207 $conf->setValues($db);
208
209
210 // Reforce log activation (samecode than into the inc.php)
211 $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1;
212 $conf->modules['syslog'] = 'syslog';
213 $conf->global->SYSLOG_LEVEL = constant('LOG_DEBUG');
214 if (!defined('SYSLOG_HANDLERS')) {
215 define('SYSLOG_HANDLERS', '["mod_syslog_file"]');
216 }
217 if (!defined('SYSLOG_FILE')) { // To avoid warning on systems with constant already defined
218 if (@is_writable('/tmp')) {
219 define('SYSLOG_FILE', '/tmp/dolibarr_install.log');
220 } elseif (!empty($_ENV["TMP"]) && @is_writable($_ENV["TMP"])) {
221 define('SYSLOG_FILE', $_ENV["TMP"].'/dolibarr_install.log');
222 } elseif (!empty($_ENV["TEMP"]) && @is_writable($_ENV["TEMP"])) {
223 define('SYSLOG_FILE', $_ENV["TEMP"].'/dolibarr_install.log');
224 } elseif (@is_writable('../../../../') && @file_exists('../../../../startdoliwamp.bat')) {
225 define('SYSLOG_FILE', '../../../../dolibarr_install.log'); // For DoliWamp
226 } elseif (@is_writable('../../')) {
227 define('SYSLOG_FILE', '../../dolibarr_install.log'); // For others
228 }
229 //print 'SYSLOG_FILE='.SYSLOG_FILE;exit;
230 }
231 if (defined('SYSLOG_FILE')) {
232 $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
233 }
234 if (!defined('SYSLOG_FILE_NO_ERROR')) {
235 define('SYSLOG_FILE_NO_ERROR', 1);
236 }
237 // We init log handler for install
238 $handlers = array('mod_syslog_file');
239 foreach ($handlers as $handler) {
240 $file = DOL_DOCUMENT_ROOT.'/core/modules/syslog/'.$handler.'.php';
241 if (!file_exists($file)) {
242 throw new Exception('Missing log handler file '.$handler.'.php');
243 }
244
245 require_once $file;
246 $loghandlerinstance = new $handler();
247 if (!$loghandlerinstance instanceof LogHandler) {
248 throw new Exception('Log handler does not extend LogHandler');
249 }
250
251 if (empty($conf->loghandlers[$handler])) {
252 $conf->loghandlers[$handler] = $loghandlerinstance;
253 }
254 }
255
256
257 $listofentities = array(1);
258
259 // Create the global $hookmanager object
260 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
261 $hookmanager = new HookManager($db);
262 $hookmanager->initHooks(array('upgrade2'));
263
264 $parameters = array('versionfrom' => $versionfrom, 'versionto' => $versionto);
265 $object = new stdClass();
266 $action = "upgrade";
267 $reshook = $hookmanager->executeHooks('doUpgradeBefore', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
268 if ($reshook >= 0 && is_array($hookmanager->resArray)) {
269 // Example: $hookmanager->resArray = array(2, 3, 10);
270 $listofentities = array_unique(array_merge($listofentities, $hookmanager->resArray));
271 }
272
273
274 /***************************************************************************************
275 *
276 * Migration of data
277 *
278 ***************************************************************************************/
279
280 dol_syslog("Process upgrade2 (step common to all entities)");
281
282 // Force to execute this at begin to avoid the new core code into Dolibarr to be broken.
283 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN birth date';
284 $db->query($sql, 1);
285 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN dateemployment date';
286 $db->query($sql, 1);
287 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN dateemploymentend date';
288 $db->query($sql, 1);
289 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN default_range integer';
290 $db->query($sql, 1);
291 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN default_c_exp_tax_cat integer';
292 $db->query($sql, 1);
293 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN langs varchar(24)';
294 $db->query($sql, 1);
295 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN fieldcomputed text';
296 $db->query($sql, 1);
297 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN fielddefault varchar(255)';
298 $db->query($sql, 1);
299 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX."extrafields ADD COLUMN enabled varchar(255) DEFAULT '1'";
300 $db->query($sql, 1);
301 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN help text';
302 $db->query($sql, 1);
303 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user_rights ADD COLUMN entity integer DEFAULT 1 NOT NULL';
304 $db->query($sql, 1);
305
306
307 $db->begin();
308
309 foreach ($listofentities as $entity) {
310 dol_syslog("Process upgrade2 (step a) for entity ".$entity);
311
312 // Set $conf context for entity
313 $conf->setEntityValues($db, $entity);
314
315 // Reset forced setup after the setValues
316 if (defined('SYSLOG_FILE')) {
317 $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
318 }
319
320 $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1; // Add also log into conf->logbuffer.
321
322 $versiontoarray = array();
323 $versionranarray = array();
324
325 dol_syslog("Process upgrade2 (step b) for entity ".$entity);
326
327 if (!$error) {
328 if (count($listofentities) > 1) {
329 print '<tr><td colspan="4">*** '.$langs->trans("Entity").' '.$entity.'</td></tr>'."\n";
330 }
331
332 // Current version is $conf->global->MAIN_VERSION_LAST_UPGRADE
333 // Version to install is DOL_VERSION
334 $dolibarrlastupgradeversionarray = preg_split('/[\.-]/', getDolGlobalString('MAIN_VERSION_LAST_UPGRADE', getDolGlobalString('MAIN_VERSION_LAST_INSTALL')));
335
336 // Every migration action must return a 4 column line with:
337 // - in the 1st column: the description of the action to do,
338 // - in the 4th column: the text 'OK' if done, or 'AlreadyDone' si nothing is done, or 'Error'
339
340 $versiontoarray = explode('.', $versionto);
341 $versionranarray = explode('.', DOL_VERSION);
342
343 $afterversionarray = explode('.', '2.0.0');
344 $beforeversionarray = explode('.', '2.7.9');
345 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
346 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
347
348 // Script for V2 -> V2.1
349 migrate_paiements($db, $langs, $conf);
350
351 migrate_contracts_det($db, $langs, $conf);
352
353 migrate_contracts_date1($db, $langs, $conf);
354
355 migrate_contracts_date2($db, $langs, $conf);
356
357 migrate_contracts_date3($db, $langs, $conf);
358
359 migrate_contracts_open($db, $langs, $conf);
360
361 migrate_modeles($db, $langs, $conf);
362
363 migrate_price_propal($db, $langs, $conf);
364
365 migrate_price_commande($db, $langs, $conf);
366
368
369 migrate_price_contrat($db, $langs, $conf);
370
372
373
374 // Script for V2.1 -> V2.2
376
378
379 migrate_links_transfert($db, $langs, $conf);
380
381
382 // Script for V2.2 -> V2.4
384
385 migrate_commande_livraison($db, $langs, $conf);
386
387 migrate_detail_livraison($db, $langs, $conf);
388
389
390 // Script for V2.5 -> V2.6
391 migrate_stocks($db, $langs, $conf);
392
393
394 // Script for V2.6 -> V2.7
395 migrate_menus($db, $langs, $conf);
396
398
400
401 migrate_rename_directories($db, $langs, $conf, '/compta', '/banque');
402
403 migrate_rename_directories($db, $langs, $conf, '/societe', '/mycompany');
404 }
405
406 // Script for 2.8
407 $afterversionarray = explode('.', '2.7.9');
408 $beforeversionarray = explode('.', '2.8.9');
409 //print $versionto.' '.versioncompare($versiontoarray,$afterversionarray).' '.versioncompare($versiontoarray,$beforeversionarray);
410 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
411 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
412
413 migrate_price_facture($db, $langs, $conf); // Code of this function works for 2.8+ because need a field tva_tx
414
415 migrate_relationship_tables($db, $langs, $conf, 'co_exp', 'fk_commande', 'commande', 'fk_expedition', 'shipping');
416
417 migrate_relationship_tables($db, $langs, $conf, 'pr_exp', 'fk_propal', 'propal', 'fk_expedition', 'shipping');
418
419 migrate_relationship_tables($db, $langs, $conf, 'pr_liv', 'fk_propal', 'propal', 'fk_livraison', 'delivery');
420
421 migrate_relationship_tables($db, $langs, $conf, 'co_liv', 'fk_commande', 'commande', 'fk_livraison', 'delivery');
422
423 migrate_relationship_tables($db, $langs, $conf, 'co_pr', 'fk_propale', 'propal', 'fk_commande', 'commande');
424
425 migrate_relationship_tables($db, $langs, $conf, 'fa_pr', 'fk_propal', 'propal', 'fk_facture', 'facture');
426
427 migrate_relationship_tables($db, $langs, $conf, 'co_fa', 'fk_commande', 'commande', 'fk_facture', 'facture');
428
429 migrate_project_user_resp($db, $langs, $conf);
430
432 }
433
434 // Script for 2.9
435 $afterversionarray = explode('.', '2.8.9');
436 $beforeversionarray = explode('.', '2.9.9');
437 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
438 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
439
440 migrate_element_time($db, $langs, $conf);
441
443
444 migrate_shipping_delivery($db, $langs, $conf);
445
446 migrate_shipping_delivery2($db, $langs, $conf);
447 }
448
449 // Script for 3.0
450 $afterversionarray = explode('.', '2.9.9');
451 $beforeversionarray = explode('.', '3.0.9');
452 //if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
453 // No particular code
454 //}
455
456 // Script for 3.1
457 $afterversionarray = explode('.', '3.0.9');
458 $beforeversionarray = explode('.', '3.1.9');
459 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
460 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
461
462 migrate_rename_directories($db, $langs, $conf, '/rss', '/externalrss');
463
464 migrate_actioncomm_element($db, $langs, $conf);
465 }
466
467 // Script for 3.2
468 $afterversionarray = explode('.', '3.1.9');
469 $beforeversionarray = explode('.', '3.2.9');
470 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
471 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
472
473 migrate_price_contrat($db, $langs, $conf);
474
475 migrate_mode_reglement($db, $langs, $conf);
476
477 migrate_clean_association($db, $langs, $conf);
478 }
479
480 // Script for 3.3
481 $afterversionarray = explode('.', '3.2.9');
482 $beforeversionarray = explode('.', '3.3.9');
483 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
484 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
485
487 }
488
489 // Script for 3.4
490 // No specific scripts
491
492 // Tasks to do always and only into last targeted version
493 $afterversionarray = explode('.', '3.6.9'); // target is after this
494 $beforeversionarray = explode('.', '3.7.9'); // target is before this
495 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
496 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
497
498 migrate_event_assignement($db, $langs, $conf);
499 }
500
501 // Scripts for 3.9
502 $afterversionarray = explode('.', '3.7.9');
503 $beforeversionarray = explode('.', '3.8.9');
504 //if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
505 // No particular code
506 //}
507
508 // Scripts for 4.0
509 $afterversionarray = explode('.', '3.9.9');
510 $beforeversionarray = explode('.', '4.0.9');
511 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
512 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
513
514 migrate_rename_directories($db, $langs, $conf, '/fckeditor', '/medias');
515 }
516
517 // Scripts for 5.0
518 $afterversionarray = explode('.', '4.0.9');
519 $beforeversionarray = explode('.', '5.0.9');
520 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
521 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
522
523 // Migrate to add entity value into llx_societe_remise
524 migrate_remise_entity($db, $langs, $conf);
525
526 // Migrate to add entity value into llx_societe_remise_except
528 }
529
530 // Scripts for 6.0
531 $afterversionarray = explode('.', '5.0.9');
532 $beforeversionarray = explode('.', '6.0.9');
533 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
534 if (isModEnabled('multicompany')) {
535 global $multicompany_transverse_mode;
536
537 // Only if the transverse mode is not used
538 if (empty($multicompany_transverse_mode)) {
539 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
540
541 // Migrate to add entity value into llx_user_rights
542 migrate_user_rights_entity($db, $langs, $conf);
543
544 // Migrate to add entity value into llx_usergroup_rights
546 }
547 }
548 }
549
550 // Scripts for 7.0
551 $afterversionarray = explode('.', '6.0.9');
552 $beforeversionarray = explode('.', '7.0.9');
553 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
554 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
555
556 // Migrate contact association
558
559 migrate_reset_blocked_log($db, $langs, $conf);
560 }
561
562 // Scripts for 8.0
563 $afterversionarray = explode('.', '7.0.9');
564 $beforeversionarray = explode('.', '8.0.9');
565 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
566 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
567
568 migrate_rename_directories($db, $langs, $conf, '/contracts', '/contract');
569 }
570
571 // Scripts for 9.0
572 $afterversionarray = explode('.', '8.0.9');
573 $beforeversionarray = explode('.', '9.0.9');
574 //if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
575 //migrate_user_photospath();
576 //}
577
578 // Scripts for 11.0
579 $afterversionarray = explode('.', '10.0.9');
580 $beforeversionarray = explode('.', '11.0.9');
581 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
582 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
583
588 }
589
590 // Scripts for 14.0
591 $afterversionarray = explode('.', '13.0.9');
592 $beforeversionarray = explode('.', '14.0.9');
593 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
594 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
595
598 }
599
600 // Scripts for 16.0
601 $afterversionarray = explode('.', '15.0.9');
602 $beforeversionarray = explode('.', '16.0.9');
603 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
604 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
605
608 }
609
610 // Scripts for 17.0
611 $afterversionarray = explode('.', '16.0.9');
612 $beforeversionarray = explode('.', '17.0.9');
613 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
614 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
615
617 }
618
619 // Scripts for 18.0
620 $afterversionarray = explode('.', '17.0.9');
621 $beforeversionarray = explode('.', '18.0.9');
622 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
623 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
624
626 }
627
628 // Scripts for 19.0
629 /*
630 $afterversionarray = explode('.', '18.0.9');
631 $beforeversionarray = explode('.', '19.0.9');
632 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
633 }
634 */
635
636 // Scripts for 20.0
637 $afterversionarray = explode('.', '19.0.9');
638 $beforeversionarray = explode('.', '20.0.9');
639 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
640 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
641
643 }
644
645 // Scripts for 21.0
646 $afterversionarray = explode('.', '20.0.9');
647 $beforeversionarray = explode('.', '21.0.9');
648
649
650 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
651 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
652
654 }
655
656 // Scripts for 22.0
657 $afterversionarray = explode('.', '21.0.9');
658 $beforeversionarray = explode('.', '22.0.9');
659 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
660 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
661
663 }
664
665 // Scripts for 23.0
666 $afterversionarray = explode('.', '22.0.9');
667 $beforeversionarray = explode('.', '23.0.9');
668 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
669 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
670
672
674
676 }
677
678 // Scripts for 23.0
679 $afterversionarray = explode('.', '23.0.9');
680 $beforeversionarray = explode('.', '24.0.9');
681 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
682 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
683
684 migrate_rename_directories($db, $langs, $conf, '/banque', '/bank');
685
687 }
688 }
689
690 // Code executed only if migration is LAST ONE. Must always be done.
691 if (versioncompare($versiontoarray, $versionranarray) >= 0 || versioncompare($versiontoarray, $versionranarray) <= -3) {
692 dol_syslog("Run migrate_... if migration is LAST ONE");
693
694 // 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)
695 $listofmodule = array(
696 'MAIN_MODULE_ACCOUNTING' => 'newboxdefonly',
697 'MAIN_MODULE_AGENDA' => 'newboxdefonly',
698 'MAIN_MODULE_BOM' => 'menuonly',
699 'MAIN_MODULE_BANQUE' => 'menuonly',
700 'MAIN_MODULE_BARCODE' => 'newboxdefonly',
701 'MAIN_MODULE_CRON' => 'newboxdefonly',
702 'MAIN_MODULE_COMMANDE' => 'newboxdefonly',
703 'MAIN_MODULE_BLOCKEDLOG' => 'noboxes',
704 'MAIN_MODULE_DON' => 'newboxdefonly',
705 'MAIN_MODULE_ECM' => 'newboxdefonly',
706 'MAIN_MODULE_EVENTORGANIZATION' => 'newboxdefonly',
707 'MAIN_MODULE_EXPENSEREPORT' => 'newboxdefonly',
708 'MAIN_MODULE_FACTURE' => 'newboxdefonly',
709 'MAIN_MODULE_FOURNISSEUR' => 'newboxdefonly',
710 'MAIN_MODULE_FICHEINTER' => 'newboxdefonly',
711 'MAIN_MODULE_HOLIDAY' => 'newboxdefonly',
712 'MAIN_MODULE_LOAN' => 'newboxdefonly',
713 'MAIN_MODULE_MARGIN' => 'menuonly',
714 'MAIN_MODULE_MRP' => 'menuonly',
715 'MAIN_MODULE_OPENSURVEY' => 'newboxdefonly',
716 'MAIN_MODULE_PARTNERSHIP' => 'newboxdefonly',
717 'MAIN_MODULE_PRINTING' => 'newboxdefonly',
718 'MAIN_MODULE_PRODUIT' => 'newboxdefonly',
719 'MAIN_MODULE_RECRUITMENT' => 'menuonly',
720 'MAIN_MODULE_RESOURCE' => 'noboxes',
721 'MAIN_MODULE_SALARIES' => 'newboxdefonly',
722 'MAIN_MODULE_SERVICE' => 'newboxdefonly',
723 //'MAIN_MODULE_SYSLOG' => 'newboxdefonly', This enabled the module syslog, but we don't want to do that.
724 'MAIN_MODULE_SOCIETE' => 'newboxdefonly',
725 'MAIN_MODULE_STRIPE' => 'menuonly',
726 'MAIN_MODULE_SUBTOTALS' => 'menuonly',
727 'MAIN_MODULE_TICKET' => 'newboxdefonly',
728 'MAIN_MODULE_TAKEPOS' => 'newboxdefonly',
729 'MAIN_MODULE_USER' => 'newboxdefonly', //This one must be always done and only into last targeted version)
730 'MAIN_MODULE_VARIANTS' => 'newboxdefonly',
731 'MAIN_MODULE_WEBSITE' => 'newboxdefonly',
732 );
733
734 $result = migrate_reload_modules($db, $langs, $conf, $listofmodule);
735 if ($result < 0) {
736 $error++;
737 }
738
739 // Grant the supplier prices permissions added in 23.0 to users/groups that already have
740 // the matching product/service rights (ids resolved by name from the rights_def reloaded
741 // just above), so nobody loses access to supplier prices on upgrade. Idempotent.
742 $result = migrate_supplier_prices_permissions($db, $langs, $conf);
743 if ($result < 0) {
744 $error++;
745 }
746
747 // Reload menus (this must be always done, and only into last targeted version)
748 // This reload the auguria menu.To reload a dynamic menu defined into module descriptor, see previours step
749 $result = migrate_reload_menu($db, $langs, $conf);
750 if ($result < 0) {
751 $error++;
752 }
753 }
754
755 // Can force activation of some module during migration with parameter 'enablemodules=MAIN_MODULE_XXX,MAIN_MODULE_YYY,...'
756 // In most cases (online install or upgrade) $enablemodules is empty. Can be forced when ran from command line.
757 if (!$error && $enablemodules) {
758 // Reload modules (this must be always done and only into last targeted version)
759 $listofmodules = array();
760 $enablemodules = preg_replace('/enablemodules=/', '', $enablemodules);
761 $tmplistofmodules = explode(',', $enablemodules);
762 foreach ($tmplistofmodules as $value) {
763 $listofmodules[$value] = 'forceactivate';
764 }
765
766 $resultreloadmodules = migrate_reload_modules($db, $langs, $conf, $listofmodules, 1);
767 if ($resultreloadmodules < 0) {
768 $error++;
769 }
770 }
771
772
773 // Can call a dedicated external upgrade process with hook doUpgradeAfterDB()
774 if (!$error) {
775 $parameters = array('versionfrom' => $versionfrom, 'versionto' => $versionto, 'conf' => $conf);
776 $object = new stdClass();
777 $action = "upgrade";
778 $reshook = $hookmanager->executeHooks('doUpgradeAfterDB', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
779 if ($hookmanager->resNbOfHooks > 0) {
780 if ($reshook < 0) {
781 print '<tr><td colspan="4">';
782 print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: ';
783 print $hookmanager->error;
784 print "<!-- (".$reshook.") -->";
785 print '</td></tr>';
786 } else {
787 print '<tr class="trforrunsql"><td colspan="4">';
788 print '<b>'.$langs->trans('UpgradeExternalModule').' (DB)</b>: <span class="ok">OK</span>';
789 print "<!-- (".$reshook.") -->";
790 print '</td></tr>';
791 }
792 } else {
793 //if (!empty($conf->modules))
794 if (!empty($conf->modules_parts['hooks'])) { // If there is at least one module with one hook, we show message to say nothing was done
795 print '<tr class="trforrunsql"><td colspan="4">';
796 print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: '.$langs->trans("NodoUpgradeAfterDB");
797 print '</td></tr>';
798 }
799 }
800 }
801 }
802
803 print '</table>';
804
805 if (!$error) {
806 // Set constant to ask to remake a new ping to inform about upgrade (if ping was already done and OK)
807 $sql = 'UPDATE '.MAIN_DB_PREFIX."const SET VALUE = 'torefresh' WHERE name = 'MAIN_FIRST_PING_OK_ID'"; // This should be useless now because constant is uniqueid+' v'+version
808 $db->query($sql, 1);
809 }
810
811 // We always commit.
812 // Process is designed so we can run it several times whatever is situation.
813 $db->commit();
814
815
816 /***************************************************************************************
817 *
818 * Migration of files
819 *
820 ***************************************************************************************/
821
822 foreach ($listofentities as $entity) {
823 // Set $conf context for entity
824 $conf->setEntityValues($db, $entity);
825 // Reset forced setup after the setValues
826 if (defined('SYSLOG_FILE')) {
827 $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
828 }
829 $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1;
830
831
832 // Copy directory medias
833 $srcroot = DOL_DOCUMENT_ROOT.'/install/medias';
834 $destroot = DOL_DATA_ROOT.'/medias';
835 dolCopyDir($srcroot, $destroot, '0', 0);
836
837
838 // Actions for all versions (no database change but delete some files and directories)
839 migrate_delete_old_files($db, $langs, $conf);
840 migrate_delete_old_dir($db, $langs, $conf);
841 // Actions for all versions (no database change but create some directories)
842 dol_mkdir(DOL_DATA_ROOT.'/bank');
843 // Actions for all versions (no database change but rename some directories)
844 migrate_rename_directories($db, $langs, $conf, '/banque/bordereau', '/bank/checkdeposits');
845
846
847 $parameters = array('versionfrom' => $versionfrom, 'versionto' => $versionto, 'conf' => $conf);
848 $object = new stdClass();
849 $action = "upgrade";
850 $reshook = $hookmanager->executeHooks('doUpgradeAfterFiles', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
851 if ($hookmanager->resNbOfHooks > 0) {
852 if ($reshook < 0) {
853 print '<tr><td colspan="4">';
854 print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: ';
855 print $hookmanager->error;
856 print "<!-- (".$reshook.") -->";
857 print '</td></tr>';
858 } else {
859 print '<tr class="trforrunsql"><td colspan="4">';
860 print '<b>'.$langs->trans('UpgradeExternalModule').' (Files)</b>: <span class="ok">OK</span>';
861 print "<!-- (".$reshook.") -->";
862 print '</td></tr>';
863 }
864 } else {
865 //if (!empty($conf->modules))
866 if (!empty($conf->modules_parts['hooks'])) { // If there is at least one module with one hook, we show message to say nothing was done
867 print '<tr class="trforrunsql"><td colspan="4">';
868 print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: '.$langs->trans("NodoUpgradeAfterFiles");
869 print '</td></tr>';
870 }
871 }
872 }
873
874 $db->close();
875
876 $silent = 0;
877 if (!$silent) {
878 print '<table width="100%">';
879 print '<tr><td style="width: 30%">'.$langs->trans("MigrationFinished").'</td>';
880 print '<td class="right">';
881 if ($error == 0) {
882 //print '<span class="ok">'.$langs->trans("OK").'</span> - '; // $error = 0 does not mean there is no error (error are not always trapped)
883 } else {
884 print '<span class="error">'.$langs->trans("Error").'</span> - ';
885 }
886
887 //if (!empty($conf->use_javascript_ajax)) { // use_javascript_ajax is not defined
888 print '<script type="text/javascript">
889 jQuery(document).ready(function() {
890 function init_trrunsql()
891 {
892 console.log("toggle .trforrunsql");
893 jQuery(".trforrunsql").toggle();
894 }
895 init_trrunsql();
896 jQuery(".trforrunsqlshowhide").click(function() {
897 init_trrunsql();
898 });
899 });
900 </script>';
901 print '<a class="reposition trforrunsqlshowhide" href="#">'.$langs->trans("ShowHideDetails").'</a>';
902 //}
903
904 print '</td></tr>'."\n";
905 print '</table>';
906 }
907
908 //print '<div><br>'.$langs->trans("MigrationFinished").'</div>';
909} else {
910 print '<div class="error">'.$langs->trans('ErrorWrongParameters').'</div>';
911 $error++;
912}
913
914$ret = 0;
915if ($error && isset($argv[1])) {
916 $ret = 1;
917}
918dolibarr_install_syslog("Exit ".$ret);
919
920dolibarr_install_syslog("--- upgrade2: end");
921pFooter($error ? 2 : 0, $setuplang);
922
923if ($db !== null && $db->connected) {
924 $db->close();
925}
926
927// Return code if ran from command line
928if ($ret) {
929 exit($ret);
930}
931
932
933
942function migrate_paiements($db, $langs, $conf)
943{
944 print '<tr><td colspan="4">';
945
946 print '<br>';
947 print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
948
949 $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement", "fk_facture");
950 $obj = $db->fetch_object($result);
951 if ($obj) {
952 $sql = "SELECT p.rowid, p.fk_facture, p.amount";
953 $sql .= " FROM ".MAIN_DB_PREFIX."paiement as p";
954 $sql .= " WHERE p.fk_facture > 0";
955
956 $resql = $db->query($sql);
957 $row = array();
958 $num = 0;
959
960 dolibarr_install_syslog("upgrade2::migrate_paiements");
961 if ($resql) {
962 $i = 0;
963 $num = $db->num_rows($resql);
964
965 while ($i < $num) {
966 $obj = $db->fetch_object($resql);
967 $row[$i][0] = $obj->rowid;
968 $row[$i][1] = $obj->fk_facture;
969 $row[$i][2] = $obj->amount;
970 $i++;
971 }
972 } else {
973 dol_print_error($db);
974 }
975
976 if ($num) {
977 print $langs->trans('MigrationPaymentsNumberToUpdate', $num)."<br>\n";
978 $res = 0;
979 if ($db->begin()) {
980 $num = count($row);
981 for ($i = 0; $i < $num; $i++) {
982 $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
983 $sql .= " VALUES (".((int) $row[$i][1]).",".((int) $row[$i][0]).",".((float) $row[$i][2]).")";
984
985 $res += $db->query($sql);
986
987 $sql = "UPDATE ".MAIN_DB_PREFIX."paiement SET fk_facture = 0 WHERE rowid = ".((int) $row[$i][0]);
988
989 $res += $db->query($sql);
990
991 print $langs->trans('MigrationProcessPaymentUpdate', $row[$i][0])."<br>\n";
992 }
993 }
994
995 if (is_array($row) && $res == (2 * count($row))) {
996 $db->commit();
997 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
998 } else {
999 $db->rollback();
1000 print $langs->trans('MigrationUpdateFailed').'<br>';
1001 }
1002 } else {
1003 print $langs->trans('MigrationPaymentsNothingToUpdate')."<br>\n";
1004 }
1005 } else {
1006 print $langs->trans('MigrationPaymentsNothingToUpdate')."<br>\n";
1007 }
1008
1009 print '</td></tr>';
1010}
1011
1023{
1024 print '<tr><td colspan="4">';
1025
1026 print '<br>';
1027 print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
1028
1029 $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement", "fk_facture");
1030 $obj = $db->fetch_object($result);
1031 if ($obj) {
1032 // All answer of this requests should have a parent into llx_paiement_facture
1033 $sql = "SELECT DISTINCT p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,";
1034 $sql .= " bu2.url_id as socid";
1035 $sql .= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)";
1036 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_paiement = p.rowid";
1037 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu2 ON (bu.fk_bank=bu2.fk_bank AND bu2.type = 'company')";
1038 $sql .= " WHERE pf.rowid IS NULL AND (p.rowid=bu.url_id AND bu.type='payment') AND bu.fk_bank = b.rowid";
1039 $sql .= " AND b.rappro = 1";
1040 $sql .= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)";
1041
1042 $resql = $db->query($sql);
1043
1044 dolibarr_install_syslog("upgrade2::migrate_paiements_orphelins_1");
1045 $row = array();
1046 if ($resql) {
1047 $i = $j = 0;
1048 $num = $db->num_rows($resql);
1049
1050 while ($i < $num) {
1051 $obj = $db->fetch_object($resql);
1052 if ($obj->pamount == $obj->bamount && $obj->socid) { // Pour etre sur d'avoir bon cas
1053 $row[$j]['paymentid'] = $obj->rowid; // paymentid
1054 $row[$j]['pamount'] = $obj->pamount;
1055 $row[$j]['fk_bank'] = $obj->fk_bank;
1056 $row[$j]['bamount'] = $obj->bamount;
1057 $row[$j]['socid'] = $obj->socid;
1058 $row[$j]['datec'] = $obj->datec;
1059 $j++;
1060 }
1061 $i++;
1062 }
1063 } else {
1064 dol_print_error($db);
1065 }
1066
1067 if (count($row)) {
1068 print $langs->trans('OrphelinsPaymentsDetectedByMethod', 1).': '.count($row)."<br>\n";
1069 $db->begin();
1070
1071 $res = 0;
1072 $num = count($row);
1073 for ($i = 0; $i < $num; $i++) {
1074 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') == 2) {
1075 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>';
1076 }
1077
1078 // Look for invoices without payment relations with the same amount and same comppany
1079 $sql = " SELECT DISTINCT f.rowid from ".MAIN_DB_PREFIX."facture as f";
1080 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
1081 $sql .= " WHERE f.fk_statut in (2,3) AND fk_soc = ".((int) $row[$i]['socid'])." AND total_ttc = ".((float) $row[$i]['pamount']);
1082 $sql .= " AND pf.fk_facture IS NULL";
1083 $sql .= " ORDER BY f.fk_statut";
1084 //print $sql.'<br>';
1085 $resql = $db->query($sql);
1086 if ($resql) {
1087 $num = $db->num_rows($resql);
1088 //print 'Nb of invoice found for this amount and company :'.$num.'<br>';
1089 if ($num >= 1) {
1090 $obj = $db->fetch_object($resql);
1091 $facid = $obj->rowid;
1092
1093 $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
1094 $sql .= " VALUES (".((int) $facid).",".((int) $row[$i]['paymentid']).", ".((float) $row[$i]['pamount']).")";
1095
1096 $res += $db->query($sql);
1097
1098 print $langs->trans('MigrationProcessPaymentUpdate', 'facid='.$facid.'-paymentid='.$row[$i]['paymentid'].'-amount='.$row[$i]['pamount'])."<br>\n";
1099 }
1100 } else {
1101 print 'ERROR';
1102 }
1103 }
1104
1105 if ($res > 0) {
1106 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1107 } else {
1108 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1109 }
1110
1111 $db->commit();
1112 } else {
1113 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1114 }
1115 } else {
1116 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1117 }
1118
1119 print '</td></tr>';
1120}
1121
1133{
1134 print '<tr><td colspan="4">';
1135
1136 print '<br>';
1137 print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
1138
1139 $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement", "fk_facture");
1140 $obj = $db->fetch_object($result);
1141 if ($obj) {
1142 // All records returned by this query should have a parent in llx_paiement_facture
1143 $sql = "SELECT DISTINCT p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,";
1144 $sql .= " bu2.url_id as socid";
1145 $sql .= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)";
1146 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_paiement = p.rowid";
1147 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu2 ON (bu.fk_bank = bu2.fk_bank AND bu2.type = 'company')";
1148 $sql .= " WHERE pf.rowid IS NULL AND (p.fk_bank = bu.fk_bank AND bu.type = 'payment') AND bu.fk_bank = b.rowid";
1149 $sql .= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)";
1150
1151 $resql = $db->query($sql);
1152
1153 dolibarr_install_syslog("upgrade2::migrate_paiements_orphelins_2");
1154 $row = array();
1155 if ($resql) {
1156 $i = $j = 0;
1157 $num = $db->num_rows($resql);
1158
1159 while ($i < $num) {
1160 $obj = $db->fetch_object($resql);
1161 if ($obj->pamount == $obj->bamount && $obj->socid) { // Pour etre sur d'avoir bon cas
1162 $row[$j]['paymentid'] = $obj->rowid; // paymentid
1163 $row[$j]['pamount'] = $obj->pamount;
1164 $row[$j]['fk_bank'] = $obj->fk_bank;
1165 $row[$j]['bamount'] = $obj->bamount;
1166 $row[$j]['socid'] = $obj->socid;
1167 $row[$j]['datec'] = $obj->datec;
1168 $j++;
1169 }
1170 $i++;
1171 }
1172 } else {
1173 dol_print_error($db);
1174 }
1175
1176 $nberr = 0;
1177
1178 $num = count($row);
1179 if ($num) {
1180 print $langs->trans('OrphelinsPaymentsDetectedByMethod', 2).': '.count($row)."<br>\n";
1181 $db->begin();
1182
1183 $res = 0;
1184 for ($i = 0; $i < $num; $i++) {
1185 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') == 2) {
1186 print '* '.$row[$i]['datec'].' paymentid='.$row[$i]['paymentid'].' pamount='.$row[$i]['pamount'].' fk_bank='.$row[$i]['fk_bank'].' '.$row[$i]['bamount'].' socid='.$row[$i]['socid'].'<br>';
1187 }
1188
1189 // Look for invoices without payment relations with the same amount and same comppany
1190 $sql = " SELECT DISTINCT f.rowid from ".MAIN_DB_PREFIX."facture as f";
1191 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
1192 $sql .= " WHERE f.fk_statut in (2,3) AND fk_soc = ".((int) $row[$i]['socid'])." AND total_ttc = ".((float) $row[$i]['pamount']);
1193 $sql .= " AND pf.fk_facture IS NULL";
1194 $sql .= " ORDER BY f.fk_statut";
1195 //print $sql.'<br>';
1196 $resql = $db->query($sql);
1197 if ($resql) {
1198 $num = $db->num_rows($resql);
1199 //print 'Nb of invoice found for this amount and company :'.$num.'<br>';
1200 if ($num >= 1) {
1201 $obj = $db->fetch_object($resql);
1202 $facid = $obj->rowid;
1203
1204 $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
1205 $sql .= " VALUES (".((int) $facid).",".((int) $row[$i]['paymentid']).", ".((float) $row[$i]['pamount']).")";
1206
1207 $res += $db->query($sql);
1208
1209 print $langs->trans('MigrationProcessPaymentUpdate', 'facid='.$facid.'-paymentid='.$row[$i]['paymentid'].'-amount='.$row[$i]['pamount'])."<br>\n";
1210 }
1211 } else {
1212 print 'ERROR';
1213 $nberr++;
1214 }
1215 }
1216
1217 if ($res > 0) {
1218 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1219 } else {
1220 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1221 }
1222
1223 $db->commit();
1224 } else {
1225 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1226 }
1227
1228 // Delete obsolete fields fk_facture
1229 $db->begin();
1230
1231 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."paiement DROP COLUMN fk_facture";
1232 $db->query($sql);
1233
1234 if (!$nberr) {
1235 $db->commit();
1236 } else {
1237 print 'ERROR';
1238 $db->rollback();
1239 }
1240 } else {
1241 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1242 }
1243
1244 print '</td></tr>';
1245}
1246
1247
1256function migrate_contracts_det($db, $langs, $conf)
1257{
1258 print '<tr><td colspan="4">';
1259
1260 $nberr = 0;
1261
1262 print '<br>';
1263 print '<b>'.$langs->trans('MigrationContractsUpdate')."</b><br>\n";
1264
1265 $sql = "SELECT c.rowid as cref, c.date_contrat, c.statut, c.fk_product, c.fk_facture, c.fk_user_author,";
1266 $sql .= " p.ref, p.label, p.description, p.price, p.tva_tx, p.duration, cd.rowid";
1267 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
1268 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p";
1269 $sql .= " ON c.fk_product = p.rowid";
1270 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd";
1271 $sql .= " ON c.rowid=cd.fk_contrat";
1272 $sql .= " WHERE cd.rowid IS NULL AND p.rowid IS NOT NULL";
1273 $resql = $db->query($sql);
1274
1275 dolibarr_install_syslog("upgrade2::migrate_contracts_det");
1276 if ($resql) {
1277 $i = 0;
1278 $row = array();
1279 $num = $db->num_rows($resql);
1280
1281 if ($num) {
1282 print $langs->trans('MigrationContractsNumberToUpdate', $num)."<br>\n";
1283 $db->begin();
1284
1285 while ($i < $num) {
1286 $obj = $db->fetch_object($resql);
1287
1288 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet (";
1289 $sql .= "fk_contrat, fk_product, statut, label, description,";
1290 $sql .= "date_ouverture_prevue, date_ouverture, date_fin_validite, tva_tx, qty,";
1291 $sql .= "subprice, price_ht, fk_user_author, fk_user_ouverture)";
1292 $sql .= " VALUES (";
1293 $sql .= ((int) $obj->cref).", ".($obj->fk_product ? ((int) $obj->fk_product) : 0).", ";
1294 $sql .= "0, ";
1295 $sql .= "'".$db->escape($obj->label)."', null, ";
1296 $sql .= ($obj->date_contrat ? "'".$db->idate($db->jdate($obj->date_contrat))."'" : "null").", ";
1297 $sql .= "null, ";
1298 $sql .= "null, ";
1299 $sql .= ((float) $obj->tva_tx).", 1, ";
1300 $sql .= ((float) $obj->price).", ".((float) $obj->price).", ".((int) $obj->fk_user_author).",";
1301 $sql .= "null";
1302 $sql .= ")";
1303
1304 if ($db->query($sql)) {
1305 print $langs->trans('MigrationContractsLineCreation', $obj->cref)."<br>\n";
1306 } else {
1307 dol_print_error($db);
1308 $nberr++;
1309 }
1310
1311 $i++;
1312 }
1313
1314 if (!$nberr) {
1315 // $db->rollback();
1316 $db->commit();
1317 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1318 } else {
1319 $db->rollback();
1320 print $langs->trans('MigrationUpdateFailed').'<br>';
1321 }
1322 } else {
1323 print $langs->trans('MigrationContractsNothingToUpdate')."<br>\n";
1324 }
1325 } else {
1326 print $langs->trans('MigrationContractsFieldDontExist')."<br>\n";
1327 // dol_print_error($db);
1328 }
1329
1330 print '</td></tr>';
1331}
1332
1341function migrate_links_transfert($db, $langs, $conf)
1342{
1343 print '<tr><td colspan="4">';
1344
1345 $nberr = 0;
1346
1347 print '<br>';
1348 print '<b>'.$langs->trans('MigrationBankTransfertsUpdate')."</b><br>\n";
1349
1350 $sql = "SELECT ba.rowid as barowid, bb.rowid as bbrowid";
1351 $sql .= " FROM ".MAIN_DB_PREFIX."bank as bb, ".MAIN_DB_PREFIX."bank as ba";
1352 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON bu.fk_bank = ba.rowid";
1353 $sql .= " WHERE ba.amount = -bb.amount AND ba.fk_account <> bb.fk_account";
1354 $sql .= " AND ba.datev = bb.datev AND ba.datec = bb.datec";
1355 $sql .= " AND bu.fk_bank IS NULL";
1356 $resql = $db->query($sql);
1357
1358 dolibarr_install_syslog("upgrade2::migrate_links_transfert");
1359 if ($resql) {
1360 $i = 0;
1361 $row = array();
1362 $num = $db->num_rows($resql);
1363
1364 if ($num) {
1365 print $langs->trans('MigrationBankTransfertsToUpdate', $num)."<br>\n";
1366 $db->begin();
1367
1368 while ($i < $num) {
1369 $obj = $db->fetch_object($resql);
1370
1371 $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url (";
1372 $sql .= "fk_bank, url_id, url, label, type";
1373 $sql .= ")";
1374 $sql .= " VALUES (";
1375 $sql .= ((int) $obj->barowid).",".((int) $obj->bbrowid).", '/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert'";
1376 $sql .= ")";
1377
1378 //print $sql.'<br>';
1379 dolibarr_install_syslog("migrate_links_transfert");
1380
1381 if (!$db->query($sql)) {
1382 dol_print_error($db);
1383 $nberr++;
1384 }
1385
1386 $i++;
1387 }
1388
1389 if (!$nberr) {
1390 // $db->rollback();
1391 $db->commit();
1392 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1393 } else {
1394 $db->rollback();
1395 print $langs->trans('MigrationUpdateFailed').'<br>';
1396 }
1397 } else {
1398 print $langs->trans('MigrationBankTransfertsNothingToUpdate')."<br>\n";
1399 }
1400 } else {
1401 dol_print_error($db);
1402 }
1403
1404 print '</td></tr>';
1405}
1406
1415function migrate_contracts_date1($db, $langs, $conf)
1416{
1417 print '<tr><td colspan="4">';
1418
1419 print '<br>';
1420 print '<b>'.$langs->trans('MigrationContractsEmptyDatesUpdate')."</b><br>\n";
1421
1422 $sql = "update ".MAIN_DB_PREFIX."contrat set date_contrat=tms where date_contrat is null";
1423 dolibarr_install_syslog("upgrade2::migrate_contracts_date1");
1424 $resql = $db->query($sql);
1425 if (!$resql) {
1426 dol_print_error($db);
1427 }
1428 if ($db->affected_rows($resql) > 0) {
1429 print $langs->trans('MigrationContractsEmptyDatesUpdateSuccess')."<br>\n";
1430 } else {
1431 print $langs->trans('MigrationContractsEmptyDatesNothingToUpdate')."<br>\n";
1432 }
1433
1434 $sql = "update ".MAIN_DB_PREFIX."contrat set datec=tms where datec is null";
1435 dolibarr_install_syslog("upgrade2::migrate_contracts_date1");
1436 $resql = $db->query($sql);
1437 if (!$resql) {
1438 dol_print_error($db);
1439 }
1440 if ($db->affected_rows($resql) > 0) {
1441 print $langs->trans('MigrationContractsEmptyCreationDatesUpdateSuccess')."<br>\n";
1442 } else {
1443 print $langs->trans('MigrationContractsEmptyCreationDatesNothingToUpdate')."<br>\n";
1444 }
1445
1446 print '</td></tr>';
1447}
1448
1457function migrate_contracts_date2($db, $langs, $conf)
1458{
1459 print '<tr><td colspan="4">';
1460
1461 $nberr = 0;
1462
1463 print '<br>';
1464 print '<b>'.$langs->trans('MigrationContractsInvalidDatesUpdate')."</b><br>\n";
1465
1466 $sql = "SELECT c.rowid as cref, c.datec, c.date_contrat, MIN(cd.date_ouverture) as datemin";
1467 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c,";
1468 $sql .= " ".MAIN_DB_PREFIX."contratdet as cd";
1469 $sql .= " WHERE c.rowid=cd.fk_contrat AND cd.date_ouverture IS NOT NULL";
1470 $sql .= " GROUP BY c.rowid, c.date_contrat";
1471 $resql = $db->query($sql);
1472
1473 dolibarr_install_syslog("upgrade2::migrate_contracts_date2");
1474 if ($resql) {
1475 $i = 0;
1476 $row = array();
1477 $num = $db->num_rows($resql);
1478
1479 if ($num) {
1480 $nbcontratsmodifie = 0;
1481 $db->begin();
1482
1483 while ($i < $num) {
1484 $obj = $db->fetch_object($resql);
1485 if ($obj->date_contrat > $obj->datemin) {
1486 $datemin = $db->jdate($obj->datemin);
1487
1488 print $langs->trans('MigrationContractsInvalidDateFix', $obj->cref, $obj->date_contrat, $obj->datemin)."<br>\n";
1489 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat";
1490 $sql .= " SET date_contrat='".$db->idate($datemin)."'";
1491 $sql .= " WHERE rowid = ".((int) $obj->cref);
1492 $resql2 = $db->query($sql);
1493 if (!$resql2) {
1494 dol_print_error($db);
1495 }
1496
1497 $nbcontratsmodifie++;
1498 }
1499 $i++;
1500 }
1501
1502 $db->commit();
1503
1504 if ($nbcontratsmodifie) {
1505 print $langs->trans('MigrationContractsInvalidDatesNumber', $nbcontratsmodifie)."<br>\n";
1506 } else {
1507 print $langs->trans('MigrationContractsInvalidDatesNothingToUpdate')."<br>\n";
1508 }
1509 }
1510 } else {
1511 dol_print_error($db);
1512 }
1513
1514 print '</td></tr>';
1515}
1516
1525function migrate_contracts_date3($db, $langs, $conf)
1526{
1527 print '<tr><td colspan="4">';
1528
1529 print '<br>';
1530 print '<b>'.$langs->trans('MigrationContractsIncoherentCreationDateUpdate')."</b><br>\n";
1531
1532 $sql = "update ".MAIN_DB_PREFIX."contrat set datec=date_contrat where datec is null or datec > date_contrat";
1533 dolibarr_install_syslog("upgrade2::migrate_contracts_date3");
1534 $resql = $db->query($sql);
1535 if (!$resql) {
1536 dol_print_error($db);
1537 }
1538 if ($db->affected_rows($resql) > 0) {
1539 print $langs->trans('MigrationContractsIncoherentCreationDateUpdateSuccess')."<br>\n";
1540 } else {
1541 print $langs->trans('MigrationContractsIncoherentCreationDateNothingToUpdate')."<br>\n";
1542 }
1543
1544 print '</td></tr>';
1545}
1546
1555function migrate_contracts_open($db, $langs, $conf)
1556{
1557 print '<tr><td colspan="4">';
1558
1559 print '<br>';
1560 print '<b>'.$langs->trans('MigrationReopeningContracts')."</b><br>\n";
1561
1562 $sql = "SELECT c.rowid as cref FROM ".MAIN_DB_PREFIX."contrat as c, ".MAIN_DB_PREFIX."contratdet as cd";
1563 $sql .= " WHERE cd.statut = 4 AND c.statut=2 AND c.rowid=cd.fk_contrat";
1564 dolibarr_install_syslog("upgrade2::migrate_contracts_open");
1565 $resql = $db->query($sql);
1566 if (!$resql) {
1567 dol_print_error($db);
1568 }
1569 if ($db->affected_rows($resql) > 0) {
1570 $i = 0;
1571 $row = array();
1572 $num = $db->num_rows($resql);
1573
1574 if ($num) {
1575 $nbcontratsmodifie = 0;
1576 $db->begin();
1577
1578 while ($i < $num) {
1579 $obj = $db->fetch_object($resql);
1580
1581 print $langs->trans('MigrationReopenThisContract', $obj->cref)."<br>\n";
1582 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat";
1583 $sql .= " SET statut = 1";
1584 $sql .= " WHERE rowid = ".((int) $obj->cref);
1585 $resql2 = $db->query($sql);
1586 if (!$resql2) {
1587 dol_print_error($db);
1588 }
1589
1590 $nbcontratsmodifie++;
1591
1592 $i++;
1593 }
1594
1595 $db->commit();
1596
1597 if ($nbcontratsmodifie) {
1598 print $langs->trans('MigrationReopenedContractsNumber', $nbcontratsmodifie)."<br>\n";
1599 } else {
1600 print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n";
1601 }
1602 }
1603 } else {
1604 print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n";
1605 }
1606
1607 print '</td></tr>';
1608}
1609
1619{
1620 global $bc;
1621
1622 print '<tr><td colspan="4">';
1623 print '<br>';
1624 print '<b>'.$langs->trans('SuppliersInvoices')."</b><br>\n";
1625 print '</td></tr>';
1626
1627 $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiementfourn", "fk_facture_fourn");
1628 $obj = $db->fetch_object($result);
1629 if ($obj) {
1630 $error = 0;
1631 $nb = 0;
1632
1633 $select_sql = 'SELECT rowid, fk_facture_fourn, amount';
1634 $select_sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn';
1635 $select_sql .= ' WHERE fk_facture_fourn IS NOT NULL';
1636
1637 dolibarr_install_syslog("upgrade2::migrate_paiementfourn_facturefourn");
1638 $select_resql = $db->query($select_sql);
1639 if ($select_resql) {
1640 $select_num = $db->num_rows($select_resql);
1641 $i = 0;
1642
1643 // For every supplier payment, add a line to paiementfourn_facturefourn
1644 while (($i < $select_num) && (!$error)) {
1645 $select_obj = $db->fetch_object($select_resql);
1646
1647 // Verify if the row is already in the new table - avoid adding duplicates
1648 $check_sql = 'SELECT fk_paiementfourn, fk_facturefourn';
1649 $check_sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn';
1650 $check_sql .= ' WHERE fk_paiementfourn = '.((int) $select_obj->rowid).' AND fk_facturefourn = '.((int) $select_obj->fk_facture_fourn);
1651 $check_resql = $db->query($check_sql);
1652 if ($check_resql) {
1653 $check_num = $db->num_rows($check_resql);
1654 if ($check_num == 0) {
1655 $db->begin();
1656
1657 if ($nb == 0) {
1658 print '<tr><td colspan="4" class="nowrap"><b>'.$langs->trans('SuppliersInvoices').'</b></td></tr>';
1659 print '<tr><td>fk_paiementfourn</td><td>fk_facturefourn</td><td>'.$langs->trans('Amount').'</td><td>&nbsp;</td></tr>';
1660 }
1661
1662 print '<tr class="oddeven">';
1663 print '<td>'.$select_obj->rowid.'</td><td>'.$select_obj->fk_facture_fourn.'</td><td>'.$select_obj->amount.'</td>';
1664
1665 $insert_sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiementfourn_facturefourn SET ';
1666 $insert_sql .= ' fk_paiementfourn = \''.((int) $select_obj->rowid).'\',';
1667 $insert_sql .= ' fk_facturefourn = \''.((int) $select_obj->fk_facture_fourn).'\',';
1668 $insert_sql .= ' amount = \''.((float) $select_obj->amount).'\'';
1669 $insert_resql = $db->query($insert_sql);
1670
1671 if ($insert_resql) {
1672 $nb++;
1673 print '<td><span class="ok">'.$langs->trans("OK").'</span></td>';
1674 } else {
1675 print '<td><span class="error">Error on insert</span></td>';
1676 $error++;
1677 }
1678 print '</tr>';
1679 }
1680 } else {
1681 $error++;
1682 }
1683 $i++;
1684 }
1685 } else {
1686 $error++;
1687 }
1688
1689 if (!$error) {
1690 if (!$nb) {
1691 print '<tr><td>'.$langs->trans("AlreadyDone").'</td></tr>';
1692 }
1693 $db->commit();
1694
1695 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."paiementfourn DROP COLUMN fk_facture_fourn";
1696 $db->query($sql);
1697 } else {
1698 print '<tr><td>'.$langs->trans("Error").'</td></tr>';
1699 $db->rollback();
1700 }
1701 } else {
1702 print '<tr><td>'.$langs->trans("AlreadyDone").'</td></tr>';
1703 }
1704}
1705
1714function migrate_price_facture($db, $langs, $conf)
1715{
1716 $err = 0;
1717
1718 $tmpmysoc = new Societe($db);
1719 $tmpmysoc->setMysoc($conf);
1720
1721 $db->begin();
1722
1723 print '<tr><td colspan="4">';
1724
1725 print '<br>';
1726 print '<b>'.$langs->trans('MigrationInvoice')."</b><br>\n";
1727
1728 // List of invoice lines not up to date
1729 $sql = "SELECT fd.rowid, fd.qty, fd.subprice, fd.remise_percent, fd.tva_tx as vatrate, fd.total_ttc, fd.info_bits,";
1730 $sql .= " f.rowid as facid, f.remise_percent as remise_percent_global, f.total_ttc as total_ttc_f";
1731 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd, ".MAIN_DB_PREFIX."facture as f";
1732 $sql .= " WHERE fd.fk_facture = f.rowid";
1733 $sql .= " AND (((fd.total_ttc = 0 AND fd.remise_percent != 100) or fd.total_ttc IS NULL) or f.total_ttc IS NULL)";
1734 //print $sql;
1735
1736 dolibarr_install_syslog("upgrade2::migrate_price_facture");
1737 $resql = $db->query($sql);
1738 if ($resql) {
1739 $num = $db->num_rows($resql);
1740 $i = 0;
1741 if ($num) {
1742 while ($i < $num) {
1743 $obj = $db->fetch_object($resql);
1744
1745 $rowid = $obj->rowid;
1746 $qty = $obj->qty;
1747 $pu = $obj->subprice;
1748 $vatrate = $obj->vatrate;
1749 $remise_percent = $obj->remise_percent;
1750 $remise_percent_global = $obj->remise_percent_global;
1751 $total_ttc_f = $obj->total_ttc_f;
1752 $info_bits = $obj->info_bits;
1753
1754 // We update the 3 new fields
1755 $facligne = new FactureLigne($db);
1756 $facligne->fetch($rowid);
1757
1758 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $facligne->product_type, $tmpmysoc);
1759 $total_ht = $result[0];
1760 $total_tva = $result[1];
1761 $total_ttc = $result[2];
1762
1763 $facligne->total_ht = (float) $total_ht;
1764 $facligne->total_tva = (float) $total_tva;
1765 $facligne->total_ttc = (float) $total_ttc;
1766
1767 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);
1768 print '. ';
1769 $facligne->update_total();
1770
1771
1772 /* On touche a facture mere uniquement si total_ttc = 0 */
1773 if (!$total_ttc_f) {
1774 $facture = new Facture($db);
1775 $facture->id = $obj->facid;
1776
1777 if ($facture->fetch($facture->id) >= 0) {
1778 if ($facture->update_price() > 0) {
1779 //print $facture->id;
1780 } else {
1781 print "Error id=".$facture->id;
1782 $err++;
1783 }
1784 } else {
1785 print "Error #3";
1786 $err++;
1787 }
1788 }
1789 print " ";
1790
1791 $i++;
1792 }
1793 } else {
1794 print $langs->trans("AlreadyDone");
1795 }
1796 $db->free($resql);
1797
1798 $db->commit();
1799 } else {
1800 print "Error #1 ".$db->error();
1801 $err++;
1802
1803 $db->rollback();
1804 }
1805
1806 print '<br>';
1807
1808 print '</td></tr>';
1809}
1810
1819function migrate_price_propal($db, $langs, $conf)
1820{
1821 $tmpmysoc = new Societe($db);
1822 $tmpmysoc->setMysoc($conf);
1823
1824 $db->begin();
1825
1826 print '<tr><td colspan="4">';
1827
1828 print '<br>';
1829 print '<b>'.$langs->trans('MigrationProposal')."</b><br>\n";
1830
1831 // List of proposal lines not up to date
1832 $sql = "SELECT pd.rowid, pd.qty, pd.subprice, pd.remise_percent, pd.tva_tx as vatrate, pd.info_bits,";
1833 $sql .= " p.rowid as propalid, p.remise_percent as remise_percent_global";
1834 $sql .= " FROM ".MAIN_DB_PREFIX."propaldet as pd, ".MAIN_DB_PREFIX."propal as p";
1835 $sql .= " WHERE pd.fk_propal = p.rowid";
1836 $sql .= " AND ((pd.total_ttc = 0 AND pd.remise_percent != 100) or pd.total_ttc IS NULL)";
1837
1838 dolibarr_install_syslog("upgrade2::migrate_price_propal");
1839 $resql = $db->query($sql);
1840 if ($resql) {
1841 $num = $db->num_rows($resql);
1842 $i = 0;
1843 if ($num) {
1844 while ($i < $num) {
1845 $obj = $db->fetch_object($resql);
1846
1847 $rowid = $obj->rowid;
1848 $qty = $obj->qty;
1849 $pu = $obj->subprice;
1850 $vatrate = $obj->vatrate;
1851 $remise_percent = $obj->remise_percent;
1852 $remise_percent_global = $obj->remise_percent_global;
1853 $info_bits = $obj->info_bits;
1854
1855 // Update the 3 new fields
1856 $propalligne = new PropaleLigne($db);
1857 $propalligne->fetch($rowid);
1858
1859 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $propalligne->product_type, $tmpmysoc);
1860 $total_ht = $result[0];
1861 $total_tva = $result[1];
1862 $total_ttc = $result[2];
1863
1864 $propalligne->total_ht = (float) $total_ht;
1865 $propalligne->total_tva = (float) $total_tva;
1866 $propalligne->total_ttc = (float) $total_ttc;
1867
1868 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);
1869 print '. ';
1870 $propalligne->update_total();
1871
1872 $i++;
1873 }
1874 } else {
1875 print $langs->trans("AlreadyDone");
1876 }
1877
1878 $db->free($resql);
1879
1880 $db->commit();
1881 } else {
1882 print "Error #1 ".$db->error();
1883
1884 $db->rollback();
1885 }
1886
1887 print '<br>';
1888
1889 print '</td></tr>';
1890}
1891
1900function migrate_price_contrat($db, $langs, $conf)
1901{
1902 $db->begin();
1903
1904 $tmpmysoc = new Societe($db);
1905 $tmpmysoc->setMysoc($conf);
1906 if (empty($tmpmysoc->country_id)) {
1907 $tmpmysoc->country_id = 0; // Ti not have this set to '' or will make sql syntax error.
1908 }
1909
1910 print '<tr><td colspan="4">';
1911
1912 print '<br>';
1913 print '<b>'.$langs->trans('MigrationContract')."</b><br>\n";
1914
1915 // List of contract lines not up to date
1916 $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
1917 $sql .= " c.rowid as contratid";
1918 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c";
1919 $sql .= " WHERE cd.fk_contrat = c.rowid";
1920 $sql .= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100 AND cd.subprice > 0) or cd.total_ttc IS NULL)";
1921
1922 dolibarr_install_syslog("upgrade2::migrate_price_contrat");
1923 $resql = $db->query($sql);
1924 if ($resql) {
1925 $num = $db->num_rows($resql);
1926 $i = 0;
1927 if ($num) {
1928 while ($i < $num) {
1929 $obj = $db->fetch_object($resql);
1930
1931 $rowid = $obj->rowid;
1932 $qty = $obj->qty;
1933 $pu = $obj->subprice;
1934 $vatrate = $obj->vatrate;
1935 $remise_percent = $obj->remise_percent;
1936 $info_bits = $obj->info_bits;
1937
1938 // We update the 3 new fields
1939 $contratligne = new ContratLigne($db);
1940 //$contratligne->fetch($rowid); Not required because update_total only updates redefined fields
1941 $contratligne->fetch($rowid);
1942
1943 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, 0, 'HT', $info_bits, $contratligne->product_type, $tmpmysoc);
1944 $total_ht = $result[0];
1945 $total_tva = $result[1];
1946 $total_ttc = $result[2];
1947
1948 $contratligne->total_ht = (float) $total_ht;
1949 $contratligne->total_tva = (float) $total_tva;
1950 $contratligne->total_ttc = (float) $total_ttc;
1951
1952 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);
1953 print '. ';
1954 $contratligne->update_total();
1955
1956 $i++;
1957 }
1958 } else {
1959 print $langs->trans("AlreadyDone");
1960 }
1961
1962 $db->free($resql);
1963
1964 $db->commit();
1965 } else {
1966 print "Error #1 ".$db->error();
1967
1968 $db->rollback();
1969 }
1970
1971 print '<br>';
1972
1973 print '</td></tr>';
1974}
1975
1984function migrate_price_commande($db, $langs, $conf)
1985{
1986 $db->begin();
1987
1988 $tmpmysoc = new Societe($db);
1989 $tmpmysoc->setMysoc($conf);
1990
1991 print '<tr><td colspan="4">';
1992
1993 print '<br>';
1994 print '<b>'.$langs->trans('MigrationOrder')."</b><br>\n";
1995
1996 // List of sales orders lines not up to date
1997 $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
1998 $sql .= " c.rowid as commandeid, c.remise_percent as remise_percent_global";
1999 $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."commande as c";
2000 $sql .= " WHERE cd.fk_commande = c.rowid";
2001 $sql .= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)";
2002
2003 dolibarr_install_syslog("upgrade2::migrate_price_commande");
2004 $resql = $db->query($sql);
2005 if ($resql) {
2006 $num = $db->num_rows($resql);
2007 $i = 0;
2008 if ($num) {
2009 while ($i < $num) {
2010 $obj = $db->fetch_object($resql);
2011
2012 $rowid = $obj->rowid;
2013 $qty = $obj->qty;
2014 $pu = $obj->subprice;
2015 $vatrate = $obj->vatrate;
2016 $remise_percent = $obj->remise_percent;
2017 $remise_percent_global = $obj->remise_percent_global;
2018 $info_bits = $obj->info_bits;
2019
2020 // We update the 3 new fields
2021 $commandeligne = new OrderLine($db);
2022 $commandeligne->fetch($rowid);
2023
2024 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $commandeligne->product_type, $tmpmysoc);
2025 $total_ht = $result[0];
2026 $total_tva = $result[1];
2027 $total_ttc = $result[2];
2028
2029 $commandeligne->total_ht = (float) $total_ht;
2030 $commandeligne->total_tva = (float) $total_tva;
2031 $commandeligne->total_ttc = (float) $total_ttc;
2032
2033 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);
2034 print '. ';
2035 $commandeligne->update_total();
2036
2037 $i++;
2038 }
2039 } else {
2040 print $langs->trans("AlreadyDone");
2041 }
2042
2043 $db->free($resql);
2044
2045 /*
2046 $sql = "DELETE FROM ".MAIN_DB_PREFIX."commandedet";
2047 $sql.= " WHERE price = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0 AND remise_percent = 0";
2048 $resql=$db->query($sql);
2049 if (! $resql)
2050 {
2051 dol_print_error($db);
2052 }
2053 */
2054
2055 $db->commit();
2056 } else {
2057 print "Error #1 ".$db->error();
2058
2059 $db->rollback();
2060 }
2061
2062 print '<br>';
2063
2064 print '</td></tr>';
2065}
2066
2076{
2077 global $mysoc;
2078
2079 $db->begin();
2080
2081 $tmpmysoc = new Societe($db);
2082 $tmpmysoc->setMysoc($conf);
2083
2084 print '<tr><td colspan="4">';
2085
2086 print '<br>';
2087 print '<b>'.$langs->trans('MigrationSupplierOrder')."</b><br>\n";
2088
2089 // List of purchase order lines not up to date
2090 $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
2091 $sql .= " c.rowid as commandeid, c.remise_percent as remise_percent_global";
2092 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd, ".MAIN_DB_PREFIX."commande_fournisseur as c";
2093 $sql .= " WHERE cd.fk_commande = c.rowid";
2094 $sql .= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)";
2095
2096 dolibarr_install_syslog("upgrade2::migrate_price_commande_fournisseur");
2097 $resql = $db->query($sql);
2098 if ($resql) {
2099 $num = $db->num_rows($resql);
2100 $i = 0;
2101 if ($num) {
2102 while ($i < $num) {
2103 $obj = $db->fetch_object($resql);
2104
2105 $rowid = $obj->rowid;
2106 $qty = $obj->qty;
2107 $pu = $obj->subprice;
2108 $vatrate = $obj->vatrate;
2109 $remise_percent = $obj->remise_percent;
2110 $remise_percent_global = $obj->remise_percent_global;
2111 $info_bits = $obj->info_bits;
2112
2113 // We update the 3 new fields
2114 $commandeligne = new CommandeFournisseurLigne($db);
2115 $commandeligne->fetch($rowid);
2116
2117 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $commandeligne->product_type, $mysoc);
2118 $total_ht = $result[0];
2119 $total_tva = $result[1];
2120 $total_ttc = $result[2];
2121
2122 $commandeligne->total_ht = (float) $total_ht;
2123 $commandeligne->total_tva = (float) $total_tva;
2124 $commandeligne->total_ttc = (float) $total_ttc;
2125
2126 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);
2127 print '. ';
2128 $commandeligne->update_total();
2129
2130 $i++;
2131 }
2132 } else {
2133 print $langs->trans("AlreadyDone");
2134 }
2135
2136 $db->free($resql);
2137
2138 /*
2139 $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet";
2140 $sql.= " WHERE subprice = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0";
2141 $resql=$db->query($sql);
2142 if (! $resql)
2143 {
2144 dol_print_error($db);
2145 }
2146 */
2147
2148 $db->commit();
2149 } else {
2150 print "Error #1 ".$db->error();
2151
2152 $db->rollback();
2153 }
2154
2155 print '<br>';
2156
2157 print '</td></tr>';
2158}
2159
2168function migrate_modeles($db, $langs, $conf)
2169{
2170 //print '<br>';
2171 //print '<b>'.$langs->trans('UpdateModelsTable')."</b><br>\n";
2172
2173 dolibarr_install_syslog("upgrade2::migrate_modeles");
2174
2175 if (isModEnabled('invoice')) {
2176 include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
2177 $modellist = ModelePDFFactures::liste_modeles($db);
2178 if (count($modellist) == 0) {
2179 // Aucun model par default.
2180 $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('crabe','invoice')";
2181 $resql = $db->query($sql);
2182 if (!$resql) {
2183 dol_print_error($db);
2184 }
2185 }
2186 }
2187
2188 if (isModEnabled('order')) {
2189 include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
2190 $modellist = ModelePDFCommandes::liste_modeles($db);
2191 if (count($modellist) == 0) {
2192 // Aucun model par default.
2193 $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('einstein','order')";
2194 $resql = $db->query($sql);
2195 if (!$resql) {
2196 dol_print_error($db);
2197 }
2198 }
2199 }
2200
2201 if (isModEnabled("shipping")) {
2202 include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
2203 $modellist = ModelePdfExpedition::liste_modeles($db);
2204 if (count($modellist) == 0) {
2205 // Aucun model par default.
2206 $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('rouget','shipping')";
2207 $resql = $db->query($sql);
2208 if (!$resql) {
2209 dol_print_error($db);
2210 }
2211 }
2212 }
2213
2214 //print $langs->trans("AlreadyDone");
2215}
2216
2217
2227{
2228 dolibarr_install_syslog("upgrade2::migrate_commande_expedition");
2229
2230 print '<tr><td colspan="4">';
2231
2232 print '<br>';
2233 print '<b>'.$langs->trans('MigrationShipmentOrderMatching')."</b><br>\n";
2234
2235 $result = $db->DDLDescTable(MAIN_DB_PREFIX."expedition", "fk_commande");
2236 $obj = $db->fetch_object($result);
2237 if ($obj) {
2238 $error = 0;
2239
2240 $db->begin();
2241
2242 $sql = "SELECT e.rowid, e.fk_commande FROM ".MAIN_DB_PREFIX."expedition as e";
2243 $resql = $db->query($sql);
2244 if ($resql) {
2245 $i = 0;
2246 $num = $db->num_rows($resql);
2247
2248 if ($num) {
2249 while ($i < $num) {
2250 $obj = $db->fetch_object($resql);
2251
2252 $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_exp (fk_expedition,fk_commande)";
2253 $sql .= " VALUES (".((int) $obj->rowid).", ".((int) $obj->fk_commande).")";
2254 $resql2 = $db->query($sql);
2255
2256 if (!$resql2) {
2257 $error++;
2258 dol_print_error($db);
2259 }
2260 print '. ';
2261 $i++;
2262 }
2263 }
2264
2265 if ($error == 0) {
2266 $db->commit();
2267 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."expedition DROP COLUMN fk_commande";
2268 print $langs->trans('FieldRenamed')."<br>\n";
2269 $db->query($sql);
2270 } else {
2271 $db->rollback();
2272 }
2273 } else {
2274 dol_print_error($db);
2275 $db->rollback();
2276 }
2277 } else {
2278 print $langs->trans('AlreadyDone')."<br>\n";
2279 }
2280 print '</td></tr>';
2281}
2282
2291function migrate_commande_livraison($db, $langs, $conf)
2292{
2293 dolibarr_install_syslog("upgrade2::migrate_commande_livraison");
2294
2295 print '<tr><td colspan="4">';
2296
2297 print '<br>';
2298 print '<b>'.$langs->trans('MigrationDeliveryOrderMatching')."</b><br>\n";
2299
2300 $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraison", "fk_commande");
2301 $obj = $db->fetch_object($result);
2302 if ($obj) {
2303 $error = 0;
2304
2305 $db->begin();
2306
2307 $sql = "SELECT l.rowid, l.fk_commande,";
2308 $sql .= " c.ref_client, c.date_livraison as delivery_date";
2309 $sql .= " FROM ".MAIN_DB_PREFIX."livraison as l, ".MAIN_DB_PREFIX."commande as c";
2310 $sql .= " WHERE c.rowid = l.fk_commande";
2311 $resql = $db->query($sql);
2312 if ($resql) {
2313 $i = 0;
2314 $num = $db->num_rows($resql);
2315
2316 if ($num) {
2317 while ($i < $num) {
2318 $obj = $db->fetch_object($resql);
2319
2320 $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_liv (fk_livraison,fk_commande)";
2321 $sql .= " VALUES (".((int) $obj->rowid).", ".((int) $obj->fk_commande).")";
2322 $resql2 = $db->query($sql);
2323
2324 if ($resql2) {
2325 $delivery_date = $db->jdate($obj->delivery_date);
2326
2327 $sqlu = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
2328 $sqlu .= " ref_client = '".$db->escape($obj->ref_client)."'";
2329 $sqlu .= ", date_livraison = '".$db->idate($delivery_date)."'";
2330 $sqlu .= " WHERE rowid = ".((int) $obj->rowid);
2331 $resql3 = $db->query($sqlu);
2332 if (!$resql3) {
2333 $error++;
2334 dol_print_error($db);
2335 }
2336 } else {
2337 $error++;
2338 dol_print_error($db);
2339 }
2340 print '. ';
2341 $i++;
2342 }
2343 }
2344
2345 if ($error == 0) {
2346 $db->commit();
2347 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraison DROP COLUMN fk_commande";
2348 print $langs->trans('FieldRenamed')."<br>\n";
2349 $db->query($sql);
2350 } else {
2351 $db->rollback();
2352 }
2353 } else {
2354 dol_print_error($db);
2355 $db->rollback();
2356 }
2357 } else {
2358 print $langs->trans('AlreadyDone')."<br>\n";
2359 }
2360 print '</td></tr>';
2361}
2362
2371function migrate_detail_livraison($db, $langs, $conf)
2372{
2373 dolibarr_install_syslog("upgrade2::migrate_detail_livraison");
2374
2375 print '<tr><td colspan="4">';
2376
2377 print '<br>';
2378 print '<b>'.$langs->trans('MigrationDeliveryDetail')."</b><br>\n";
2379
2380 // This is done if field fk_commande_ligne exists.
2381 // If not this means migration was already done.
2382 $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraisondet", "fk_commande_ligne");
2383 $obj = $db->fetch_object($result);
2384 if ($obj) {
2385 $error = 0;
2386
2387 $db->begin();
2388
2389 $sql = "SELECT cd.rowid, cd.fk_product, cd.description, cd.subprice, cd.total_ht";
2390 $sql .= ", ld.fk_livraison";
2391 $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."livraisondet as ld";
2392 $sql .= " WHERE ld.fk_commande_ligne = cd.rowid";
2393 $resql = $db->query($sql);
2394 if ($resql) {
2395 $i = 0;
2396 $num = $db->num_rows($resql);
2397
2398 if ($num) {
2399 while ($i < $num) {
2400 $obj = $db->fetch_object($resql);
2401
2402 $sql = "UPDATE ".MAIN_DB_PREFIX."livraisondet SET";
2403 $sql .= " fk_product = ".((int) $obj->fk_product);
2404 $sql .= ",description = '".$db->escape($obj->description)."'";
2405 $sql .= ",subprice = ".price2num($obj->subprice);
2406 $sql .= ",total_ht = ".price2num($obj->total_ht);
2407 $sql .= " WHERE fk_commande_ligne = ".((int) $obj->rowid);
2408 $resql2 = $db->query($sql);
2409
2410 if ($resql2) {
2411 $sql = "SELECT total_ht";
2412 $sql .= " FROM ".MAIN_DB_PREFIX."livraison";
2413 $sql .= " WHERE rowid = ".((int) $obj->fk_livraison);
2414 $resql3 = $db->query($sql);
2415
2416 if ($resql3) {
2417 $obju = $db->fetch_object($resql3);
2418 $total_ht = $obju->total_ht + $obj->total_ht;
2419
2420 $sqlu = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
2421 $sqlu .= " total_ht = ".price2num($total_ht, 'MT');
2422 $sqlu .= " WHERE rowid = ".((int) $obj->fk_livraison);
2423 $resql4 = $db->query($sqlu);
2424 if (!$resql4) {
2425 $error++;
2426 dol_print_error($db);
2427 }
2428 } else {
2429 $error++;
2430 dol_print_error($db);
2431 }
2432 } else {
2433 $error++;
2434 dol_print_error($db);
2435 }
2436 print '. ';
2437 $i++;
2438 }
2439 }
2440
2441 if ($error == 0) {
2442 $db->commit();
2443 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraisondet CHANGE fk_commande_ligne fk_origin_line integer";
2444 print $langs->trans('FieldRenamed')."<br>\n";
2445 $db->query($sql);
2446 } else {
2447 $db->rollback();
2448 }
2449 } else {
2450 dol_print_error($db);
2451 $db->rollback();
2452 }
2453 } else {
2454 $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraisondet", "fk_origin_line");
2455 $obj = $db->fetch_object($result);
2456 if (!$obj) {
2457 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraisondet ADD COLUMN fk_origin_line integer after fk_livraison";
2458 $db->query($sql);
2459 }
2460 print $langs->trans('AlreadyDone')."<br>\n";
2461 }
2462 print '</td></tr>';
2463}
2464
2473function migrate_stocks($db, $langs, $conf)
2474{
2475 dolibarr_install_syslog("upgrade2::migrate_stocks");
2476
2477 print '<tr><td colspan="4">';
2478
2479 print '<br>';
2480 print '<b>'.$langs->trans('MigrationStockDetail')."</b><br>\n";
2481
2482 $error = 0;
2483
2484 $db->begin();
2485
2486 $sql = "SELECT SUM(reel) as total, fk_product";
2487 $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
2488 $sql .= " GROUP BY fk_product";
2489 $resql = $db->query($sql);
2490 if ($resql) {
2491 $i = 0;
2492 $num = $db->num_rows($resql);
2493
2494 if ($num) {
2495 while ($i < $num) {
2496 $obj = $db->fetch_object($resql);
2497
2498 $sql = "UPDATE ".MAIN_DB_PREFIX."product SET";
2499 $sql .= " stock = ".price2num($obj->total, 'MS');
2500 $sql .= " WHERE rowid = ".((int) $obj->fk_product);
2501
2502 $resql2 = $db->query($sql);
2503 if ($resql2) {
2504 } else {
2505 $error++;
2506 dol_print_error($db);
2507 }
2508 print '. ';
2509 $i++;
2510 }
2511 }
2512
2513 if ($error == 0) {
2514 $db->commit();
2515 } else {
2516 $db->rollback();
2517 }
2518 } else {
2519 dol_print_error($db);
2520 $db->rollback();
2521 }
2522
2523 print '</td></tr>';
2524}
2525
2535function migrate_menus($db, $langs, $conf)
2536{
2537 dolibarr_install_syslog("upgrade2::migrate_menus");
2538
2539 print '<tr><td colspan="4">';
2540
2541 print '<br>';
2542 print '<b>'.$langs->trans('MigrationMenusDetail')."</b><br>\n";
2543
2544 $error = 0;
2545
2546 if ($db->DDLInfoTable(MAIN_DB_PREFIX."menu_constraint")) {
2547 $db->begin();
2548
2549 $sql = "SELECT m.rowid, mc.action";
2550 $sql .= " FROM ".MAIN_DB_PREFIX."menu_constraint as mc, ".MAIN_DB_PREFIX."menu_const as md, ".MAIN_DB_PREFIX."menu as m";
2551 $sql .= " WHERE md.fk_menu = m.rowid AND md.fk_constraint = mc.rowid";
2552 $sql .= " AND m.enabled = '1'";
2553 $resql = $db->query($sql);
2554 if ($resql) {
2555 $i = 0;
2556 $num = $db->num_rows($resql);
2557 if ($num) {
2558 while ($i < $num) {
2559 $obj = $db->fetch_object($resql);
2560
2561 $sql = "UPDATE ".MAIN_DB_PREFIX."menu SET";
2562 $sql .= " enabled = '".$db->escape($obj->action)."'";
2563 $sql .= " WHERE rowid = ".((int) $obj->rowid);
2564 $sql .= " AND enabled = '1'";
2565
2566 $resql2 = $db->query($sql);
2567 if ($resql2) {
2568 } else {
2569 $error++;
2570 dol_print_error($db);
2571 }
2572 print '. ';
2573 $i++;
2574 }
2575 }
2576
2577 if ($error == 0) {
2578 $db->commit();
2579 } else {
2580 $db->rollback();
2581 }
2582 } else {
2583 dol_print_error($db);
2584 $db->rollback();
2585 }
2586 } else {
2587 print $langs->trans('AlreadyDone')."<br>\n";
2588 }
2589
2590 print '</td></tr>';
2591}
2592
2603{
2604 dolibarr_install_syslog("upgrade2::migrate_commande_deliveryaddress");
2605
2606 print '<tr><td colspan="4">';
2607
2608 print '<br>';
2609 print '<b>'.$langs->trans('MigrationDeliveryAddress')."</b><br>\n";
2610
2611 $error = 0;
2612
2613 if ($db->DDLInfoTable(MAIN_DB_PREFIX."co_exp")) {
2614 $db->begin();
2615
2616 $sql = "SELECT c.fk_adresse_livraison, ce.fk_expedition";
2617 $sql .= " FROM ".MAIN_DB_PREFIX."commande as c";
2618 $sql .= ", ".MAIN_DB_PREFIX."co_exp as ce";
2619 $sql .= " WHERE c.rowid = ce.fk_commande";
2620 $sql .= " AND c.fk_adresse_livraison IS NOT NULL AND c.fk_adresse_livraison != 0";
2621
2622 $resql = $db->query($sql);
2623 if ($resql) {
2624 $i = 0;
2625 $num = $db->num_rows($resql);
2626
2627 if ($num) {
2628 while ($i < $num) {
2629 $obj = $db->fetch_object($resql);
2630
2631 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
2632 $sql .= " fk_adresse_livraison = '".$db->escape($obj->fk_adresse_livraison)."'";
2633 $sql .= " WHERE rowid = ".((int) $obj->fk_expedition);
2634
2635 $resql2 = $db->query($sql);
2636 if (!$resql2) {
2637 $error++;
2638 dol_print_error($db);
2639 }
2640 print '. ';
2641 $i++;
2642 }
2643 } else {
2644 print $langs->trans('AlreadyDone')."<br>\n";
2645 }
2646
2647 if ($error == 0) {
2648 $db->commit();
2649 } else {
2650 $db->rollback();
2651 }
2652 } else {
2653 dol_print_error($db);
2654 $db->rollback();
2655 }
2656 } else {
2657 print $langs->trans('AlreadyDone')."<br>\n";
2658 }
2659
2660 print '</td></tr>';
2661}
2662
2673{
2674 dolibarr_install_syslog("upgrade2::migrate_restore_missing_links");
2675
2676 if (($db->type == 'mysql' || $db->type == 'mysqli')) {
2677 if (versioncompare($db->getVersionArray(), array(4, 0)) < 0) {
2678 dolibarr_install_syslog("upgrade2::migrate_restore_missing_links Version of database too old to make this migrate action");
2679 return 0;
2680 }
2681 }
2682 print '<tr><td colspan="4">';
2683
2684 print '<br>';
2685 print '<b>'.$langs->trans('MigrationFixData')."</b> (1)<br>\n";
2686
2687 $error = 0;
2688
2689
2690 // Restore missing link for this cross foreign key (link 1 <=> 1). Direction 1.
2691 $table1 = 'facturedet';
2692 $field1 = 'fk_remise_except';
2693 $table2 = 'societe_remise_except';
2694 $field2 = 'fk_facture_line';
2695
2696 $db->begin();
2697
2698 $sql = "SELECT t1.rowid, t1.".$db->sanitize($field1)." as field";
2699 $sql .= " FROM ".MAIN_DB_PREFIX.$db->sanitize($table1)." as t1";
2700 $sql .= " WHERE t1.".$db->sanitize($field1)." IS NOT NULL AND t1.".$db->sanitize($field1)." NOT IN";
2701 $sql .= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$db->sanitize($table2)." as t2";
2702 $sql .= " WHERE t1.rowid = t2.".$db->sanitize($field2).")";
2703
2704 dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 1");
2705 $resql = $db->query($sql);
2706 if ($resql) {
2707 $i = 0;
2708 $num = $db->num_rows($resql);
2709
2710 if ($num) {
2711 while ($i < $num) {
2712 $obj = $db->fetch_object($resql);
2713
2714 print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.<br>';
2715
2716 $sql = "UPDATE ".MAIN_DB_PREFIX.$db->sanitize($table2)." SET";
2717 $sql .= " ".$db->sanitize($field2)." = '".$db->escape($obj->rowid)."'";
2718 $sql .= " WHERE rowid = ".((int) $obj->field);
2719
2720 $resql2 = $db->query($sql);
2721 if (!$resql2) {
2722 $error++;
2723 dol_print_error($db);
2724 }
2725 //print '. ';
2726 $i++;
2727 }
2728 } else {
2729 print $langs->trans('AlreadyDone')."<br>\n";
2730 }
2731
2732 if ($error == 0) {
2733 $db->commit();
2734 } else {
2735 $db->rollback();
2736 }
2737 } else {
2738 dol_print_error($db);
2739 $db->rollback();
2740 }
2741
2742 print '</td></tr>';
2743
2744
2745 print '<tr><td colspan="4">';
2746
2747 print '<br>';
2748 print '<b>'.$langs->trans('MigrationFixData')."</b> (2)<br>\n";
2749
2750 // Restore missing link for this cross foreign key (link 1 <=> 1). Direction 2.
2751 $table2 = 'facturedet';
2752 $field2 = 'fk_remise_except';
2753 $table1 = 'societe_remise_except';
2754 $field1 = 'fk_facture_line';
2755
2756 $db->begin();
2757
2758 $sql = "SELECT t1.rowid, t1.".$db->sanitize($field1)." as field";
2759 $sql .= " FROM ".MAIN_DB_PREFIX.$db->sanitize($table1)." as t1";
2760 $sql .= " WHERE t1.".$db->sanitize($field1)." IS NOT NULL AND t1.".$db->sanitize($field1)." NOT IN";
2761 $sql .= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$db->sanitize($table2)." as t2";
2762 $sql .= " WHERE t1.rowid = t2.".$db->sanitize($field2).")";
2763
2764 dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 2");
2765 $resql = $db->query($sql);
2766 if ($resql) {
2767 $i = 0;
2768 $num = $db->num_rows($resql);
2769
2770 if ($num) {
2771 while ($i < $num) {
2772 $obj = $db->fetch_object($resql);
2773
2774 print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.<br>';
2775
2776 $sql = "UPDATE ".MAIN_DB_PREFIX.$db->sanitize($table2)." SET";
2777 $sql .= " ".$db->sanitize($field2)." = '".$db->escape($obj->rowid)."'";
2778 $sql .= " WHERE rowid = ".((int) $obj->field);
2779
2780 $resql2 = $db->query($sql);
2781 if (!$resql2) {
2782 $error++;
2783 dol_print_error($db);
2784 }
2785 //print '. ';
2786 $i++;
2787 }
2788 } else {
2789 print $langs->trans('AlreadyDone')."<br>\n";
2790 }
2791
2792 if ($error == 0) {
2793 $db->commit();
2794 } else {
2795 $db->rollback();
2796 }
2797 } else {
2798 dol_print_error($db);
2799 $db->rollback();
2800 }
2801
2802 print '</td></tr>';
2803
2804 return ($error ? -1 : 1);
2805}
2806
2815function migrate_project_user_resp($db, $langs, $conf)
2816{
2817 dolibarr_install_syslog("upgrade2::migrate_project_user_resp");
2818
2819 print '<tr><td colspan="4">';
2820
2821 print '<br>';
2822 print '<b>'.$langs->trans('MigrationProjectUserResp')."</b><br>\n";
2823
2824 $result = $db->DDLDescTable(MAIN_DB_PREFIX."projet", "fk_user_resp");
2825 $obj = $db->fetch_object($result);
2826 if ($obj) {
2827 $error = 0;
2828
2829 $db->begin();
2830
2831 $sql = "SELECT rowid, fk_user_resp FROM ".MAIN_DB_PREFIX."projet";
2832 $resql = $db->query($sql);
2833 if ($resql) {
2834 $i = 0;
2835 $num = $db->num_rows($resql);
2836
2837 if ($num) {
2838 while ($i < $num) {
2839 $obj = $db->fetch_object($resql);
2840
2841 $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact (";
2842 $sql2 .= "datecreate";
2843 $sql2 .= ", statut";
2844 $sql2 .= ", element_id";
2845 $sql2 .= ", fk_c_type_contact";
2846 $sql2 .= ", fk_socpeople";
2847 $sql2 .= ") VALUES (";
2848 $sql2 .= "'".$db->idate(dol_now())."'";
2849 $sql2 .= ", '4'";
2850 $sql2 .= ", ".((int) $obj->rowid);
2851 $sql2 .= ", '160'";
2852 $sql2 .= ", ".((int) $obj->fk_user_resp);
2853 $sql2 .= ")";
2854
2855 if ($obj->fk_user_resp > 0) {
2856 $resql2 = $db->query($sql2);
2857 if (!$resql2) {
2858 $error++;
2859 dol_print_error($db);
2860 }
2861 }
2862 print '. ';
2863
2864 $i++;
2865 }
2866 }
2867
2868 if ($error == 0) {
2869 $sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."projet DROP COLUMN fk_user_resp";
2870 if ($db->query($sqlDrop)) {
2871 $db->commit();
2872 } else {
2873 $db->rollback();
2874 }
2875 } else {
2876 $db->rollback();
2877 }
2878 } else {
2879 dol_print_error($db);
2880 $db->rollback();
2881 }
2882 } else {
2883 print $langs->trans('AlreadyDone')."<br>\n";
2884 }
2885 print '</td></tr>';
2886}
2887
2897{
2898 dolibarr_install_syslog("upgrade2::migrate_project_task_actors");
2899
2900 print '<tr><td colspan="4">';
2901
2902 print '<br>';
2903 print '<b>'.$langs->trans('MigrationProjectTaskActors')."</b><br>\n";
2904
2905 if ($db->DDLInfoTable(MAIN_DB_PREFIX."projet_task_actors")) {
2906 $error = 0;
2907
2908 $db->begin();
2909
2910 $sql = "SELECT fk_projet_task as fk_project_task, fk_user FROM ".MAIN_DB_PREFIX."projet_task_actors";
2911 $resql = $db->query($sql);
2912 if ($resql) {
2913 $i = 0;
2914 $num = $db->num_rows($resql);
2915
2916 if ($num) {
2917 while ($i < $num) {
2918 $obj = $db->fetch_object($resql);
2919
2920 $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact (";
2921 $sql2 .= "datecreate";
2922 $sql2 .= ", statut";
2923 $sql2 .= ", element_id";
2924 $sql2 .= ", fk_c_type_contact";
2925 $sql2 .= ", fk_socpeople";
2926 $sql2 .= ") VALUES (";
2927 $sql2 .= "'".$db->idate(dol_now())."'";
2928 $sql2 .= ", '4'";
2929 $sql2 .= ", ".((int) $obj->fk_project_task);
2930 $sql2 .= ", '180'";
2931 $sql2 .= ", ".((int) $obj->fk_user);
2932 $sql2 .= ")";
2933
2934 $resql2 = $db->query($sql2);
2935
2936 if (!$resql2) {
2937 $error++;
2938 dol_print_error($db);
2939 }
2940 print '. ';
2941 $i++;
2942 }
2943 }
2944
2945 if ($error == 0) {
2946 $sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX."projet_task_actors";
2947 if ($db->query($sqlDrop)) {
2948 $db->commit();
2949 } else {
2950 $db->rollback();
2951 }
2952 } else {
2953 $db->rollback();
2954 }
2955 } else {
2956 dol_print_error($db);
2957 $db->rollback();
2958 }
2959 } else {
2960 print $langs->trans('AlreadyDone')."<br>\n";
2961 }
2962 print '</td></tr>';
2963}
2964
2978function migrate_relationship_tables($db, $langs, $conf, $table, $fk_source, $sourcetype, $fk_target, $targettype)
2979{
2980 print '<tr><td colspan="4">';
2981
2982 print '<br>';
2983 print '<b>'.$langs->trans('MigrationRelationshipTables', MAIN_DB_PREFIX.$table)."</b><br>\n";
2984
2985 $error = 0;
2986
2987 if ($db->DDLInfoTable(MAIN_DB_PREFIX.$table)) {
2988 dolibarr_install_syslog("upgrade2::migrate_relationship_tables table = ".MAIN_DB_PREFIX.$table);
2989
2990 $db->begin();
2991
2992 $sqlSelect = "SELECT ".$db->sanitize($fk_source).", ".$db->sanitize($fk_target);
2993 $sqlSelect .= " FROM ".MAIN_DB_PREFIX.$table;
2994
2995 $resql = $db->query($sqlSelect);
2996 if ($resql) {
2997 $i = 0;
2998 $num = $db->num_rows($resql);
2999
3000 if ($num) {
3001 while ($i < $num) {
3002 $obj = $db->fetch_object($resql);
3003
3004 $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
3005 $sqlInsert .= "fk_source";
3006 $sqlInsert .= ", sourcetype";
3007 $sqlInsert .= ", fk_target";
3008 $sqlInsert .= ", targettype";
3009 $sqlInsert .= ") VALUES (";
3010 $sqlInsert .= ((int) $obj->$fk_source);
3011 $sqlInsert .= ", '".$db->escape($sourcetype)."'";
3012 $sqlInsert .= ", ".((int) $obj->$fk_target);
3013 $sqlInsert .= ", '".$db->escape($targettype)."'";
3014 $sqlInsert .= ")";
3015
3016 $result = $db->query($sqlInsert);
3017 if (!$result) {
3018 $error++;
3019 dol_print_error($db);
3020 }
3021 print '. ';
3022 $i++;
3023 }
3024 } else {
3025 print $langs->trans('AlreadyDone')."<br>\n";
3026 }
3027
3028 if ($error == 0) {
3029 $sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX.$db->sanitize($table);
3030 if ($db->query($sqlDrop)) {
3031 $db->commit();
3032 } else {
3033 $db->rollback();
3034 }
3035 } else {
3036 $db->rollback();
3037 }
3038 } else {
3039 dol_print_error($db);
3040 $db->rollback();
3041 }
3042 } else {
3043 print $langs->trans('AlreadyDone')."<br>\n";
3044 }
3045
3046 print '</td></tr>';
3047}
3048
3057function migrate_element_time($db, $langs, $conf)
3058{
3059 dolibarr_install_syslog("upgrade2::migrate_element_time");
3060
3061 print '<tr><td colspan="4">';
3062
3063 print '<br>';
3064 print '<b>'.$langs->trans('MigrationProjectTaskTime')."</b><br>\n";
3065
3066 $error = 0;
3067
3068 $db->begin();
3069
3070 $sql = "SELECT rowid, fk_element, element_duration";
3071 $sql .= " FROM ".MAIN_DB_PREFIX."element_time";
3072 $resql = $db->query($sql);
3073 if ($resql) {
3074 $i = 0;
3075 $num = $db->num_rows($resql);
3076
3077 if ($num) {
3078 $totaltime = array();
3079 $oldtime = 0;
3080
3081 while ($i < $num) {
3082 $obj = $db->fetch_object($resql);
3083
3084 if ($obj->element_duration > 0) {
3085 // convert to second
3086 // only for int time and float time ex: 1.75 for 1h45
3087 list($hour, $min) = explode('.', $obj->element_duration);
3088 $hour = (int) $hour * 60 * 60;
3089 $min = (int) ((float) ('.'.$min)) * 3600;
3090 $newtime = $hour + $min;
3091
3092 $sql2 = "UPDATE ".MAIN_DB_PREFIX."element_time SET";
3093 $sql2 .= " element_duration = ".((int) $newtime);
3094 $sql2 .= " WHERE rowid = ".((int) $obj->rowid);
3095
3096 $resql2 = $db->query($sql2);
3097 if (!$resql2) {
3098 $error++;
3099 dol_print_error($db);
3100 }
3101 print '. ';
3102 $oldtime++;
3103 if (!empty($totaltime[$obj->fk_element])) {
3104 $totaltime[$obj->fk_element] += $newtime;
3105 } else {
3106 $totaltime[$obj->fk_element] = $newtime;
3107 }
3108 } else {
3109 if (!empty($totaltime[$obj->fk_element])) {
3110 $totaltime[$obj->fk_element] += $obj->element_duration;
3111 } else {
3112 $totaltime[$obj->fk_element] = $obj->element_duration;
3113 }
3114 }
3115
3116 $i++;
3117 }
3118
3119 if ($error == 0) {
3120 if ($oldtime > 0) {
3121 foreach ($totaltime as $taskid => $total_duration) {
3122 $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET";
3123 $sql .= " duration_effective = ".((int) $total_duration);
3124 $sql .= " WHERE rowid = ".((int) $taskid);
3125
3126 $resql = $db->query($sql);
3127 if (!$resql) {
3128 $error++;
3129 dol_print_error($db);
3130 }
3131 }
3132 } else {
3133 print $langs->trans('AlreadyDone')."<br>\n";
3134 }
3135 } else {
3136 dol_print_error($db);
3137 }
3138 } else {
3139 print $langs->trans('AlreadyDone')."<br>\n";
3140 }
3141 } else {
3142 dol_print_error($db);
3143 }
3144
3145 if ($error == 0) {
3146 $db->commit();
3147 } else {
3148 $db->rollback();
3149 }
3150
3151 print '</td></tr>';
3152}
3153
3163{
3164 print '<tr><td colspan="4">';
3165
3166 print '<br>';
3167 print '<b>'.$langs->trans('MigrationCustomerOrderShipping')."</b><br>\n";
3168
3169 $error = 0;
3170
3171 $result1 = $db->DDLDescTable(MAIN_DB_PREFIX."expedition", "ref_customer");
3172 $result2 = $db->DDLDescTable(MAIN_DB_PREFIX."expedition", "date_delivery");
3173 $obj1 = $db->fetch_object($result1);
3174 $obj2 = $db->fetch_object($result2);
3175 if (!$obj1 && !$obj2) {
3176 dolibarr_install_syslog("upgrade2::migrate_customerorder_shipping");
3177
3178 $db->begin();
3179
3180 $sqlAdd1 = "ALTER TABLE ".MAIN_DB_PREFIX."expedition ADD COLUMN ref_customer varchar(30) AFTER entity";
3181 $sqlAdd2 = "ALTER TABLE ".MAIN_DB_PREFIX."expedition ADD COLUMN date_delivery date DEFAULT NULL AFTER date_expedition";
3182
3183 if ($db->query($sqlAdd1) && $db->query($sqlAdd2)) {
3184 $sqlSelect = "SELECT e.rowid as shipping_id, c.ref_client, c.date_livraison as delivery_date";
3185 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."expedition as e";
3186 $sqlSelect .= ", ".MAIN_DB_PREFIX."element_element as el";
3187 $sqlSelect .= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON c.rowid = el.fk_source AND el.sourcetype = 'commande'";
3188 $sqlSelect .= " WHERE e.rowid = el.fk_target";
3189 $sqlSelect .= " AND el.targettype = 'shipping'";
3190
3191 $resql = $db->query($sqlSelect);
3192 if ($resql) {
3193 $i = 0;
3194 $num = $db->num_rows($resql);
3195
3196 if ($num) {
3197 while ($i < $num) {
3198 $obj = $db->fetch_object($resql);
3199
3200 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
3201 $sqlUpdate .= " ref_customer = '".$db->escape($obj->ref_client)."'";
3202 $sqlUpdate .= ", date_delivery = '".$db->escape($obj->delivery_date ? $obj->delivery_date : 'null')."'";
3203 $sqlUpdate .= " WHERE rowid = ".((int) $obj->shipping_id);
3204
3205 $result = $db->query($sqlUpdate);
3206 if (!$result) {
3207 $error++;
3208 dol_print_error($db);
3209 }
3210 print '. ';
3211 $i++;
3212 }
3213 } else {
3214 print $langs->trans('AlreadyDone')."<br>\n";
3215 }
3216
3217 if ($error == 0) {
3218 $db->commit();
3219 } else {
3220 dol_print_error($db);
3221 $db->rollback();
3222 }
3223 } else {
3224 dol_print_error($db);
3225 $db->rollback();
3226 }
3227 } else {
3228 dol_print_error($db);
3229 $db->rollback();
3230 }
3231 } else {
3232 print $langs->trans('AlreadyDone')."<br>\n";
3233 }
3234
3235 print '</td></tr>';
3236}
3237
3246function migrate_shipping_delivery($db, $langs, $conf)
3247{
3248 print '<tr><td colspan="4">';
3249
3250 print '<br>';
3251 print '<b>'.$langs->trans('MigrationShippingDelivery')."</b><br>\n";
3252
3253 $error = 0;
3254
3255 $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraison", "fk_expedition");
3256 $obj = $db->fetch_object($result);
3257 if ($obj) {
3258 dolibarr_install_syslog("upgrade2::migrate_shipping_delivery");
3259
3260 $db->begin();
3261
3262 $sqlSelect = "SELECT rowid, fk_expedition";
3263 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."livraison";
3264 $sqlSelect .= " WHERE fk_expedition is not null";
3265
3266 $resql = $db->query($sqlSelect);
3267 if ($resql) {
3268 $i = 0;
3269 $num = $db->num_rows($resql);
3270
3271 if ($num) {
3272 while ($i < $num) {
3273 $obj = $db->fetch_object($resql);
3274
3275 $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
3276 $sqlInsert .= "fk_source";
3277 $sqlInsert .= ", sourcetype";
3278 $sqlInsert .= ", fk_target";
3279 $sqlInsert .= ", targettype";
3280 $sqlInsert .= ") VALUES (";
3281 $sqlInsert .= ((int) $obj->fk_expedition);
3282 $sqlInsert .= ", 'shipping'";
3283 $sqlInsert .= ", ".((int) $obj->rowid);
3284 $sqlInsert .= ", 'delivery'";
3285 $sqlInsert .= ")";
3286
3287 $result = $db->query($sqlInsert);
3288 if ($result) {
3289 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET fk_expedition = NULL";
3290 $sqlUpdate .= " WHERE rowid = ".((int) $obj->rowid);
3291
3292 $result = $db->query($sqlUpdate);
3293 if (!$result) {
3294 $error++;
3295 dol_print_error($db);
3296 }
3297 print '. ';
3298 } else {
3299 $error++;
3300 dol_print_error($db);
3301 }
3302 $i++;
3303 }
3304 } else {
3305 print $langs->trans('AlreadyDone')."<br>\n";
3306 }
3307
3308 if ($error == 0) {
3309 $sqlDelete = "DELETE FROM ".MAIN_DB_PREFIX."element_element WHERE sourcetype = 'commande' AND targettype = 'delivery'";
3310 $db->query($sqlDelete);
3311
3312 $db->commit();
3313
3314 // DDL commands must not be inside a transaction
3315 $sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."livraison DROP COLUMN fk_expedition";
3316 $db->query($sqlDrop);
3317 } else {
3318 dol_print_error($db);
3319 $db->rollback();
3320 }
3321 } else {
3322 dol_print_error($db);
3323 $db->rollback();
3324 }
3325 } else {
3326 print $langs->trans('AlreadyDone')."<br>\n";
3327 }
3328
3329 print '</td></tr>';
3330}
3331
3341function migrate_shipping_delivery2($db, $langs, $conf)
3342{
3343 print '<tr><td colspan="4">';
3344
3345 print '<br>';
3346 print '<b>'.$langs->trans('MigrationShippingDelivery2')."</b><br>\n";
3347
3348 $error = 0;
3349
3350 dolibarr_install_syslog("upgrade2::migrate_shipping_delivery2");
3351
3352 $db->begin();
3353
3354 $sqlSelect = "SELECT l.rowid as delivery_id, e.ref_customer, e.date_delivery";
3355 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."livraison as l,";
3356 $sqlSelect .= " ".MAIN_DB_PREFIX."element_element as el,";
3357 $sqlSelect .= " ".MAIN_DB_PREFIX."expedition as e";
3358 $sqlSelect .= " WHERE l.rowid = el.fk_target";
3359 $sqlSelect .= " AND el.targettype = 'delivery'";
3360 $sqlSelect .= " AND e.rowid = el.fk_source AND el.sourcetype = 'shipping'";
3361 $sqlSelect .= " AND (e.ref_customer IS NOT NULL OR e.date_delivery IS NOT NULL)"; // Useless to process this record if both are null
3362 // Add condition to know if we never migrate this record
3363 $sqlSelect .= " AND (l.ref_customer IS NULL".($db->type != 'pgsql' ? " or l.ref_customer = ''" : "").")";
3364 $sqlSelect .= " AND (l.date_delivery IS NULL".($db->type != 'pgsql' ? " or l.date_delivery = ''" : "").")";
3365
3366 $resql = $db->query($sqlSelect);
3367 if ($resql) {
3368 $i = 0;
3369 $num = $db->num_rows($resql);
3370
3371 if ($num) {
3372 while ($i < $num) {
3373 $obj = $db->fetch_object($resql);
3374
3375 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
3376 $sqlUpdate .= " ref_customer = '".$db->escape($obj->ref_customer)."',";
3377 $sqlUpdate .= " date_delivery = ".($obj->date_delivery ? "'".$db->escape($obj->date_delivery)."'" : 'null');
3378 $sqlUpdate .= " WHERE rowid = ".((int) $obj->delivery_id);
3379
3380 $result = $db->query($sqlUpdate);
3381 if (!$result) {
3382 $error++;
3383 dol_print_error($db);
3384 }
3385 print '. ';
3386 $i++;
3387 }
3388 } else {
3389 print $langs->trans('AlreadyDone')."<br>\n";
3390 }
3391
3392 if ($error == 0) {
3393 $db->commit();
3394 } else {
3395 dol_print_error($db);
3396 $db->rollback();
3397 }
3398 } else {
3399 dol_print_error($db);
3400 $db->rollback();
3401 }
3402
3403 print '</td></tr>';
3404}
3405
3414function migrate_actioncomm_element($db, $langs, $conf)
3415{
3416 print '<tr><td colspan="4">';
3417
3418 print '<br>';
3419 print '<b>'.$langs->trans('MigrationActioncommElement')."</b><br>\n";
3420
3421 $elements = array(
3422 'propal' => 'propalrowid',
3423 'order' => 'fk_commande',
3424 'invoice' => 'fk_facture',
3425 'contract' => 'fk_contract',
3426 'order_supplier' => 'fk_supplier_order',
3427 'invoice_supplier' => 'fk_supplier_invoice'
3428 );
3429
3430 foreach ($elements as $type => $field) {
3431 $result = $db->DDLDescTable(MAIN_DB_PREFIX."actioncomm", $field);
3432 $obj = $db->fetch_object($result);
3433 if ($obj) {
3434 dolibarr_install_syslog("upgrade2::migrate_actioncomm_element field=".$field);
3435
3436 $db->begin();
3437
3438 $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm SET ";
3439 $sql .= "fk_element = ".$db->sanitize($field).", elementtype = '".$db->escape($type)."'";
3440 $sql .= " WHERE ".$db->sanitize($field)." IS NOT NULL";
3441 $sql .= " AND fk_element IS NULL";
3442 $sql .= " AND elementtype IS NULL";
3443
3444 $resql = $db->query($sql);
3445 if ($resql) {
3446 $db->commit();
3447
3448 // DDL commands must not be inside a transaction
3449 // We will drop at next version because a migrate should be runnable several times if it fails.
3450 //$sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."actioncomm DROP COLUMN ".$field;
3451 //$db->query($sqlDrop);
3452 //print '. ';
3453 } else {
3454 dol_print_error($db);
3455 $db->rollback();
3456 }
3457 } else {
3458 print $langs->trans('AlreadyDone')."<br>\n";
3459 }
3460 }
3461
3462 print '</td></tr>';
3463}
3464
3473function migrate_mode_reglement($db, $langs, $conf)
3474{
3475 print '<tr><td colspan="4">';
3476
3477 print '<br>';
3478 print '<b>'.$langs->trans('MigrationPaymentMode')."</b><br>\n";
3479
3480 $elements = array(
3481 'old_id' => array(5, 8, 9, 10, 11),
3482 'new_id' => array(50, 51, 52, 53, 54),
3483 'code' => array('VAD', 'TRA', 'LCR', 'FAC', 'PRO'),
3484 'tables' => array('commande_fournisseur', 'commande', 'facture_rec', 'facture', 'propal')
3485 );
3486 $count = 0;
3487
3488 foreach ($elements['old_id'] as $key => $old_id) {
3489 $error = 0;
3490
3491 dolibarr_install_syslog("upgrade2::migrate_mode_reglement code=".$elements['code'][$key]);
3492
3493 $sqlSelect = "SELECT id";
3494 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."c_paiement";
3495 $sqlSelect .= " WHERE id = ".((int) $old_id);
3496 $sqlSelect .= " AND code = '".$db->escape($elements['code'][$key])."'";
3497
3498 $resql = $db->query($sqlSelect);
3499 if ($resql) {
3500 $num = $db->num_rows($resql);
3501 if ($num) {
3502 $count++;
3503
3504 $db->begin();
3505
3506 $sqla = "UPDATE ".MAIN_DB_PREFIX."paiement SET";
3507 $sqla .= " fk_paiement = ".((int) $elements['new_id'][$key]);
3508 $sqla .= " WHERE fk_paiement = ".((int) $old_id);
3509 $sqla .= " AND fk_paiement IN (SELECT id FROM ".MAIN_DB_PREFIX."c_paiement WHERE id = ".((int) $old_id)." AND code = '".$db->escape($elements['code'][$key])."')";
3510 $resqla = $db->query($sqla);
3511
3512 $sql = "UPDATE ".MAIN_DB_PREFIX."c_paiement SET";
3513 $sql .= " id = ".((int) $elements['new_id'][$key]);
3514 $sql .= " WHERE id = ".((int) $old_id);
3515 $sql .= " AND code = '".$db->escape($elements['code'][$key])."'";
3516 $resql = $db->query($sql);
3517
3518 if ($resqla && $resql) {
3519 foreach ($elements['tables'] as $table) {
3520 $sql = "UPDATE ".MAIN_DB_PREFIX.$db->sanitize($table)." SET ";
3521 $sql .= "fk_mode_reglement = ".((int) $elements['new_id'][$key]);
3522 $sql .= " WHERE fk_mode_reglement = ".((int) $old_id);
3523
3524 $resql = $db->query($sql);
3525 if (!$resql) {
3526 dol_print_error($db);
3527 $error++;
3528 }
3529 print '. ';
3530 }
3531
3532 if (!$error) {
3533 $db->commit();
3534 } else {
3535 dol_print_error($db);
3536 $db->rollback();
3537 }
3538 } else {
3539 dol_print_error($db);
3540 $db->rollback();
3541 }
3542 }
3543 }
3544 }
3545
3546 if ($count == 0) {
3547 print $langs->trans('AlreadyDone')."<br>\n";
3548 }
3549
3550
3551 print '</td></tr>';
3552}
3553
3554
3563function migrate_clean_association($db, $langs, $conf)
3564{
3565 $result = $db->DDLDescTable(MAIN_DB_PREFIX."categorie_association");
3566 if ($result) { // result defined for version 3.2 or -
3567 $obj = $db->fetch_object($result);
3568 if ($obj) { // It table categorie_association exists
3569 $couples = array();
3570 $children = array();
3571 $sql = "SELECT fk_categorie_mere, fk_categorie_fille";
3572 $sql .= " FROM ".MAIN_DB_PREFIX."categorie_association";
3573 dolibarr_install_syslog("upgrade: search duplicate");
3574 $resql = $db->query($sql);
3575 if ($resql) {
3576 $num = $db->num_rows($resql);
3577 while ($obj = $db->fetch_object($resql)) {
3578 if (!isset($children[$obj->fk_categorie_fille])) { // Only one record as child (a child has only on parent).
3579 if ($obj->fk_categorie_mere != $obj->fk_categorie_fille) {
3580 $children[$obj->fk_categorie_fille] = 1; // Set record for this child
3581 $couples[$obj->fk_categorie_mere.'_'.$obj->fk_categorie_fille] = array('mere' => $obj->fk_categorie_mere, 'fille' => $obj->fk_categorie_fille);
3582 }
3583 }
3584 }
3585
3586 dolibarr_install_syslog("upgrade: result is num=".$num." count(couples)=".count($couples));
3587
3588 // If there is duplicates couples or child with two parents
3589 if (count($couples) > 0 && $num > count($couples)) {
3590 $error = 0;
3591
3592 $db->begin();
3593
3594 // We delete all
3595 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_association";
3596 dolibarr_install_syslog("upgrade: delete association");
3597 $resqld = $db->query($sql);
3598 if ($resqld) {
3599 // And we insert only each record once
3600 foreach ($couples as $key => $val) {
3601 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_association(fk_categorie_mere,fk_categorie_fille)";
3602 $sql .= " VALUES(".((int) $val['mere']).", ".((int) $val['fille']).")";
3603 dolibarr_install_syslog("upgrade: insert association");
3604 $resqli = $db->query($sql);
3605 if (!$resqli) {
3606 $error++;
3607 }
3608 }
3609 }
3610
3611 if (!$error) {
3612 print '<tr><td>'.$langs->trans("MigrationCategorieAssociation").'</td>';
3613 print '<td class="right">'.$langs->trans("RemoveDuplicates").' '.$langs->trans("Success").' ('.$num.'=>'.count($couples).')</td></tr>';
3614 $db->commit();
3615 } else {
3616 print '<tr><td>'.$langs->trans("MigrationCategorieAssociation").'</td>';
3617 print '<td class="right">'.$langs->trans("RemoveDuplicates").' '.$langs->trans("Failed").'</td></tr>';
3618 $db->rollback();
3619 }
3620 }
3621 } else {
3622 print '<tr><td>'.$langs->trans("Error").'</td>';
3623 print '<td class="right"><div class="error">'.$db->lasterror().'</div></td></tr>';
3624 }
3625 }
3626 }
3627}
3628
3629
3639{
3640 print '<tr><td colspan="4">';
3641
3642 print '<br>';
3643 print '<b>'.$langs->trans('MigrationCategorieAssociation')."</b><br>\n";
3644
3645 $error = 0;
3646
3647 if ($db->DDLInfoTable(MAIN_DB_PREFIX."categorie_association")) {
3648 dolibarr_install_syslog("upgrade2::migrate_categorie_association");
3649
3650 $db->begin();
3651
3652 $sqlSelect = "SELECT fk_categorie_mere, fk_categorie_fille";
3653 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."categorie_association";
3654
3655 $resql = $db->query($sqlSelect);
3656 if ($resql) {
3657 $i = 0;
3658 $num = $db->num_rows($resql);
3659
3660 if ($num) {
3661 while ($i < $num) {
3662 $obj = $db->fetch_object($resql);
3663
3664 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."categorie SET ";
3665 $sqlUpdate .= "fk_parent = ".((int) $obj->fk_categorie_mere);
3666 $sqlUpdate .= " WHERE rowid = ".((int) $obj->fk_categorie_fille);
3667
3668 $result = $db->query($sqlUpdate);
3669 if (!$result) {
3670 $error++;
3671 dol_print_error($db);
3672 }
3673 print '. ';
3674 $i++;
3675 }
3676 } else {
3677 print $langs->trans('AlreadyDone')."<br>\n";
3678 }
3679
3680 if (!$error) {
3681 $db->commit();
3682 } else {
3683 $db->rollback();
3684 }
3685 } else {
3686 dol_print_error($db);
3687 $db->rollback();
3688 }
3689 } else {
3690 print $langs->trans('AlreadyDone')."<br>\n";
3691 }
3692
3693 print '</td></tr>';
3694}
3695
3704function migrate_event_assignement($db, $langs, $conf)
3705{
3706 print '<tr><td colspan="4">';
3707
3708 print '<br>';
3709 print '<b>'.$langs->trans('MigrationEvents')."</b><br>\n";
3710
3711 $error = 0;
3712
3713 dolibarr_install_syslog("upgrade2::migrate_event_assignement");
3714
3715 $db->begin();
3716
3717 $sqlSelect = "SELECT a.id, a.fk_user_action";
3718 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
3719 $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";
3720 $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')";
3721 $sqlSelect .= " ORDER BY a.id";
3722 //print $sqlSelect;
3723
3724 $resql = $db->query($sqlSelect);
3725 if ($resql) {
3726 $i = 0;
3727 $num = $db->num_rows($resql);
3728
3729 if ($num) {
3730 while ($i < $num) {
3731 $obj = $db->fetch_object($resql);
3732
3733 $sqlUpdate = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element) ";
3734 $sqlUpdate .= "VALUES(".((int) $obj->id).", 'user', ".((int) $obj->fk_user_action).")";
3735
3736 $result = $db->query($sqlUpdate);
3737 if (!$result) {
3738 $error++;
3739 dol_print_error($db);
3740 }
3741 print '. ';
3742 $i++;
3743 }
3744 } else {
3745 print $langs->trans('AlreadyDone')."<br>\n";
3746 }
3747
3748 if (!$error) {
3749 $db->commit();
3750 } else {
3751 $db->rollback();
3752 }
3753 } else {
3754 dol_print_error($db);
3755 $db->rollback();
3756 }
3757
3758
3759 print '</td></tr>';
3760}
3761
3771{
3772 print '<tr><td colspan="4">';
3773
3774 print '<br>';
3775 print '<b>'.$langs->trans('MigrationEventsContact')."</b><br>\n";
3776
3777 $error = 0;
3778
3779 dolibarr_install_syslog("upgrade2::migrate_event_assignement");
3780
3781 $db->begin();
3782
3783 $sqlSelect = "SELECT a.id, a.fk_contact";
3784 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
3785 $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";
3786 $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')";
3787 $sqlSelect .= " ORDER BY a.id";
3788 //print $sqlSelect;
3789
3790 $resql = $db->query($sqlSelect);
3791 if ($resql) {
3792 $i = 0;
3793 $num = $db->num_rows($resql);
3794
3795 if ($num) {
3796 while ($i < $num) {
3797 $obj = $db->fetch_object($resql);
3798
3799 $sqlUpdate = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element) ";
3800 $sqlUpdate .= "VALUES(".((int) $obj->id).", 'socpeople', ".((int) $obj->fk_contact).")";
3801
3802 $result = $db->query($sqlUpdate);
3803 if (!$result) {
3804 $error++;
3805 dol_print_error($db);
3806 }
3807 print '. ';
3808 $i++;
3809 }
3810 } else {
3811 print $langs->trans('AlreadyDone')."<br>\n";
3812 }
3813
3814 if (!$error) {
3815 $db->commit();
3816 } else {
3817 $db->rollback();
3818 }
3819 } else {
3820 dol_print_error($db);
3821 $db->rollback();
3822 }
3823
3824
3825 print '</td></tr>';
3826}
3827
3828
3837function migrate_reset_blocked_log($db, $langs, $conf)
3838{
3839 global $user;
3840
3841 require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php';
3842
3843 print '<tr><td colspan="4">';
3844
3845 print '<br>';
3846 print '<b>'.$langs->trans('MigrationResetBlockedLog')."</b><br>\n";
3847
3848 $error = 0;
3849
3850 dolibarr_install_syslog("upgrade2::migrate_reset_blocked_log");
3851
3852 $db->begin();
3853
3854 $sqlSelect = "SELECT DISTINCT entity";
3855 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."blockedlog";
3856
3857 //print $sqlSelect;
3858
3859 $resql = $db->query($sqlSelect);
3860 if ($resql) {
3861 $i = 0;
3862 $num = $db->num_rows($resql);
3863
3864 if ($num) {
3865 while ($i < $num) {
3866 $obj = $db->fetch_object($resql);
3867
3868 print 'Process entity '.$obj->entity;
3869
3870 $sqlSearch = "SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."blockedlog WHERE action = 'MODULE_SET' and entity = ".((int) $obj->entity);
3871 $resqlSearch = $db->query($sqlSearch);
3872 if ($resqlSearch) {
3873 $objSearch = $db->fetch_object($resqlSearch);
3874 //var_dump($objSearch);
3875 if ($objSearch && $objSearch->nb == 0) {
3876 print ' - Record for entity must be reset...';
3877
3878 $sqlUpdate = "DELETE FROM ".MAIN_DB_PREFIX."blockedlog";
3879 $sqlUpdate .= " WHERE entity = ".((int) $obj->entity);
3880 $resqlUpdate = $db->query($sqlUpdate);
3881 if (!$resqlUpdate) {
3882 $error++;
3883 dol_print_error($db);
3884 } else {
3885 // Add set line
3886 $object = new stdClass();
3887 $object->id = 0;
3888 $object->element = 'module';
3889 $object->ref = 'systemevent';
3890 $object->entity = $obj->entity;
3891 $object->date = dol_now();
3892
3893 $b = new BlockedLog($db);
3894 $b->setObjectData($object, 'MODULE_SET', 0, $user, 0);
3895
3896 $res = $b->create($user);
3897 if ($res <= 0) {
3898 $error++;
3899 }
3900 }
3901 } else {
3902 print ' - '.$langs->trans('AlreadyDone').'<br>';
3903 }
3904 } else {
3905 dol_print_error($db);
3906 }
3907
3908 $i++;
3909 }
3910 } else {
3911 print $langs->trans('NothingToDo')."<br>\n";
3912 }
3913
3914 if (!$error) {
3915 $db->commit();
3916 } else {
3917 $db->rollback();
3918 }
3919 } else {
3920 dol_print_error($db);
3921 $db->rollback();
3922 }
3923
3924 print '</td></tr>';
3925}
3926
3927
3936function migrate_remise_entity($db, $langs, $conf)
3937{
3938 print '<tr><td colspan="4">';
3939
3940 print '<br>';
3941 print '<b>'.$langs->trans('MigrationRemiseEntity')."</b><br>\n";
3942
3943 $error = 0;
3944
3945 dolibarr_install_syslog("upgrade2::migrate_remise_entity");
3946
3947 $db->begin();
3948
3949 $sqlSelect = "SELECT sr.rowid, s.entity";
3950 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."societe_remise as sr, ".MAIN_DB_PREFIX."societe as s";
3951 $sqlSelect .= " WHERE sr.fk_soc = s.rowid and sr.entity != s.entity";
3952
3953 //print $sqlSelect;
3954
3955 $resql = $db->query($sqlSelect);
3956 if ($resql) {
3957 $i = 0;
3958 $num = $db->num_rows($resql);
3959
3960 if ($num) {
3961 while ($i < $num) {
3962 $obj = $db->fetch_object($resql);
3963
3964 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise SET";
3965 $sqlUpdate .= " entity = ".((int) $obj->entity);
3966 $sqlUpdate .= " WHERE rowid = ".((int) $obj->rowid);
3967
3968 $result = $db->query($sqlUpdate);
3969 if (!$result) {
3970 $error++;
3971 dol_print_error($db);
3972 }
3973
3974 print '. ';
3975 $i++;
3976 }
3977 } else {
3978 print $langs->trans('AlreadyDone')."<br>\n";
3979 }
3980
3981 if (!$error) {
3982 $db->commit();
3983 } else {
3984 $db->rollback();
3985 }
3986 } else {
3987 dol_print_error($db);
3988 $db->rollback();
3989 }
3990
3991 print '</td></tr>';
3992}
3993
4003{
4004 print '<tr><td colspan="4">';
4005
4006 print '<br>';
4007 print '<b>'.$langs->trans('MigrationRemiseExceptEntity')."</b><br>\n";
4008
4009 $error = 0;
4010
4011 dolibarr_install_syslog("upgrade2::migrate_remise_except_entity");
4012
4013 $db->begin();
4014
4015 $sqlSelect = "SELECT sr.rowid, sr.fk_soc, sr.fk_facture_source, sr.fk_facture, sr.fk_facture_line";
4016 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr";
4017 //print $sqlSelect;
4018
4019 $resql = $db->query($sqlSelect);
4020 if ($resql) {
4021 $i = 0;
4022 $num = $db->num_rows($resql);
4023
4024 if ($num) {
4025 while ($i < $num) {
4026 $obj = $db->fetch_object($resql);
4027
4028 if (!empty($obj->fk_facture_source) || !empty($obj->fk_facture)) {
4029 $fk_facture = (!empty($obj->fk_facture_source) ? $obj->fk_facture_source : $obj->fk_facture);
4030
4031 $sqlSelect2 = "SELECT f.entity";
4032 $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."facture as f";
4033 $sqlSelect2 .= " WHERE f.rowid = ".((int) $fk_facture);
4034 } elseif (!empty($obj->fk_facture_line)) {
4035 $sqlSelect2 = "SELECT f.entity";
4036 $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as fd";
4037 $sqlSelect2 .= " WHERE fd.rowid = ".((int) $obj->fk_facture_line);
4038 $sqlSelect2 .= " AND fd.fk_facture = f.rowid";
4039 } else {
4040 $sqlSelect2 = "SELECT s.entity";
4041 $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."societe as s";
4042 $sqlSelect2 .= " WHERE s.rowid = ".((int) $obj->fk_soc);
4043 }
4044
4045 $resql2 = $db->query($sqlSelect2);
4046 if ($resql2) {
4047 if ($db->num_rows($resql2) > 0) {
4048 $obj2 = $db->fetch_object($resql2);
4049
4050 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except SET";
4051 $sqlUpdate .= " entity = ".((int) $obj2->entity);
4052 $sqlUpdate .= " WHERE rowid = ".((int) $obj->rowid);
4053
4054 $result = $db->query($sqlUpdate);
4055 if (!$result) {
4056 $error++;
4057 dol_print_error($db);
4058 }
4059 }
4060 } else {
4061 $error++;
4062 dol_print_error($db);
4063 }
4064
4065 print '. ';
4066 $i++;
4067 }
4068 } else {
4069 print $langs->trans('AlreadyDone')."<br>\n";
4070 }
4071
4072 if (!$error) {
4073 $db->commit();
4074 } else {
4075 $db->rollback();
4076 }
4077 } else {
4078 dol_print_error($db);
4079 $db->rollback();
4080 }
4081
4082
4083 print '</td></tr>';
4084}
4085
4103{
4104 dolibarr_install_syslog("upgrade2::migrate_supplier_prices_permissions");
4105
4106 // Grant each target permission to holders of any of its source permissions.
4107 // Format: array('to' => array(module, perms, subperms), 'from' => array(array(module, perms, subperms), ...))
4108 $rules = array(
4109 array('to' => array('produit', 'product_advance', 'read_supplier_prices'), 'from' => array(array('produit', 'lire', ''), array('produit', 'creer', ''))),
4110 array('to' => array('produit', 'product_advance', 'write_supplier_prices'), 'from' => array(array('produit', 'creer', ''))),
4111 array('to' => array('service', 'service_advance', 'read_supplier_prices'), 'from' => array(array('service', 'lire', ''))),
4112 );
4113
4114 $error = 0;
4115 $db->begin();
4116
4117 foreach ($rules as $rule) {
4118 // Resolve the target permission id by name (skip if the module/permission is not present)
4119 $targetid = migrate_get_rights_def_id($db, $rule['to'][0], $rule['to'][1], $rule['to'][2]);
4120 if ($targetid <= 0) {
4121 continue;
4122 }
4123
4124 // Resolve the source permission ids by name
4125 $sourceids = array();
4126 foreach ($rule['from'] as $from) {
4127 $id = migrate_get_rights_def_id($db, $from[0], $from[1], $from[2]);
4128 if ($id > 0) {
4129 $sourceids[] = $id;
4130 }
4131 }
4132 if (empty($sourceids)) {
4133 continue;
4134 }
4135 $sourcelist = implode(',', $sourceids);
4136
4137 // Grant to groups that hold a source permission but not yet the target
4138 $sql = "INSERT INTO ".MAIN_DB_PREFIX."usergroup_rights (entity, fk_usergroup, fk_id)";
4139 $sql .= " SELECT DISTINCT gr.entity, gr.fk_usergroup, ".((int) $targetid);
4140 $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_rights as gr";
4141 $sql .= " WHERE gr.fk_id IN (".$db->sanitize($sourcelist).")";
4142 $sql .= " AND NOT EXISTS (SELECT 1 FROM ".MAIN_DB_PREFIX."usergroup_rights as ex WHERE ex.fk_usergroup = gr.fk_usergroup AND ex.entity = gr.entity AND ex.fk_id = ".((int) $targetid).")";
4143 if (!$db->query($sql)) {
4144 $error++;
4145 break;
4146 }
4147
4148 // Grant to users that hold a source permission but not yet the target
4149 $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_rights (entity, fk_user, fk_id)";
4150 $sql .= " SELECT DISTINCT ur.entity, ur.fk_user, ".((int) $targetid);
4151 $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur";
4152 $sql .= " WHERE ur.fk_id IN (".$db->sanitize($sourcelist).")";
4153 $sql .= " AND NOT EXISTS (SELECT 1 FROM ".MAIN_DB_PREFIX."user_rights as ex WHERE ex.fk_user = ur.fk_user AND ex.entity = ur.entity AND ex.fk_id = ".((int) $targetid).")";
4154 if (!$db->query($sql)) {
4155 $error++;
4156 break;
4157 }
4158 }
4159
4160 if ($error) {
4161 $db->rollback();
4162 return -1;
4163 }
4164 $db->commit();
4165 return 0;
4166}
4167
4177function migrate_get_rights_def_id($db, $module, $perms, $subperms)
4178{
4179 $sql = "SELECT id FROM ".MAIN_DB_PREFIX."rights_def";
4180 $sql .= " WHERE module = '".$db->escape($module)."'";
4181 $sql .= " AND perms = '".$db->escape($perms)."'";
4182 if ($subperms === '') {
4183 $sql .= " AND (subperms IS NULL OR subperms = '')";
4184 } else {
4185 $sql .= " AND subperms = '".$db->escape($subperms)."'";
4186 }
4187 $resql = $db->query($sql);
4188 if (!$resql) {
4189 return 0;
4190 }
4191 $obj = $db->fetch_object($resql);
4192 return $obj ? (int) $obj->id : 0;
4193}
4194
4203function migrate_user_rights_entity($db, $langs, $conf)
4204{
4205 print '<tr><td colspan="4">';
4206
4207 print '<b>'.$langs->trans('MigrationUserRightsEntity')."</b><br>\n";
4208
4209 $error = 0;
4210
4211 dolibarr_install_syslog("upgrade2::migrate_user_rights_entity");
4212
4213 $db->begin();
4214
4215 $sqlSelect = "SELECT u.rowid, u.entity";
4216 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."user as u";
4217 $sqlSelect .= " WHERE u.entity > 1";
4218 //print $sqlSelect;
4219
4220 $resql = $db->query($sqlSelect);
4221 if ($resql) {
4222 $i = 0;
4223 $num = $db->num_rows($resql);
4224
4225 if ($num) {
4226 while ($i < $num) {
4227 $obj = $db->fetch_object($resql);
4228
4229 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."user_rights SET";
4230 $sqlUpdate .= " entity = ".((int) $obj->entity);
4231 $sqlUpdate .= " WHERE fk_user = ".((int) $obj->rowid);
4232
4233 $result = $db->query($sqlUpdate);
4234 if (!$result) {
4235 $error++;
4236 dol_print_error($db);
4237 }
4238
4239 print '. ';
4240 $i++;
4241 }
4242 } else {
4243 print $langs->trans('AlreadyDone')."<br>\n";
4244 }
4245
4246 if (!$error) {
4247 $db->commit();
4248 } else {
4249 $db->rollback();
4250 }
4251 } else {
4252 dol_print_error($db);
4253 $db->rollback();
4254 }
4255
4256
4257 print '</td></tr>';
4258}
4259
4269{
4270 print '<tr><td colspan="4">';
4271
4272 print '<b>'.$langs->trans('MigrationUserGroupRightsEntity')."</b><br>\n";
4273
4274 $error = 0;
4275
4276 dolibarr_install_syslog("upgrade2::migrate_usergroup_rights_entity");
4277
4278 $db->begin();
4279
4280 $sqlSelect = "SELECT u.rowid, u.entity";
4281 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."usergroup as u";
4282 $sqlSelect .= " WHERE u.entity > 1";
4283 //print $sqlSelect;
4284
4285 $resql = $db->query($sqlSelect);
4286 if ($resql) {
4287 $i = 0;
4288 $num = $db->num_rows($resql);
4289
4290 if ($num) {
4291 while ($i < $num) {
4292 $obj = $db->fetch_object($resql);
4293
4294 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."usergroup_rights SET";
4295 $sqlUpdate .= " entity = ".((int) $obj->entity);
4296 $sqlUpdate .= " WHERE fk_usergroup = ".((int) $obj->rowid);
4297
4298 $result = $db->query($sqlUpdate);
4299 if (!$result) {
4300 $error++;
4301 dol_print_error($db);
4302 }
4303
4304 print '. ';
4305 $i++;
4306 }
4307 } else {
4308 print $langs->trans('AlreadyDone')."<br>\n";
4309 }
4310
4311 if (!$error) {
4312 $db->commit();
4313 } else {
4314 $db->rollback();
4315 }
4316 } else {
4317 dol_print_error($db);
4318 $db->rollback();
4319 }
4320
4321
4322 print '</td></tr>';
4323}
4324
4335function migrate_rename_directories($db, $langs, $conf, $oldname, $newname)
4336{
4337 dolibarr_install_syslog("upgrade2::migrate_rename_directories");
4338
4339 if (is_dir(DOL_DATA_ROOT.$oldname) && !file_exists(DOL_DATA_ROOT.$newname)) {
4340 dolibarr_install_syslog("upgrade2::migrate_rename_directories move ".DOL_DATA_ROOT.$oldname.' into '.DOL_DATA_ROOT.$newname);
4341 @rename(DOL_DATA_ROOT.$oldname, DOL_DATA_ROOT.$newname);
4342 } else {
4343 // If new directory already exists, we copy content of old one intotnew one
4344 dolCopyDir(DOL_DATA_ROOT.$oldname, DOL_DATA_ROOT.$newname, '0', 1);
4345 }
4346}
4347
4348
4357function migrate_delete_old_files($db, $langs, $conf)
4358{
4359 $ret = true;
4360
4361 dolibarr_install_syslog("upgrade2::migrate_delete_old_files");
4362
4363 // List of files to delete
4364 $filetodeletearray = array(
4365 '/core/ajax/ajaxcompanies.php',
4366 '/core/triggers/interface_demo.class.php',
4367 '/core/menus/barre_left/default.php',
4368 '/core/menus/barre_top/default.php',
4369 '/core/modules/modComptabiliteExpert.class.php',
4370 '/core/modules/modCommercial.class.php',
4371 '/core/modules/modPaybox.class.php',
4372 '/core/modules/modProduit.class.php',
4373 '/core/modules/modSkype.class.php',
4374 '/core/modules/modactivite.class.php', // A file from an external module that should not be here
4375 '/core/triggers/interface_modWebcalendar_Webcalsynchro.class.php',
4376 '/core/triggers/interface_modCommande_Ecotax.class.php',
4377 '/core/triggers/interface_modCommande_fraisport.class.php',
4378 '/core/triggers/interface_modPropale_PropalWorkflow.class.php',
4379 '/core/triggers/interface_50_modBlockedlog_ActionsBlockedLog.class.php', // now has position 99
4380 '/core/triggers/interface_99_modWebhook_WebhookTriggers.class.php',
4381 '/core/triggers/interface_99_modZapier_ZapierTriggers.class.php',
4382 '/core/menus/smartphone/iphone.lib.php',
4383 '/core/menus/smartphone/iphone_backoffice.php',
4384 '/core/menus/smartphone/iphone_frontoffice.php',
4385 '/core/menus/standard/auguria_backoffice.php',
4386 '/core/menus/standard/auguria_frontoffice.php',
4387 '/core/menus/standard/eldy_backoffice.php',
4388 '/core/menus/standard/eldy_frontoffice.php',
4389 '/core/modules/export/export_excel.modules.php',
4390 '/core/modules/export/export_csv.modules.php',
4391 '/core/modules/export/exportcsv.modules.php',
4392 '/core/modules/export/export_excel2007new.modules.php',
4393 '/core/modules/facture/pdf_crabe.modules.php',
4394 '/core/modules/commande/doc/pdf_einstein.modules.php',
4395 '/core/modules/expedition/doc/pdf_rouget.modules.php',
4396 '/core/modules/propale/doc/pdf_azur.modules.php',
4397 '/core/modules/supplier_order/doc/pdf_muscadet.modules.php',
4398 '/core/modules/supplier_proposal/doc/pdf_aurore.modules.php',
4399 '/core/modules/facture/pdf_oursin.modules.php',
4400 '/core/modules/mailings/contacts2.modules.php',
4401 '/core/modules/mailings/contacts3.modules.php',
4402 '/core/modules/mailings/contacts4.modules.php',
4403 '/core/modules/mailings/framboise.modules.php',
4404 '/core/modules/mailings/dolibarr_services_expired.modules.php',
4405 '/core/modules/mailings/peche.modules.php',
4406 '/core/modules/mailings/poire.modules.php',
4407 '/core/modules/mailings/kiwi.modules.php',
4408 '/core/modules/syslog/mod_syslog_chromephp.php',
4409 '/core/modules/syslog/mod_syslog_firephp.php',
4410 '/core/modules/syslog/logHandlerInterface.php',
4411 '/core/boxes/box_members.php',
4412
4413 '/includes/restler/framework/Luracast/Restler/Data/Object.php',
4414 '/includes/nusoap/lib/class.*',
4415 '/phenix/inc/triggers/interface_modPhenix_Phenixsynchro.class.php',
4416 '/webcalendar/inc/triggers/interface_modWebcalendar_webcalsynchro.class.php',
4417
4418 '/api/class/api_generic.class.php',
4419 '/asterisk/cidlookup.php',
4420 '/categories/class/api_category.class.php',
4421 '/categories/class/api_deprecated_category.class.php',
4422 '/compta/facture/class/api_invoice.class.php',
4423 '/commande/class/api_commande.class.php',
4424 '/partnership/class/api_partnership.class.php',
4425 '/product/class/api_product.class.php',
4426 '/recruitment/class/api_recruitment.class.php',
4427 '/societe/class/api_contact.class.php',
4428 '/societe/class/api_thirdparty.class.php',
4429 '/support/online.php',
4430 '/takepos/class/actions_takepos.class.php',
4431 '/user/class/api_user.class.php',
4432
4433 '/install/mysql/tables/llx_c_ticketsup_category.key.sql',
4434 '/install/mysql/tables/llx_c_ticketsup_category.sql',
4435 '/install/mysql/tables/llx_c_ticketsup_severity.key.sql',
4436 '/install/mysql/tables/llx_c_ticketsup_severity.sql',
4437 '/install/mysql/tables/llx_c_ticketsup_type.key.sql',
4438 '/install/mysql/tables/llx_c_ticketsup_type.sql',
4439
4440 '/install/mysql/tables/llx_categorie_mo-mrp_mo.sql',
4441 '/install/mysql/tables/llx_categorie_mo-mrp_mo.key.sql'
4442 );
4443
4444 /*
4445 print '<tr><td colspan="4">';
4446 print '<b>'.$langs->trans('DeleteOldFiles')."</b><br>\n";
4447 print '</td></tr>';
4448 */
4449
4450 foreach ($filetodeletearray as $filetodelete) {
4451 //print '<b>'DOL_DOCUMENT_ROOT.$filetodelete."</b><br>\n";
4452 if (preg_match('/\*/', $filetodelete) || file_exists(DOL_DOCUMENT_ROOT.$filetodelete)) {
4453 //print "Process file ".$filetodelete."\n";
4454 $result = dol_delete_file(DOL_DOCUMENT_ROOT.$filetodelete, 0, (preg_match('/\*/', $filetodelete) ? 1 : 0), 0, null, true, 0);
4455 if (!$result) {
4456 $langs->load("errors");
4457 print '<div class="error">'.$langs->trans("Error").': '.$langs->trans("ErrorFailToDeleteFile", DOL_DOCUMENT_ROOT.$filetodelete);
4458 print ' '.$langs->trans("RemoveItManuallyAndPressF5ToContinue").'</div>';
4459 } else {
4460 //print $langs->trans("FileWasRemoved", $filetodelete).'<br>';
4461 }
4462 }
4463 }
4464
4465 return $ret;
4466}
4467
4476function migrate_delete_old_dir($db, $langs, $conf)
4477{
4478 $ret = true;
4479
4480 dolibarr_install_syslog("upgrade2::migrate_delete_old_dir");
4481
4482 // List of files to delete
4483 $filetodeletearray = array(
4484 DOL_DOCUMENT_ROOT.'/core/modules/facture/terre',
4485 DOL_DOCUMENT_ROOT.'/core/modules/facture/mercure',
4486 );
4487
4488 // On linux, we can also removed old directory with a different case than new directory.
4489 if (!empty($_SERVER["WINDIR"])) {
4490 $filetodeletearray[] = DOL_DOCUMENT_ROOT.'/includes/phpoffice/PhpSpreadsheet';
4491 }
4492
4493 foreach ($filetodeletearray as $filetodelete) {
4494 $result = 1;
4495 if (file_exists($filetodelete)) {
4496 $result = dol_delete_dir_recursive($filetodelete);
4497 }
4498 if (!$result) {
4499 $langs->load("errors");
4500 print '<div class="error">'.$langs->trans("Error").': '.$langs->trans("ErrorFailToDeleteDir", $filetodelete);
4501 print ' '.$langs->trans("RemoveItManuallyAndPressF5ToContinue").'</div>';
4502 }
4503 }
4504
4505 return $ret;
4506}
4507
4508
4521function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $force = 0)
4522{
4523 global $user;
4524
4525 if (count($listofmodule) == 0) {
4526 return 0;
4527 }
4528
4529 if (!is_object($user)) {
4530 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4531 $user = new User($db); // To avoid error during migration
4532 }
4533
4534 dolibarr_install_syslog("upgrade2::migrate_reload_modules force=".$force.", listofmodule=".implode(',', array_keys($listofmodule)), LOG_NOTICE);
4535
4536 $reloadactionformodules = array(
4537 'MAIN_MODULE_AGENDA' => array('class' => 'modAgenda', 'remove' => 1),
4538 'MAIN_MODULE_API' => array('class' => 'modApi'),
4539 'MAIN_MODULE_BARCODE' => array('class' => 'modBarcode', 'remove' => 1),
4540 'MAIN_MODULE_BLOCKEDLOG' => array('class' => 'modBlockedLog', 'deleteinsertmenus' => 1),
4541 'MAIN_MODULE_CRON' => array('class' => 'modCron', 'remove' => 1),
4542 'MAIN_MODULE_SOCIETE' => array('class' => 'modSociete', 'remove' => 1),
4543 'MAIN_MODULE_PRODUIT' => array('class' => 'modProduct'),
4544 'MAIN_MODULE_SERVICE' => array('class' => 'modService'),
4545 'MAIN_MODULE_COMMANDE' => array('class' => 'modCommande'),
4546 'MAIN_MODULE_DON' => array('class' => 'modDon'),
4547 'MAIN_MODULE_FACTURE' => array('class' => 'modFacture'),
4548 'MAIN_MODULE_FICHEINTER' => array('class' => 'modFicheinter'),
4549 'MAIN_MODULE_FOURNISSEUR' => array('class' => 'modFournisseur'),
4550 'MAIN_MODULE_EXPEDITION' => array('class' => 'modExpedition'),
4551 'MAIN_MODULE_EXPENSEREPORT' => array('class' => 'modExpenseReport'),
4552 'MAIN_MODULE_EVENTORGANIZATION' => array('class' => 'modEventOrganization', 'remove' => 1),
4553 'MAIN_MODULE_ECM' => array('class' => 'modECM', 'remove' => 1),
4554 'MAIN_MODULE_HOLIDAY' => array('class' => 'modHoliday', 'remove' => 1),
4555 'MAIN_MODULE_KNOWLEDGEMANAGEMENT' => array('class' => 'modKnowledgeManagement', 'remove' => 1),
4556 'MAIN_MODULE_LOAN' => array('class' => 'modLoan', 'remove' => 1),
4557 'MAIN_MODULE_PROPAL' => array('class' => 'modPropale'),
4558 'MAIN_MODULE_SUPPLIERPROPOSAL' => array('class' => 'modSupplierProposal', 'remove' => 1),
4559 'MAIN_MODULE_OPENSURVEY' => array('class' => 'modOpenSurvey', 'remove' => 1),
4560 'MAIN_MODULE_PRODUCTBATCH' => array('class' => 'modProductBatch', 'remove' => 1),
4561 'MAIN_MODULE_TAKEPOS' => array('class' => 'modTakePos', 'remove' => 1),
4562 'MAIN_MODULE_VARIANTS' => array('class' => 'modVariants', 'remove' => 1),
4563 'MAIN_MODULE_EMAILCOLLECTOR' => array('class' => 'modEmailCollector', 'remove' => 1),
4564 );
4565
4566 foreach ($listofmodule as $moduletoreload => $reloadmode) { // reloadmodule can be 'noboxes', 'newboxdefonly', 'forceactivate'
4567 $modulekey = preg_replace('/^MAIN_MODULE_/', '', $moduletoreload);
4568
4569 if (empty($moduletoreload) || (!isModEnabled(strtolower($modulekey)) && !$force)) {
4570 continue; // Discard reload if module not enabled
4571 }
4572
4573 $mod = null;
4574
4575 if (!empty($reloadactionformodules[$moduletoreload])) {
4576 dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate module ".$moduletoreload." with mode ".$reloadmode);
4577
4578 $val = $reloadactionformodules[$moduletoreload];
4579 $classformodule = $val['class'];
4580 $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/'.$classformodule.'.class.php';
4581 if ($res) {
4582 $mod = new $classformodule($db);
4583 if (!empty($val['remove'])) {
4584 $mod->remove('noboxes');
4585 }
4586 if (!empty($val['deleteinsertmenus'])) {
4587 // We only reload menus
4588 $mod->delete_menus();
4589 $mod->insert_menus();
4590 } else {
4591 $mod->init($reloadmode);
4592 }
4593 }
4594 } else { // Other generic cases/modules
4595 $reg = array();
4596 preg_match('/([a-zA-Z0-9]+)/', $modulekey, $reg);
4597 if (!empty($reg[1])) {
4598 if (strtoupper($moduletoreload) == $moduletoreload) { // If key has at least one uppercase
4599 $moduletoreloadshort = ucfirst(strtolower($reg[1]));
4600 } else { // If key is a mix of up and low case
4601 $moduletoreloadshort = $reg[1];
4602 }
4603
4604 dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate module ".$moduletoreloadshort." with mode ".$reloadmode." (generic code)", LOG_NOTICE);
4605
4606 $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/mod'.$moduletoreloadshort.'.class.php';
4607 if ($res) {
4608 $classname = 'mod'.$moduletoreloadshort;
4609 $mod = new $classname($db);
4610 '@phan-var-force DolibarrModules $mod';
4611
4612 //$mod->remove('noboxes');
4613 $mod->delete_menus(); // We must delete to be sure it is inserted with new values
4614 $mod->init($reloadmode);
4615 } else {
4616 dolibarr_install_syslog('Failed to include '.DOL_DOCUMENT_ROOT.'/core/modules/mod'.$moduletoreloadshort.'.class.php', LOG_ERR);
4617
4618 $res = @dol_include_once(strtolower($moduletoreloadshort).'/core/modules/mod'.$moduletoreloadshort.'.class.php');
4619 if ($res) {
4620 $classname = 'mod'.$moduletoreloadshort;
4621 $mod = new $classname($db);
4622 '@phan-var-force DolibarrModules $mod';
4623 $mod->init($reloadmode);
4624 } else {
4625 dolibarr_install_syslog('Failed to include '.strtolower($moduletoreloadshort).'/core/modules/mod'.$moduletoreloadshort.'.class.php', LOG_ERR);
4626 print "Error, can't find module with name ".$moduletoreload."\n";
4627 return -1;
4628 }
4629 }
4630 } else {
4631 dolibarr_install_syslog("Error, can't find module with name ".$moduletoreload, LOG_ERR);
4632 print "Error, can't find module with name ".$moduletoreload."\n";
4633 return -1;
4634 }
4635 }
4636
4637 if (!empty($mod) && is_object($mod)) {
4638 print '<tr class="trforrunsql"><td colspan="4">';
4639 print '<b>'.$langs->trans('Upgrade').'</b>: ';
4640 print $langs->trans('MigrationReloadModule').' '.$mod->getName(); // We keep getName outside of trans because getName is already encoded/translated
4641 print "<!-- (".$reloadmode.") -->";
4642 print "<br>\n";
4643 print '</td></tr>';
4644 }
4645 }
4646
4647 return 1;
4648}
4649
4650
4651
4660function migrate_reload_menu($db, $langs, $conf)
4661{
4662 global $conf;
4663 dolibarr_install_syslog("upgrade2::migrate_reload_menu");
4664
4665 // Define list of menu handlers to initialize
4666 $listofmenuhandler = array();
4667 if (getDolGlobalString('MAIN_MENU_STANDARD') == 'auguria_menu' || getDolGlobalString('MAIN_MENU_SMARTPHONE') == 'auguria_menu'
4668 || getDolGlobalString('MAIN_MENUFRONT_STANDARD') == 'auguria_menu' || getDolGlobalString('MAIN_MENUFRONT_SMARTPHONE') == 'auguria_menu') {
4669 $listofmenuhandler['auguria'] = 1; // We set here only dynamic menu handlers
4670 }
4671
4672 foreach ($listofmenuhandler as $key => $val) {
4673 print '<tr class="trforrunsql"><td colspan="4">';
4674
4675 //print "x".$key;
4676 print '<br>';
4677 print '<b>'.$langs->trans('Upgrade').'</b>: '.$langs->trans('MenuHandler')." ".$key."<br>\n";
4678
4679 // Load sql ini_menu_handler.sql file
4680 $dir = DOL_DOCUMENT_ROOT."/core/menus/";
4681 $file = 'init_menu_'.$key.'.sql';
4682 if (file_exists($dir.$file)) {
4683 $result = run_sql($dir.$file, 1, 0, 1, $key);
4684 }
4685
4686 print '</td></tr>';
4687 }
4688
4689 return 1;
4690}
4691
4698{
4699 global $conf, $db, $langs, $user;
4700
4701 if (!is_object($user)) {
4702 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4703 $user = new User($db); // To avoid error during migration
4704 }
4705
4706 print '<tr><td colspan="4">';
4707
4708 print '<b>'.$langs->trans('MigrationProductLotPath')."</b><br>\n";
4709
4710 $sql = "SELECT rowid, entity, batch, fk_product from ".MAIN_DB_PREFIX."product_lot";
4711 $resql = $db->query($sql);
4712
4713 if ($resql) {
4714 $modulepart = "product_batch";
4715
4716 $lot = new Productlot($db);
4717
4718 while ($obj = $db->fetch_object($resql)) {
4719 $entity = (empty($obj->entity) ? 1 : $obj->entity);
4720 if ($entity > 1) {
4721 $dir = DOL_DATA_ROOT.'/'.$entity.'/'.$conf->productbatch->multidir_output[$entity];
4722 } else {
4723 $dir = $conf->productbatch->multidir_output[$entity];
4724 }
4725
4726 if ($dir) {
4727 $lot->id = (int) $obj->rowid;
4728 $lot->ref = (string) $obj->rowid; // No ref for the moment
4729 $lot->batch = $obj->batch;
4730 $lot->entity = $obj->entity;
4731 $lot->fk_product = $obj->fk_product;
4732
4733 $savref = $lot->ref;
4734
4735 $lot->ref = $obj->batch;
4736 $origin = $dir . '/' . get_exdir(0, 0, 0, 1, $lot, $modulepart);
4737
4738 $lot->ref = $savref; // So restore the id
4739 $destin = $dir . '/' . get_exdir(0, 0, 0, 1, $lot, $modulepart);
4740
4741 //var_dump($origin.' -> '.$destin.' '.$lot->batch.' dir origin is '.dol_is_dir($origin));exit;
4742
4743 if (dol_is_dir($origin) && !dol_is_dir($destin)) {
4744 dol_move_dir($origin, $destin, 0);
4745 }
4746 }
4747 }
4748 }
4749 print '</td></tr>';
4750
4751 return 1;
4752}
4753
4760{
4761 global $conf, $db, $langs, $user;
4762
4763 print '<tr><td colspan="4">';
4764
4765 print '<b>'.$langs->trans('MigrationUserPhotoPath')."</b><br>\n";
4766
4767 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4768 $fuser = new User($db);
4769 if (!is_object($user)) {
4770 $user = $fuser; // To avoid error during migration
4771 }
4772
4773 $sql = "SELECT rowid as uid, entity from ".MAIN_DB_PREFIX."user"; // Get list of all users
4774 $resql = $db->query($sql);
4775 if ($resql) {
4776 while ($obj = $db->fetch_object($resql)) {
4777 //$fuser->fetch($obj->uid);
4778 $fuser->id = $obj->uid;
4779 $fuser->entity = $obj->entity;
4780
4781 //echo '<hr>'.$fuser->id.' -> '.$fuser->entity;
4782 $entity = (empty($fuser->entity) ? 1 : $fuser->entity);
4783 if ($entity > 1) {
4784 $dir = DOL_DATA_ROOT.'/'.$entity.'/users';
4785 } else {
4786 $dir = $conf->user->multidir_output[$entity]; // $conf->user->multidir_output[] for each entity is construct by the multicompany module
4787 }
4788
4789 if ($dir) {
4790 //print "Process user id ".$fuser->id."<br>\n";
4791 $origin = $dir.'/'.get_exdir($fuser->id, 2, 0, 1, $fuser, 'user'); // Use old behaviour to get x/y path
4792 $destin = $dir.'/'.$fuser->id;
4793
4794 $origin_osencoded = dol_osencode($origin);
4795
4796 dol_mkdir($destin);
4797
4798 //echo '<hr>'.$origin.' -> '.$destin;
4799 if (dol_is_dir($origin)) {
4800 $handle = opendir($origin_osencoded);
4801 if (is_resource($handle)) {
4802 while (($file = readdir($handle)) !== false) {
4803 if ($file == '.' || $file == '..') {
4804 continue;
4805 }
4806
4807 if (dol_is_dir($origin.'/'.$file)) { // it is a dir (like 'thumbs')
4808 $thumbs = opendir($origin_osencoded.'/'.$file);
4809 if (is_resource($thumbs)) {
4810 dol_mkdir($destin.'/'.$file);
4811 while (($thumb = readdir($thumbs)) !== false) {
4812 if (!dol_is_file($destin.'/'.$file.'/'.$thumb)) {
4813 if ($thumb == '.' || $thumb == '..') {
4814 continue;
4815 }
4816
4817 //print $origin.'/'.$file.'/'.$thumb.' -> '.$destin.'/'.$file.'/'.$thumb.'<br>'."\n";
4818 print '.';
4819 dol_copy($origin.'/'.$file.'/'.$thumb, $destin.'/'.$file.'/'.$thumb, '0', 0);
4820 //var_dump('aaa');exit;
4821 }
4822 }
4823 // dol_delete_dir($origin.'/'.$file);
4824 }
4825 } else { // it is a file
4826 if (!dol_is_file($destin.'/'.$file)) {
4827 //print $origin.'/'.$file.' -> '.$destin.'/'.$file.'<br>'."\n";
4828 print '.';
4829 dol_copy($origin.'/'.$file, $destin.'/'.$file, '0', 0);
4830 //var_dump('eee');exit;
4831 }
4832 }
4833 }
4834 }
4835 }
4836 }
4837 }
4838 }
4839
4840 print '</td></tr>';
4841}
4842
4849{
4850 global $db, $langs, $user;
4851
4852 print '<tr><td colspan="4">';
4853
4854 print '<b>'.$langs->trans('MigrationUserPhotoPath')."</b><br>\n";
4855
4856 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4857 $fuser = new User($db);
4858 if (!is_object($user)) {
4859 $user = $fuser; // To avoid error during migration
4860 }
4861
4862 $sql = "SELECT rowid as uid, entity, photo from ".MAIN_DB_PREFIX."user"; // Get list of all users
4863 $resql = $db->query($sql);
4864 if ($resql) {
4865 while ($obj = $db->fetch_object($resql)) {
4866 //$fuser->fetch($obj->uid);
4867 $fuser->id = $obj->uid;
4868 $fuser->entity = $obj->entity;
4869 $fuser->photo = $obj->photo;
4870
4871 //echo '<hr>'.$fuser->id.' -> '.$fuser->entity;
4872 $entity = (empty($fuser->entity) ? 1 : $fuser->entity);
4873 if ($entity > 1) {
4874 $dir = DOL_DATA_ROOT.'/'.$entity.'/users';
4875 } else {
4876 $dir = DOL_DATA_ROOT.'/users';
4877 }
4878
4879 if ($dir) {
4880 //print "Process user id ".$fuser->id."<br>\n";
4881 $origin = $dir.'/'.$fuser->id;
4882 $destin = $dir.'/'.$fuser->id.'/photos';
4883
4884 $origin_osencoded = dol_osencode($origin);
4885
4886 dol_mkdir($destin);
4887
4888 //echo '<hr>'.$origin.' -> '.$destin;
4889 if (dol_is_dir($origin)) {
4890 $handle = opendir($origin_osencoded);
4891 if (is_resource($handle)) {
4892 while (($file = readdir($handle)) !== false) {
4893 if ($file == '.' || $file == '..' || $file == 'photos') {
4894 continue;
4895 }
4896 if (!empty($fuser->photo) && ($file != $fuser->photo && $file != 'thumbs')) {
4897 continue;
4898 }
4899
4900 if (dol_is_dir($origin.'/'.$file)) { // it is a dir (like 'thumbs')
4901 $thumbs = opendir($origin_osencoded.'/'.$file);
4902 if (is_resource($thumbs)) {
4903 dol_mkdir($destin.'/'.$file);
4904 while (($thumb = readdir($thumbs)) !== false) {
4905 if (!dol_is_file($destin.'/'.$file.'/'.$thumb)) {
4906 if ($thumb == '.' || $thumb == '..') {
4907 continue;
4908 }
4909
4910 //print $origin.'/'.$file.'/'.$thumb.' -> '.$destin.'/'.$file.'/'.$thumb.'<br>'."\n";
4911 print '.';
4912 dol_copy($origin.'/'.$file.'/'.$thumb, $destin.'/'.$file.'/'.$thumb, '0', 0);
4913 }
4914 }
4915 // dol_delete_dir($origin.'/'.$file);
4916 }
4917 } else { // it is a file
4918 if (!dol_is_file($destin.'/'.$file)) {
4919 //print $origin.'/'.$file.' -> '.$destin.'/'.$file.'<br>'."\n";
4920 print '.';
4921 dol_copy($origin.'/'.$file, $destin.'/'.$file, '0', 0);
4922 }
4923 }
4924 }
4925 }
4926 }
4927 }
4928 }
4929 }
4930
4931 print '</td></tr>';
4932}
4933
4934
4935
4942{
4943 global $conf, $db, $langs;
4944
4945 print '<tr class="trforrunsql"><td>';
4946
4947 print '<b>'.$langs->trans('MigrationHolidayPath')."</b><br>\n";
4948
4949 include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
4950 $holiday = new Holiday($db);
4951
4952 $sql = "SELECT rowid as uid, ref, entity from ".MAIN_DB_PREFIX."holiday"; // Get list of all holiday
4953
4954 $resql = $db->query($sql);
4955 if ($resql) {
4956 while ($obj = $db->fetch_object($resql)) {
4957 //$holiday->fetch($obj->uid);
4958 $holiday->id = $obj->uid;
4959 $holiday->ref = $obj->ref;
4960 $holiday->entity = $obj->entity;
4961
4962 //echo '<hr>'.$holiday->id.' -> '.$holiday->entity;
4963 $entity = (empty($holiday->entity) ? 1 : $holiday->entity);
4964 if ($entity > 1) {
4965 $dir = DOL_DATA_ROOT.'/'.$entity.'/holiday';
4966 } else {
4967 $dir = $conf->holiday->multidir_output[$entity]; // $conf->user->multidir_output[] for each entity is construct by the multicompany module
4968 }
4969
4970 if ($dir) {
4971 //print "Process holiday id ".$holiday->id."<br>\n";
4972 $origin = $dir.'/'.get_exdir($holiday->id, 2, 0, 1, $holiday, 'holiday'); // Use old behaviour to get x/y path
4973 $destin = $dir.'/'.$holiday->ref;
4974
4975 $origin_osencoded = dol_osencode($origin);
4976
4977 dol_mkdir($destin);
4978
4979 //echo $origin.' -> '.$destin."<br>\n";
4980 if (dol_is_dir($origin)) {
4981 $handle = opendir($origin_osencoded);
4982 if (is_resource($handle)) {
4983 while (($file = readdir($handle)) !== false) {
4984 if ($file == '.' || $file == '..') {
4985 continue;
4986 }
4987
4988 if (dol_is_dir($origin.'/'.$file)) { // it is a dir (like 'thumbs')
4989 $thumbs = opendir($origin_osencoded.'/'.$file);
4990 if (is_resource($thumbs)) {
4991 dol_mkdir($destin.'/'.$file);
4992 while (($thumb = readdir($thumbs)) !== false) {
4993 if (!dol_is_file($destin.'/'.$file.'/'.$thumb)) {
4994 if ($thumb == '.' || $thumb == '..') {
4995 continue;
4996 }
4997
4998 //print $origin.'/'.$file.'/'.$thumb.' -> '.$destin.'/'.$file.'/'.$thumb.'<br>'."\n";
4999 print '.';
5000 dol_copy($origin.'/'.$file.'/'.$thumb, $destin.'/'.$file.'/'.$thumb, '0', 0);
5001 //var_dump('aaa');exit;
5002 }
5003 }
5004 // dol_delete_dir($origin.'/'.$file);
5005 }
5006 } else { // it is a file
5007 if (!dol_is_file($destin.'/'.$file)) {
5008 //print $origin.'/'.$file.' -> '.$destin.'/'.$file.'<br>'."\n";
5009 print '.';
5010 dol_copy($origin.'/'.$file, $destin.'/'.$file, '0', 0);
5011 }
5012 }
5013 }
5014 }
5015 }
5016 }
5017 }
5018 }
5019
5020 print '</td></tr>';
5021}
5022
5023
5024/* TODO: Modify the Paid status and `fk_facture` of the invoices paid in full
5025
5026Lookup incorrect invoices:
5027select 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
5028having f.total_ttc = sum(pf.amount)
5029
5030Correct the incorrect invoices:
5031update llx_facture set paye=1, fk_statut=2 where close_code is null
5032and rowid in (...)
5033*/
5034
5042{
5043 global $db, $langs;
5044 // skype,twitter,facebook,linkedin,instagram,snapchat,googleplus,youtube,whatsapp
5045 $error = 0;
5046 $db->begin();
5047 print '<tr><td colspan="4">';
5048 $sql = 'SELECT rowid, socialnetworks';
5049 $sql .= ', skype, twitter, facebook, linkedin, instagram, snapchat, googleplus, youtube, whatsapp FROM '.MAIN_DB_PREFIX.'user WHERE';
5050 $sql .= " skype IS NOT NULL OR skype <> ''";
5051 $sql .= " OR twitter IS NOT NULL OR twitter <> ''";
5052 $sql .= " OR facebook IS NOT NULL OR facebook <> ''";
5053 $sql .= " OR linkedin IS NOT NULL OR linkedin <> ''";
5054 $sql .= " OR instagram IS NOT NULL OR instagram <> ''";
5055 $sql .= " OR snapchat IS NOT NULL OR snapchat <> ''";
5056 $sql .= " OR googleplus IS NOT NULL OR googleplus <> ''";
5057 $sql .= " OR youtube IS NOT NULL OR youtube <> ''";
5058 $sql .= " OR whatsapp IS NOT NULL OR whatsapp <> ''";
5059
5060 $resql = $db->query($sql);
5061 if ($resql) {
5062 while ($obj = $db->fetch_object($resql)) {
5063 $arraysocialnetworks = array();
5064 if (!empty($obj->skype)) {
5065 $arraysocialnetworks['skype'] = $obj->skype;
5066 }
5067 if (!empty($obj->twitter)) {
5068 $arraysocialnetworks['twitter'] = $obj->twitter;
5069 }
5070 if (!empty($obj->facebook)) {
5071 $arraysocialnetworks['facebook'] = $obj->facebook;
5072 }
5073 if (!empty($obj->linkedin)) {
5074 $arraysocialnetworks['linkedin'] = $obj->linkedin;
5075 }
5076 if (!empty($obj->instagram)) {
5077 $arraysocialnetworks['instagram'] = $obj->instagram;
5078 }
5079 if (!empty($obj->snapchat)) {
5080 $arraysocialnetworks['snapchat'] = $obj->snapchat;
5081 }
5082 if (!empty($obj->googleplus)) {
5083 $arraysocialnetworks['googleplus'] = $obj->googleplus;
5084 }
5085 if (!empty($obj->youtube)) {
5086 $arraysocialnetworks['youtube'] = $obj->youtube;
5087 }
5088 if (!empty($obj->whatsapp)) {
5089 $arraysocialnetworks['whatsapp'] = $obj->whatsapp;
5090 }
5091 if ($obj->socialnetworks == '' || is_null($obj->socialnetworks)) {
5092 $obj->socialnetworks = '[]';
5093 }
5094 $socialnetworks = array_merge($arraysocialnetworks, json_decode($obj->socialnetworks, true));
5095 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX."user SET socialnetworks='".$db->escape(json_encode($socialnetworks))."'";
5096 $sqlupd .= ', skype=null';
5097 $sqlupd .= ', twitter=null';
5098 $sqlupd .= ', facebook=null';
5099 $sqlupd .= ', linkedin=null';
5100 $sqlupd .= ', instagram=null';
5101 $sqlupd .= ', snapchat=null';
5102 $sqlupd .= ', googleplus=null';
5103 $sqlupd .= ', youtube=null';
5104 $sqlupd .= ', whatsapp=null';
5105 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
5106
5107 $resqlupd = $db->query($sqlupd);
5108 if (!$resqlupd) {
5109 dol_print_error($db);
5110 $error++;
5111 }
5112 }
5113 } else {
5114 $error++;
5115 }
5116 if (!$error) {
5117 $db->commit();
5118 } else {
5119 dol_print_error($db);
5120 $db->rollback();
5121 }
5122 print '<b>'.$langs->trans('MigrationFieldsSocialNetworks', 'Users')."</b><br>\n";
5123 print '</td></tr>';
5124}
5125
5133{
5134 global $db, $langs;
5135
5136 print '<tr><td colspan="4">';
5137 $error = 0;
5138 $db->begin();
5139 print '<tr><td colspan="4">';
5140 $sql = 'SELECT rowid, socialnetworks';
5141 $sql .= ', skype, twitter, facebook, linkedin, instagram, snapchat, googleplus, youtube, whatsapp FROM '.MAIN_DB_PREFIX.'adherent WHERE ';
5142 $sql .= " skype IS NOT NULL OR skype <> ''";
5143 $sql .= " OR twitter IS NOT NULL OR twitter <> ''";
5144 $sql .= " OR facebook IS NOT NULL OR facebook <> ''";
5145 $sql .= " OR linkedin IS NOT NULL OR linkedin <> ''";
5146 $sql .= " OR instagram IS NOT NULL OR instagram <> ''";
5147 $sql .= " OR snapchat IS NOT NULL OR snapchat <> ''";
5148 $sql .= " OR googleplus IS NOT NULL OR googleplus <> ''";
5149 $sql .= " OR youtube IS NOT NULL OR youtube <> ''";
5150 $sql .= " OR whatsapp IS NOT NULL OR whatsapp <> ''";
5151 //print $sql;
5152 $resql = $db->query($sql);
5153 if ($resql) {
5154 while ($obj = $db->fetch_object($resql)) {
5155 $arraysocialnetworks = array();
5156 if (!empty($obj->skype)) {
5157 $arraysocialnetworks['skype'] = $obj->skype;
5158 }
5159 if (!empty($obj->twitter)) {
5160 $arraysocialnetworks['twitter'] = $obj->twitter;
5161 }
5162 if (!empty($obj->facebook)) {
5163 $arraysocialnetworks['facebook'] = $obj->facebook;
5164 }
5165 if (!empty($obj->linkedin)) {
5166 $arraysocialnetworks['linkedin'] = $obj->linkedin;
5167 }
5168 if (!empty($obj->instagram)) {
5169 $arraysocialnetworks['instagram'] = $obj->instagram;
5170 }
5171 if (!empty($obj->snapchat)) {
5172 $arraysocialnetworks['snapchat'] = $obj->snapchat;
5173 }
5174 if (!empty($obj->googleplus)) {
5175 $arraysocialnetworks['googleplus'] = $obj->googleplus;
5176 }
5177 if (!empty($obj->youtube)) {
5178 $arraysocialnetworks['youtube'] = $obj->youtube;
5179 }
5180 if (!empty($obj->whatsapp)) {
5181 $arraysocialnetworks['whatsapp'] = $obj->whatsapp;
5182 }
5183 if ($obj->socialnetworks == '' || is_null($obj->socialnetworks)) {
5184 $obj->socialnetworks = '[]';
5185 }
5186 $socialnetworks = array_merge($arraysocialnetworks, json_decode($obj->socialnetworks, true));
5187 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX."adherent SET socialnetworks='".$db->escape(json_encode($socialnetworks))."'";
5188 $sqlupd .= ', skype=null';
5189 $sqlupd .= ', twitter=null';
5190 $sqlupd .= ', facebook=null';
5191 $sqlupd .= ', linkedin=null';
5192 $sqlupd .= ', instagram=null';
5193 $sqlupd .= ', snapchat=null';
5194 $sqlupd .= ', googleplus=null';
5195 $sqlupd .= ', youtube=null';
5196 $sqlupd .= ', whatsapp=null';
5197 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
5198 //print $sqlupd."<br>";
5199 $resqlupd = $db->query($sqlupd);
5200 if (!$resqlupd) {
5201 dol_print_error($db);
5202 $error++;
5203 }
5204 }
5205 } else {
5206 $error++;
5207 }
5208 if (!$error) {
5209 $db->commit();
5210 } else {
5211 dol_print_error($db);
5212 $db->rollback();
5213 }
5214 print '<b>'.$langs->trans('MigrationFieldsSocialNetworks', 'Members')."</b><br>\n";
5215 print '</td></tr>';
5216}
5217
5225{
5226 global $db, $langs;
5227 // jabberid,skype,twitter,facebook,linkedin,instagram,snapchat,googleplus,youtube,whatsapp
5228 $error = 0;
5229 $db->begin();
5230 print '<tr><td colspan="4">';
5231 $sql = 'SELECT rowid, socialnetworks';
5232 $sql .= ', jabberid, skype, twitter, facebook, linkedin, instagram, snapchat, googleplus, youtube, whatsapp FROM '.MAIN_DB_PREFIX.'socpeople WHERE';
5233 $sql .= " jabberid IS NOT NULL OR jabberid <> ''";
5234 $sql .= " OR skype IS NOT NULL OR skype <> ''";
5235 $sql .= " OR twitter IS NOT NULL OR twitter <> ''";
5236 $sql .= " OR facebook IS NOT NULL OR facebook <> ''";
5237 $sql .= " OR linkedin IS NOT NULL OR linkedin <> ''";
5238 $sql .= " OR instagram IS NOT NULL OR instagram <> ''";
5239 $sql .= " OR snapchat IS NOT NULL OR snapchat <> ''";
5240 $sql .= " OR googleplus IS NOT NULL OR googleplus <> ''";
5241 $sql .= " OR youtube IS NOT NULL OR youtube <> ''";
5242 $sql .= " OR whatsapp IS NOT NULL OR whatsapp <> ''";
5243 //print $sql;
5244 $resql = $db->query($sql);
5245 if ($resql) {
5246 while ($obj = $db->fetch_object($resql)) {
5247 $arraysocialnetworks = array();
5248 if (!empty($obj->jabberid)) {
5249 $arraysocialnetworks['jabber'] = $obj->jabberid;
5250 }
5251 if (!empty($obj->skype)) {
5252 $arraysocialnetworks['skype'] = $obj->skype;
5253 }
5254 if (!empty($obj->twitter)) {
5255 $arraysocialnetworks['twitter'] = $obj->twitter;
5256 }
5257 if (!empty($obj->facebook)) {
5258 $arraysocialnetworks['facebook'] = $obj->facebook;
5259 }
5260 if (!empty($obj->linkedin)) {
5261 $arraysocialnetworks['linkedin'] = $obj->linkedin;
5262 }
5263 if (!empty($obj->instagram)) {
5264 $arraysocialnetworks['instagram'] = $obj->instagram;
5265 }
5266 if (!empty($obj->snapchat)) {
5267 $arraysocialnetworks['snapchat'] = $obj->snapchat;
5268 }
5269 if (!empty($obj->googleplus)) {
5270 $arraysocialnetworks['googleplus'] = $obj->googleplus;
5271 }
5272 if (!empty($obj->youtube)) {
5273 $arraysocialnetworks['youtube'] = $obj->youtube;
5274 }
5275 if (!empty($obj->whatsapp)) {
5276 $arraysocialnetworks['whatsapp'] = $obj->whatsapp;
5277 }
5278 if ($obj->socialnetworks == '' || is_null($obj->socialnetworks)) {
5279 $obj->socialnetworks = '[]';
5280 }
5281 $socialnetworks = array_merge($arraysocialnetworks, json_decode($obj->socialnetworks, true));
5282 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX."socpeople SET socialnetworks='".$db->escape(json_encode($socialnetworks))."'";
5283 $sqlupd .= ', jabberid=null';
5284 $sqlupd .= ', skype=null';
5285 $sqlupd .= ', twitter=null';
5286 $sqlupd .= ', facebook=null';
5287 $sqlupd .= ', linkedin=null';
5288 $sqlupd .= ', instagram=null';
5289 $sqlupd .= ', snapchat=null';
5290 $sqlupd .= ', googleplus=null';
5291 $sqlupd .= ', youtube=null';
5292 $sqlupd .= ', whatsapp=null';
5293 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
5294 //print $sqlupd."<br>";
5295 $resqlupd = $db->query($sqlupd);
5296 if (!$resqlupd) {
5297 dol_print_error($db);
5298 $error++;
5299 }
5300 }
5301 } else {
5302 $error++;
5303 }
5304 if (!$error) {
5305 $db->commit();
5306 } else {
5307 dol_print_error($db);
5308 $db->rollback();
5309 }
5310 print '<b>'.$langs->trans('MigrationFieldsSocialNetworks', 'Contacts')."</b><br>\n";
5311 print '</td></tr>';
5312}
5313
5321{
5322 global $db, $langs;
5323 // skype,twitter,facebook,linkedin,instagram,snapchat,googleplus,youtube,whatsapp
5324 $error = 0;
5325 $db->begin();
5326 print '<tr><td colspan="4">';
5327 $sql = 'SELECT rowid, socialnetworks';
5328 $sql .= ', skype, twitter, facebook, linkedin, instagram, snapchat, googleplus, youtube, whatsapp FROM '.MAIN_DB_PREFIX.'societe WHERE ';
5329 $sql .= " skype IS NOT NULL OR skype <> ''";
5330 $sql .= " OR twitter IS NOT NULL OR twitter <> ''";
5331 $sql .= " OR facebook IS NOT NULL OR facebook <> ''";
5332 $sql .= " OR linkedin IS NOT NULL OR linkedin <> ''";
5333 $sql .= " OR instagram IS NOT NULL OR instagram <> ''";
5334 $sql .= " OR snapchat IS NOT NULL OR snapchat <> ''";
5335 $sql .= " OR googleplus IS NOT NULL OR googleplus <> ''";
5336 $sql .= " OR youtube IS NOT NULL OR youtube <> ''";
5337 $sql .= " OR whatsapp IS NOT NULL OR whatsapp <> ''";
5338
5339 $resql = $db->query($sql);
5340 if ($resql) {
5341 while ($obj = $db->fetch_object($resql)) {
5342 $arraysocialnetworks = array();
5343 if (!empty($obj->skype)) {
5344 $arraysocialnetworks['skype'] = $obj->skype;
5345 }
5346 if (!empty($obj->twitter)) {
5347 $arraysocialnetworks['twitter'] = $obj->twitter;
5348 }
5349 if (!empty($obj->facebook)) {
5350 $arraysocialnetworks['facebook'] = $obj->facebook;
5351 }
5352 if (!empty($obj->linkedin)) {
5353 $arraysocialnetworks['linkedin'] = $obj->linkedin;
5354 }
5355 if (!empty($obj->instagram)) {
5356 $arraysocialnetworks['instagram'] = $obj->instagram;
5357 }
5358 if (!empty($obj->snapchat)) {
5359 $arraysocialnetworks['snapchat'] = $obj->snapchat;
5360 }
5361 if (!empty($obj->googleplus)) {
5362 $arraysocialnetworks['googleplus'] = $obj->googleplus;
5363 }
5364 if (!empty($obj->youtube)) {
5365 $arraysocialnetworks['youtube'] = $obj->youtube;
5366 }
5367 if (!empty($obj->whatsapp)) {
5368 $arraysocialnetworks['whatsapp'] = $obj->whatsapp;
5369 }
5370 if ($obj->socialnetworks == '' || is_null($obj->socialnetworks)) {
5371 $obj->socialnetworks = '[]';
5372 }
5373 $socialnetworks = array_merge($arraysocialnetworks, json_decode($obj->socialnetworks, true));
5374 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX."societe SET socialnetworks='".$db->escape(json_encode($socialnetworks))."'";
5375 $sqlupd .= ', skype=null';
5376 $sqlupd .= ', twitter=null';
5377 $sqlupd .= ', facebook=null';
5378 $sqlupd .= ', linkedin=null';
5379 $sqlupd .= ', instagram=null';
5380 $sqlupd .= ', snapchat=null';
5381 $sqlupd .= ', googleplus=null';
5382 $sqlupd .= ', youtube=null';
5383 $sqlupd .= ', whatsapp=null';
5384 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
5385 //print $sqlupd."<br>";
5386 $resqlupd = $db->query($sqlupd);
5387 if (!$resqlupd) {
5388 dol_print_error($db);
5389 $error++;
5390 }
5391 }
5392 } else {
5393 $error++;
5394 }
5395 if (!$error) {
5396 $db->commit();
5397 } else {
5398 dol_print_error($db);
5399 $db->rollback();
5400 }
5401 print '<b>'.$langs->trans('MigrationFieldsSocialNetworks', 'Thirdparties')."</b><br>\n";
5402 print '</td></tr>';
5403}
5404
5405
5412function migrate_export_import_profiles($mode = 'export')
5413{
5414 global $db, $langs;
5415
5416 $error = 0;
5417 $resultstring = '';
5418
5419 $db->begin();
5420
5421 print '<tr class="trforrunsql"><td colspan="4">';
5422 $sql = 'SELECT rowid, field';
5423 if ($mode == 'export') {
5424 $sql .= ', filter';
5425 }
5426 $sql .= ' FROM '.MAIN_DB_PREFIX.$mode.'_model WHERE';
5427 $sql .= " type LIKE 'propale_%' OR type LIKE 'commande_%' OR type LIKE 'facture_%'";
5428 //print $sql;
5429 $resql = $db->query($sql);
5430 if ($resql) {
5431 while ($obj = $db->fetch_object($resql)) {
5432 $oldfield = $obj->field;
5433 $newfield = str_replace(array(',f.facnumber', 'f.facnumber,', 'f.total,', 'f.tva,'), array(',f.ref', 'f.ref,', 'f.total_ht,', 'f.total_tva,'), $oldfield);
5434
5435 if ($mode == 'export') {
5436 $oldfilter = $obj->filter;
5437 $newfilter = str_replace(array('f.facnumber=', 'f.total=', 'f.tva='), array('f.ref=', 'f.total_ht=', 'f.total_tva='), $oldfilter);
5438 } else {
5439 $oldfilter = '';
5440 $newfilter = '';
5441 }
5442
5443 if ($oldfield != $newfield || $oldfilter != $newfilter) {
5444 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX.$mode."_model SET field = '".$db->escape($newfield)."'";
5445 if ($mode == 'export') {
5446 $sqlupd .= ", filter = '".$db->escape($newfilter)."'";
5447 }
5448 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
5449 $resultstring .= '<tr class="trforrunsql" style=""><td class="wordbreak" colspan="4">'.$sqlupd."</td></tr>\n";
5450 $resqlupd = $db->query($sqlupd);
5451 if (!$resqlupd) {
5452 dol_print_error($db);
5453 $error++;
5454 }
5455 }
5456 }
5457 } else {
5458 $error++;
5459 }
5460 if (!$error) {
5461 $db->commit();
5462 } else {
5463 dol_print_error($db);
5464 $db->rollback();
5465 }
5466 print '<b>'.$langs->trans('MigrationImportOrExportProfiles', $mode)."</b><br>\n";
5467 print '</td></tr>';
5468
5469 if ($resultstring) {
5470 print $resultstring;
5471 } else {
5472 print '<tr class="trforrunsql" style=""><td class="wordbreak" colspan="4">'.$langs->trans("NothingToDo")."</td></tr>\n";
5473 }
5474}
5475
5482{
5483 global $db, $langs;
5484
5485 $error = 0;
5486 $resultstring = '';
5487
5488 $db->begin();
5489 print '<tr class="trforrunsql"><td colspan="4">';
5490 print '<b>'.$langs->trans('MigrationContractLineRank')."</b><br>\n";
5491
5492 $sql = "SELECT c.rowid as cid ,cd.rowid as cdid,cd.rang FROM ".$db->prefix()."contratdet as cd INNER JOIN ".$db->prefix()."contrat as c ON c.rowid=cd.fk_contrat AND cd.rang=0";
5493 $sql .= " ORDER BY c.rowid,cd.rowid";
5494
5495 $resql = $db->query($sql);
5496 if ($resql) {
5497 $currentRank = 0;
5498 $current_contract = 0;
5499 while ($obj = $db->fetch_object($resql)) {
5500 if (empty($current_contract) || $current_contract == $obj->cid) {
5501 $currentRank++;
5502 } else {
5503 $currentRank = 1;
5504 }
5505
5506 $sqlUpd = "UPDATE ".$db->prefix()."contratdet SET rang=".(int) $currentRank." WHERE rowid=".(int) $obj->cdid;
5507 $resultstring = '.';
5508 print $resultstring;
5509 $resqlUpd = $db->query($sqlUpd);
5510 if (!$resqlUpd) {
5511 dol_print_error($db);
5512 $error++;
5513 }
5514
5515 $current_contract = $obj->cid;
5516 }
5517 } else {
5518 $error++;
5519 }
5520 if (!$error) {
5521 $db->commit();
5522 } else {
5523 $db->rollback();
5524 }
5525
5526 print '</td></tr>';
5527
5528 if (!$resultstring) {
5529 print '<tr class="trforrunsql" style=""><td class="wordbreak" colspan="4">'.$langs->trans("NothingToDo")."</td></tr>\n";
5530 }
5531}
5532
5539{
5540 global $db, $langs;
5541
5542 $lock = getDolGlobalInt('MIGRATION_FLAG_INVOICE_MODELS_V20');
5543
5544 $firstInstallVersion = getDolGlobalString('MAIN_VERSION_FIRST_INSTALL', DOL_VERSION);
5545 $migrationNeeded = (versioncompare(explode('.', $firstInstallVersion, 3), array(20, 0, -5)) < 0 && !$lock);
5546
5547 print '<tr class="trforrunsql"><td colspan="4">';
5548 print '<b>'.$langs->trans('InvoiceExportModelsMigration')."</b>: \n";
5549
5550 if (! $migrationNeeded) {
5551 print $langs->trans("AlreadyDone");
5552 print '</td></tr>';
5553 dolibarr_set_const($db, 'MIGRATION_FLAG_INVOICE_MODELS_V20', 1, 'chaine', 0, 'To flag the upgrade of invoice template has been set', 0);
5554 return;
5555 }
5556
5557
5558 $db->begin();
5559
5560 $sql1 = "UPDATE ".$db->prefix()."export_model SET type = 'facture_0' WHERE type = 'facture_1'";
5561
5562 $resql1 = $db->query($sql1);
5563
5564 if (! $resql1) {
5565 dol_print_error($db);
5566 $db->rollback();
5567 print '</td></tr>';
5568 return;
5569 }
5570
5571 $modified1 = $db->affected_rows($resql1);
5572
5573 print str_repeat('.', $modified1);
5574
5575 $db->free($resql1);
5576
5577 $sql2 = "UPDATE ".$db->prefix()."export_model SET type = 'facture_1' WHERE type = 'facture_2'";
5578
5579 $resql2 = $db->query($sql2);
5580
5581 if (! $resql2) {
5582 dol_print_error($db);
5583 $db->rollback();
5584 print '</td></tr>';
5585 return;
5586 }
5587
5588 $modified2 = $db->affected_rows($resql2);
5589
5590 print str_repeat('.', $modified2);
5591
5592 $db->free($resql2);
5593
5594 if (empty($modified1 + $modified2)) {
5595 print $langs->trans('NothingToDo');
5596 }
5597
5598 $db->commit();
5599
5600 dolibarr_set_const($db, 'MIGRATION_FLAG_INVOICE_MODELS_V20', 1, 'chaine', 0, 'To flag the upgrade of invoice template has been set', 0);
5601
5602 echo '</td></tr>';
5603}
5604
5612{
5613 global $db, $langs;
5614
5615 $error = 0;
5616 $resultstring = '';
5617 $bookKeepingAddon = '';
5618
5619 // For the moment we set the numbering rule to neon (the rule argon has a lot of critical bugs to fix first).
5620 if (getDolGlobalString('BOOKKEEPING_ADDON') == '') {
5621 dolibarr_set_const($db, 'BOOKKEEPING_ADDON', 'mod_bookkeeping_neon', 'chaine', 0, '', $entity);
5622 $bookKeepingAddon = 'mod_bookkeeping_neon';
5623 }
5624
5625 print '<tr class="trforrunsql"><td colspan="4">';
5626 print '<b>'.$langs->trans('MigrationAccountancyBookkeeping')."</b><br>\n";
5627
5628 // TODO
5629 if ($bookKeepingAddon === 'mod_bookkeeping_argon') {
5630 $db->begin();
5631
5632 $sql = "SELECT DISTINCT YEAR(doc_date) as doc_year, MONTH(doc_date) as doc_month, code_journal, piece_num FROM ".$db->prefix()."accounting_bookkeeping";
5633 $sql .= " WHERE ref IS NULL AND entity = ".((int) $entity);
5634 $sql .= " ORDER BY doc_year, doc_month, code_journal, piece_num";
5635
5636 $resql = $db->query($sql);
5637
5638 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php';
5639 $bookkeeping = new BookKeeping($db);
5640 if ($resql) {
5641 while ($obj = $db->fetch_object($resql)) {
5642 $bookkeeping->doc_date = dol_mktime(0, 0, 0, $obj->doc_month, 1, $obj->doc_year);
5643 $bookkeeping->code_journal = $obj->code_journal;
5644 $ref = $bookkeeping->getNextNumRef();
5645
5646 $sqlUpd = "UPDATE ".$db->prefix()."accounting_bookkeeping SET ref = '".$db->escape($ref)."' WHERE piece_num = '".$db->escape($obj->piece_num)."' AND entity = ".((int) $entity);
5647 $resultstring = '.';
5648 print $resultstring;
5649 $resqlUpd = $db->query($sqlUpd);
5650 if (!$resqlUpd) {
5651 dol_print_error($db);
5652 $error++;
5653 }
5654 }
5655 } else {
5656 $error++;
5657 }
5658
5659 if (!$error) {
5660 $db->commit();
5661 } else {
5662 $db->rollback();
5663 }
5664 }
5665
5666 print '</td></tr>';
5667
5668 if (!$resultstring) {
5669 print '<tr class="trforrunsql" style=""><td class="wordbreak" colspan="4">'.$langs->trans("NothingToDo")."</td></tr>\n";
5670 }
5671}
5672
5679{
5680 global $conf, $db, $langs;
5681
5682 print '<tr class="trforrunsql"><td colspan="4">';
5683 print '<b>'.$langs->trans('MigrationApiRestTokens')."</b>:\n";
5684
5685 $error = 0;
5686 $nbofmigration = 0;
5687 $allexistingtokens = array();
5688
5689 $db->begin();
5690
5691 $sqlforalltokens = "SELECT oat.tokenstring";
5692 $sqlforalltokens .= " FROM ".$db->prefix()."oauth_token AS oat";
5693 $sqlforalltokens .= " WHERE oat.service = 'dolibarr_rest_api'";
5694
5695 $resalltoken = $db->query($sqlforalltokens);
5696
5697 if ($resalltoken) {
5698 while ($tokenobj = $db->fetch_object($resalltoken)) {
5699 $allexistingtokens[] = dolDecrypt($tokenobj->tokenstring);
5700 }
5701 } else {
5702 $error++;
5703 dol_print_error($db);
5704 $db->rollback();
5705 }
5706
5707 if (!$error) {
5708 $sql = "SELECT 'dolibarr_rest_api' AS service, u.api_key AS tokenstring, u.rowid AS fk_user, u.entity";
5709 $sql .= " FROM ".MAIN_DB_PREFIX."user AS u";
5710 $sql .= " WHERE u.api_key IS NOT NULL AND u.api_key <> ''";
5711
5712 $result = $db->query($sql);
5713
5714 if ($result) {
5715 $tmpuser = new User($db);
5716
5717 while ($obj = $db->fetch_object($result)) {
5718 if (!in_array(dolDecrypt($obj->tokenstring), $allexistingtokens)) {
5719 // Load the object of the user of token so we can get the API_COUNT_CALL
5720 unset($tmpuser->conf);
5721 $tmpuser->conf = new stdClass();
5722 $tmpuser->fetch((int) $obj->fk_user, '', '', 1, ($obj->entity ? $obj->entity : $conf->entity));
5723
5724 $sqlforinsert = "INSERT INTO ".MAIN_DB_PREFIX."oauth_token (service, tokenstring, fk_user, datec, entity, apicount_total)";
5725 $sqlforinsert .= " VALUES ('".$db->escape($obj->service)."', '".$db->escape(dolEncrypt(dolDecrypt($obj->tokenstring)))."', ";
5726 $sqlforinsert .= ((int) $obj->fk_user).", '".$db->idate(dol_now())."', ".((int) $obj->entity).", ";
5727 $sqlforinsert .= getDolUserInt('API_COUNT_CALL', 0, $tmpuser);
5728 $sqlforinsert .= ")";
5729
5730 $insertresult = $db->query($sqlforinsert);
5731 if (!$insertresult) {
5732 $error++;
5733 dol_print_error($db);
5734 } else {
5735 $nbofmigration++;
5736 }
5737 }
5738 }
5739
5740 if (!$error) {
5741 $db->commit();
5742 } else {
5743 $db->rollback();
5744 }
5745 } else {
5746 dol_print_error($db);
5747 $db->rollback();
5748 }
5749 }
5750
5751 if (!$nbofmigration) {
5752 print $langs->trans("NothingToDo")."\n";
5753 } else {
5754 print $langs->trans('MigratedTokens', $nbofmigration);
5755 }
5756 print '</td></tr>';
5757}
5758
5759
5768{
5769 global $conf, $db, $langs;
5770
5771 include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
5772 include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5773
5774 print '<tr class="trforrunsql"><td colspan="4">';
5775 print '<b>'.$langs->trans('InitAHMACKeyForBlockedLog')."</b>:\n";
5776
5777 $db->begin();
5778
5779 // Create HMAC if it does not exists yet
5780 $hmac_encoded_secret_key = getDolGlobalString('BLOCKEDLOG_HMAC_KEY');
5781 if (empty($hmac_encoded_secret_key)) {
5782 // Add key
5783 $randomsecret = bin2hex(random_bytes(32)); // 64 char hex - 256 bits
5784
5785 $hmac_secret_key = 'BLOCKEDLOGHMAC'.$randomsecret; // Example: 'BLOCKEDLOGHMACY3Ewx37RXbSd8gL9JV8p7Wqw7qvq2K2A'
5786
5787 $result = dolibarr_set_const($db, 'BLOCKEDLOG_HMAC_KEY', $hmac_secret_key, 'chaine', 0, 'The secret key for HMAC used for blockedlog record', $conf->entity); // Will encrypt the value using dolCrypt and store it.
5788
5789 if ($result < 0) {
5790 dol_print_error($db);
5791 $db->rollback();
5792
5793 print '</td></tr>';
5794 return -1;
5795 }
5796
5797 print $langs->trans('Done');
5798 } elseif (!preg_match('/^(dolcrypt|dolobfuscation)/', $hmac_encoded_secret_key)) {
5799 // The value is stored in clear, without any prefix. This happens on instances migrated from a
5800 // version that stored it unencrypted. dolDecrypt() returns such a value unchanged, so the test
5801 // below used to pass and the value was left in clear, which then breaks getClearHMACSecretKey().
5802 // Store the same key again so it gets encrypted, without changing the key itself.
5803 $result = dolibarr_set_const($db, 'BLOCKEDLOG_HMAC_KEY', $hmac_encoded_secret_key, 'chaine', 0, 'The secret key for HMAC used for blockedlog record', $conf->entity);
5804 if ($result < 0) {
5805 dol_print_error($db);
5806 $db->rollback();
5807
5808 print '</td></tr>';
5809 return -1;
5810 }
5811 print $langs->trans('Done')." (BLOCKEDLOG_HMAC_KEY was stored in clear, it has been encrypted)\n";
5812 } else {
5813 // Decode the HMAC key
5814 $hmac_secret_key = dolDecrypt($hmac_encoded_secret_key);
5815
5816 if (! preg_match('/^BLOCKEDLOGHMAC/', $hmac_secret_key)) {
5817 print 'Error: Failed to decode the crypted value of the parameter BLOCKEDLOG_HMAC_KEY using the $dolibarr_main_crypt_key. A value was found in config parameters in database but decoding failed. May be the database data were restored onto another environment and the coding/decoding key $dolibarr_main_dolcrypt_key was not restored with the same value in conf.php file.';
5818 print 'Restore the value of $dolibarr_main_crypt_key that was used for encryption in database and restart the migration.';
5819 print 'If you don\'t use the Unalterable Log module, you can also remove the BLOCKEDLOG_HMAC_KEY entry from llx_const table. If you use the Unalterable Log, this is not possible because this will invalidate all past record.';
5820 $db->rollback();
5821
5822 print '</td></tr>';
5823 return -1;
5824 }
5825
5826 print $langs->trans("NothingToDo")."\n";
5827 }
5828
5829 $db->commit();
5830
5831 print '</td></tr>';
5832 return 1;
5833}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
run_sql($sqlfile, $silent=1, $entity=0, $usesavepoint=1, $handler='', $okerror='default', $linelengthlimit=32768, $nocommentremoval=0, $offsetforchartofaccount=0, $colspan=0, $onlysqltoimportwebsite=0, $database='')
Launch a sql file.
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
versioncompare($versionarray1, $versionarray2)
Compare 2 versions (stored into 2 arrays), to know if a version (a,b,c) is lower than (x,...
Definition admin.lib.php:72
migrate_blockedlog_add_end_file()
Migrate an old database to add the .end flag.
Class to manage Blocked Log.
Class to manage Ledger (General Ledger and Subledger)
Class to manage line orders.
Class to manage lines of contracts.
Class to manage invoices.
Class to manage invoice lines.
Class of the module paid holiday.
Class to manage hooks.
Parent class for log handlers.
static liste_modeles($db, $maxfilenamelength=0)
Return list of active generation modules.
static liste_modeles($db, $maxfilenamelength=0)
Return list of active generation modules.
static liste_modeles($db, $maxfilenamelength=0)
Return list of active generation modules.
Class to manage order lines.
Class with list of lots and properties.
Class to manage commercial proposal lines.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
global $mysoc
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
$conffile
dol_copy($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=0)
Copy a file to another file.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_move_dir($srcdir, $destdir, $overwriteifexists=1, $indexdatabase=1, $renamedircontent=1)
Move a directory into another name.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayreplacement=null, $excludesubdir=0, $excludefileext=null, $excludearchivefiles=0)
Copy a dir to another dir.
dol_is_file($pathoffile)
Return if path is a file.
dol_is_dir($folder)
Test if filename is a directory.
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
getDoliDBInstance($type, $host, $user, $pass, $name, $port, $forcenew=false)
Return a DoliDB instance (database handler).
getDolUserInt($key, $default=0, $tmpuser=null)
Return Dolibarr user constant int value.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
pHeader($subtitle, $next, $action='set', $param='', $forcejqueryurl='', $csstable='main-inside')
Show HTML header of install pages.
Definition inc.php:553
pFooter($nonext=0, $setuplang='', $jscheckfunction='', $withpleasewait=0, $morehtml='')
Print HTML footer of install pages.
Definition inc.php:647
dolibarr_install_syslog($message, $level=LOG_DEBUG)
Log function for install pages.
Definition inc.php:711
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $notused, $price_base_type, $info_bits, $type, $seller=null, $localtaxes_array=[], $progress=100, $multicurrency_tx=1, $pu_devise=0, $multicurrency_code='')
Calculate totals (net, vat, ...) of a line.
Definition price.lib.php:90
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as p p num_paiement as f pf amount as amount
Definition receipt.php:494
dol_decode($chain, $key='1')
Decode a base 64 encoded + specific delta change.
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='', $obfuscationmode='dolcrypt')
Encode a string with a symmetric encryption.
migrate_supplier_prices_permissions($db, $langs, $conf)
Grant the "supplier prices" advanced permissions introduced in 23.0 (product/service read_supplier_pr...
if($db !==null && $db->connected) if( $ret migrate_paiements)($db, $langs, $conf)
Records payment links for an invoice in a join table (link n<-->n for payments<-->invoices)
Definition upgrade2.php:942
migrate_links_transfert($db, $langs, $conf)
Function to migrate links into llx_bank_url.
migrate_paiements_orphelins_1($db, $langs, $conf)
Repair orphan payments (lost relations due to bugs) Query to check if there are still orphans: select...
migrate_user_rights_entity($db, $langs, $conf)
Migrate to add entity value into llx_user_rights.
migrate_reload_modules($db, $langs, $conf, $listofmodule=array(), $force=0)
Disable/Re-enable features modules.
migrate_contracts_date3($db, $langs, $conf)
Mise a jour des dates de creation de contrat.
migrate_restore_missing_links($db, $langs, $conf)
Migration du champ fk_remise_except dans llx_facturedet doit correspondre a Link in llx_societe_remis...
migrate_rename_directories($db, $langs, $conf, $oldname, $newname)
Migration directory.
migrate_project_task_actors($db, $langs, $conf)
Migration de la table llx_projet_task_actors vers llx_element_contact.
migrate_holiday_path()
Migrate file from old path to new one for users.
migrate_commande_deliveryaddress($db, $langs, $conf)
Migration du champ fk_adresse_livraison dans expedition 2.6 -> 2.7.
migrate_project_user_resp($db, $langs, $conf)
Migration du champ fk_user_resp de llx_projet vers llx_element_contact.
migrate_contracts_open($db, $langs, $conf)
Reopen the contracts that have at least one line that is not closed (/completed).
migrate_shipping_delivery($db, $langs, $conf)
Migrate link stored into fk_expedition into llx_element_element.
migrate_delete_old_dir($db, $langs, $conf)
Remove deprecated directories.
migrate_accountingbookkeeping(int $entity)
Migrate Ref in bookkeeping lines.
migrate_price_propal($db, $langs, $conf)
Update total of proposal lines.
migrate_stocks($db, $langs, $conf)
Migration of the stock field in the Products table.
migrate_paiementfourn_facturefourn($db, $langs, $conf)
Factures fournisseurs.
migrate_contacts_socialnetworks()
Migrate contacts fields facebook and co to socialnetworks Can be called only when version is 10....
migrate_customerorder_shipping($db, $langs, $conf)
Migrate order ref_customer and date_delivery fields to llx_expedition.
migrate_detail_livraison($db, $langs, $conf)
Migrate the Order Details in the Delivery Details.
migrate_remise_except_entity($db, $langs, $conf)
Migrate to add entity value into llx_societe_remise_except.
migrate_paiements_orphelins_2($db, $langs, $conf)
Repair orphan payments (lost relations due to bugs) Query to check if there are still orphans: select...
migrate_price_contrat($db, $langs, $conf)
Update total of contract lines.
migrate_users_socialnetworks()
Migrate users fields facebook and co to socialnetworks.
migrate_user_photospath2()
Migrate file from old path users/99/file.jpg into users/99/photos/file.jpg.
migrate_contracts_det($db, $langs, $conf)
Update the contracts (Contract Management + Contract Detail)
migrate_get_rights_def_id($db, $module, $perms, $subperms)
Return the permission id (llx_rights_def.id) matching a module/perms/subperms triplet,...
migrate_price_facture($db, $langs, $conf)
Update total of invoice lines.
migrate_usergroup_rights_entity($db, $langs, $conf)
Migrate to add entity value into llx_usergroup_rights.
migrate_relationship_tables($db, $langs, $conf, $table, $fk_source, $sourcetype, $fk_target, $targettype)
Migration des tables de relation.
migrate_modeles($db, $langs, $conf)
Mise a jour des modeles selectionnes.
migrate_reset_blocked_log($db, $langs, $conf)
Migrate to reset the blocked log for V7+ algorithm.
migrate_mode_reglement($db, $langs, $conf)
Migrate link stored into fk_mode_reglement.
migrate_export_import_profiles($mode='export')
Migrate export and import profiles to fix field name that was renamed.
migrate_contracts_date2($db, $langs, $conf)
Update contracts with date min real if service date is lower.
migrate_commande_expedition($db, $langs, $conf)
Relations between the Shipping and Client Order in the table llx_co_exp.
migrate_actioncomm_element($db, $langs, $conf)
Migrate link stored into fk_xxxx into fk_element and elementtype.
migrate_blockedlog_add_hmac_key()
Add the HMAC key for blockedlog v2+ Note that this is used on old version only.
migrate_productlot_path()
Migrate file from old path to new one for lot path.
migrate_user_photospath()
Migrate file from old path to new one for users.
migrate_invoice_export_models()
Invoice exports been shifted (facture_1 => facture_0, facture_2 => facture_1) in version 20,...
migrate_thirdparties_socialnetworks()
Migrate thirdparties fields facebook and co to socialnetworks Can be called only when version is 10....
migrate_event_assignement($db, $langs, $conf)
Migrate event assignment to owner.
migrate_clean_association($db, $langs, $conf)
Delete duplicates in table categorie_association.
migrate_commande_livraison($db, $langs, $conf)
Correspondence of the deliveries and the Customer Orders in the table llx_co_liv.
migrate_event_assignement_contact($db, $langs, $conf)
Migrate event assignment to owner.
migrate_contracts_date1($db, $langs, $conf)
Update missing Contract Dates.
migrate_remise_entity($db, $langs, $conf)
Migrate to add entity value into llx_societe_remise.
migrate_contractdet_rank()
Migrate Rank into contract line.
migrate_menus($db, $langs, $conf)
Migration of menus (use only 1 table instead of 3) 2.6 -> 2.7.
migrate_categorie_association($db, $langs, $conf)
Migrate categorie association.
migrate_delete_old_files($db, $langs, $conf)
Delete deprecated files.
migrate_price_commande_fournisseur($db, $langs, $conf)
Update total of purchase order lines.
migrate_element_time($db, $langs, $conf)
Migrate duration in seconds.
migrate_members_socialnetworks()
Migrate members fields facebook and co to socialnetworks Can be called only when version is 10....
migrate_reload_menu($db, $langs, $conf)
Reload SQL menu file (if dynamic menus, if modified by version)
migrate_price_commande($db, $langs, $conf)
Update total of sales order lines.
migrate_shipping_delivery2($db, $langs, $conf)
We try to complete field ref_customer and date_delivery that are empty into llx_livraison.
migrate_apiresttokens()
Migrate API key in oauth_token table.