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