dolibarr 22.0.5
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 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';
79
80global $langs;
81
82$grant_query = '';
83$step = 2;
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 $path = __DIR__.'/';
134 if (substr($sapi_type, 0, 3) == 'cli') {
135 print 'Syntax from command line: '.$script_file." x.y.z a.b.c [MAIN_MODULE_NAME1_TO_ENABLE,MAIN_MODULE_NAME2_TO_ENABLE...]\n";
136 print 'Example, upgrade from 19 to 20: '.$script_file." 19.0.0 20.0.0\n";
137 print 'Example, enable a module only: '.$script_file." 0.0.0 0.0.0 MAIN_MODULE_Adherent\n";
138 print "\n";
139 }
140 exit;
141}
142
143pHeader('', 'step5', GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'upgrade', 'versionfrom='.$versionfrom.'&versionto='.$versionto, '', 'main-inside main-inside-borderbottom');
144
145
146if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ09'))) {
147 print '<h3><img class="valignmiddle inline-block paddingright" src="../theme/common/octicons/build/svg/database.svg" width="20" alt="Database"> ';
148 print '<span class="inline-block valignmiddle">'.$langs->trans('DataMigration').'</span></h3>';
149
150 print '<table class="centpercent">';
151
152 // If password is encoded, we decode it
153 if ((!empty($dolibarr_main_db_pass) && preg_match('/(crypted|dolcrypt):/i', (string) $dolibarr_main_db_pass)) || !empty($dolibarr_main_db_encrypted_pass)) {
154 require_once $dolibarr_main_document_root.'/core/lib/security.lib.php';
155 if (!empty($dolibarr_main_db_pass) && preg_match('/crypted:/i', $dolibarr_main_db_pass)) {
156 $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', (string) $dolibarr_main_db_pass);
157 $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
158 $dolibarr_main_db_pass = dol_decode((string) $dolibarr_main_db_pass);
159 } elseif (preg_match('/dolcrypt:/i', (string) $dolibarr_main_db_pass)) {
160 $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
161 $dolibarr_main_db_pass = dolDecrypt((string) $dolibarr_main_db_pass);
162 } else {
163 $dolibarr_main_db_pass = dol_decode((string) $dolibarr_main_db_encrypted_pass);
164 }
165 }
166
167 // $conf is already instantiated inside inc.php
168 $conf->db->type = $dolibarr_main_db_type;
169 $conf->db->host = $dolibarr_main_db_host;
170 $conf->db->port = $dolibarr_main_db_port;
171 $conf->db->name = $dolibarr_main_db_name;
172 $conf->db->user = $dolibarr_main_db_user;
173 $conf->db->pass = $dolibarr_main_db_pass;
174
175 $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, (int) $conf->db->port);
176
177 if (!$db->connected) {
178 print '<tr><td colspan="4">'.$langs->trans("ErrorFailedToConnectToDatabase", $conf->db->name).'</td><td class="right">'.$langs->trans('Error').'</td></tr>';
179 dolibarr_install_syslog('upgrade2: failed to connect to database :'.$conf->db->name.' on '.$conf->db->host.' for user '.$conf->db->user, LOG_ERR);
180 $error++;
181 }
182
183 if (!$error) {
184 if ($db->database_selected) {
185 dolibarr_install_syslog('upgrade2: database connection successful :'.$dolibarr_main_db_name);
186 } else {
187 $error++;
188 }
189 }
190
191 if (empty($dolibarr_main_db_encryption)) {
192 $dolibarr_main_db_encryption = 0;
193 }
194 $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption;
195 if (empty($dolibarr_main_db_cryptkey)) {
196 $dolibarr_main_db_cryptkey = '';
197 }
198 $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey;
199
200 // Load global conf
201 $conf->setValues($db);
202
203
204 // Reforce log activation (samecode than into the inc.php)
205 $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1;
206 $conf->modules['syslog'] = 'syslog';
207 $conf->global->SYSLOG_LEVEL = constant('LOG_DEBUG');
208 if (!defined('SYSLOG_HANDLERS')) {
209 define('SYSLOG_HANDLERS', '["mod_syslog_file"]');
210 }
211 if (!defined('SYSLOG_FILE')) { // To avoid warning on systems with constant already defined
212 if (@is_writable('/tmp')) {
213 define('SYSLOG_FILE', '/tmp/dolibarr_install.log');
214 } elseif (!empty($_ENV["TMP"]) && @is_writable($_ENV["TMP"])) {
215 define('SYSLOG_FILE', $_ENV["TMP"].'/dolibarr_install.log');
216 } elseif (!empty($_ENV["TEMP"]) && @is_writable($_ENV["TEMP"])) {
217 define('SYSLOG_FILE', $_ENV["TEMP"].'/dolibarr_install.log');
218 } elseif (@is_writable('../../../../') && @file_exists('../../../../startdoliwamp.bat')) {
219 define('SYSLOG_FILE', '../../../../dolibarr_install.log'); // For DoliWamp
220 } elseif (@is_writable('../../')) {
221 define('SYSLOG_FILE', '../../dolibarr_install.log'); // For others
222 }
223 //print 'SYSLOG_FILE='.SYSLOG_FILE;exit;
224 }
225 if (defined('SYSLOG_FILE')) {
226 $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
227 }
228 if (!defined('SYSLOG_FILE_NO_ERROR')) {
229 define('SYSLOG_FILE_NO_ERROR', 1);
230 }
231 // We init log handler for install
232 $handlers = array('mod_syslog_file');
233 foreach ($handlers as $handler) {
234 $file = DOL_DOCUMENT_ROOT.'/core/modules/syslog/'.$handler.'.php';
235 if (!file_exists($file)) {
236 throw new Exception('Missing log handler file '.$handler.'.php');
237 }
238
239 require_once $file;
240 $loghandlerinstance = new $handler();
241 if (!$loghandlerinstance instanceof LogHandler) {
242 throw new Exception('Log handler does not extend LogHandler');
243 }
244
245 if (empty($conf->loghandlers[$handler])) {
246 $conf->loghandlers[$handler] = $loghandlerinstance;
247 }
248 }
249
250
251 $listofentities = array(1);
252
253 // Create the global $hookmanager object
254 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
255 $hookmanager = new HookManager($db);
256 $hookmanager->initHooks(array('upgrade2'));
257
258 $parameters = array('versionfrom' => $versionfrom, 'versionto' => $versionto);
259 $object = new stdClass();
260 $action = "upgrade";
261 $reshook = $hookmanager->executeHooks('doUpgradeBefore', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
262 if ($reshook >= 0 && is_array($hookmanager->resArray)) {
263 // Example: $hookmanager->resArray = array(2, 3, 10);
264 $listofentities = array_unique(array_merge($listofentities, $hookmanager->resArray));
265 }
266
267
268 /***************************************************************************************
269 *
270 * Migration of data
271 *
272 ***************************************************************************************/
273
274 // Force to execute this at begin to avoid the new core code into Dolibarr to be broken.
275 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN birth date';
276 $db->query($sql, 1);
277 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN dateemployment date';
278 $db->query($sql, 1);
279 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN dateemploymentend date';
280 $db->query($sql, 1);
281 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN default_range integer';
282 $db->query($sql, 1);
283 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user ADD COLUMN default_c_exp_tax_cat integer';
284 $db->query($sql, 1);
285 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN langs varchar(24)';
286 $db->query($sql, 1);
287 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN fieldcomputed text';
288 $db->query($sql, 1);
289 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN fielddefault varchar(255)';
290 $db->query($sql, 1);
291 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX."extrafields ADD COLUMN enabled varchar(255) DEFAULT '1'";
292 $db->query($sql, 1);
293 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'extrafields ADD COLUMN help text';
294 $db->query($sql, 1);
295 $sql = 'ALTER TABLE '.MAIN_DB_PREFIX.'user_rights ADD COLUMN entity integer DEFAULT 1 NOT NULL';
296 $db->query($sql, 1);
297
298
299 $db->begin();
300
301 foreach ($listofentities as $entity) {
302 dol_syslog("Process upgrade2 for entity ".$entity);
303
304 // Set $conf context for entity
305 $conf->setEntityValues($db, $entity);
306
307 // Reset forced setup after the setValues
308 if (defined('SYSLOG_FILE')) {
309 $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
310 }
311
312 $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1; // Add also log into conf->logbuffer.
313
314 $versiontoarray = array();
315 $versionranarray = array();
316
317 dol_syslog("Process upgrade2 d for entity ".$entity);
318
319 if (!$error) {
320 if (count($listofentities) > 1) {
321 print '<tr><td colspan="4">*** '.$langs->trans("Entity").' '.$entity.'</td></tr>'."\n";
322 }
323
324 // Current version is $conf->global->MAIN_VERSION_LAST_UPGRADE
325 // Version to install is DOL_VERSION
326 $dolibarrlastupgradeversionarray = preg_split('/[\.-]/', isset($conf->global->MAIN_VERSION_LAST_UPGRADE) ? $conf->global->MAIN_VERSION_LAST_UPGRADE : (isset($conf->global->MAIN_VERSION_LAST_INSTALL) ? $conf->global->MAIN_VERSION_LAST_INSTALL : ''));
327
328 // Chaque action de migration doit renvoyer une ligne sur 4 colonnes avec
329 // dans la 1ere colonne, la description de l'action a faire
330 // dans la 4eme colonne, le texte 'OK' si fait ou 'AlreadyDone' si rien n'est fait ou 'Error'
331
332 $versiontoarray = explode('.', $versionto);
333 $versionranarray = explode('.', DOL_VERSION);
334
335 $afterversionarray = explode('.', '2.0.0');
336 $beforeversionarray = explode('.', '2.7.9');
337 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
338 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
339
340 // Script pour V2 -> V2.1
341 migrate_paiements($db, $langs, $conf);
342
343 migrate_contracts_det($db, $langs, $conf);
344
345 migrate_contracts_date1($db, $langs, $conf);
346
347 migrate_contracts_date2($db, $langs, $conf);
348
349 migrate_contracts_date3($db, $langs, $conf);
350
351 migrate_contracts_open($db, $langs, $conf);
352
353 migrate_modeles($db, $langs, $conf);
354
355 migrate_price_propal($db, $langs, $conf);
356
357 migrate_price_commande($db, $langs, $conf);
358
360
361 migrate_price_contrat($db, $langs, $conf);
362
364
365
366 // Script pour V2.1 -> V2.2
368
370
371 migrate_links_transfert($db, $langs, $conf);
372
373
374 // Script pour V2.2 -> V2.4
376
377 migrate_commande_livraison($db, $langs, $conf);
378
379 migrate_detail_livraison($db, $langs, $conf);
380
381
382 // Script pour V2.5 -> V2.6
383 migrate_stocks($db, $langs, $conf);
384
385
386 // Script pour V2.6 -> V2.7
387 migrate_menus($db, $langs, $conf);
388
390
392
393 migrate_rename_directories($db, $langs, $conf, '/compta', '/banque');
394
395 migrate_rename_directories($db, $langs, $conf, '/societe', '/mycompany');
396 }
397
398 // Script for 2.8
399 $afterversionarray = explode('.', '2.7.9');
400 $beforeversionarray = explode('.', '2.8.9');
401 //print $versionto.' '.versioncompare($versiontoarray,$afterversionarray).' '.versioncompare($versiontoarray,$beforeversionarray);
402 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
403 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
404
405 migrate_price_facture($db, $langs, $conf); // Code of this function works for 2.8+ because need a field tva_tx
406
407 migrate_relationship_tables($db, $langs, $conf, 'co_exp', 'fk_commande', 'commande', 'fk_expedition', 'shipping');
408
409 migrate_relationship_tables($db, $langs, $conf, 'pr_exp', 'fk_propal', 'propal', 'fk_expedition', 'shipping');
410
411 migrate_relationship_tables($db, $langs, $conf, 'pr_liv', 'fk_propal', 'propal', 'fk_livraison', 'delivery');
412
413 migrate_relationship_tables($db, $langs, $conf, 'co_liv', 'fk_commande', 'commande', 'fk_livraison', 'delivery');
414
415 migrate_relationship_tables($db, $langs, $conf, 'co_pr', 'fk_propale', 'propal', 'fk_commande', 'commande');
416
417 migrate_relationship_tables($db, $langs, $conf, 'fa_pr', 'fk_propal', 'propal', 'fk_facture', 'facture');
418
419 migrate_relationship_tables($db, $langs, $conf, 'co_fa', 'fk_commande', 'commande', 'fk_facture', 'facture');
420
421 migrate_project_user_resp($db, $langs, $conf);
422
424 }
425
426 // Script for 2.9
427 $afterversionarray = explode('.', '2.8.9');
428 $beforeversionarray = explode('.', '2.9.9');
429 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
430 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
431
432 migrate_element_time($db, $langs, $conf);
433
435
436 migrate_shipping_delivery($db, $langs, $conf);
437
438 migrate_shipping_delivery2($db, $langs, $conf);
439 }
440
441 // Script for 3.0
442 $afterversionarray = explode('.', '2.9.9');
443 $beforeversionarray = explode('.', '3.0.9');
444 //if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
445 // No particular code
446 //}
447
448 // Script for 3.1
449 $afterversionarray = explode('.', '3.0.9');
450 $beforeversionarray = explode('.', '3.1.9');
451 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
452 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
453
454 migrate_rename_directories($db, $langs, $conf, '/rss', '/externalrss');
455
456 migrate_actioncomm_element($db, $langs, $conf);
457 }
458
459 // Script for 3.2
460 $afterversionarray = explode('.', '3.1.9');
461 $beforeversionarray = explode('.', '3.2.9');
462 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
463 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
464
465 migrate_price_contrat($db, $langs, $conf);
466
467 migrate_mode_reglement($db, $langs, $conf);
468
469 migrate_clean_association($db, $langs, $conf);
470 }
471
472 // Script for 3.3
473 $afterversionarray = explode('.', '3.2.9');
474 $beforeversionarray = explode('.', '3.3.9');
475 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
476 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
477
479 }
480
481 // Script for 3.4
482 // No specific scripts
483
484 // Tasks to do always and only into last targeted version
485 $afterversionarray = explode('.', '3.6.9'); // target is after this
486 $beforeversionarray = explode('.', '3.7.9'); // target is before this
487 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
488 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
489
490 migrate_event_assignement($db, $langs, $conf);
491 }
492
493 // Scripts for 3.9
494 $afterversionarray = explode('.', '3.7.9');
495 $beforeversionarray = explode('.', '3.8.9');
496 //if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
497 // No particular code
498 //}
499
500 // Scripts for 4.0
501 $afterversionarray = explode('.', '3.9.9');
502 $beforeversionarray = explode('.', '4.0.9');
503 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
504 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
505
506 migrate_rename_directories($db, $langs, $conf, '/fckeditor', '/medias');
507 }
508
509 // Scripts for 5.0
510 $afterversionarray = explode('.', '4.0.9');
511 $beforeversionarray = explode('.', '5.0.9');
512 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
513 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
514
515 // Migrate to add entity value into llx_societe_remise
516 migrate_remise_entity($db, $langs, $conf);
517
518 // Migrate to add entity value into llx_societe_remise_except
520 }
521
522 // Scripts for 6.0
523 $afterversionarray = explode('.', '5.0.9');
524 $beforeversionarray = explode('.', '6.0.9');
525 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
526 if (isModEnabled('multicompany')) {
527 global $multicompany_transverse_mode;
528
529 // Only if the transverse mode is not used
530 if (empty($multicompany_transverse_mode)) {
531 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
532
533 // Migrate to add entity value into llx_user_rights
534 migrate_user_rights_entity($db, $langs, $conf);
535
536 // Migrate to add entity value into llx_usergroup_rights
538 }
539 }
540 }
541
542 // Scripts for 7.0
543 $afterversionarray = explode('.', '6.0.9');
544 $beforeversionarray = explode('.', '7.0.9');
545 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
546 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
547
548 // Migrate contact association
550
551 migrate_reset_blocked_log($db, $langs, $conf);
552 }
553
554 // Scripts for 8.0
555 $afterversionarray = explode('.', '7.0.9');
556 $beforeversionarray = explode('.', '8.0.9');
557 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
558 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
559
560 migrate_rename_directories($db, $langs, $conf, '/contracts', '/contract');
561 }
562
563 // Scripts for 9.0
564 $afterversionarray = explode('.', '8.0.9');
565 $beforeversionarray = explode('.', '9.0.9');
566 //if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
567 //migrate_user_photospath();
568 //}
569
570 // Scripts for 11.0
571 $afterversionarray = explode('.', '10.0.9');
572 $beforeversionarray = explode('.', '11.0.9');
573 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
574 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
575
580 }
581
582 // Scripts for 14.0
583 $afterversionarray = explode('.', '13.0.9');
584 $beforeversionarray = explode('.', '14.0.9');
585 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
586 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
587
590 }
591
592 // Scripts for 16.0
593 $afterversionarray = explode('.', '15.0.9');
594 $beforeversionarray = explode('.', '16.0.9');
595 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
596 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
597
600 }
601
602 // Scripts for 17.0
603 $afterversionarray = explode('.', '16.0.9');
604 $beforeversionarray = explode('.', '17.0.9');
605 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
606 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
607
609 }
610
611 // Scripts for 18.0
612 $afterversionarray = explode('.', '17.0.9');
613 $beforeversionarray = explode('.', '18.0.9');
614 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
615 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
616
618 }
619
620 // Scripts for 19.0
621 /*
622 $afterversionarray = explode('.', '18.0.9');
623 $beforeversionarray = explode('.', '19.0.9');
624 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
625 }
626 */
627
628 // Scripts for 20.0
629 $afterversionarray = explode('.', '19.0.9');
630 $beforeversionarray = explode('.', '20.0.9');
631 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
632 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
633
635 }
636
637 // Scripts for 21.0
638 $afterversionarray = explode('.', '20.0.9');
639 $beforeversionarray = explode('.', '21.0.9');
640
641
642 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
643 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
644
646 }
647
648 // Scripts for 22.0
649 $afterversionarray = explode('.', '21.0.9');
650 $beforeversionarray = explode('.', '22.0.9');
651 if (versioncompare($versiontoarray, $afterversionarray) >= 0 && versioncompare($versiontoarray, $beforeversionarray) <= 0) {
652 dol_syslog("Run migrate_... versionto is between ".json_encode($afterversionarray)." and ".json_encode($beforeversionarray));
653
655 }
656 }
657
658 // Code executed only if migration is LAST ONE. Must always be done.
659 if (versioncompare($versiontoarray, $versionranarray) >= 0 || versioncompare($versiontoarray, $versionranarray) <= -3) {
660 dol_syslog("Run migrate_... if migration is LAST ONE");
661
662 // 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)
663 $listofmodule = array(
664 'MAIN_MODULE_ACCOUNTING' => 'newboxdefonly',
665 'MAIN_MODULE_AGENDA' => 'newboxdefonly',
666 'MAIN_MODULE_BOM' => 'menuonly',
667 'MAIN_MODULE_BANQUE' => 'menuonly',
668 'MAIN_MODULE_BARCODE' => 'newboxdefonly',
669 'MAIN_MODULE_CRON' => 'newboxdefonly',
670 'MAIN_MODULE_COMMANDE' => 'newboxdefonly',
671 'MAIN_MODULE_BLOCKEDLOG' => 'noboxes',
672 'MAIN_MODULE_DEPLACEMENT' => 'newboxdefonly',
673 'MAIN_MODULE_DON' => 'newboxdefonly',
674 'MAIN_MODULE_ECM' => 'newboxdefonly',
675 'MAIN_MODULE_EXTERNALSITE' => 'newboxdefonly',
676 'MAIN_MODULE_EXPENSEREPORT' => 'newboxdefonly',
677 'MAIN_MODULE_FACTURE' => 'newboxdefonly',
678 'MAIN_MODULE_FOURNISSEUR' => 'newboxdefonly',
679 'MAIN_MODULE_FICHEINTER' => 'newboxdefonly',
680 'MAIN_MODULE_HOLIDAY' => 'newboxdefonly',
681 'MAIN_MODULE_LOAN' => 'newboxdefonly',
682 'MAIN_MODULE_MARGIN' => 'menuonly',
683 'MAIN_MODULE_MRP' => 'menuonly',
684 'MAIN_MODULE_OPENSURVEY' => 'newboxdefonly',
685 'MAIN_MODULE_PAYBOX' => 'newboxdefonly',
686 'MAIN_MODULE_PRINTING' => 'newboxdefonly',
687 'MAIN_MODULE_PRODUIT' => 'newboxdefonly',
688 'MAIN_MODULE_RECRUITMENT' => 'menuonly',
689 'MAIN_MODULE_RESOURCE' => 'noboxes',
690 'MAIN_MODULE_SALARIES' => 'newboxdefonly',
691 'MAIN_MODULE_SERVICE' => 'newboxdefonly',
692 'MAIN_MODULE_SYSLOG' => 'newboxdefonly',
693 'MAIN_MODULE_SOCIETE' => 'newboxdefonly',
694 'MAIN_MODULE_STRIPE' => 'menuonly',
695 'MAIN_MODULE_TICKET' => 'newboxdefonly',
696 'MAIN_MODULE_TAKEPOS' => 'newboxdefonly',
697 'MAIN_MODULE_USER' => 'newboxdefonly', //This one must be always done and only into last targeted version)
698 'MAIN_MODULE_VARIANTS' => 'newboxdefonly',
699 'MAIN_MODULE_WEBSITE' => 'newboxdefonly',
700 );
701
702 $result = migrate_reload_modules($db, $langs, $conf, $listofmodule);
703 if ($result < 0) {
704 $error++;
705 }
706
707 // Reload menus (this must be always and only into last targeted version)
708 $result = migrate_reload_menu($db, $langs, $conf);
709 if ($result < 0) {
710 $error++;
711 }
712 }
713
714 // Can force activation of some module during migration with parameter 'enablemodules=MAIN_MODULE_XXX,MAIN_MODULE_YYY,...'
715 // In most cases (online install or upgrade) $enablemodules is empty. Can be forced when ran from command line.
716 if (!$error && $enablemodules) {
717 // Reload modules (this must be always done and only into last targeted version)
718 $listofmodules = array();
719 $enablemodules = preg_replace('/enablemodules=/', '', $enablemodules);
720 $tmplistofmodules = explode(',', $enablemodules);
721 foreach ($tmplistofmodules as $value) {
722 $listofmodules[$value] = 'forceactivate';
723 }
724
725 $resultreloadmodules = migrate_reload_modules($db, $langs, $conf, $listofmodules, 1);
726 if ($resultreloadmodules < 0) {
727 $error++;
728 }
729 }
730
731
732 // Can call a dedicated external upgrade process with hook doUpgradeAfterDB()
733 if (!$error) {
734 $parameters = array('versionfrom' => $versionfrom, 'versionto' => $versionto, 'conf' => $conf);
735 $object = new stdClass();
736 $action = "upgrade";
737 $reshook = $hookmanager->executeHooks('doUpgradeAfterDB', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
738 if ($hookmanager->resNbOfHooks > 0) {
739 if ($reshook < 0) {
740 print '<tr><td colspan="4">';
741 print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: ';
742 print $hookmanager->error;
743 print "<!-- (".$reshook.") -->";
744 print '</td></tr>';
745 } else {
746 print '<tr class="trforrunsql"><td colspan="4">';
747 print '<b>'.$langs->trans('UpgradeExternalModule').' (DB)</b>: <span class="ok">OK</span>';
748 print "<!-- (".$reshook.") -->";
749 print '</td></tr>';
750 }
751 } else {
752 //if (!empty($conf->modules))
753 if (!empty($conf->modules_parts['hooks'])) { // If there is at least one module with one hook, we show message to say nothing was done
754 print '<tr class="trforrunsql"><td colspan="4">';
755 print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: '.$langs->trans("NodoUpgradeAfterDB");
756 print '</td></tr>';
757 }
758 }
759 }
760 }
761
762 print '</table>';
763
764 if (!$error) {
765 // Set constant to ask to remake a new ping to inform about upgrade (if first ping was done and OK)
766 $sql = 'UPDATE '.MAIN_DB_PREFIX."const SET VALUE = 'torefresh' WHERE name = 'MAIN_FIRST_PING_OK_ID'";
767 $db->query($sql, 1);
768 }
769
770 // We always commit.
771 // Process is designed so we can run it several times whatever is situation.
772 $db->commit();
773
774
775 /***************************************************************************************
776 *
777 * Migration of files
778 *
779 ***************************************************************************************/
780
781 foreach ($listofentities as $entity) {
782 // Set $conf context for entity
783 $conf->setEntityValues($db, $entity);
784 // Reset forced setup after the setValues
785 if (defined('SYSLOG_FILE')) {
786 $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
787 }
788 $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1;
789
790
791 // Copy directory medias
792 $srcroot = DOL_DOCUMENT_ROOT.'/install/medias';
793 $destroot = DOL_DATA_ROOT.'/medias';
794 dolCopyDir($srcroot, $destroot, '0', 0);
795
796
797 // Actions for all versions (no database change but delete some files and directories)
798 migrate_delete_old_files($db, $langs, $conf);
799 migrate_delete_old_dir($db, $langs, $conf);
800 // Actions for all versions (no database change but create some directories)
801 dol_mkdir(DOL_DATA_ROOT.'/bank');
802 // Actions for all versions (no database change but rename some directories)
803 migrate_rename_directories($db, $langs, $conf, '/banque/bordereau', '/bank/checkdeposits');
804
805
806 $parameters = array('versionfrom' => $versionfrom, 'versionto' => $versionto, 'conf' => $conf);
807 $object = new stdClass();
808 $action = "upgrade";
809 $reshook = $hookmanager->executeHooks('doUpgradeAfterFiles', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
810 if ($hookmanager->resNbOfHooks > 0) {
811 if ($reshook < 0) {
812 print '<tr><td colspan="4">';
813 print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: ';
814 print $hookmanager->error;
815 print "<!-- (".$reshook.") -->";
816 print '</td></tr>';
817 } else {
818 print '<tr class="trforrunsql"><td colspan="4">';
819 print '<b>'.$langs->trans('UpgradeExternalModule').' (Files)</b>: <span class="ok">OK</span>';
820 print "<!-- (".$reshook.") -->";
821 print '</td></tr>';
822 }
823 } else {
824 //if (!empty($conf->modules))
825 if (!empty($conf->modules_parts['hooks'])) { // If there is at least one module with one hook, we show message to say nothing was done
826 print '<tr class="trforrunsql"><td colspan="4">';
827 print '<b>'.$langs->trans('UpgradeExternalModule').'</b>: '.$langs->trans("NodoUpgradeAfterFiles");
828 print '</td></tr>';
829 }
830 }
831 }
832
833 $db->close();
834
835 $silent = 0;
836 if (!$silent) {
837 print '<table width="100%">';
838 print '<tr><td style="width: 30%">'.$langs->trans("MigrationFinished").'</td>';
839 print '<td class="right">';
840 if ($error == 0) {
841 //print '<span class="ok">'.$langs->trans("OK").'</span> - '; // $error = 0 does not mean there is no error (error are not always trapped)
842 } else {
843 print '<span class="error">'.$langs->trans("Error").'</span> - ';
844 }
845
846 //if (!empty($conf->use_javascript_ajax)) { // use_javascript_ajax is not defined
847 print '<script type="text/javascript">
848 jQuery(document).ready(function() {
849 function init_trrunsql()
850 {
851 console.log("toggle .trforrunsql");
852 jQuery(".trforrunsql").toggle();
853 }
854 init_trrunsql();
855 jQuery(".trforrunsqlshowhide").click(function() {
856 init_trrunsql();
857 });
858 });
859 </script>';
860 print '<a class="trforrunsqlshowhide" href="#">'.$langs->trans("ShowHideDetails").'</a>';
861 //}
862
863 print '</td></tr>'."\n";
864 print '</table>';
865 }
866
867 //print '<div><br>'.$langs->trans("MigrationFinished").'</div>';
868} else {
869 print '<div class="error">'.$langs->trans('ErrorWrongParameters').'</div>';
870 $error++;
871}
872
873$ret = 0;
874if ($error && isset($argv[1])) {
875 $ret = 1;
876}
877dolibarr_install_syslog("Exit ".$ret);
878
879dolibarr_install_syslog("--- upgrade2: end");
880pFooter($error ? 2 : 0, $setuplang);
881
882if ($db->connected) {
883 $db->close();
884}
885
886// Return code if ran from command line
887if ($ret) {
888 exit($ret);
889}
890
891
892
901function migrate_paiements($db, $langs, $conf)
902{
903 print '<tr><td colspan="4">';
904
905 print '<br>';
906 print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
907
908 $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement", "fk_facture");
909 $obj = $db->fetch_object($result);
910 if ($obj) {
911 $sql = "SELECT p.rowid, p.fk_facture, p.amount";
912 $sql .= " FROM ".MAIN_DB_PREFIX."paiement as p";
913 $sql .= " WHERE p.fk_facture > 0";
914
915 $resql = $db->query($sql);
916 $row = array();
917 $num = 0;
918
919 dolibarr_install_syslog("upgrade2::migrate_paiements");
920 if ($resql) {
921 $i = 0;
922 $num = $db->num_rows($resql);
923
924 while ($i < $num) {
925 $obj = $db->fetch_object($resql);
926 $row[$i][0] = $obj->rowid;
927 $row[$i][1] = $obj->fk_facture;
928 $row[$i][2] = $obj->amount;
929 $i++;
930 }
931 } else {
932 dol_print_error($db);
933 }
934
935 if ($num) {
936 print $langs->trans('MigrationPaymentsNumberToUpdate', $num)."<br>\n";
937 $res = 0;
938 if ($db->begin()) {
939 $num = count($row);
940 for ($i = 0; $i < $num; $i++) {
941 $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
942 $sql .= " VALUES (".((int) $row[$i][1]).",".((int) $row[$i][0]).",".((float) $row[$i][2]).")";
943
944 $res += $db->query($sql);
945
946 $sql = "UPDATE ".MAIN_DB_PREFIX."paiement SET fk_facture = 0 WHERE rowid = ".((int) $row[$i][0]);
947
948 $res += $db->query($sql);
949
950 print $langs->trans('MigrationProcessPaymentUpdate', $row[$i][0])."<br>\n";
951 }
952 }
953
954 if (is_array($row) && $res == (2 * count($row))) {
955 $db->commit();
956 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
957 } else {
958 $db->rollback();
959 print $langs->trans('MigrationUpdateFailed').'<br>';
960 }
961 } else {
962 print $langs->trans('MigrationPaymentsNothingToUpdate')."<br>\n";
963 }
964 } else {
965 print $langs->trans('MigrationPaymentsNothingToUpdate')."<br>\n";
966 }
967
968 print '</td></tr>';
969}
970
982{
983 print '<tr><td colspan="4">';
984
985 print '<br>';
986 print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
987
988 $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement", "fk_facture");
989 $obj = $db->fetch_object($result);
990 if ($obj) {
991 // All answer of this requests should have a parent into llx_paiement_facture
992 $sql = "SELECT DISTINCT p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,";
993 $sql .= " bu2.url_id as socid";
994 $sql .= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)";
995 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_paiement = p.rowid";
996 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu2 ON (bu.fk_bank=bu2.fk_bank AND bu2.type = 'company')";
997 $sql .= " WHERE pf.rowid IS NULL AND (p.rowid=bu.url_id AND bu.type='payment') AND bu.fk_bank = b.rowid";
998 $sql .= " AND b.rappro = 1";
999 $sql .= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)";
1000
1001 $resql = $db->query($sql);
1002
1003 dolibarr_install_syslog("upgrade2::migrate_paiements_orphelins_1");
1004 $row = array();
1005 if ($resql) {
1006 $i = $j = 0;
1007 $num = $db->num_rows($resql);
1008
1009 while ($i < $num) {
1010 $obj = $db->fetch_object($resql);
1011 if ($obj->pamount == $obj->bamount && $obj->socid) { // Pour etre sur d'avoir bon cas
1012 $row[$j]['paymentid'] = $obj->rowid; // paymentid
1013 $row[$j]['pamount'] = $obj->pamount;
1014 $row[$j]['fk_bank'] = $obj->fk_bank;
1015 $row[$j]['bamount'] = $obj->bamount;
1016 $row[$j]['socid'] = $obj->socid;
1017 $row[$j]['datec'] = $obj->datec;
1018 $j++;
1019 }
1020 $i++;
1021 }
1022 } else {
1023 dol_print_error($db);
1024 }
1025
1026 if (count($row)) {
1027 print $langs->trans('OrphelinsPaymentsDetectedByMethod', 1).': '.count($row)."<br>\n";
1028 $db->begin();
1029
1030 $res = 0;
1031 $num = count($row);
1032 for ($i = 0; $i < $num; $i++) {
1033 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') == 2) {
1034 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>';
1035 }
1036
1037 // Look for invoices without payment relations with the same amount and same comppany
1038 $sql = " SELECT DISTINCT f.rowid from ".MAIN_DB_PREFIX."facture as f";
1039 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
1040 $sql .= " WHERE f.fk_statut in (2,3) AND fk_soc = ".((int) $row[$i]['socid'])." AND total_ttc = ".((float) $row[$i]['pamount']);
1041 $sql .= " AND pf.fk_facture IS NULL";
1042 $sql .= " ORDER BY f.fk_statut";
1043 //print $sql.'<br>';
1044 $resql = $db->query($sql);
1045 if ($resql) {
1046 $num = $db->num_rows($resql);
1047 //print 'Nb of invoice found for this amount and company :'.$num.'<br>';
1048 if ($num >= 1) {
1049 $obj = $db->fetch_object($resql);
1050 $facid = $obj->rowid;
1051
1052 $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
1053 $sql .= " VALUES (".((int) $facid).",".((int) $row[$i]['paymentid']).", ".((float) $row[$i]['pamount']).")";
1054
1055 $res += $db->query($sql);
1056
1057 print $langs->trans('MigrationProcessPaymentUpdate', 'facid='.$facid.'-paymentid='.$row[$i]['paymentid'].'-amount='.$row[$i]['pamount'])."<br>\n";
1058 }
1059 } else {
1060 print 'ERROR';
1061 }
1062 }
1063
1064 if ($res > 0) {
1065 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1066 } else {
1067 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1068 }
1069
1070 $db->commit();
1071 } else {
1072 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1073 }
1074 } else {
1075 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1076 }
1077
1078 print '</td></tr>';
1079}
1080
1092{
1093 print '<tr><td colspan="4">';
1094
1095 print '<br>';
1096 print '<b>'.$langs->trans('MigrationPaymentsUpdate')."</b><br>\n";
1097
1098 $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiement", "fk_facture");
1099 $obj = $db->fetch_object($result);
1100 if ($obj) {
1101 // Tous les enregistrements qui sortent de cette requete devrait avoir un pere dans llx_paiement_facture
1102 $sql = "SELECT DISTINCT p.rowid, p.datec, p.amount as pamount, bu.fk_bank, b.amount as bamount,";
1103 $sql .= " bu2.url_id as socid";
1104 $sql .= " FROM (".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."bank_url as bu, ".MAIN_DB_PREFIX."bank as b)";
1105 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON pf.fk_paiement = p.rowid";
1106 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu2 ON (bu.fk_bank = bu2.fk_bank AND bu2.type = 'company')";
1107 $sql .= " WHERE pf.rowid IS NULL AND (p.fk_bank = bu.fk_bank AND bu.type = 'payment') AND bu.fk_bank = b.rowid";
1108 $sql .= " AND (p.fk_facture = 0 OR p.fk_facture IS NULL)";
1109
1110 $resql = $db->query($sql);
1111
1112 dolibarr_install_syslog("upgrade2::migrate_paiements_orphelins_2");
1113 $row = array();
1114 if ($resql) {
1115 $i = $j = 0;
1116 $num = $db->num_rows($resql);
1117
1118 while ($i < $num) {
1119 $obj = $db->fetch_object($resql);
1120 if ($obj->pamount == $obj->bamount && $obj->socid) { // Pour etre sur d'avoir bon cas
1121 $row[$j]['paymentid'] = $obj->rowid; // paymentid
1122 $row[$j]['pamount'] = $obj->pamount;
1123 $row[$j]['fk_bank'] = $obj->fk_bank;
1124 $row[$j]['bamount'] = $obj->bamount;
1125 $row[$j]['socid'] = $obj->socid;
1126 $row[$j]['datec'] = $obj->datec;
1127 $j++;
1128 }
1129 $i++;
1130 }
1131 } else {
1132 dol_print_error($db);
1133 }
1134
1135 $nberr = 0;
1136
1137 $num = count($row);
1138 if ($num) {
1139 print $langs->trans('OrphelinsPaymentsDetectedByMethod', 2).': '.count($row)."<br>\n";
1140 $db->begin();
1141
1142 $res = 0;
1143 for ($i = 0; $i < $num; $i++) {
1144 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') == 2) {
1145 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>';
1146 }
1147
1148 // Look for invoices without payment relations with the same amount and same comppany
1149 $sql = " SELECT DISTINCT f.rowid from ".MAIN_DB_PREFIX."facture as f";
1150 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
1151 $sql .= " WHERE f.fk_statut in (2,3) AND fk_soc = ".((int) $row[$i]['socid'])." AND total_ttc = ".((float) $row[$i]['pamount']);
1152 $sql .= " AND pf.fk_facture IS NULL";
1153 $sql .= " ORDER BY f.fk_statut";
1154 //print $sql.'<br>';
1155 $resql = $db->query($sql);
1156 if ($resql) {
1157 $num = $db->num_rows($resql);
1158 //print 'Nb of invoice found for this amount and company :'.$num.'<br>';
1159 if ($num >= 1) {
1160 $obj = $db->fetch_object($resql);
1161 $facid = $obj->rowid;
1162
1163 $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount)";
1164 $sql .= " VALUES (".((int) $facid).",".((int) $row[$i]['paymentid']).", ".((float) $row[$i]['pamount']).")";
1165
1166 $res += $db->query($sql);
1167
1168 print $langs->trans('MigrationProcessPaymentUpdate', 'facid='.$facid.'-paymentid='.$row[$i]['paymentid'].'-amount='.$row[$i]['pamount'])."<br>\n";
1169 }
1170 } else {
1171 print 'ERROR';
1172 $nberr++;
1173 }
1174 }
1175
1176 if ($res > 0) {
1177 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1178 } else {
1179 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1180 }
1181
1182 $db->commit();
1183 } else {
1184 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1185 }
1186
1187 // Delete obsolete fields fk_facture
1188 $db->begin();
1189
1190 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."paiement DROP COLUMN fk_facture";
1191 $db->query($sql);
1192
1193 if (!$nberr) {
1194 $db->commit();
1195 } else {
1196 print 'ERROR';
1197 $db->rollback();
1198 }
1199 } else {
1200 print $langs->trans('MigrationPaymentsNothingUpdatable')."<br>\n";
1201 }
1202
1203 print '</td></tr>';
1204}
1205
1206
1215function migrate_contracts_det($db, $langs, $conf)
1216{
1217 print '<tr><td colspan="4">';
1218
1219 $nberr = 0;
1220
1221 print '<br>';
1222 print '<b>'.$langs->trans('MigrationContractsUpdate')."</b><br>\n";
1223
1224 $sql = "SELECT c.rowid as cref, c.date_contrat, c.statut, c.fk_product, c.fk_facture, c.fk_user_author,";
1225 $sql .= " p.ref, p.label, p.description, p.price, p.tva_tx, p.duration, cd.rowid";
1226 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
1227 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p";
1228 $sql .= " ON c.fk_product = p.rowid";
1229 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd";
1230 $sql .= " ON c.rowid=cd.fk_contrat";
1231 $sql .= " WHERE cd.rowid IS NULL AND p.rowid IS NOT NULL";
1232 $resql = $db->query($sql);
1233
1234 dolibarr_install_syslog("upgrade2::migrate_contracts_det");
1235 if ($resql) {
1236 $i = 0;
1237 $row = array();
1238 $num = $db->num_rows($resql);
1239
1240 if ($num) {
1241 print $langs->trans('MigrationContractsNumberToUpdate', $num)."<br>\n";
1242 $db->begin();
1243
1244 while ($i < $num) {
1245 $obj = $db->fetch_object($resql);
1246
1247 $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet (";
1248 $sql .= "fk_contrat, fk_product, statut, label, description,";
1249 $sql .= "date_ouverture_prevue, date_ouverture, date_fin_validite, tva_tx, qty,";
1250 $sql .= "subprice, price_ht, fk_user_author, fk_user_ouverture)";
1251 $sql .= " VALUES (";
1252 $sql .= ((int) $obj->cref).", ".($obj->fk_product ? ((int) $obj->fk_product) : 0).", ";
1253 $sql .= "0, ";
1254 $sql .= "'".$db->escape($obj->label)."', null, ";
1255 $sql .= ($obj->date_contrat ? "'".$db->idate($db->jdate($obj->date_contrat))."'" : "null").", ";
1256 $sql .= "null, ";
1257 $sql .= "null, ";
1258 $sql .= ((float) $obj->tva_tx).", 1, ";
1259 $sql .= ((float) $obj->price).", ".((float) $obj->price).", ".((int) $obj->fk_user_author).",";
1260 $sql .= "null";
1261 $sql .= ")";
1262
1263 if ($db->query($sql)) {
1264 print $langs->trans('MigrationContractsLineCreation', $obj->cref)."<br>\n";
1265 } else {
1266 dol_print_error($db);
1267 $nberr++;
1268 }
1269
1270 $i++;
1271 }
1272
1273 if (!$nberr) {
1274 // $db->rollback();
1275 $db->commit();
1276 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1277 } else {
1278 $db->rollback();
1279 print $langs->trans('MigrationUpdateFailed').'<br>';
1280 }
1281 } else {
1282 print $langs->trans('MigrationContractsNothingToUpdate')."<br>\n";
1283 }
1284 } else {
1285 print $langs->trans('MigrationContractsFieldDontExist')."<br>\n";
1286 // dol_print_error($db);
1287 }
1288
1289 print '</td></tr>';
1290}
1291
1300function migrate_links_transfert($db, $langs, $conf)
1301{
1302 print '<tr><td colspan="4">';
1303
1304 $nberr = 0;
1305
1306 print '<br>';
1307 print '<b>'.$langs->trans('MigrationBankTransfertsUpdate')."</b><br>\n";
1308
1309 $sql = "SELECT ba.rowid as barowid, bb.rowid as bbrowid";
1310 $sql .= " FROM ".MAIN_DB_PREFIX."bank as bb, ".MAIN_DB_PREFIX."bank as ba";
1311 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON bu.fk_bank = ba.rowid";
1312 $sql .= " WHERE ba.amount = -bb.amount AND ba.fk_account <> bb.fk_account";
1313 $sql .= " AND ba.datev = bb.datev AND ba.datec = bb.datec";
1314 $sql .= " AND bu.fk_bank IS NULL";
1315 $resql = $db->query($sql);
1316
1317 dolibarr_install_syslog("upgrade2::migrate_links_transfert");
1318 if ($resql) {
1319 $i = 0;
1320 $row = array();
1321 $num = $db->num_rows($resql);
1322
1323 if ($num) {
1324 print $langs->trans('MigrationBankTransfertsToUpdate', $num)."<br>\n";
1325 $db->begin();
1326
1327 while ($i < $num) {
1328 $obj = $db->fetch_object($resql);
1329
1330 $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url (";
1331 $sql .= "fk_bank, url_id, url, label, type";
1332 $sql .= ")";
1333 $sql .= " VALUES (";
1334 $sql .= $obj->barowid.",".$obj->bbrowid.", '/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert'";
1335 $sql .= ")";
1336
1337 //print $sql.'<br>';
1338 dolibarr_install_syslog("migrate_links_transfert");
1339
1340 if (!$db->query($sql)) {
1341 dol_print_error($db);
1342 $nberr++;
1343 }
1344
1345 $i++;
1346 }
1347
1348 if (!$nberr) {
1349 // $db->rollback();
1350 $db->commit();
1351 print $langs->trans('MigrationSuccessfullUpdate')."<br>";
1352 } else {
1353 $db->rollback();
1354 print $langs->trans('MigrationUpdateFailed').'<br>';
1355 }
1356 } else {
1357 print $langs->trans('MigrationBankTransfertsNothingToUpdate')."<br>\n";
1358 }
1359 } else {
1360 dol_print_error($db);
1361 }
1362
1363 print '</td></tr>';
1364}
1365
1374function migrate_contracts_date1($db, $langs, $conf)
1375{
1376 print '<tr><td colspan="4">';
1377
1378 print '<br>';
1379 print '<b>'.$langs->trans('MigrationContractsEmptyDatesUpdate')."</b><br>\n";
1380
1381 $sql = "update ".MAIN_DB_PREFIX."contrat set date_contrat=tms where date_contrat is null";
1382 dolibarr_install_syslog("upgrade2::migrate_contracts_date1");
1383 $resql = $db->query($sql);
1384 if (!$resql) {
1385 dol_print_error($db);
1386 }
1387 if ($db->affected_rows($resql) > 0) {
1388 print $langs->trans('MigrationContractsEmptyDatesUpdateSuccess')."<br>\n";
1389 } else {
1390 print $langs->trans('MigrationContractsEmptyDatesNothingToUpdate')."<br>\n";
1391 }
1392
1393 $sql = "update ".MAIN_DB_PREFIX."contrat set datec=tms where datec is null";
1394 dolibarr_install_syslog("upgrade2::migrate_contracts_date1");
1395 $resql = $db->query($sql);
1396 if (!$resql) {
1397 dol_print_error($db);
1398 }
1399 if ($db->affected_rows($resql) > 0) {
1400 print $langs->trans('MigrationContractsEmptyCreationDatesUpdateSuccess')."<br>\n";
1401 } else {
1402 print $langs->trans('MigrationContractsEmptyCreationDatesNothingToUpdate')."<br>\n";
1403 }
1404
1405 print '</td></tr>';
1406}
1407
1416function migrate_contracts_date2($db, $langs, $conf)
1417{
1418 print '<tr><td colspan="4">';
1419
1420 $nberr = 0;
1421
1422 print '<br>';
1423 print '<b>'.$langs->trans('MigrationContractsInvalidDatesUpdate')."</b><br>\n";
1424
1425 $sql = "SELECT c.rowid as cref, c.datec, c.date_contrat, MIN(cd.date_ouverture) as datemin";
1426 $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c,";
1427 $sql .= " ".MAIN_DB_PREFIX."contratdet as cd";
1428 $sql .= " WHERE c.rowid=cd.fk_contrat AND cd.date_ouverture IS NOT NULL";
1429 $sql .= " GROUP BY c.rowid, c.date_contrat";
1430 $resql = $db->query($sql);
1431
1432 dolibarr_install_syslog("upgrade2::migrate_contracts_date2");
1433 if ($resql) {
1434 $i = 0;
1435 $row = array();
1436 $num = $db->num_rows($resql);
1437
1438 if ($num) {
1439 $nbcontratsmodifie = 0;
1440 $db->begin();
1441
1442 while ($i < $num) {
1443 $obj = $db->fetch_object($resql);
1444 if ($obj->date_contrat > $obj->datemin) {
1445 $datemin = $db->jdate($obj->datemin);
1446
1447 print $langs->trans('MigrationContractsInvalidDateFix', $obj->cref, $obj->date_contrat, $obj->datemin)."<br>\n";
1448 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat";
1449 $sql .= " SET date_contrat='".$db->idate($datemin)."'";
1450 $sql .= " WHERE rowid = ".((int) $obj->cref);
1451 $resql2 = $db->query($sql);
1452 if (!$resql2) {
1453 dol_print_error($db);
1454 }
1455
1456 $nbcontratsmodifie++;
1457 }
1458 $i++;
1459 }
1460
1461 $db->commit();
1462
1463 if ($nbcontratsmodifie) {
1464 print $langs->trans('MigrationContractsInvalidDatesNumber', $nbcontratsmodifie)."<br>\n";
1465 } else {
1466 print $langs->trans('MigrationContractsInvalidDatesNothingToUpdate')."<br>\n";
1467 }
1468 }
1469 } else {
1470 dol_print_error($db);
1471 }
1472
1473 print '</td></tr>';
1474}
1475
1484function migrate_contracts_date3($db, $langs, $conf)
1485{
1486 print '<tr><td colspan="4">';
1487
1488 print '<br>';
1489 print '<b>'.$langs->trans('MigrationContractsIncoherentCreationDateUpdate')."</b><br>\n";
1490
1491 $sql = "update ".MAIN_DB_PREFIX."contrat set datec=date_contrat where datec is null or datec > date_contrat";
1492 dolibarr_install_syslog("upgrade2::migrate_contracts_date3");
1493 $resql = $db->query($sql);
1494 if (!$resql) {
1495 dol_print_error($db);
1496 }
1497 if ($db->affected_rows($resql) > 0) {
1498 print $langs->trans('MigrationContractsIncoherentCreationDateUpdateSuccess')."<br>\n";
1499 } else {
1500 print $langs->trans('MigrationContractsIncoherentCreationDateNothingToUpdate')."<br>\n";
1501 }
1502
1503 print '</td></tr>';
1504}
1505
1514function migrate_contracts_open($db, $langs, $conf)
1515{
1516 print '<tr><td colspan="4">';
1517
1518 print '<br>';
1519 print '<b>'.$langs->trans('MigrationReopeningContracts')."</b><br>\n";
1520
1521 $sql = "SELECT c.rowid as cref FROM ".MAIN_DB_PREFIX."contrat as c, ".MAIN_DB_PREFIX."contratdet as cd";
1522 $sql .= " WHERE cd.statut = 4 AND c.statut=2 AND c.rowid=cd.fk_contrat";
1523 dolibarr_install_syslog("upgrade2::migrate_contracts_open");
1524 $resql = $db->query($sql);
1525 if (!$resql) {
1526 dol_print_error($db);
1527 }
1528 if ($db->affected_rows($resql) > 0) {
1529 $i = 0;
1530 $row = array();
1531 $num = $db->num_rows($resql);
1532
1533 if ($num) {
1534 $nbcontratsmodifie = 0;
1535 $db->begin();
1536
1537 while ($i < $num) {
1538 $obj = $db->fetch_object($resql);
1539
1540 print $langs->trans('MigrationReopenThisContract', $obj->cref)."<br>\n";
1541 $sql = "UPDATE ".MAIN_DB_PREFIX."contrat";
1542 $sql .= " SET statut = 1";
1543 $sql .= " WHERE rowid = ".((int) $obj->cref);
1544 $resql2 = $db->query($sql);
1545 if (!$resql2) {
1546 dol_print_error($db);
1547 }
1548
1549 $nbcontratsmodifie++;
1550
1551 $i++;
1552 }
1553
1554 $db->commit();
1555
1556 if ($nbcontratsmodifie) {
1557 print $langs->trans('MigrationReopenedContractsNumber', $nbcontratsmodifie)."<br>\n";
1558 } else {
1559 print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n";
1560 }
1561 }
1562 } else {
1563 print $langs->trans('MigrationReopeningContractsNothingToUpdate')."<br>\n";
1564 }
1565
1566 print '</td></tr>';
1567}
1568
1578{
1579 global $bc;
1580
1581 print '<tr><td colspan="4">';
1582 print '<br>';
1583 print '<b>'.$langs->trans('SuppliersInvoices')."</b><br>\n";
1584 print '</td></tr>';
1585
1586 $result = $db->DDLDescTable(MAIN_DB_PREFIX."paiementfourn", "fk_facture_fourn");
1587 $obj = $db->fetch_object($result);
1588 if ($obj) {
1589 $error = 0;
1590 $nb = 0;
1591
1592 $select_sql = 'SELECT rowid, fk_facture_fourn, amount';
1593 $select_sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn';
1594 $select_sql .= ' WHERE fk_facture_fourn IS NOT NULL';
1595
1596 dolibarr_install_syslog("upgrade2::migrate_paiementfourn_facturefourn");
1597 $select_resql = $db->query($select_sql);
1598 if ($select_resql) {
1599 $select_num = $db->num_rows($select_resql);
1600 $i = 0;
1601
1602 // Pour chaque paiement fournisseur, on insere une ligne dans paiementfourn_facturefourn
1603 while (($i < $select_num) && (!$error)) {
1604 $select_obj = $db->fetch_object($select_resql);
1605
1606 // Verifier si la ligne est deja dans la nouvelle table. On ne veut pas inserer de doublons.
1607 $check_sql = 'SELECT fk_paiementfourn, fk_facturefourn';
1608 $check_sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn';
1609 $check_sql .= ' WHERE fk_paiementfourn = '.((int) $select_obj->rowid).' AND fk_facturefourn = '.((int) $select_obj->fk_facture_fourn);
1610 $check_resql = $db->query($check_sql);
1611 if ($check_resql) {
1612 $check_num = $db->num_rows($check_resql);
1613 if ($check_num == 0) {
1614 $db->begin();
1615
1616 if ($nb == 0) {
1617 print '<tr><td colspan="4" class="nowrap"><b>'.$langs->trans('SuppliersInvoices').'</b></td></tr>';
1618 print '<tr><td>fk_paiementfourn</td><td>fk_facturefourn</td><td>'.$langs->trans('Amount').'</td><td>&nbsp;</td></tr>';
1619 }
1620
1621 print '<tr class="oddeven">';
1622 print '<td>'.$select_obj->rowid.'</td><td>'.$select_obj->fk_facture_fourn.'</td><td>'.$select_obj->amount.'</td>';
1623
1624 $insert_sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiementfourn_facturefourn SET ';
1625 $insert_sql .= ' fk_paiementfourn = \''.$select_obj->rowid.'\',';
1626 $insert_sql .= ' fk_facturefourn = \''.$select_obj->fk_facture_fourn.'\',';
1627 $insert_sql .= ' amount = \''.$select_obj->amount.'\'';
1628 $insert_resql = $db->query($insert_sql);
1629
1630 if ($insert_resql) {
1631 $nb++;
1632 print '<td><span class="ok">'.$langs->trans("OK").'</span></td>';
1633 } else {
1634 print '<td><span class="error">Error on insert</span></td>';
1635 $error++;
1636 }
1637 print '</tr>';
1638 }
1639 } else {
1640 $error++;
1641 }
1642 $i++;
1643 }
1644 } else {
1645 $error++;
1646 }
1647
1648 if (!$error) {
1649 if (!$nb) {
1650 print '<tr><td>'.$langs->trans("AlreadyDone").'</td></tr>';
1651 }
1652 $db->commit();
1653
1654 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."paiementfourn DROP COLUMN fk_facture_fourn";
1655 $db->query($sql);
1656 } else {
1657 print '<tr><td>'.$langs->trans("Error").'</td></tr>';
1658 $db->rollback();
1659 }
1660 } else {
1661 print '<tr><td>'.$langs->trans("AlreadyDone").'</td></tr>';
1662 }
1663}
1664
1673function migrate_price_facture($db, $langs, $conf)
1674{
1675 $err = 0;
1676
1677 $tmpmysoc = new Societe($db);
1678 $tmpmysoc->setMysoc($conf);
1679
1680 $db->begin();
1681
1682 print '<tr><td colspan="4">';
1683
1684 print '<br>';
1685 print '<b>'.$langs->trans('MigrationInvoice')."</b><br>\n";
1686
1687 // List of invoice lines not up to date
1688 $sql = "SELECT fd.rowid, fd.qty, fd.subprice, fd.remise_percent, fd.tva_tx as vatrate, fd.total_ttc, fd.info_bits,";
1689 $sql .= " f.rowid as facid, f.remise_percent as remise_percent_global, f.total_ttc as total_ttc_f";
1690 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd, ".MAIN_DB_PREFIX."facture as f";
1691 $sql .= " WHERE fd.fk_facture = f.rowid";
1692 $sql .= " AND (((fd.total_ttc = 0 AND fd.remise_percent != 100) or fd.total_ttc IS NULL) or f.total_ttc IS NULL)";
1693 //print $sql;
1694
1695 dolibarr_install_syslog("upgrade2::migrate_price_facture");
1696 $resql = $db->query($sql);
1697 if ($resql) {
1698 $num = $db->num_rows($resql);
1699 $i = 0;
1700 if ($num) {
1701 while ($i < $num) {
1702 $obj = $db->fetch_object($resql);
1703
1704 $rowid = $obj->rowid;
1705 $qty = $obj->qty;
1706 $pu = $obj->subprice;
1707 $vatrate = $obj->vatrate;
1708 $remise_percent = $obj->remise_percent;
1709 $remise_percent_global = $obj->remise_percent_global;
1710 $total_ttc_f = $obj->total_ttc_f;
1711 $info_bits = $obj->info_bits;
1712
1713 // On met a jour les 3 nouveaux champs
1714 $facligne = new FactureLigne($db);
1715 $facligne->fetch($rowid);
1716
1717 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $facligne->product_type, $tmpmysoc);
1718 $total_ht = $result[0];
1719 $total_tva = $result[1];
1720 $total_ttc = $result[2];
1721
1722 $facligne->total_ht = (float) $total_ht;
1723 $facligne->total_tva = (float) $total_tva;
1724 $facligne->total_ttc = (float) $total_ttc;
1725
1726 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);
1727 print '. ';
1728 $facligne->update_total();
1729
1730
1731 /* On touche a facture mere uniquement si total_ttc = 0 */
1732 if (!$total_ttc_f) {
1733 $facture = new Facture($db);
1734 $facture->id = $obj->facid;
1735
1736 if ($facture->fetch($facture->id) >= 0) {
1737 if ($facture->update_price() > 0) {
1738 //print $facture->id;
1739 } else {
1740 print "Error id=".$facture->id;
1741 $err++;
1742 }
1743 } else {
1744 print "Error #3";
1745 $err++;
1746 }
1747 }
1748 print " ";
1749
1750 $i++;
1751 }
1752 } else {
1753 print $langs->trans("AlreadyDone");
1754 }
1755 $db->free($resql);
1756
1757 $db->commit();
1758 } else {
1759 print "Error #1 ".$db->error();
1760 $err++;
1761
1762 $db->rollback();
1763 }
1764
1765 print '<br>';
1766
1767 print '</td></tr>';
1768}
1769
1778function migrate_price_propal($db, $langs, $conf)
1779{
1780 $tmpmysoc = new Societe($db);
1781 $tmpmysoc->setMysoc($conf);
1782
1783 $db->begin();
1784
1785 print '<tr><td colspan="4">';
1786
1787 print '<br>';
1788 print '<b>'.$langs->trans('MigrationProposal')."</b><br>\n";
1789
1790 // List of proposal lines not up to date
1791 $sql = "SELECT pd.rowid, pd.qty, pd.subprice, pd.remise_percent, pd.tva_tx as vatrate, pd.info_bits,";
1792 $sql .= " p.rowid as propalid, p.remise_percent as remise_percent_global";
1793 $sql .= " FROM ".MAIN_DB_PREFIX."propaldet as pd, ".MAIN_DB_PREFIX."propal as p";
1794 $sql .= " WHERE pd.fk_propal = p.rowid";
1795 $sql .= " AND ((pd.total_ttc = 0 AND pd.remise_percent != 100) or pd.total_ttc IS NULL)";
1796
1797 dolibarr_install_syslog("upgrade2::migrate_price_propal");
1798 $resql = $db->query($sql);
1799 if ($resql) {
1800 $num = $db->num_rows($resql);
1801 $i = 0;
1802 if ($num) {
1803 while ($i < $num) {
1804 $obj = $db->fetch_object($resql);
1805
1806 $rowid = $obj->rowid;
1807 $qty = $obj->qty;
1808 $pu = $obj->subprice;
1809 $vatrate = $obj->vatrate;
1810 $remise_percent = $obj->remise_percent;
1811 $remise_percent_global = $obj->remise_percent_global;
1812 $info_bits = $obj->info_bits;
1813
1814 // On met a jour les 3 nouveaux champs
1815 $propalligne = new PropaleLigne($db);
1816 $propalligne->fetch($rowid);
1817
1818 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $propalligne->product_type, $tmpmysoc);
1819 $total_ht = $result[0];
1820 $total_tva = $result[1];
1821 $total_ttc = $result[2];
1822
1823 $propalligne->total_ht = (float) $total_ht;
1824 $propalligne->total_tva = (float) $total_tva;
1825 $propalligne->total_ttc = (float) $total_ttc;
1826
1827 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);
1828 print '. ';
1829 $propalligne->update_total();
1830
1831 $i++;
1832 }
1833 } else {
1834 print $langs->trans("AlreadyDone");
1835 }
1836
1837 $db->free($resql);
1838
1839 $db->commit();
1840 } else {
1841 print "Error #1 ".$db->error();
1842
1843 $db->rollback();
1844 }
1845
1846 print '<br>';
1847
1848 print '</td></tr>';
1849}
1850
1859function migrate_price_contrat($db, $langs, $conf)
1860{
1861 $db->begin();
1862
1863 $tmpmysoc = new Societe($db);
1864 $tmpmysoc->setMysoc($conf);
1865 if (empty($tmpmysoc->country_id)) {
1866 $tmpmysoc->country_id = 0; // Ti not have this set to '' or will make sql syntax error.
1867 }
1868
1869 print '<tr><td colspan="4">';
1870
1871 print '<br>';
1872 print '<b>'.$langs->trans('MigrationContract')."</b><br>\n";
1873
1874 // List of contract lines not up to date
1875 $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
1876 $sql .= " c.rowid as contratid";
1877 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c";
1878 $sql .= " WHERE cd.fk_contrat = c.rowid";
1879 $sql .= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100 AND cd.subprice > 0) or cd.total_ttc IS NULL)";
1880
1881 dolibarr_install_syslog("upgrade2::migrate_price_contrat");
1882 $resql = $db->query($sql);
1883 if ($resql) {
1884 $num = $db->num_rows($resql);
1885 $i = 0;
1886 if ($num) {
1887 while ($i < $num) {
1888 $obj = $db->fetch_object($resql);
1889
1890 $rowid = $obj->rowid;
1891 $qty = $obj->qty;
1892 $pu = $obj->subprice;
1893 $vatrate = $obj->vatrate;
1894 $remise_percent = $obj->remise_percent;
1895 $info_bits = $obj->info_bits;
1896
1897 // On met a jour les 3 nouveaux champs
1898 $contratligne = new ContratLigne($db);
1899 //$contratligne->fetch($rowid); Non requis car le update_total ne met a jour que chp redefinis
1900 $contratligne->fetch($rowid);
1901
1902 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, 0, 'HT', $info_bits, $contratligne->product_type, $tmpmysoc);
1903 $total_ht = $result[0];
1904 $total_tva = $result[1];
1905 $total_ttc = $result[2];
1906
1907 $contratligne->total_ht = (float) $total_ht;
1908 $contratligne->total_tva = (float) $total_tva;
1909 $contratligne->total_ttc = (float) $total_ttc;
1910
1911 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);
1912 print '. ';
1913 $contratligne->update_total();
1914
1915 $i++;
1916 }
1917 } else {
1918 print $langs->trans("AlreadyDone");
1919 }
1920
1921 $db->free($resql);
1922
1923 $db->commit();
1924 } else {
1925 print "Error #1 ".$db->error();
1926
1927 $db->rollback();
1928 }
1929
1930 print '<br>';
1931
1932 print '</td></tr>';
1933}
1934
1943function migrate_price_commande($db, $langs, $conf)
1944{
1945 $db->begin();
1946
1947 $tmpmysoc = new Societe($db);
1948 $tmpmysoc->setMysoc($conf);
1949
1950 print '<tr><td colspan="4">';
1951
1952 print '<br>';
1953 print '<b>'.$langs->trans('MigrationOrder')."</b><br>\n";
1954
1955 // List of sales orders lines not up to date
1956 $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
1957 $sql .= " c.rowid as commandeid, c.remise_percent as remise_percent_global";
1958 $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."commande as c";
1959 $sql .= " WHERE cd.fk_commande = c.rowid";
1960 $sql .= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)";
1961
1962 dolibarr_install_syslog("upgrade2::migrate_price_commande");
1963 $resql = $db->query($sql);
1964 if ($resql) {
1965 $num = $db->num_rows($resql);
1966 $i = 0;
1967 if ($num) {
1968 while ($i < $num) {
1969 $obj = $db->fetch_object($resql);
1970
1971 $rowid = $obj->rowid;
1972 $qty = $obj->qty;
1973 $pu = $obj->subprice;
1974 $vatrate = $obj->vatrate;
1975 $remise_percent = $obj->remise_percent;
1976 $remise_percent_global = $obj->remise_percent_global;
1977 $info_bits = $obj->info_bits;
1978
1979 // On met a jour les 3 nouveaux champs
1980 $commandeligne = new OrderLine($db);
1981 $commandeligne->fetch($rowid);
1982
1983 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $commandeligne->product_type, $tmpmysoc);
1984 $total_ht = $result[0];
1985 $total_tva = $result[1];
1986 $total_ttc = $result[2];
1987
1988 $commandeligne->total_ht = (float) $total_ht;
1989 $commandeligne->total_tva = (float) $total_tva;
1990 $commandeligne->total_ttc = (float) $total_ttc;
1991
1992 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);
1993 print '. ';
1994 $commandeligne->update_total();
1995
1996 $i++;
1997 }
1998 } else {
1999 print $langs->trans("AlreadyDone");
2000 }
2001
2002 $db->free($resql);
2003
2004 /*
2005 $sql = "DELETE FROM ".MAIN_DB_PREFIX."commandedet";
2006 $sql.= " WHERE price = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0 AND remise_percent = 0";
2007 $resql=$db->query($sql);
2008 if (! $resql)
2009 {
2010 dol_print_error($db);
2011 }
2012 */
2013
2014 $db->commit();
2015 } else {
2016 print "Error #1 ".$db->error();
2017
2018 $db->rollback();
2019 }
2020
2021 print '<br>';
2022
2023 print '</td></tr>';
2024}
2025
2035{
2036 global $mysoc;
2037
2038 $db->begin();
2039
2040 $tmpmysoc = new Societe($db);
2041 $tmpmysoc->setMysoc($conf);
2042
2043 print '<tr><td colspan="4">';
2044
2045 print '<br>';
2046 print '<b>'.$langs->trans('MigrationSupplierOrder')."</b><br>\n";
2047
2048 // List of purchase order lines not up to date
2049 $sql = "SELECT cd.rowid, cd.qty, cd.subprice, cd.remise_percent, cd.tva_tx as vatrate, cd.info_bits,";
2050 $sql .= " c.rowid as commandeid, c.remise_percent as remise_percent_global";
2051 $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd, ".MAIN_DB_PREFIX."commande_fournisseur as c";
2052 $sql .= " WHERE cd.fk_commande = c.rowid";
2053 $sql .= " AND ((cd.total_ttc = 0 AND cd.remise_percent != 100) or cd.total_ttc IS NULL)";
2054
2055 dolibarr_install_syslog("upgrade2::migrate_price_commande_fournisseur");
2056 $resql = $db->query($sql);
2057 if ($resql) {
2058 $num = $db->num_rows($resql);
2059 $i = 0;
2060 if ($num) {
2061 while ($i < $num) {
2062 $obj = $db->fetch_object($resql);
2063
2064 $rowid = $obj->rowid;
2065 $qty = $obj->qty;
2066 $pu = $obj->subprice;
2067 $vatrate = $obj->vatrate;
2068 $remise_percent = $obj->remise_percent;
2069 $remise_percent_global = $obj->remise_percent_global;
2070 $info_bits = $obj->info_bits;
2071
2072 // On met a jour les 3 nouveaux champs
2073 $commandeligne = new CommandeFournisseurLigne($db);
2074 $commandeligne->fetch($rowid);
2075
2076 $result = calcul_price_total($qty, $pu, $remise_percent, $vatrate, 0, 0, $remise_percent_global, 'HT', $info_bits, $commandeligne->product_type, $mysoc);
2077 $total_ht = $result[0];
2078 $total_tva = $result[1];
2079 $total_ttc = $result[2];
2080
2081 $commandeligne->total_ht = (float) $total_ht;
2082 $commandeligne->total_tva = (float) $total_tva;
2083 $commandeligne->total_ttc = (float) $total_ttc;
2084
2085 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);
2086 print '. ';
2087 $commandeligne->update_total();
2088
2089 $i++;
2090 }
2091 } else {
2092 print $langs->trans("AlreadyDone");
2093 }
2094
2095 $db->free($resql);
2096
2097 /*
2098 $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet";
2099 $sql.= " WHERE subprice = 0 and total_ttc = 0 and total_tva = 0 and total_ht = 0";
2100 $resql=$db->query($sql);
2101 if (! $resql)
2102 {
2103 dol_print_error($db);
2104 }
2105 */
2106
2107 $db->commit();
2108 } else {
2109 print "Error #1 ".$db->error();
2110
2111 $db->rollback();
2112 }
2113
2114 print '<br>';
2115
2116 print '</td></tr>';
2117}
2118
2127function migrate_modeles($db, $langs, $conf)
2128{
2129 //print '<br>';
2130 //print '<b>'.$langs->trans('UpdateModelsTable')."</b><br>\n";
2131
2132 dolibarr_install_syslog("upgrade2::migrate_modeles");
2133
2134 if (isModEnabled('invoice')) {
2135 include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
2136 $modellist = ModelePDFFactures::liste_modeles($db);
2137 if (count($modellist) == 0) {
2138 // Aucun model par default.
2139 $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('crabe','invoice')";
2140 $resql = $db->query($sql);
2141 if (!$resql) {
2142 dol_print_error($db);
2143 }
2144 }
2145 }
2146
2147 if (isModEnabled('order')) {
2148 include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
2149 $modellist = ModelePDFCommandes::liste_modeles($db);
2150 if (count($modellist) == 0) {
2151 // Aucun model par default.
2152 $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('einstein','order')";
2153 $resql = $db->query($sql);
2154 if (!$resql) {
2155 dol_print_error($db);
2156 }
2157 }
2158 }
2159
2160 if (isModEnabled("shipping")) {
2161 include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
2162 $modellist = ModelePdfExpedition::liste_modeles($db);
2163 if (count($modellist) == 0) {
2164 // Aucun model par default.
2165 $sql = " insert into ".MAIN_DB_PREFIX."document_model(nom,type) values('rouget','shipping')";
2166 $resql = $db->query($sql);
2167 if (!$resql) {
2168 dol_print_error($db);
2169 }
2170 }
2171 }
2172
2173 //print $langs->trans("AlreadyDone");
2174}
2175
2176
2186{
2187 dolibarr_install_syslog("upgrade2::migrate_commande_expedition");
2188
2189 print '<tr><td colspan="4">';
2190
2191 print '<br>';
2192 print '<b>'.$langs->trans('MigrationShipmentOrderMatching')."</b><br>\n";
2193
2194 $result = $db->DDLDescTable(MAIN_DB_PREFIX."expedition", "fk_commande");
2195 $obj = $db->fetch_object($result);
2196 if ($obj) {
2197 $error = 0;
2198
2199 $db->begin();
2200
2201 $sql = "SELECT e.rowid, e.fk_commande FROM ".MAIN_DB_PREFIX."expedition as e";
2202 $resql = $db->query($sql);
2203 if ($resql) {
2204 $i = 0;
2205 $num = $db->num_rows($resql);
2206
2207 if ($num) {
2208 while ($i < $num) {
2209 $obj = $db->fetch_object($resql);
2210
2211 $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_exp (fk_expedition,fk_commande)";
2212 $sql .= " VALUES (".((int) $obj->rowid).", ".((int) $obj->fk_commande).")";
2213 $resql2 = $db->query($sql);
2214
2215 if (!$resql2) {
2216 $error++;
2217 dol_print_error($db);
2218 }
2219 print '. ';
2220 $i++;
2221 }
2222 }
2223
2224 if ($error == 0) {
2225 $db->commit();
2226 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."expedition DROP COLUMN fk_commande";
2227 print $langs->trans('FieldRenamed')."<br>\n";
2228 $db->query($sql);
2229 } else {
2230 $db->rollback();
2231 }
2232 } else {
2233 dol_print_error($db);
2234 $db->rollback();
2235 }
2236 } else {
2237 print $langs->trans('AlreadyDone')."<br>\n";
2238 }
2239 print '</td></tr>';
2240}
2241
2250function migrate_commande_livraison($db, $langs, $conf)
2251{
2252 dolibarr_install_syslog("upgrade2::migrate_commande_livraison");
2253
2254 print '<tr><td colspan="4">';
2255
2256 print '<br>';
2257 print '<b>'.$langs->trans('MigrationDeliveryOrderMatching')."</b><br>\n";
2258
2259 $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraison", "fk_commande");
2260 $obj = $db->fetch_object($result);
2261 if ($obj) {
2262 $error = 0;
2263
2264 $db->begin();
2265
2266 $sql = "SELECT l.rowid, l.fk_commande,";
2267 $sql .= " c.ref_client, c.date_livraison as delivery_date";
2268 $sql .= " FROM ".MAIN_DB_PREFIX."livraison as l, ".MAIN_DB_PREFIX."commande as c";
2269 $sql .= " WHERE c.rowid = l.fk_commande";
2270 $resql = $db->query($sql);
2271 if ($resql) {
2272 $i = 0;
2273 $num = $db->num_rows($resql);
2274
2275 if ($num) {
2276 while ($i < $num) {
2277 $obj = $db->fetch_object($resql);
2278
2279 $sql = "INSERT INTO ".MAIN_DB_PREFIX."co_liv (fk_livraison,fk_commande)";
2280 $sql .= " VALUES (".((int) $obj->rowid).", ".((int) $obj->fk_commande).")";
2281 $resql2 = $db->query($sql);
2282
2283 if ($resql2) {
2284 $delivery_date = $db->jdate($obj->delivery_date);
2285
2286 $sqlu = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
2287 $sqlu .= " ref_client = '".$db->escape($obj->ref_client)."'";
2288 $sqlu .= ", date_livraison = '".$db->idate($delivery_date)."'";
2289 $sqlu .= " WHERE rowid = ".((int) $obj->rowid);
2290 $resql3 = $db->query($sqlu);
2291 if (!$resql3) {
2292 $error++;
2293 dol_print_error($db);
2294 }
2295 } else {
2296 $error++;
2297 dol_print_error($db);
2298 }
2299 print '. ';
2300 $i++;
2301 }
2302 }
2303
2304 if ($error == 0) {
2305 $db->commit();
2306 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraison DROP COLUMN fk_commande";
2307 print $langs->trans('FieldRenamed')."<br>\n";
2308 $db->query($sql);
2309 } else {
2310 $db->rollback();
2311 }
2312 } else {
2313 dol_print_error($db);
2314 $db->rollback();
2315 }
2316 } else {
2317 print $langs->trans('AlreadyDone')."<br>\n";
2318 }
2319 print '</td></tr>';
2320}
2321
2330function migrate_detail_livraison($db, $langs, $conf)
2331{
2332 dolibarr_install_syslog("upgrade2::migrate_detail_livraison");
2333
2334 print '<tr><td colspan="4">';
2335
2336 print '<br>';
2337 print '<b>'.$langs->trans('MigrationDeliveryDetail')."</b><br>\n";
2338
2339 // This is done if field fk_commande_ligne exists.
2340 // If not this means migration was already done.
2341 $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraisondet", "fk_commande_ligne");
2342 $obj = $db->fetch_object($result);
2343 if ($obj) {
2344 $error = 0;
2345
2346 $db->begin();
2347
2348 $sql = "SELECT cd.rowid, cd.fk_product, cd.description, cd.subprice, cd.total_ht";
2349 $sql .= ", ld.fk_livraison";
2350 $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."livraisondet as ld";
2351 $sql .= " WHERE ld.fk_commande_ligne = cd.rowid";
2352 $resql = $db->query($sql);
2353 if ($resql) {
2354 $i = 0;
2355 $num = $db->num_rows($resql);
2356
2357 if ($num) {
2358 while ($i < $num) {
2359 $obj = $db->fetch_object($resql);
2360
2361 $sql = "UPDATE ".MAIN_DB_PREFIX."livraisondet SET";
2362 $sql .= " fk_product = ".((int) $obj->fk_product);
2363 $sql .= ",description = '".$db->escape($obj->description)."'";
2364 $sql .= ",subprice = ".price2num($obj->subprice);
2365 $sql .= ",total_ht = ".price2num($obj->total_ht);
2366 $sql .= " WHERE fk_commande_ligne = ".((int) $obj->rowid);
2367 $resql2 = $db->query($sql);
2368
2369 if ($resql2) {
2370 $sql = "SELECT total_ht";
2371 $sql .= " FROM ".MAIN_DB_PREFIX."livraison";
2372 $sql .= " WHERE rowid = ".((int) $obj->fk_livraison);
2373 $resql3 = $db->query($sql);
2374
2375 if ($resql3) {
2376 $obju = $db->fetch_object($resql3);
2377 $total_ht = $obju->total_ht + $obj->total_ht;
2378
2379 $sqlu = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
2380 $sqlu .= " total_ht = ".price2num($total_ht, 'MT');
2381 $sqlu .= " WHERE rowid = ".((int) $obj->fk_livraison);
2382 $resql4 = $db->query($sqlu);
2383 if (!$resql4) {
2384 $error++;
2385 dol_print_error($db);
2386 }
2387 } else {
2388 $error++;
2389 dol_print_error($db);
2390 }
2391 } else {
2392 $error++;
2393 dol_print_error($db);
2394 }
2395 print '. ';
2396 $i++;
2397 }
2398 }
2399
2400 if ($error == 0) {
2401 $db->commit();
2402 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraisondet CHANGE fk_commande_ligne fk_origin_line integer";
2403 print $langs->trans('FieldRenamed')."<br>\n";
2404 $db->query($sql);
2405 } else {
2406 $db->rollback();
2407 }
2408 } else {
2409 dol_print_error($db);
2410 $db->rollback();
2411 }
2412 } else {
2413 $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraisondet", "fk_origin_line");
2414 $obj = $db->fetch_object($result);
2415 if (!$obj) {
2416 $sql = "ALTER TABLE ".MAIN_DB_PREFIX."livraisondet ADD COLUMN fk_origin_line integer after fk_livraison";
2417 $db->query($sql);
2418 }
2419 print $langs->trans('AlreadyDone')."<br>\n";
2420 }
2421 print '</td></tr>';
2422}
2423
2432function migrate_stocks($db, $langs, $conf)
2433{
2434 dolibarr_install_syslog("upgrade2::migrate_stocks");
2435
2436 print '<tr><td colspan="4">';
2437
2438 print '<br>';
2439 print '<b>'.$langs->trans('MigrationStockDetail')."</b><br>\n";
2440
2441 $error = 0;
2442
2443 $db->begin();
2444
2445 $sql = "SELECT SUM(reel) as total, fk_product";
2446 $sql .= " FROM ".MAIN_DB_PREFIX."product_stock as ps";
2447 $sql .= " GROUP BY fk_product";
2448 $resql = $db->query($sql);
2449 if ($resql) {
2450 $i = 0;
2451 $num = $db->num_rows($resql);
2452
2453 if ($num) {
2454 while ($i < $num) {
2455 $obj = $db->fetch_object($resql);
2456
2457 $sql = "UPDATE ".MAIN_DB_PREFIX."product SET";
2458 $sql .= " stock = ".price2num($obj->total, 'MS');
2459 $sql .= " WHERE rowid = ".((int) $obj->fk_product);
2460
2461 $resql2 = $db->query($sql);
2462 if ($resql2) {
2463 } else {
2464 $error++;
2465 dol_print_error($db);
2466 }
2467 print '. ';
2468 $i++;
2469 }
2470 }
2471
2472 if ($error == 0) {
2473 $db->commit();
2474 } else {
2475 $db->rollback();
2476 }
2477 } else {
2478 dol_print_error($db);
2479 $db->rollback();
2480 }
2481
2482 print '</td></tr>';
2483}
2484
2494function migrate_menus($db, $langs, $conf)
2495{
2496 dolibarr_install_syslog("upgrade2::migrate_menus");
2497
2498 print '<tr><td colspan="4">';
2499
2500 print '<br>';
2501 print '<b>'.$langs->trans('MigrationMenusDetail')."</b><br>\n";
2502
2503 $error = 0;
2504
2505 if ($db->DDLInfoTable(MAIN_DB_PREFIX."menu_constraint")) {
2506 $db->begin();
2507
2508 $sql = "SELECT m.rowid, mc.action";
2509 $sql .= " FROM ".MAIN_DB_PREFIX."menu_constraint as mc, ".MAIN_DB_PREFIX."menu_const as md, ".MAIN_DB_PREFIX."menu as m";
2510 $sql .= " WHERE md.fk_menu = m.rowid AND md.fk_constraint = mc.rowid";
2511 $sql .= " AND m.enabled = '1'";
2512 $resql = $db->query($sql);
2513 if ($resql) {
2514 $i = 0;
2515 $num = $db->num_rows($resql);
2516 if ($num) {
2517 while ($i < $num) {
2518 $obj = $db->fetch_object($resql);
2519
2520 $sql = "UPDATE ".MAIN_DB_PREFIX."menu SET";
2521 $sql .= " enabled = '".$db->escape($obj->action)."'";
2522 $sql .= " WHERE rowid = ".((int) $obj->rowid);
2523 $sql .= " AND enabled = '1'";
2524
2525 $resql2 = $db->query($sql);
2526 if ($resql2) {
2527 } else {
2528 $error++;
2529 dol_print_error($db);
2530 }
2531 print '. ';
2532 $i++;
2533 }
2534 }
2535
2536 if ($error == 0) {
2537 $db->commit();
2538 } else {
2539 $db->rollback();
2540 }
2541 } else {
2542 dol_print_error($db);
2543 $db->rollback();
2544 }
2545 } else {
2546 print $langs->trans('AlreadyDone')."<br>\n";
2547 }
2548
2549 print '</td></tr>';
2550}
2551
2562{
2563 dolibarr_install_syslog("upgrade2::migrate_commande_deliveryaddress");
2564
2565 print '<tr><td colspan="4">';
2566
2567 print '<br>';
2568 print '<b>'.$langs->trans('MigrationDeliveryAddress')."</b><br>\n";
2569
2570 $error = 0;
2571
2572 if ($db->DDLInfoTable(MAIN_DB_PREFIX."co_exp")) {
2573 $db->begin();
2574
2575 $sql = "SELECT c.fk_adresse_livraison, ce.fk_expedition";
2576 $sql .= " FROM ".MAIN_DB_PREFIX."commande as c";
2577 $sql .= ", ".MAIN_DB_PREFIX."co_exp as ce";
2578 $sql .= " WHERE c.rowid = ce.fk_commande";
2579 $sql .= " AND c.fk_adresse_livraison IS NOT NULL AND c.fk_adresse_livraison != 0";
2580
2581 $resql = $db->query($sql);
2582 if ($resql) {
2583 $i = 0;
2584 $num = $db->num_rows($resql);
2585
2586 if ($num) {
2587 while ($i < $num) {
2588 $obj = $db->fetch_object($resql);
2589
2590 $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
2591 $sql .= " fk_adresse_livraison = '".$db->escape($obj->fk_adresse_livraison)."'";
2592 $sql .= " WHERE rowid = ".((int) $obj->fk_expedition);
2593
2594 $resql2 = $db->query($sql);
2595 if (!$resql2) {
2596 $error++;
2597 dol_print_error($db);
2598 }
2599 print '. ';
2600 $i++;
2601 }
2602 } else {
2603 print $langs->trans('AlreadyDone')."<br>\n";
2604 }
2605
2606 if ($error == 0) {
2607 $db->commit();
2608 } else {
2609 $db->rollback();
2610 }
2611 } else {
2612 dol_print_error($db);
2613 $db->rollback();
2614 }
2615 } else {
2616 print $langs->trans('AlreadyDone')."<br>\n";
2617 }
2618
2619 print '</td></tr>';
2620}
2621
2632{
2633 dolibarr_install_syslog("upgrade2::migrate_restore_missing_links");
2634
2635 if (($db->type == 'mysql' || $db->type == 'mysqli')) {
2636 if (versioncompare($db->getVersionArray(), array(4, 0)) < 0) {
2637 dolibarr_install_syslog("upgrade2::migrate_restore_missing_links Version of database too old to make this migrate action");
2638 return 0;
2639 }
2640 }
2641 print '<tr><td colspan="4">';
2642
2643 print '<br>';
2644 print '<b>'.$langs->trans('MigrationFixData')."</b> (1)<br>\n";
2645
2646 $error = 0;
2647
2648
2649 // Restore missing link for this cross foreign key (link 1 <=> 1). Direction 1.
2650 $table1 = 'facturedet';
2651 $field1 = 'fk_remise_except';
2652 $table2 = 'societe_remise_except';
2653 $field2 = 'fk_facture_line';
2654
2655 $db->begin();
2656
2657 $sql = "SELECT t1.rowid, t1.".$field1." as field";
2658 $sql .= " FROM ".MAIN_DB_PREFIX.$table1." as t1";
2659 $sql .= " WHERE t1.".$field1." IS NOT NULL AND t1.".$field1." NOT IN";
2660 $sql .= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$table2." as t2";
2661 $sql .= " WHERE t1.rowid = t2.".$field2.")";
2662
2663 dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 1");
2664 $resql = $db->query($sql);
2665 if ($resql) {
2666 $i = 0;
2667 $num = $db->num_rows($resql);
2668
2669 if ($num) {
2670 while ($i < $num) {
2671 $obj = $db->fetch_object($resql);
2672
2673 print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.<br>';
2674
2675 $sql = "UPDATE ".MAIN_DB_PREFIX.$db->sanitize($table2)." SET";
2676 $sql .= " ".$db->sanitize($field2)." = '".$db->escape($obj->rowid)."'";
2677 $sql .= " WHERE rowid = ".((int) $obj->field);
2678
2679 $resql2 = $db->query($sql);
2680 if (!$resql2) {
2681 $error++;
2682 dol_print_error($db);
2683 }
2684 //print '. ';
2685 $i++;
2686 }
2687 } else {
2688 print $langs->trans('AlreadyDone')."<br>\n";
2689 }
2690
2691 if ($error == 0) {
2692 $db->commit();
2693 } else {
2694 $db->rollback();
2695 }
2696 } else {
2697 dol_print_error($db);
2698 $db->rollback();
2699 }
2700
2701 print '</td></tr>';
2702
2703
2704 print '<tr><td colspan="4">';
2705
2706 print '<br>';
2707 print '<b>'.$langs->trans('MigrationFixData')."</b> (2)<br>\n";
2708
2709 // Restore missing link for this cross foreign key (link 1 <=> 1). Direction 2.
2710 $table2 = 'facturedet';
2711 $field2 = 'fk_remise_except';
2712 $table1 = 'societe_remise_except';
2713 $field1 = 'fk_facture_line';
2714
2715 $db->begin();
2716
2717 $sql = "SELECT t1.rowid, t1.".$field1." as field";
2718 $sql .= " FROM ".MAIN_DB_PREFIX.$table1." as t1";
2719 $sql .= " WHERE t1.".$field1." IS NOT NULL AND t1.".$field1." NOT IN";
2720 $sql .= " (SELECT t2.rowid FROM ".MAIN_DB_PREFIX.$table2." as t2";
2721 $sql .= " WHERE t1.rowid = t2.".$field2.")";
2722
2723 dolibarr_install_syslog("upgrade2::migrate_restore_missing_links DIRECTION 2");
2724 $resql = $db->query($sql);
2725 if ($resql) {
2726 $i = 0;
2727 $num = $db->num_rows($resql);
2728
2729 if ($num) {
2730 while ($i < $num) {
2731 $obj = $db->fetch_object($resql);
2732
2733 print 'Line '.$obj->rowid.' in '.$table1.' is linked to record '.$obj->field.' in '.$table2.' that has no link to '.$table1.'. We fix this.<br>';
2734
2735 $sql = "UPDATE ".MAIN_DB_PREFIX.$db->sanitize($table2)." SET";
2736 $sql .= " ".$db->sanitize($field2)." = '".$db->escape($obj->rowid)."'";
2737 $sql .= " WHERE rowid = ".((int) $obj->field);
2738
2739 $resql2 = $db->query($sql);
2740 if (!$resql2) {
2741 $error++;
2742 dol_print_error($db);
2743 }
2744 //print '. ';
2745 $i++;
2746 }
2747 } else {
2748 print $langs->trans('AlreadyDone')."<br>\n";
2749 }
2750
2751 if ($error == 0) {
2752 $db->commit();
2753 } else {
2754 $db->rollback();
2755 }
2756 } else {
2757 dol_print_error($db);
2758 $db->rollback();
2759 }
2760
2761 print '</td></tr>';
2762
2763 return ($error ? -1 : 1);
2764}
2765
2774function migrate_project_user_resp($db, $langs, $conf)
2775{
2776 dolibarr_install_syslog("upgrade2::migrate_project_user_resp");
2777
2778 print '<tr><td colspan="4">';
2779
2780 print '<br>';
2781 print '<b>'.$langs->trans('MigrationProjectUserResp')."</b><br>\n";
2782
2783 $result = $db->DDLDescTable(MAIN_DB_PREFIX."projet", "fk_user_resp");
2784 $obj = $db->fetch_object($result);
2785 if ($obj) {
2786 $error = 0;
2787
2788 $db->begin();
2789
2790 $sql = "SELECT rowid, fk_user_resp FROM ".MAIN_DB_PREFIX."projet";
2791 $resql = $db->query($sql);
2792 if ($resql) {
2793 $i = 0;
2794 $num = $db->num_rows($resql);
2795
2796 if ($num) {
2797 while ($i < $num) {
2798 $obj = $db->fetch_object($resql);
2799
2800 $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact (";
2801 $sql2 .= "datecreate";
2802 $sql2 .= ", statut";
2803 $sql2 .= ", element_id";
2804 $sql2 .= ", fk_c_type_contact";
2805 $sql2 .= ", fk_socpeople";
2806 $sql2 .= ") VALUES (";
2807 $sql2 .= "'".$db->idate(dol_now())."'";
2808 $sql2 .= ", '4'";
2809 $sql2 .= ", ".$obj->rowid;
2810 $sql2 .= ", '160'";
2811 $sql2 .= ", ".$obj->fk_user_resp;
2812 $sql2 .= ")";
2813
2814 if ($obj->fk_user_resp > 0) {
2815 $resql2 = $db->query($sql2);
2816 if (!$resql2) {
2817 $error++;
2818 dol_print_error($db);
2819 }
2820 }
2821 print '. ';
2822
2823 $i++;
2824 }
2825 }
2826
2827 if ($error == 0) {
2828 $sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."projet DROP COLUMN fk_user_resp";
2829 if ($db->query($sqlDrop)) {
2830 $db->commit();
2831 } else {
2832 $db->rollback();
2833 }
2834 } else {
2835 $db->rollback();
2836 }
2837 } else {
2838 dol_print_error($db);
2839 $db->rollback();
2840 }
2841 } else {
2842 print $langs->trans('AlreadyDone')."<br>\n";
2843 }
2844 print '</td></tr>';
2845}
2846
2856{
2857 dolibarr_install_syslog("upgrade2::migrate_project_task_actors");
2858
2859 print '<tr><td colspan="4">';
2860
2861 print '<br>';
2862 print '<b>'.$langs->trans('MigrationProjectTaskActors')."</b><br>\n";
2863
2864 if ($db->DDLInfoTable(MAIN_DB_PREFIX."projet_task_actors")) {
2865 $error = 0;
2866
2867 $db->begin();
2868
2869 $sql = "SELECT fk_projet_task as fk_project_task, fk_user FROM ".MAIN_DB_PREFIX."projet_task_actors";
2870 $resql = $db->query($sql);
2871 if ($resql) {
2872 $i = 0;
2873 $num = $db->num_rows($resql);
2874
2875 if ($num) {
2876 while ($i < $num) {
2877 $obj = $db->fetch_object($resql);
2878
2879 $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."element_contact (";
2880 $sql2 .= "datecreate";
2881 $sql2 .= ", statut";
2882 $sql2 .= ", element_id";
2883 $sql2 .= ", fk_c_type_contact";
2884 $sql2 .= ", fk_socpeople";
2885 $sql2 .= ") VALUES (";
2886 $sql2 .= "'".$db->idate(dol_now())."'";
2887 $sql2 .= ", '4'";
2888 $sql2 .= ", ".$obj->fk_project_task;
2889 $sql2 .= ", '180'";
2890 $sql2 .= ", ".$obj->fk_user;
2891 $sql2 .= ")";
2892
2893 $resql2 = $db->query($sql2);
2894
2895 if (!$resql2) {
2896 $error++;
2897 dol_print_error($db);
2898 }
2899 print '. ';
2900 $i++;
2901 }
2902 }
2903
2904 if ($error == 0) {
2905 $sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX."projet_task_actors";
2906 if ($db->query($sqlDrop)) {
2907 $db->commit();
2908 } else {
2909 $db->rollback();
2910 }
2911 } else {
2912 $db->rollback();
2913 }
2914 } else {
2915 dol_print_error($db);
2916 $db->rollback();
2917 }
2918 } else {
2919 print $langs->trans('AlreadyDone')."<br>\n";
2920 }
2921 print '</td></tr>';
2922}
2923
2937function migrate_relationship_tables($db, $langs, $conf, $table, $fk_source, $sourcetype, $fk_target, $targettype)
2938{
2939 print '<tr><td colspan="4">';
2940
2941 print '<br>';
2942 print '<b>'.$langs->trans('MigrationRelationshipTables', MAIN_DB_PREFIX.$table)."</b><br>\n";
2943
2944 $error = 0;
2945
2946 if ($db->DDLInfoTable(MAIN_DB_PREFIX.$table)) {
2947 dolibarr_install_syslog("upgrade2::migrate_relationship_tables table = ".MAIN_DB_PREFIX.$table);
2948
2949 $db->begin();
2950
2951 $sqlSelect = "SELECT ".$fk_source.", ".$fk_target;
2952 $sqlSelect .= " FROM ".MAIN_DB_PREFIX.$table;
2953
2954 $resql = $db->query($sqlSelect);
2955 if ($resql) {
2956 $i = 0;
2957 $num = $db->num_rows($resql);
2958
2959 if ($num) {
2960 while ($i < $num) {
2961 $obj = $db->fetch_object($resql);
2962
2963 $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
2964 $sqlInsert .= "fk_source";
2965 $sqlInsert .= ", sourcetype";
2966 $sqlInsert .= ", fk_target";
2967 $sqlInsert .= ", targettype";
2968 $sqlInsert .= ") VALUES (";
2969 $sqlInsert .= $obj->$fk_source;
2970 $sqlInsert .= ", '".$db->escape($sourcetype)."'";
2971 $sqlInsert .= ", ".$obj->$fk_target;
2972 $sqlInsert .= ", '".$db->escape($targettype)."'";
2973 $sqlInsert .= ")";
2974
2975 $result = $db->query($sqlInsert);
2976 if (!$result) {
2977 $error++;
2978 dol_print_error($db);
2979 }
2980 print '. ';
2981 $i++;
2982 }
2983 } else {
2984 print $langs->trans('AlreadyDone')."<br>\n";
2985 }
2986
2987 if ($error == 0) {
2988 $sqlDrop = "DROP TABLE ".MAIN_DB_PREFIX.$table;
2989 if ($db->query($sqlDrop)) {
2990 $db->commit();
2991 } else {
2992 $db->rollback();
2993 }
2994 } else {
2995 $db->rollback();
2996 }
2997 } else {
2998 dol_print_error($db);
2999 $db->rollback();
3000 }
3001 } else {
3002 print $langs->trans('AlreadyDone')."<br>\n";
3003 }
3004
3005 print '</td></tr>';
3006}
3007
3016function migrate_element_time($db, $langs, $conf)
3017{
3018 dolibarr_install_syslog("upgrade2::migrate_element_time");
3019
3020 print '<tr><td colspan="4">';
3021
3022 print '<br>';
3023 print '<b>'.$langs->trans('MigrationProjectTaskTime')."</b><br>\n";
3024
3025 $error = 0;
3026
3027 $db->begin();
3028
3029 $sql = "SELECT rowid, fk_element, element_duration";
3030 $sql .= " FROM ".MAIN_DB_PREFIX."element_time";
3031 $resql = $db->query($sql);
3032 if ($resql) {
3033 $i = 0;
3034 $num = $db->num_rows($resql);
3035
3036 if ($num) {
3037 $totaltime = array();
3038 $oldtime = 0;
3039
3040 while ($i < $num) {
3041 $obj = $db->fetch_object($resql);
3042
3043 if ($obj->element_duration > 0) {
3044 // convert to second
3045 // only for int time and float time ex: 1.75 for 1h45
3046 list($hour, $min) = explode('.', $obj->element_duration);
3047 $hour = (int) $hour * 60 * 60;
3048 $min = (int) ((float) ('.'.$min)) * 3600;
3049 $newtime = $hour + $min;
3050
3051 $sql2 = "UPDATE ".MAIN_DB_PREFIX."element_time SET";
3052 $sql2 .= " element_duration = ".((int) $newtime);
3053 $sql2 .= " WHERE rowid = ".((int) $obj->rowid);
3054
3055 $resql2 = $db->query($sql2);
3056 if (!$resql2) {
3057 $error++;
3058 dol_print_error($db);
3059 }
3060 print '. ';
3061 $oldtime++;
3062 if (!empty($totaltime[$obj->fk_element])) {
3063 $totaltime[$obj->fk_element] += $newtime;
3064 } else {
3065 $totaltime[$obj->fk_element] = $newtime;
3066 }
3067 } else {
3068 if (!empty($totaltime[$obj->fk_element])) {
3069 $totaltime[$obj->fk_element] += $obj->element_duration;
3070 } else {
3071 $totaltime[$obj->fk_element] = $obj->element_duration;
3072 }
3073 }
3074
3075 $i++;
3076 }
3077
3078 if ($error == 0) {
3079 if ($oldtime > 0) {
3080 foreach ($totaltime as $taskid => $total_duration) {
3081 $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET";
3082 $sql .= " duration_effective = ".((int) $total_duration);
3083 $sql .= " WHERE rowid = ".((int) $taskid);
3084
3085 $resql = $db->query($sql);
3086 if (!$resql) {
3087 $error++;
3088 dol_print_error($db);
3089 }
3090 }
3091 } else {
3092 print $langs->trans('AlreadyDone')."<br>\n";
3093 }
3094 } else {
3095 dol_print_error($db);
3096 }
3097 } else {
3098 print $langs->trans('AlreadyDone')."<br>\n";
3099 }
3100 } else {
3101 dol_print_error($db);
3102 }
3103
3104 if ($error == 0) {
3105 $db->commit();
3106 } else {
3107 $db->rollback();
3108 }
3109
3110 print '</td></tr>';
3111}
3112
3122{
3123 print '<tr><td colspan="4">';
3124
3125 print '<br>';
3126 print '<b>'.$langs->trans('MigrationCustomerOrderShipping')."</b><br>\n";
3127
3128 $error = 0;
3129
3130 $result1 = $db->DDLDescTable(MAIN_DB_PREFIX."expedition", "ref_customer");
3131 $result2 = $db->DDLDescTable(MAIN_DB_PREFIX."expedition", "date_delivery");
3132 $obj1 = $db->fetch_object($result1);
3133 $obj2 = $db->fetch_object($result2);
3134 if (!$obj1 && !$obj2) {
3135 dolibarr_install_syslog("upgrade2::migrate_customerorder_shipping");
3136
3137 $db->begin();
3138
3139 $sqlAdd1 = "ALTER TABLE ".MAIN_DB_PREFIX."expedition ADD COLUMN ref_customer varchar(30) AFTER entity";
3140 $sqlAdd2 = "ALTER TABLE ".MAIN_DB_PREFIX."expedition ADD COLUMN date_delivery date DEFAULT NULL AFTER date_expedition";
3141
3142 if ($db->query($sqlAdd1) && $db->query($sqlAdd2)) {
3143 $sqlSelect = "SELECT e.rowid as shipping_id, c.ref_client, c.date_livraison as delivery_date";
3144 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."expedition as e";
3145 $sqlSelect .= ", ".MAIN_DB_PREFIX."element_element as el";
3146 $sqlSelect .= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON c.rowid = el.fk_source AND el.sourcetype = 'commande'";
3147 $sqlSelect .= " WHERE e.rowid = el.fk_target";
3148 $sqlSelect .= " AND el.targettype = 'shipping'";
3149
3150 $resql = $db->query($sqlSelect);
3151 if ($resql) {
3152 $i = 0;
3153 $num = $db->num_rows($resql);
3154
3155 if ($num) {
3156 while ($i < $num) {
3157 $obj = $db->fetch_object($resql);
3158
3159 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
3160 $sqlUpdate .= " ref_customer = '".$db->escape($obj->ref_client)."'";
3161 $sqlUpdate .= ", date_delivery = '".$db->escape($obj->delivery_date ? $obj->delivery_date : 'null')."'";
3162 $sqlUpdate .= " WHERE rowid = ".((int) $obj->shipping_id);
3163
3164 $result = $db->query($sqlUpdate);
3165 if (!$result) {
3166 $error++;
3167 dol_print_error($db);
3168 }
3169 print '. ';
3170 $i++;
3171 }
3172 } else {
3173 print $langs->trans('AlreadyDone')."<br>\n";
3174 }
3175
3176 if ($error == 0) {
3177 $db->commit();
3178 } else {
3179 dol_print_error($db);
3180 $db->rollback();
3181 }
3182 } else {
3183 dol_print_error($db);
3184 $db->rollback();
3185 }
3186 } else {
3187 dol_print_error($db);
3188 $db->rollback();
3189 }
3190 } else {
3191 print $langs->trans('AlreadyDone')."<br>\n";
3192 }
3193
3194 print '</td></tr>';
3195}
3196
3205function migrate_shipping_delivery($db, $langs, $conf)
3206{
3207 print '<tr><td colspan="4">';
3208
3209 print '<br>';
3210 print '<b>'.$langs->trans('MigrationShippingDelivery')."</b><br>\n";
3211
3212 $error = 0;
3213
3214 $result = $db->DDLDescTable(MAIN_DB_PREFIX."livraison", "fk_expedition");
3215 $obj = $db->fetch_object($result);
3216 if ($obj) {
3217 dolibarr_install_syslog("upgrade2::migrate_shipping_delivery");
3218
3219 $db->begin();
3220
3221 $sqlSelect = "SELECT rowid, fk_expedition";
3222 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."livraison";
3223 $sqlSelect .= " WHERE fk_expedition is not null";
3224
3225 $resql = $db->query($sqlSelect);
3226 if ($resql) {
3227 $i = 0;
3228 $num = $db->num_rows($resql);
3229
3230 if ($num) {
3231 while ($i < $num) {
3232 $obj = $db->fetch_object($resql);
3233
3234 $sqlInsert = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
3235 $sqlInsert .= "fk_source";
3236 $sqlInsert .= ", sourcetype";
3237 $sqlInsert .= ", fk_target";
3238 $sqlInsert .= ", targettype";
3239 $sqlInsert .= ") VALUES (";
3240 $sqlInsert .= $obj->fk_expedition;
3241 $sqlInsert .= ", 'shipping'";
3242 $sqlInsert .= ", ".$obj->rowid;
3243 $sqlInsert .= ", 'delivery'";
3244 $sqlInsert .= ")";
3245
3246 $result = $db->query($sqlInsert);
3247 if ($result) {
3248 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET fk_expedition = NULL";
3249 $sqlUpdate .= " WHERE rowid = ".((int) $obj->rowid);
3250
3251 $result = $db->query($sqlUpdate);
3252 if (!$result) {
3253 $error++;
3254 dol_print_error($db);
3255 }
3256 print '. ';
3257 } else {
3258 $error++;
3259 dol_print_error($db);
3260 }
3261 $i++;
3262 }
3263 } else {
3264 print $langs->trans('AlreadyDone')."<br>\n";
3265 }
3266
3267 if ($error == 0) {
3268 $sqlDelete = "DELETE FROM ".MAIN_DB_PREFIX."element_element WHERE sourcetype = 'commande' AND targettype = 'delivery'";
3269 $db->query($sqlDelete);
3270
3271 $db->commit();
3272
3273 // DDL commands must not be inside a transaction
3274 $sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."livraison DROP COLUMN fk_expedition";
3275 $db->query($sqlDrop);
3276 } else {
3277 dol_print_error($db);
3278 $db->rollback();
3279 }
3280 } else {
3281 dol_print_error($db);
3282 $db->rollback();
3283 }
3284 } else {
3285 print $langs->trans('AlreadyDone')."<br>\n";
3286 }
3287
3288 print '</td></tr>';
3289}
3290
3300function migrate_shipping_delivery2($db, $langs, $conf)
3301{
3302 print '<tr><td colspan="4">';
3303
3304 print '<br>';
3305 print '<b>'.$langs->trans('MigrationShippingDelivery2')."</b><br>\n";
3306
3307 $error = 0;
3308
3309 dolibarr_install_syslog("upgrade2::migrate_shipping_delivery2");
3310
3311 $db->begin();
3312
3313 $sqlSelect = "SELECT l.rowid as delivery_id, e.ref_customer, e.date_delivery";
3314 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."livraison as l,";
3315 $sqlSelect .= " ".MAIN_DB_PREFIX."element_element as el,";
3316 $sqlSelect .= " ".MAIN_DB_PREFIX."expedition as e";
3317 $sqlSelect .= " WHERE l.rowid = el.fk_target";
3318 $sqlSelect .= " AND el.targettype = 'delivery'";
3319 $sqlSelect .= " AND e.rowid = el.fk_source AND el.sourcetype = 'shipping'";
3320 $sqlSelect .= " AND (e.ref_customer IS NOT NULL OR e.date_delivery IS NOT NULL)"; // Useless to process this record if both are null
3321 // Add condition to know if we never migrate this record
3322 $sqlSelect .= " AND (l.ref_customer IS NULL".($db->type != 'pgsql' ? " or l.ref_customer = ''" : "").")";
3323 $sqlSelect .= " AND (l.date_delivery IS NULL".($db->type != 'pgsql' ? " or l.date_delivery = ''" : "").")";
3324
3325 $resql = $db->query($sqlSelect);
3326 if ($resql) {
3327 $i = 0;
3328 $num = $db->num_rows($resql);
3329
3330 if ($num) {
3331 while ($i < $num) {
3332 $obj = $db->fetch_object($resql);
3333
3334 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."livraison SET";
3335 $sqlUpdate .= " ref_customer = '".$db->escape($obj->ref_customer)."',";
3336 $sqlUpdate .= " date_delivery = ".($obj->date_delivery ? "'".$db->escape($obj->date_delivery)."'" : 'null');
3337 $sqlUpdate .= " WHERE rowid = ".((int) $obj->delivery_id);
3338
3339 $result = $db->query($sqlUpdate);
3340 if (!$result) {
3341 $error++;
3342 dol_print_error($db);
3343 }
3344 print '. ';
3345 $i++;
3346 }
3347 } else {
3348 print $langs->trans('AlreadyDone')."<br>\n";
3349 }
3350
3351 if ($error == 0) {
3352 $db->commit();
3353 } else {
3354 dol_print_error($db);
3355 $db->rollback();
3356 }
3357 } else {
3358 dol_print_error($db);
3359 $db->rollback();
3360 }
3361
3362 print '</td></tr>';
3363}
3364
3373function migrate_actioncomm_element($db, $langs, $conf)
3374{
3375 print '<tr><td colspan="4">';
3376
3377 print '<br>';
3378 print '<b>'.$langs->trans('MigrationActioncommElement')."</b><br>\n";
3379
3380 $elements = array(
3381 'propal' => 'propalrowid',
3382 'order' => 'fk_commande',
3383 'invoice' => 'fk_facture',
3384 'contract' => 'fk_contract',
3385 'order_supplier' => 'fk_supplier_order',
3386 'invoice_supplier' => 'fk_supplier_invoice'
3387 );
3388
3389 foreach ($elements as $type => $field) {
3390 $result = $db->DDLDescTable(MAIN_DB_PREFIX."actioncomm", $field);
3391 $obj = $db->fetch_object($result);
3392 if ($obj) {
3393 dolibarr_install_syslog("upgrade2::migrate_actioncomm_element field=".$field);
3394
3395 $db->begin();
3396
3397 $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm SET ";
3398 $sql .= "fk_element = ".$db->sanitize($field).", elementtype = '".$db->escape($type)."'";
3399 $sql .= " WHERE ".$db->sanitize($field)." IS NOT NULL";
3400 $sql .= " AND fk_element IS NULL";
3401 $sql .= " AND elementtype IS NULL";
3402
3403 $resql = $db->query($sql);
3404 if ($resql) {
3405 $db->commit();
3406
3407 // DDL commands must not be inside a transaction
3408 // We will drop at next version because a migrate should be runnable several times if it fails.
3409 //$sqlDrop = "ALTER TABLE ".MAIN_DB_PREFIX."actioncomm DROP COLUMN ".$field;
3410 //$db->query($sqlDrop);
3411 //print '. ';
3412 } else {
3413 dol_print_error($db);
3414 $db->rollback();
3415 }
3416 } else {
3417 print $langs->trans('AlreadyDone')."<br>\n";
3418 }
3419 }
3420
3421 print '</td></tr>';
3422}
3423
3432function migrate_mode_reglement($db, $langs, $conf)
3433{
3434 print '<tr><td colspan="4">';
3435
3436 print '<br>';
3437 print '<b>'.$langs->trans('MigrationPaymentMode')."</b><br>\n";
3438
3439 $elements = array(
3440 'old_id' => array(5, 8, 9, 10, 11),
3441 'new_id' => array(50, 51, 52, 53, 54),
3442 'code' => array('VAD', 'TRA', 'LCR', 'FAC', 'PRO'),
3443 'tables' => array('commande_fournisseur', 'commande', 'facture_rec', 'facture', 'propal')
3444 );
3445 $count = 0;
3446
3447 foreach ($elements['old_id'] as $key => $old_id) {
3448 $error = 0;
3449
3450 dolibarr_install_syslog("upgrade2::migrate_mode_reglement code=".$elements['code'][$key]);
3451
3452 $sqlSelect = "SELECT id";
3453 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."c_paiement";
3454 $sqlSelect .= " WHERE id = ".((int) $old_id);
3455 $sqlSelect .= " AND code = '".$db->escape($elements['code'][$key])."'";
3456
3457 $resql = $db->query($sqlSelect);
3458 if ($resql) {
3459 $num = $db->num_rows($resql);
3460 if ($num) {
3461 $count++;
3462
3463 $db->begin();
3464
3465 $sqla = "UPDATE ".MAIN_DB_PREFIX."paiement SET";
3466 $sqla .= " fk_paiement = ".((int) $elements['new_id'][$key]);
3467 $sqla .= " WHERE fk_paiement = ".((int) $old_id);
3468 $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])."')";
3469 $resqla = $db->query($sqla);
3470
3471 $sql = "UPDATE ".MAIN_DB_PREFIX."c_paiement SET";
3472 $sql .= " id = ".((int) $elements['new_id'][$key]);
3473 $sql .= " WHERE id = ".((int) $old_id);
3474 $sql .= " AND code = '".$db->escape($elements['code'][$key])."'";
3475 $resql = $db->query($sql);
3476
3477 if ($resqla && $resql) {
3478 foreach ($elements['tables'] as $table) {
3479 $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
3480 $sql .= "fk_mode_reglement = ".((int) $elements['new_id'][$key]);
3481 $sql .= " WHERE fk_mode_reglement = ".((int) $old_id);
3482
3483 $resql = $db->query($sql);
3484 if (!$resql) {
3485 dol_print_error($db);
3486 $error++;
3487 }
3488 print '. ';
3489 }
3490
3491 if (!$error) {
3492 $db->commit();
3493 } else {
3494 dol_print_error($db);
3495 $db->rollback();
3496 }
3497 } else {
3498 dol_print_error($db);
3499 $db->rollback();
3500 }
3501 }
3502 }
3503 }
3504
3505 if ($count == 0) {
3506 print $langs->trans('AlreadyDone')."<br>\n";
3507 }
3508
3509
3510 print '</td></tr>';
3511}
3512
3513
3522function migrate_clean_association($db, $langs, $conf)
3523{
3524 $result = $db->DDLDescTable(MAIN_DB_PREFIX."categorie_association");
3525 if ($result) { // result defined for version 3.2 or -
3526 $obj = $db->fetch_object($result);
3527 if ($obj) { // It table categorie_association exists
3528 $couples = array();
3529 $children = array();
3530 $sql = "SELECT fk_categorie_mere, fk_categorie_fille";
3531 $sql .= " FROM ".MAIN_DB_PREFIX."categorie_association";
3532 dolibarr_install_syslog("upgrade: search duplicate");
3533 $resql = $db->query($sql);
3534 if ($resql) {
3535 $num = $db->num_rows($resql);
3536 while ($obj = $db->fetch_object($resql)) {
3537 if (!isset($children[$obj->fk_categorie_fille])) { // Only one record as child (a child has only on parent).
3538 if ($obj->fk_categorie_mere != $obj->fk_categorie_fille) {
3539 $children[$obj->fk_categorie_fille] = 1; // Set record for this child
3540 $couples[$obj->fk_categorie_mere.'_'.$obj->fk_categorie_fille] = array('mere' => $obj->fk_categorie_mere, 'fille' => $obj->fk_categorie_fille);
3541 }
3542 }
3543 }
3544
3545 dolibarr_install_syslog("upgrade: result is num=".$num." count(couples)=".count($couples));
3546
3547 // If there is duplicates couples or child with two parents
3548 if (count($couples) > 0 && $num > count($couples)) {
3549 $error = 0;
3550
3551 $db->begin();
3552
3553 // We delete all
3554 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_association";
3555 dolibarr_install_syslog("upgrade: delete association");
3556 $resqld = $db->query($sql);
3557 if ($resqld) {
3558 // And we insert only each record once
3559 foreach ($couples as $key => $val) {
3560 $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_association(fk_categorie_mere,fk_categorie_fille)";
3561 $sql .= " VALUES(".((int) $val['mere']).", ".((int) $val['fille']).")";
3562 dolibarr_install_syslog("upgrade: insert association");
3563 $resqli = $db->query($sql);
3564 if (!$resqli) {
3565 $error++;
3566 }
3567 }
3568 }
3569
3570 if (!$error) {
3571 print '<tr><td>'.$langs->trans("MigrationCategorieAssociation").'</td>';
3572 print '<td class="right">'.$langs->trans("RemoveDuplicates").' '.$langs->trans("Success").' ('.$num.'=>'.count($couples).')</td></tr>';
3573 $db->commit();
3574 } else {
3575 print '<tr><td>'.$langs->trans("MigrationCategorieAssociation").'</td>';
3576 print '<td class="right">'.$langs->trans("RemoveDuplicates").' '.$langs->trans("Failed").'</td></tr>';
3577 $db->rollback();
3578 }
3579 }
3580 } else {
3581 print '<tr><td>'.$langs->trans("Error").'</td>';
3582 print '<td class="right"><div class="error">'.$db->lasterror().'</div></td></tr>';
3583 }
3584 }
3585 }
3586}
3587
3588
3598{
3599 print '<tr><td colspan="4">';
3600
3601 print '<br>';
3602 print '<b>'.$langs->trans('MigrationCategorieAssociation')."</b><br>\n";
3603
3604 $error = 0;
3605
3606 if ($db->DDLInfoTable(MAIN_DB_PREFIX."categorie_association")) {
3607 dolibarr_install_syslog("upgrade2::migrate_categorie_association");
3608
3609 $db->begin();
3610
3611 $sqlSelect = "SELECT fk_categorie_mere, fk_categorie_fille";
3612 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."categorie_association";
3613
3614 $resql = $db->query($sqlSelect);
3615 if ($resql) {
3616 $i = 0;
3617 $num = $db->num_rows($resql);
3618
3619 if ($num) {
3620 while ($i < $num) {
3621 $obj = $db->fetch_object($resql);
3622
3623 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."categorie SET ";
3624 $sqlUpdate .= "fk_parent = ".((int) $obj->fk_categorie_mere);
3625 $sqlUpdate .= " WHERE rowid = ".((int) $obj->fk_categorie_fille);
3626
3627 $result = $db->query($sqlUpdate);
3628 if (!$result) {
3629 $error++;
3630 dol_print_error($db);
3631 }
3632 print '. ';
3633 $i++;
3634 }
3635 } else {
3636 print $langs->trans('AlreadyDone')."<br>\n";
3637 }
3638
3639 if (!$error) {
3640 $db->commit();
3641 } else {
3642 $db->rollback();
3643 }
3644 } else {
3645 dol_print_error($db);
3646 $db->rollback();
3647 }
3648 } else {
3649 print $langs->trans('AlreadyDone')."<br>\n";
3650 }
3651
3652 print '</td></tr>';
3653}
3654
3663function migrate_event_assignement($db, $langs, $conf)
3664{
3665 print '<tr><td colspan="4">';
3666
3667 print '<br>';
3668 print '<b>'.$langs->trans('MigrationEvents')."</b><br>\n";
3669
3670 $error = 0;
3671
3672 dolibarr_install_syslog("upgrade2::migrate_event_assignement");
3673
3674 $db->begin();
3675
3676 $sqlSelect = "SELECT a.id, a.fk_user_action";
3677 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
3678 $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";
3679 $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')";
3680 $sqlSelect .= " ORDER BY a.id";
3681 //print $sqlSelect;
3682
3683 $resql = $db->query($sqlSelect);
3684 if ($resql) {
3685 $i = 0;
3686 $num = $db->num_rows($resql);
3687
3688 if ($num) {
3689 while ($i < $num) {
3690 $obj = $db->fetch_object($resql);
3691
3692 $sqlUpdate = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element) ";
3693 $sqlUpdate .= "VALUES(".((int) $obj->id).", 'user', ".((int) $obj->fk_user_action).")";
3694
3695 $result = $db->query($sqlUpdate);
3696 if (!$result) {
3697 $error++;
3698 dol_print_error($db);
3699 }
3700 print '. ';
3701 $i++;
3702 }
3703 } else {
3704 print $langs->trans('AlreadyDone')."<br>\n";
3705 }
3706
3707 if (!$error) {
3708 $db->commit();
3709 } else {
3710 $db->rollback();
3711 }
3712 } else {
3713 dol_print_error($db);
3714 $db->rollback();
3715 }
3716
3717
3718 print '</td></tr>';
3719}
3720
3730{
3731 print '<tr><td colspan="4">';
3732
3733 print '<br>';
3734 print '<b>'.$langs->trans('MigrationEventsContact')."</b><br>\n";
3735
3736 $error = 0;
3737
3738 dolibarr_install_syslog("upgrade2::migrate_event_assignement");
3739
3740 $db->begin();
3741
3742 $sqlSelect = "SELECT a.id, a.fk_contact";
3743 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
3744 $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";
3745 $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')";
3746 $sqlSelect .= " ORDER BY a.id";
3747 //print $sqlSelect;
3748
3749 $resql = $db->query($sqlSelect);
3750 if ($resql) {
3751 $i = 0;
3752 $num = $db->num_rows($resql);
3753
3754 if ($num) {
3755 while ($i < $num) {
3756 $obj = $db->fetch_object($resql);
3757
3758 $sqlUpdate = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element) ";
3759 $sqlUpdate .= "VALUES(".((int) $obj->id).", 'socpeople', ".((int) $obj->fk_contact).")";
3760
3761 $result = $db->query($sqlUpdate);
3762 if (!$result) {
3763 $error++;
3764 dol_print_error($db);
3765 }
3766 print '. ';
3767 $i++;
3768 }
3769 } else {
3770 print $langs->trans('AlreadyDone')."<br>\n";
3771 }
3772
3773 if (!$error) {
3774 $db->commit();
3775 } else {
3776 $db->rollback();
3777 }
3778 } else {
3779 dol_print_error($db);
3780 $db->rollback();
3781 }
3782
3783
3784 print '</td></tr>';
3785}
3786
3787
3796function migrate_reset_blocked_log($db, $langs, $conf)
3797{
3798 global $user;
3799
3800 require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php';
3801
3802 print '<tr><td colspan="4">';
3803
3804 print '<br>';
3805 print '<b>'.$langs->trans('MigrationResetBlockedLog')."</b><br>\n";
3806
3807 $error = 0;
3808
3809 dolibarr_install_syslog("upgrade2::migrate_reset_blocked_log");
3810
3811 $db->begin();
3812
3813 $sqlSelect = "SELECT DISTINCT entity";
3814 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."blockedlog";
3815
3816 //print $sqlSelect;
3817
3818 $resql = $db->query($sqlSelect);
3819 if ($resql) {
3820 $i = 0;
3821 $num = $db->num_rows($resql);
3822
3823 if ($num) {
3824 while ($i < $num) {
3825 $obj = $db->fetch_object($resql);
3826
3827 print 'Process entity '.$obj->entity;
3828
3829 $sqlSearch = "SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."blockedlog WHERE action = 'MODULE_SET' and entity = ".((int) $obj->entity);
3830 $resqlSearch = $db->query($sqlSearch);
3831 if ($resqlSearch) {
3832 $objSearch = $db->fetch_object($resqlSearch);
3833 //var_dump($objSearch);
3834 if ($objSearch && $objSearch->nb == 0) {
3835 print ' - Record for entity must be reset...';
3836
3837 $sqlUpdate = "DELETE FROM ".MAIN_DB_PREFIX."blockedlog";
3838 $sqlUpdate .= " WHERE entity = ".((int) $obj->entity);
3839 $resqlUpdate = $db->query($sqlUpdate);
3840 if (!$resqlUpdate) {
3841 $error++;
3842 dol_print_error($db);
3843 } else {
3844 // Add set line
3845 $object = new stdClass();
3846 $object->id = 1;
3847 $object->element = 'module';
3848 $object->ref = 'systemevent';
3849 $object->entity = $obj->entity;
3850 $object->date = dol_now();
3851
3852 $b = new BlockedLog($db);
3853 $b->setObjectData($object, 'MODULE_SET', 0);
3854
3855 $res = $b->create($user);
3856 if ($res <= 0) {
3857 $error++;
3858 }
3859 }
3860 } else {
3861 print ' - '.$langs->trans('AlreadyInV7').'<br>';
3862 }
3863 } else {
3864 dol_print_error($db);
3865 }
3866
3867 $i++;
3868 }
3869 } else {
3870 print $langs->trans('NothingToDo')."<br>\n";
3871 }
3872
3873 if (!$error) {
3874 $db->commit();
3875 } else {
3876 $db->rollback();
3877 }
3878 } else {
3879 dol_print_error($db);
3880 $db->rollback();
3881 }
3882
3883 print '</td></tr>';
3884}
3885
3886
3895function migrate_remise_entity($db, $langs, $conf)
3896{
3897 print '<tr><td colspan="4">';
3898
3899 print '<br>';
3900 print '<b>'.$langs->trans('MigrationRemiseEntity')."</b><br>\n";
3901
3902 $error = 0;
3903
3904 dolibarr_install_syslog("upgrade2::migrate_remise_entity");
3905
3906 $db->begin();
3907
3908 $sqlSelect = "SELECT sr.rowid, s.entity";
3909 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."societe_remise as sr, ".MAIN_DB_PREFIX."societe as s";
3910 $sqlSelect .= " WHERE sr.fk_soc = s.rowid and sr.entity != s.entity";
3911
3912 //print $sqlSelect;
3913
3914 $resql = $db->query($sqlSelect);
3915 if ($resql) {
3916 $i = 0;
3917 $num = $db->num_rows($resql);
3918
3919 if ($num) {
3920 while ($i < $num) {
3921 $obj = $db->fetch_object($resql);
3922
3923 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise SET";
3924 $sqlUpdate .= " entity = ".$obj->entity;
3925 $sqlUpdate .= " WHERE rowid = ".((int) $obj->rowid);
3926
3927 $result = $db->query($sqlUpdate);
3928 if (!$result) {
3929 $error++;
3930 dol_print_error($db);
3931 }
3932
3933 print '. ';
3934 $i++;
3935 }
3936 } else {
3937 print $langs->trans('AlreadyDone')."<br>\n";
3938 }
3939
3940 if (!$error) {
3941 $db->commit();
3942 } else {
3943 $db->rollback();
3944 }
3945 } else {
3946 dol_print_error($db);
3947 $db->rollback();
3948 }
3949
3950 print '</td></tr>';
3951}
3952
3962{
3963 print '<tr><td colspan="4">';
3964
3965 print '<br>';
3966 print '<b>'.$langs->trans('MigrationRemiseExceptEntity')."</b><br>\n";
3967
3968 $error = 0;
3969
3970 dolibarr_install_syslog("upgrade2::migrate_remise_except_entity");
3971
3972 $db->begin();
3973
3974 $sqlSelect = "SELECT sr.rowid, sr.fk_soc, sr.fk_facture_source, sr.fk_facture, sr.fk_facture_line";
3975 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr";
3976 //print $sqlSelect;
3977
3978 $resql = $db->query($sqlSelect);
3979 if ($resql) {
3980 $i = 0;
3981 $num = $db->num_rows($resql);
3982
3983 if ($num) {
3984 while ($i < $num) {
3985 $obj = $db->fetch_object($resql);
3986
3987 if (!empty($obj->fk_facture_source) || !empty($obj->fk_facture)) {
3988 $fk_facture = (!empty($obj->fk_facture_source) ? $obj->fk_facture_source : $obj->fk_facture);
3989
3990 $sqlSelect2 = "SELECT f.entity";
3991 $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."facture as f";
3992 $sqlSelect2 .= " WHERE f.rowid = ".((int) $fk_facture);
3993 } elseif (!empty($obj->fk_facture_line)) {
3994 $sqlSelect2 = "SELECT f.entity";
3995 $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as fd";
3996 $sqlSelect2 .= " WHERE fd.rowid = ".((int) $obj->fk_facture_line);
3997 $sqlSelect2 .= " AND fd.fk_facture = f.rowid";
3998 } else {
3999 $sqlSelect2 = "SELECT s.entity";
4000 $sqlSelect2 .= " FROM ".MAIN_DB_PREFIX."societe as s";
4001 $sqlSelect2 .= " WHERE s.rowid = ".((int) $obj->fk_soc);
4002 }
4003
4004 $resql2 = $db->query($sqlSelect2);
4005 if ($resql2) {
4006 if ($db->num_rows($resql2) > 0) {
4007 $obj2 = $db->fetch_object($resql2);
4008
4009 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except SET";
4010 $sqlUpdate .= " entity = ".((int) $obj2->entity);
4011 $sqlUpdate .= " WHERE rowid = ".((int) $obj->rowid);
4012
4013 $result = $db->query($sqlUpdate);
4014 if (!$result) {
4015 $error++;
4016 dol_print_error($db);
4017 }
4018 }
4019 } else {
4020 $error++;
4021 dol_print_error($db);
4022 }
4023
4024 print '. ';
4025 $i++;
4026 }
4027 } else {
4028 print $langs->trans('AlreadyDone')."<br>\n";
4029 }
4030
4031 if (!$error) {
4032 $db->commit();
4033 } else {
4034 $db->rollback();
4035 }
4036 } else {
4037 dol_print_error($db);
4038 $db->rollback();
4039 }
4040
4041
4042 print '</td></tr>';
4043}
4044
4053function migrate_user_rights_entity($db, $langs, $conf)
4054{
4055 print '<tr><td colspan="4">';
4056
4057 print '<b>'.$langs->trans('MigrationUserRightsEntity')."</b><br>\n";
4058
4059 $error = 0;
4060
4061 dolibarr_install_syslog("upgrade2::migrate_user_rights_entity");
4062
4063 $db->begin();
4064
4065 $sqlSelect = "SELECT u.rowid, u.entity";
4066 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."user as u";
4067 $sqlSelect .= " WHERE u.entity > 1";
4068 //print $sqlSelect;
4069
4070 $resql = $db->query($sqlSelect);
4071 if ($resql) {
4072 $i = 0;
4073 $num = $db->num_rows($resql);
4074
4075 if ($num) {
4076 while ($i < $num) {
4077 $obj = $db->fetch_object($resql);
4078
4079 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."user_rights SET";
4080 $sqlUpdate .= " entity = ".((int) $obj->entity);
4081 $sqlUpdate .= " WHERE fk_user = ".((int) $obj->rowid);
4082
4083 $result = $db->query($sqlUpdate);
4084 if (!$result) {
4085 $error++;
4086 dol_print_error($db);
4087 }
4088
4089 print '. ';
4090 $i++;
4091 }
4092 } else {
4093 print $langs->trans('AlreadyDone')."<br>\n";
4094 }
4095
4096 if (!$error) {
4097 $db->commit();
4098 } else {
4099 $db->rollback();
4100 }
4101 } else {
4102 dol_print_error($db);
4103 $db->rollback();
4104 }
4105
4106
4107 print '</td></tr>';
4108}
4109
4119{
4120 print '<tr><td colspan="4">';
4121
4122 print '<b>'.$langs->trans('MigrationUserGroupRightsEntity')."</b><br>\n";
4123
4124 $error = 0;
4125
4126 dolibarr_install_syslog("upgrade2::migrate_usergroup_rights_entity");
4127
4128 $db->begin();
4129
4130 $sqlSelect = "SELECT u.rowid, u.entity";
4131 $sqlSelect .= " FROM ".MAIN_DB_PREFIX."usergroup as u";
4132 $sqlSelect .= " WHERE u.entity > 1";
4133 //print $sqlSelect;
4134
4135 $resql = $db->query($sqlSelect);
4136 if ($resql) {
4137 $i = 0;
4138 $num = $db->num_rows($resql);
4139
4140 if ($num) {
4141 while ($i < $num) {
4142 $obj = $db->fetch_object($resql);
4143
4144 $sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."usergroup_rights SET";
4145 $sqlUpdate .= " entity = ".((int) $obj->entity);
4146 $sqlUpdate .= " WHERE fk_usergroup = ".((int) $obj->rowid);
4147
4148 $result = $db->query($sqlUpdate);
4149 if (!$result) {
4150 $error++;
4151 dol_print_error($db);
4152 }
4153
4154 print '. ';
4155 $i++;
4156 }
4157 } else {
4158 print $langs->trans('AlreadyDone')."<br>\n";
4159 }
4160
4161 if (!$error) {
4162 $db->commit();
4163 } else {
4164 $db->rollback();
4165 }
4166 } else {
4167 dol_print_error($db);
4168 $db->rollback();
4169 }
4170
4171
4172 print '</td></tr>';
4173}
4174
4185function migrate_rename_directories($db, $langs, $conf, $oldname, $newname)
4186{
4187 dolibarr_install_syslog("upgrade2::migrate_rename_directories");
4188
4189 if (is_dir(DOL_DATA_ROOT.$oldname) && !file_exists(DOL_DATA_ROOT.$newname)) {
4190 dolibarr_install_syslog("upgrade2::migrate_rename_directories move ".DOL_DATA_ROOT.$oldname.' into '.DOL_DATA_ROOT.$newname);
4191 @rename(DOL_DATA_ROOT.$oldname, DOL_DATA_ROOT.$newname);
4192 }
4193}
4194
4195
4204function migrate_delete_old_files($db, $langs, $conf)
4205{
4206 $ret = true;
4207
4208 dolibarr_install_syslog("upgrade2::migrate_delete_old_files");
4209
4210 // List of files to delete
4211 $filetodeletearray = array(
4212 '/core/ajax/ajaxcompanies.php',
4213 '/core/triggers/interface_demo.class.php',
4214 '/core/menus/barre_left/default.php',
4215 '/core/menus/barre_top/default.php',
4216 '/core/modules/modComptabiliteExpert.class.php',
4217 '/core/modules/modCommercial.class.php',
4218 '/core/modules/modProduit.class.php',
4219 '/core/modules/modSkype.class.php',
4220 '/core/modules/modactivite.class.php', // A file from external module that should not be here
4221 '/core/triggers/interface_modWebcalendar_Webcalsynchro.class.php',
4222 '/core/triggers/interface_modCommande_Ecotax.class.php',
4223 '/core/triggers/interface_modCommande_fraisport.class.php',
4224 '/core/triggers/interface_modPropale_PropalWorkflow.class.php',
4225 '/core/triggers/interface_99_modWebhook_WebhookTriggers.class.php',
4226 '/core/triggers/interface_99_modZapier_ZapierTriggers.class.php',
4227 '/core/menus/smartphone/iphone.lib.php',
4228 '/core/menus/smartphone/iphone_backoffice.php',
4229 '/core/menus/smartphone/iphone_frontoffice.php',
4230 '/core/menus/standard/auguria_backoffice.php',
4231 '/core/menus/standard/auguria_frontoffice.php',
4232 '/core/menus/standard/eldy_backoffice.php',
4233 '/core/menus/standard/eldy_frontoffice.php',
4234 '/core/modules/export/export_excel.modules.php',
4235 '/core/modules/export/export_csv.modules.php',
4236 '/core/modules/export/exportcsv.modules.php',
4237 '/core/modules/export/export_excel2007new.modules.php',
4238 '/core/modules/facture/pdf_crabe.modules.php',
4239 '/core/modules/facture/pdf_oursin.modules.php',
4240 '/core/modules/mailings/contacts2.modules.php',
4241 '/core/modules/mailings/contacts3.modules.php',
4242 '/core/modules/mailings/contacts4.modules.php',
4243 '/core/modules/mailings/framboise.modules.php',
4244 '/core/modules/mailings/dolibarr_services_expired.modules.php',
4245 '/core/modules/mailings/peche.modules.php',
4246 '/core/modules/mailings/poire.modules.php',
4247 '/core/modules/mailings/kiwi.modules.php',
4248 '/core/modules/syslog/mod_syslog_chromephp.php',
4249 '/core/modules/syslog/mod_syslog_firephp.php',
4250 '/core/modules/syslog/logHandlerInterface.php',
4251 '/core/boxes/box_members.php',
4252
4253 '/includes/restler/framework/Luracast/Restler/Data/Object.php',
4254 '/includes/nusoap/lib/class.*',
4255 '/phenix/inc/triggers/interface_modPhenix_Phenixsynchro.class.php',
4256 '/webcalendar/inc/triggers/interface_modWebcalendar_webcalsynchro.class.php',
4257
4258 '/api/class/api_generic.class.php',
4259 '/asterisk/cidlookup.php',
4260 '/categories/class/api_category.class.php',
4261 '/categories/class/api_deprecated_category.class.php',
4262 '/compta/facture/class/api_invoice.class.php',
4263 '/commande/class/api_commande.class.php',
4264 '/partnership/class/api_partnership.class.php',
4265 '/product/class/api_product.class.php',
4266 '/recruitment/class/api_recruitment.class.php',
4267 '/societe/class/api_contact.class.php',
4268 '/societe/class/api_thirdparty.class.php',
4269 '/support/online.php',
4270 '/takepos/class/actions_takepos.class.php',
4271 '/user/class/api_user.class.php',
4272
4273 '/install/mysql/tables/llx_c_ticketsup_category.key.sql',
4274 '/install/mysql/tables/llx_c_ticketsup_category.sql',
4275 '/install/mysql/tables/llx_c_ticketsup_severity.key.sql',
4276 '/install/mysql/tables/llx_c_ticketsup_severity.sql',
4277 '/install/mysql/tables/llx_c_ticketsup_type.key.sql',
4278 '/install/mysql/tables/llx_c_ticketsup_type.sql'
4279 );
4280
4281 /*
4282 print '<tr><td colspan="4">';
4283 print '<b>'.$langs->trans('DeleteOldFiles')."</b><br>\n";
4284 print '</td></tr>';
4285 */
4286
4287 foreach ($filetodeletearray as $filetodelete) {
4288 //print '<b>'DOL_DOCUMENT_ROOT.$filetodelete."</b><br>\n";
4289 if (preg_match('/\*/', $filetodelete) || file_exists(DOL_DOCUMENT_ROOT.$filetodelete)) {
4290 //print "Process file ".$filetodelete."\n";
4291 $result = dol_delete_file(DOL_DOCUMENT_ROOT.$filetodelete, 0, (preg_match('/\*/', $filetodelete) ? 1 : 0), 0, null, true, 0);
4292 if (!$result) {
4293 $langs->load("errors");
4294 print '<div class="error">'.$langs->trans("Error").': '.$langs->trans("ErrorFailToDeleteFile", DOL_DOCUMENT_ROOT.$filetodelete);
4295 print ' '.$langs->trans("RemoveItManuallyAndPressF5ToContinue").'</div>';
4296 } else {
4297 //print $langs->trans("FileWasRemoved", $filetodelete).'<br>';
4298 }
4299 }
4300 }
4301
4302 return $ret;
4303}
4304
4313function migrate_delete_old_dir($db, $langs, $conf)
4314{
4315 $ret = true;
4316
4317 dolibarr_install_syslog("upgrade2::migrate_delete_old_dir");
4318
4319 // List of files to delete
4320 $filetodeletearray = array(
4321 DOL_DOCUMENT_ROOT.'/core/modules/facture/terre',
4322 DOL_DOCUMENT_ROOT.'/core/modules/facture/mercure',
4323 );
4324
4325 // On linux, we can also removed old directory with a different case than new directory.
4326 if (!empty($_SERVER["WINDIR"])) {
4327 $filetodeletearray[] = DOL_DOCUMENT_ROOT.'/includes/phpoffice/PhpSpreadsheet';
4328 }
4329
4330 foreach ($filetodeletearray as $filetodelete) {
4331 $result = 1;
4332 if (file_exists($filetodelete)) {
4333 $result = dol_delete_dir_recursive($filetodelete);
4334 }
4335 if (!$result) {
4336 $langs->load("errors");
4337 print '<div class="error">'.$langs->trans("Error").': '.$langs->trans("ErrorFailToDeleteDir", $filetodelete);
4338 print ' '.$langs->trans("RemoveItManuallyAndPressF5ToContinue").'</div>';
4339 }
4340 }
4341
4342 return $ret;
4343}
4344
4345
4358function migrate_reload_modules($db, $langs, $conf, $listofmodule = array(), $force = 0)
4359{
4360 global $user;
4361
4362 if (count($listofmodule) == 0) {
4363 return 0;
4364 }
4365
4366 if (!is_object($user)) {
4367 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4368 $user = new User($db); // To avoid error during migration
4369 }
4370
4371 dolibarr_install_syslog("upgrade2::migrate_reload_modules force=".$force.", listofmodule=".implode(',', array_keys($listofmodule)), LOG_NOTICE);
4372
4373 $reloadactionformodules = array(
4374 'MAIN_MODULE_AGENDA' => array('class' => 'modAgenda', 'remove' => 1),
4375 'MAIN_MODULE_API' => array('class' => 'modApi'),
4376 'MAIN_MODULE_BARCODE' => array('class' => 'modBarcode', 'remove' => 1),
4377 'MAIN_MODULE_BLOCKEDLOG' => array('class' => 'modBlockedLog', 'deleteinsertmenus' => 1),
4378 'MAIN_MODULE_CRON' => array('class' => 'modCron', 'remove' => 1),
4379 'MAIN_MODULE_EXTERNALSITE' => array('class' => 'modExternalSite', 'remove' => 1),
4380 'MAIN_MODULE_SOCIETE' => array('class' => 'modSociete', 'remove' => 1),
4381 'MAIN_MODULE_PRODUIT' => array('class' => 'modProduct'),
4382 'MAIN_MODULE_SERVICE' => array('class' => 'modService'),
4383 'MAIN_MODULE_COMMANDE' => array('class' => 'modCommande'),
4384 'MAIN_MODULE_DON' => array('class' => 'modDon'),
4385 'MAIN_MODULE_FACTURE' => array('class' => 'modFacture'),
4386 'MAIN_MODULE_FICHEINTER' => array('class' => 'modFicheinter'),
4387 'MAIN_MODULE_FOURNISSEUR' => array('class' => 'modFournisseur'),
4388 'MAIN_MODULE_EXPEDITION' => array('class' => 'modExpedition'),
4389 'MAIN_MODULE_EXPENSEREPORT' => array('class' => 'modExpenseReport'),
4390 'MAIN_MODULE_EVENTORGANIZATION' => array('class' => 'modEventOrganization', 'remove' => 1),
4391 'MAIN_MODULE_ECM' => array('class' => 'modECM', 'remove' => 1),
4392 'MAIN_MODULE_HOLIDAY' => array('class' => 'modHoliday', 'remove' => 1),
4393 'MAIN_MODULE_KNOWLEDGEMANAGEMENT' => array('class' => 'modKnowledgeManagement', 'remove' => 1),
4394 'MAIN_MODULE_LOAN' => array('class' => 'modLoan', 'remove' => 1),
4395 'MAIN_MODULE_PAYBOX' => array('class' => 'modPaybox', 'remove' => 1),
4396 'MAIN_MODULE_PROPAL' => array('class' => 'modPropale'),
4397 'MAIN_MODULE_SUPPLIERPROPOSAL' => array('class' => 'modSupplierProposal', 'remove' => 1),
4398 'MAIN_MODULE_OPENSURVEY' => array('class' => 'modOpenSurvey', 'remove' => 1),
4399 'MAIN_MODULE_PRODUCTBATCH' => array('class' => 'modProductBatch', 'remove' => 1),
4400 'MAIN_MODULE_TAKEPOS' => array('class' => 'modTakePos', 'remove' => 1),
4401 'MAIN_MODULE_VARIANTS' => array('class' => 'modVariants', 'remove' => 1),
4402 'MAIN_MODULE_EMAILCOLLECTOR' => array('class' => 'modEmailCollector', 'remove' => 1),
4403 );
4404
4405 foreach ($listofmodule as $moduletoreload => $reloadmode) { // reloadmodule can be 'noboxes', 'newboxdefonly', 'forceactivate'
4406 if (empty($moduletoreload) || (empty($conf->global->$moduletoreload) && !$force)) {
4407 continue; // Discard reload if module not enabled
4408 }
4409
4410 $mod = null;
4411
4412 if (!empty($reloadactionformodules[$moduletoreload])) {
4413 dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate module ".$moduletoreload." with mode ".$reloadmode);
4414
4415 $val = $reloadactionformodules[$moduletoreload];
4416 $classformodule = $val['class'];
4417 $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/'.$classformodule.'.class.php';
4418 if ($res) {
4419 $mod = new $classformodule($db);
4420 if (!empty($val['remove'])) {
4421 $mod->remove('noboxes');
4422 }
4423 if (!empty($val['deleteinsertmenus'])) {
4424 // We only reload menus
4425 $mod->delete_menus();
4426 $mod->insert_menus();
4427 } else {
4428 $mod->init($reloadmode);
4429 }
4430 }
4431 } else { // Other generic cases/modules
4432 $reg = array();
4433 $tmp = preg_match('/MAIN_MODULE_([a-zA-Z0-9]+)/', $moduletoreload, $reg);
4434 if (!empty($reg[1])) {
4435 if (strtoupper($moduletoreload) == $moduletoreload) { // If key is un uppercase
4436 $moduletoreloadshort = ucfirst(strtolower($reg[1]));
4437 } else { // If key is a mix of up and low case
4438 $moduletoreloadshort = $reg[1];
4439 }
4440
4441 dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate module ".$moduletoreloadshort." with mode ".$reloadmode." (generic code)", LOG_NOTICE);
4442
4443 $res = @include_once DOL_DOCUMENT_ROOT.'/core/modules/mod'.$moduletoreloadshort.'.class.php';
4444 if ($res) {
4445 $classname = 'mod'.$moduletoreloadshort;
4446 $mod = new $classname($db);
4447 '@phan-var-force DolibarrModules $mod';
4448
4449 //$mod->remove('noboxes');
4450 $mod->delete_menus(); // We must delete to be sure it is inserted with new values
4451 $mod->init($reloadmode);
4452 } else {
4453 dolibarr_install_syslog('Failed to include '.DOL_DOCUMENT_ROOT.'/core/modules/mod'.$moduletoreloadshort.'.class.php', LOG_ERR);
4454
4455 $res = @dol_include_once(strtolower($moduletoreloadshort).'/core/modules/mod'.$moduletoreloadshort.'.class.php');
4456 if ($res) {
4457 $classname = 'mod'.$moduletoreloadshort;
4458 $mod = new $classname($db);
4459 '@phan-var-force DolibarrModules $mod';
4460 $mod->init($reloadmode);
4461 } else {
4462 dolibarr_install_syslog('Failed to include '.strtolower($moduletoreloadshort).'/core/modules/mod'.$moduletoreloadshort.'.class.php', LOG_ERR);
4463 print "Error, can't find module with name ".$moduletoreload."\n";
4464 return -1;
4465 }
4466 }
4467 } else {
4468 dolibarr_install_syslog("Error, can't find module with name ".$moduletoreload, LOG_ERR);
4469 print "Error, can't find module with name ".$moduletoreload."\n";
4470 return -1;
4471 }
4472 }
4473
4474 if (!empty($mod) && is_object($mod)) {
4475 print '<tr class="trforrunsql"><td colspan="4">';
4476 print '<b>'.$langs->trans('Upgrade').'</b>: ';
4477 print $langs->trans('MigrationReloadModule').' '.$mod->getName(); // We keep getName outside of trans because getName is already encoded/translated
4478 print "<!-- (".$reloadmode.") -->";
4479 print "<br>\n";
4480 print '</td></tr>';
4481 }
4482 }
4483
4484 return 1;
4485}
4486
4487
4488
4497function migrate_reload_menu($db, $langs, $conf)
4498{
4499 global $conf;
4500 dolibarr_install_syslog("upgrade2::migrate_reload_menu");
4501
4502 // Define list of menu handlers to initialize
4503 $listofmenuhandler = array();
4504 if (getDolGlobalString('MAIN_MENU_STANDARD') == 'auguria_menu' || getDolGlobalString('MAIN_MENU_SMARTPHONE') == 'auguria_menu'
4505 || getDolGlobalString('MAIN_MENUFRONT_STANDARD') == 'auguria_menu' || getDolGlobalString('MAIN_MENUFRONT_SMARTPHONE') == 'auguria_menu') {
4506 $listofmenuhandler['auguria'] = 1; // We set here only dynamic menu handlers
4507 }
4508
4509 foreach ($listofmenuhandler as $key => $val) {
4510 print '<tr class="trforrunsql"><td colspan="4">';
4511
4512 //print "x".$key;
4513 print '<br>';
4514 print '<b>'.$langs->trans('Upgrade').'</b>: '.$langs->trans('MenuHandler')." ".$key."<br>\n";
4515
4516 // Load sql ini_menu_handler.sql file
4517 $dir = DOL_DOCUMENT_ROOT."/core/menus/";
4518 $file = 'init_menu_'.$key.'.sql';
4519 if (file_exists($dir.$file)) {
4520 $result = run_sql($dir.$file, 1, 0, 1, $key);
4521 }
4522
4523 print '</td></tr>';
4524 }
4525
4526 return 1;
4527}
4528
4535{
4536 global $conf, $db, $langs, $user;
4537
4538 if (!is_object($user)) {
4539 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4540 $user = new User($db); // To avoid error during migration
4541 }
4542
4543 print '<tr><td colspan="4">';
4544
4545 print '<b>'.$langs->trans('MigrationProductLotPath')."</b><br>\n";
4546
4547 $sql = "SELECT rowid, entity, batch, fk_product from ".MAIN_DB_PREFIX."product_lot";
4548 $resql = $db->query($sql);
4549
4550 if ($resql) {
4551 $modulepart="product_batch";
4552
4553 $lot = new Productlot($db);
4554
4555 while ($obj = $db->fetch_object($resql)) {
4556 $entity = (empty($obj->entity) ? 1 : $obj->entity);
4557 if ($entity > 1) {
4558 $dir = DOL_DATA_ROOT.'/'.$entity.'/'.$conf->productbatch->multidir_output[$entity];
4559 } else {
4560 $dir = $conf->productbatch->multidir_output[$entity];
4561 }
4562
4563 if ($dir) {
4564 $lot->id = $obj->rowid;
4565 $lot->ref = $obj->id; // No ref for the moment
4566 $lot->batch = $obj->batch;
4567 $lot->entity = $obj->entity;
4568 $lot->fk_product = $obj->fk_product;
4569
4570 $savref = $lot->ref;
4571
4572 $lot->ref = $obj->batch;
4573 $origin = $dir . '/' . get_exdir(0, 0, 0, 1, $lot, $modulepart);
4574
4575 $lot->ref = $savref; // So restore the id
4576 $destin = $dir . '/' . get_exdir(0, 0, 0, 1, $lot, $modulepart);
4577
4578 //var_dump($origin.' -> '.$destin.' '.$lot->batch.' dir origin is '.dol_is_dir($origin));exit;
4579
4580 if (dol_is_dir($origin) && !dol_is_dir($destin)) {
4581 dol_move_dir($origin, $destin, 0);
4582 }
4583 }
4584 }
4585 }
4586 print '</td></tr>';
4587
4588 return 1;
4589}
4590
4597{
4598 global $conf, $db, $langs, $user;
4599
4600 print '<tr><td colspan="4">';
4601
4602 print '<b>'.$langs->trans('MigrationUserPhotoPath')."</b><br>\n";
4603
4604 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4605 $fuser = new User($db);
4606 if (!is_object($user)) {
4607 $user = $fuser; // To avoid error during migration
4608 }
4609
4610 $sql = "SELECT rowid as uid, entity from ".MAIN_DB_PREFIX."user"; // Get list of all users
4611 $resql = $db->query($sql);
4612 if ($resql) {
4613 while ($obj = $db->fetch_object($resql)) {
4614 //$fuser->fetch($obj->uid);
4615 $fuser->id = $obj->uid;
4616 $fuser->entity = $obj->entity;
4617
4618 //echo '<hr>'.$fuser->id.' -> '.$fuser->entity;
4619 $entity = (empty($fuser->entity) ? 1 : $fuser->entity);
4620 if ($entity > 1) {
4621 $dir = DOL_DATA_ROOT.'/'.$entity.'/users';
4622 } else {
4623 $dir = $conf->user->multidir_output[$entity]; // $conf->user->multidir_output[] for each entity is construct by the multicompany module
4624 }
4625
4626 if ($dir) {
4627 //print "Process user id ".$fuser->id."<br>\n";
4628 $origin = $dir.'/'.get_exdir($fuser->id, 2, 0, 1, $fuser, 'user'); // Use old behaviour to get x/y path
4629 $destin = $dir.'/'.$fuser->id;
4630
4631 $origin_osencoded = dol_osencode($origin);
4632
4633 dol_mkdir($destin);
4634
4635 //echo '<hr>'.$origin.' -> '.$destin;
4636 if (dol_is_dir($origin)) {
4637 $handle = opendir($origin_osencoded);
4638 if (is_resource($handle)) {
4639 while (($file = readdir($handle)) !== false) {
4640 if ($file == '.' || $file == '..') {
4641 continue;
4642 }
4643
4644 if (dol_is_dir($origin.'/'.$file)) { // it is a dir (like 'thumbs')
4645 $thumbs = opendir($origin_osencoded.'/'.$file);
4646 if (is_resource($thumbs)) {
4647 dol_mkdir($destin.'/'.$file);
4648 while (($thumb = readdir($thumbs)) !== false) {
4649 if (!dol_is_file($destin.'/'.$file.'/'.$thumb)) {
4650 if ($thumb == '.' || $thumb == '..') {
4651 continue;
4652 }
4653
4654 //print $origin.'/'.$file.'/'.$thumb.' -> '.$destin.'/'.$file.'/'.$thumb.'<br>'."\n";
4655 print '.';
4656 dol_copy($origin.'/'.$file.'/'.$thumb, $destin.'/'.$file.'/'.$thumb, '0', 0);
4657 //var_dump('aaa');exit;
4658 }
4659 }
4660 // dol_delete_dir($origin.'/'.$file);
4661 }
4662 } else { // it is a file
4663 if (!dol_is_file($destin.'/'.$file)) {
4664 //print $origin.'/'.$file.' -> '.$destin.'/'.$file.'<br>'."\n";
4665 print '.';
4666 dol_copy($origin.'/'.$file, $destin.'/'.$file, '0', 0);
4667 //var_dump('eee');exit;
4668 }
4669 }
4670 }
4671 }
4672 }
4673 }
4674 }
4675 }
4676
4677 print '</td></tr>';
4678}
4679
4686{
4687 global $db, $langs, $user;
4688
4689 print '<tr><td colspan="4">';
4690
4691 print '<b>'.$langs->trans('MigrationUserPhotoPath')."</b><br>\n";
4692
4693 include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4694 $fuser = new User($db);
4695 if (!is_object($user)) {
4696 $user = $fuser; // To avoid error during migration
4697 }
4698
4699 $sql = "SELECT rowid as uid, entity, photo from ".MAIN_DB_PREFIX."user"; // Get list of all users
4700 $resql = $db->query($sql);
4701 if ($resql) {
4702 while ($obj = $db->fetch_object($resql)) {
4703 //$fuser->fetch($obj->uid);
4704 $fuser->id = $obj->uid;
4705 $fuser->entity = $obj->entity;
4706 $fuser->photo = $obj->photo;
4707
4708 //echo '<hr>'.$fuser->id.' -> '.$fuser->entity;
4709 $entity = (empty($fuser->entity) ? 1 : $fuser->entity);
4710 if ($entity > 1) {
4711 $dir = DOL_DATA_ROOT.'/'.$entity.'/users';
4712 } else {
4713 $dir = DOL_DATA_ROOT.'/users';
4714 }
4715
4716 if ($dir) {
4717 //print "Process user id ".$fuser->id."<br>\n";
4718 $origin = $dir.'/'.$fuser->id;
4719 $destin = $dir.'/'.$fuser->id.'/photos';
4720
4721 $origin_osencoded = dol_osencode($origin);
4722
4723 dol_mkdir($destin);
4724
4725 //echo '<hr>'.$origin.' -> '.$destin;
4726 if (dol_is_dir($origin)) {
4727 $handle = opendir($origin_osencoded);
4728 if (is_resource($handle)) {
4729 while (($file = readdir($handle)) !== false) {
4730 if ($file == '.' || $file == '..' || $file == 'photos') {
4731 continue;
4732 }
4733 if (!empty($fuser->photo) && ($file != $fuser->photo && $file != 'thumbs')) {
4734 continue;
4735 }
4736
4737 if (dol_is_dir($origin.'/'.$file)) { // it is a dir (like 'thumbs')
4738 $thumbs = opendir($origin_osencoded.'/'.$file);
4739 if (is_resource($thumbs)) {
4740 dol_mkdir($destin.'/'.$file);
4741 while (($thumb = readdir($thumbs)) !== false) {
4742 if (!dol_is_file($destin.'/'.$file.'/'.$thumb)) {
4743 if ($thumb == '.' || $thumb == '..') {
4744 continue;
4745 }
4746
4747 //print $origin.'/'.$file.'/'.$thumb.' -> '.$destin.'/'.$file.'/'.$thumb.'<br>'."\n";
4748 print '.';
4749 dol_copy($origin.'/'.$file.'/'.$thumb, $destin.'/'.$file.'/'.$thumb, '0', 0);
4750 }
4751 }
4752 // dol_delete_dir($origin.'/'.$file);
4753 }
4754 } else { // it is a file
4755 if (!dol_is_file($destin.'/'.$file)) {
4756 //print $origin.'/'.$file.' -> '.$destin.'/'.$file.'<br>'."\n";
4757 print '.';
4758 dol_copy($origin.'/'.$file, $destin.'/'.$file, '0', 0);
4759 }
4760 }
4761 }
4762 }
4763 }
4764 }
4765 }
4766 }
4767
4768 print '</td></tr>';
4769}
4770
4771
4772/* A faire egalement: Modif statut paye et fk_facture des factures payes completement
4773
4774On recherche facture incorrecte:
4775select 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
4776having f.total_ttc = sum(pf.amount)
4777
4778On les corrige:
4779update llx_facture set paye=1, fk_statut=2 where close_code is null
4780and rowid in (...)
4781*/
4782
4790{
4791 global $db, $langs;
4792 // skype,twitter,facebook,linkedin,instagram,snapchat,googleplus,youtube,whatsapp
4793 $error = 0;
4794 $db->begin();
4795 print '<tr><td colspan="4">';
4796 $sql = 'SELECT rowid, socialnetworks';
4797 $sql .= ', skype, twitter, facebook, linkedin, instagram, snapchat, googleplus, youtube, whatsapp FROM '.MAIN_DB_PREFIX.'user WHERE';
4798 $sql .= " skype IS NOT NULL OR skype <> ''";
4799 $sql .= " OR twitter IS NOT NULL OR twitter <> ''";
4800 $sql .= " OR facebook IS NOT NULL OR facebook <> ''";
4801 $sql .= " OR linkedin IS NOT NULL OR linkedin <> ''";
4802 $sql .= " OR instagram IS NOT NULL OR instagram <> ''";
4803 $sql .= " OR snapchat IS NOT NULL OR snapchat <> ''";
4804 $sql .= " OR googleplus IS NOT NULL OR googleplus <> ''";
4805 $sql .= " OR youtube IS NOT NULL OR youtube <> ''";
4806 $sql .= " OR whatsapp IS NOT NULL OR whatsapp <> ''";
4807 //print $sql;
4808 $resql = $db->query($sql);
4809 if ($resql) {
4810 while ($obj = $db->fetch_object($resql)) {
4811 $arraysocialnetworks = array();
4812 if (!empty($obj->skype)) {
4813 $arraysocialnetworks['skype'] = $obj->skype;
4814 }
4815 if (!empty($obj->twitter)) {
4816 $arraysocialnetworks['twitter'] = $obj->twitter;
4817 }
4818 if (!empty($obj->facebook)) {
4819 $arraysocialnetworks['facebook'] = $obj->facebook;
4820 }
4821 if (!empty($obj->linkedin)) {
4822 $arraysocialnetworks['linkedin'] = $obj->linkedin;
4823 }
4824 if (!empty($obj->instagram)) {
4825 $arraysocialnetworks['instagram'] = $obj->instagram;
4826 }
4827 if (!empty($obj->snapchat)) {
4828 $arraysocialnetworks['snapchat'] = $obj->snapchat;
4829 }
4830 if (!empty($obj->googleplus)) {
4831 $arraysocialnetworks['googleplus'] = $obj->googleplus;
4832 }
4833 if (!empty($obj->youtube)) {
4834 $arraysocialnetworks['youtube'] = $obj->youtube;
4835 }
4836 if (!empty($obj->whatsapp)) {
4837 $arraysocialnetworks['whatsapp'] = $obj->whatsapp;
4838 }
4839 if ($obj->socialnetworks == '' || is_null($obj->socialnetworks)) {
4840 $obj->socialnetworks = '[]';
4841 }
4842 $socialnetworks = array_merge($arraysocialnetworks, json_decode($obj->socialnetworks, true));
4843 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX."user SET socialnetworks='".$db->escape(json_encode($socialnetworks))."'";
4844 $sqlupd .= ', skype=null';
4845 $sqlupd .= ', twitter=null';
4846 $sqlupd .= ', facebook=null';
4847 $sqlupd .= ', linkedin=null';
4848 $sqlupd .= ', instagram=null';
4849 $sqlupd .= ', snapchat=null';
4850 $sqlupd .= ', googleplus=null';
4851 $sqlupd .= ', youtube=null';
4852 $sqlupd .= ', whatsapp=null';
4853 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
4854 //print $sqlupd."<br>";
4855 $resqlupd = $db->query($sqlupd);
4856 if (!$resqlupd) {
4857 dol_print_error($db);
4858 $error++;
4859 }
4860 }
4861 } else {
4862 $error++;
4863 }
4864 if (!$error) {
4865 $db->commit();
4866 } else {
4867 dol_print_error($db);
4868 $db->rollback();
4869 }
4870 print '<b>'.$langs->trans('MigrationFieldsSocialNetworks', 'Users')."</b><br>\n";
4871 print '</td></tr>';
4872}
4873
4881{
4882 global $db, $langs;
4883
4884 print '<tr><td colspan="4">';
4885 $error = 0;
4886 $db->begin();
4887 print '<tr><td colspan="4">';
4888 $sql = 'SELECT rowid, socialnetworks';
4889 $sql .= ', skype, twitter, facebook, linkedin, instagram, snapchat, googleplus, youtube, whatsapp FROM '.MAIN_DB_PREFIX.'adherent WHERE ';
4890 $sql .= " skype IS NOT NULL OR skype <> ''";
4891 $sql .= " OR twitter IS NOT NULL OR twitter <> ''";
4892 $sql .= " OR facebook IS NOT NULL OR facebook <> ''";
4893 $sql .= " OR linkedin IS NOT NULL OR linkedin <> ''";
4894 $sql .= " OR instagram IS NOT NULL OR instagram <> ''";
4895 $sql .= " OR snapchat IS NOT NULL OR snapchat <> ''";
4896 $sql .= " OR googleplus IS NOT NULL OR googleplus <> ''";
4897 $sql .= " OR youtube IS NOT NULL OR youtube <> ''";
4898 $sql .= " OR whatsapp IS NOT NULL OR whatsapp <> ''";
4899 //print $sql;
4900 $resql = $db->query($sql);
4901 if ($resql) {
4902 while ($obj = $db->fetch_object($resql)) {
4903 $arraysocialnetworks = array();
4904 if (!empty($obj->skype)) {
4905 $arraysocialnetworks['skype'] = $obj->skype;
4906 }
4907 if (!empty($obj->twitter)) {
4908 $arraysocialnetworks['twitter'] = $obj->twitter;
4909 }
4910 if (!empty($obj->facebook)) {
4911 $arraysocialnetworks['facebook'] = $obj->facebook;
4912 }
4913 if (!empty($obj->linkedin)) {
4914 $arraysocialnetworks['linkedin'] = $obj->linkedin;
4915 }
4916 if (!empty($obj->instagram)) {
4917 $arraysocialnetworks['instagram'] = $obj->instagram;
4918 }
4919 if (!empty($obj->snapchat)) {
4920 $arraysocialnetworks['snapchat'] = $obj->snapchat;
4921 }
4922 if (!empty($obj->googleplus)) {
4923 $arraysocialnetworks['googleplus'] = $obj->googleplus;
4924 }
4925 if (!empty($obj->youtube)) {
4926 $arraysocialnetworks['youtube'] = $obj->youtube;
4927 }
4928 if (!empty($obj->whatsapp)) {
4929 $arraysocialnetworks['whatsapp'] = $obj->whatsapp;
4930 }
4931 if ($obj->socialnetworks == '' || is_null($obj->socialnetworks)) {
4932 $obj->socialnetworks = '[]';
4933 }
4934 $socialnetworks = array_merge($arraysocialnetworks, json_decode($obj->socialnetworks, true));
4935 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX."adherent SET socialnetworks='".$db->escape(json_encode($socialnetworks))."'";
4936 $sqlupd .= ', skype=null';
4937 $sqlupd .= ', twitter=null';
4938 $sqlupd .= ', facebook=null';
4939 $sqlupd .= ', linkedin=null';
4940 $sqlupd .= ', instagram=null';
4941 $sqlupd .= ', snapchat=null';
4942 $sqlupd .= ', googleplus=null';
4943 $sqlupd .= ', youtube=null';
4944 $sqlupd .= ', whatsapp=null';
4945 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
4946 //print $sqlupd."<br>";
4947 $resqlupd = $db->query($sqlupd);
4948 if (!$resqlupd) {
4949 dol_print_error($db);
4950 $error++;
4951 }
4952 }
4953 } else {
4954 $error++;
4955 }
4956 if (!$error) {
4957 $db->commit();
4958 } else {
4959 dol_print_error($db);
4960 $db->rollback();
4961 }
4962 print '<b>'.$langs->trans('MigrationFieldsSocialNetworks', 'Members')."</b><br>\n";
4963 print '</td></tr>';
4964}
4965
4973{
4974 global $db, $langs;
4975 // jabberid,skype,twitter,facebook,linkedin,instagram,snapchat,googleplus,youtube,whatsapp
4976 $error = 0;
4977 $db->begin();
4978 print '<tr><td colspan="4">';
4979 $sql = 'SELECT rowid, socialnetworks';
4980 $sql .= ', jabberid, skype, twitter, facebook, linkedin, instagram, snapchat, googleplus, youtube, whatsapp FROM '.MAIN_DB_PREFIX.'socpeople WHERE';
4981 $sql .= " jabberid IS NOT NULL OR jabberid <> ''";
4982 $sql .= " OR skype IS NOT NULL OR skype <> ''";
4983 $sql .= " OR twitter IS NOT NULL OR twitter <> ''";
4984 $sql .= " OR facebook IS NOT NULL OR facebook <> ''";
4985 $sql .= " OR linkedin IS NOT NULL OR linkedin <> ''";
4986 $sql .= " OR instagram IS NOT NULL OR instagram <> ''";
4987 $sql .= " OR snapchat IS NOT NULL OR snapchat <> ''";
4988 $sql .= " OR googleplus IS NOT NULL OR googleplus <> ''";
4989 $sql .= " OR youtube IS NOT NULL OR youtube <> ''";
4990 $sql .= " OR whatsapp IS NOT NULL OR whatsapp <> ''";
4991 //print $sql;
4992 $resql = $db->query($sql);
4993 if ($resql) {
4994 while ($obj = $db->fetch_object($resql)) {
4995 $arraysocialnetworks = array();
4996 if (!empty($obj->jabberid)) {
4997 $arraysocialnetworks['jabber'] = $obj->jabberid;
4998 }
4999 if (!empty($obj->skype)) {
5000 $arraysocialnetworks['skype'] = $obj->skype;
5001 }
5002 if (!empty($obj->twitter)) {
5003 $arraysocialnetworks['twitter'] = $obj->twitter;
5004 }
5005 if (!empty($obj->facebook)) {
5006 $arraysocialnetworks['facebook'] = $obj->facebook;
5007 }
5008 if (!empty($obj->linkedin)) {
5009 $arraysocialnetworks['linkedin'] = $obj->linkedin;
5010 }
5011 if (!empty($obj->instagram)) {
5012 $arraysocialnetworks['instagram'] = $obj->instagram;
5013 }
5014 if (!empty($obj->snapchat)) {
5015 $arraysocialnetworks['snapchat'] = $obj->snapchat;
5016 }
5017 if (!empty($obj->googleplus)) {
5018 $arraysocialnetworks['googleplus'] = $obj->googleplus;
5019 }
5020 if (!empty($obj->youtube)) {
5021 $arraysocialnetworks['youtube'] = $obj->youtube;
5022 }
5023 if (!empty($obj->whatsapp)) {
5024 $arraysocialnetworks['whatsapp'] = $obj->whatsapp;
5025 }
5026 if ($obj->socialnetworks == '' || is_null($obj->socialnetworks)) {
5027 $obj->socialnetworks = '[]';
5028 }
5029 $socialnetworks = array_merge($arraysocialnetworks, json_decode($obj->socialnetworks, true));
5030 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX."socpeople SET socialnetworks='".$db->escape(json_encode($socialnetworks))."'";
5031 $sqlupd .= ', jabberid=null';
5032 $sqlupd .= ', skype=null';
5033 $sqlupd .= ', twitter=null';
5034 $sqlupd .= ', facebook=null';
5035 $sqlupd .= ', linkedin=null';
5036 $sqlupd .= ', instagram=null';
5037 $sqlupd .= ', snapchat=null';
5038 $sqlupd .= ', googleplus=null';
5039 $sqlupd .= ', youtube=null';
5040 $sqlupd .= ', whatsapp=null';
5041 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
5042 //print $sqlupd."<br>";
5043 $resqlupd = $db->query($sqlupd);
5044 if (!$resqlupd) {
5045 dol_print_error($db);
5046 $error++;
5047 }
5048 }
5049 } else {
5050 $error++;
5051 }
5052 if (!$error) {
5053 $db->commit();
5054 } else {
5055 dol_print_error($db);
5056 $db->rollback();
5057 }
5058 print '<b>'.$langs->trans('MigrationFieldsSocialNetworks', 'Contacts')."</b><br>\n";
5059 print '</td></tr>';
5060}
5061
5069{
5070 global $db, $langs;
5071 // skype,twitter,facebook,linkedin,instagram,snapchat,googleplus,youtube,whatsapp
5072 $error = 0;
5073 $db->begin();
5074 print '<tr><td colspan="4">';
5075 $sql = 'SELECT rowid, socialnetworks';
5076 $sql .= ', skype, twitter, facebook, linkedin, instagram, snapchat, googleplus, youtube, whatsapp FROM '.MAIN_DB_PREFIX.'societe WHERE ';
5077 $sql .= " skype IS NOT NULL OR skype <> ''";
5078 $sql .= " OR twitter IS NOT NULL OR twitter <> ''";
5079 $sql .= " OR facebook IS NOT NULL OR facebook <> ''";
5080 $sql .= " OR linkedin IS NOT NULL OR linkedin <> ''";
5081 $sql .= " OR instagram IS NOT NULL OR instagram <> ''";
5082 $sql .= " OR snapchat IS NOT NULL OR snapchat <> ''";
5083 $sql .= " OR googleplus IS NOT NULL OR googleplus <> ''";
5084 $sql .= " OR youtube IS NOT NULL OR youtube <> ''";
5085 $sql .= " OR whatsapp IS NOT NULL OR whatsapp <> ''";
5086 //print $sql;
5087 $resql = $db->query($sql);
5088 if ($resql) {
5089 while ($obj = $db->fetch_object($resql)) {
5090 $arraysocialnetworks = array();
5091 if (!empty($obj->skype)) {
5092 $arraysocialnetworks['skype'] = $obj->skype;
5093 }
5094 if (!empty($obj->twitter)) {
5095 $arraysocialnetworks['twitter'] = $obj->twitter;
5096 }
5097 if (!empty($obj->facebook)) {
5098 $arraysocialnetworks['facebook'] = $obj->facebook;
5099 }
5100 if (!empty($obj->linkedin)) {
5101 $arraysocialnetworks['linkedin'] = $obj->linkedin;
5102 }
5103 if (!empty($obj->instagram)) {
5104 $arraysocialnetworks['instagram'] = $obj->instagram;
5105 }
5106 if (!empty($obj->snapchat)) {
5107 $arraysocialnetworks['snapchat'] = $obj->snapchat;
5108 }
5109 if (!empty($obj->googleplus)) {
5110 $arraysocialnetworks['googleplus'] = $obj->googleplus;
5111 }
5112 if (!empty($obj->youtube)) {
5113 $arraysocialnetworks['youtube'] = $obj->youtube;
5114 }
5115 if (!empty($obj->whatsapp)) {
5116 $arraysocialnetworks['whatsapp'] = $obj->whatsapp;
5117 }
5118 if ($obj->socialnetworks == '' || is_null($obj->socialnetworks)) {
5119 $obj->socialnetworks = '[]';
5120 }
5121 $socialnetworks = array_merge($arraysocialnetworks, json_decode($obj->socialnetworks, true));
5122 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX."societe SET socialnetworks='".$db->escape(json_encode($socialnetworks))."'";
5123 $sqlupd .= ', skype=null';
5124 $sqlupd .= ', twitter=null';
5125 $sqlupd .= ', facebook=null';
5126 $sqlupd .= ', linkedin=null';
5127 $sqlupd .= ', instagram=null';
5128 $sqlupd .= ', snapchat=null';
5129 $sqlupd .= ', googleplus=null';
5130 $sqlupd .= ', youtube=null';
5131 $sqlupd .= ', whatsapp=null';
5132 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
5133 //print $sqlupd."<br>";
5134 $resqlupd = $db->query($sqlupd);
5135 if (!$resqlupd) {
5136 dol_print_error($db);
5137 $error++;
5138 }
5139 }
5140 } else {
5141 $error++;
5142 }
5143 if (!$error) {
5144 $db->commit();
5145 } else {
5146 dol_print_error($db);
5147 $db->rollback();
5148 }
5149 print '<b>'.$langs->trans('MigrationFieldsSocialNetworks', 'Thirdparties')."</b><br>\n";
5150 print '</td></tr>';
5151}
5152
5153
5160function migrate_export_import_profiles($mode = 'export')
5161{
5162 global $db, $langs;
5163
5164 $error = 0;
5165 $resultstring = '';
5166
5167 $db->begin();
5168
5169 print '<tr class="trforrunsql"><td colspan="4">';
5170 $sql = 'SELECT rowid, field';
5171 if ($mode == 'export') {
5172 $sql .= ', filter';
5173 }
5174 $sql .= ' FROM '.MAIN_DB_PREFIX.$mode.'_model WHERE';
5175 $sql .= " type LIKE 'propale_%' OR type LIKE 'commande_%' OR type LIKE 'facture_%'";
5176 //print $sql;
5177 $resql = $db->query($sql);
5178 if ($resql) {
5179 while ($obj = $db->fetch_object($resql)) {
5180 $oldfield = $obj->field;
5181 $newfield = str_replace(array(',f.facnumber', 'f.facnumber,', 'f.total,', 'f.tva,'), array(',f.ref', 'f.ref,', 'f.total_ht,', 'f.total_tva,'), $oldfield);
5182
5183 if ($mode == 'export') {
5184 $oldfilter = $obj->filter;
5185 $newfilter = str_replace(array('f.facnumber=', 'f.total=', 'f.tva='), array('f.ref=', 'f.total_ht=', 'f.total_tva='), $oldfilter);
5186 } else {
5187 $oldfilter = '';
5188 $newfilter = '';
5189 }
5190
5191 if ($oldfield != $newfield || $oldfilter != $newfilter) {
5192 $sqlupd = 'UPDATE '.MAIN_DB_PREFIX.$mode."_model SET field = '".$db->escape($newfield)."'";
5193 if ($mode == 'export') {
5194 $sqlupd .= ", filter = '".$db->escape($newfilter)."'";
5195 }
5196 $sqlupd .= ' WHERE rowid = '.((int) $obj->rowid);
5197 $resultstring .= '<tr class="trforrunsql" style=""><td class="wordbreak" colspan="4">'.$sqlupd."</td></tr>\n";
5198 $resqlupd = $db->query($sqlupd);
5199 if (!$resqlupd) {
5200 dol_print_error($db);
5201 $error++;
5202 }
5203 }
5204 }
5205 } else {
5206 $error++;
5207 }
5208 if (!$error) {
5209 $db->commit();
5210 } else {
5211 dol_print_error($db);
5212 $db->rollback();
5213 }
5214 print '<b>'.$langs->trans('MigrationImportOrExportProfiles', $mode)."</b><br>\n";
5215 print '</td></tr>';
5216
5217 if ($resultstring) {
5218 print $resultstring;
5219 } else {
5220 print '<tr class="trforrunsql" style=""><td class="wordbreak" colspan="4">'.$langs->trans("NothingToDo")."</td></tr>\n";
5221 }
5222}
5223
5230{
5231 global $db, $langs;
5232
5233 $error = 0;
5234 $resultstring = '';
5235
5236 $db->begin();
5237 print '<tr class="trforrunsql"><td colspan="4">';
5238 print '<b>'.$langs->trans('MigrationContractLineRank')."</b><br>\n";
5239
5240 $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";
5241 $sql .= " ORDER BY c.rowid,cd.rowid";
5242
5243 $resql = $db->query($sql);
5244 if ($resql) {
5245 $currentRank = 0;
5246 $current_contract = 0;
5247 while ($obj = $db->fetch_object($resql)) {
5248 if (empty($current_contract) || $current_contract == $obj->cid) {
5249 $currentRank++;
5250 } else {
5251 $currentRank = 1;
5252 }
5253
5254 $sqlUpd = "UPDATE ".$db->prefix()."contratdet SET rang=".(int) $currentRank." WHERE rowid=".(int) $obj->cdid;
5255 $resultstring = '.';
5256 print $resultstring;
5257 $resqlUpd = $db->query($sqlUpd);
5258 if (!$resqlUpd) {
5259 dol_print_error($db);
5260 $error++;
5261 }
5262
5263 $current_contract = $obj->cid;
5264 }
5265 } else {
5266 $error++;
5267 }
5268 if (!$error) {
5269 $db->commit();
5270 } else {
5271 $db->rollback();
5272 }
5273
5274 print '</td></tr>';
5275
5276 if (!$resultstring) {
5277 print '<tr class="trforrunsql" style=""><td class="wordbreak" colspan="4">'.$langs->trans("NothingToDo")."</td></tr>\n";
5278 }
5279}
5280
5287{
5288 global $db, $langs;
5289
5290 $lock = getDolGlobalInt('MIGRATION_FLAG_INVOICE_MODELS_V20');
5291
5292 $firstInstallVersion = getDolGlobalString('MAIN_VERSION_FIRST_INSTALL', DOL_VERSION);
5293 $migrationNeeded = (versioncompare(explode('.', $firstInstallVersion, 3), array(20, 0, -5)) < 0 && !$lock);
5294
5295 print '<tr class="trforrunsql"><td colspan="4">';
5296 print '<b>'.$langs->trans('InvoiceExportModelsMigration')."</b>: \n";
5297
5298 if (! $migrationNeeded) {
5299 print $langs->trans("AlreadyDone");
5300 print '</td></tr>';
5301 dolibarr_set_const($db, 'MIGRATION_FLAG_INVOICE_MODELS_V20', 1, 'chaine', 0, 'To flag the upgrade of invoice template has been set', 0);
5302 return;
5303 }
5304
5305
5306 $db->begin();
5307
5308 $sql1 = "UPDATE ".$db->prefix()."export_model SET type = 'facture_0' WHERE type = 'facture_1'";
5309
5310 $resql1 = $db->query($sql1);
5311
5312 if (! $resql1) {
5313 dol_print_error($db);
5314 $db->rollback();
5315 print '</td></tr>';
5316 return;
5317 }
5318
5319 $modified1 = $db->affected_rows($resql1);
5320
5321 print str_repeat('.', $modified1);
5322
5323 $db->free($resql1);
5324
5325 $sql2 = "UPDATE ".$db->prefix()."export_model SET type = 'facture_1' WHERE type = 'facture_2'";
5326
5327 $resql2 = $db->query($sql2);
5328
5329 if (! $resql2) {
5330 dol_print_error($db);
5331 $db->rollback();
5332 print '</td></tr>';
5333 return;
5334 }
5335
5336 $modified2 = $db->affected_rows($resql2);
5337
5338 print str_repeat('.', $modified2);
5339
5340 $db->free($resql2);
5341
5342 if (empty($modified1 + $modified2)) {
5343 print $langs->trans('NothingToDo');
5344 }
5345
5346 $db->commit();
5347
5348 dolibarr_set_const($db, 'MIGRATION_FLAG_INVOICE_MODELS_V20', 1, 'chaine', 0, 'To flag the upgrade of invoice template has been set', 0);
5349
5350 echo '</td></tr>';
5351}
5352
5360{
5361 global $db, $langs;
5362
5363 $error = 0;
5364 $resultstring = '';
5365 $bookKeepingAddon = '';
5366
5367 // For the moment we set the numbering rule to neon (the rule argon has a lot of critical bugs to fix first).
5368 if (getDolGlobalString('BOOKKEEPING_ADDON') == '') {
5369 dolibarr_set_const($db, 'BOOKKEEPING_ADDON', 'mod_bookkeeping_neon', 'chaine', 0, '', $entity);
5370 $bookKeepingAddon = 'mod_bookkeeping_neon';
5371 }
5372
5373 print '<tr class="trforrunsql"><td colspan="4">';
5374 print '<b>'.$langs->trans('MigrationAccountancyBookkeeping')."</b><br>\n";
5375
5376 // TODO
5377 if ($bookKeepingAddon === 'mod_bookkeeping_argon') {
5378 $db->begin();
5379
5380 $sql = "SELECT DISTINCT YEAR(doc_date) as doc_year, MONTH(doc_date) as doc_month, code_journal, piece_num FROM ".$db->prefix()."accounting_bookkeeping";
5381 $sql .= " WHERE ref IS NULL AND entity = ".((int) $entity);
5382 $sql .= " ORDER BY doc_year, doc_month, code_journal, piece_num";
5383
5384 $resql = $db->query($sql);
5385
5386 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php';
5387 $bookkeeping = new BookKeeping($db);
5388 if ($resql) {
5389 while ($obj = $db->fetch_object($resql)) {
5390 $bookkeeping->doc_date = dol_mktime(0, 0, 0, $obj->doc_month, 1, $obj->doc_year);
5391 $bookkeeping->code_journal = $obj->code_journal;
5392 $ref = $bookkeeping->getNextNumRef();
5393
5394 $sqlUpd = "UPDATE ".$db->prefix()."accounting_bookkeeping SET ref = '".$db->escape($ref)."' WHERE piece_num = '".$db->escape($obj->piece_num)."' AND entity = ".((int) $entity);
5395 $resultstring = '.';
5396 print $resultstring;
5397 $resqlUpd = $db->query($sqlUpd);
5398 if (!$resqlUpd) {
5399 dol_print_error($db);
5400 $error++;
5401 }
5402 }
5403 } else {
5404 $error++;
5405 }
5406
5407 if (!$error) {
5408 $db->commit();
5409 } else {
5410 $db->rollback();
5411 }
5412 }
5413
5414 print '</td></tr>';
5415
5416 if (!$resultstring) {
5417 print '<tr class="trforrunsql" style=""><td class="wordbreak" colspan="4">'.$langs->trans("NothingToDo")."</td></tr>\n";
5418 }
5419}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
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 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.
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_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...
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_now($mode='auto')
Return date for now.
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.
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:538
pFooter($nonext=0, $setuplang='', $jscheckfunction='', $withpleasewait=0, $morehtml='')
Print HTML footer of install pages.
Definition inc.php:631
dolibarr_install_syslog($message, $level=LOG_DEBUG)
Log function for install pages.
Definition inc.php:695
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
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
dol_decode($chain, $key='1')
Decode a base 64 encoded + specific delta change.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.
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...
Definition upgrade2.php:981
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_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:901
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_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_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.