dolibarr 23.0.3
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 MDW <mdeweerd@users.noreply.github.com>
9 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
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;
70require_once $dolibarr_main_document_root.'/compta/facture/class/facture.class.php';
71require_once $dolibarr_main_document_root.'/comm/propal/class/propal.class.php';
72require_once $dolibarr_main_document_root.'/contrat/class/contrat.class.php';
73require_once $dolibarr_main_document_root.'/commande/class/commande.class.php';
74require_once $dolibarr_main_document_root.'/fourn/class/fournisseur.commande.class.php';
75require_once $dolibarr_main_document_root.'/core/lib/price.lib.php';
76require_once $dolibarr_main_document_root.'/core/class/menubase.class.php';
77require_once $dolibarr_main_document_root.'/core/lib/admin.lib.php';
78require_once $dolibarr_main_document_root.'/core/lib/files.lib.php';
79require_once $dolibarr_main_document_root.'/user/class/user.class.php';
80
81global $langs;
82
83
84$error = 0;
85
86
87// This page can be long. We increase the allowed delay, but this does not work when we are in safe_mode.
88$err = error_reporting();
89error_reporting(0);
90if (getDolGlobalInt('MAIN_OVERRIDE_TIME_LIMIT')) {
91 @set_time_limit(getDolGlobalInt('MAIN_OVERRIDE_TIME_LIMIT'));
92} else {
93 @set_time_limit(600);
94}
95error_reporting($err);
96
97$setuplang = GETPOST("selectlang", 'aZ09', 3) ? GETPOST("selectlang", 'aZ09', 3) : 'auto';
98$langs->setDefaultLang($setuplang);
99$versionfrom = GETPOST("versionfrom", 'alpha', 3) ? GETPOST("versionfrom", 'alpha', 3) : (empty($argv[1]) ? '' : $argv[1]);
100$versionto = GETPOST("versionto", 'alpha', 3) ? GETPOST("versionto", 'alpha', 3) : (empty($argv[2]) ? '' : $argv[2]);
101$enablemodules = GETPOST("enablemodules", 'alpha', 3) ? GETPOST("enablemodules", 'alpha', 3) : (empty($argv[3]) ? '' : $argv[3]);
102
103$langs->loadLangs(array("admin", "install", "bills", "suppliers"));
104
105if ($dolibarr_main_db_type == 'mysqli') {
106 $choix = 1;
107}
108if ($dolibarr_main_db_type == 'pgsql') {
109 $choix = 2;
110}
111if ($dolibarr_main_db_type == 'mssql') {
112 $choix = 3;
113}
114
115
116dolibarr_install_syslog("--- upgrade2: entering upgrade2.php page ".$versionfrom." ".$versionto." ".$enablemodules);
117if (!is_object($conf)) {
118 dolibarr_install_syslog("upgrade2: conf file not initialized", LOG_ERR);
119}
120
121
122
123/*
124 * View
125 */
126
127if ((!$versionfrom || preg_match('/version/', $versionfrom)) && (!$versionto || preg_match('/version/', $versionto))) {
128 print 'Error: Parameter versionfrom or versionto missing or having a bad format.'."\n";
129 print 'Upgrade must be ran from command line with parameters or called from page install/index.php (like a first install)'."\n";
130 // Test if batch mode
131 $sapi_type = php_sapi_name();
132 $script_file = basename(__FILE__);
133 if (substr($sapi_type, 0, 3) == 'cli') {
134 print 'Syntax from command line: '.$script_file." x.y.z a.b.c [MAIN_MODULE_NAME1_TO_ENABLE,MAIN_MODULE_NAME2_TO_ENABLE...]\n";
135 print 'Example, upgrade from 19 to 20: '.$script_file." 19.0.0 20.0.0\n";
136 print 'Example, enable a module only: '.$script_file." 0.0.0 0.0.0 MAIN_MODULE_Adherent\n";
137 print "\n";
138 }
139 exit;
140}
141
142pHeader('', 'step5', GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'upgrade', 'versionfrom='.$versionfrom.'&versionto='.$versionto, '', 'main-inside main-inside-borderbottom');
143
144
145if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ09'))) {
146 print '<h3><img class="valignmiddle inline-block paddingright" src="../public/theme/common/database.svg" width="20" alt="Database"> ';
147 print '<span class="inline-block valignmiddle">'.$langs->trans('DataMigration').'</span></h3>';
148
149 print '<table class="centpercent">';
150
151 // If password is encoded, we decode it
152 if ((!empty($dolibarr_main_db_pass) && preg_match('/(crypted|dolcrypt):/i', (string) $dolibarr_main_db_pass)) || !empty($dolibarr_main_db_encrypted_pass)) {
153 require_once $dolibarr_main_document_root.'/core/lib/security.lib.php';
154 if (!empty($dolibarr_main_db_pass) && preg_match('/crypted:/i', $dolibarr_main_db_pass)) {
155 $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', (string) $dolibarr_main_db_pass);
156 $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
157 $dolibarr_main_db_pass = dol_decode((string) $dolibarr_main_db_pass);
158 } elseif (preg_match('/dolcrypt:/i', (string) $dolibarr_main_db_pass)) {
159 $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
160 $dolibarr_main_db_pass = dolDecrypt((string) $dolibarr_main_db_pass);
161 } else {
162 $dolibarr_main_db_pass = dol_decode((string) $dolibarr_main_db_encrypted_pass);
163 }
164 }
165
166 // $conf is already instantiated inside inc.php
167 $conf->db->type = $dolibarr_main_db_type;
168 $conf->db->host = $dolibarr_main_db_host;
169 $conf->db->port = $dolibarr_main_db_port;
170 $conf->db->name = $dolibarr_main_db_name;
171 $conf->db->user = $dolibarr_main_db_user;
172 $conf->db->pass = $dolibarr_main_db_pass;
173
174 $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, (int) $conf->db->port);
175
176 if (!$db->connected) {
177 print '<tr><td colspan="4">'.$langs->trans("ErrorFailedToConnectToDatabase", $conf->db->name).'</td><td class="right">'.$langs->trans('Error').'</td></tr>';
178 dolibarr_install_syslog('upgrade2: failed to connect to database :'.$conf->db->name.' on '.$conf->db->host.' for user '.$conf->db->user, LOG_ERR);
179 $error++;
180 }
181
182 if (!$error) {
183 if ($db->database_selected) {
184 dolibarr_install_syslog('upgrade2: database connection successful :'.$dolibarr_main_db_name);
185 } else {
186 $error++;
187 }
188 }
189
190 if (empty($dolibarr_main_db_encryption)) {
191 $dolibarr_main_db_encryption = 0;
192 }
193 $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption;
194 if (empty($dolibarr_main_db_cryptkey)) {
195 $dolibarr_main_db_cryptkey = '';
196 }
197 $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey;
198
199 // Load global conf
200 $conf->setValues($db);
201
202
203 // Reforce log activation (samecode than into the inc.php)
204 $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1;
205 $conf->modules['syslog'] = 'syslog';
206 $conf->global->SYSLOG_LEVEL = constant('LOG_DEBUG');
207 if (!defined('SYSLOG_HANDLERS')) {
208 define('SYSLOG_HANDLERS', '["mod_syslog_file"]');
209 }
210 if (!defined('SYSLOG_FILE')) { // To avoid warning on systems with constant already defined
211 if (@is_writable('/tmp')) {
212 define('SYSLOG_FILE', '/tmp/dolibarr_install.log');
213 } elseif (!empty($_ENV["TMP"]) && @is_writable($_ENV["TMP"])) {
214 define('SYSLOG_FILE', $_ENV["TMP"].'/dolibarr_install.log');
215 } elseif (!empty($_ENV["TEMP"]) && @is_writable($_ENV["TEMP"])) {
216 define('SYSLOG_FILE', $_ENV["TEMP"].'/dolibarr_install.log');
217 } elseif (@is_writable('../../../../') && @file_exists('../../../../startdoliwamp.bat')) {
218 define('SYSLOG_FILE', '../../../../dolibarr_install.log'); // For DoliWamp
219 } elseif (@is_writable('../../')) {
220 define('SYSLOG_FILE', '../../dolibarr_install.log'); // For others
221 }
222 //print 'SYSLOG_FILE='.SYSLOG_FILE;exit;
223 }
224 if (defined('SYSLOG_FILE')) {
225 $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
226 }
227 if (!defined('SYSLOG_FILE_NO_ERROR')) {
228 define('SYSLOG_FILE_NO_ERROR', 1);
229 }
230 // We init log handler for install
231 $handlers = array('mod_syslog_file');
232 foreach ($handlers as $handler) {
233 $file = DOL_DOCUMENT_ROOT.'/core/modules/syslog/'.$handler.'.php';
234 if (!file_exists($file)) {
235 throw new Exception('Missing log handler file '.$handler.'.php');
236 }
237
238 require_once $file;
239 $loghandlerinstance = new $handler();
240 if (!$loghandlerinstance instanceof LogHandler) {
241 throw new Exception('Log handler does not extend LogHandler');
242 }
243
244 if (empty($conf->loghandlers[$handler])) {
245 $conf->loghandlers[$handler] = $loghandlerinstance;
246 }
247 }
248
249
250 $listofentities = array(1);
251
252 // Create the global $hookmanager object
253 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
254 $hookmanager = new HookManager($db);
255 $hookmanager->initHooks(array('upgrade2'));
256
257 $parameters = array('versionfrom' => $versionfrom, 'versionto' => $versionto);
258 $object = new stdClass();
259 $action = "upgrade";
260 $reshook = $hookmanager->executeHooks('doUpgradeBefore', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
261 if ($reshook >= 0 && is_array($hookmanager->resArray)) {
262 // Example: $hookmanager->resArray = array(2, 3, 10);
263 $listofentities = array_unique(array_merge($listofentities, $hookmanager->resArray));
264 }
265
266
267 /***************************************************************************************
268 *
269 * Migration of data
270 *
271 ***************************************************************************************/
272
273 dol_syslog("Process upgrade2 (step common to all entities)");
274
275 // Force to execute this at begin to avoid the new core code into Dolibarr to be broken.
276 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN birth date';
277 $db->query($sql, 1);
278 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN dateemployment date';
279 $db->query($sql, 1);
280 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN dateemploymentend date';
281 $db->query($sql, 1);
282 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN default_range integer';
283 $db->query($sql, 1);
284 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN default_c_exp_tax_cat integer';
285 $db->query($sql, 1);
286 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN langs varchar(24)';
287 $db->query($sql, 1);
288 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN fieldcomputed text';
289 $db->query($sql, 1);
290 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN fielddefault varchar(255)';
291 $db->query($sql, 1);
292 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX."extrafields ADD COLUMN enabled varchar(255) DEFAULT '1'";
293 $db->query($sql, 1);
294 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN help text';
295 $db->query($sql, 1);
296 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user_rights ADD COLUMN entity integer DEFAULT 1 NOT NULL';
297 $db->query($sql, 1);
298
299
300 $db->begin();
301
302 foreach ($listofentities as $entity) {
303 dol_syslog("Process upgrade2 (step a) for entity ".$entity);
304
305 // Set $conf context for entity
306 $conf->setEntityValues($db, $entity);
307
308 // Reset forced setup after the setValues
309 if (defined('SYSLOG_FILE')) {
310 $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
311 }
312
313 $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1; // Add also log into conf->logbuffer.
314
315 $versiontoarray = array();
316 $versionranarray = array();
317
318 dol_syslog("Process upgrade2 (step b) for entity ".$entity);
319
320 if (!$error) {
321 if (count($listofentities) > 1) {
322 print '<tr><td colspan="4">*** '.$langs->trans("Entity").' '.$entity.'</td></tr>'."\n";
323 }
324
325 // Current version is $conf->global->MAIN_VERSION_LAST_UPGRADE
326 // Version to install is DOL_VERSION
327 $dolibarrlastupgradeversionarray = preg_split('/[\.-]/', getDolGlobalString('MAIN_VERSION_LAST_UPGRADE', getDolGlobalString('MAIN_VERSION_LAST_INSTALL')));
328
329 // Chaque action de migration doit renvoyer une ligne sur 4 colonnes avec
330 // dans la 1ere colonne, la description de l'action a faire
331 // dans la 4eme colonne, le texte 'OK' si fait ou 'AlreadyDone' si rien n'est fait ou 'Error'
332
333 $versiontoarray = explode('.', $versionto);
334 $versionranarray = explode('.', DOL_VERSION);
335
336 $afterversionarray = explode('.', '2.0.0');
337 $beforeversionarray = explode('.', '2.7.9');
338 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
339 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
340
341 // Script pour V2 -> V2.1
342 migrate_paiements($db, $langs, $conf);
343
344 migrate_contracts_det($db, $langs, $conf);
345
346 migrate_contracts_date1($db, $langs, $conf);
347
348 migrate_contracts_date2($db, $langs, $conf);
349
350 migrate_contracts_date3($db, $langs, $conf);
351
352 migrate_contracts_open($db, $langs, $conf);
353
354 migrate_modeles($db, $langs, $conf);
355
356 migrate_price_propal($db, $langs, $conf);
357
358 migrate_price_commande($db, $langs, $conf);
359
360 migrate_price_commande_fournisseur($db, $langs, $conf);
361
362 migrate_price_contrat($db, $langs, $conf);
363
364 migrate_paiementfourn_facturefourn($db, $langs, $conf);
365
366
367 // Script pour V2.1 -> V2.2
368 migrate_paiements_orphelins_1($db, $langs, $conf);
369
370 migrate_paiements_orphelins_2($db, $langs, $conf);
371
372 migrate_links_transfert($db, $langs, $conf);
373
374
375 // Script pour V2.2 -> V2.4
376 migrate_commande_expedition($db, $langs, $conf);
377
378 migrate_commande_livraison($db, $langs, $conf);
379
380 migrate_detail_livraison($db, $langs, $conf);
381
382
383 // Script pour V2.5 -> V2.6
384 migrate_stocks($db, $langs, $conf);
385
386
387 // Script pour V2.6 -> V2.7
388 migrate_menus($db, $langs, $conf);
389
390 migrate_commande_deliveryaddress($db, $langs, $conf);
391
392 migrate_restore_missing_links($db, $langs, $conf);
393
394 migrate_rename_directories($db, $langs, $conf, '/compta', '/banque');
395
396 migrate_rename_directories($db, $langs, $conf, '/societe', '/mycompany');
397 }
398
399 // Script for 2.8
400 $afterversionarray = explode('.', '2.7.9');
401 $beforeversionarray = explode('.', '2.8.9');
402 //print $versionto.' '.versioncompare($versiontoarray,$afterversionarray).' '.versioncompare($versiontoarray,$beforeversionarray);
403 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
404 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
405
406 migrate_price_facture($db, $langs, $conf); // Code of this function works for 2.8+ because need a field tva_tx
407
408 migrate_relationship_tables($db, $langs, $conf, 'co_exp', 'fk_commande', 'commande', 'fk_expedition', 'shipping');
409
410 migrate_relationship_tables($db, $langs, $conf, 'pr_exp', 'fk_propal', 'propal', 'fk_expedition', 'shipping');
411
412 migrate_relationship_tables($db, $langs, $conf, 'pr_liv', 'fk_propal', 'propal', 'fk_livraison', 'delivery');
413
414 migrate_relationship_tables($db, $langs, $conf, 'co_liv', 'fk_commande', 'commande', 'fk_livraison', 'delivery');
415
416 migrate_relationship_tables($db, $langs, $conf, 'co_pr', 'fk_propale', 'propal', 'fk_commande', 'commande');
417
418 migrate_relationship_tables($db, $langs, $conf, 'fa_pr', 'fk_propal', 'propal', 'fk_facture', 'facture');
419
420 migrate_relationship_tables($db, $langs, $conf, 'co_fa', 'fk_commande', 'commande', 'fk_facture', 'facture');
421
422 migrate_project_user_resp($db, $langs, $conf);
423
424 migrate_project_task_actors($db, $langs, $conf);
425 }
426
427 // Script for 2.9
428 $afterversionarray = explode('.', '2.8.9');
429 $beforeversionarray = explode('.', '2.9.9');
430 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
431 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
432
433 migrate_element_time($db, $langs, $conf);
434
435 migrate_customerorder_shipping($db, $langs, $conf);
436
437 migrate_shipping_delivery($db, $langs, $conf);
438
439 migrate_shipping_delivery2($db, $langs, $conf);
440 }
441
442 // Script for 3.0
443 $afterversionarray = explode('.', '2.9.9');
444 $beforeversionarray = explode('.', '3.0.9');
445 //if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
446 // No particular code
447 //}
448
449 // Script for 3.1
450 $afterversionarray = explode('.', '3.0.9');
451 $beforeversionarray = explode('.', '3.1.9');
452 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
453 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
454
455 migrate_rename_directories($db, $langs, $conf, '/rss', '/externalrss');
456
457 migrate_actioncomm_element($db, $langs, $conf);
458 }
459
460 // Script for 3.2
461 $afterversionarray = explode('.', '3.1.9');
462 $beforeversionarray = explode('.', '3.2.9');
463 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
464 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
465
466 migrate_price_contrat($db, $langs, $conf);
467
468 migrate_mode_reglement($db, $langs, $conf);
469
470 migrate_clean_association($db, $langs, $conf);
471 }
472
473 // Script for 3.3
474 $afterversionarray = explode('.', '3.2.9');
475 $beforeversionarray = explode('.', '3.3.9');
476 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
477 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
478
479 migrate_categorie_association($db, $langs, $conf);
480 }
481
482 // Script for 3.4
483 // No specific scripts
484
485 // Tasks to do always and only into last targeted version
486 $afterversionarray = explode('.', '3.6.9'); // target is after this
487 $beforeversionarray = explode('.', '3.7.9'); // target is before this
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
491 migrate_event_assignement($db, $langs, $conf);
492 }
493
494 // Scripts for 3.9
495 $afterversionarray = explode('.', '3.7.9');
496 $beforeversionarray = explode('.', '3.8.9');
497 //if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
498 // No particular code
499 //}
500
501 // Scripts for 4.0
502 $afterversionarray = explode('.', '3.9.9');
503 $beforeversionarray = explode('.', '4.0.9');
504 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
505 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
506
507 migrate_rename_directories($db, $langs, $conf, '/fckeditor', '/medias');
508 }
509
510 // Scripts for 5.0
511 $afterversionarray = explode('.', '4.0.9');
512 $beforeversionarray = explode('.', '5.0.9');
513 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
514 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
515
516 // Migrate to add entity value into llx_societe_remise
517 migrate_remise_entity($db, $langs, $conf);
518
519 // Migrate to add entity value into llx_societe_remise_except
520 migrate_remise_except_entity($db, $langs, $conf);
521 }
522
523 // Scripts for 6.0
524 $afterversionarray = explode('.', '5.0.9');
525 $beforeversionarray = explode('.', '6.0.9');
526 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
527 if (isModEnabled('multicompany')) {
528 global $multicompany_transverse_mode;
529
530 // Only if the transverse mode is not used
531 if (empty($multicompany_transverse_mode)) {
532 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
533
534 // Migrate to add entity value into llx_user_rights
535 migrate_user_rights_entity($db, $langs, $conf);
536
537 // Migrate to add entity value into llx_usergroup_rights
538 migrate_usergroup_rights_entity($db, $langs, $conf);
539 }
540 }
541 }
542
543 // Scripts for 7.0
544 $afterversionarray = explode('.', '6.0.9');
545 $beforeversionarray = explode('.', '7.0.9');
546 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
547 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
548
549 // Migrate contact association
550 migrate_event_assignement_contact($db, $langs, $conf);
551
552 migrate_reset_blocked_log($db, $langs, $conf);
553 }
554
555 // Scripts for 8.0
556 $afterversionarray = explode('.', '7.0.9');
557 $beforeversionarray = explode('.', '8.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_rename_directories($db, $langs, $conf, '/contracts', '/contract');
562 }
563
564 // Scripts for 9.0
565 $afterversionarray = explode('.', '8.0.9');
566 $beforeversionarray = explode('.', '9.0.9');
567 //if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
568 //migrate_user_photospath();
569 //}
570
571 // Scripts for 11.0
572 $afterversionarray = explode('.', '10.0.9');
573 $beforeversionarray = explode('.', '11.0.9');
574 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
575 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
576
581 }
582
583 // Scripts for 14.0
584 $afterversionarray = explode('.', '13.0.9');
585 $beforeversionarray = explode('.', '14.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
591 }
592
593 // Scripts for 16.0
594 $afterversionarray = explode('.', '15.0.9');
595 $beforeversionarray = explode('.', '16.0.9');
596 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
597 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
598
601 }
602
603 // Scripts for 17.0
604 $afterversionarray = explode('.', '16.0.9');
605 $beforeversionarray = explode('.', '17.0.9');
606 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
607 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
608
610 }
611
612 // Scripts for 18.0
613 $afterversionarray = explode('.', '17.0.9');
614 $beforeversionarray = explode('.', '18.0.9');
615 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
616 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
617
619 }
620
621 // Scripts for 19.0
622 /*
623 $afterversionarray = explode('.', '18.0.9');
624 $beforeversionarray = explode('.', '19.0.9');
625 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
626 }
627 */
628
629 // Scripts for 20.0
630 $afterversionarray = explode('.', '19.0.9');
631 $beforeversionarray = explode('.', '20.0.9');
632 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
633 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
634
636 }
637
638 // Scripts for 21.0
639 $afterversionarray = explode('.', '20.0.9');
640 $beforeversionarray = explode('.', '21.0.9');
641
642
643 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
644 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
645
647 }
648
649 // Scripts for 22.0
650 $afterversionarray = explode('.', '21.0.9');
651 $beforeversionarray = explode('.', '22.0.9');
652 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
653 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
654
656 }
657
658 // Scripts for 23.0
659 $afterversionarray = explode('.', '22.0.9');
660 $beforeversionarray = explode('.', '23.0.9');
661 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
662 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
663
665
667
669 }
670 }
671
672 // Code executed only if migration is LAST ONE. Must always be done.
673 if (versioncompare($versiontoarray, $versionranarray) >= 0 || versioncompare($versiontoarray, $versionranarray) <= -3) {
674 dol_syslog("Run migrate_... if migration is LAST ONE");
675
676 // 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)
677 $listofmodule = array(
678 'MAIN_MODULE_ACCOUNTING' => 'newboxdefonly',
679 'MAIN_MODULE_AGENDA' => 'newboxdefonly',
680 'MAIN_MODULE_BOM' => 'menuonly',
681 'MAIN_MODULE_BANQUE' => 'menuonly',
682 'MAIN_MODULE_BARCODE' => 'newboxdefonly',
683 'MAIN_MODULE_CRON' => 'newboxdefonly',
684 'MAIN_MODULE_COMMANDE' => 'newboxdefonly',
685 'MAIN_MODULE_BLOCKEDLOG' => 'noboxes',
686 'MAIN_MODULE_DON' => 'newboxdefonly',
687 'MAIN_MODULE_ECM' => 'newboxdefonly',
688 'MAIN_MODULE_EVENTORGANIZATION' => 'newboxdefonly',
689 'MAIN_MODULE_EXPENSEREPORT' => 'newboxdefonly',
690 'MAIN_MODULE_FACTURE' => 'newboxdefonly',
691 'MAIN_MODULE_FOURNISSEUR' => 'newboxdefonly',
692 'MAIN_MODULE_FICHEINTER' => 'newboxdefonly',
693 'MAIN_MODULE_HOLIDAY' => 'newboxdefonly',
694 'MAIN_MODULE_LOAN' => 'newboxdefonly',
695 'MAIN_MODULE_MARGIN' => 'menuonly',
696 'MAIN_MODULE_MRP' => 'menuonly',
697 'MAIN_MODULE_OPENSURVEY' => 'newboxdefonly',
698 'MAIN_MODULE_PARTNERSHIP' => 'newboxdefonly',
699 'MAIN_MODULE_PRINTING' => 'newboxdefonly',
700 'MAIN_MODULE_PRODUIT' => 'newboxdefonly',
701 'MAIN_MODULE_RECRUITMENT' => 'menuonly',
702 'MAIN_MODULE_RESOURCE' => 'noboxes',
703 'MAIN_MODULE_SALARIES' => 'newboxdefonly',
704 'MAIN_MODULE_SERVICE' => 'newboxdefonly',
705 'MAIN_MODULE_SYSLOG' => 'newboxdefonly',
706 'MAIN_MODULE_SOCIETE' => 'newboxdefonly',
707 'MAIN_MODULE_STRIPE' => 'menuonly',
708 'MAIN_MODULE_TICKET' => 'newboxdefonly',
709 'MAIN_MODULE_TAKEPOS' => 'newboxdefonly',
710 'MAIN_MODULE_USER' => 'newboxdefonly', //This one must be always done and only into last targeted version)
711 'MAIN_MODULE_VARIANTS' => 'newboxdefonly',
712 'MAIN_MODULE_WEBSITE' => 'newboxdefonly',
713 );
714
715 $result = migrate_reload_modules($db, $langs, $conf, $listofmodule);
716 if ($result < 0) {
717 $error++;
718 }
719
720 // Grant the supplier prices permissions added in 23.0 to users/groups that already have
721 // the matching product/service rights (ids resolved by name from the rights_def reloaded
722 // just above), so nobody loses access to supplier prices on upgrade. Idempotent.
723 $result = migrate_supplier_prices_permissions($db, $langs, $conf);
724 if ($result < 0) {
725 $error++;
726 }
727
728 // Reload menus (this must be always done, and only into last targeted version)
729 // This reload the auguria menu.To reload a dynamic menu defined into module descriptor, see previours step
730 $result = migrate_reload_menu($db, $langs, $conf);
731 if ($result < 0) {
732 $error++;
733 }
734 }
735
736 // Can force activation of some module during migration with parameter 'enablemodules=MAIN_MODULE_XXX,MAIN_MODULE_YYY,...'
737 // In most cases (online install or upgrade) $enablemodules is empty. Can be forced when ran from command line.
738 if (!$error && $enablemodules) {
739 // Reload modules (this must be always done and only into last targeted version)
740 $listofmodules = array();
741 $enablemodules = preg_replace('/enablemodules=/', '', $enablemodules);
742 $tmplistofmodules = explode(',', $enablemodules);
743 foreach ($tmplistofmodules as $value) {
744 $listofmodules[$value] = 'forceactivate';
745 }
746
747 $resultreloadmodules = migrate_reload_modules($db, $langs, $conf, $listofmodules, 1);
748 if ($resultreloadmodules < 0) {
749 $error++;
750 }
751 }
752
753
754 // Can call a dedicated external upgrade process with hook doUpgradeAfterDB()
755 if (!$error) {
756 $parameters = array('versionfrom' => $versionfrom, 'versionto' => $versionto, 'conf' => $conf);
757 $object = new stdClass();
758 $action = "upgrade";
759 $reshook = $hookmanager->executeHooks('doUpgradeAfterDB', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
760 if ($hookmanager->resNbOfHooks > 0) {
761 if ($reshook < 0) {
762 print '<tr><td colspan="4">';
763 print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: ';
764 print $hookmanager->error;
765 print "<!-- (".$reshook.") -->";
766 print '</td></tr>';
767 } else {
768 print '<tr class="trforrunsql"><td colspan="4">';
769 print '<b>'.$langs->trans('UpgradeExternalModule').' (DB)</b>: <span class="ok">OK</span>';
770 print "<!-- (".$reshook.") -->";
771 print '</td></tr>';
772 }
773 } else {
774 //if (!empty($conf->modules))
775 if (!empty($conf->modules_parts['hooks'])) { // If there is at least one module with one hook, we show message to say nothing was done
776 print '<tr class="trforrunsql"><td colspan="4">';
777 print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: '.$langs->trans("NodoUpgradeAfterDB");
778 print '</td></tr>';
779 }
780 }
781 }
782 }
783
784 print '</table>';
785
786 if (!$error) {
787 // Set constant to ask to remake a new ping to inform about upgrade (if ping was already done and OK)
788 $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
789 $db->query($sql, 1);
790 }
791
792 // We always commit.
793 // Process is designed so we can run it several times whatever is situation.
794 $db->commit();
795
796
797 /***************************************************************************************
798 *
799 * Migration of files
800 *
801 ***************************************************************************************/
802
803 foreach ($listofentities as $entity) {
804 // Set $conf context for entity
805 $conf->setEntityValues($db, $entity);
806 // Reset forced setup after the setValues
807 if (defined('SYSLOG_FILE')) {
808 $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
809 }
810 $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1;
811
812
813 // Copy directory medias
814 $srcroot = DOL_DOCUMENT_ROOT.'/install/medias';
815 $destroot = DOL_DATA_ROOT.'/medias';
816 dolCopyDir($srcroot, $destroot, '0', 0);
817
818
819 // Actions for all versions (no database change but delete some files and directories)
820 migrate_delete_old_files($db, $langs, $conf);
821 migrate_delete_old_dir($db, $langs, $conf);
822 // Actions for all versions (no database change but create some directories)
823 dol_mkdir(DOL_DATA_ROOT.'/bank');
824 // Actions for all versions (no database change but rename some directories)
825 migrate_rename_directories($db, $langs, $conf, '/banque/bordereau', '/bank/checkdeposits');
826
827
828 $parameters = array('versionfrom' => $versionfrom, 'versionto' => $versionto, 'conf' => $conf);
829 $object = new stdClass();
830 $action = "upgrade";
831 $reshook = $hookmanager->executeHooks('doUpgradeAfterFiles', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
832 if ($hookmanager->resNbOfHooks > 0) {
833 if ($reshook < 0) {
834 print '<tr><td colspan="4">';
835 print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: ';
836 print $hookmanager->error;
837 print "<!-- (".$reshook.") -->";
838 print '</td></tr>';
839 } else {
840 print '<tr class="trforrunsql"><td colspan="4">';
841 print '<b>'.$langs->trans('UpgradeExternalModule').' (Files)</b>: <span class="ok">OK</span>';
842 print "<!-- (".$reshook.") -->";
843 print '</td></tr>';
844 }
845 } else {
846 //if (!empty($conf->modules))
847 if (!empty($conf->modules_parts['hooks'])) { // If there is at least one module with one hook, we show message to say nothing was done
848 print '<tr class="trforrunsql"><td colspan="4">';
849 print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: '.$langs->trans("NodoUpgradeAfterFiles");
850 print '</td></tr>';
851 }
852 }
853 }
854
855 $db->close();
856
857 $silent = 0;
858 if (!$silent) {
859 print '<table width="100%">';
860 print '<tr><td style="width: 30%">'.$langs->trans("MigrationFinished").'</td>';
861 print '<td class="right">';
862 if ($error == 0) {
863 //print '<span class="ok">'.$langs->trans("OK").'</span> - '; // $error = 0 does not mean there is no error (error are not always trapped)
864 } else {
865 print '<span class="error">'.$langs->trans("Error").'</span> - ';
866 }
867
868 //if (!empty($conf->use_javascript_ajax)) { // use_javascript_ajax is not defined
869 print '<script type="text/javascript">
870 jQuery(document).ready(function() {
871 function init_trrunsql()
872 {
873 console.log("toggle .trforrunsql");
874 jQuery(".trforrunsql").toggle();
875 }
876 init_trrunsql();
877 jQuery(".trforrunsqlshowhide").click(function() {
878 init_trrunsql();
879 });
880 });
881 </script>';
882 print '<a class="trforrunsqlshowhide" href="#">'.$langs->trans("ShowHideDetails").'</a>';
883 //}
884
885 print '</td></tr>'."\n";
886 print '</table>';
887 }
888
889 //print '<div><br>'.$langs->trans("MigrationFinished").'</div>';
890} else {
891 print '<div class="error">'.$langs->trans('ErrorWrongParameters').'</div>';
892 $error++;
893}
894
895$ret = 0;
896if ($error && isset($argv[1])) {
897 $ret = 1;
898}
899dolibarr_install_syslog("Exit ".$ret);
900
901dolibarr_install_syslog("--- upgrade2: end");
902pFooter($error ? 2 : 0, $setuplang);
903
904if ($db->connected) {
905 $db->close();
906}
907
908// Return code if ran from command line
909if ($ret) {
910 exit($ret);
911}
912
913
914
923function migrate_paiements($db, $langs, $conf)
924{
925 print '<tr><td colspan="4">';
926
927 print '<br>';
928 print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
929
930 $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement", "fk_facture");
931 $obj = $db->fetch_object($result);
932 if ($obj) {
933 $sql = "SELECT p.rowid, p.fk_facture, p.amount";
934 $sql .= " FROM ".MAIN_DB_PREFIX."paiement as p";
935 $sql .= " WHERE p.fk_facture > 0";
936
937 $resql = $db->query($sql);
938 $row = array();
939 $num = 0;
940
941 dolibarr_install_syslog("upgrade2::migrate_paiements");
942 if ($resql) {
943 $i = 0;
944 $num = $db->num_rows($resql);
945
946 while ($i < $num) {
947 $obj = $db->fetch_object($resql);
948 $row[$i][0] = $obj->rowid;
949 $row[$i][1] = $obj->fk_facture;
950 $row[$i][2] = $obj->amount;
951 $i++;
952 }
953 } else {
954 dol_print_error($db);
955 }
956
957 if ($num) {
958 print $langs->trans('MigrationPaymentsNumberToUpdate', $num)."<br>\n";
959 $res = 0;
960 if ($db->begin()) {
961 $num = count($row);
962 for ($i = 0; $i < $num; $i++) {
963 $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
964 $sql .= " VALUES (".((int) $row[$i][1]).",".((int) $row[$i][0]).",".((float) $row[$i][2]).")";
965
966 $res += $db->query($sql);
967
968 $sql = "UPDATE ".MAIN_DB_PREFIX."paiement SET fk_facture = 0 WHERE rowid = ".((int) $row[$i][0]);
969
970 $res += $db->query($sql);
971
972 print $langs->trans('MigrationProcessPaymentUpdate', $row[$i][0])."<br>\n";
973 }
974 }
975
976 if (is_array($row) && $res == (2 * count($row))) {
977 $db->commit();
978 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
979 } else {
980 $db->rollback();
981 print $langs->trans('MigrationUpdateFailed').'<br>';
982 }
983 } else {
984 print $langs->trans('MigrationPaymentsNothingToUpdate')."<br>\n";
985 }
986 } else {
987 print $langs->trans('MigrationPaymentsNothingToUpdate')."<br>\n";
988 }
989
990 print '</td></tr>';
991}
992
1003function migrate_paiements_orphelins_1($db, $langs, $conf)
1004{
1005 print '<tr><td colspan="4">';
1006
1007 print '<br>';
1008 print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
1009
1010 $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement", "fk_facture");
1011 $obj = $db->fetch_object($result);
1012 if ($obj) {
1013 // All answer of this requests should have a parent into llx_paiement_facture
1014 $sql = "SELECT DISTINCT p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,";
1015 $sql .= " bu2.url_id as socid";
1016 $sql .= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)";
1017 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_paiement = p.rowid";
1018 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu2 ON (bu.fk_bank=bu2.fk_bank AND bu2.type = 'company')";
1019 $sql .= " WHERE pf.rowid IS NULL AND (p.rowid=bu.url_id AND bu.type='payment') AND bu.fk_bank = b.rowid";
1020 $sql .= " AND b.rappro = 1";
1021 $sql .= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)";
1022
1023 $resql = $db->query($sql);
1024
1025 dolibarr_install_syslog("upgrade2::migrate_paiements_orphelins_1");
1026 $row = array();
1027 if ($resql) {
1028 $i = $j = 0;
1029 $num = $db->num_rows($resql);
1030
1031 while ($i < $num) {
1032 $obj = $db->fetch_object($resql);
1033 if ($obj->pamount == $obj->bamount && $obj->socid) { // Pour etre sur d'avoir bon cas
1034 $row[$j]['paymentid'] = $obj->rowid; // paymentid
1035 $row[$j]['pamount'] = $obj->pamount;
1036 $row[$j]['fk_bank'] = $obj->fk_bank;
1037 $row[$j]['bamount'] = $obj->bamount;
1038 $row[$j]['socid'] = $obj->socid;
1039 $row[$j]['datec'] = $obj->datec;
1040 $j++;
1041 }
1042 $i++;
1043 }
1044 } else {
1045 dol_print_error($db);
1046 }
1047
1048 if (count($row)) {
1049 print $langs->trans('OrphelinsPaymentsDetectedByMethod', 1).': '.count($row)."<br>\n";
1050 $db->begin();
1051
1052 $res = 0;
1053 $num = count($row);
1054 for ($i = 0; $i < $num; $i++) {
1055 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') == 2) {
1056 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>';
1057 }
1058
1059 // Look for invoices without payment relations with the same amount and same comppany
1060 $sql = " SELECT DISTINCT f.rowid from ".MAIN_DB_PREFIX."facture as f";
1061 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
1062 $sql .= " WHERE f.fk_statut in (2,3) AND fk_soc = ".((int) $row[$i]['socid'])." AND total_ttc = ".((float) $row[$i]['pamount']);
1063 $sql .= " AND pf.fk_facture IS NULL";
1064 $sql .= " ORDER BY f.fk_statut";
1065 //print $sql.'<br>';
1066 $resql = $db->query($sql);
1067 if ($resql) {
1068 $num = $db->num_rows($resql);
1069 //print 'Nb of invoice found for this amount and company :'.$num.'<br>';
1070 if ($num >= 1) {
1071 $obj = $db->fetch_object($resql);
1072 $facid = $obj->rowid;
1073
1074 $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
1075 $sql .= " VALUES (".((int) $facid).",".((int) $row[$i]['paymentid']).", ".((float) $row[$i]['pamount']).")";
1076
1077 $res += $db->query($sql);
1078
1079 print $langs->trans('MigrationProcessPaymentUpdate', 'facid='.$facid.'-paymentid='.$row[$i]['paymentid'].'-amount='.$row[$i]['pamount'])."<br>\n";
1080 }
1081 } else {
1082 print 'ERROR';
1083 }
1084 }
1085
1086 if ($res > 0) {
1087 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1088 } else {
1089 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1090 }
1091
1092 $db->commit();
1093 } else {
1094 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1095 }
1096 } else {
1097 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1098 }
1099
1100 print '</td></tr>';
1101}
1102
1113function migrate_paiements_orphelins_2($db, $langs, $conf)
1114{
1115 print '<tr><td colspan="4">';
1116
1117 print '<br>';
1118 print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
1119
1120 $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement", "fk_facture");
1121 $obj = $db->fetch_object($result);
1122 if ($obj) {
1123 // Tous les enregistrements qui sortent de cette requete devrait avoir un pere dans llx_paiement_facture
1124 $sql = "SELECT DISTINCT p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,";
1125 $sql .= " bu2.url_id as socid";
1126 $sql .= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)";
1127 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_paiement = p.rowid";
1128 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu2 ON (bu.fk_bank = bu2.fk_bank AND bu2.type = 'company')";
1129 $sql .= " WHERE pf.rowid IS NULL AND (p.fk_bank = bu.fk_bank AND bu.type = 'payment') AND bu.fk_bank = b.rowid";
1130 $sql .= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)";
1131
1132 $resql = $db->query($sql);
1133
1134 dolibarr_install_syslog("upgrade2::migrate_paiements_orphelins_2");
1135 $row = array();
1136 if ($resql) {
1137 $i = $j = 0;
1138 $num = $db->num_rows($resql);
1139
1140 while ($i < $num) {
1141 $obj = $db->fetch_object($resql);
1142 if ($obj->pamount == $obj->bamount && $obj->socid) { // Pour etre sur d'avoir bon cas
1143 $row[$j]['paymentid'] = $obj->rowid; // paymentid
1144 $row[$j]['pamount'] = $obj->pamount;
1145 $row[$j]['fk_bank'] = $obj->fk_bank;
1146 $row[$j]['bamount'] = $obj->bamount;
1147 $row[$j]['socid'] = $obj->socid;
1148 $row[$j]['datec'] = $obj->datec;
1149 $j++;
1150 }
1151 $i++;
1152 }
1153 } else {
1154 dol_print_error($db);
1155 }
1156
1157 $nberr = 0;
1158
1159 $num = count($row);
1160 if ($num) {
1161 print $langs->trans('OrphelinsPaymentsDetectedByMethod', 2).': '.count($row)."<br>\n";
1162 $db->begin();
1163
1164 $res = 0;
1165 for ($i = 0; $i < $num; $i++) {
1166 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') == 2) {
1167 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>';
1168 }
1169
1170 // Look for invoices without payment relations with the same amount and same comppany
1171 $sql = " SELECT DISTINCT f.rowid from ".MAIN_DB_PREFIX."facture as f";
1172 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
1173 $sql .= " WHERE f.fk_statut in (2,3) AND fk_soc = ".((int) $row[$i]['socid'])." AND total_ttc = ".((float) $row[$i]['pamount']);
1174 $sql .= " AND pf.fk_facture IS NULL";
1175 $sql .= " ORDER BY f.fk_statut";
1176 //print $sql.'<br>';
1177 $resql = $db->query($sql);
1178 if ($resql) {
1179 $num = $db->num_rows($resql);
1180 //print 'Nb of invoice found for this amount and company :'.$num.'<br>';
1181 if ($num >= 1) {
1182 $obj = $db->fetch_object($resql);
1183 $facid = $obj->rowid;
1184
1185 $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
1186 $sql .= " VALUES (".((int) $facid).",".((int) $row[$i]['paymentid']).", ".((float) $row[$i]['pamount']).")";
1187
1188 $res += $db->query($sql);
1189
1190 print $langs->trans('MigrationProcessPaymentUpdate', 'facid='.$facid.'-paymentid='.$row[$i]['paymentid'].'-amount='.$row[$i]['pamount'])."<br>\n";
1191 }
1192 } else {
1193 print 'ERROR';
1194 $nberr++;
1195 }
1196 }
1197
1198 if ($res > 0) {
1199 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1200 } else {
1201 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1202 }
1203
1204 $db->commit();
1205 } else {
1206 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1207 }
1208
1209 // Delete obsolete fields fk_facture
1210 $db->begin();
1211
1212 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."paiement DROP COLUMN fk_facture";
1213 $db->query($sql);
1214
1215 if (!$nberr) {
1216 $db->commit();
1217 } else {
1218 print 'ERROR';
1219 $db->rollback();
1220 }
1221 } else {
1222 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1223 }
1224
1225 print '</td></tr>';
1226}
1227
1228
1237function migrate_contracts_det($db, $langs, $conf)
1238{
1239 print '<tr><td colspan="4">';
1240
1241 $nberr = 0;
1242
1243 print '<br>';
1244 print '<b>'.$langs->trans('MigrationContractsUpdate')."</b><br>\n";
1245
1246 $sql = "SELECT c.rowid as cref, c.date_contrat, c.statut, c.fk_product, c.fk_facture, c.fk_user_author,";
1247 $sql .= " p.ref, p.label, p.description, p.price, p.tva_tx, p.duration, cd.rowid";
1248 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
1249 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p";
1250 $sql .= " ON c.fk_product = p.rowid";
1251 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd";
1252 $sql .= " ON c.rowid=cd.fk_contrat";
1253 $sql .= " WHERE cd.rowid IS NULL AND p.rowid IS NOT NULL";
1254 $resql = $db->query($sql);
1255
1256 dolibarr_install_syslog("upgrade2::migrate_contracts_det");
1257 if ($resql) {
1258 $i = 0;
1259 $row = array();
1260 $num = $db->num_rows($resql);
1261
1262 if ($num) {
1263 print $langs->trans('MigrationContractsNumberToUpdate', $num)."<br>\n";
1264 $db->begin();
1265
1266 while ($i < $num) {
1267 $obj = $db->fetch_object($resql);
1268
1269 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet (";
1270 $sql .= "fk_contrat, fk_product, statut, label, description,";
1271 $sql .= "date_ouverture_prevue, date_ouverture, date_fin_validite, tva_tx, qty,";
1272 $sql .= "subprice, price_ht, fk_user_author, fk_user_ouverture)";
1273 $sql .= " VALUES (";
1274 $sql .= ((int) $obj->cref).", ".($obj->fk_product ? ((int) $obj->fk_product) : 0).", ";
1275 $sql .= "0, ";
1276 $sql .= "'".$db->escape($obj->label)."', null, ";
1277 $sql .= ($obj->date_contrat ? "'".$db->idate($db->jdate($obj->date_contrat))."'" : "null").", ";
1278 $sql .= "null, ";
1279 $sql .= "null, ";
1280 $sql .= ((float) $obj->tva_tx).", 1, ";
1281 $sql .= ((float) $obj->price).", ".((float) $obj->price).", ".((int) $obj->fk_user_author).",";
1282 $sql .= "null";
1283 $sql .= ")";
1284
1285 if ($db->query($sql)) {
1286 print $langs->trans('MigrationContractsLineCreation', $obj->cref)."<br>\n";
1287 } else {
1288 dol_print_error($db);
1289 $nberr++;
1290 }
1291
1292 $i++;
1293 }
1294
1295 if (!$nberr) {
1296 // $db->rollback();
1297 $db->commit();
1298 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1299 } else {
1300 $db->rollback();
1301 print $langs->trans('MigrationUpdateFailed').'<br>';
1302 }
1303 } else {
1304 print $langs->trans('MigrationContractsNothingToUpdate')."<br>\n";
1305 }
1306 } else {
1307 print $langs->trans('MigrationContractsFieldDontExist')."<br>\n";
1308 // dol_print_error($db);
1309 }
1310
1311 print '</td></tr>';
1312}
1313
1322function migrate_links_transfert($db, $langs, $conf)
1323{
1324 print '<tr><td colspan="4">';
1325
1326 $nberr = 0;
1327
1328 print '<br>';
1329 print '<b>'.$langs->trans('MigrationBankTransfertsUpdate')."</b><br>\n";
1330
1331 $sql = "SELECT ba.rowid as barowid, bb.rowid as bbrowid";
1332 $sql .= " FROM ".MAIN_DB_PREFIX."bank as bb, ".MAIN_DB_PREFIX."bank as ba";
1333 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON bu.fk_bank = ba.rowid";
1334 $sql .= " WHERE ba.amount = -bb.amount AND ba.fk_account <> bb.fk_account";
1335 $sql .= " AND ba.datev = bb.datev AND ba.datec = bb.datec";
1336 $sql .= " AND bu.fk_bank IS NULL";
1337 $resql = $db->query($sql);
1338
1339 dolibarr_install_syslog("upgrade2::migrate_links_transfert");
1340 if ($resql) {
1341 $i = 0;
1342 $row = array();
1343 $num = $db->num_rows($resql);
1344
1345 if ($num) {
1346 print $langs->trans('MigrationBankTransfertsToUpdate', $num)."<br>\n";
1347 $db->begin();
1348
1349 while ($i < $num) {
1350 $obj = $db->fetch_object($resql);
1351
1352 $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url (";
1353 $sql .= "fk_bank, url_id, url, label, type";
1354 $sql .= ")";
1355 $sql .= " VALUES (";
1356 $sql .= $obj->barowid.",".$obj->bbrowid.", '/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert'";
1357 $sql .= ")";
1358
1359 //print $sql.'<br>';
1360 dolibarr_install_syslog("migrate_links_transfert");
1361
1362 if (!$db->query($sql)) {
1363 dol_print_error($db);
1364 $nberr++;
1365 }
1366
1367 $i++;
1368 }
1369
1370 if (!$nberr) {
1371 // $db->rollback();
1372 $db->commit();
1373 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1374 } else {
1375 $db->rollback();
1376 print $langs->trans('MigrationUpdateFailed').'<br>';
1377 }
1378 } else {
1379 print $langs->trans('MigrationBankTransfertsNothingToUpdate')."<br>\n";
1380 }
1381 } else {
1382 dol_print_error($db);
1383 }
1384
1385 print '</td></tr>';
1386}
1387
1396function migrate_contracts_date1($db, $langs, $conf)
1397{
1398 print '<tr><td colspan="4">';
1399
1400 print '<br>';
1401 print '<b>'.$langs->trans('MigrationContractsEmptyDatesUpdate')."</b><br>\n";
1402
1403 $sql = "update ".MAIN_DB_PREFIX."contrat set date_contrat=tms where date_contrat is null";
1404 dolibarr_install_syslog("upgrade2::migrate_contracts_date1");
1405 $resql = $db->query($sql);
1406 if (!$resql) {
1407 dol_print_error($db);
1408 }
1409 if ($db->affected_rows($resql) > 0) {
1410 print $langs->trans('MigrationContractsEmptyDatesUpdateSuccess')."<br>\n";
1411 } else {
1412 print $langs->trans('MigrationContractsEmptyDatesNothingToUpdate')."<br>\n";
1413 }
1414
1415 $sql = "update ".MAIN_DB_PREFIX."contrat set datec=tms where datec is null";
1416 dolibarr_install_syslog("upgrade2::migrate_contracts_date1");
1417 $resql = $db->query($sql);
1418 if (!$resql) {
1419 dol_print_error($db);
1420 }
1421 if ($db->affected_rows($resql) > 0) {
1422 print $langs->trans('MigrationContractsEmptyCreationDatesUpdateSuccess')."<br>\n";
1423 } else {
1424 print $langs->trans('MigrationContractsEmptyCreationDatesNothingToUpdate')."<br>\n";
1425 }
1426
1427 print '</td></tr>';
1428}
1429
1438function migrate_contracts_date2($db, $langs, $conf)
1439{
1440 print '<tr><td colspan="4">';
1441
1442 $nberr = 0;
1443
1444 print '<br>';
1445 print '<b>'.$langs->trans('MigrationContractsInvalidDatesUpdate')."</b><br>\n";
1446
1447 $sql = "SELECT c.rowid as cref, c.datec, c.date_contrat, MIN(cd.date_ouverture) as datemin";
1448 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c,";
1449 $sql .= " ".MAIN_DB_PREFIX."contratdet as cd";
1450 $sql .= " WHERE c.rowid=cd.fk_contrat AND cd.date_ouverture IS NOT NULL";
1451 $sql .= " GROUP BY c.rowid, c.date_contrat";
1452 $resql = $db->query($sql);
1453
1454 dolibarr_install_syslog("upgrade2::migrate_contracts_date2");
1455 if ($resql) {
1456 $i = 0;
1457 $row = array();
1458 $num = $db->num_rows($resql);
1459
1460 if ($num) {
1461 $nbcontratsmodifie = 0;
1462 $db->begin();
1463
1464 while ($i < $num) {
1465 $obj = $db->fetch_object($resql);
1466 if ($obj->date_contrat > $obj->datemin) {
1467 $datemin = $db->jdate($obj->datemin);
1468
1469 print $langs->trans('MigrationContractsInvalidDateFix', $obj->cref, $obj->date_contrat, $obj->datemin)."<br>\n";
1470 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat";
1471 $sql .= " SET date_contrat='".$db->idate($datemin)."'";
1472 $sql .= " WHERE rowid = ".((int) $obj->cref);
1473 $resql2 = $db->query($sql);
1474 if (!$resql2) {
1475 dol_print_error($db);
1476 }
1477
1478 $nbcontratsmodifie++;
1479 }
1480 $i++;
1481 }
1482
1483 $db->commit();
1484
1485 if ($nbcontratsmodifie) {
1486 print $langs->trans('MigrationContractsInvalidDatesNumber', $nbcontratsmodifie)."<br>\n";
1487 } else {
1488 print $langs->trans('MigrationContractsInvalidDatesNothingToUpdate')."<br>\n";
1489 }
1490 }
1491 } else {
1492 dol_print_error($db);
1493 }
1494
1495 print '</td></tr>';
1496}
1497
1506function migrate_contracts_date3($db, $langs, $conf)
1507{
1508 print '<tr><td colspan="4">';
1509
1510 print '<br>';
1511 print '<b>'.$langs->trans('MigrationContractsIncoherentCreationDateUpdate')."</b><br>\n";
1512
1513 $sql = "update ".MAIN_DB_PREFIX."contrat set datec=date_contrat where datec is null or datec > date_contrat";
1514 dolibarr_install_syslog("upgrade2::migrate_contracts_date3");
1515 $resql = $db->query($sql);
1516 if (!$resql) {
1517 dol_print_error($db);
1518 }
1519 if ($db->affected_rows($resql) > 0) {
1520 print $langs->trans('MigrationContractsIncoherentCreationDateUpdateSuccess')."<br>\n";
1521 } else {
1522 print $langs->trans('MigrationContractsIncoherentCreationDateNothingToUpdate')."<br>\n";
1523 }
1524
1525 print '</td></tr>';
1526}
1527
1536function migrate_contracts_open($db, $langs, $conf)
1537{
1538 print '<tr><td colspan="4">';
1539
1540 print '<br>';
1541 print '<b>'.$langs->trans('MigrationReopeningContracts')."</b><br>\n";
1542
1543 $sql = "SELECT c.rowid as cref FROM ".MAIN_DB_PREFIX."contrat as c, ".MAIN_DB_PREFIX."contratdet as cd";
1544 $sql .= " WHERE cd.statut = 4 AND c.statut=2 AND c.rowid=cd.fk_contrat";
1545 dolibarr_install_syslog("upgrade2::migrate_contracts_open");
1546 $resql = $db->query($sql);
1547 if (!$resql) {
1548 dol_print_error($db);
1549 }
1550 if ($db->affected_rows($resql) > 0) {
1551 $i = 0;
1552 $row = array();
1553 $num = $db->num_rows($resql);
1554
1555 if ($num) {
1556 $nbcontratsmodifie = 0;
1557 $db->begin();
1558
1559 while ($i < $num) {
1560 $obj = $db->fetch_object($resql);
1561
1562 print $langs->trans('MigrationReopenThisContract', $obj->cref)."<br>\n";
1563 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat";
1564 $sql .= " SET statut = 1";
1565 $sql .= " WHERE rowid = ".((int) $obj->cref);
1566 $resql2 = $db->query($sql);
1567 if (!$resql2) {
1568 dol_print_error($db);
1569 }
1570
1571 $nbcontratsmodifie++;
1572
1573 $i++;
1574 }
1575
1576 $db->commit();
1577
1578 if ($nbcontratsmodifie) {
1579 print $langs->trans('MigrationReopenedContractsNumber', $nbcontratsmodifie)."<br>\n";
1580 } else {
1581 print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n";
1582 }
1583 }
1584 } else {
1585 print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n";
1586 }
1587
1588 print '</td></tr>';
1589}
1590
1599function migrate_paiementfourn_facturefourn($db, $langs, $conf)
1600{
1601 global $bc;
1602
1603 print '<tr><td colspan="4">';
1604 print '<br>';
1605 print '<b>'.$langs->trans('SuppliersInvoices')."</b><br>\n";
1606 print '</td></tr>';
1607
1608 $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiementfourn", "fk_facture_fourn");
1609 $obj = $db->fetch_object($result);
1610 if ($obj) {
1611 $error = 0;
1612 $nb = 0;
1613
1614 $select_sql = 'SELECT rowid, fk_facture_fourn, amount';
1615 $select_sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn';
1616 $select_sql .= ' WHERE fk_facture_fourn IS NOT NULL';
1617
1618 dolibarr_install_syslog("upgrade2::migrate_paiementfourn_facturefourn");
1619 $select_resql = $db->query($select_sql);
1620 if ($select_resql) {
1621 $select_num = $db->num_rows($select_resql);
1622 $i = 0;
1623
1624 // Pour chaque paiement fournisseur, on insere une ligne dans paiementfourn_facturefourn
1625 while (($i < $select_num) && (!$error)) {
1626 $select_obj = $db->fetch_object($select_resql);
1627
1628 // Verifier si la ligne est deja dans la nouvelle table. On ne veut pas inserer de doublons.
1629 $check_sql = 'SELECT fk_paiementfourn, fk_facturefourn';
1630 $check_sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn';
1631 $check_sql .= ' WHERE fk_paiementfourn = '.((int) $select_obj->rowid).' AND fk_facturefourn = '.((int) $select_obj->fk_facture_fourn);
1632 $check_resql = $db->query($check_sql);
1633 if ($check_resql) {
1634 $check_num = $db->num_rows($check_resql);
1635 if ($check_num == 0) {
1636 $db->begin();
1637
1638 if ($nb == 0) {
1639 print '<tr><td colspan="4" class="nowrap"><b>'.$langs->trans('SuppliersInvoices').'</b></td></tr>';
1640 print '<tr><td>fk_paiementfourn</td><td>fk_facturefourn</td><td>'.$langs->trans('Amount').'</td><td>&nbsp;</td></tr>';
1641 }
1642
1643 print '<tr class="oddeven">';
1644 print '<td>'.$select_obj->rowid.'</td><td>'.$select_obj->fk_facture_fourn.'</td><td>'.$select_obj->amount.'</td>';
1645
1646 $insert_sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiementfourn_facturefourn SET ';
1647 $insert_sql .= ' fk_paiementfourn = \''.$select_obj->rowid.'\',';
1648 $insert_sql .= ' fk_facturefourn = \''.$select_obj->fk_facture_fourn.'\',';
1649 $insert_sql .= ' amount = \''.$select_obj->amount.'\'';
1650 $insert_resql = $db->query($insert_sql);
1651
1652 if ($insert_resql) {
1653 $nb++;
1654 print '<td><span class="ok">'.$langs->trans("OK").'</span></td>';
1655 } else {
1656 print '<td><span class="error">Error on insert</span></td>';
1657 $error++;
1658 }
1659 print '</tr>';
1660 }
1661 } else {
1662 $error++;
1663 }
1664 $i++;
1665 }
1666 } else {
1667 $error++;
1668 }
1669
1670 if (!$error) {
1671 if (!$nb) {
1672 print '<tr><td>'.$langs->trans("AlreadyDone").'</td></tr>';
1673 }
1674 $db->commit();
1675
1676 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."paiementfourn DROP COLUMN fk_facture_fourn";
1677 $db->query($sql);
1678 } else {
1679 print '<tr><td>'.$langs->trans("Error").'</td></tr>';
1680 $db->rollback();
1681 }
1682 } else {
1683 print '<tr><td>'.$langs->trans("AlreadyDone").'</td></tr>';
1684 }
1685}
1686
1695function migrate_price_facture($db, $langs, $conf)
1696{
1697 $err = 0;
1698
1699 $tmpmysoc = new Societe($db);
1700 $tmpmysoc->setMysoc($conf);
1701
1702 $db->begin();
1703
1704 print '<tr><td colspan="4">';
1705
1706 print '<br>';
1707 print '<b>'.$langs->trans('MigrationInvoice')."</b><br>\n";
1708
1709 // List of invoice lines not up to date
1710 $sql = "SELECT fd.rowid, fd.qty, fd.subprice, fd.remise_percent, fd.tva_tx as vatrate, fd.total_ttc, fd.info_bits,";
1711 $sql .= " f.rowid as facid, f.remise_percent as remise_percent_global, f.total_ttc as total_ttc_f";
1712 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd, ".MAIN_DB_PREFIX."facture as f";
1713 $sql .= " WHERE fd.fk_facture = f.rowid";
1714 $sql .= " AND (((fd.total_ttc = 0 AND fd.remise_percent != 100) or fd.total_ttc IS NULL) or f.total_ttc IS NULL)";
1715 //print $sql;
1716
1717 dolibarr_install_syslog("upgrade2::migrate_price_facture");
1718 $resql = $db->query($sql);
1719 if ($resql) {
1720 $num = $db->num_rows($resql);
1721 $i = 0;
1722 if ($num) {
1723 while ($i < $num) {
1724 $obj = $db->fetch_object($resql);
1725
1726 $rowid = $obj->rowid;
1727 $qty = $obj->qty;
1728 $pu = $obj->subprice;
1729 $vatrate = $obj->vatrate;
1730 $remise_percent = $obj->remise_percent;
1731 $remise_percent_global = $obj->remise_percent_global;
1732 $total_ttc_f = $obj->total_ttc_f;
1733 $info_bits = $obj->info_bits;
1734
1735 // On met a jour les 3 nouveaux champs
1736 $facligne = new FactureLigne($db);
1737 $facligne->fetch($rowid);
1738
1739 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $facligne->product_type, $tmpmysoc);
1740 $total_ht = $result[0];
1741 $total_tva = $result[1];
1742 $total_ttc = $result[2];
1743
1744 $facligne->total_ht = (float) $total_ht;
1745 $facligne->total_tva = (float) $total_tva;
1746 $facligne->total_ttc = (float) $total_ttc;
1747
1748 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);
1749 print '. ';
1750 $facligne->update_total();
1751
1752
1753 /* On touche a facture mere uniquement si total_ttc = 0 */
1754 if (!$total_ttc_f) {
1755 $facture = new Facture($db);
1756 $facture->id = $obj->facid;
1757
1758 if ($facture->fetch($facture->id) >= 0) {
1759 if ($facture->update_price() > 0) {
1760 //print $facture->id;
1761 } else {
1762 print "Error id=".$facture->id;
1763 $err++;
1764 }
1765 } else {
1766 print "Error #3";
1767 $err++;
1768 }
1769 }
1770 print " ";
1771
1772 $i++;
1773 }
1774 } else {
1775 print $langs->trans("AlreadyDone");
1776 }
1777 $db->free($resql);
1778
1779 $db->commit();
1780 } else {
1781 print "Error #1 ".$db->error();
1782 $err++;
1783
1784 $db->rollback();
1785 }
1786
1787 print '<br>';
1788
1789 print '</td></tr>';
1790}
1791
1800function migrate_price_propal($db, $langs, $conf)
1801{
1802 $tmpmysoc = new Societe($db);
1803 $tmpmysoc->setMysoc($conf);
1804
1805 $db->begin();
1806
1807 print '<tr><td colspan="4">';
1808
1809 print '<br>';
1810 print '<b>'.$langs->trans('MigrationProposal')."</b><br>\n";
1811
1812 // List of proposal lines not up to date
1813 $sql = "SELECT pd.rowid, pd.qty, pd.subprice, pd.remise_percent, pd.tva_tx as vatrate, pd.info_bits,";
1814 $sql .= " p.rowid as propalid, p.remise_percent as remise_percent_global";
1815 $sql .= " FROM ".MAIN_DB_PREFIX."propaldet as pd, ".MAIN_DB_PREFIX."propal as p";
1816 $sql .= " WHERE pd.fk_propal = p.rowid";
1817 $sql .= " AND ((pd.total_ttc = 0 AND pd.remise_percent != 100) or pd.total_ttc IS NULL)";
1818
1819 dolibarr_install_syslog("upgrade2::migrate_price_propal");
1820 $resql = $db->query($sql);
1821 if ($resql) {
1822 $num = $db->num_rows($resql);
1823 $i = 0;
1824 if ($num) {
1825 while ($i < $num) {
1826 $obj = $db->fetch_object($resql);
1827
1828 $rowid = $obj->rowid;
1829 $qty = $obj->qty;
1830 $pu = $obj->subprice;
1831 $vatrate = $obj->vatrate;
1832 $remise_percent = $obj->remise_percent;
1833 $remise_percent_global = $obj->remise_percent_global;
1834 $info_bits = $obj->info_bits;
1835
1836 // On met a jour les 3 nouveaux champs
1837 $propalligne = new PropaleLigne($db);
1838 $propalligne->fetch($rowid);
1839
1840 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $propalligne->product_type, $tmpmysoc);
1841 $total_ht = $result[0];
1842 $total_tva = $result[1];
1843 $total_ttc = $result[2];
1844
1845 $propalligne->total_ht = (float) $total_ht;
1846 $propalligne->total_tva = (float) $total_tva;
1847 $propalligne->total_ttc = (float) $total_ttc;
1848
1849 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);
1850 print '. ';
1851 $propalligne->update_total();
1852
1853 $i++;
1854 }
1855 } else {
1856 print $langs->trans("AlreadyDone");
1857 }
1858
1859 $db->free($resql);
1860
1861 $db->commit();
1862 } else {
1863 print "Error #1 ".$db->error();
1864
1865 $db->rollback();
1866 }
1867
1868 print '<br>';
1869
1870 print '</td></tr>';
1871}
1872
1881function migrate_price_contrat($db, $langs, $conf)
1882{
1883 $db->begin();
1884
1885 $tmpmysoc = new Societe($db);
1886 $tmpmysoc->setMysoc($conf);
1887 if (empty($tmpmysoc->country_id)) {
1888 $tmpmysoc->country_id = 0; // Ti not have this set to '' or will make sql syntax error.
1889 }
1890
1891 print '<tr><td colspan="4">';
1892
1893 print '<br>';
1894 print '<b>'.$langs->trans('MigrationContract')."</b><br>\n";
1895
1896 // List of contract lines not up to date
1897 $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
1898 $sql .= " c.rowid as contratid";
1899 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c";
1900 $sql .= " WHERE cd.fk_contrat = c.rowid";
1901 $sql .= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100 AND cd.subprice > 0) or cd.total_ttc IS NULL)";
1902
1903 dolibarr_install_syslog("upgrade2::migrate_price_contrat");
1904 $resql = $db->query($sql);
1905 if ($resql) {
1906 $num = $db->num_rows($resql);
1907 $i = 0;
1908 if ($num) {
1909 while ($i < $num) {
1910 $obj = $db->fetch_object($resql);
1911
1912 $rowid = $obj->rowid;
1913 $qty = $obj->qty;
1914 $pu = $obj->subprice;
1915 $vatrate = $obj->vatrate;
1916 $remise_percent = $obj->remise_percent;
1917 $info_bits = $obj->info_bits;
1918
1919 // On met a jour les 3 nouveaux champs
1920 $contratligne = new ContratLigne($db);
1921 //$contratligne->fetch($rowid); Non requis car le update_total ne met a jour que chp redefinis
1922 $contratligne->fetch($rowid);
1923
1924 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, 0, 'HT', $info_bits, $contratligne->product_type, $tmpmysoc);
1925 $total_ht = $result[0];
1926 $total_tva = $result[1];
1927 $total_ttc = $result[2];
1928
1929 $contratligne->total_ht = (float) $total_ht;
1930 $contratligne->total_tva = (float) $total_tva;
1931 $contratligne->total_ttc = (float) $total_ttc;
1932
1933 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);
1934 print '. ';
1935 $contratligne->update_total();
1936
1937 $i++;
1938 }
1939 } else {
1940 print $langs->trans("AlreadyDone");
1941 }
1942
1943 $db->free($resql);
1944
1945 $db->commit();
1946 } else {
1947 print "Error #1 ".$db->error();
1948
1949 $db->rollback();
1950 }
1951
1952 print '<br>';
1953
1954 print '</td></tr>';
1955}
1956
1965function migrate_price_commande($db, $langs, $conf)
1966{
1967 $db->begin();
1968
1969 $tmpmysoc = new Societe($db);
1970 $tmpmysoc->setMysoc($conf);
1971
1972 print '<tr><td colspan="4">';
1973
1974 print '<br>';
1975 print '<b>'.$langs->trans('MigrationOrder')."</b><br>\n";
1976
1977 // List of sales orders lines not up to date
1978 $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
1979 $sql .= " c.rowid as commandeid, c.remise_percent as remise_percent_global";
1980 $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."commande as c";
1981 $sql .= " WHERE cd.fk_commande = c.rowid";
1982 $sql .= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)";
1983
1984 dolibarr_install_syslog("upgrade2::migrate_price_commande");
1985 $resql = $db->query($sql);
1986 if ($resql) {
1987 $num = $db->num_rows($resql);
1988 $i = 0;
1989 if ($num) {
1990 while ($i < $num) {
1991 $obj = $db->fetch_object($resql);
1992
1993 $rowid = $obj->rowid;
1994 $qty = $obj->qty;
1995 $pu = $obj->subprice;
1996 $vatrate = $obj->vatrate;
1997 $remise_percent = $obj->remise_percent;
1998 $remise_percent_global = $obj->remise_percent_global;
1999 $info_bits = $obj->info_bits;
2000
2001 // On met a jour les 3 nouveaux champs
2002 $commandeligne = new OrderLine($db);
2003 $commandeligne->fetch($rowid);
2004
2005 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $commandeligne->product_type, $tmpmysoc);
2006 $total_ht = $result[0];
2007 $total_tva = $result[1];
2008 $total_ttc = $result[2];
2009
2010 $commandeligne->total_ht = (float) $total_ht;
2011 $commandeligne->total_tva = (float) $total_tva;
2012 $commandeligne->total_ttc = (float) $total_ttc;
2013
2014 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);
2015 print '. ';
2016 $commandeligne->update_total();
2017
2018 $i++;
2019 }
2020 } else {
2021 print $langs->trans("AlreadyDone");
2022 }
2023
2024 $db->free($resql);
2025
2026 /*
2027 $sql = "DELETE FROM ".MAIN_DB_PREFIX."commandedet";
2028 $sql.= " WHERE price = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0 AND remise_percent = 0";
2029 $resql=$db->query($sql);
2030 if (! $resql)
2031 {
2032 dol_print_error($db);
2033 }
2034 */
2035
2036 $db->commit();
2037 } else {
2038 print "Error #1 ".$db->error();
2039
2040 $db->rollback();
2041 }
2042
2043 print '<br>';
2044
2045 print '</td></tr>';
2046}
2047
2056function migrate_price_commande_fournisseur($db, $langs, $conf)
2057{
2058 global $mysoc;
2059
2060 $db->begin();
2061
2062 $tmpmysoc = new Societe($db);
2063 $tmpmysoc->setMysoc($conf);
2064
2065 print '<tr><td colspan="4">';
2066
2067 print '<br>';
2068 print '<b>'.$langs->trans('MigrationSupplierOrder')."</b><br>\n";
2069
2070 // List of purchase order lines not up to date
2071 $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
2072 $sql .= " c.rowid as commandeid, c.remise_percent as remise_percent_global";
2073 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd, ".MAIN_DB_PREFIX."commande_fournisseur as c";
2074 $sql .= " WHERE cd.fk_commande = c.rowid";
2075 $sql .= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)";
2076
2077 dolibarr_install_syslog("upgrade2::migrate_price_commande_fournisseur");
2078 $resql = $db->query($sql);
2079 if ($resql) {
2080 $num = $db->num_rows($resql);
2081 $i = 0;
2082 if ($num) {
2083 while ($i < $num) {
2084 $obj = $db->fetch_object($resql);
2085
2086 $rowid = $obj->rowid;
2087 $qty = $obj->qty;
2088 $pu = $obj->subprice;
2089 $vatrate = $obj->vatrate;
2090 $remise_percent = $obj->remise_percent;
2091 $remise_percent_global = $obj->remise_percent_global;
2092 $info_bits = $obj->info_bits;
2093
2094 // On met a jour les 3 nouveaux champs
2095 $commandeligne = new CommandeFournisseurLigne($db);
2096 $commandeligne->fetch($rowid);
2097
2098 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $commandeligne->product_type, $mysoc);
2099 $total_ht = $result[0];
2100 $total_tva = $result[1];
2101 $total_ttc = $result[2];
2102
2103 $commandeligne->total_ht = (float) $total_ht;
2104 $commandeligne->total_tva = (float) $total_tva;
2105 $commandeligne->total_ttc = (float) $total_ttc;
2106
2107 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);
2108 print '. ';
2109 $commandeligne->update_total();
2110
2111 $i++;
2112 }
2113 } else {
2114 print $langs->trans("AlreadyDone");
2115 }
2116
2117 $db->free($resql);
2118
2119 /*
2120 $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet";
2121 $sql.= " WHERE subprice = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0";
2122 $resql=$db->query($sql);
2123 if (! $resql)
2124 {
2125 dol_print_error($db);
2126 }
2127 */
2128
2129 $db->commit();
2130 } else {
2131 print "Error #1 ".$db->error();
2132
2133 $db->rollback();
2134 }
2135
2136 print '<br>';
2137
2138 print '</td></tr>';
2139}
2140
2149function migrate_modeles($db, $langs, $conf)
2150{
2151 //print '<br>';
2152 //print '<b>'.$langs->trans('UpdateModelsTable')."</b><br>\n";
2153
2154 dolibarr_install_syslog("upgrade2::migrate_modeles");
2155
2156 if (isModEnabled('invoice')) {
2157 include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
2158 $modellist = ModelePDFFactures::liste_modeles($db);
2159 if (count($modellist) == 0) {
2160 // Aucun model par default.
2161 $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('crabe','invoice')";
2162 $resql = $db->query($sql);
2163 if (!$resql) {
2164 dol_print_error($db);
2165 }
2166 }
2167 }
2168
2169 if (isModEnabled('order')) {
2170 include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
2171 $modellist = ModelePDFCommandes::liste_modeles($db);
2172 if (count($modellist) == 0) {
2173 // Aucun model par default.
2174 $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('einstein','order')";
2175 $resql = $db->query($sql);
2176 if (!$resql) {
2177 dol_print_error($db);
2178 }
2179 }
2180 }
2181
2182 if (isModEnabled("shipping")) {
2183 include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
2184 $modellist = ModelePdfExpedition::liste_modeles($db);
2185 if (count($modellist) == 0) {
2186 // Aucun model par default.
2187 $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('rouget','shipping')";
2188 $resql = $db->query($sql);
2189 if (!$resql) {
2190 dol_print_error($db);
2191 }
2192 }
2193 }
2194
2195 //print $langs->trans("AlreadyDone");
2196}
2197
2198
2207function migrate_commande_expedition($db, $langs, $conf)
2208{
2209 dolibarr_install_syslog("upgrade2::migrate_commande_expedition");
2210
2211 print '<tr><td colspan="4">';
2212
2213 print '<br>';
2214 print '<b>'.$langs->trans('MigrationShipmentOrderMatching')."</b><br>\n";
2215
2216 $result = $db->DDLDescTable(MAIN_DB_PREFIX."expedition", "fk_commande");
2217 $obj = $db->fetch_object($result);
2218 if ($obj) {
2219 $error = 0;
2220
2221 $db->begin();
2222
2223 $sql = "SELECT e.rowid, e.fk_commande FROM ".MAIN_DB_PREFIX."expedition as e";
2224 $resql = $db->query($sql);
2225 if ($resql) {
2226 $i = 0;
2227 $num = $db->num_rows($resql);
2228
2229 if ($num) {
2230 while ($i < $num) {
2231 $obj = $db->fetch_object($resql);
2232
2233 $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_exp (fk_expedition,fk_commande)";
2234 $sql .= " VALUES (".((int) $obj->rowid).", ".((int) $obj->fk_commande).")";
2235 $resql2 = $db->query($sql);
2236
2237 if (!$resql2) {
2238 $error++;
2239 dol_print_error($db);
2240 }
2241 print '. ';
2242 $i++;
2243 }
2244 }
2245
2246 if ($error == 0) {
2247 $db->commit();
2248 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."expedition DROP COLUMN fk_commande";
2249 print $langs->trans('FieldRenamed')."<br>\n";
2250 $db->query($sql);
2251 } else {
2252 $db->rollback();
2253 }
2254 } else {
2255 dol_print_error($db);
2256 $db->rollback();
2257 }
2258 } else {
2259 print $langs->trans('AlreadyDone')."<br>\n";
2260 }
2261 print '</td></tr>';
2262}
2263
2272function migrate_commande_livraison($db, $langs, $conf)
2273{
2274 dolibarr_install_syslog("upgrade2::migrate_commande_livraison");
2275
2276 print '<tr><td colspan="4">';
2277
2278 print '<br>';
2279 print '<b>'.$langs->trans('MigrationDeliveryOrderMatching')."</b><br>\n";
2280
2281 $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraison", "fk_commande");
2282 $obj = $db->fetch_object($result);
2283 if ($obj) {
2284 $error = 0;
2285
2286 $db->begin();
2287
2288 $sql = "SELECT l.rowid, l.fk_commande,";
2289 $sql .= " c.ref_client, c.date_livraison as delivery_date";
2290 $sql .= " FROM ".MAIN_DB_PREFIX."livraison as l, ".MAIN_DB_PREFIX."commande as c";
2291 $sql .= " WHERE c.rowid = l.fk_commande";
2292 $resql = $db->query($sql);
2293 if ($resql) {
2294 $i = 0;
2295 $num = $db->num_rows($resql);
2296
2297 if ($num) {
2298 while ($i < $num) {
2299 $obj = $db->fetch_object($resql);
2300
2301 $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_liv (fk_livraison,fk_commande)";
2302 $sql .= " VALUES (".((int) $obj->rowid).", ".((int) $obj->fk_commande).")";
2303 $resql2 = $db->query($sql);
2304
2305 if ($resql2) {
2306 $delivery_date = $db->jdate($obj->delivery_date);
2307
2308 $sqlu = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
2309 $sqlu .= " ref_client = '".$db->escape($obj->ref_client)."'";
2310 $sqlu .= ", date_livraison = '".$db->idate($delivery_date)."'";
2311 $sqlu .= " WHERE rowid = ".((int) $obj->rowid);
2312 $resql3 = $db->query($sqlu);
2313 if (!$resql3) {
2314 $error++;
2315 dol_print_error($db);
2316 }
2317 } else {
2318 $error++;
2319 dol_print_error($db);
2320 }
2321 print '. ';
2322 $i++;
2323 }
2324 }
2325
2326 if ($error == 0) {
2327 $db->commit();
2328 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraison DROP COLUMN fk_commande";
2329 print $langs->trans('FieldRenamed')."<br>\n";
2330 $db->query($sql);
2331 } else {
2332 $db->rollback();
2333 }
2334 } else {
2335 dol_print_error($db);
2336 $db->rollback();
2337 }
2338 } else {
2339 print $langs->trans('AlreadyDone')."<br>\n";
2340 }
2341 print '</td></tr>';
2342}
2343
2352function migrate_detail_livraison($db, $langs, $conf)
2353{
2354 dolibarr_install_syslog("upgrade2::migrate_detail_livraison");
2355
2356 print '<tr><td colspan="4">';
2357
2358 print '<br>';
2359 print '<b>'.$langs->trans('MigrationDeliveryDetail')."</b><br>\n";
2360
2361 // This is done if field fk_commande_ligne exists.
2362 // If not this means migration was already done.
2363 $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraisondet", "fk_commande_ligne");
2364 $obj = $db->fetch_object($result);
2365 if ($obj) {
2366 $error = 0;
2367
2368 $db->begin();
2369
2370 $sql = "SELECT cd.rowid, cd.fk_product, cd.description, cd.subprice, cd.total_ht";
2371 $sql .= ", ld.fk_livraison";
2372 $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."livraisondet as ld";
2373 $sql .= " WHERE ld.fk_commande_ligne = cd.rowid";
2374 $resql = $db->query($sql);
2375 if ($resql) {
2376 $i = 0;
2377 $num = $db->num_rows($resql);
2378
2379 if ($num) {
2380 while ($i < $num) {
2381 $obj = $db->fetch_object($resql);
2382
2383 $sql = "UPDATE ".MAIN_DB_PREFIX."livraisondet SET";
2384 $sql .= " fk_product = ".((int) $obj->fk_product);
2385 $sql .= ",description = '".$db->escape($obj->description)."'";
2386 $sql .= ",subprice = ".price2num($obj->subprice);
2387 $sql .= ",total_ht = ".price2num($obj->total_ht);
2388 $sql .= " WHERE fk_commande_ligne = ".((int) $obj->rowid);
2389 $resql2 = $db->query($sql);
2390
2391 if ($resql2) {
2392 $sql = "SELECT total_ht";
2393 $sql .= " FROM ".MAIN_DB_PREFIX."livraison";
2394 $sql .= " WHERE rowid = ".((int) $obj->fk_livraison);
2395 $resql3 = $db->query($sql);
2396
2397 if ($resql3) {
2398 $obju = $db->fetch_object($resql3);
2399 $total_ht = $obju->total_ht + $obj->total_ht;
2400
2401 $sqlu = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
2402 $sqlu .= " total_ht = ".price2num($total_ht, 'MT');
2403 $sqlu .= " WHERE rowid = ".((int) $obj->fk_livraison);
2404 $resql4 = $db->query($sqlu);
2405 if (!$resql4) {
2406 $error++;
2407 dol_print_error($db);
2408 }
2409 } else {
2410 $error++;
2411 dol_print_error($db);
2412 }
2413 } else {
2414 $error++;
2415 dol_print_error($db);
2416 }
2417 print '. ';
2418 $i++;
2419 }
2420 }
2421
2422 if ($error == 0) {
2423 $db->commit();
2424 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraisondet CHANGE fk_commande_ligne fk_origin_line integer";
2425 print $langs->trans('FieldRenamed')."<br>\n";
2426 $db->query($sql);
2427 } else {
2428 $db->rollback();
2429 }
2430 } else {
2431 dol_print_error($db);
2432 $db->rollback();
2433 }
2434 } else {
2435 $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraisondet", "fk_origin_line");
2436 $obj = $db->fetch_object($result);
2437 if (!$obj) {
2438 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraisondet ADD COLUMN fk_origin_line integer after fk_livraison";
2439 $db->query($sql);
2440 }
2441 print $langs->trans('AlreadyDone')."<br>\n";
2442 }
2443 print '</td></tr>';
2444}
2445
2454function migrate_stocks($db, $langs, $conf)
2455{
2456 dolibarr_install_syslog("upgrade2::migrate_stocks");
2457
2458 print '<tr><td colspan="4">';
2459
2460 print '<br>';
2461 print '<b>'.$langs->trans('MigrationStockDetail')."</b><br>\n";
2462
2463 $error = 0;
2464
2465 $db->begin();
2466
2467 $sql = "SELECT SUM(reel) as total, fk_product";
2468 $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
2469 $sql .= " GROUP BY fk_product";
2470 $resql = $db->query($sql);
2471 if ($resql) {
2472 $i = 0;
2473 $num = $db->num_rows($resql);
2474
2475 if ($num) {
2476 while ($i < $num) {
2477 $obj = $db->fetch_object($resql);
2478
2479 $sql = "UPDATE ".MAIN_DB_PREFIX."product SET";
2480 $sql .= " stock = ".price2num($obj->total, 'MS');
2481 $sql .= " WHERE rowid = ".((int) $obj->fk_product);
2482
2483 $resql2 = $db->query($sql);
2484 if ($resql2) {
2485 } else {
2486 $error++;
2487 dol_print_error($db);
2488 }
2489 print '. ';
2490 $i++;
2491 }
2492 }
2493
2494 if ($error == 0) {
2495 $db->commit();
2496 } else {
2497 $db->rollback();
2498 }
2499 } else {
2500 dol_print_error($db);
2501 $db->rollback();
2502 }
2503
2504 print '</td></tr>';
2505}
2506
2516function migrate_menus($db, $langs, $conf)
2517{
2518 dolibarr_install_syslog("upgrade2::migrate_menus");
2519
2520 print '<tr><td colspan="4">';
2521
2522 print '<br>';
2523 print '<b>'.$langs->trans('MigrationMenusDetail')."</b><br>\n";
2524
2525 $error = 0;
2526
2527 if ($db->DDLInfoTable(MAIN_DB_PREFIX."menu_constraint")) {
2528 $db->begin();
2529
2530 $sql = "SELECT m.rowid, mc.action";
2531 $sql .= " FROM ".MAIN_DB_PREFIX."menu_constraint as mc, ".MAIN_DB_PREFIX."menu_const as md, ".MAIN_DB_PREFIX."menu as m";
2532 $sql .= " WHERE md.fk_menu = m.rowid AND md.fk_constraint = mc.rowid";
2533 $sql .= " AND m.enabled = '1'";
2534 $resql = $db->query($sql);
2535 if ($resql) {
2536 $i = 0;
2537 $num = $db->num_rows($resql);
2538 if ($num) {
2539 while ($i < $num) {
2540 $obj = $db->fetch_object($resql);
2541
2542 $sql = "UPDATE ".MAIN_DB_PREFIX."menu SET";
2543 $sql .= " enabled = '".$db->escape($obj->action)."'";
2544 $sql .= " WHERE rowid = ".((int) $obj->rowid);
2545 $sql .= " AND enabled = '1'";
2546
2547 $resql2 = $db->query($sql);
2548 if ($resql2) {
2549 } else {
2550 $error++;
2551 dol_print_error($db);
2552 }
2553 print '. ';
2554 $i++;
2555 }
2556 }
2557
2558 if ($error == 0) {
2559 $db->commit();
2560 } else {
2561 $db->rollback();
2562 }
2563 } else {
2564 dol_print_error($db);
2565 $db->rollback();
2566 }
2567 } else {
2568 print $langs->trans('AlreadyDone')."<br>\n";
2569 }
2570
2571 print '</td></tr>';
2572}
2573
2583function migrate_commande_deliveryaddress($db, $langs, $conf)
2584{
2585 dolibarr_install_syslog("upgrade2::migrate_commande_deliveryaddress");
2586
2587 print '<tr><td colspan="4">';
2588
2589 print '<br>';
2590 print '<b>'.$langs->trans('MigrationDeliveryAddress')."</b><br>\n";
2591
2592 $error = 0;
2593
2594 if ($db->DDLInfoTable(MAIN_DB_PREFIX."co_exp")) {
2595 $db->begin();
2596
2597 $sql = "SELECT c.fk_adresse_livraison, ce.fk_expedition";
2598 $sql .= " FROM ".MAIN_DB_PREFIX."commande as c";
2599 $sql .= ", ".MAIN_DB_PREFIX."co_exp as ce";
2600 $sql .= " WHERE c.rowid = ce.fk_commande";
2601 $sql .= " AND c.fk_adresse_livraison IS NOT NULL AND c.fk_adresse_livraison != 0";
2602
2603 $resql = $db->query($sql);
2604 if ($resql) {
2605 $i = 0;
2606 $num = $db->num_rows($resql);
2607
2608 if ($num) {
2609 while ($i < $num) {
2610 $obj = $db->fetch_object($resql);
2611
2612 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
2613 $sql .= " fk_adresse_livraison = '".$db->escape($obj->fk_adresse_livraison)."'";
2614 $sql .= " WHERE rowid = ".((int) $obj->fk_expedition);
2615
2616 $resql2 = $db->query($sql);
2617 if (!$resql2) {
2618 $error++;
2619 dol_print_error($db);
2620 }
2621 print '. ';
2622 $i++;
2623 }
2624 } else {
2625 print $langs->trans('AlreadyDone')."<br>\n";
2626 }
2627
2628 if ($error == 0) {
2629 $db->commit();
2630 } else {
2631 $db->rollback();
2632 }
2633 } else {
2634 dol_print_error($db);
2635 $db->rollback();
2636 }
2637 } else {
2638 print $langs->trans('AlreadyDone')."<br>\n";
2639 }
2640
2641 print '</td></tr>';
2642}
2643
2653function migrate_restore_missing_links($db, $langs, $conf)
2654{
2655 dolibarr_install_syslog("upgrade2::migrate_restore_missing_links");
2656
2657 if (($db->type == 'mysql' || $db->type == 'mysqli')) {
2658 if (versioncompare($db->getVersionArray(), array(4, 0)) < 0) {
2659 dolibarr_install_syslog("upgrade2::migrate_restore_missing_links Version of database too old to make this migrate action");
2660 return 0;
2661 }
2662 }
2663 print '<tr><td colspan="4">';
2664
2665 print '<br>';
2666 print '<b>'.$langs->trans('MigrationFixData')."</b> (1)<br>\n";
2667
2668 $error = 0;
2669
2670
2671 // Restore missing link for this cross foreign key (link 1 <=> 1). Direction 1.
2672 $table1 = 'facturedet';
2673 $field1 = 'fk_remise_except';
2674 $table2 = 'societe_remise_except';
2675 $field2 = 'fk_facture_line';
2676
2677 $db->begin();
2678
2679 $sql = "SELECT t1.rowid, t1.".$field1." as field";
2680 $sql .= " FROM ".MAIN_DB_PREFIX.$table1." as t1";
2681 $sql .= " WHERE t1.".$field1." IS NOT NULL AND t1.".$field1." NOT IN";
2682 $sql .= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$table2." as t2";
2683 $sql .= " WHERE t1.rowid = t2.".$field2.")";
2684
2685 dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 1");
2686 $resql = $db->query($sql);
2687 if ($resql) {
2688 $i = 0;
2689 $num = $db->num_rows($resql);
2690
2691 if ($num) {
2692 while ($i < $num) {
2693 $obj = $db->fetch_object($resql);
2694
2695 print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.<br>';
2696
2697 $sql = "UPDATE ".MAIN_DB_PREFIX.$db->sanitize($table2)." SET";
2698 $sql .= " ".$db->sanitize($field2)." = '".$db->escape($obj->rowid)."'";
2699 $sql .= " WHERE rowid = ".((int) $obj->field);
2700
2701 $resql2 = $db->query($sql);
2702 if (!$resql2) {
2703 $error++;
2704 dol_print_error($db);
2705 }
2706 //print '. ';
2707 $i++;
2708 }
2709 } else {
2710 print $langs->trans('AlreadyDone')."<br>\n";
2711 }
2712
2713 if ($error == 0) {
2714 $db->commit();
2715 } else {
2716 $db->rollback();
2717 }
2718 } else {
2719 dol_print_error($db);
2720 $db->rollback();
2721 }
2722
2723 print '</td></tr>';
2724
2725
2726 print '<tr><td colspan="4">';
2727
2728 print '<br>';
2729 print '<b>'.$langs->trans('MigrationFixData')."</b> (2)<br>\n";
2730
2731 // Restore missing link for this cross foreign key (link 1 <=> 1). Direction 2.
2732 $table2 = 'facturedet';
2733 $field2 = 'fk_remise_except';
2734 $table1 = 'societe_remise_except';
2735 $field1 = 'fk_facture_line';
2736
2737 $db->begin();
2738
2739 $sql = "SELECT t1.rowid, t1.".$field1." as field";
2740 $sql .= " FROM ".MAIN_DB_PREFIX.$table1." as t1";
2741 $sql .= " WHERE t1.".$field1." IS NOT NULL AND t1.".$field1." NOT IN";
2742 $sql .= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$table2." as t2";
2743 $sql .= " WHERE t1.rowid = t2.".$field2.")";
2744
2745 dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 2");
2746 $resql = $db->query($sql);
2747 if ($resql) {
2748 $i = 0;
2749 $num = $db->num_rows($resql);
2750
2751 if ($num) {
2752 while ($i < $num) {
2753 $obj = $db->fetch_object($resql);
2754
2755 print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.<br>';
2756
2757 $sql = "UPDATE ".MAIN_DB_PREFIX.$db->sanitize($table2)." SET";
2758 $sql .= " ".$db->sanitize($field2)." = '".$db->escape($obj->rowid)."'";
2759 $sql .= " WHERE rowid = ".((int) $obj->field);
2760
2761 $resql2 = $db->query($sql);
2762 if (!$resql2) {
2763 $error++;
2764 dol_print_error($db);
2765 }
2766 //print '. ';
2767 $i++;
2768 }
2769 } else {
2770 print $langs->trans('AlreadyDone')."<br>\n";
2771 }
2772
2773 if ($error == 0) {
2774 $db->commit();
2775 } else {
2776 $db->rollback();
2777 }
2778 } else {
2779 dol_print_error($db);
2780 $db->rollback();
2781 }
2782
2783 print '</td></tr>';
2784
2785 return ($error ? -1 : 1);
2786}
2787
2796function migrate_project_user_resp($db, $langs, $conf)
2797{
2798 dolibarr_install_syslog("upgrade2::migrate_project_user_resp");
2799
2800 print '<tr><td colspan="4">';
2801
2802 print '<br>';
2803 print '<b>'.$langs->trans('MigrationProjectUserResp')."</b><br>\n";
2804
2805 $result = $db->DDLDescTable(MAIN_DB_PREFIX."projet", "fk_user_resp");
2806 $obj = $db->fetch_object($result);
2807 if ($obj) {
2808 $error = 0;
2809
2810 $db->begin();
2811
2812 $sql = "SELECT rowid, fk_user_resp FROM ".MAIN_DB_PREFIX."projet";
2813 $resql = $db->query($sql);
2814 if ($resql) {
2815 $i = 0;
2816 $num = $db->num_rows($resql);
2817
2818 if ($num) {
2819 while ($i < $num) {
2820 $obj = $db->fetch_object($resql);
2821
2822 $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact (";
2823 $sql2 .= "datecreate";
2824 $sql2 .= ", statut";
2825 $sql2 .= ", element_id";
2826 $sql2 .= ", fk_c_type_contact";
2827 $sql2 .= ", fk_socpeople";
2828 $sql2 .= ") VALUES (";
2829 $sql2 .= "'".$db->idate(dol_now())."'";
2830 $sql2 .= ", '4'";
2831 $sql2 .= ", ".$obj->rowid;
2832 $sql2 .= ", '160'";
2833 $sql2 .= ", ".$obj->fk_user_resp;
2834 $sql2 .= ")";
2835
2836 if ($obj->fk_user_resp > 0) {
2837 $resql2 = $db->query($sql2);
2838 if (!$resql2) {
2839 $error++;
2840 dol_print_error($db);
2841 }
2842 }
2843 print '. ';
2844
2845 $i++;
2846 }
2847 }
2848
2849 if ($error == 0) {
2850 $sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."projet DROP COLUMN fk_user_resp";
2851 if ($db->query($sqlDrop)) {
2852 $db->commit();
2853 } else {
2854 $db->rollback();
2855 }
2856 } else {
2857 $db->rollback();
2858 }
2859 } else {
2860 dol_print_error($db);
2861 $db->rollback();
2862 }
2863 } else {
2864 print $langs->trans('AlreadyDone')."<br>\n";
2865 }
2866 print '</td></tr>';
2867}
2868
2877function migrate_project_task_actors($db, $langs, $conf)
2878{
2879 dolibarr_install_syslog("upgrade2::migrate_project_task_actors");
2880
2881 print '<tr><td colspan="4">';
2882
2883 print '<br>';
2884 print '<b>'.$langs->trans('MigrationProjectTaskActors')."</b><br>\n";
2885
2886 if ($db->DDLInfoTable(MAIN_DB_PREFIX."projet_task_actors")) {
2887 $error = 0;
2888
2889 $db->begin();
2890
2891 $sql = "SELECT fk_projet_task as fk_project_task, fk_user FROM ".MAIN_DB_PREFIX."projet_task_actors";
2892 $resql = $db->query($sql);
2893 if ($resql) {
2894 $i = 0;
2895 $num = $db->num_rows($resql);
2896
2897 if ($num) {
2898 while ($i < $num) {
2899 $obj = $db->fetch_object($resql);
2900
2901 $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact (";
2902 $sql2 .= "datecreate";
2903 $sql2 .= ", statut";
2904 $sql2 .= ", element_id";
2905 $sql2 .= ", fk_c_type_contact";
2906 $sql2 .= ", fk_socpeople";
2907 $sql2 .= ") VALUES (";
2908 $sql2 .= "'".$db->idate(dol_now())."'";
2909 $sql2 .= ", '4'";
2910 $sql2 .= ", ".$obj->fk_project_task;
2911 $sql2 .= ", '180'";
2912 $sql2 .= ", ".$obj->fk_user;
2913 $sql2 .= ")";
2914
2915 $resql2 = $db->query($sql2);
2916
2917 if (!$resql2) {
2918 $error++;
2919 dol_print_error($db);
2920 }
2921 print '. ';
2922 $i++;
2923 }
2924 }
2925
2926 if ($error == 0) {
2927 $sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX."projet_task_actors";
2928 if ($db->query($sqlDrop)) {
2929 $db->commit();
2930 } else {
2931 $db->rollback();
2932 }
2933 } else {
2934 $db->rollback();
2935 }
2936 } else {
2937 dol_print_error($db);
2938 $db->rollback();
2939 }
2940 } else {
2941 print $langs->trans('AlreadyDone')."<br>\n";
2942 }
2943 print '</td></tr>';
2944}
2945
2959function migrate_relationship_tables($db, $langs, $conf, $table, $fk_source, $sourcetype, $fk_target, $targettype)
2960{
2961 print '<tr><td colspan="4">';
2962
2963 print '<br>';
2964 print '<b>'.$langs->trans('MigrationRelationshipTables', MAIN_DB_PREFIX.$table)."</b><br>\n";
2965
2966 $error = 0;
2967
2968 if ($db->DDLInfoTable(MAIN_DB_PREFIX.$table)) {
2969 dolibarr_install_syslog("upgrade2::migrate_relationship_tables table = ".MAIN_DB_PREFIX.$table);
2970
2971 $db->begin();
2972
2973 $sqlSelect = "SELECT ".$fk_source.", ".$fk_target;
2974 $sqlSelect .= " FROM ".MAIN_DB_PREFIX.$table;
2975
2976 $resql = $db->query($sqlSelect);
2977 if ($resql) {
2978 $i = 0;
2979 $num = $db->num_rows($resql);
2980
2981 if ($num) {
2982 while ($i < $num) {
2983 $obj = $db->fetch_object($resql);
2984
2985 $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
2986 $sqlInsert .= "fk_source";
2987 $sqlInsert .= ", sourcetype";
2988 $sqlInsert .= ", fk_target";
2989 $sqlInsert .= ", targettype";
2990 $sqlInsert .= ") VALUES (";
2991 $sqlInsert .= $obj->$fk_source;
2992 $sqlInsert .= ", '".$db->escape($sourcetype)."'";
2993 $sqlInsert .= ", ".$obj->$fk_target;
2994 $sqlInsert .= ", '".$db->escape($targettype)."'";
2995 $sqlInsert .= ")";
2996
2997 $result = $db->query($sqlInsert);
2998 if (!$result) {
2999 $error++;
3000 dol_print_error($db);
3001 }
3002 print '. ';
3003 $i++;
3004 }
3005 } else {
3006 print $langs->trans('AlreadyDone')."<br>\n";
3007 }
3008
3009 if ($error == 0) {
3010 $sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX.$table;
3011 if ($db->query($sqlDrop)) {
3012 $db->commit();
3013 } else {
3014 $db->rollback();
3015 }
3016 } else {
3017 $db->rollback();
3018 }
3019 } else {
3020 dol_print_error($db);
3021 $db->rollback();
3022 }
3023 } else {
3024 print $langs->trans('AlreadyDone')."<br>\n";
3025 }
3026
3027 print '</td></tr>';
3028}
3029
3038function migrate_element_time($db, $langs, $conf)
3039{
3040 dolibarr_install_syslog("upgrade2::migrate_element_time");
3041
3042 print '<tr><td colspan="4">';
3043
3044 print '<br>';
3045 print '<b>'.$langs->trans('MigrationProjectTaskTime')."</b><br>\n";
3046
3047 $error = 0;
3048
3049 $db->begin();
3050
3051 $sql = "SELECT rowid, fk_element, element_duration";
3052 $sql .= " FROM ".MAIN_DB_PREFIX."element_time";
3053 $resql = $db->query($sql);
3054 if ($resql) {
3055 $i = 0;
3056 $num = $db->num_rows($resql);
3057
3058 if ($num) {
3059 $totaltime = array();
3060 $oldtime = 0;
3061
3062 while ($i < $num) {
3063 $obj = $db->fetch_object($resql);
3064
3065 if ($obj->element_duration > 0) {
3066 // convert to second
3067 // only for int time and float time ex: 1.75 for 1h45
3068 list($hour, $min) = explode('.', $obj->element_duration);
3069 $hour = (int) $hour * 60 * 60;
3070 $min = (int) ((float) ('.'.$min)) * 3600;
3071 $newtime = $hour + $min;
3072
3073 $sql2 = "UPDATE ".MAIN_DB_PREFIX."element_time SET";
3074 $sql2 .= " element_duration = ".((int) $newtime);
3075 $sql2 .= " WHERE rowid = ".((int) $obj->rowid);
3076
3077 $resql2 = $db->query($sql2);
3078 if (!$resql2) {
3079 $error++;
3080 dol_print_error($db);
3081 }
3082 print '. ';
3083 $oldtime++;
3084 if (!empty($totaltime[$obj->fk_element])) {
3085 $totaltime[$obj->fk_element] += $newtime;
3086 } else {
3087 $totaltime[$obj->fk_element] = $newtime;
3088 }
3089 } else {
3090 if (!empty($totaltime[$obj->fk_element])) {
3091 $totaltime[$obj->fk_element] += $obj->element_duration;
3092 } else {
3093 $totaltime[$obj->fk_element] = $obj->element_duration;
3094 }
3095 }
3096
3097 $i++;
3098 }
3099
3100 if ($error == 0) {
3101 if ($oldtime > 0) {
3102 foreach ($totaltime as $taskid => $total_duration) {
3103 $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET";
3104 $sql .= " duration_effective = ".((int) $total_duration);
3105 $sql .= " WHERE rowid = ".((int) $taskid);
3106
3107 $resql = $db->query($sql);
3108 if (!$resql) {
3109 $error++;
3110 dol_print_error($db);
3111 }
3112 }
3113 } else {
3114 print $langs->trans('AlreadyDone')."<br>\n";
3115 }
3116 } else {
3117 dol_print_error($db);
3118 }
3119 } else {
3120 print $langs->trans('AlreadyDone')."<br>\n";
3121 }
3122 } else {
3123 dol_print_error($db);
3124 }
3125
3126 if ($error == 0) {
3127 $db->commit();
3128 } else {
3129 $db->rollback();
3130 }
3131
3132 print '</td></tr>';
3133}
3134
3143function migrate_customerorder_shipping($db, $langs, $conf)
3144{
3145 print '<tr><td colspan="4">';
3146
3147 print '<br>';
3148 print '<b>'.$langs->trans('MigrationCustomerOrderShipping')."</b><br>\n";
3149
3150 $error = 0;
3151
3152 $result1 = $db->DDLDescTable(MAIN_DB_PREFIX."expedition", "ref_customer");
3153 $result2 = $db->DDLDescTable(MAIN_DB_PREFIX."expedition", "date_delivery");
3154 $obj1 = $db->fetch_object($result1);
3155 $obj2 = $db->fetch_object($result2);
3156 if (!$obj1 && !$obj2) {
3157 dolibarr_install_syslog("upgrade2::migrate_customerorder_shipping");
3158
3159 $db->begin();
3160
3161 $sqlAdd1 = "ALTER TABLE ".MAIN_DB_PREFIX."expedition ADD COLUMN ref_customer varchar(30) AFTER entity";
3162 $sqlAdd2 = "ALTER TABLE ".MAIN_DB_PREFIX."expedition ADD COLUMN date_delivery date DEFAULT NULL AFTER date_expedition";
3163
3164 if ($db->query($sqlAdd1) && $db->query($sqlAdd2)) {
3165 $sqlSelect = "SELECT e.rowid as shipping_id, c.ref_client, c.date_livraison as delivery_date";
3166 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."expedition as e";
3167 $sqlSelect .= ", ".MAIN_DB_PREFIX."element_element as el";
3168 $sqlSelect .= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON c.rowid = el.fk_source AND el.sourcetype = 'commande'";
3169 $sqlSelect .= " WHERE e.rowid = el.fk_target";
3170 $sqlSelect .= " AND el.targettype = 'shipping'";
3171
3172 $resql = $db->query($sqlSelect);
3173 if ($resql) {
3174 $i = 0;
3175 $num = $db->num_rows($resql);
3176
3177 if ($num) {
3178 while ($i < $num) {
3179 $obj = $db->fetch_object($resql);
3180
3181 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
3182 $sqlUpdate .= " ref_customer = '".$db->escape($obj->ref_client)."'";
3183 $sqlUpdate .= ", date_delivery = '".$db->escape($obj->delivery_date ? $obj->delivery_date : 'null')."'";
3184 $sqlUpdate .= " WHERE rowid = ".((int) $obj->shipping_id);
3185
3186 $result = $db->query($sqlUpdate);
3187 if (!$result) {
3188 $error++;
3189 dol_print_error($db);
3190 }
3191 print '. ';
3192 $i++;
3193 }
3194 } else {
3195 print $langs->trans('AlreadyDone')."<br>\n";
3196 }
3197
3198 if ($error == 0) {
3199 $db->commit();
3200 } else {
3201 dol_print_error($db);
3202 $db->rollback();
3203 }
3204 } else {
3205 dol_print_error($db);
3206 $db->rollback();
3207 }
3208 } else {
3209 dol_print_error($db);
3210 $db->rollback();
3211 }
3212 } else {
3213 print $langs->trans('AlreadyDone')."<br>\n";
3214 }
3215
3216 print '</td></tr>';
3217}
3218
3227function migrate_shipping_delivery($db, $langs, $conf)
3228{
3229 print '<tr><td colspan="4">';
3230
3231 print '<br>';
3232 print '<b>'.$langs->trans('MigrationShippingDelivery')."</b><br>\n";
3233
3234 $error = 0;
3235
3236 $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraison", "fk_expedition");
3237 $obj = $db->fetch_object($result);
3238 if ($obj) {
3239 dolibarr_install_syslog("upgrade2::migrate_shipping_delivery");
3240
3241 $db->begin();
3242
3243 $sqlSelect = "SELECT rowid, fk_expedition";
3244 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."livraison";
3245 $sqlSelect .= " WHERE fk_expedition is not null";
3246
3247 $resql = $db->query($sqlSelect);
3248 if ($resql) {
3249 $i = 0;
3250 $num = $db->num_rows($resql);
3251
3252 if ($num) {
3253 while ($i < $num) {
3254 $obj = $db->fetch_object($resql);
3255
3256 $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
3257 $sqlInsert .= "fk_source";
3258 $sqlInsert .= ", sourcetype";
3259 $sqlInsert .= ", fk_target";
3260 $sqlInsert .= ", targettype";
3261 $sqlInsert .= ") VALUES (";
3262 $sqlInsert .= $obj->fk_expedition;
3263 $sqlInsert .= ", 'shipping'";
3264 $sqlInsert .= ", ".$obj->rowid;
3265 $sqlInsert .= ", 'delivery'";
3266 $sqlInsert .= ")";
3267
3268 $result = $db->query($sqlInsert);
3269 if ($result) {
3270 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET fk_expedition = NULL";
3271 $sqlUpdate .= " WHERE rowid = ".((int) $obj->rowid);
3272
3273 $result = $db->query($sqlUpdate);
3274 if (!$result) {
3275 $error++;
3276 dol_print_error($db);
3277 }
3278 print '. ';
3279 } else {
3280 $error++;
3281 dol_print_error($db);
3282 }
3283 $i++;
3284 }
3285 } else {
3286 print $langs->trans('AlreadyDone')."<br>\n";
3287 }
3288
3289 if ($error == 0) {
3290 $sqlDelete = "DELETE FROM ".MAIN_DB_PREFIX."element_element WHERE sourcetype = 'commande' AND targettype = 'delivery'";
3291 $db->query($sqlDelete);
3292
3293 $db->commit();
3294
3295 // DDL commands must not be inside a transaction
3296 $sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."livraison DROP COLUMN fk_expedition";
3297 $db->query($sqlDrop);
3298 } else {
3299 dol_print_error($db);
3300 $db->rollback();
3301 }
3302 } else {
3303 dol_print_error($db);
3304 $db->rollback();
3305 }
3306 } else {
3307 print $langs->trans('AlreadyDone')."<br>\n";
3308 }
3309
3310 print '</td></tr>';
3311}
3312
3322function migrate_shipping_delivery2($db, $langs, $conf)
3323{
3324 print '<tr><td colspan="4">';
3325
3326 print '<br>';
3327 print '<b>'.$langs->trans('MigrationShippingDelivery2')."</b><br>\n";
3328
3329 $error = 0;
3330
3331 dolibarr_install_syslog("upgrade2::migrate_shipping_delivery2");
3332
3333 $db->begin();
3334
3335 $sqlSelect = "SELECT l.rowid as delivery_id, e.ref_customer, e.date_delivery";
3336 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."livraison as l,";
3337 $sqlSelect .= " ".MAIN_DB_PREFIX."element_element as el,";
3338 $sqlSelect .= " ".MAIN_DB_PREFIX."expedition as e";
3339 $sqlSelect .= " WHERE l.rowid = el.fk_target";
3340 $sqlSelect .= " AND el.targettype = 'delivery'";
3341 $sqlSelect .= " AND e.rowid = el.fk_source AND el.sourcetype = 'shipping'";
3342 $sqlSelect .= " AND (e.ref_customer IS NOT NULL OR e.date_delivery IS NOT NULL)"; // Useless to process this record if both are null
3343 // Add condition to know if we never migrate this record
3344 $sqlSelect .= " AND (l.ref_customer IS NULL".($db->type != 'pgsql' ? " or l.ref_customer = ''" : "").")";
3345 $sqlSelect .= " AND (l.date_delivery IS NULL".($db->type != 'pgsql' ? " or l.date_delivery = ''" : "").")";
3346
3347 $resql = $db->query($sqlSelect);
3348 if ($resql) {
3349 $i = 0;
3350 $num = $db->num_rows($resql);
3351
3352 if ($num) {
3353 while ($i < $num) {
3354 $obj = $db->fetch_object($resql);
3355
3356 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
3357 $sqlUpdate .= " ref_customer = '".$db->escape($obj->ref_customer)."',";
3358 $sqlUpdate .= " date_delivery = ".($obj->date_delivery ? "'".$db->escape($obj->date_delivery)."'" : 'null');
3359 $sqlUpdate .= " WHERE rowid = ".((int) $obj->delivery_id);
3360
3361 $result = $db->query($sqlUpdate);
3362 if (!$result) {
3363 $error++;
3364 dol_print_error($db);
3365 }
3366 print '. ';
3367 $i++;
3368 }
3369 } else {
3370 print $langs->trans('AlreadyDone')."<br>\n";
3371 }
3372
3373 if ($error == 0) {
3374 $db->commit();
3375 } else {
3376 dol_print_error($db);
3377 $db->rollback();
3378 }
3379 } else {
3380 dol_print_error($db);
3381 $db->rollback();
3382 }
3383
3384 print '</td></tr>';
3385}
3386
3395function migrate_actioncomm_element($db, $langs, $conf)
3396{
3397 print '<tr><td colspan="4">';
3398
3399 print '<br>';
3400 print '<b>'.$langs->trans('MigrationActioncommElement')."</b><br>\n";
3401
3402 $elements = array(
3403 'propal' => 'propalrowid',
3404 'order' => 'fk_commande',
3405 'invoice' => 'fk_facture',
3406 'contract' => 'fk_contract',
3407 'order_supplier' => 'fk_supplier_order',
3408 'invoice_supplier' => 'fk_supplier_invoice'
3409 );
3410
3411 foreach ($elements as $type => $field) {
3412 $result = $db->DDLDescTable(MAIN_DB_PREFIX."actioncomm", $field);
3413 $obj = $db->fetch_object($result);
3414 if ($obj) {
3415 dolibarr_install_syslog("upgrade2::migrate_actioncomm_element field=".$field);
3416
3417 $db->begin();
3418
3419 $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm SET ";
3420 $sql .= "fk_element = ".$db->sanitize($field).", elementtype = '".$db->escape($type)."'";
3421 $sql .= " WHERE ".$db->sanitize($field)." IS NOT NULL";
3422 $sql .= " AND fk_element IS NULL";
3423 $sql .= " AND elementtype IS NULL";
3424
3425 $resql = $db->query($sql);
3426 if ($resql) {
3427 $db->commit();
3428
3429 // DDL commands must not be inside a transaction
3430 // We will drop at next version because a migrate should be runnable several times if it fails.
3431 //$sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."actioncomm DROP COLUMN ".$field;
3432 //$db->query($sqlDrop);
3433 //print '. ';
3434 } else {
3435 dol_print_error($db);
3436 $db->rollback();
3437 }
3438 } else {
3439 print $langs->trans('AlreadyDone')."<br>\n";
3440 }
3441 }
3442
3443 print '</td></tr>';
3444}
3445
3454function migrate_mode_reglement($db, $langs, $conf)
3455{
3456 print '<tr><td colspan="4">';
3457
3458 print '<br>';
3459 print '<b>'.$langs->trans('MigrationPaymentMode')."</b><br>\n";
3460
3461 $elements = array(
3462 'old_id' => array(5, 8, 9, 10, 11),
3463 'new_id' => array(50, 51, 52, 53, 54),
3464 'code' => array('VAD', 'TRA', 'LCR', 'FAC', 'PRO'),
3465 'tables' => array('commande_fournisseur', 'commande', 'facture_rec', 'facture', 'propal')
3466 );
3467 $count = 0;
3468
3469 foreach ($elements['old_id'] as $key => $old_id) {
3470 $error = 0;
3471
3472 dolibarr_install_syslog("upgrade2::migrate_mode_reglement code=".$elements['code'][$key]);
3473
3474 $sqlSelect = "SELECT id";
3475 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."c_paiement";
3476 $sqlSelect .= " WHERE id = ".((int) $old_id);
3477 $sqlSelect .= " AND code = '".$db->escape($elements['code'][$key])."'";
3478
3479 $resql = $db->query($sqlSelect);
3480 if ($resql) {
3481 $num = $db->num_rows($resql);
3482 if ($num) {
3483 $count++;
3484
3485 $db->begin();
3486
3487 $sqla = "UPDATE ".MAIN_DB_PREFIX."paiement SET";
3488 $sqla .= " fk_paiement = ".((int) $elements['new_id'][$key]);
3489 $sqla .= " WHERE fk_paiement = ".((int) $old_id);
3490 $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])."')";
3491 $resqla = $db->query($sqla);
3492
3493 $sql = "UPDATE ".MAIN_DB_PREFIX."c_paiement SET";
3494 $sql .= " id = ".((int) $elements['new_id'][$key]);
3495 $sql .= " WHERE id = ".((int) $old_id);
3496 $sql .= " AND code = '".$db->escape($elements['code'][$key])."'";
3497 $resql = $db->query($sql);
3498
3499 if ($resqla && $resql) {
3500 foreach ($elements['tables'] as $table) {
3501 $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
3502 $sql .= "fk_mode_reglement = ".((int) $elements['new_id'][$key]);
3503 $sql .= " WHERE fk_mode_reglement = ".((int) $old_id);
3504
3505 $resql = $db->query($sql);
3506 if (!$resql) {
3507 dol_print_error($db);
3508 $error++;
3509 }
3510 print '. ';
3511 }
3512
3513 if (!$error) {
3514 $db->commit();
3515 } else {
3516 dol_print_error($db);
3517 $db->rollback();
3518 }
3519 } else {
3520 dol_print_error($db);
3521 $db->rollback();
3522 }
3523 }
3524 }
3525 }
3526
3527 if ($count == 0) {
3528 print $langs->trans('AlreadyDone')."<br>\n";
3529 }
3530
3531
3532 print '</td></tr>';
3533}
3534
3535
3544function migrate_clean_association($db, $langs, $conf)
3545{
3546 $result = $db->DDLDescTable(MAIN_DB_PREFIX."categorie_association");
3547 if ($result) { // result defined for version 3.2 or -
3548 $obj = $db->fetch_object($result);
3549 if ($obj) { // It table categorie_association exists
3550 $couples = array();
3551 $children = array();
3552 $sql = "SELECT fk_categorie_mere, fk_categorie_fille";
3553 $sql .= " FROM ".MAIN_DB_PREFIX."categorie_association";
3554 dolibarr_install_syslog("upgrade: search duplicate");
3555 $resql = $db->query($sql);
3556 if ($resql) {
3557 $num = $db->num_rows($resql);
3558 while ($obj = $db->fetch_object($resql)) {
3559 if (!isset($children[$obj->fk_categorie_fille])) { // Only one record as child (a child has only on parent).
3560 if ($obj->fk_categorie_mere != $obj->fk_categorie_fille) {
3561 $children[$obj->fk_categorie_fille] = 1; // Set record for this child
3562 $couples[$obj->fk_categorie_mere.'_'.$obj->fk_categorie_fille] = array('mere' => $obj->fk_categorie_mere, 'fille' => $obj->fk_categorie_fille);
3563 }
3564 }
3565 }
3566
3567 dolibarr_install_syslog("upgrade: result is num=".$num." count(couples)=".count($couples));
3568
3569 // If there is duplicates couples or child with two parents
3570 if (count($couples) > 0 && $num > count($couples)) {
3571 $error = 0;
3572
3573 $db->begin();
3574
3575 // We delete all
3576 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_association";
3577 dolibarr_install_syslog("upgrade: delete association");
3578 $resqld = $db->query($sql);
3579 if ($resqld) {
3580 // And we insert only each record once
3581 foreach ($couples as $key => $val) {
3582 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_association(fk_categorie_mere,fk_categorie_fille)";
3583 $sql .= " VALUES(".((int) $val['mere']).", ".((int) $val['fille']).")";
3584 dolibarr_install_syslog("upgrade: insert association");
3585 $resqli = $db->query($sql);
3586 if (!$resqli) {
3587 $error++;
3588 }
3589 }
3590 }
3591
3592 if (!$error) {
3593 print '<tr><td>'.$langs->trans("MigrationCategorieAssociation").'</td>';
3594 print '<td class="right">'.$langs->trans("RemoveDuplicates").' '.$langs->trans("Success").' ('.$num.'=>'.count($couples).')</td></tr>';
3595 $db->commit();
3596 } else {
3597 print '<tr><td>'.$langs->trans("MigrationCategorieAssociation").'</td>';
3598 print '<td class="right">'.$langs->trans("RemoveDuplicates").' '.$langs->trans("Failed").'</td></tr>';
3599 $db->rollback();
3600 }
3601 }
3602 } else {
3603 print '<tr><td>'.$langs->trans("Error").'</td>';
3604 print '<td class="right"><div class="error">'.$db->lasterror().'</div></td></tr>';
3605 }
3606 }
3607 }
3608}
3609
3610
3619function migrate_categorie_association($db, $langs, $conf)
3620{
3621 print '<tr><td colspan="4">';
3622
3623 print '<br>';
3624 print '<b>'.$langs->trans('MigrationCategorieAssociation')."</b><br>\n";
3625
3626 $error = 0;
3627
3628 if ($db->DDLInfoTable(MAIN_DB_PREFIX."categorie_association")) {
3629 dolibarr_install_syslog("upgrade2::migrate_categorie_association");
3630
3631 $db->begin();
3632
3633 $sqlSelect = "SELECT fk_categorie_mere, fk_categorie_fille";
3634 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."categorie_association";
3635
3636 $resql = $db->query($sqlSelect);
3637 if ($resql) {
3638 $i = 0;
3639 $num = $db->num_rows($resql);
3640
3641 if ($num) {
3642 while ($i < $num) {
3643 $obj = $db->fetch_object($resql);
3644
3645 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."categorie SET ";
3646 $sqlUpdate .= "fk_parent = ".((int) $obj->fk_categorie_mere);
3647 $sqlUpdate .= " WHERE rowid = ".((int) $obj->fk_categorie_fille);
3648
3649 $result = $db->query($sqlUpdate);
3650 if (!$result) {
3651 $error++;
3652 dol_print_error($db);
3653 }
3654 print '. ';
3655 $i++;
3656 }
3657 } else {
3658 print $langs->trans('AlreadyDone')."<br>\n";
3659 }
3660
3661 if (!$error) {
3662 $db->commit();
3663 } else {
3664 $db->rollback();
3665 }
3666 } else {
3667 dol_print_error($db);
3668 $db->rollback();
3669 }
3670 } else {
3671 print $langs->trans('AlreadyDone')."<br>\n";
3672 }
3673
3674 print '</td></tr>';
3675}
3676
3685function migrate_event_assignement($db, $langs, $conf)
3686{
3687 print '<tr><td colspan="4">';
3688
3689 print '<br>';
3690 print '<b>'.$langs->trans('MigrationEvents')."</b><br>\n";
3691
3692 $error = 0;
3693
3694 dolibarr_install_syslog("upgrade2::migrate_event_assignement");
3695
3696 $db->begin();
3697
3698 $sqlSelect = "SELECT a.id, a.fk_user_action";
3699 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
3700 $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";
3701 $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')";
3702 $sqlSelect .= " ORDER BY a.id";
3703 //print $sqlSelect;
3704
3705 $resql = $db->query($sqlSelect);
3706 if ($resql) {
3707 $i = 0;
3708 $num = $db->num_rows($resql);
3709
3710 if ($num) {
3711 while ($i < $num) {
3712 $obj = $db->fetch_object($resql);
3713
3714 $sqlUpdate = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element) ";
3715 $sqlUpdate .= "VALUES(".((int) $obj->id).", 'user', ".((int) $obj->fk_user_action).")";
3716
3717 $result = $db->query($sqlUpdate);
3718 if (!$result) {
3719 $error++;
3720 dol_print_error($db);
3721 }
3722 print '. ';
3723 $i++;
3724 }
3725 } else {
3726 print $langs->trans('AlreadyDone')."<br>\n";
3727 }
3728
3729 if (!$error) {
3730 $db->commit();
3731 } else {
3732 $db->rollback();
3733 }
3734 } else {
3735 dol_print_error($db);
3736 $db->rollback();
3737 }
3738
3739
3740 print '</td></tr>';
3741}
3742
3751function migrate_event_assignement_contact($db, $langs, $conf)
3752{
3753 print '<tr><td colspan="4">';
3754
3755 print '<br>';
3756 print '<b>'.$langs->trans('MigrationEventsContact')."</b><br>\n";
3757
3758 $error = 0;
3759
3760 dolibarr_install_syslog("upgrade2::migrate_event_assignement");
3761
3762 $db->begin();
3763
3764 $sqlSelect = "SELECT a.id, a.fk_contact";
3765 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
3766 $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";
3767 $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')";
3768 $sqlSelect .= " ORDER BY a.id";
3769 //print $sqlSelect;
3770
3771 $resql = $db->query($sqlSelect);
3772 if ($resql) {
3773 $i = 0;
3774 $num = $db->num_rows($resql);
3775
3776 if ($num) {
3777 while ($i < $num) {
3778 $obj = $db->fetch_object($resql);
3779
3780 $sqlUpdate = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element) ";
3781 $sqlUpdate .= "VALUES(".((int) $obj->id).", 'socpeople', ".((int) $obj->fk_contact).")";
3782
3783 $result = $db->query($sqlUpdate);
3784 if (!$result) {
3785 $error++;
3786 dol_print_error($db);
3787 }
3788 print '. ';
3789 $i++;
3790 }
3791 } else {
3792 print $langs->trans('AlreadyDone')."<br>\n";
3793 }
3794
3795 if (!$error) {
3796 $db->commit();
3797 } else {
3798 $db->rollback();
3799 }
3800 } else {
3801 dol_print_error($db);
3802 $db->rollback();
3803 }
3804
3805
3806 print '</td></tr>';
3807}
3808
3809
3818function migrate_reset_blocked_log($db, $langs, $conf)
3819{
3820 global $user;
3821
3822 require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php';
3823
3824 print '<tr><td colspan="4">';
3825
3826 print '<br>';
3827 print '<b>'.$langs->trans('MigrationResetBlockedLog')."</b><br>\n";
3828
3829 $error = 0;
3830
3831 dolibarr_install_syslog("upgrade2::migrate_reset_blocked_log");
3832
3833 $db->begin();
3834
3835 $sqlSelect = "SELECT DISTINCT entity";
3836 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."blockedlog";
3837
3838 //print $sqlSelect;
3839
3840 $resql = $db->query($sqlSelect);
3841 if ($resql) {
3842 $i = 0;
3843 $num = $db->num_rows($resql);
3844
3845 if ($num) {
3846 while ($i < $num) {
3847 $obj = $db->fetch_object($resql);
3848
3849 print 'Process entity '.$obj->entity;
3850
3851 $sqlSearch = "SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."blockedlog WHERE action = 'MODULE_SET' and entity = ".((int) $obj->entity);
3852 $resqlSearch = $db->query($sqlSearch);
3853 if ($resqlSearch) {
3854 $objSearch = $db->fetch_object($resqlSearch);
3855 //var_dump($objSearch);
3856 if ($objSearch && $objSearch->nb == 0) {
3857 print ' - Record for entity must be reset...';
3858
3859 $sqlUpdate = "DELETE FROM ".MAIN_DB_PREFIX."blockedlog";
3860 $sqlUpdate .= " WHERE entity = ".((int) $obj->entity);
3861 $resqlUpdate = $db->query($sqlUpdate);
3862 if (!$resqlUpdate) {
3863 $error++;
3864 dol_print_error($db);
3865 } else {
3866 // Add set line
3867 $object = new stdClass();
3868 $object->id = 1;
3869 $object->element = 'module';
3870 $object->ref = 'systemevent';
3871 $object->entity = $obj->entity;
3872 $object->date = dol_now();
3873
3874 $b = new BlockedLog($db);
3875 $b->setObjectData($object, 'MODULE_SET', 0, $user, null);
3876
3877 $res = $b->create($user);
3878 if ($res <= 0) {
3879 $error++;
3880 }
3881 }
3882 } else {
3883 print ' - '.$langs->trans('AlreadyInV7').'<br>';
3884 }
3885 } else {
3886 dol_print_error($db);
3887 }
3888
3889 $i++;
3890 }
3891 } else {
3892 print $langs->trans('NothingToDo')."<br>\n";
3893 }
3894
3895 if (!$error) {
3896 $db->commit();
3897 } else {
3898 $db->rollback();
3899 }
3900 } else {
3901 dol_print_error($db);
3902 $db->rollback();
3903 }
3904
3905 print '</td></tr>';
3906}
3907
3908
3917function migrate_remise_entity($db, $langs, $conf)
3918{
3919 print '<tr><td colspan="4">';
3920
3921 print '<br>';
3922 print '<b>'.$langs->trans('MigrationRemiseEntity')."</b><br>\n";
3923
3924 $error = 0;
3925
3926 dolibarr_install_syslog("upgrade2::migrate_remise_entity");
3927
3928 $db->begin();
3929
3930 $sqlSelect = "SELECT sr.rowid, s.entity";
3931 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."societe_remise as sr, ".MAIN_DB_PREFIX."societe as s";
3932 $sqlSelect .= " WHERE sr.fk_soc = s.rowid and sr.entity != s.entity";
3933
3934 //print $sqlSelect;
3935
3936 $resql = $db->query($sqlSelect);
3937 if ($resql) {
3938 $i = 0;
3939 $num = $db->num_rows($resql);
3940
3941 if ($num) {
3942 while ($i < $num) {
3943 $obj = $db->fetch_object($resql);
3944
3945 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise SET";
3946 $sqlUpdate .= " entity = ".$obj->entity;
3947 $sqlUpdate .= " WHERE rowid = ".((int) $obj->rowid);
3948
3949 $result = $db->query($sqlUpdate);
3950 if (!$result) {
3951 $error++;
3952 dol_print_error($db);
3953 }
3954
3955 print '. ';
3956 $i++;
3957 }
3958 } else {
3959 print $langs->trans('AlreadyDone')."<br>\n";
3960 }
3961
3962 if (!$error) {
3963 $db->commit();
3964 } else {
3965 $db->rollback();
3966 }
3967 } else {
3968 dol_print_error($db);
3969 $db->rollback();
3970 }
3971
3972 print '</td></tr>';
3973}
3974
3983function migrate_remise_except_entity($db, $langs, $conf)
3984{
3985 print '<tr><td colspan="4">';
3986
3987 print '<br>';
3988 print '<b>'.$langs->trans('MigrationRemiseExceptEntity')."</b><br>\n";
3989
3990 $error = 0;
3991
3992 dolibarr_install_syslog("upgrade2::migrate_remise_except_entity");
3993
3994 $db->begin();
3995
3996 $sqlSelect = "SELECT sr.rowid, sr.fk_soc, sr.fk_facture_source, sr.fk_facture, sr.fk_facture_line";
3997 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr";
3998 //print $sqlSelect;
3999
4000 $resql = $db->query($sqlSelect);
4001 if ($resql) {
4002 $i = 0;
4003 $num = $db->num_rows($resql);
4004
4005 if ($num) {
4006 while ($i < $num) {
4007 $obj = $db->fetch_object($resql);
4008
4009 if (!empty($obj->fk_facture_source) || !empty($obj->fk_facture)) {
4010 $fk_facture = (!empty($obj->fk_facture_source) ? $obj->fk_facture_source : $obj->fk_facture);
4011
4012 $sqlSelect2 = "SELECT f.entity";
4013 $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."facture as f";
4014 $sqlSelect2 .= " WHERE f.rowid = ".((int) $fk_facture);
4015 } elseif (!empty($obj->fk_facture_line)) {
4016 $sqlSelect2 = "SELECT f.entity";
4017 $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as fd";
4018 $sqlSelect2 .= " WHERE fd.rowid = ".((int) $obj->fk_facture_line);
4019 $sqlSelect2 .= " AND fd.fk_facture = f.rowid";
4020 } else {
4021 $sqlSelect2 = "SELECT s.entity";
4022 $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."societe as s";
4023 $sqlSelect2 .= " WHERE s.rowid = ".((int) $obj->fk_soc);
4024 }
4025
4026 $resql2 = $db->query($sqlSelect2);
4027 if ($resql2) {
4028 if ($db->num_rows($resql2) > 0) {
4029 $obj2 = $db->fetch_object($resql2);
4030
4031 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except SET";
4032 $sqlUpdate .= " entity = ".((int) $obj2->entity);
4033 $sqlUpdate .= " WHERE rowid = ".((int) $obj->rowid);
4034
4035 $result = $db->query($sqlUpdate);
4036 if (!$result) {
4037 $error++;
4038 dol_print_error($db);
4039 }
4040 }
4041 } else {
4042 $error++;
4043 dol_print_error($db);
4044 }
4045
4046 print '. ';
4047 $i++;
4048 }
4049 } else {
4050 print $langs->trans('AlreadyDone')."<br>\n";
4051 }
4052
4053 if (!$error) {
4054 $db->commit();
4055 } else {
4056 $db->rollback();
4057 }
4058 } else {
4059 dol_print_error($db);
4060 $db->rollback();
4061 }
4062
4063
4064 print '</td></tr>';
4065}
4066
4083function migrate_supplier_prices_permissions($db, $langs, $conf)
4084{
4085 dolibarr_install_syslog("upgrade2::migrate_supplier_prices_permissions");
4086
4087 // Grant each target permission to holders of any of its source permissions.
4088 // Format: array('to' => array(module, perms, subperms), 'from' => array(array(module, perms, subperms), ...))
4089 $rules = array(
4090 array('to' => array('produit', 'product_advance', 'read_supplier_prices'), 'from' => array(array('produit', 'lire', ''), array('produit', 'creer', ''))),
4091 array('to' => array('produit', 'product_advance', 'write_supplier_prices'), 'from' => array(array('produit', 'creer', ''))),
4092 array('to' => array('service', 'service_advance', 'read_supplier_prices'), 'from' => array(array('service', 'lire', ''))),
4093 );
4094
4095 $error = 0;
4096 $db->begin();
4097
4098 foreach ($rules as $rule) {
4099 // Resolve the target permission id by name (skip if the module/permission is not present)
4100 $targetid = migrate_get_rights_def_id($db, $rule['to'][0], $rule['to'][1], $rule['to'][2]);
4101 if ($targetid <= 0) {
4102 continue;
4103 }
4104
4105 // Resolve the source permission ids by name
4106 $sourceids = array();
4107 foreach ($rule['from'] as $from) {
4108 $id = migrate_get_rights_def_id($db, $from[0], $from[1], $from[2]);
4109 if ($id > 0) {
4110 $sourceids[] = $id;
4111 }
4112 }
4113 if (empty($sourceids)) {
4114 continue;
4115 }
4116 $sourcelist = implode(',', $sourceids);
4117
4118 // Grant to groups that hold a source permission but not yet the target
4119 $sql = "INSERT INTO ".MAIN_DB_PREFIX."usergroup_rights (entity, fk_usergroup, fk_id)";
4120 $sql .= " SELECT DISTINCT gr.entity, gr.fk_usergroup, ".((int) $targetid);
4121 $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_rights as gr";
4122 $sql .= " WHERE gr.fk_id IN (".$db->sanitize($sourcelist).")";
4123 $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).")";
4124 if (!$db->query($sql)) {
4125 $error++;
4126 break;
4127 }
4128
4129 // Grant to users that hold a source permission but not yet the target
4130 $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_rights (entity, fk_user, fk_id)";
4131 $sql .= " SELECT DISTINCT ur.entity, ur.fk_user, ".((int) $targetid);
4132 $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur";
4133 $sql .= " WHERE ur.fk_id IN (".$db->sanitize($sourcelist).")";
4134 $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).")";
4135 if (!$db->query($sql)) {
4136 $error++;
4137 break;
4138 }
4139 }
4140
4141 if ($error) {
4142 $db->rollback();
4143 return -1;
4144 }
4145 $db->commit();
4146 return 0;
4147}
4148
4158function migrate_get_rights_def_id($db, $module, $perms, $subperms)
4159{
4160 $sql = "SELECT id FROM ".MAIN_DB_PREFIX."rights_def";
4161 $sql .= " WHERE module = '".$db->escape($module)."'";
4162 $sql .= " AND perms = '".$db->escape($perms)."'";
4163 if ($subperms === '') {
4164 $sql .= " AND (subperms IS NULL OR subperms = '')";
4165 } else {
4166 $sql .= " AND subperms = '".$db->escape($subperms)."'";
4167 }
4168 $resql = $db->query($sql);
4169 if (!$resql) {
4170 return 0;
4171 }
4172 $obj = $db->fetch_object($resql);
4173 return $obj ? (int) $obj->id : 0;
4174}
4175
4184function migrate_user_rights_entity($db, $langs, $conf)
4185{
4186 print '<tr><td colspan="4">';
4187
4188 print '<b>'.$langs->trans('MigrationUserRightsEntity')."</b><br>\n";
4189
4190 $error = 0;
4191
4192 dolibarr_install_syslog("upgrade2::migrate_user_rights_entity");
4193
4194 $db->begin();
4195
4196 $sqlSelect = "SELECT u.rowid, u.entity";
4197 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."user as u";
4198 $sqlSelect .= " WHERE u.entity > 1";
4199 //print $sqlSelect;
4200
4201 $resql = $db->query($sqlSelect);
4202 if ($resql) {
4203 $i = 0;
4204 $num = $db->num_rows($resql);
4205
4206 if ($num) {
4207 while ($i < $num) {
4208 $obj = $db->fetch_object($resql);
4209
4210 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."user_rights SET";
4211 $sqlUpdate .= " entity = ".((int) $obj->entity);
4212 $sqlUpdate .= " WHERE fk_user = ".((int) $obj->rowid);
4213
4214 $result = $db->query($sqlUpdate);
4215 if (!$result) {
4216 $error++;
4217 dol_print_error($db);
4218 }
4219
4220 print '. ';
4221 $i++;
4222 }
4223 } else {
4224 print $langs->trans('AlreadyDone')."<br>\n";
4225 }
4226
4227 if (!$error) {
4228 $db->commit();
4229 } else {
4230 $db->rollback();
4231 }
4232 } else {
4233 dol_print_error($db);
4234 $db->rollback();
4235 }
4236
4237
4238 print '</td></tr>';
4239}
4240
4249function migrate_usergroup_rights_entity($db, $langs, $conf)
4250{
4251 print '<tr><td colspan="4">';
4252
4253 print '<b>'.$langs->trans('MigrationUserGroupRightsEntity')."</b><br>\n";
4254
4255 $error = 0;
4256
4257 dolibarr_install_syslog("upgrade2::migrate_usergroup_rights_entity");
4258
4259 $db->begin();
4260
4261 $sqlSelect = "SELECT u.rowid, u.entity";
4262 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."usergroup as u";
4263 $sqlSelect .= " WHERE u.entity > 1";
4264 //print $sqlSelect;
4265
4266 $resql = $db->query($sqlSelect);
4267 if ($resql) {
4268 $i = 0;
4269 $num = $db->num_rows($resql);
4270
4271 if ($num) {
4272 while ($i < $num) {
4273 $obj = $db->fetch_object($resql);
4274
4275 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."usergroup_rights SET";
4276 $sqlUpdate .= " entity = ".((int) $obj->entity);
4277 $sqlUpdate .= " WHERE fk_usergroup = ".((int) $obj->rowid);
4278
4279 $result = $db->query($sqlUpdate);
4280 if (!$result) {
4281 $error++;
4282 dol_print_error($db);
4283 }
4284
4285 print '. ';
4286 $i++;
4287 }
4288 } else {
4289 print $langs->trans('AlreadyDone')."<br>\n";
4290 }
4291
4292 if (!$error) {
4293 $db->commit();
4294 } else {
4295 $db->rollback();
4296 }
4297 } else {
4298 dol_print_error($db);
4299 $db->rollback();
4300 }
4301
4302
4303 print '</td></tr>';
4304}
4305
4316function migrate_rename_directories($db, $langs, $conf, $oldname, $newname)
4317{
4318 dolibarr_install_syslog("upgrade2::migrate_rename_directories");
4319
4320 if (is_dir(DOL_DATA_ROOT.$oldname) && !file_exists(DOL_DATA_ROOT.$newname)) {
4321 dolibarr_install_syslog("upgrade2::migrate_rename_directories move ".DOL_DATA_ROOT.$oldname.' into '.DOL_DATA_ROOT.$newname);
4322 @rename(DOL_DATA_ROOT.$oldname, DOL_DATA_ROOT.$newname);
4323 }
4324}
4325
4326
4335function migrate_delete_old_files($db, $langs, $conf)
4336{
4337 $ret = true;
4338
4339 dolibarr_install_syslog("upgrade2::migrate_delete_old_files");
4340
4341 // List of files to delete
4342 $filetodeletearray = array(
4343 '/core/ajax/ajaxcompanies.php',
4344 '/core/triggers/interface_demo.class.php',
4345 '/core/menus/barre_left/default.php',
4346 '/core/menus/barre_top/default.php',
4347 '/core/modules/modComptabiliteExpert.class.php',
4348 '/core/modules/modCommercial.class.php',
4349 '/core/modules/modProduit.class.php',
4350 '/core/modules/modSkype.class.php',
4351 '/core/modules/modactivite.class.php', // A file from external module that should not be here
4352 '/core/triggers/interface_modWebcalendar_Webcalsynchro.class.php',
4353 '/core/triggers/interface_modCommande_Ecotax.class.php',
4354 '/core/triggers/interface_modCommande_fraisport.class.php',
4355 '/core/triggers/interface_modPropale_PropalWorkflow.class.php',
4356 '/core/triggers/interface_99_modWebhook_WebhookTriggers.class.php',
4357 '/core/triggers/interface_99_modZapier_ZapierTriggers.class.php',
4358 '/core/menus/smartphone/iphone.lib.php',
4359 '/core/menus/smartphone/iphone_backoffice.php',
4360 '/core/menus/smartphone/iphone_frontoffice.php',
4361 '/core/menus/standard/auguria_backoffice.php',
4362 '/core/menus/standard/auguria_frontoffice.php',
4363 '/core/menus/standard/eldy_backoffice.php',
4364 '/core/menus/standard/eldy_frontoffice.php',
4365 '/core/modules/export/export_excel.modules.php',
4366 '/core/modules/export/export_csv.modules.php',
4367 '/core/modules/export/exportcsv.modules.php',
4368 '/core/modules/export/export_excel2007new.modules.php',
4369 '/core/modules/facture/pdf_crabe.modules.php',
4370 '/core/modules/facture/pdf_oursin.modules.php',
4371 '/core/modules/mailings/contacts2.modules.php',
4372 '/core/modules/mailings/contacts3.modules.php',
4373 '/core/modules/mailings/contacts4.modules.php',
4374 '/core/modules/mailings/framboise.modules.php',
4375 '/core/modules/mailings/dolibarr_services_expired.modules.php',
4376 '/core/modules/mailings/peche.modules.php',
4377 '/core/modules/mailings/poire.modules.php',
4378 '/core/modules/mailings/kiwi.modules.php',
4379 '/core/modules/syslog/mod_syslog_chromephp.php',
4380 '/core/modules/syslog/mod_syslog_firephp.php',
4381 '/core/modules/syslog/logHandlerInterface.php',
4382 '/core/boxes/box_members.php',
4383
4384 '/includes/restler/framework/Luracast/Restler/Data/Object.php',
4385 '/includes/nusoap/lib/class.*',
4386 '/phenix/inc/triggers/interface_modPhenix_Phenixsynchro.class.php',
4387 '/webcalendar/inc/triggers/interface_modWebcalendar_webcalsynchro.class.php',
4388
4389 '/api/class/api_generic.class.php',
4390 '/asterisk/cidlookup.php',
4391 '/categories/class/api_category.class.php',
4392 '/categories/class/api_deprecated_category.class.php',
4393 '/compta/facture/class/api_invoice.class.php',
4394 '/commande/class/api_commande.class.php',
4395 '/partnership/class/api_partnership.class.php',
4396 '/product/class/api_product.class.php',
4397 '/recruitment/class/api_recruitment.class.php',
4398 '/societe/class/api_contact.class.php',
4399 '/societe/class/api_thirdparty.class.php',
4400 '/support/online.php',
4401 '/takepos/class/actions_takepos.class.php',
4402 '/user/class/api_user.class.php',
4403
4404 '/install/mysql/tables/llx_c_ticketsup_category.key.sql',
4405 '/install/mysql/tables/llx_c_ticketsup_category.sql',
4406 '/install/mysql/tables/llx_c_ticketsup_severity.key.sql',
4407 '/install/mysql/tables/llx_c_ticketsup_severity.sql',
4408 '/install/mysql/tables/llx_c_ticketsup_type.key.sql',
4409 '/install/mysql/tables/llx_c_ticketsup_type.sql'
4410 );
4411
4412 /*
4413 print '<tr><td colspan="4">';
4414 print '<b>'.$langs->trans('DeleteOldFiles')."</b><br>\n";
4415 print '</td></tr>';
4416 */
4417
4418 foreach ($filetodeletearray as $filetodelete) {
4419 //print '<b>'DOL_DOCUMENT_ROOT.$filetodelete."</b><br>\n";
4420 if (preg_match('/\*/', $filetodelete) || file_exists(DOL_DOCUMENT_ROOT.$filetodelete)) {
4421 //print "Process file ".$filetodelete."\n";
4422 $result = dol_delete_file(DOL_DOCUMENT_ROOT.$filetodelete, 0, (preg_match('/\*/', $filetodelete) ? 1 : 0), 0, null, true, 0);
4423 if (!$result) {
4424 $langs->load("errors");
4425 print '<div class="error">'.$langs->trans("Error").': '.$langs->trans("ErrorFailToDeleteFile", DOL_DOCUMENT_ROOT.$filetodelete);
4426 print ' '.$langs->trans("RemoveItManuallyAndPressF5ToContinue").'</div>';
4427 } else {
4428 //print $langs->trans("FileWasRemoved", $filetodelete).'<br>';
4429 }
4430 }
4431 }
4432
4433 return $ret;
4434}
4435
4444function migrate_delete_old_dir($db, $langs, $conf)
4445{
4446 $ret = true;
4447
4448 dolibarr_install_syslog("upgrade2::migrate_delete_old_dir");
4449
4450 // List of files to delete
4451 $filetodeletearray = array(
4452 DOL_DOCUMENT_ROOT.'/core/modules/facture/terre',
4453 DOL_DOCUMENT_ROOT.'/core/modules/facture/mercure',
4454 );
4455
4456 // On linux, we can also removed old directory with a different case than new directory.
4457 if (!empty($_SERVER["WINDIR"])) {
4458 $filetodeletearray[] = DOL_DOCUMENT_ROOT.'/includes/phpoffice/PhpSpreadsheet';
4459 }
4460
4461 foreach ($filetodeletearray as $filetodelete) {
4462 $result = 1;
4463 if (file_exists($filetodelete)) {
4464 $result = dol_delete_dir_recursive($filetodelete);
4465 }
4466 if (!$result) {
4467 $langs->load("errors");
4468 print '<div class="error">'.$langs->trans("Error").': '.$langs->trans("ErrorFailToDeleteDir", $filetodelete);
4469 print ' '.$langs->trans("RemoveItManuallyAndPressF5ToContinue").'</div>';
4470 }
4471 }
4472
4473 return $ret;
4474}
4475
4476
4489function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $force = 0)
4490{
4491 global $user;
4492
4493 if (count($listofmodule) == 0) {
4494 return 0;
4495 }
4496
4497 if (!is_object($user)) {
4498 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4499 $user = new User($db); // To avoid error during migration
4500 }
4501
4502 dolibarr_install_syslog("upgrade2::migrate_reload_modules force=".$force.", listofmodule=".implode(',', array_keys($listofmodule)), LOG_NOTICE);
4503
4504 $reloadactionformodules = array(
4505 'MAIN_MODULE_AGENDA' => array('class' => 'modAgenda', 'remove' => 1),
4506 'MAIN_MODULE_API' => array('class' => 'modApi'),
4507 'MAIN_MODULE_BARCODE' => array('class' => 'modBarcode', 'remove' => 1),
4508 'MAIN_MODULE_BLOCKEDLOG' => array('class' => 'modBlockedLog', 'deleteinsertmenus' => 1),
4509 'MAIN_MODULE_CRON' => array('class' => 'modCron', 'remove' => 1),
4510 'MAIN_MODULE_SOCIETE' => array('class' => 'modSociete', 'remove' => 1),
4511 'MAIN_MODULE_PRODUIT' => array('class' => 'modProduct'),
4512 'MAIN_MODULE_SERVICE' => array('class' => 'modService'),
4513 'MAIN_MODULE_COMMANDE' => array('class' => 'modCommande'),
4514 'MAIN_MODULE_DON' => array('class' => 'modDon'),
4515 'MAIN_MODULE_FACTURE' => array('class' => 'modFacture'),
4516 'MAIN_MODULE_FICHEINTER' => array('class' => 'modFicheinter'),
4517 'MAIN_MODULE_FOURNISSEUR' => array('class' => 'modFournisseur'),
4518 'MAIN_MODULE_EXPEDITION' => array('class' => 'modExpedition'),
4519 'MAIN_MODULE_EXPENSEREPORT' => array('class' => 'modExpenseReport'),
4520 'MAIN_MODULE_EVENTORGANIZATION' => array('class' => 'modEventOrganization', 'remove' => 1),
4521 'MAIN_MODULE_ECM' => array('class' => 'modECM', 'remove' => 1),
4522 'MAIN_MODULE_HOLIDAY' => array('class' => 'modHoliday', 'remove' => 1),
4523 'MAIN_MODULE_KNOWLEDGEMANAGEMENT' => array('class' => 'modKnowledgeManagement', 'remove' => 1),
4524 'MAIN_MODULE_LOAN' => array('class' => 'modLoan', 'remove' => 1),
4525 'MAIN_MODULE_PAYBOX' => array('class' => 'modPaybox', 'remove' => 1),
4526 'MAIN_MODULE_PROPAL' => array('class' => 'modPropale'),
4527 'MAIN_MODULE_SUPPLIERPROPOSAL' => array('class' => 'modSupplierProposal', 'remove' => 1),
4528 'MAIN_MODULE_OPENSURVEY' => array('class' => 'modOpenSurvey', 'remove' => 1),
4529 'MAIN_MODULE_PRODUCTBATCH' => array('class' => 'modProductBatch', 'remove' => 1),
4530 'MAIN_MODULE_TAKEPOS' => array('class' => 'modTakePos', 'remove' => 1),
4531 'MAIN_MODULE_VARIANTS' => array('class' => 'modVariants', 'remove' => 1),
4532 'MAIN_MODULE_EMAILCOLLECTOR' => array('class' => 'modEmailCollector', 'remove' => 1),
4533 );
4534
4535 foreach ($listofmodule as $moduletoreload => $reloadmode) { // reloadmodule can be 'noboxes', 'newboxdefonly', 'forceactivate'
4536 $modulekey = preg_replace('/^MAIN_MODULE_/', '', $moduletoreload);
4537
4538 if (empty($moduletoreload) || (!isModEnabled(strtolower($modulekey)) && !$force)) {
4539 continue; // Discard reload if module not enabled
4540 }
4541
4542 $mod = null;
4543
4544 if (!empty($reloadactionformodules[$moduletoreload])) {
4545 dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate module ".$moduletoreload." with mode ".$reloadmode);
4546
4547 $val = $reloadactionformodules[$moduletoreload];
4548 $classformodule = $val['class'];
4549 $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/'.$classformodule.'.class.php';
4550 if ($res) {
4551 $mod = new $classformodule($db);
4552 if (!empty($val['remove'])) {
4553 $mod->remove('noboxes');
4554 }
4555 if (!empty($val['deleteinsertmenus'])) {
4556 // We only reload menus
4557 $mod->delete_menus();
4558 $mod->insert_menus();
4559 } else {
4560 $mod->init($reloadmode);
4561 }
4562 }
4563 } else { // Other generic cases/modules
4564 $reg = array();
4565 preg_match('/([a-zA-Z0-9]+)/', $modulekey, $reg);
4566 if (!empty($reg[1])) {
4567 if (strtoupper($moduletoreload) == $moduletoreload) { // If key has at least one uppercase
4568 $moduletoreloadshort = ucfirst(strtolower($reg[1]));
4569 } else { // If key is a mix of up and low case
4570 $moduletoreloadshort = $reg[1];
4571 }
4572
4573 dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate module ".$moduletoreloadshort." with mode ".$reloadmode." (generic code)", LOG_NOTICE);
4574
4575 $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/mod'.$moduletoreloadshort.'.class.php';
4576 if ($res) {
4577 $classname = 'mod'.$moduletoreloadshort;
4578 $mod = new $classname($db);
4579 '@phan-var-force DolibarrModules $mod';
4580
4581 //$mod->remove('noboxes');
4582 $mod->delete_menus(); // We must delete to be sure it is inserted with new values
4583 $mod->init($reloadmode);
4584 } else {
4585 dolibarr_install_syslog('Failed to include '.DOL_DOCUMENT_ROOT.'/core/modules/mod'.$moduletoreloadshort.'.class.php', LOG_ERR);
4586
4587 $res = @dol_include_once(strtolower($moduletoreloadshort).'/core/modules/mod'.$moduletoreloadshort.'.class.php');
4588 if ($res) {
4589 $classname = 'mod'.$moduletoreloadshort;
4590 $mod = new $classname($db);
4591 '@phan-var-force DolibarrModules $mod';
4592 $mod->init($reloadmode);
4593 } else {
4594 dolibarr_install_syslog('Failed to include '.strtolower($moduletoreloadshort).'/core/modules/mod'.$moduletoreloadshort.'.class.php', LOG_ERR);
4595 print "Error, can't find module with name ".$moduletoreload."\n";
4596 return -1;
4597 }
4598 }
4599 } else {
4600 dolibarr_install_syslog("Error, can't find module with name ".$moduletoreload, LOG_ERR);
4601 print "Error, can't find module with name ".$moduletoreload."\n";
4602 return -1;
4603 }
4604 }
4605
4606 if (!empty($mod) && is_object($mod)) {
4607 print '<tr class="trforrunsql"><td colspan="4">';
4608 print '<b>'.$langs->trans('Upgrade').'</b>: ';
4609 print $langs->trans('MigrationReloadModule').' '.$mod->getName(); // We keep getName outside of trans because getName is already encoded/translated
4610 print "<!-- (".$reloadmode.") -->";
4611 print "<br>\n";
4612 print '</td></tr>';
4613 }
4614 }
4615
4616 return 1;
4617}
4618
4619
4620
4629function migrate_reload_menu($db, $langs, $conf)
4630{
4631 global $conf;
4632 dolibarr_install_syslog("upgrade2::migrate_reload_menu");
4633
4634 // Define list of menu handlers to initialize
4635 $listofmenuhandler = array();
4636 if (getDolGlobalString('MAIN_MENU_STANDARD') == 'auguria_menu' || getDolGlobalString('MAIN_MENU_SMARTPHONE') == 'auguria_menu'
4637 || getDolGlobalString('MAIN_MENUFRONT_STANDARD') == 'auguria_menu' || getDolGlobalString('MAIN_MENUFRONT_SMARTPHONE') == 'auguria_menu') {
4638 $listofmenuhandler['auguria'] = 1; // We set here only dynamic menu handlers
4639 }
4640
4641 foreach ($listofmenuhandler as $key => $val) {
4642 print '<tr class="trforrunsql"><td colspan="4">';
4643
4644 //print "x".$key;
4645 print '<br>';
4646 print '<b>'.$langs->trans('Upgrade').'</b>: '.$langs->trans('MenuHandler')." ".$key."<br>\n";
4647
4648 // Load sql ini_menu_handler.sql file
4649 $dir = DOL_DOCUMENT_ROOT."/core/menus/";
4650 $file = 'init_menu_'.$key.'.sql';
4651 if (file_exists($dir.$file)) {
4652 $result = run_sql($dir.$file, 1, 0, 1, $key);
4653 }
4654
4655 print '</td></tr>';
4656 }
4657
4658 return 1;
4659}
4660
4667{
4668 global $conf, $db, $langs, $user;
4669
4670 if (!is_object($user)) {
4671 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4672 $user = new User($db); // To avoid error during migration
4673 }
4674
4675 print '<tr><td colspan="4">';
4676
4677 print '<b>'.$langs->trans('MigrationProductLotPath')."</b><br>\n";
4678
4679 $sql = "SELECT rowid, entity, batch, fk_product from ".MAIN_DB_PREFIX."product_lot";
4680 $resql = $db->query($sql);
4681
4682 if ($resql) {
4683 $modulepart="product_batch";
4684
4685 $lot = new Productlot($db);
4686
4687 while ($obj = $db->fetch_object($resql)) {
4688 $entity = (empty($obj->entity) ? 1 : $obj->entity);
4689 if ($entity > 1) {
4690 $dir = DOL_DATA_ROOT.'/'.$entity.'/'.$conf->productbatch->multidir_output[$entity];
4691 } else {
4692 $dir = $conf->productbatch->multidir_output[$entity];
4693 }
4694
4695 if ($dir) {
4696 $lot->id = (int) $obj->rowid;
4697 $lot->ref = (string) $obj->rowid; // No ref for the moment
4698 $lot->batch = $obj->batch;
4699 $lot->entity = $obj->entity;
4700 $lot->fk_product = $obj->fk_product;
4701
4702 $savref = $lot->ref;
4703
4704 $lot->ref = $obj->batch;
4705 $origin = $dir . '/' . get_exdir(0, 0, 0, 1, $lot, $modulepart);
4706
4707 $lot->ref = $savref; // So restore the id
4708 $destin = $dir . '/' . get_exdir(0, 0, 0, 1, $lot, $modulepart);
4709
4710 //var_dump($origin.' -> '.$destin.' '.$lot->batch.' dir origin is '.dol_is_dir($origin));exit;
4711
4712 if (dol_is_dir($origin) && !dol_is_dir($destin)) {
4713 dol_move_dir($origin, $destin, 0);
4714 }
4715 }
4716 }
4717 }
4718 print '</td></tr>';
4719
4720 return 1;
4721}
4722
4729{
4730 global $conf, $db, $langs, $user;
4731
4732 print '<tr><td colspan="4">';
4733
4734 print '<b>'.$langs->trans('MigrationUserPhotoPath')."</b><br>\n";
4735
4736 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4737 $fuser = new User($db);
4738 if (!is_object($user)) {
4739 $user = $fuser; // To avoid error during migration
4740 }
4741
4742 $sql = "SELECT rowid as uid, entity from ".MAIN_DB_PREFIX."user"; // Get list of all users
4743 $resql = $db->query($sql);
4744 if ($resql) {
4745 while ($obj = $db->fetch_object($resql)) {
4746 //$fuser->fetch($obj->uid);
4747 $fuser->id = $obj->uid;
4748 $fuser->entity = $obj->entity;
4749
4750 //echo '<hr>'.$fuser->id.' -> '.$fuser->entity;
4751 $entity = (empty($fuser->entity) ? 1 : $fuser->entity);
4752 if ($entity > 1) {
4753 $dir = DOL_DATA_ROOT.'/'.$entity.'/users';
4754 } else {
4755 $dir = $conf->user->multidir_output[$entity]; // $conf->user->multidir_output[] for each entity is construct by the multicompany module
4756 }
4757
4758 if ($dir) {
4759 //print "Process user id ".$fuser->id."<br>\n";
4760 $origin = $dir.'/'.get_exdir($fuser->id, 2, 0, 1, $fuser, 'user'); // Use old behaviour to get x/y path
4761 $destin = $dir.'/'.$fuser->id;
4762
4763 $origin_osencoded = dol_osencode($origin);
4764
4765 dol_mkdir($destin);
4766
4767 //echo '<hr>'.$origin.' -> '.$destin;
4768 if (dol_is_dir($origin)) {
4769 $handle = opendir($origin_osencoded);
4770 if (is_resource($handle)) {
4771 while (($file = readdir($handle)) !== false) {
4772 if ($file == '.' || $file == '..') {
4773 continue;
4774 }
4775
4776 if (dol_is_dir($origin.'/'.$file)) { // it is a dir (like 'thumbs')
4777 $thumbs = opendir($origin_osencoded.'/'.$file);
4778 if (is_resource($thumbs)) {
4779 dol_mkdir($destin.'/'.$file);
4780 while (($thumb = readdir($thumbs)) !== false) {
4781 if (!dol_is_file($destin.'/'.$file.'/'.$thumb)) {
4782 if ($thumb == '.' || $thumb == '..') {
4783 continue;
4784 }
4785
4786 //print $origin.'/'.$file.'/'.$thumb.' -> '.$destin.'/'.$file.'/'.$thumb.'<br>'."\n";
4787 print '.';
4788 dol_copy($origin.'/'.$file.'/'.$thumb, $destin.'/'.$file.'/'.$thumb, '0', 0);
4789 //var_dump('aaa');exit;
4790 }
4791 }
4792 // dol_delete_dir($origin.'/'.$file);
4793 }
4794 } else { // it is a file
4795 if (!dol_is_file($destin.'/'.$file)) {
4796 //print $origin.'/'.$file.' -> '.$destin.'/'.$file.'<br>'."\n";
4797 print '.';
4798 dol_copy($origin.'/'.$file, $destin.'/'.$file, '0', 0);
4799 //var_dump('eee');exit;
4800 }
4801 }
4802 }
4803 }
4804 }
4805 }
4806 }
4807 }
4808
4809 print '</td></tr>';
4810}
4811
4818{
4819 global $db, $langs, $user;
4820
4821 print '<tr><td colspan="4">';
4822
4823 print '<b>'.$langs->trans('MigrationUserPhotoPath')."</b><br>\n";
4824
4825 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4826 $fuser = new User($db);
4827 if (!is_object($user)) {
4828 $user = $fuser; // To avoid error during migration
4829 }
4830
4831 $sql = "SELECT rowid as uid, entity, photo from ".MAIN_DB_PREFIX."user"; // Get list of all users
4832 $resql = $db->query($sql);
4833 if ($resql) {
4834 while ($obj = $db->fetch_object($resql)) {
4835 //$fuser->fetch($obj->uid);
4836 $fuser->id = $obj->uid;
4837 $fuser->entity = $obj->entity;
4838 $fuser->photo = $obj->photo;
4839
4840 //echo '<hr>'.$fuser->id.' -> '.$fuser->entity;
4841 $entity = (empty($fuser->entity) ? 1 : $fuser->entity);
4842 if ($entity > 1) {
4843 $dir = DOL_DATA_ROOT.'/'.$entity.'/users';
4844 } else {
4845 $dir = DOL_DATA_ROOT.'/users';
4846 }
4847
4848 if ($dir) {
4849 //print "Process user id ".$fuser->id."<br>\n";
4850 $origin = $dir.'/'.$fuser->id;
4851 $destin = $dir.'/'.$fuser->id.'/photos';
4852
4853 $origin_osencoded = dol_osencode($origin);
4854
4855 dol_mkdir($destin);
4856
4857 //echo '<hr>'.$origin.' -> '.$destin;
4858 if (dol_is_dir($origin)) {
4859 $handle = opendir($origin_osencoded);
4860 if (is_resource($handle)) {
4861 while (($file = readdir($handle)) !== false) {
4862 if ($file == '.' || $file == '..' || $file == 'photos') {
4863 continue;
4864 }
4865 if (!empty($fuser->photo) && ($file != $fuser->photo && $file != 'thumbs')) {
4866 continue;
4867 }
4868
4869 if (dol_is_dir($origin.'/'.$file)) { // it is a dir (like 'thumbs')
4870 $thumbs = opendir($origin_osencoded.'/'.$file);
4871 if (is_resource($thumbs)) {
4872 dol_mkdir($destin.'/'.$file);
4873 while (($thumb = readdir($thumbs)) !== false) {
4874 if (!dol_is_file($destin.'/'.$file.'/'.$thumb)) {
4875 if ($thumb == '.' || $thumb == '..') {
4876 continue;
4877 }
4878
4879 //print $origin.'/'.$file.'/'.$thumb.' -> '.$destin.'/'.$file.'/'.$thumb.'<br>'."\n";
4880 print '.';
4881 dol_copy($origin.'/'.$file.'/'.$thumb, $destin.'/'.$file.'/'.$thumb, '0', 0);
4882 }
4883 }
4884 // dol_delete_dir($origin.'/'.$file);
4885 }
4886 } else { // it is a file
4887 if (!dol_is_file($destin.'/'.$file)) {
4888 //print $origin.'/'.$file.' -> '.$destin.'/'.$file.'<br>'."\n";
4889 print '.';
4890 dol_copy($origin.'/'.$file, $destin.'/'.$file, '0', 0);
4891 }
4892 }
4893 }
4894 }
4895 }
4896 }
4897 }
4898 }
4899
4900 print '</td></tr>';
4901}
4902
4903
4904
4911{
4912 global $conf, $db, $langs;
4913
4914 print '<tr class="trforrunsql"><td>';
4915
4916 print '<b>'.$langs->trans('MigrationHolidayPath')."</b><br>\n";
4917
4918 include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
4919 $holiday = new Holiday($db);
4920
4921 $sql = "SELECT rowid as uid, ref, entity from ".MAIN_DB_PREFIX."holiday"; // Get list of all holiday
4922
4923 $resql = $db->query($sql);
4924 if ($resql) {
4925 while ($obj = $db->fetch_object($resql)) {
4926 //$holiday->fetch($obj->uid);
4927 $holiday->id = $obj->uid;
4928 $holiday->ref = $obj->ref;
4929 $holiday->entity = $obj->entity;
4930
4931 //echo '<hr>'.$holiday->id.' -> '.$holiday->entity;
4932 $entity = (empty($holiday->entity) ? 1 : $holiday->entity);
4933 if ($entity > 1) {
4934 $dir = DOL_DATA_ROOT.'/'.$entity.'/holiday';
4935 } else {
4936 $dir = $conf->holiday->multidir_output[$entity]; // $conf->user->multidir_output[] for each entity is construct by the multicompany module
4937 }
4938
4939 if ($dir) {
4940 //print "Process holiday id ".$holiday->id."<br>\n";
4941 $origin = $dir.'/'.get_exdir($holiday->id, 2, 0, 1, $holiday, 'holiday'); // Use old behaviour to get x/y path
4942 $destin = $dir.'/'.$holiday->ref;
4943
4944 $origin_osencoded = dol_osencode($origin);
4945
4946 dol_mkdir($destin);
4947
4948 //echo $origin.' -> '.$destin."<br>\n";
4949 if (dol_is_dir($origin)) {
4950 $handle = opendir($origin_osencoded);
4951 if (is_resource($handle)) {
4952 while (($file = readdir($handle)) !== false) {
4953 if ($file == '.' || $file == '..') {
4954 continue;
4955 }
4956
4957 if (dol_is_dir($origin.'/'.$file)) { // it is a dir (like 'thumbs')
4958 $thumbs = opendir($origin_osencoded.'/'.$file);
4959 if (is_resource($thumbs)) {
4960 dol_mkdir($destin.'/'.$file);
4961 while (($thumb = readdir($thumbs)) !== false) {
4962 if (!dol_is_file($destin.'/'.$file.'/'.$thumb)) {
4963 if ($thumb == '.' || $thumb == '..') {
4964 continue;
4965 }
4966
4967 //print $origin.'/'.$file.'/'.$thumb.' -> '.$destin.'/'.$file.'/'.$thumb.'<br>'."\n";
4968 print '.';
4969 dol_copy($origin.'/'.$file.'/'.$thumb, $destin.'/'.$file.'/'.$thumb, '0', 0);
4970 //var_dump('aaa');exit;
4971 }
4972 }
4973 // dol_delete_dir($origin.'/'.$file);
4974 }
4975 } else { // it is a file
4976 if (!dol_is_file($destin.'/'.$file)) {
4977 //print $origin.'/'.$file.' -> '.$destin.'/'.$file.'<br>'."\n";
4978 print '.';
4979 dol_copy($origin.'/'.$file, $destin.'/'.$file, '0', 0);
4980 //var_dump('eee');exit;
4981 }
4982 }
4983 }
4984 }
4985 }
4986 }
4987 }
4988 }
4989
4990 print '</td></tr>';
4991}
4992
4993
4994/* A faire egalement: Modif statut paye et fk_facture des factures payes completement
4995
4996On recherche facture incorrecte:
4997select 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
4998having f.total_ttc = sum(pf.amount)
4999
5000On les corrige:
5001update llx_facture set paye=1, fk_statut=2 where close_code is null
5002and rowid in (...)
5003*/
5004
5012{
5013 global $db, $langs;
5014 // skype,twitter,facebook,linkedin,instagram,snapchat,googleplus,youtube,whatsapp
5015 $error = 0;
5016 $db->begin();
5017 print '<tr><td colspan="4">';
5018 $sql = 'SELECT rowid, socialnetworks';
5019 $sql .= ', skype, twitter, facebook, linkedin, instagram, snapchat, googleplus, youtube, whatsapp FROM '.MAIN_DB_PREFIX.'user WHERE';
5020 $sql .= " skype IS NOT NULL OR skype <> ''";
5021 $sql .= " OR twitter IS NOT NULL OR twitter <> ''";
5022 $sql .= " OR facebook IS NOT NULL OR facebook <> ''";
5023 $sql .= " OR linkedin IS NOT NULL OR linkedin <> ''";
5024 $sql .= " OR instagram IS NOT NULL OR instagram <> ''";
5025 $sql .= " OR snapchat IS NOT NULL OR snapchat <> ''";
5026 $sql .= " OR googleplus IS NOT NULL OR googleplus <> ''";
5027 $sql .= " OR youtube IS NOT NULL OR youtube <> ''";
5028 $sql .= " OR whatsapp IS NOT NULL OR whatsapp <> ''";
5029 //print $sql;
5030 $resql = $db->query($sql);
5031 if ($resql) {
5032 while ($obj = $db->fetch_object($resql)) {
5033 $arraysocialnetworks = array();
5034 if (!empty($obj->skype)) {
5035 $arraysocialnetworks['skype'] = $obj->skype;
5036 }
5037 if (!empty($obj->twitter)) {
5038 $arraysocialnetworks['twitter'] = $obj->twitter;
5039 }
5040 if (!empty($obj->facebook)) {
5041 $arraysocialnetworks['facebook'] = $obj->facebook;
5042 }
5043 if (!empty($obj->linkedin)) {
5044 $arraysocialnetworks['linkedin'] = $obj->linkedin;
5045 }
5046 if (!empty($obj->instagram)) {
5047 $arraysocialnetworks['instagram'] = $obj->instagram;
5048 }
5049 if (!empty($obj->snapchat)) {
5050 $arraysocialnetworks['snapchat'] = $obj->snapchat;
5051 }
5052 if (!empty($obj->googleplus)) {
5053 $arraysocialnetworks['googleplus'] = $obj->googleplus;
5054 }
5055 if (!empty($obj->youtube)) {
5056 $arraysocialnetworks['youtube'] = $obj->youtube;
5057 }
5058 if (!empty($obj->whatsapp)) {
5059 $arraysocialnetworks['whatsapp'] = $obj->whatsapp;
5060 }
5061 if ($obj->socialnetworks == '' || is_null($obj->socialnetworks)) {
5062 $obj->socialnetworks = '[]';
5063 }
5064 $socialnetworks = array_merge($arraysocialnetworks, json_decode($obj->socialnetworks, true));
5065 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX."user SET socialnetworks='".$db->escape(json_encode($socialnetworks))."'";
5066 $sqlupd .= ', skype=null';
5067 $sqlupd .= ', twitter=null';
5068 $sqlupd .= ', facebook=null';
5069 $sqlupd .= ', linkedin=null';
5070 $sqlupd .= ', instagram=null';
5071 $sqlupd .= ', snapchat=null';
5072 $sqlupd .= ', googleplus=null';
5073 $sqlupd .= ', youtube=null';
5074 $sqlupd .= ', whatsapp=null';
5075 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
5076 //print $sqlupd."<br>";
5077 $resqlupd = $db->query($sqlupd);
5078 if (!$resqlupd) {
5079 dol_print_error($db);
5080 $error++;
5081 }
5082 }
5083 } else {
5084 $error++;
5085 }
5086 if (!$error) {
5087 $db->commit();
5088 } else {
5089 dol_print_error($db);
5090 $db->rollback();
5091 }
5092 print '<b>'.$langs->trans('MigrationFieldsSocialNetworks', 'Users')."</b><br>\n";
5093 print '</td></tr>';
5094}
5095
5103{
5104 global $db, $langs;
5105
5106 print '<tr><td colspan="4">';
5107 $error = 0;
5108 $db->begin();
5109 print '<tr><td colspan="4">';
5110 $sql = 'SELECT rowid, socialnetworks';
5111 $sql .= ', skype, twitter, facebook, linkedin, instagram, snapchat, googleplus, youtube, whatsapp FROM '.MAIN_DB_PREFIX.'adherent WHERE ';
5112 $sql .= " skype IS NOT NULL OR skype <> ''";
5113 $sql .= " OR twitter IS NOT NULL OR twitter <> ''";
5114 $sql .= " OR facebook IS NOT NULL OR facebook <> ''";
5115 $sql .= " OR linkedin IS NOT NULL OR linkedin <> ''";
5116 $sql .= " OR instagram IS NOT NULL OR instagram <> ''";
5117 $sql .= " OR snapchat IS NOT NULL OR snapchat <> ''";
5118 $sql .= " OR googleplus IS NOT NULL OR googleplus <> ''";
5119 $sql .= " OR youtube IS NOT NULL OR youtube <> ''";
5120 $sql .= " OR whatsapp IS NOT NULL OR whatsapp <> ''";
5121 //print $sql;
5122 $resql = $db->query($sql);
5123 if ($resql) {
5124 while ($obj = $db->fetch_object($resql)) {
5125 $arraysocialnetworks = array();
5126 if (!empty($obj->skype)) {
5127 $arraysocialnetworks['skype'] = $obj->skype;
5128 }
5129 if (!empty($obj->twitter)) {
5130 $arraysocialnetworks['twitter'] = $obj->twitter;
5131 }
5132 if (!empty($obj->facebook)) {
5133 $arraysocialnetworks['facebook'] = $obj->facebook;
5134 }
5135 if (!empty($obj->linkedin)) {
5136 $arraysocialnetworks['linkedin'] = $obj->linkedin;
5137 }
5138 if (!empty($obj->instagram)) {
5139 $arraysocialnetworks['instagram'] = $obj->instagram;
5140 }
5141 if (!empty($obj->snapchat)) {
5142 $arraysocialnetworks['snapchat'] = $obj->snapchat;
5143 }
5144 if (!empty($obj->googleplus)) {
5145 $arraysocialnetworks['googleplus'] = $obj->googleplus;
5146 }
5147 if (!empty($obj->youtube)) {
5148 $arraysocialnetworks['youtube'] = $obj->youtube;
5149 }
5150 if (!empty($obj->whatsapp)) {
5151 $arraysocialnetworks['whatsapp'] = $obj->whatsapp;
5152 }
5153 if ($obj->socialnetworks == '' || is_null($obj->socialnetworks)) {
5154 $obj->socialnetworks = '[]';
5155 }
5156 $socialnetworks = array_merge($arraysocialnetworks, json_decode($obj->socialnetworks, true));
5157 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX."adherent SET socialnetworks='".$db->escape(json_encode($socialnetworks))."'";
5158 $sqlupd .= ', skype=null';
5159 $sqlupd .= ', twitter=null';
5160 $sqlupd .= ', facebook=null';
5161 $sqlupd .= ', linkedin=null';
5162 $sqlupd .= ', instagram=null';
5163 $sqlupd .= ', snapchat=null';
5164 $sqlupd .= ', googleplus=null';
5165 $sqlupd .= ', youtube=null';
5166 $sqlupd .= ', whatsapp=null';
5167 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
5168 //print $sqlupd."<br>";
5169 $resqlupd = $db->query($sqlupd);
5170 if (!$resqlupd) {
5171 dol_print_error($db);
5172 $error++;
5173 }
5174 }
5175 } else {
5176 $error++;
5177 }
5178 if (!$error) {
5179 $db->commit();
5180 } else {
5181 dol_print_error($db);
5182 $db->rollback();
5183 }
5184 print '<b>'.$langs->trans('MigrationFieldsSocialNetworks', 'Members')."</b><br>\n";
5185 print '</td></tr>';
5186}
5187
5195{
5196 global $db, $langs;
5197 // jabberid,skype,twitter,facebook,linkedin,instagram,snapchat,googleplus,youtube,whatsapp
5198 $error = 0;
5199 $db->begin();
5200 print '<tr><td colspan="4">';
5201 $sql = 'SELECT rowid, socialnetworks';
5202 $sql .= ', jabberid, skype, twitter, facebook, linkedin, instagram, snapchat, googleplus, youtube, whatsapp FROM '.MAIN_DB_PREFIX.'socpeople WHERE';
5203 $sql .= " jabberid IS NOT NULL OR jabberid <> ''";
5204 $sql .= " OR skype IS NOT NULL OR skype <> ''";
5205 $sql .= " OR twitter IS NOT NULL OR twitter <> ''";
5206 $sql .= " OR facebook IS NOT NULL OR facebook <> ''";
5207 $sql .= " OR linkedin IS NOT NULL OR linkedin <> ''";
5208 $sql .= " OR instagram IS NOT NULL OR instagram <> ''";
5209 $sql .= " OR snapchat IS NOT NULL OR snapchat <> ''";
5210 $sql .= " OR googleplus IS NOT NULL OR googleplus <> ''";
5211 $sql .= " OR youtube IS NOT NULL OR youtube <> ''";
5212 $sql .= " OR whatsapp IS NOT NULL OR whatsapp <> ''";
5213 //print $sql;
5214 $resql = $db->query($sql);
5215 if ($resql) {
5216 while ($obj = $db->fetch_object($resql)) {
5217 $arraysocialnetworks = array();
5218 if (!empty($obj->jabberid)) {
5219 $arraysocialnetworks['jabber'] = $obj->jabberid;
5220 }
5221 if (!empty($obj->skype)) {
5222 $arraysocialnetworks['skype'] = $obj->skype;
5223 }
5224 if (!empty($obj->twitter)) {
5225 $arraysocialnetworks['twitter'] = $obj->twitter;
5226 }
5227 if (!empty($obj->facebook)) {
5228 $arraysocialnetworks['facebook'] = $obj->facebook;
5229 }
5230 if (!empty($obj->linkedin)) {
5231 $arraysocialnetworks['linkedin'] = $obj->linkedin;
5232 }
5233 if (!empty($obj->instagram)) {
5234 $arraysocialnetworks['instagram'] = $obj->instagram;
5235 }
5236 if (!empty($obj->snapchat)) {
5237 $arraysocialnetworks['snapchat'] = $obj->snapchat;
5238 }
5239 if (!empty($obj->googleplus)) {
5240 $arraysocialnetworks['googleplus'] = $obj->googleplus;
5241 }
5242 if (!empty($obj->youtube)) {
5243 $arraysocialnetworks['youtube'] = $obj->youtube;
5244 }
5245 if (!empty($obj->whatsapp)) {
5246 $arraysocialnetworks['whatsapp'] = $obj->whatsapp;
5247 }
5248 if ($obj->socialnetworks == '' || is_null($obj->socialnetworks)) {
5249 $obj->socialnetworks = '[]';
5250 }
5251 $socialnetworks = array_merge($arraysocialnetworks, json_decode($obj->socialnetworks, true));
5252 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX."socpeople SET socialnetworks='".$db->escape(json_encode($socialnetworks))."'";
5253 $sqlupd .= ', jabberid=null';
5254 $sqlupd .= ', skype=null';
5255 $sqlupd .= ', twitter=null';
5256 $sqlupd .= ', facebook=null';
5257 $sqlupd .= ', linkedin=null';
5258 $sqlupd .= ', instagram=null';
5259 $sqlupd .= ', snapchat=null';
5260 $sqlupd .= ', googleplus=null';
5261 $sqlupd .= ', youtube=null';
5262 $sqlupd .= ', whatsapp=null';
5263 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
5264 //print $sqlupd."<br>";
5265 $resqlupd = $db->query($sqlupd);
5266 if (!$resqlupd) {
5267 dol_print_error($db);
5268 $error++;
5269 }
5270 }
5271 } else {
5272 $error++;
5273 }
5274 if (!$error) {
5275 $db->commit();
5276 } else {
5277 dol_print_error($db);
5278 $db->rollback();
5279 }
5280 print '<b>'.$langs->trans('MigrationFieldsSocialNetworks', 'Contacts')."</b><br>\n";
5281 print '</td></tr>';
5282}
5283
5291{
5292 global $db, $langs;
5293 // skype,twitter,facebook,linkedin,instagram,snapchat,googleplus,youtube,whatsapp
5294 $error = 0;
5295 $db->begin();
5296 print '<tr><td colspan="4">';
5297 $sql = 'SELECT rowid, socialnetworks';
5298 $sql .= ', skype, twitter, facebook, linkedin, instagram, snapchat, googleplus, youtube, whatsapp FROM '.MAIN_DB_PREFIX.'societe WHERE ';
5299 $sql .= " skype IS NOT NULL OR skype <> ''";
5300 $sql .= " OR twitter IS NOT NULL OR twitter <> ''";
5301 $sql .= " OR facebook IS NOT NULL OR facebook <> ''";
5302 $sql .= " OR linkedin IS NOT NULL OR linkedin <> ''";
5303 $sql .= " OR instagram IS NOT NULL OR instagram <> ''";
5304 $sql .= " OR snapchat IS NOT NULL OR snapchat <> ''";
5305 $sql .= " OR googleplus IS NOT NULL OR googleplus <> ''";
5306 $sql .= " OR youtube IS NOT NULL OR youtube <> ''";
5307 $sql .= " OR whatsapp IS NOT NULL OR whatsapp <> ''";
5308 //print $sql;
5309 $resql = $db->query($sql);
5310 if ($resql) {
5311 while ($obj = $db->fetch_object($resql)) {
5312 $arraysocialnetworks = array();
5313 if (!empty($obj->skype)) {
5314 $arraysocialnetworks['skype'] = $obj->skype;
5315 }
5316 if (!empty($obj->twitter)) {
5317 $arraysocialnetworks['twitter'] = $obj->twitter;
5318 }
5319 if (!empty($obj->facebook)) {
5320 $arraysocialnetworks['facebook'] = $obj->facebook;
5321 }
5322 if (!empty($obj->linkedin)) {
5323 $arraysocialnetworks['linkedin'] = $obj->linkedin;
5324 }
5325 if (!empty($obj->instagram)) {
5326 $arraysocialnetworks['instagram'] = $obj->instagram;
5327 }
5328 if (!empty($obj->snapchat)) {
5329 $arraysocialnetworks['snapchat'] = $obj->snapchat;
5330 }
5331 if (!empty($obj->googleplus)) {
5332 $arraysocialnetworks['googleplus'] = $obj->googleplus;
5333 }
5334 if (!empty($obj->youtube)) {
5335 $arraysocialnetworks['youtube'] = $obj->youtube;
5336 }
5337 if (!empty($obj->whatsapp)) {
5338 $arraysocialnetworks['whatsapp'] = $obj->whatsapp;
5339 }
5340 if ($obj->socialnetworks == '' || is_null($obj->socialnetworks)) {
5341 $obj->socialnetworks = '[]';
5342 }
5343 $socialnetworks = array_merge($arraysocialnetworks, json_decode($obj->socialnetworks, true));
5344 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX."societe SET socialnetworks='".$db->escape(json_encode($socialnetworks))."'";
5345 $sqlupd .= ', skype=null';
5346 $sqlupd .= ', twitter=null';
5347 $sqlupd .= ', facebook=null';
5348 $sqlupd .= ', linkedin=null';
5349 $sqlupd .= ', instagram=null';
5350 $sqlupd .= ', snapchat=null';
5351 $sqlupd .= ', googleplus=null';
5352 $sqlupd .= ', youtube=null';
5353 $sqlupd .= ', whatsapp=null';
5354 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
5355 //print $sqlupd."<br>";
5356 $resqlupd = $db->query($sqlupd);
5357 if (!$resqlupd) {
5358 dol_print_error($db);
5359 $error++;
5360 }
5361 }
5362 } else {
5363 $error++;
5364 }
5365 if (!$error) {
5366 $db->commit();
5367 } else {
5368 dol_print_error($db);
5369 $db->rollback();
5370 }
5371 print '<b>'.$langs->trans('MigrationFieldsSocialNetworks', 'Thirdparties')."</b><br>\n";
5372 print '</td></tr>';
5373}
5374
5375
5382function migrate_export_import_profiles($mode = 'export')
5383{
5384 global $db, $langs;
5385
5386 $error = 0;
5387 $resultstring = '';
5388
5389 $db->begin();
5390
5391 print '<tr class="trforrunsql"><td colspan="4">';
5392 $sql = 'SELECT rowid, field';
5393 if ($mode == 'export') {
5394 $sql .= ', filter';
5395 }
5396 $sql .= ' FROM '.MAIN_DB_PREFIX.$mode.'_model WHERE';
5397 $sql .= " type LIKE 'propale_%' OR type LIKE 'commande_%' OR type LIKE 'facture_%'";
5398 //print $sql;
5399 $resql = $db->query($sql);
5400 if ($resql) {
5401 while ($obj = $db->fetch_object($resql)) {
5402 $oldfield = $obj->field;
5403 $newfield = str_replace(array(',f.facnumber', 'f.facnumber,', 'f.total,', 'f.tva,'), array(',f.ref', 'f.ref,', 'f.total_ht,', 'f.total_tva,'), $oldfield);
5404
5405 if ($mode == 'export') {
5406 $oldfilter = $obj->filter;
5407 $newfilter = str_replace(array('f.facnumber=', 'f.total=', 'f.tva='), array('f.ref=', 'f.total_ht=', 'f.total_tva='), $oldfilter);
5408 } else {
5409 $oldfilter = '';
5410 $newfilter = '';
5411 }
5412
5413 if ($oldfield != $newfield || $oldfilter != $newfilter) {
5414 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX.$mode."_model SET field = '".$db->escape($newfield)."'";
5415 if ($mode == 'export') {
5416 $sqlupd .= ", filter = '".$db->escape($newfilter)."'";
5417 }
5418 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
5419 $resultstring .= '<tr class="trforrunsql" style=""><td class="wordbreak" colspan="4">'.$sqlupd."</td></tr>\n";
5420 $resqlupd = $db->query($sqlupd);
5421 if (!$resqlupd) {
5422 dol_print_error($db);
5423 $error++;
5424 }
5425 }
5426 }
5427 } else {
5428 $error++;
5429 }
5430 if (!$error) {
5431 $db->commit();
5432 } else {
5433 dol_print_error($db);
5434 $db->rollback();
5435 }
5436 print '<b>'.$langs->trans('MigrationImportOrExportProfiles', $mode)."</b><br>\n";
5437 print '</td></tr>';
5438
5439 if ($resultstring) {
5440 print $resultstring;
5441 } else {
5442 print '<tr class="trforrunsql" style=""><td class="wordbreak" colspan="4">'.$langs->trans("NothingToDo")."</td></tr>\n";
5443 }
5444}
5445
5452{
5453 global $db, $langs;
5454
5455 $error = 0;
5456 $resultstring = '';
5457
5458 $db->begin();
5459 print '<tr class="trforrunsql"><td colspan="4">';
5460 print '<b>'.$langs->trans('MigrationContractLineRank')."</b><br>\n";
5461
5462 $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";
5463 $sql .= " ORDER BY c.rowid,cd.rowid";
5464
5465 $resql = $db->query($sql);
5466 if ($resql) {
5467 $currentRank = 0;
5468 $current_contract = 0;
5469 while ($obj = $db->fetch_object($resql)) {
5470 if (empty($current_contract) || $current_contract == $obj->cid) {
5471 $currentRank++;
5472 } else {
5473 $currentRank = 1;
5474 }
5475
5476 $sqlUpd = "UPDATE ".$db->prefix()."contratdet SET rang=".(int) $currentRank." WHERE rowid=".(int) $obj->cdid;
5477 $resultstring = '.';
5478 print $resultstring;
5479 $resqlUpd = $db->query($sqlUpd);
5480 if (!$resqlUpd) {
5481 dol_print_error($db);
5482 $error++;
5483 }
5484
5485 $current_contract = $obj->cid;
5486 }
5487 } else {
5488 $error++;
5489 }
5490 if (!$error) {
5491 $db->commit();
5492 } else {
5493 $db->rollback();
5494 }
5495
5496 print '</td></tr>';
5497
5498 if (!$resultstring) {
5499 print '<tr class="trforrunsql" style=""><td class="wordbreak" colspan="4">'.$langs->trans("NothingToDo")."</td></tr>\n";
5500 }
5501}
5502
5509{
5510 global $db, $langs;
5511
5512 $lock = getDolGlobalInt('MIGRATION_FLAG_INVOICE_MODELS_V20');
5513
5514 $firstInstallVersion = getDolGlobalString('MAIN_VERSION_FIRST_INSTALL', DOL_VERSION);
5515 $migrationNeeded = (versioncompare(explode('.', $firstInstallVersion, 3), array(20, 0, -5)) < 0 && !$lock);
5516
5517 print '<tr class="trforrunsql"><td colspan="4">';
5518 print '<b>'.$langs->trans('InvoiceExportModelsMigration')."</b>: \n";
5519
5520 if (! $migrationNeeded) {
5521 print $langs->trans("AlreadyDone");
5522 print '</td></tr>';
5523 dolibarr_set_const($db, 'MIGRATION_FLAG_INVOICE_MODELS_V20', 1, 'chaine', 0, 'To flag the upgrade of invoice template has been set', 0);
5524 return;
5525 }
5526
5527
5528 $db->begin();
5529
5530 $sql1 = "UPDATE ".$db->prefix()."export_model SET type = 'facture_0' WHERE type = 'facture_1'";
5531
5532 $resql1 = $db->query($sql1);
5533
5534 if (! $resql1) {
5535 dol_print_error($db);
5536 $db->rollback();
5537 print '</td></tr>';
5538 return;
5539 }
5540
5541 $modified1 = $db->affected_rows($resql1);
5542
5543 print str_repeat('.', $modified1);
5544
5545 $db->free($resql1);
5546
5547 $sql2 = "UPDATE ".$db->prefix()."export_model SET type = 'facture_1' WHERE type = 'facture_2'";
5548
5549 $resql2 = $db->query($sql2);
5550
5551 if (! $resql2) {
5552 dol_print_error($db);
5553 $db->rollback();
5554 print '</td></tr>';
5555 return;
5556 }
5557
5558 $modified2 = $db->affected_rows($resql2);
5559
5560 print str_repeat('.', $modified2);
5561
5562 $db->free($resql2);
5563
5564 if (empty($modified1 + $modified2)) {
5565 print $langs->trans('NothingToDo');
5566 }
5567
5568 $db->commit();
5569
5570 dolibarr_set_const($db, 'MIGRATION_FLAG_INVOICE_MODELS_V20', 1, 'chaine', 0, 'To flag the upgrade of invoice template has been set', 0);
5571
5572 echo '</td></tr>';
5573}
5574
5582{
5583 global $db, $langs;
5584
5585 $error = 0;
5586 $resultstring = '';
5587 $bookKeepingAddon = '';
5588
5589 // For the moment we set the numbering rule to neon (the rule argon has a lot of critical bugs to fix first).
5590 if (getDolGlobalString('BOOKKEEPING_ADDON') == '') {
5591 dolibarr_set_const($db, 'BOOKKEEPING_ADDON', 'mod_bookkeeping_neon', 'chaine', 0, '', $entity);
5592 $bookKeepingAddon = 'mod_bookkeeping_neon';
5593 }
5594
5595 print '<tr class="trforrunsql"><td colspan="4">';
5596 print '<b>'.$langs->trans('MigrationAccountancyBookkeeping')."</b><br>\n";
5597
5598 // TODO
5599 if ($bookKeepingAddon === 'mod_bookkeeping_argon') {
5600 $db->begin();
5601
5602 $sql = "SELECT DISTINCT YEAR(doc_date) as doc_year, MONTH(doc_date) as doc_month, code_journal, piece_num FROM ".$db->prefix()."accounting_bookkeeping";
5603 $sql .= " WHERE ref IS NULL AND entity = ".((int) $entity);
5604 $sql .= " ORDER BY doc_year, doc_month, code_journal, piece_num";
5605
5606 $resql = $db->query($sql);
5607
5608 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php';
5609 $bookkeeping = new BookKeeping($db);
5610 if ($resql) {
5611 while ($obj = $db->fetch_object($resql)) {
5612 $bookkeeping->doc_date = dol_mktime(0, 0, 0, $obj->doc_month, 1, $obj->doc_year);
5613 $bookkeeping->code_journal = $obj->code_journal;
5614 $ref = $bookkeeping->getNextNumRef();
5615
5616 $sqlUpd = "UPDATE ".$db->prefix()."accounting_bookkeeping SET ref = '".$db->escape($ref)."' WHERE piece_num = '".$db->escape($obj->piece_num)."' AND entity = ".((int) $entity);
5617 $resultstring = '.';
5618 print $resultstring;
5619 $resqlUpd = $db->query($sqlUpd);
5620 if (!$resqlUpd) {
5621 dol_print_error($db);
5622 $error++;
5623 }
5624 }
5625 } else {
5626 $error++;
5627 }
5628
5629 if (!$error) {
5630 $db->commit();
5631 } else {
5632 $db->rollback();
5633 }
5634 }
5635
5636 print '</td></tr>';
5637
5638 if (!$resultstring) {
5639 print '<tr class="trforrunsql" style=""><td class="wordbreak" colspan="4">'.$langs->trans("NothingToDo")."</td></tr>\n";
5640 }
5641}
5642
5649{
5650 global $conf, $db, $langs;
5651
5652 print '<tr class="trforrunsql"><td colspan="4">';
5653 print '<b>'.$langs->trans('MigrationApiRestTokens')."</b>:\n";
5654
5655 $error = 0;
5656 $nbofmigration = 0;
5657 $allexistingtokens = array();
5658
5659 $db->begin();
5660
5661 $sqlforalltokens = "SELECT oat.tokenstring";
5662 $sqlforalltokens .= " FROM ".$db->prefix()."oauth_token AS oat";
5663 $sqlforalltokens .= " WHERE oat.service = 'dolibarr_rest_api'";
5664
5665 $resalltoken = $db->query($sqlforalltokens);
5666
5667 if ($resalltoken) {
5668 while ($tokenobj = $db->fetch_object($resalltoken)) {
5669 $allexistingtokens[] = dolDecrypt($tokenobj->tokenstring);
5670 }
5671 } else {
5672 $error++;
5673 dol_print_error($db);
5674 $db->rollback();
5675 }
5676
5677 if (!$error) {
5678 $sql = "SELECT 'dolibarr_rest_api' AS service, u.api_key AS tokenstring, u.rowid AS fk_user, u.entity";
5679 $sql .= " FROM llx_user AS u";
5680 $sql .= " WHERE u.api_key IS NOT NULL AND u.api_key <> ''";
5681
5682 $result = $db->query($sql);
5683
5684 if ($result) {
5685 $tmpuser = new User($db);
5686
5687 while ($obj = $db->fetch_object($result)) {
5688 if (!in_array(dolDecrypt($obj->tokenstring), $allexistingtokens)) {
5689 // Load the object of the user of token so we can get the API_COUNT_CALL
5690 unset($tmpuser->conf); $tmpuser->conf = new stdClass();
5691 $tmpuser->fetch((int) $obj->fk_user, '', '', 1, ($obj->entity ? $obj->entity : $conf->entity));
5692
5693 $sqlforinsert = "INSERT INTO ".MAIN_DB_PREFIX."oauth_token (service, tokenstring, fk_user, datec, entity, apicount_total)";
5694 $sqlforinsert .= " VALUES ('".$db->escape($obj->service)."', '".$db->escape(dolEncrypt(dolDecrypt($obj->tokenstring)))."', ";
5695 $sqlforinsert .= ((int) $obj->fk_user).", '".$db->idate(dol_now())."', ".((int) $obj->entity).", ";
5696 $sqlforinsert .= getDolUserInt('API_COUNT_CALL', 0, $tmpuser);
5697 $sqlforinsert .= ")";
5698
5699 $insertresult = $db->query($sqlforinsert);
5700 if (!$insertresult) {
5701 $error++;
5702 dol_print_error($db);
5703 } else {
5704 $nbofmigration++;
5705 }
5706 }
5707 }
5708
5709 if (!$error) {
5710 $db->commit();
5711 } else {
5712 $db->rollback();
5713 }
5714 } else {
5715 dol_print_error($db);
5716 $db->rollback();
5717 }
5718 }
5719
5720 if (!$nbofmigration) {
5721 print $langs->trans("NothingToDo")."\n";
5722 } else {
5723 print $langs->trans('MigratedTokens', $nbofmigration);
5724 }
5725 print '</td></tr>';
5726}
5727
5728
5735{
5736 global $conf, $db, $langs;
5737
5738 include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
5739 include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
5740
5741 print '<tr class="trforrunsql"><td colspan="4">';
5742 print '<b>'.$langs->trans('InitAHMACKeyForBlockedLog')."</b>:\n";
5743
5744 $db->begin();
5745
5746 // Create HMAC if it does not exists yet
5747 $hmac_encoded_secret_key = getDolGlobalString('BLOCKEDLOG_HMAC_KEY');
5748 if (empty($hmac_encoded_secret_key)) {
5749 // Add key
5750 $hmac_secret_key = 'BLOCKEDLOGHMAC'.getRandomPassword(true); // This is using random_int for 32 chars
5751
5752 $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.
5753
5754 if ($result < 0) {
5755 dol_print_error($db);
5756 $db->rollback();
5757
5758 print '</td></tr>';
5759 return -1;
5760 }
5761
5762 print $langs->trans('Done');
5763 } else {
5764 // Decode the HMAC key
5765 $hmac_secret_key = dolDecrypt($hmac_encoded_secret_key);
5766
5767 if (! preg_match('/^BLOCKEDLOGHMAC/', $hmac_secret_key)) {
5768 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.';
5769 print 'Restore the value of $dolibarr_main_crypt_key that was used for encryption in database and restart the migration.';
5770 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.';
5771 $db->rollback();
5772
5773 print '</td></tr>';
5774 return -1;
5775 }
5776
5777 print $langs->trans("NothingToDo")."\n";
5778 }
5779
5780 $db->commit();
5781
5782 print '</td></tr>';
5783 return 1;
5784}
$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:71
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.
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...
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)
Return value of a param into GET or POST supervariable.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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)
getDoliDBInstance($type, $host, $user, $pass, $name, $port)
Return a DoliDB instance (database handler).
pHeader($subtitle, $next, $action='set', $param='', $forcejqueryurl='', $csstable='main-inside')
Show HTML header of install pages.
Definition inc.php:541
pFooter($nonext=0, $setuplang='', $jscheckfunction='', $withpleasewait=0, $morehtml='')
Print HTML footer of install pages.
Definition inc.php:635
dolibarr_install_syslog($message, $level=LOG_DEBUG)
Log function for install pages.
Definition inc.php:699
calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocaltax1_rate, $uselocaltax2_rate, $remise_percent_global, $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
if(getDolGlobalString( 'TAKEPOS_SHOW_CUSTOMER')) print $langs trans('Date')." left 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 PaymentTypeShortLIQ right SELECT p pos_change as p datep as p p num_paiement as f pf amount as amount
Definition receipt.php:466
dolEncrypt($chain, $key='', $ciphering='', $forceseed='')
Encode a string with a symmetric encryption.
dol_decode($chain, $key='1')
Decode a base 64 encoded + specific delta change.
dolDecrypt($chain, $key='')
Decode 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...
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.
if($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:923
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)
Reouverture des contrats qui ont au moins une ligne non fermee.
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 du champ stock dans produits.
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)
Migration des details commandes dans les details livraisons.
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)
Mise a jour des contrats (gestion du contrat + detail de contrat)
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)
Correspondence des expeditions et des commandes clients dans la 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.
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 des livraisons et des commandes clients dans la table llx_co_liv.
migrate_event_assignement_contact($db, $langs, $conf)
Migrate event assignment to owner.
migrate_contracts_date1($db, $langs, $conf)
Mise a jour des date de contrats non renseignees.
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.