dolibarr 25.0.0-alpha
repair.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
6 * Copyright (C) 2021-2026 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
8 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
9 * Copyright (C) 2024 Vincent de Grandpré <vincent@de-grandpre.quebec>
10 * Copyright (C) 2025 Alexandre Spangaro <alexandre@inovea-conseil.com>
11 * Copyright (C) 2026 Solution Libre SAS <contact@solution-libre.fr>
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 3 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <https://www.gnu.org/licenses/>.
25 */
26
32include_once 'inc.php';
33
53'
54@phan-var-force ?string $dolibarr_main_db_encryption
55@phan-var-force ?string $dolibarr_main_db_cryptkey
56@phan-var-force ?string $dolibarr_main_db_type
57';
58
59if (file_exists($conffile)) {
60 include_once $conffile;
61}
62
63require_once $dolibarr_main_document_root.'/core/lib/admin.lib.php';
64include_once $dolibarr_main_document_root.'/core/lib/images.lib.php';
65require_once $dolibarr_main_document_root.'/core/class/extrafields.class.php';
66require_once $dolibarr_main_document_root.'/core/class/html.form.class.php';
67require_once 'lib/repair.lib.php';
68
69$ok = 0;
70
71
72// This page may be long. We are increasing the time allowed.
73// Only works if not in safe_mode.
74$err = error_reporting();
75error_reporting(0);
76@set_time_limit(120);
77error_reporting($err);
78
79$setuplang = GETPOST("selectlang", 'aZ09', 3) ? GETPOST("selectlang", 'aZ09', 3) : 'auto';
80$langs->setDefaultLang($setuplang);
81
82$langs->loadLangs(array("main", "errors", "admin", "install", "other"));
83
84if ($dolibarr_main_db_type == "mysqli") {
85 $choix = 1;
86}
87if ($dolibarr_main_db_type == "pgsql") {
88 $choix = 2;
89}
90if ($dolibarr_main_db_type == "mssql") {
91 $choix = 3;
92}
93
94
95dolibarr_install_syslog("--- repair: entering upgrade.php page");
96if (!is_object($conf)) {
97 dolibarr_install_syslog("repair: conf file not initialized", LOG_ERR);
98}
99
100
101// This page runs on the install bootstrap, which never sets $user.
102// dol_delete_file() -> EcmFiles::delete(User $user) requires a User,
103// so we force an empty one here, before any action that may need it.
104require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
105
106// The installer does not initialize the session and CSRF token like main.inc.php.
107if (session_status() === PHP_SESSION_NONE) {
108 session_start();
109}
110if (empty($_SESSION['newtoken'])) {
111 $_SESSION['newtoken'] = bin2hex(random_bytes(32));
112}
113$imagerepairactions = array('restore_thirdparties_logos', 'rebuild_product_thumbs');
114$imagerepairaction = '';
115foreach ($imagerepairactions as $imageaction) {
116 if (GETPOSTISSET($imageaction)) {
117 $imagerepairaction = $imageaction;
118 }
119}
120$imagerepairentity = $imagerepairaction !== '' && GETPOSTISSET($imagerepairaction.'_entity') ? GETPOSTINT($imagerepairaction.'_entity') : 1;
121$imagerepairmode = $imagerepairaction !== '' ? GETPOST($imagerepairaction, 'aZ09') : '';
122$imagerepairtoken = GETPOST('token', 'alphanohtml');
123$imagerepairpost = $imagerepairmode === 'confirmed' && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST';
124$ecmrepairbufferlevel = ob_get_level();
125$ecmrepairpost = GETPOST('clean_ecm_files_table', 'aZ09') === 'confirmed' && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST';
126if ($ecmrepairpost || $imagerepairpost) {
127 ob_start(); // Allow a redirect after the installer has rendered its progress output.
128}
129
130
131/*
132 * View
133 */
134
135pHeader($langs->trans("Repair"), "repair", GETPOST('action', 'aZ09'));
136print '<input type="hidden" name="token" value="'.newToken().'">';
138
139// Action to launch the repair script
140$actiondone = 1;
141
142print '<div class="div-table-responsive-no-min">';
143print '<table cellspacing="0" cellpadding="1" class="centpercent">';
144$error = 0;
145
146// If password is encoded, we decode it
147if (preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) {
148 require_once $dolibarr_main_document_root.'/core/lib/security.lib.php';
149 if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) {
150 $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass);
151 $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
152 $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass);
153 } elseif (preg_match('/dolcrypt:/i', $dolibarr_main_db_pass)) {
154 $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
155 $dolibarr_main_db_pass = dolDecrypt($dolibarr_main_db_pass);
156 } else {
157 $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass);
158 }
159}
160
161// $conf is already instancied inside inc.php
162$conf->db->type = $dolibarr_main_db_type;
163$conf->db->host = $dolibarr_main_db_host;
164$conf->db->port = $dolibarr_main_db_port;
165$conf->db->name = $dolibarr_main_db_name;
166$conf->db->user = $dolibarr_main_db_user;
167$conf->db->pass = $dolibarr_main_db_pass;
168
169// For encryption
170$conf->db->dolibarr_main_db_encryption = isset($dolibarr_main_db_encryption) ? $dolibarr_main_db_encryption : 0;
171$conf->db->dolibarr_main_db_cryptkey = isset($dolibarr_main_db_cryptkey) ? $dolibarr_main_db_cryptkey : '';
172
173$db = getDoliDBInstance($conf->db->type, $conf->db->host, (string) $conf->db->user, (string) $conf->db->pass, (string) $conf->db->name, (int) $conf->db->port);
174$user = new User($db);
175
176$form = new Form($db);
177
178if ($db->connected) {
179 print '<tr><td class="nowrap">';
180 print $langs->trans("ServerConnection")." : ".$dolibarr_main_db_host.'</td><td class="right">'.$langs->trans("OK")."</td></tr>";
181 dolibarr_install_syslog("repair: ".$langs->transnoentities("ServerConnection").": ".$dolibarr_main_db_host.$langs->transnoentities("OK"));
182 $ok = 1;
183} else {
184 print "<tr><td>".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name).'</td><td class="right">'.$langs->transnoentities("Error")."</td></tr>";
185 dolibarr_install_syslog("repair: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name));
186 $ok = 0;
187}
188
189if ($ok) {
190 if ($db->database_selected) {
191 print '<tr><td class="nowrap">';
192 print $langs->trans("DatabaseConnection")." : ".$dolibarr_main_db_name.'</td><td class="right">'.$langs->trans("OK")."</td></tr>";
193 dolibarr_install_syslog("repair: database connection successful: ".$dolibarr_main_db_name);
194 $ok = 1;
195 } else {
196 print "<tr><td>".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name).'</td><td class="right">'.$langs->trans("Error")."</td></tr>";
197 dolibarr_install_syslog("repair: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name));
198 $ok = 0;
199 }
200}
201
202// Show database version
203if ($ok) {
204 $version = $db->getVersion();
205 $versionarray = $db->getVersionArray();
206 print '<tr><td>'.$langs->trans("ServerVersion").'</td>';
207 print '<td class="right">'.$version.'</td></tr>';
208 dolibarr_install_syslog("repair: ".$langs->transnoentities("ServerVersion").": ".$version);
209 //print '<td class="right">'.join('.',$versionarray).'</td></tr>';
210}
211
212print '</table>';
213print '</div>';
214
215print '<br>';
216
217
218$conf->setValues($db);
219// Reset forced setup after the setValues
220if (defined('SYSLOG_FILE')) {
221 $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
222}
223$conf->global->MAIN_ENABLE_LOG_TO_HTML = 1;
224
225// Maintenance runs under the installer lock, without an authenticated application user.
226$ecmrepairentities = array(1 => $langs->trans('Entity').' 1');
227if (isModEnabled('multicompany')) {
228 $resql = $db->query("SELECT rowid, label FROM ".$db->prefix()."entity ORDER BY rowid");
229 if ($resql) {
230 while (is_object($obj = $db->fetch_object($resql))) {
231 $ecmrepairentities[(int) $obj->rowid] = dol_html_entity_decode($obj->label, 0);
232 }
233 $db->free($resql);
234 }
235}
236$ecmrepairentity = GETPOSTISSET('ecm_entity') ? GETPOSTINT('ecm_entity') : 1;
237
238print '<div class="info" style="padding-top: 10px">';
239print 'Select a link "test" or "confirmed" to launch a reparation on the chosen option...';
240print '</div>';
241print '<br>';
242
243print '<div class="div-table-responsive-no-min">';
244print '<table class="liste centpercent" style="border: 1px solid #ccc">';
245print '<tr>';
246print '<th></th>';
247print '<th></th>';
248print '<th>Launch test</th>';
249print '<th>Launch confirmed</th>';
250print '</tr>';
251
252$warning_using_utf8mb4 = '';
253if ($dolibarr_main_db_character_set != 'utf8mb4') {
254 $warning_using_utf8mb4 = '<img src="../theme/eldy/img/warning.png" class="pictofortooltip valignmiddle" title="If you switch to utf8mb4, you must also check the value for $dolibarr_main_db_character_set and $dolibarr_main_db_collation into conf/conf.php file.">';
255}
256
257$sections = [
258 'Miscellaneous' => [
259 [
260 'name' => 'standard',
261 'info' => 'Miscellaneous fixes'
262 ]
263 ],
264 'Modules' => [
265 [
266 'name' => 'force_disable_of_modules_not_found',
267 'info' => 'Disable modules not found'
268 ]
269 ],
270 'Files' => [
271 [
272 'name' => 'restore_thirdparties_logos',
273 'info' => 'Restore logos for thirdparties'
274 ],
275 [
276 'name' => 'restore_user_pictures',
277 'info' => 'Restore user pictures'
278 ],
279 [
280 'name' => 'rebuild_product_thumbs',
281 'info' => 'Rebuild product thumbnails'
282 ],
283 [
284 'name' => 'repair_mailing_path',
285 'info' => 'Repair path of mailing files',
286 'tooltip' => 'Should be applied when using emailing module with > 99 mailings. In that case, please also set MAILING_USE_NEW_PATH_FOR_FILES.'
287 ]
288 ],
289 'Clean tables and data' => [
290 [
291 'name' => 'clean_linked_elements',
292 'info' => 'Clean linked elements'
293 ],
294 [
295 'name' => 'clean_menus',
296 'info' => 'Clean menus'
297 ],
298 [
299 'name' => 'clean_orphelin_dir',
300 'info' => 'Clean orphan directories'
301 ],
302 [
303 'name' => 'clean_product_stock_batch',
304 'info' => 'Clean product stock batch'
305 ],
306 [
307 'name' => 'clean_perm_table',
308 'info' => 'Clean permissions table'
309 ],
310 [
311 'name' => 'clean_ecm_files_table',
312 'info' => 'Clean ECM files table'
313 ],
314 [
315 'name' => 'repair_link_dispatch_lines_supplier_order_lines',
316 'info' => 'Repair link between dispatch lines and supplier order lines'
317 ]
318 ],
319 'Init empty data' => [
320 [
321 'name' => 'set_empty_time_spent_amount',
322 'info' => 'Init empty time spent amount'
323 ]
324 ],
325 'Structure' => [
326 [
327 'name' => 'force_utf8_on_tables',
328 'info' => 'Force utf8 + row=dynamic, for mysql/mariadb only'
329 ],
330 [
331 'name' => 'force_utf8mb4_on_tables',
332 'info' => 'Force utf8mb4 + row=dynamic, for mysql/mariadb only' . $warning_using_utf8mb4
333 ],
334 [
335 'name' => 'force_collation_from_conf_on_tables',
336 'info' => 'Force '.$conf->db->character_set.'/'.$conf->db->dolibarr_main_db_collation.' + row=dynamic, for mysql/mariadb only'
337 ]
338 ]
339];
340
341if ($db->type == 'pgsql') {
342 $sections['Rebuild sequence'] = [
343 [
344 'name' => 'rebuild_sequences',
345 'info' => 'For postgresql only'
346 ]
347 ];
348}
349
350if ($imagerepairaction !== '') {
351 $imagevalid = in_array($imagerepairmode, array('test', 'confirmed'), true) && $imagerepairentity > 0 && isset($ecmrepairentities[$imagerepairentity]);
352 foreach ($sections as $options) {
353 foreach ($options as $opt) {
354 if ($opt['name'] !== $imagerepairaction && GETPOSTISSET($opt['name'])) {
355 $imagevalid = false; // Do not run another repair under the selected image entity's configuration.
356 }
357 }
358 }
359 if (!$imagevalid) {
360 $ok = 0;
361 print '<tr><td colspan="4" class="error">'.$langs->trans('ErrorWrongParameters').'</td></tr>';
362 } elseif ($imagerepairmode === 'confirmed' && (!$imagerepairpost || !is_string($imagerepairtoken) || !hash_equals(newToken(), $imagerepairtoken))) {
363 $ok = 0;
364 print '<tr><td colspan="4" class="error">'.$langs->trans('RepairImagesInvalidToken').'</td></tr>';
365 } elseif ($ok) {
366 // Image paths and legacy photo settings need the selected entity's native configuration.
367 if ($conf->setEntityValues($db, $imagerepairentity) < 0) {
368 $ok = 0;
369 dol_print_error($db);
370 } elseif ($imagerepairentity > 1 && !isModEnabled('multicompany')) {
371 $ok = 0;
372 print '<tr><td colspan="4" class="error">'.$langs->trans('RepairImagesDirectoryUnavailable').'</td></tr>';
373 }
374 if (defined('SYSLOG_FILE')) {
375 $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
376 }
377 $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1;
378 }
379}
380
381$conf->use_javascript_ajax = 1;
382
383foreach ($sections as $section => $options) {
384 print '<tr style="background:#f4f4f4;font-weight:bold"><td colspan="5">'.$section.'</td></tr>';
385 foreach ($options as $opt) {
386 $option = $opt['name'];
387 $info = $opt['info'];
388 $tooltip = empty($opt['tooltip']) ? '' : $opt['tooltip'];
389 $value = GETPOST($option, 'alpha') ? GETPOST($option, 'alpha') : 'undefined';
390 // Generate links with the right option and value
391 $url_test = $_SERVER['PHP_SELF'].'?'.$option.'=test#pleasebepatient';
392 $url_confirmed = $_SERVER['PHP_SELF'].'?'.$option.'=confirmed#pleasebepatient';
393 print '<tr>';
394 print '<td>' . $option . '</td>';
395 print '<td>';
396 if ($tooltip) {
397 print $form->textwithpicto($info, $tooltip);
398 } else {
399 print $info;
400 }
401 if ($option == 'clean_ecm_files_table') {
402 print '<br><label for="ecm_entity">'.$langs->trans('RepairEcmEntity').'</label> ';
403 print '<link rel="stylesheet" href="../public/includes/jquery/plugins/select2/dist/css/select2.css">';
404 print '<script src="../public/includes/jquery/plugins/select2/dist/js/select2.full.min.js"></script>';
405 print $form->selectarray('ecm_entity', $ecmrepairentities, $ecmrepairentity, 0, 0, 0, 'style="width: 220px"', 0, 0, 0, '', 'minwidth150');
406 }
407 if (in_array($option, $imagerepairactions, true)) {
408 print '<br><label for="'.$option.'_entity">'.$langs->trans('RepairImagesEntity').'</label> ';
409 $imageentity = GETPOSTISSET($option.'_entity') ? GETPOSTINT($option.'_entity') : 1;
410 print $form->selectarray($option.'_entity', $ecmrepairentities, $imageentity, 0, 0, 0, 'style="width: 220px"', 0, 0, 0, '', 'minwidth150');
411 }
412 print '</td>';
413 if ($option == 'clean_ecm_files_table' || in_array($option, $imagerepairactions, true)) {
414 print '<td class="center"><button class="button" type="submit" name="'.$option.'" value="test">'.$langs->trans('Test').'</button></td>';
415 print '<td class="center"><button class="button" type="submit" name="'.$option.'" value="confirmed">'.$langs->trans('Repair').'</button></td>';
416 } else {
417 print '<td class="center"><a href="'.$url_test.'" title="Launch test on option '.$option.'">test</a>'.($value == 'test' ? ' (launched)' : '').'</td>';
418 print '<td class="center"><a href="'.$url_confirmed.'" title="Launch repair on option '.$option.'">repair</a>'.($value == 'confirmed' ? ' (launched)' : '').'</td>';
419 }
420 print '</tr>';
421 }
422}
423print '</table>';
424print '</div>';
425
426
427print '<br id="sectionresult">';
428print '<br>';
429
430
431/* Start action here */
432$oneoptionset = 0;
433$oneoptionset = (GETPOST('standard', 'alpha') || GETPOST('restore_thirdparties_logos', 'alpha') || GETPOST('clean_linked_elements', 'alpha') || GETPOST('clean_menus', 'alpha')
434 || GETPOST('clean_orphelin_dir', 'alpha') || GETPOST('clean_product_stock_batch', 'alpha') || GETPOST('set_empty_time_spent_amount', 'alpha') || GETPOST('rebuild_product_thumbs', 'alpha')
435 || GETPOST('clean_perm_table', 'alpha') || GETPOST('clean_ecm_files_table', 'alpha')
436 || GETPOST('force_disable_of_modules_not_found', 'alpha')
437 || GETPOST('force_utf8_on_tables', 'alpha') || GETPOST('force_utf8mb4_on_tables', 'alpha') || GETPOST('force_collation_from_conf_on_tables', 'alpha')
438 || GETPOST('rebuild_sequences', 'alpha') || GETPOST('recalculateinvoicetotal', 'alpha')) || GETPOST('repair_mailing_path', 'alpha');
439
440if ($ok && $oneoptionset) {
441 print '<div id="pleasebepatient"></div>';
442 // Show wait message
443 print $langs->trans("PleaseBePatient").'<br><br>';
444
445 // Flush (some browser need a certain amount of data)
446 print str_repeat(' ', 1024);
447 if (!$ecmrepairpost && !$imagerepairpost) {
448 if (ob_get_level() > 0) {
449 ob_flush();
450 }
451 flush();
452 }
453}
454
455
456
457print '<table cellspacing="0" cellpadding="1" class="centpercent">';
458
459// run_sql: Run repair SQL file
460if ($ok && GETPOST('standard', 'alpha')) {
461 $dir = "mysql/migration/";
462
463 $filelist = array();
464 $i = 0;
465 $ok = 0;
466
467 // Recupere list fichier
468 $filesindir = array();
469 $handle = opendir($dir);
470 if (is_resource($handle)) {
471 while (($file = readdir($handle)) !== false) {
472 if (preg_match('/\.sql$/i', $file)) {
473 $filesindir[] = $file;
474 }
475 }
476 }
477 sort($filesindir);
478
479 foreach ($filesindir as $file) {
480 if (preg_match('/repair/i', $file)) {
481 $filelist[] = $file;
482 }
483 }
484
485 // Loop on each file
486 foreach ($filelist as $file) {
487 print '<tr><td class="nowrap">*** ';
488 print $langs->trans("Script").'</td><td class="right">'.$file.'</td></tr>';
489
490 $name = dol_substr($file, 0, dol_strlen($file) - 4);
491
492 // Run sql script
493 $ok = run_sql($dir.$file, 0, 0, 1);
494 }
495}
496
497
498// sync_extrafields: Search list of fields declared and list of fields created into databases, then create fields missing
499
500if ($ok && GETPOST('standard', 'alpha')) {
501 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contratligne.class.php';
502
503 print '<tr><td colspan="2"><br>*** Update denormalized_lower_planned_end_date.</td></tr>';
504 $sqltoupdatecontract = "UPDATE ".MAIN_DB_PREFIX."contrat";
505 $sqltoupdatecontract .= " SET denormalized_lower_planned_end_date = (SELECT MIN(date_fin_validite) FROM ".MAIN_DB_PREFIX."contratdet as cd WHERE cd.fk_contrat = c.rowid AND cd.statut = ".ContratLigne::STATUS_OPEN.")";
506 $resqltoupdatecontract = $db->query($sqltoupdatecontract);
507
508 $extrafields = new ExtraFields($db);
509
510 // List of tables that has an extrafield table
511 $listofmodulesextra = array('societe' => 'societe', 'adherent' => 'adherent', 'product' => 'product',
512 'socpeople' => 'socpeople', 'propal' => 'propal', 'commande' => 'commande',
513 'facture' => 'facture', 'facturedet' => 'facturedet', 'facture_rec' => 'facture_rec', 'facturedet_rec' => 'facturedet_rec',
514 'supplier_proposal' => 'supplier_proposal', 'commande_fournisseur' => 'commande_fournisseur',
515 'facture_fourn' => 'facture_fourn', 'facture_fourn_rec' => 'facture_fourn_rec', 'facture_fourn_det' => 'facture_fourn_det', 'facture_fourn_det_rec' => 'facture_fourn_det_rec',
516 'fichinter' => 'fichinter', 'fichinterdet' => 'fichinterdet',
517 'inventory' => 'inventory',
518 'actioncomm' => 'actioncomm', 'bom_bom' => 'bom_bom', 'mrp_mo' => 'mrp_mo',
519 'adherent_type' => 'adherent_type', 'user' => 'user', 'partnership' => 'partnership', 'projet' => 'projet', 'projet_task' => 'projet_task', 'ticket' => 'ticket', 'payment_various' => 'payment_various');
520 //$listofmodulesextra = array('fichinter'=>'fichinter');
521
522 print '<tr><td colspan="2"><br>*** Check that fields into the extra table structure match the table of definition. If not, add column into table</td></tr>';
523 foreach ($listofmodulesextra as $tablename => $elementtype) {
524 // Get list of fields
525 $tableextra = MAIN_DB_PREFIX.$tablename.'_extrafields';
526
527 // Define $arrayoffieldsdesc
528 $arrayoffieldsdesc = $extrafields->fetch_name_optionals_label($elementtype);
529
530 // Define $arrayoffieldsfound
531 $arrayoffieldsfound = array();
532 $resql = $db->DDLDescTable($tableextra);
533 if ($resql) {
534 print '<tr><td>Check availability of extra field for '.$tableextra;
535 $i = 0;
536 while ($obj = $db->fetch_object($resql)) {
537 $fieldname = $fieldtype = '';
538 if (preg_match('/mysql/', $db->type)) {
539 $fieldname = $obj->Field;
540 $fieldtype = $obj->Type;
541 } else {
542 $fieldname = isset($obj->Key) ? $obj->Key : $obj->attname;
543 $fieldtype = isset($obj->Type) ? $obj->Type : 'varchar';
544 }
545
546 if (empty($fieldname)) {
547 continue;
548 }
549 if (in_array($fieldname, array('rowid', 'tms', 'fk_object', 'import_key'))) {
550 continue;
551 }
552 $arrayoffieldsfound[$fieldname] = array('type' => $fieldtype);
553 }
554 print ' - Found '.count($arrayoffieldsfound).' fields into table';
555 if (count($arrayoffieldsfound) > 0) {
556 print ' <span class="opacitymedium">('.implode(', ', array_keys($arrayoffieldsfound)).')</span>';
557 }
558 print '<br>'."\n";
559
560 // If it does not match, we create fields
561 foreach ($arrayoffieldsdesc as $code => $label) {
562 if (!in_array($code, array_keys($arrayoffieldsfound))) {
563 print 'Found field '.$code.' declared into '.MAIN_DB_PREFIX.'extrafields table but not found into desc of table '.$tableextra." -> ";
564 $type = $extrafields->attributes[$elementtype]['type'][$code];
565 $length = $extrafields->attributes[$elementtype]['size'][$code];
566 $attribute = '';
567 $default = '';
568 $extra = '';
569 $null = 'null';
570
571 if ($type == 'boolean') {
572 $typedb = 'int';
573 $lengthdb = '1';
574 } elseif ($type == 'price') {
575 $typedb = 'double';
576 $lengthdb = '24,8';
577 } elseif ($type == 'phone') {
578 $typedb = 'varchar';
579 $lengthdb = '20';
580 } elseif ($type == 'mail') {
581 $typedb = 'varchar';
582 $lengthdb = '128';
583 } elseif (($type == 'select') || ($type == 'sellist') || ($type == 'radio') || ($type == 'checkbox') || ($type == 'chkbxlst')) {
584 $typedb = 'text';
585 $lengthdb = '';
586 } elseif ($type == 'link') {
587 $typedb = 'int';
588 $lengthdb = '11';
589 } else {
590 $typedb = $type;
591 $lengthdb = $length;
592 }
593
594 $field_desc = array(
595 'type' => $typedb,
596 'value' => $lengthdb,
597 'attribute' => $attribute,
598 'default' => $default,
599 'extra' => $extra,
600 'null' => $null
601 );
602 //var_dump($field_desc);exit;
603
604 $result = 0;
605 if (GETPOST('standard', 'alpha') == 'confirmed') {
606 $result = $db->DDLAddField($tableextra, $code, $field_desc, "");
607
608 if ($result < 0) {
609 print "KO ".$db->lasterror."<br>\n";
610 } else {
611 print "OK<br>\n";
612 }
613 } else {
614 print ' - Mode test, no column added.';
615 }
616 }
617 }
618
619 print "</td><td>&nbsp;</td></tr>\n";
620 } else {
621 print '<tr><td>Table '.$tableextra.' is not found</td><td></td></tr>'."\n";
622 }
623 }
624}
625
626
627// clean_data_ecm_dir: Clean data into ecm_directories table
628if ($ok && GETPOST('standard', 'alpha')) {
630}
631
632
633// clean declaration constants
634if ($ok && GETPOST('standard', 'alpha')) {
635 print '<tr><td colspan="2"><br>*** Clean constant record of modules not enabled</td></tr>';
636
637 $sql = "SELECT name, entity, value";
638 $sql .= " FROM ".MAIN_DB_PREFIX."const as c";
639 $sql .= " WHERE name LIKE 'MAIN_MODULE_%_TPL' OR name LIKE 'MAIN_MODULE_%_CSS' OR name LIKE 'MAIN_MODULE_%_JS' OR name LIKE 'MAIN_MODULE_%_HOOKS'";
640 $sql .= " OR name LIKE 'MAIN_MODULE_%_TRIGGERS' OR name LIKE 'MAIN_MODULE_%_THEME' OR name LIKE 'MAIN_MODULE_%_SUBSTITUTIONS' OR name LIKE 'MAIN_MODULE_%_MODELS'";
641 $sql .= " OR name LIKE 'MAIN_MODULE_%_MENUS' OR name LIKE 'MAIN_MODULE_%_LOGIN' OR name LIKE 'MAIN_MODULE_%_BARCODE' OR name LIKE 'MAIN_MODULE_%_TABS_%'";
642 $sql .= " OR name LIKE 'MAIN_MODULE_%_MODULEFOREXTERNAL'";
643 $sql .= " ORDER BY name, entity";
644
645 $resql = $db->query($sql);
646 if ($resql) {
647 $num = $db->num_rows($resql);
648
649 if ($num) {
650 $db->begin();
651
652 $i = 0;
653 while ($i < $num) {
654 $obj = $db->fetch_object($resql);
655
656 $reg = array();
657 if (preg_match('/MAIN_MODULE_([^_\W]+)_(\w+)/i', $obj->name, $reg)) {
658 $name = $reg[1];
659 $type = $reg[2];
660
661 $sql2 = "SELECT COUNT(*) as nb";
662 $sql2 .= " FROM ".MAIN_DB_PREFIX."const as c";
663 $sql2 .= " WHERE name = 'MAIN_MODULE_".$db->sanitize($name)."'";
664 $sql2 .= " AND entity = ".((int) $obj->entity);
665 $resql2 = $db->query($sql2);
666 if ($resql2) {
667 $obj2 = $db->fetch_object($resql2);
668 if ($obj2 && $obj2->nb == 0) {
669 // Module not found, so we can remove entry
670 $sqldelete = "DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = '".$db->escape($obj->name)."' AND entity = ".((int) $obj->entity);
671
672 if (GETPOST('standard', 'alpha') == 'confirmed') {
673 $db->query($sqldelete);
674
675 print '<tr><td>Widget '.$obj->name.' set in entity '.$obj->entity.' with value '.$obj->value.' -> Module '.$name.' not enabled in entity '.((int) $obj->entity).', we delete record</td></tr>';
676 } else {
677 print '<tr><td>Widget '.$obj->name.' set in entity '.$obj->entity.' with value '.$obj->value.' -> Module '.$name.' not enabled in entity '.((int) $obj->entity).', we should delete record (not done, mode test)</td></tr>';
678 }
679 } else {
680 //print '<tr><td>Constant '.$obj->name.' set in entity '.$obj->entity.' with value '.$obj->value.' -> Module found in entity '.$obj->entity.', we keep record</td></tr>';
681 }
682 }
683 }
684
685 $i++;
686 }
687
688 $db->commit();
689 }
690 } else {
691 dol_print_error($db);
692 }
693}
694
695
696// clean box of not enabled modules
697if ($ok && GETPOST('standard', 'alpha')) {
698 print '<tr><td colspan="2"><br>*** Clean definition of boxes of modules not enabled</td></tr>';
699
700 $sql = "SELECT file, entity FROM ".MAIN_DB_PREFIX."boxes_def";
701 $sql .= " WHERE file like '%@%'";
702
703 $resql = $db->query($sql);
704 if ($resql) {
705 $num = $db->num_rows($resql);
706
707 if ($num) {
708 $db->begin();
709
710 $i = 0;
711 while ($i < $num) {
712 $obj = $db->fetch_object($resql);
713
714 $reg = array();
715 if (preg_match('/^(\w+)@(\w+)$/i', $obj->file, $reg)) {
716 $name = $reg[1];
717 $module = $reg[2];
718
719 $sql2 = "SELECT COUNT(*) as nb";
720 $sql2 .= " FROM ".MAIN_DB_PREFIX."const as c";
721 $sql2 .= " WHERE name = 'MAIN_MODULE_".strtoupper($module)."'"; // @phan-suppress-current-line SqlInjection
722 $sql2 .= " AND entity = ".((int) $obj->entity);
723 $sql2 .= " AND value <> 0";
724 $resql2 = $db->query($sql2);
725 if ($resql2) {
726 $obj2 = $db->fetch_object($resql2);
727 if ($obj2 && $obj2->nb == 0) {
728 // Module not found, so we canremove entry
729 $sqldeletea = "DELETE FROM ".MAIN_DB_PREFIX."boxes WHERE entity = ".((int) $obj->entity)." AND box_id IN (SELECT rowid FROM ".MAIN_DB_PREFIX."boxes_def WHERE file = '".$db->escape($obj->file)."' AND entity = ".((int) $obj->entity).")";
730 $sqldeleteb = "DELETE FROM ".MAIN_DB_PREFIX."boxes_def WHERE file = '".$db->escape($obj->file)."' AND entity = ".((int) $obj->entity);
731
732 if (GETPOST('standard', 'alpha') == 'confirmed') {
733 $db->query($sqldeletea);
734 $db->query($sqldeleteb);
735
736 print '<tr><td>Constant '.$obj->file.' set in boxes_def for entity '.$obj->entity.' but MAIN_MODULE_'.strtoupper($module).' not defined in entity '.((int) $obj->entity).', we delete record</td></tr>';
737 } else {
738 print '<tr><td>Constant '.$obj->file.' set in boxes_def for entity '.$obj->entity.' but MAIN_MODULE_'.strtoupper($module).' not defined in entity '.((int) $obj->entity).', we should delete record (not done, mode test)</td></tr>';
739 }
740 } else {
741 //print '<tr><td>Constant '.$obj->name.' set in entity '.$obj->entity.' with value '.$obj->value.' -> Module found in entity '.$obj->entity.', we keep record</td></tr>';
742 }
743 }
744 }
745
746 $i++;
747 }
748
749 $db->commit();
750 }
751 }
752}
753
754
755// restore_thirdparties_logos: Move logos to correct new directory.
756if ($ok && GETPOST('restore_thirdparties_logos')) {
757 //$exts=array('gif','png','jpg');
758
759 $ext = '';
760
761 print '<tr><td colspan="2"><br>*** Restore thirdparties logo<br>';
762
763 $imagebasedir = '';
764 if (isset($conf->societe->multidir_output[$conf->entity]) && is_string($conf->societe->multidir_output[$conf->entity]) && trim($conf->societe->multidir_output[$conf->entity]) !== '') {
765 $imagebasedir = (string) getMultidirOutput(null, 'societe');
766 }
767 if ($imagebasedir === '' || strpos($imagebasedir, 'error-') === 0
768 || !dol_is_dir($imagebasedir) || !is_readable(dol_osencode($imagebasedir))
769 || !repairImagePathIsSafe($imagebasedir, $imagebasedir, DOL_DATA_ROOT)) {
770 print '<tr><td class="error">'.$langs->trans('RepairImagesDirectoryUnavailable').'</td></tr>';
771 $ok = 0;
772 }
773 $sql = "SELECT s.rowid, s.nom as name, s.logo FROM ".MAIN_DB_PREFIX."societe as s";
774 $sql .= " WHERE s.entity = ".((int) $conf->entity);
775 $sql .= " ORDER BY s.nom";
776 $resql = $ok ? $db->query($sql) : false;
777 if ($resql) {
778 $num = $db->num_rows($resql);
779 $i = 0;
780
781 while ($i < $num) {
782 $obj = $db->fetch_object($resql);
783
784 /*
785 $name=preg_replace('/é/','',$obj->name);
786 $name=preg_replace('/ /','_',$name);
787 $name=preg_replace('/\'/','',$name);
788 */
789
790 if ((string) $obj->logo !== dol_sanitizeFileName((string) $obj->logo)) {
791 $error++;
792 $i++;
793 continue;
794 }
795 $name = pathinfo((string) $obj->logo, PATHINFO_FILENAME);
796 $extension = pathinfo((string) $obj->logo, PATHINFO_EXTENSION);
797 $ext = $extension !== '' ? '.'.$extension : '';
798
799 if (!empty($name)) {
800 $filetotest = $imagebasedir.'/logos/'.$name.$ext;
801 $filetotestsmall = $imagebasedir.'/logos/thumbs/'.$name.'_small'.$ext;
802 $exists = (int) dol_is_file($filetotest);
803 print 'Check thirdparty '.$obj->rowid.' name='.dol_escape_htmltag($obj->name).' logo='.dol_escape_htmltag($obj->logo).' file '.dol_escape_htmltag($filetotest)." exists=".$exists."<br>\n";
804 $filetarget = $imagebasedir.'/'.$obj->rowid.'/logos/'.$name.$ext;
805 $filetargetsmall = $imagebasedir.'/'.$obj->rowid.'/logos/thumbs/'.$name.'_small'.$ext;
806 $imagesafe = true;
807 foreach (array($filetotest, $filetotestsmall, $filetarget, $filetargetsmall) as $imagepath) {
808 if (!repairImagePathIsSafe($imagepath, $imagebasedir, DOL_DATA_ROOT)) {
809 $imagesafe = false;
810 break;
811 }
812 }
813 if (!$imagesafe) {
814 dol_syslog('Image repair skipped an unsafe thirdparty path, id='.((int) $obj->rowid), LOG_WARNING);
815 $error++;
816 $i++;
817 continue;
818 }
819 if ($exists) {
820 $existt = dol_is_file($filetarget);
821 if (!$existt) {
822 if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') {
823 if (dol_mkdir($imagebasedir.'/'.$obj->rowid.'/logos') < 0) {
824 $error++;
825 }
826 }
827
828 print " &nbsp; &nbsp; &nbsp; -> Copy file ".dol_escape_htmltag($filetotest)." -> ".dol_escape_htmltag($filetarget)."<br>\n";
829 if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') {
830 if (dol_copy($filetotest, $filetarget, '', 0) < 0) {
831 $error++;
832 }
833 }
834 }
835
836 $existtt = dol_is_file($filetargetsmall);
837 if (!$existtt && dol_is_file($filetotestsmall)) {
838 if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') {
839 if (dol_mkdir($imagebasedir.'/'.$obj->rowid.'/logos/thumbs') < 0) {
840 $error++;
841 }
842 }
843 print " &nbsp; &nbsp; &nbsp; -> Copy file ".dol_escape_htmltag($filetotestsmall)." -> ".dol_escape_htmltag($filetargetsmall)."<br>\n";
844 if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') {
845 if (dol_copy($filetotestsmall, $filetargetsmall, '', 0) < 0) {
846 $error++;
847 }
848 }
849 }
850 }
851 }
852
853 $i++;
854 }
855 } else {
856 if ($ok) {
857 dol_print_error($db);
858 }
859 $ok = 0;
860 }
861
862 print '</td></tr>';
863}
864
865
866
867// restore_user_pictures: Move pictures to correct new directory.
868if ($ok && GETPOST('restore_user_pictures', 'alpha')) {
869 //$exts=array('gif','png','jpg');
870
871 $ext = '';
872
873 print '<tr><td colspan="2"><br>*** Restore user pictures<br>';
874
875 $sql = "SELECT s.rowid, s.firstname, s.lastname, s.login, s.photo FROM ".MAIN_DB_PREFIX."user as s ORDER BY s.rowid";
876 $resql = $db->query($sql);
877 if ($resql) {
878 $num = $db->num_rows($resql);
879 $i = 0;
880
881 while ($i < $num) {
882 $obj = $db->fetch_object($resql);
883
884 /*
885 $name=preg_replace('/é/','',$obj->name);
886 $name=preg_replace('/ /','_',$name);
887 $name=preg_replace('/\'/','',$name);
888 */
889
890 $tmp = explode('.', (string) $obj->photo);
891 $name = $tmp[0];
892 if (isset($tmp[1])) {
893 $ext = '.'.$tmp[1];
894 }
895
896 if (!empty($name)) {
897 $filetotest = $dolibarr_main_data_root.'/users/'.substr(sprintf('%08d', $obj->rowid), -1, 1).'/'.substr(sprintf('%08d', $obj->rowid), -2, 1).'/'.$name.$ext;
898 $filetotestsmall = $dolibarr_main_data_root.'/users/'.substr(sprintf('%08d', $obj->rowid), -1, 1).'/'.substr(sprintf('%08d', $obj->rowid), -2, 1).'/thumbs/'.$name.'_small'.$ext;
899 $filetotestmini = $dolibarr_main_data_root.'/users/'.substr(sprintf('%08d', $obj->rowid), -1, 1).'/'.substr(sprintf('%08d', $obj->rowid), -2, 1).'/thumbs/'.$name.'_mini'.$ext;
900 $exists = (int) dol_is_file($filetotest);
901 print 'Check user '.$obj->rowid.' lastname='.$obj->lastname.' firstname='.$obj->firstname.' photo='.$obj->photo.' file '.$filetotest." exists=".$exists."<br>\n";
902 if ($exists) {
903 $filetarget = $dolibarr_main_data_root.'/users/'.$obj->rowid.'/'.$name.$ext;
904 $filetargetsmall = $dolibarr_main_data_root.'/users/'.$obj->rowid.'/thumbs/'.$name.'_small'.$ext;
905 $filetargetmini = $dolibarr_main_data_root.'/users/'.$obj->rowid.'/thumbs/'.$name.'_mini'.$ext;
906
907 $existt = dol_is_file($filetarget);
908 if (!$existt) {
909 if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') {
910 dol_mkdir($dolibarr_main_data_root.'/users/'.$obj->rowid);
911 }
912
913 print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotest." -> ".$filetarget."<br>\n";
914 if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') {
915 dol_copy($filetotest, $filetarget, '', 0);
916 }
917 }
918
919 $existtt = dol_is_file($filetargetsmall);
920 if (!$existtt) {
921 if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') {
922 dol_mkdir($dolibarr_main_data_root.'/users/'.$obj->rowid.'/thumbs');
923 }
924
925 print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotestsmall." -> ".$filetargetsmall."<br>\n";
926 if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') {
927 dol_copy($filetotestsmall, $filetargetsmall, '', 0);
928 }
929 }
930
931 $existtt = dol_is_file($filetargetmini);
932 if (!$existtt) {
933 if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') {
934 dol_mkdir($dolibarr_main_data_root.'/users/'.$obj->rowid.'/thumbs');
935 }
936
937 print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotestmini." -> ".$filetargetmini."<br>\n";
938 if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') {
939 dol_copy($filetotestmini, $filetargetmini, '', 0);
940 }
941 }
942 }
943 }
944
945 $i++;
946 }
947 } else {
948 $ok = 0;
949 dol_print_error($db);
950 }
951
952 print '</td></tr>';
953}
954
955
956// rebuild_product_thumbs: Rebuild thumbs for product files
957if ($ok && GETPOST('rebuild_product_thumbs', 'alpha')) {
958 $ext = '';
959 global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
960
961 print '<tr><td colspan="2"><br>*** Rebuild product thumbs<br>';
962
963 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
964 $staticproduct = new Product($db);
965 $imagebasedir = '';
966 if (isset($conf->product->multidir_output[$conf->entity]) && is_string($conf->product->multidir_output[$conf->entity]) && trim($conf->product->multidir_output[$conf->entity]) !== '') {
967 $imagebasedir = (string) getMultidirOutput(null, 'product');
968 }
969 if ($imagebasedir === '' || strpos($imagebasedir, 'error-') === 0
970 || !dol_is_dir($imagebasedir) || !is_readable(dol_osencode($imagebasedir))
971 || !repairImagePathIsSafe($imagebasedir, $imagebasedir, DOL_DATA_ROOT)) {
972 print '<tr><td class="error">'.$langs->trans('RepairImagesDirectoryUnavailable').'</td></tr>';
973 $ok = 0;
974 }
975 $sql = "SELECT s.rowid, s.ref FROM ".MAIN_DB_PREFIX."product as s";
976 $sql .= " WHERE s.entity = ".((int) $conf->entity);
977 $sql .= " ORDER BY s.ref";
978 $resql = $ok ? $db->query($sql) : false;
979 if ($resql) {
980 $num = $db->num_rows($resql);
981 $i = 0;
982
983 while ($i < $num) {
984 $obj = $db->fetch_object($resql);
985
986 if (!empty($obj->ref)) {
987 $staticproduct->id = (int) $obj->rowid;
988 $staticproduct->ref = (string) $obj->ref;
989 $imagedir = $imagebasedir.'/'.get_exdir(0, 0, 0, 1, $staticproduct, 'product');
990 if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
991 $imagedir .= '/'.$staticproduct->id.'/photos';
992 }
993 $realimagedir = realpath(dol_osencode($imagedir));
994 if ($realimagedir === false) {
995 $i++;
996 continue;
997 }
998 $imagesafe = repairImagePathIsSafe($imagedir, $imagebasedir, DOL_DATA_ROOT) && repairImagePathIsSafe($imagedir.'/thumbs', $imagebasedir, DOL_DATA_ROOT);
999 if ($imagesafe) {
1000 foreach (dol_dir_list($imagedir.'/thumbs', 'all', 0, '', null, 'name', SORT_ASC, 0, 1) as $thumb) {
1001 if (!repairImagePathIsSafe($thumb['fullname'], $imagebasedir, DOL_DATA_ROOT)) {
1002 $imagesafe = false;
1003 break;
1004 }
1005 }
1006 }
1007 if (!$imagesafe) {
1008 dol_syslog('Image repair skipped an unsafe product path, id='.((int) $obj->rowid), LOG_WARNING);
1009 $error++;
1010 $i++;
1011 continue;
1012 }
1013 $files = dol_dir_list($imagedir, 'files', 0, '', null, 'name', SORT_ASC, 0, 1, '', 1);
1014 foreach ($files as $file) {
1015 if (!repairImagePathIsSafe($file['fullname'], $imagebasedir, DOL_DATA_ROOT)) {
1016 $error++;
1017 continue;
1018 }
1019 // Generate thumbs.
1020 if (image_format_supported($file['fullname']) == 1) {
1021 $imgThumbSmall = 'notbuild';
1022 if (GETPOST('rebuild_product_thumbs', 'alpha') == 'confirmed') {
1023 // Used on logon for example
1024 $imgThumbSmall = vignette($file['fullname'], $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
1025 if (!is_string($imgThumbSmall) || !dol_is_file($imgThumbSmall)) {
1026 $error++;
1027 }
1028 }
1029 print 'Check product '.$obj->rowid.", file ".dol_escape_htmltag($file['fullname'])." -> ".dol_escape_htmltag((string) $imgThumbSmall)." maxwidthsmall=".$maxwidthsmall." maxheightsmall=".$maxheightsmall."<br>\n";
1030 $imgThumbMini = 'notbuild';
1031 if (GETPOST('rebuild_product_thumbs', 'alpha') == 'confirmed') {
1032 // Create mini thumbs for image (Ratio is near 16/9)
1033 // Used on menu or for setup page for example
1034 $imgThumbMini = vignette($file['fullname'], $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
1035 if (!is_string($imgThumbMini) || !dol_is_file($imgThumbMini)) {
1036 $error++;
1037 }
1038 }
1039 print 'Check product '.$obj->rowid.", file ".dol_escape_htmltag($file['fullname'])." -> ".dol_escape_htmltag((string) $imgThumbMini)." maxwidthmini=".$maxwidthmini." maxheightmini=".$maxheightmini."<br>\n";
1040 }
1041 }
1042 }
1043
1044 $i++;
1045 }
1046 } else {
1047 if ($ok) {
1048 dol_print_error($db);
1049 }
1050 $ok = 0;
1051 }
1052
1053 print '</td></tr>';
1054}
1055
1056// clean_linked_elements: Check and clean linked elements
1057if ($ok && GETPOST('clean_linked_elements', 'alpha')) {
1058 print '<tr><td colspan="2"><br>*** Check table of linked elements and delete orphelins links</td></tr>';
1059 // propal => order
1060 print '<tr><td colspan="2">'.checkLinkedElements('propal', 'commande')."</td></tr>\n";
1061
1062 // propal => invoice
1063 print '<tr><td colspan="2">'.checkLinkedElements('propal', 'facture')."</td></tr>\n";
1064
1065 // order => invoice
1066 print '<tr><td colspan="2">'.checkLinkedElements('commande', 'facture')."</td></tr>\n";
1067
1068 // order => shipping
1069 print '<tr><td colspan="2">'.checkLinkedElements('commande', 'shipping')."</td></tr>\n";
1070
1071 // shipping => delivery
1072 print '<tr><td colspan="2">'.checkLinkedElements('shipping', 'delivery')."</td></tr>\n";
1073
1074 // order_supplier => invoice_supplier
1075 print '<tr><td colspan="2">'.checkLinkedElements('order_supplier', 'invoice_supplier')."</td></tr>\n";
1076}
1077
1078
1079// clean_menus: Check orphelins menus
1080if ($ok && GETPOST('clean_menus', 'alpha')) {
1081 print '<tr><td colspan="2"><br>*** Clean menu entries coming from disabled modules</td></tr>';
1082
1083 $sql = "SELECT rowid, module";
1084 $sql .= " FROM ".MAIN_DB_PREFIX."menu as c";
1085 $sql .= " WHERE module IS NOT NULL AND module <> ''";
1086 $sql .= " AND c.entity = ".((int) $conf->entity);
1087 $sql .= " ORDER BY module";
1088
1089 $resql = $db->query($sql);
1090 if ($resql) {
1091 $num = $db->num_rows($resql);
1092 if ($num) {
1093 $i = 0;
1094 while ($i < $num) {
1095 $obj = $db->fetch_object($resql);
1096
1097 $modulecond = $obj->module;
1098 $modulecondarray = explode('|', $obj->module); // Name of module
1099
1100 print '<tr><td>';
1101 print $modulecond;
1102
1103 $db->begin();
1104
1105 if ($modulecond) { // And menu entry for module $modulecond was found in database.
1106 $moduleok = 0;
1107 foreach ($modulecondarray as $tmpname) {
1108 if ($tmpname == 'margins') {
1109 $tmpname = 'margin'; // TODO Remove this when normalized
1110 }
1111
1112 $result = 0;
1113 if (!empty($conf->$tmpname)) {
1114 $result = $conf->$tmpname->enabled;
1115 }
1116 if ($result) {
1117 $moduleok++;
1118 }
1119 }
1120
1121 if (!$moduleok && $modulecond) {
1122 print ' - Module condition '.$modulecond.' seems ko, we delete menu entry.';
1123 if (GETPOST('clean_menus') == 'confirmed') {
1124 $sql2 = "DELETE FROM ".MAIN_DB_PREFIX."menu WHERE module = '".$db->escape($modulecond)."'";
1125 $sql2 .= " AND entity = ".((int) $conf->entity);
1126 $resql2 = $db->query($sql2);
1127 if (!$resql2) {
1128 $error++;
1129 dol_print_error($db);
1130 } else {
1131 print ' - <span class="warning">Cleaned</span>';
1132 }
1133 } else {
1134 print ' - <span class="warning">Canceled (test mode)</span>';
1135 }
1136 } else {
1137 print ' - Module condition '.$modulecond.' is ok, we do nothing.';
1138 }
1139 }
1140
1141 if (!$error) {
1142 $db->commit();
1143 } else {
1144 $db->rollback();
1145 }
1146
1147 print'</td></tr>';
1148
1149 if ($error) {
1150 break;
1151 }
1152
1153 $i++;
1154 }
1155 } else {
1156 print '<tr><td>No menu entries of disabled menus found</td></tr>';
1157 }
1158 } else {
1159 dol_print_error($db);
1160 }
1161}
1162
1163
1164
1165// clean_orphelin_dir: Run purge of directory
1166if ($ok && GETPOST('clean_orphelin_dir', 'alpha')) {
1167 $listmodulepart = array('company', 'invoice', 'invoice_supplier', 'propal', 'order', 'order_supplier', 'contract', 'tax');
1168 foreach ($listmodulepart as $modulepart) {
1169 $filearray = array();
1170 $upload_dir = isset($conf->$modulepart->dir_output) ? $conf->$modulepart->dir_output : '';
1171 if ($modulepart == 'company') {
1172 $upload_dir = $conf->societe->dir_output; // TODO change for multicompany sharing
1173 }
1174 if ($modulepart == 'invoice') {
1175 $upload_dir = $conf->facture->dir_output;
1176 }
1177 if ($modulepart == 'invoice_supplier') {
1178 $upload_dir = $conf->fournisseur->facture->dir_output;
1179 }
1180 if ($modulepart == 'order') {
1181 $upload_dir = $conf->commande->dir_output;
1182 }
1183 if ($modulepart == 'order_supplier') {
1184 $upload_dir = $conf->fournisseur->commande->dir_output;
1185 }
1186 if ($modulepart == 'contract') {
1187 $upload_dir = $conf->contrat->dir_output;
1188 }
1189
1190 if (empty($upload_dir)) {
1191 continue;
1192 }
1193
1194 print '<tr><td colspan="2"><br>*** Clean orphelins files into files '.$upload_dir.'</td></tr>';
1195
1196 $filearray = dol_dir_list($upload_dir, "files", 1, '', array('^SPECIMEN\.pdf$', '^\.', '(\.meta|_preview.*\.png)$', '^temp$', '^payments$', '^CVS$', '^thumbs$'), '', SORT_DESC, 1, 1);
1197
1198 $object_instance = null;
1199 // To show ref or specific information according to view to show (defined by $module)
1200 if ($modulepart == 'company') {
1201 include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1202 $object_instance = new Societe($db);
1203 }
1204 if ($modulepart == 'invoice') {
1205 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1206 $object_instance = new Facture($db);
1207 } elseif ($modulepart == 'invoice_supplier') {
1208 include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
1209 $object_instance = new FactureFournisseur($db);
1210 } elseif ($modulepart == 'propal') {
1211 include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
1212 $object_instance = new Propal($db);
1213 } elseif ($modulepart == 'order') {
1214 include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
1215 $object_instance = new Commande($db);
1216 } elseif ($modulepart == 'order_supplier') {
1217 include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1218 $object_instance = new CommandeFournisseur($db);
1219 } elseif ($modulepart == 'contract') {
1220 include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
1221 $object_instance = new Contrat($db);
1222 } elseif ($modulepart == 'tax') {
1223 include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
1224 $object_instance = new ChargeSociales($db);
1225 }
1226
1227 foreach ($filearray as $key => $file) {
1228 if (!is_dir($file['name'])
1229 && $file['name'] != '.'
1230 && $file['name'] != '..'
1231 && $file['name'] != 'CVS'
1232 ) {
1233 // Define relative path used to store the file
1234 $relativefile = preg_replace('/'.preg_quote($upload_dir.'/', '/').'/', '', $file['fullname']);
1235
1236 //var_dump($file);
1237 $id = 0;
1238 $ref = '';
1239 $object_instance->id = 0;
1240 $object_instance->ref = '';
1241 $label = '';
1242
1243 // To show ref or specific information according to view to show (defined by $module)
1244 if ($modulepart == 'invoice') {
1245 preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg);
1246 $ref = empty($reg[1]) ? '' : $reg[1];
1247 }
1248 if ($modulepart == 'invoice_supplier') {
1249 preg_match('/(\d+)\/[^\/]+$/', $relativefile, $reg);
1250 $id = empty($reg[1]) ? '' : $reg[1];
1251 }
1252 if ($modulepart == 'propal') {
1253 preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg);
1254 $ref = empty($reg[1]) ? '' : $reg[1];
1255 }
1256 if ($modulepart == 'order') {
1257 preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg);
1258 $ref = empty($reg[1]) ? '' : $reg[1];
1259 }
1260 if ($modulepart == 'order_supplier') {
1261 preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg);
1262 $ref = empty($reg[1]) ? '' : $reg[1];
1263 }
1264 if ($modulepart == 'contract') {
1265 preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg);
1266 $ref = empty($reg[1]) ? '' : $reg[1];
1267 }
1268 if ($modulepart == 'tax') {
1269 preg_match('/(\d+)\/[^\/]+$/', $relativefile, $reg);
1270 $id = empty($reg[1]) ? '' : $reg[1];
1271 }
1272
1273 if (($id || $ref) && $object_instance !== null) {
1274 //print 'Fetch '.$id.' or '.$ref.'<br>';
1275 $result = $object_instance->fetch($id, $ref);
1276 //print $result.'<br>';
1277 if ($result == 0) { // Not found but no error
1278 // Clean of orphelins directories are done into repair.php
1279 print '<tr><td colspan="2">';
1280 print 'Delete orphelins file '.$file['fullname'].'<br>';
1281 if (GETPOST('clean_orphelin_dir', 'alpha') == 'confirmed') {
1282 dol_delete_file($file['fullname'], 1, 1, 1);
1283 dol_delete_dir(dirname($file['fullname']), 1);
1284 }
1285 print "</td></tr>";
1286 } elseif ($result < 0) {
1287 print 'Error in '.get_class($object_instance).'.fetch of id'.$id.' ref='.$ref.', result='.$result.'<br>';
1288 }
1289 }
1290 }
1291 }
1292 }
1293}
1294
1295$methodtofix = '';
1296// clean_linked_elements: Check and clean linked elements
1297if ($ok && GETPOST('clean_product_stock_batch', 'alpha')) {
1298 $methodtofix = GETPOST('methodtofix', 'alpha') ? GETPOST('methodtofix', 'alpha') : 'updatestock';
1299
1300 print '<tr><td colspan="2"><br>*** Clean table product_batch, methodtofix='.$methodtofix.' (possible values: updatestock or updatebatch)</td></tr>';
1301
1302 $sql = "SELECT p.rowid, p.ref, p.tobatch, ps.rowid as psrowid, ps.fk_entrepot, ps.reel, SUM(pb.qty) as reelbatch";
1303 $sql .= " FROM ".MAIN_DB_PREFIX."product as p, ".MAIN_DB_PREFIX."product_stock as ps LEFT JOIN ".MAIN_DB_PREFIX."product_batch as pb ON ps.rowid = pb.fk_product_stock";
1304 $sql .= " WHERE p.rowid = ps.fk_product";
1305 $sql .= " GROUP BY p.rowid, p.ref, p.tobatch, ps.rowid, ps.fk_entrepot, ps.reel";
1306 $sql .= " HAVING (SUM(pb.qty) IS NOT NULL AND reel != SUM(pb.qty)) OR (SUM(pb.qty) IS NULL AND p.tobatch > 0)";
1307
1308 $resql = $db->query($sql);
1309 if ($resql) {
1310 $num = $db->num_rows($resql);
1311
1312 if ($num) {
1313 $i = 0;
1314 while ($i < $num) {
1315 $obj = $db->fetch_object($resql);
1316 print '<tr><td>Product '.$obj->rowid.'-'.$obj->ref.' in warehouse id='.$obj->fk_entrepot.' (product_stock.id='.$obj->psrowid.'): '.$obj->reel.' (Stock product_stock.reel) != '.($obj->reelbatch ? $obj->reelbatch : '0').' (Stock batch sum product_batch)';
1317
1318 // Fix is required
1319 if ($obj->reel != $obj->reelbatch) {
1320 if (empty($obj->tobatch)) {
1321 // If product is not a product that support batches, we can clean stock by deleting the product batch lines
1322 print ' -> Delete qty '.$obj->reelbatch.' for any lot linked to fk_product_stock='.$obj->psrowid;
1323 $sql2 = "DELETE FROM ".MAIN_DB_PREFIX."product_batch";
1324 $sql2 .= " WHERE fk_product_stock = ".((int) $obj->psrowid);
1325 print '<br>'.$sql2;
1326
1327 if (GETPOST('clean_product_stock_batch') == 'confirmed') {
1328 $resql2 = $db->query($sql2);
1329 if (!$resql2) {
1330 $error++;
1331 dol_print_error($db);
1332 }
1333 }
1334 } else {
1335 if ($methodtofix == 'updatebatch') {
1336 // Method 1
1337 print ' -> Insert qty '.($obj->reel - $obj->reelbatch).' with lot 000000 linked to fk_product_stock='.$obj->psrowid;
1338 $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."product_batch(fk_product_stock, batch, qty)";
1339 $sql2 .= "VALUES(".((int) $obj->psrowid).", '000000', ".((float) ($obj->reel - $obj->reelbatch)).")";
1340 print '<br>'.$sql2;
1341
1342 if (GETPOST('clean_product_stock_batch') == 'confirmed') {
1343 $resql2 = $db->query($sql2);
1344 if (!$resql2) {
1345 // TODO If it fails, we must make update
1346 //$sql2 ="UPDATE ".MAIN_DB_PREFIX."product_batch";
1347 //$sql2.=" SET ".$obj->psrowid.", '000000', ".($obj->reel - $obj->reelbatch).")";
1348 //$sql2.=" WHERE fk_product_stock = ".((int) $obj->psrowid)
1349 }
1350 }
1351 }
1352 if ($methodtofix == 'updatestock') {
1353 // Method 2
1354 print ' -> Update qty of product_stock with qty = '.($obj->reelbatch ? ((float) $obj->reelbatch) : '0').' for ps.rowid = '.((int) $obj->psrowid);
1355 $sql2 = "UPDATE ".MAIN_DB_PREFIX."product_stock";
1356 $sql2 .= " SET reel = ".($obj->reelbatch ? ((float) $obj->reelbatch) : '0')." WHERE rowid = ".((int) $obj->psrowid);
1357 print '<br>'.$sql2;
1358
1359 if (GETPOST('clean_product_stock_batch') == 'confirmed') {
1360 $error = 0;
1361
1362 $db->begin();
1363
1364 $resql2 = $db->query($sql2);
1365 if ($resql2) {
1366 // We update product_stock, so we must fill p.stock into product too.
1367 $sql3 = 'UPDATE '.MAIN_DB_PREFIX.'product p SET p.stock= (SELECT SUM(ps.reel) FROM '.MAIN_DB_PREFIX.'product_stock ps WHERE ps.fk_product = p.rowid)';
1368 $resql3 = $db->query($sql3);
1369 if (!$resql3) {
1370 $error++;
1371 dol_print_error($db);
1372 }
1373 } else {
1374 $error++;
1375 dol_print_error($db);
1376 }
1377
1378 if (!$error) {
1379 $db->commit();
1380 } else {
1381 $db->rollback();
1382 }
1383 }
1384 }
1385 }
1386 }
1387
1388 print'</td></tr>';
1389
1390 $i++;
1391 }
1392 } else {
1393 print '<tr><td colspan="2">Nothing to do</td></tr>';
1394 }
1395 } else {
1396 dol_print_error($db);
1397 }
1398}
1399
1400
1401// clean_product_stock_negative_if_batch
1402if ($ok && GETPOST('clean_product_stock_negative_if_batch', 'alpha')) {
1403 print '<tr><td colspan="2"><br>Clean table product_batch, methodtofix='.$methodtofix.' (possible values: updatestock or updatebatch)</td></tr>';
1404
1405 $sql = "SELECT p.rowid, p.ref, p.tobatch, ps.rowid as psrowid, ps.fk_entrepot, ps.reel, SUM(pb.qty) as reelbatch";
1406 $sql .= " FROM ".MAIN_DB_PREFIX."product as p, ".MAIN_DB_PREFIX."product_stock as ps, ".MAIN_DB_PREFIX."product_batch as pb";
1407 $sql .= " WHERE p.rowid = ps.fk_product AND ps.rowid = pb.fk_product_stock";
1408 $sql .= " AND p.tobatch > 0";
1409 $sql .= " GROUP BY p.rowid, p.ref, p.tobatch, ps.rowid, ps.fk_entrepot, ps.reel";
1410 $sql .= " HAVING reel != SUM(pb.qty)";
1411 $resql = $db->query($sql);
1412 if ($resql) {
1413 $num = $db->num_rows($resql);
1414
1415 if ($num) {
1416 $i = 0;
1417 while ($i < $num) {
1418 $obj = $db->fetch_object($resql);
1419 print '<tr><td>'.$obj->rowid.'-'.$obj->ref.'-'.$obj->fk_entrepot.' -> '.$obj->psrowid.': '.$obj->reel.' != '.$obj->reelbatch;
1420
1421 // TODO
1422 }
1423 }
1424 }
1425}
1426
1427// set_empty_time_spent_amount
1428if ($ok && GETPOST('set_empty_time_spent_amount', 'alpha')) {
1429 print '<tr><td colspan="2"><br>*** Set value of time spent without amount</td></tr>';
1430
1431 $sql = "SELECT COUNT(ptt.rowid) as nb, u.rowid as user_id, u.login, u.thm as user_thm";
1432 $sql .= " FROM ".MAIN_DB_PREFIX."element_time as ptt, ".MAIN_DB_PREFIX."user as u";
1433 $sql .= " WHERE ptt.fk_user = u.rowid";
1434 $sql .= " AND ptt.thm IS NULL and u.thm > 0";
1435 $sql .= " GROUP BY u.rowid, u.login, u.thm";
1436
1437 $resql = $db->query($sql);
1438 if ($resql) {
1439 $num = $db->num_rows($resql);
1440
1441 if ($num) {
1442 $i = 0;
1443 while ($i < $num) {
1444 $obj = $db->fetch_object($resql);
1445 print '<tr><td>'.$obj->login.'-'.$obj->user_id.' ('.$obj->nb.' lines to fix) -> '.$obj->user_thm;
1446
1447 $db->begin();
1448
1449 if (GETPOST('set_empty_time_spent_amount') == 'confirmed') {
1450 $sql2 = "UPDATE ".MAIN_DB_PREFIX."element_time";
1451 $sql2 .= " SET thm = ".((float) $obj->user_thm)." WHERE thm IS NULL AND fk_user = ".((int) $obj->user_id);
1452 $resql2 = $db->query($sql2);
1453 if (!$resql2) {
1454 $error++;
1455 dol_print_error($db);
1456 }
1457 }
1458
1459 if (!$error) {
1460 $db->commit();
1461 } else {
1462 $db->rollback();
1463 }
1464
1465 print'</td></tr>';
1466
1467 if ($error) {
1468 break;
1469 }
1470
1471 $i++;
1472 }
1473 } else {
1474 print '<tr><td>No time spent with empty line on users with a hourly rate defined</td></tr>';
1475 }
1476 } else {
1477 dol_print_error($db);
1478 }
1479}
1480
1481
1482// force_disable_of_modules_not_found
1483if ($ok && GETPOST('force_disable_of_modules_not_found', 'alpha')) {
1484 print '<tr><td colspan="2"><br>*** Force modules not found physically to be disabled (only modules adding js, css or hooks can be detected as removed physically)</td></tr>';
1485
1486 $arraylistofkey = array('hooks', 'js', 'css');
1487
1488 foreach ($arraylistofkey as $key) {
1489 $sql = "SELECT DISTINCT name, value";
1490 $sql .= " FROM ".MAIN_DB_PREFIX."const as c";
1491 $sql .= " WHERE name LIKE 'MAIN_MODULE_%_".strtoupper($db->escape($key))."'";
1492 $sql .= " ORDER BY name";
1493
1494 $resql = $db->query($sql);
1495 if ($resql) {
1496 $num = $db->num_rows($resql);
1497 if ($num) {
1498 $i = 0;
1499 while ($i < $num) {
1500 $obj = $db->fetch_object($resql);
1501 $constantname = $obj->name; // Name of constant for hook or js or css declaration
1502
1503 print '<tr><td>';
1504 print dol_escape_htmltag($constantname);
1505
1506 $db->begin();
1507
1508 $reg = array();
1509 if (preg_match('/MAIN_MODULE_(.*)_'.strtoupper($key).'/i', $constantname, $reg)) {
1510 $name = strtolower($reg[1]);
1511
1512 if ($name) { // An entry for key $key and module $name was found in database.
1513 $reloffile = '';
1514 $result = 'found';
1515
1516 if ($key == 'hooks') {
1517 $reloffile = $name.'/class/actions_'.$name.'.class.php';
1518 }
1519 if ($key == 'js') {
1520 $value = $obj->value;
1521 $valuearray = (array) json_decode($value); // Force cast into array because sometimes it is a stdClass
1522 $reloffile = $valuearray[0];
1523 $reloffile = preg_replace('/^\//', '', $valuearray[0]);
1524 }
1525 if ($key == 'css') {
1526 $value = $obj->value;
1527 $valuearray = (array) json_decode($value); // Force cast into array because sometimes it is a stdClass
1528 if ($value && (!is_array($valuearray) || count($valuearray) == 0)) {
1529 $valuearray = array();
1530 $valuearray[0] = $value; // If value was not a json array but a string
1531 }
1532 $reloffile = preg_replace('/^\//', '', $valuearray[0]);
1533 }
1534
1535 if ($reloffile) {
1536 //var_dump($key.' - '.$value.' - '.$reloffile);
1537 try {
1538 $result = dol_buildpath($reloffile, 0, 2);
1539 } catch (Exception $e) {
1540 $result = 'found'; // If error, we force like if we found to avoid any deletion
1541 }
1542 } else {
1543 $result = 'found'; //
1544 }
1545
1546 if (!$result) {
1547 print ' - File of '.$key.' ('.$reloffile.') NOT found, we disable the module.';
1548 if (GETPOST('force_disable_of_modules_not_found') == 'confirmed') {
1549 $sql2 = "DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = 'MAIN_MODULE_".strtoupper($name)."_".strtoupper($key)."'"; // @phan-suppress-current-line SqlInjection
1550 $resql2 = $db->query($sql2);
1551 if (!$resql2) {
1552 $error++;
1553 dol_print_error($db);
1554 }
1555 $sql3 = "DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = 'MAIN_MODULE_".strtoupper($name)."'"; // @phan-suppress-current-line SqlInjection
1556 $resql3 = $db->query($sql3);
1557 if (!$resql3) {
1558 $error++;
1559 dol_print_error($db);
1560 } else {
1561 print ' - <span class="warning">Cleaned</span>';
1562 }
1563 } else {
1564 print ' - <span class="warning">Canceled (test mode)</span>';
1565 }
1566 } else {
1567 print ' - File of '.$key.' ('.$reloffile.') found, we do nothing.';
1568 }
1569 }
1570
1571 if (!$error) {
1572 $db->commit();
1573 } else {
1574 $db->rollback();
1575 }
1576 }
1577
1578 print'</td></tr>';
1579
1580 if ($error) {
1581 break;
1582 }
1583
1584 $i++;
1585 }
1586 } else {
1587 print '<tr><td>No active module with missing files found by searching on MAIN_MODULE_(.*)_'.strtoupper($key).'</td></tr>';
1588 }
1589 } else {
1590 dol_print_error($db);
1591 }
1592 }
1593}
1594
1595
1596// clean_old_module_entries: Clean data into const when files of module were removed without being
1597if ($ok && GETPOST('clean_perm_table', 'alpha')) {
1598 print '<tr><td colspan="2"><br>*** Clean table user_rights from lines of external modules no more enabled</td></tr>';
1599
1600 $listofmods = '';
1601 foreach ($conf->modules as $key => $val) {
1602 $listofmods .= ($listofmods ? ',' : '')."'".$db->escape($val)."'";
1603 }
1604
1605 $sql = "SELECT id, libelle as label, module from ".MAIN_DB_PREFIX."rights_def WHERE module NOT IN (".$db->sanitize($listofmods, 1).") AND id > 100000";
1606 $sql .= " AND entity = ".((int) $conf->entity);
1607
1608 $resql = $db->query($sql);
1609 if ($resql) {
1610 $num = $db->num_rows($resql);
1611 if ($num) {
1612 $i = 0;
1613 while ($i < $num) {
1614 $obj = $db->fetch_object($resql);
1615 if ($obj->id > 0) {
1616 print '<tr><td>Found line with id '.$obj->id.', label "'.$obj->label.'" of module "'.$obj->module.'" to delete';
1617 if (GETPOST('clean_perm_table', 'alpha') == 'confirmed') { // If confirmed, proceed with deletion
1618 $sqldelete = "DELETE FROM ".MAIN_DB_PREFIX."rights_def WHERE id = ".((int) $obj->id);
1619 $sqldelete .= " AND entity = ".((int) $conf->entity);
1620 $resqldelete = $db->query($sqldelete);
1621 if (!$resqldelete) {
1622 dol_print_error($db);
1623 }
1624 print ' - deleted';
1625 }
1626 print '</td></tr>';
1627 }
1628 $i++;
1629 }
1630 } else {
1631 print '<tr><td>No lines of a disabled external module (with id > 100000) found into table rights_def</td></tr>';
1632 }
1633 } else {
1634 dol_print_error($db);
1635 }
1636}
1637
1638
1639// clean_old_module_entries: Clean data into const when files of module were removed without being
1640if ($ok && GETPOST('clean_ecm_files_table', 'alpha')) {
1641 $ecmrepairmode = GETPOST('clean_ecm_files_table', 'aZ09');
1642 $ecmrepairtoken = GETPOST('token', 'alphanohtml');
1643 if (!in_array($ecmrepairmode, array('test', 'confirmed'), true) || $ecmrepairentity <= 0 || !isset($ecmrepairentities[$ecmrepairentity])) {
1644 print '<tr><td class="error">'.$langs->trans('ErrorWrongParameters').'</td></tr>';
1645 } elseif ($ecmrepairmode === 'confirmed' && (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' || !is_string($ecmrepairtoken) || !hash_equals(newToken(), $ecmrepairtoken))) {
1646 print '<tr><td class="error">'.$langs->trans('RepairEcmInvalidToken').'</td></tr>';
1647 } else {
1648 print '<tr><td colspan="2"><br>'.$langs->trans('RepairEcmHeading', dol_escape_htmltag($ecmrepairentities[$ecmrepairentity])).'</td></tr>';
1649 $ecmreport = repairEcmFiles($db, $ecmrepairentity, DOL_DATA_ROOT, $ecmrepairmode === 'confirmed');
1650 foreach ($ecmreport['entries'] as $ecmentry) {
1651 print '<tr><td>'.((int) $ecmentry['id']).'</td><td>'.dol_escape_htmltag($ecmentry['path']).'</td></tr>';
1652 }
1653 print '<tr><td colspan="2">'.$langs->trans('RepairEcmSummary', $ecmreport['processed'], $ecmreport['missing'], $ecmreport['deleted'], $ecmreport['skipped']).'</td></tr>';
1654 if ($ecmrepairmode === 'test') {
1655 print '<tr><td colspan="2">'.$langs->trans('RepairEcmTestMode').'</td></tr>';
1656 }
1657 if ($ecmreport['limitreached']) {
1658 print '<tr><td colspan="2">'.$langs->trans('RepairEcmLimit', 100).'</td></tr>';
1659 }
1660 if ($ecmreport['error'] !== '') {
1661 print '<tr><td colspan="2" class="error">'.$langs->trans($ecmreport['error']).'</td></tr>';
1662 }
1663 if ($ecmrepairmode === 'confirmed' && $ecmreport['error'] === '') {
1664 setEventMessages($langs->trans('RepairEcmCompleted', dol_escape_htmltag($ecmrepairentities[$ecmrepairentity]), $ecmreport['deleted']), null, 'mesgs');
1665 while (ob_get_level() > $ecmrepairbufferlevel) {
1666 ob_end_clean();
1667 }
1668 $db->close();
1669 header('Location: '.$_SERVER['PHP_SELF'].'?clean_ecm_files_table=test&ecm_entity='.((int) $ecmrepairentity).'&selectlang='.urlencode($setuplang), true, 303);
1670 exit;
1671 }
1672 }
1673}
1674
1675// force utf8 on tables
1676if ($ok && GETPOST('force_utf8_on_tables', 'alpha')) {
1677 print '<tr><td colspan="2"><br>*** Force page code and collation of tables into utf8/utf8_unicode_ci and row_format=dynamic (for mysql/mariadb only)</td></tr>';
1678
1679 if ($db->type == "mysql" || $db->type == "mysqli") {
1680 $force_utf8_on_tables = GETPOST('force_utf8_on_tables', 'alpha');
1681
1682 $listoftables = $db->DDLListTablesFull($db->database_name);
1683
1684 // Disable foreign key checking for avoid errors
1685 if ($force_utf8_on_tables == 'confirmed') {
1686 $sql = 'SET FOREIGN_KEY_CHECKS=0';
1687 print '<!-- '.$sql.' -->';
1688 print '<tr><td colspan="2">'.$sql.'</td></tr>';
1689 $resql = $db->query($sql);
1690 }
1691
1692 $foreignkeystorestore = array();
1693
1694 // First loop to delete foreign keys
1695 foreach ($listoftables as $table) {
1696 // do not convert llx_const if mysql encrypt/decrypt is used
1697 if ($conf->db->dolibarr_main_db_encryption != 0 && preg_match('/\_const$/', $table[0])) {
1698 continue;
1699 }
1700 if ($table[1] == 'VIEW') {
1701 print '<tr><td colspan="2">'.$table[0].' is a '.$table[1].' <span class="opacitymedium">(Skipped)</span></td></tr>';
1702 continue;
1703 }
1704
1705 // Special case of tables with foreign key on varchar fields
1706 $arrayofforeignkey = array(
1707 'llx_accounting_account' => 'fk_accounting_account_fk_pcg_version',
1708 'llx_accounting_system' => 'fk_accounting_account_fk_pcg_version',
1709 'llx_c_type_contact' => 'fk_societe_commerciaux_fk_c_type_contact_code',
1710 'llx_societe_commerciaux' => 'fk_societe_commerciaux_fk_c_type_contact_code'
1711 );
1712
1713 foreach ($arrayofforeignkey as $tmptable => $foreignkeyname) {
1714 if ($table[0] == $tmptable) {
1715 print '<tr><td colspan="2">';
1716 $sqltmp = "ALTER TABLE ".$db->sanitize($table[0])." DROP FOREIGN KEY ".$db->sanitize($foreignkeyname);
1717 print $sqltmp;
1718 if ($force_utf8_on_tables == 'confirmed') {
1719 $resqltmp = $db->query($sqltmp);
1720 } else {
1721 print ' - <span class="opacitymedium">Disabled</span>';
1722 }
1723 print '</td></tr>';
1724 $foreignkeystorestore[$tmptable] = $foreignkeyname;
1725 }
1726 }
1727 }
1728
1729 foreach ($listoftables as $table) {
1730 // do not convert llx_const if mysql encrypt/decrypt is used
1731 if ($conf->db->dolibarr_main_db_encryption != 0 && preg_match('/\_const$/', $table[0])) {
1732 continue;
1733 }
1734 if ($table[1] == 'VIEW') {
1735 print '<tr><td colspan="2">'.$table[0].' is a '.$table[1].' <span class="opacitymedium">(Skipped)</span></td></tr>';
1736 continue;
1737 }
1738
1739 $collation = 'utf8_unicode_ci';
1740 $defaultcollation = $db->getDefaultCollationDatabase();
1741 if (preg_match('/general/', $defaultcollation)) {
1742 $collation = 'utf8_general_ci';
1743 }
1744
1745 print '<tr><td colspan="2">';
1746 print $table[0];
1747 $sql1 = "ALTER TABLE ".$db->sanitize($table[0])." ROW_FORMAT=dynamic";
1748 $sql2 = "ALTER TABLE ".$db->sanitize($table[0])." CONVERT TO CHARACTER SET utf8 COLLATE ".$db->sanitize($collation);
1749 print '<!-- '.$sql1.' -->';
1750 print '<!-- '.$sql2.' -->';
1751 if ($force_utf8_on_tables == 'confirmed') {
1752 $resql1 = $db->query($sql1);
1753 if ($resql1) {
1754 $resql2 = $db->query($sql2);
1755 } else {
1756 $resql2 = false;
1757 }
1758 print ' - Done '.(($resql1 && $resql2) ? '<span class="opacitymedium">(OK)</span>' : '<span class="error" title="'.dol_escape_htmltag($db->lasterror).'">(KO)</span>');
1759 } else {
1760 print ' - <span class="opacitymedium">Disabled</span>';
1761 }
1762 print '</td></tr>';
1763 flush();
1764 if (ob_get_level() > 0) {
1765 ob_flush();
1766 }
1767 }
1768
1769 // Restore dropped foreign keys
1770 foreach ($foreignkeystorestore as $tmptable => $foreignkeyname) {
1771 $stringtofindinline = "ALTER TABLE .* ADD CONSTRAINT ".$db->sanitize($foreignkeyname);
1772 $fileforkeys = DOL_DOCUMENT_ROOT.'/install/mysql/tables/'.$tmptable.'.key.sql';
1773 //print 'Search in '.$fileforkeys.' to get '.$stringtofindinline."<br>\n";
1774
1775 $handle = fopen($fileforkeys, 'r');
1776 if ($handle) {
1777 while (($line = fgets($handle)) !== false) {
1778 // Process the line read.
1779 if (preg_match('/^'.$stringtofindinline.'/i', $line)) {
1780 $resqltmp = $db->query($line);
1781 print '<tr><td colspan="2">';
1782 print $line;
1783 print ' - Done '.($resqltmp ? '<span class="opacitymedium">(OK)</span>' : '<span class="error" title="'.dol_escape_htmltag($db->lasterror).'">(KO)</span>');
1784 print '</td></tr>';
1785 break;
1786 }
1787 }
1788 fclose($handle);
1789 }
1790 flush();
1791 if (ob_get_level() > 0) {
1792 ob_flush();
1793 }
1794 }
1795
1796 // Enable foreign key checking
1797 if ($force_utf8_on_tables == 'confirmed') {
1798 $sql = 'SET FOREIGN_KEY_CHECKS=1';
1799 print '<!-- '.$sql.' -->';
1800 print '<tr><td colspan="2">'.$sql.'</td></tr>';
1801 $resql = $db->query($sql);
1802 }
1803 } else {
1804 print '<tr><td colspan="2">Not available with database type '.$db->type.'</td></tr>';
1805 }
1806}
1807
1808// force utf8mb4 on tables EXPERIMENTAL !
1809if ($ok && GETPOST('force_utf8mb4_on_tables', 'alpha')) {
1810 print '<tr><td colspan="2"><br>*** Force page code and collation of tables into utf8mb4/utf8mb4_unicode_ci (for mysql/mariadb only)</td></tr>';
1811
1812 if ($db->type == "mysql" || $db->type == "mysqli") {
1813 $force_utf8mb4_on_tables = GETPOST('force_utf8mb4_on_tables', 'alpha');
1814
1815
1816 $listoftables = $db->DDLListTablesFull($db->database_name);
1817
1818 // Disable foreign key checking for avoid errors
1819 if ($force_utf8mb4_on_tables == 'confirmed') {
1820 $sql = 'SET FOREIGN_KEY_CHECKS=0';
1821 print '<!-- '.$sql.' -->';
1822 print '<tr><td colspan="2">'.$sql.'</td></tr>';
1823 $resql = $db->query($sql);
1824 }
1825
1826 $foreignkeystorestore = array();
1827
1828 // First loop to delete foreign keys
1829 foreach ($listoftables as $table) {
1830 // do not convert llx_const if mysql encrypt/decrypt is used
1831 if ($conf->db->dolibarr_main_db_encryption != 0 && preg_match('/\_const$/', $table[0])) {
1832 continue;
1833 }
1834 if ($table[1] == 'VIEW') {
1835 print '<tr><td colspan="2">'.$table[0].' is a '.$table[1].' <span class="opacitymedium">(Skipped)</span></td></tr>';
1836 continue;
1837 }
1838
1839 // Special case of tables with foreign key on varchar fields
1840 $arrayofforeignkey = array(
1841 'llx_accounting_account' => 'fk_accounting_account_fk_pcg_version',
1842 'llx_accounting_system' => 'fk_accounting_account_fk_pcg_version',
1843 'llx_c_type_contact' => 'fk_societe_commerciaux_fk_c_type_contact_code',
1844 'llx_societe_commerciaux' => 'fk_societe_commerciaux_fk_c_type_contact_code'
1845 );
1846
1847 foreach ($arrayofforeignkey as $tmptable => $foreignkeyname) {
1848 if ($table[0] == $tmptable) {
1849 print '<tr><td colspan="2">';
1850 $sqltmp = "ALTER TABLE ".$db->sanitize($table[0])." DROP FOREIGN KEY ".$db->sanitize($foreignkeyname);
1851 print $sqltmp;
1852 if ($force_utf8mb4_on_tables == 'confirmed') {
1853 $resqltmp = $db->query($sqltmp);
1854 } else {
1855 print ' - <span class="opacitymedium">Disabled</span>';
1856 }
1857 print '</td></tr>';
1858 $foreignkeystorestore[$tmptable] = $foreignkeyname;
1859 }
1860 }
1861 }
1862
1863 foreach ($listoftables as $table) {
1864 // do not convert llx_const if mysql encrypt/decrypt is used
1865 if ($conf->db->dolibarr_main_db_encryption != 0 && preg_match('/\_const$/', $table[0])) {
1866 continue;
1867 }
1868 if ($table[1] == 'VIEW') {
1869 print '<tr><td colspan="2">'.$table[0].' is a '.$table[1].' <span class="opacitymedium">(Skipped)</span></td></tr>';
1870 continue;
1871 }
1872
1873 $collation = 'utf8mb4_unicode_ci';
1874 $defaultcollation = $db->getDefaultCollationDatabase();
1875 if (preg_match('/general/', $defaultcollation)) {
1876 $collation = 'utf8mb4_general_ci';
1877 }
1878
1879 print '<tr><td colspan="2">';
1880 print $table[0];
1881 $sql1 = "ALTER TABLE ".$db->sanitize($table[0])." ROW_FORMAT=dynamic";
1882 $sql2 = "ALTER TABLE ".$db->sanitize($table[0])." CONVERT TO CHARACTER SET utf8mb4 COLLATE ".$db->sanitize($collation);
1883 print '<!-- '.$sql1.' -->';
1884 print '<!-- '.$sql2.' -->';
1885 if ($force_utf8mb4_on_tables == 'confirmed') {
1886 $resql1 = $db->query($sql1);
1887 if ($resql1) {
1888 $resql2 = $db->query($sql2);
1889 } else {
1890 $resql2 = false;
1891 }
1892 print ' - Done '.(($resql1 && $resql2) ? '<span class="opacitymedium">(OK)</span>' : '<span class="error" title="'.dol_escape_htmltag($db->lasterror).'">(KO)</span>');
1893 } else {
1894 print ' - <span class="opacitymedium">Disabled</span>';
1895 }
1896 print '</td></tr>';
1897 flush();
1898 if (ob_get_level() > 0) {
1899 ob_flush();
1900 }
1901 }
1902
1903 // Restore dropped foreign keys
1904 foreach ($foreignkeystorestore as $tmptable => $foreignkeyname) {
1905 $stringtofindinline = "ALTER TABLE .* ADD CONSTRAINT ".$db->sanitize($foreignkeyname);
1906 $fileforkeys = DOL_DOCUMENT_ROOT.'/install/mysql/tables/'.$tmptable.'.key.sql';
1907 //print 'Search in '.$fileforkeys.' to get '.$stringtofindinline."<br>\n";
1908
1909 $handle = fopen($fileforkeys, 'r');
1910 if ($handle) {
1911 while (($line = fgets($handle)) !== false) {
1912 // Process the line read.
1913 if (preg_match('/^'.$stringtofindinline.'/i', $line)) {
1914 $resqltmp = $db->query($line);
1915 print '<tr><td colspan="2">';
1916 print $line;
1917 print ' - Done '.($resqltmp ? '<span class="opacitymedium">(OK)</span>' : '<span class="error" title="'.dol_escape_htmltag($db->lasterror).'">(KO)</span>');
1918 print '</td></tr>';
1919 break;
1920 }
1921 }
1922 fclose($handle);
1923 }
1924 flush();
1925 if (ob_get_level() > 0) {
1926 ob_flush();
1927 }
1928 }
1929
1930 // Enable foreign key checking
1931 if ($force_utf8mb4_on_tables == 'confirmed') {
1932 $sql = 'SET FOREIGN_KEY_CHECKS=1';
1933 print '<!-- '.$sql.' -->';
1934 print '<tr><td colspan="2">'.$sql.'</td></tr>';
1935 $resql = $db->query($sql);
1936 }
1937 } else {
1938 print '<tr><td colspan="2">Not available with database type '.$db->type.'</td></tr>';
1939 }
1940}
1941
1942if ($ok && GETPOST('force_collation_from_conf_on_tables', 'alpha')) {
1943 print '<tr><td colspan="2"><br>*** Force page code and collation of tables into '.$conf->db->character_set.'/'.$conf->db->dolibarr_main_db_collation.' and row_format=dynamic (for mysql/mariadb only)</td></tr>';
1944
1945 if ($db->type == "mysql" || $db->type == "mysqli") {
1946 $force_collation_from_conf_on_tables = GETPOST('force_collation_from_conf_on_tables', 'alpha');
1947
1948 $listoftables = $db->DDLListTablesFull($db->database_name);
1949
1950 // Disable foreign key checking for avoid errors
1951 if ($force_collation_from_conf_on_tables == 'confirmed') {
1952 $sql = 'SET FOREIGN_KEY_CHECKS=0';
1953 print '<!-- '.$sql.' -->';
1954 $resql = $db->query($sql);
1955 }
1956
1957 foreach ($listoftables as $table) {
1958 // do not convert collation on llx_const if mysql encrypt/decrypt is used
1959 if ($conf->db->dolibarr_main_db_encryption != 0 && preg_match('/\_const$/', $table[0])) {
1960 continue;
1961 }
1962 if ($table[1] == 'VIEW') {
1963 print '<tr><td colspan="2">'.$table[0].' is a '.$table[1].' (Skipped)</td></tr>';
1964 continue;
1965 }
1966
1967 print '<tr><td colspan="2">';
1968 print $table[0];
1969 $sql1 = "ALTER TABLE ".$table[0]." ROW_FORMAT=dynamic"; // @phan-suppress-current-line SqlInjection
1970 $sql2 = "ALTER TABLE ".$table[0]." CONVERT TO CHARACTER SET ".$conf->db->character_set." COLLATE ".$conf->db->dolibarr_main_db_collation; // @phan-suppress-current-line SqlInjection
1971 print '<!-- '.$sql1.' -->';
1972 print '<!-- '.$sql2.' -->';
1973 if ($force_collation_from_conf_on_tables == 'confirmed') {
1974 $resql1 = $db->query($sql1);
1975 if ($resql1) {
1976 $resql2 = $db->query($sql2);
1977 } else {
1978 $resql2 = false;
1979 }
1980 print ' - Done '.(($resql1 && $resql2) ? '<span class="opacitymedium">(OK)</span>' : '<span class="error" title="'.dol_escape_htmltag($db->lasterror).'">(KO)</span>');
1981 } else {
1982 print ' - <span class="opacitymedium">Disabled</span>';
1983 }
1984 print '</td></tr>';
1985 }
1986
1987 // Enable foreign key checking
1988 if ($force_collation_from_conf_on_tables == 'confirmed') {
1989 $sql = 'SET FOREIGN_KEY_CHECKS=1';
1990 print '<!-- '.$sql.' -->';
1991 $resql = $db->query($sql);
1992 }
1993 } else {
1994 print '<tr><td colspan="2">Not available with database type '.$db->type.'</td></tr>';
1995 }
1996}
1997
1998// rebuild sequences for pgsql
1999if ($ok && GETPOST('rebuild_sequences', 'alpha')) {
2000 print '<tr><td colspan="2"><br>*** Force to rebuild sequences (for postgresql only)</td></tr>';
2001
2002 if ($db->type == "pgsql") {
2003 $rebuild_sequence = GETPOST('rebuild_sequences', 'alpha');
2004
2005 if ($rebuild_sequence == 'confirmed') {
2006 $sql = "SELECT dol_util_rebuild_sequences();";
2007 print '<!-- '.$sql.' -->';
2008 $resql = $db->query($sql);
2009 }
2010 } else {
2011 print '<tr><td colspan="2">Not available with database type '.$db->type.'</td></tr>';
2012 }
2013}
2014
2015//
2016if ($ok && GETPOST('repair_link_dispatch_lines_supplier_order_lines')) {
2017 /*
2018 * This script is meant to be run when upgrading from a dolibarr version < 3.8
2019 * to a newer version.
2020 *
2021 * Version 3.8 introduces a new column in llx_commande_fournisseur_dispatch, which
2022 * matches the dispatch to a specific supplier order line (so that if there are
2023 * several with the same product, the user can specifically tell which products of
2024 * which line were dispatched where).
2025 *
2026 * However when migrating, the new column has a default value of 0, which means that
2027 * old supplier orders whose lines were dispatched using the old dolibarr version
2028 * have unspecific dispatch lines, which are not taken into account by the new version,
2029 * thus making the order look like it was never dispatched at all.
2030 *
2031 * This scripts sets this foreign key to the first matching supplier order line whose
2032 * product (and supplier order of course) are the same as the dispatch’s.
2033 *
2034 * If the dispatched quantity is more than indicated on the order line (this happens if
2035 * there are several order lines for the same product), it creates new dispatch lines
2036 * pointing to the other order lines accordingly, until all the dispatched quantity is
2037 * accounted for.
2038 */
2039
2040 $repair_link_dispatch_lines_supplier_order_lines = GETPOST('repair_link_dispatch_lines_supplier_order_lines', 'alpha');
2041
2042
2043 echo '<tr><th>Repair llx_receptiondet_batch.fk_commandefourndet</th></tr>';
2044 echo '<tr><td>Repair in progress. This may take a while.</td></tr>';
2045
2046 $sql_dispatch = 'SELECT * FROM '.MAIN_DB_PREFIX.'receptiondet_batch WHERE COALESCE(fk_elementdet, 0) = 0';
2047 $db->begin();
2048 $resql_dispatch = $db->query($sql_dispatch);
2049 $n_processed_rows = 0;
2050 $errors = array();
2051 if ($resql_dispatch) {
2052 if ($db->num_rows($resql_dispatch) == 0) {
2053 echo '<tr><td>Nothing to do.</td></tr>';
2054 exit;
2055 }
2056 while ($obj_dispatch = $db->fetch_object($resql_dispatch)) {
2057 $sql_line = 'SELECT line.rowid, line.qty FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet AS line';
2058 $sql_line .= ' WHERE line.fk_commande = '.((int) $obj_dispatch->fk_commande);
2059 $sql_line .= ' AND line.fk_product = '.((int) $obj_dispatch->fk_product);
2060 $resql_line = $db->query($sql_line);
2061
2062 // In case there are multiple line with the same product for this supplier order,
2063 // split the dispatch line in as many lines as there are on the order for the product,
2064 // and set the line quantity to a value within the limit the "budget" set in dispatch.qty
2065
2066 $remaining_qty = $obj_dispatch->qty;
2067 $first_iteration = true;
2068 if (!$resql_line) {
2069 echo '<tr><td>Unable to find a matching supplier order line for dispatch #'.$obj_dispatch->rowid.'</td></tr>';
2070 $errors[] = $sql_line;
2071 $n_processed_rows++;
2072 continue;
2073 }
2074 if ($db->num_rows($resql_line) == 0) {
2075 continue;
2076 }
2077 while ($obj_line = $db->fetch_object($resql_line)) {
2078 if (!$remaining_qty) {
2079 break;
2080 }
2081 if (!$obj_line->rowid) {
2082 continue;
2083 }
2084 $qty_for_line = min($remaining_qty, $obj_line->qty);
2085 if ($first_iteration) {
2086 $sql_attach = 'UPDATE '.MAIN_DB_PREFIX.'receptiondet_batch';
2087 $sql_attach .= ' SET fk_elementdet = '.((int) $obj_line->rowid).', qty = '.((float) $qty_for_line);
2088 $sql_attach .= ' WHERE rowid = '.((int) $obj_dispatch->rowid);
2089 $first_iteration = false;
2090 } else {
2091 $sql_attach_values = array(
2092 (string) ((int) $obj_dispatch->fk_element),
2093 (string) ((int) $obj_dispatch->fk_product),
2094 (string) ((int) $obj_line->rowid),
2095 (string) ((float) $qty_for_line),
2096 (string) ((int) $obj_dispatch->fk_entrepot),
2097 (string) ((int) $obj_dispatch->fk_user),
2098 $obj_dispatch->datec ? "'".$db->idate($db->jdate($obj_dispatch->datec))."'" : 'NULL',
2099 $obj_dispatch->comment ? "'".$db->escape($obj_dispatch->comment)."'" : 'NULL',
2100 $obj_dispatch->status ? (string) ((int) $obj_dispatch->status) : 'NULL',
2101 $obj_dispatch->tms ? "'".$db->idate($db->jdate($obj_dispatch->tms))."'" : 'NULL',
2102 $obj_dispatch->batch ? "'".$db->escape($obj_dispatch->batch)."'" : 'NULL',
2103 $obj_dispatch->eatby ? "'".$db->escape($obj_dispatch->eatby)."'" : 'NULL',
2104 $obj_dispatch->sellby ? "'".$db->escape($obj_dispatch->sellby)."'" : 'NULL'
2105 );
2106 $sql_attach_values = implode(', ', $sql_attach_values);
2107
2108 $sql_attach = 'INSERT INTO '.MAIN_DB_PREFIX.'receptiondet_batch';
2109 $sql_attach .= ' (fk_element, fk_product, fk_elementdet, qty, fk_entrepot, fk_user, datec, comment, status, tms, batch, eatby, sellby)';
2110 $sql_attach .= " VALUES (".$sql_attach_values.")"; // The string is already sanitized
2111 }
2112
2113 if ($repair_link_dispatch_lines_supplier_order_lines == 'confirmed') {
2114 $resql_attach = $db->query($sql_attach);
2115 } else {
2116 $resql_attach = true; // Force success in test mode
2117 }
2118
2119 if ($resql_attach) {
2120 $remaining_qty -= $qty_for_line;
2121 } else {
2122 $errors[] = $sql_attach;
2123 }
2124
2125 $first_iteration = false;
2126 }
2127 $n_processed_rows++;
2128
2129 // report progress every 256th row
2130 if (!($n_processed_rows & 0xff)) {
2131 echo '<tr><td>Processed '.$n_processed_rows.' rows with '.count($errors).' errors…'."</td></tr>\n";
2132 flush();
2133 if (ob_get_level() > 0) {
2134 ob_flush();
2135 }
2136 }
2137 }
2138 } else {
2139 echo '<tr><td>Unable to find any dispatch without an fk_commandefourndet.'."</td></tr>\n";
2140 echo $sql_dispatch."\n";
2141 }
2142 echo '<tr><td>Fixed '.$n_processed_rows.' rows with '.count($errors).' errors…'."</td></tr>\n";
2143 echo '<tr><td>DONE.'."</td></tr>\n";
2144
2145 if (count($errors)) {
2146 $db->rollback();
2147 echo '<tr><td>The transaction was rolled back due to errors: nothing was changed by the script.</td></tr>';
2148 } else {
2149 $db->commit();
2150 }
2151 $db->close();
2152
2153 echo '<tr><td><h3>SQL queries with errors:</h3></tr></td>';
2154 echo '<tr><td>'.implode('</td></tr><tr><td>', $errors).'</td></tr>';
2155}
2156
2157// Repair llx_commande_fournisseur to eliminate duplicate reference
2158if ($ok && GETPOST('repair_supplier_order_duplicate_ref')) {
2159 require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.commande.class.php';
2160 include_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
2161
2162 $db->begin();
2163
2164 $err = 0;
2165
2166 // Query to find all duplicate supplier orders
2167 $sql = "SELECT * FROM " . MAIN_DB_PREFIX . "commande_fournisseur";
2168 $sql .= " WHERE entity = ".((int) $conf->entity);
2169 $sql .= " AND ref IN (SELECT cf.ref FROM " . MAIN_DB_PREFIX . "commande_fournisseur cf WHERE cf.entity = ".((int) $conf->entity)." GROUP BY cf.ref HAVING COUNT(cf.rowid) > 1)";
2170 $sql .= " ORDER BY rowid";
2171
2172 // Build a list of ref => []CommandeFournisseur
2173 $duplicateSupplierOrders = [];
2174 $resql = $db->query($sql);
2175 if ($resql) {
2176 while ($rawSupplierOrder = $db->fetch_object($resql)) {
2177 $supplierOrder = new CommandeFournisseur($db);
2178 $supplierOrder->setVarsFromFetchObj($rawSupplierOrder);
2179
2180 $duplicateSupplierOrders[$rawSupplierOrder->ref] [] = $supplierOrder;
2181 }
2182 } else {
2183 $err++;
2184 }
2185
2186 // Process all duplicate supplier order and regenerate the reference for all except the first one
2187 foreach ($duplicateSupplierOrders as $ref => $supplierOrders) {
2189 foreach (array_slice($supplierOrders, 1) as $supplierOrder) {
2190 // Definition of supplier order numbering model name
2191 $soc = new Societe($db);
2192 $soc->fetch((int) $supplierOrder->fourn_id);
2193
2194 $newRef = $supplierOrder->getNextNumRef($soc);
2195
2196 $sql = "UPDATE " . MAIN_DB_PREFIX . "commande_fournisseur cf SET cf.ref = '" . $db->escape($newRef) . "' WHERE cf.rowid = " . (int) $supplierOrder->id;
2197 $sql .= " AND cf.entity = ".((int) $conf->entity);
2198 if (!$db->query($sql)) {
2199 $err++;
2200 }
2201 }
2202 }
2203
2204 if ($err == 0) {
2205 $db->commit();
2206 } else {
2207 $db->rollback();
2208 }
2209}
2210
2211// Repair llx_invoice to calculate totals from line items
2212// WARNING : The process can be long on production environments due to restrictions.
2213// consider raising php_max_execution time if failing to execute completely.
2214if ($ok && GETPOST('recalculateinvoicetotal') == 'confirmed') {
2215 $err = 0;
2216 $db->begin();
2217 $sql = "
2218 SELECT
2219 f.rowid,
2220 SUM(fd.total_ht) as total_ht
2221 FROM ".MAIN_DB_PREFIX."facture f
2222 LEFT JOIN ".MAIN_DB_PREFIX."facturedet fd
2223 ON fd.fk_facture = f.rowid
2224 WHERE f.total_ht = 0
2225 GROUP BY fd.fk_facture HAVING SUM(fd.total_ht) <> 0";
2226 $resql = $db->query($sql);
2227 if ($resql) {
2228 $num = $db->num_rows($resql);
2229 print "We found ".$num." factures qualified that will have their total recalculated because they are at zero and line items not at zero\n";
2230 dol_syslog("We found ".$num." factures qualified that will have their total recalculated because they are at zero and line items not at zero");
2231
2232 if ($num) {
2233 $i = 0;
2234 while ($i < $num) {
2235 $obj = $db->fetch_object($resql);
2236 $sql_calculs = "
2237 SELECT
2238 SUM(fd.total_ht) as 'total_ht',
2239 SUM(fd.total_tva) as 'total_tva',
2240 SUM(fd.total_localtax1) as 'localtax1',
2241 SUM(fd.total_localtax2) as 'localtax2',
2242 SUM(fd.total_ttc) as 'total_ttc'
2243 FROM
2244 ".MAIN_DB_PREFIX."facturedet fd
2245 WHERE
2246 fd.fk_facture = ".((int) $obj->rowid);
2247 $ressql_calculs = $db->query($sql_calculs);
2248 while ($obj_calcul = $db->fetch_object($ressql_calculs)) {
2249 // Calculate the sum of received payments
2250 $sql_paiements = "SELECT SUM(amount) as somme from ".MAIN_DB_PREFIX."paiement_facture WHERE fk_facture = ".((int) $obj->rowid);
2251 $montantPaiements = $db->fetch_object($db->query($sql_paiements))->somme;
2252 $totHt = ($obj_calcul->total_ht ? price2num($obj_calcul->total_ht, 'MT') : 0);
2253 $totTva = ($obj_calcul->total_tva ? price2num($obj_calcul->total_tva, 'MT') : 0);
2254 $totLocal1 = ($obj_calcul->localtax1 ? price2num($obj_calcul->localtax1, 'MT') : 0);
2255 $totLocal2 = ($obj_calcul->localtax2 ? price2num($obj_calcul->localtax2, 'MT') : 0);
2256 $totTtc = $totHt + $totTva + $totLocal1 + $totLocal2;
2257 $sql_maj = "
2258 UPDATE ".MAIN_DB_PREFIX."facture
2259 SET
2260 total_ht = ".((float) $totHt).",
2261 total_tva = ".((float) $totTva).",
2262 localtax1 = ".((float) $totLocal1).",
2263 localtax2 = ".((float) $totLocal2).",
2264 total_ttc = ".((float) $totTtc).",
2265 fk_statut = ".($totTtc == price2num($montantPaiements, 'MT') ? 2 : 1).",
2266 paid = ".($totTtc == price2num($montantPaiements, 'MT') ? 1 : 0)."
2267 WHERE
2268 rowid = ".((int) $obj->rowid);
2269 $db->query($sql_maj);
2270 }
2271 $i++;
2272 }
2273 } else {
2274 print "Pas de factures à traiter\n";
2275 }
2276 } else {
2277 dol_print_error($db);
2278 dol_syslog("calculate_total_and_taxes.php: Error");
2279 $err++;
2280 }
2281
2282 if ($err == 0) {
2283 $db->commit();
2284 } else {
2285 $db->rollback();
2286 }
2287}
2288
2289// Repair mailing path
2290if ($ok && GETPOST('repair_mailing_path')) {
2291 global $user;
2292 $sav_user = is_object($user) ? clone $user : $user;
2293
2294 require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/mailing.class.php';
2295 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
2296
2297 print '<tr><td colspan="2"><br>*** Repair mailing path<br>';
2298
2305 function migrate_mailing_filespath($mailing)
2306 {
2307 global $db, $conf, $user;
2308
2309 $dir = $conf->mailing->dir_output;
2310 $origin = $dir.'/'.get_exdir($mailing->id, 2, 0, 1, $mailing, 'mailing');
2311 $destin = $dir.'/'.get_exdir($mailing->id, 0, 0, 1, $mailing, 'mailing');
2312
2313 $origin_osencoded = dol_osencode($origin);
2314 $destin_osencoded = dol_osencode($destin);
2315 dol_mkdir($destin);
2316
2317 $user = new User($db);
2318 $user->fetch($mailing->user_creation_id);
2319
2320 if (dol_is_dir($origin)) {
2321 $handle = opendir($origin_osencoded);
2322 if (is_resource($handle)) {
2323 while (($file = readdir($handle)) !== false) {
2324 if ($file != '.' && $file != '..' && is_dir($origin_osencoded.'/'.$file)) {
2325 $thumbs = opendir($origin_osencoded.'/'.$file);
2326 if (is_resource($thumbs)) {
2327 dol_mkdir($destin.'/'.$file);
2328 while (($thumb = readdir($thumbs)) !== false) {
2329 $res = dol_move($origin.'/'.$file.'/'.$thumb, $destin.'/'.$file.'/'.$thumb);
2330 $msg = ($res ? ' * Migration successful' : 'Migration failed') . ' for file '.$origin.'/'.$file.'.<br>';
2331 print($msg);
2332 }
2333 // dol_delete_dir($origin.'/'.$file);
2334 }
2335 } else {
2336 if (dol_is_file($origin.'/'.$file)) {
2337 $res = dol_move($origin.'/'.$file, $destin.'/'.$file);
2338 $msg = ($res ? ' * Migration successful' : 'Migration failed') . ' for file '.$origin.'/'.$file.'.<br>';
2339 print($msg);
2340 }
2341 }
2342 }
2343 }
2344 }
2345 }
2346
2347 $mailing = new Mailing($db);
2348
2349 $sql = "SELECT rowid as mid from ".MAIN_DB_PREFIX."mailing"; // Get list of all mailing
2350 $resql = $db->query($sql);
2351 if ($resql) {
2352 while ($obj = $db->fetch_object($resql)) {
2353 $mailing->fetch($obj->mid);
2354 print "Migrating mailing id=".$mailing->id." ref=".$mailing->ref."<br>\n";
2355 migrate_mailing_filespath($mailing);
2356 }
2357 } else {
2358 $ok = 0;
2359 dol_print_error($db);
2360 }
2361
2362 $user = $sav_user;
2363
2364 print '</td></tr>';
2365}
2366
2367if ($imagerepairaction !== '' && $error) {
2368 $ok = 0;
2369 print '<tr><td class="error">'.$langs->trans('RepairImagesFailed').'</td></tr>';
2370}
2371
2372if ($ok && $imagerepairpost && !$error) {
2373 setEventMessages($langs->trans('RepairImagesCompleted', dol_escape_htmltag($ecmrepairentities[$imagerepairentity])), null, 'mesgs');
2374 while (ob_get_level() > $ecmrepairbufferlevel) {
2375 ob_end_clean();
2376 }
2377 $db->close();
2378 header('Location: '.$_SERVER['PHP_SELF'].'?'.$imagerepairaction.'=test&'.$imagerepairaction.'_entity='.((int) $imagerepairentity).'&selectlang='.urlencode($setuplang), true, 303);
2379 exit;
2380}
2381
2382print '</table>';
2383
2384if (empty($actiondone)) {
2385 print '<div class="error">'.$langs->trans("ErrorWrongParameters").'</div>';
2386}
2387
2388if ($oneoptionset) {
2389 print '<br>';
2390 print '<div class="center" style="padding-top: 10px"><a href="../index.php?mainmenu=home&leftmenu=home'.(GETPOSTISSET("login") ? '&username='.urlencode(GETPOST("login")) : '').'">';
2391 print img_picto('', 'url', 'class="pictofixedwidth"');
2392 print $langs->trans("GoToDolibarr");
2393 print '</a></div>';
2394}
2395
2396dolibarr_install_syslog("--- repair: end");
2397pFooter(1, $setuplang);
2398
2399if ($db->connected) {
2400 $db->close();
2401}
2402
2403// Return code if ran from command line
2404if (!$ok && isset($argv[1])) {
2405 exit(1);
2406}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
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.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class for managing the social charges.
Class to manage predefined suppliers products.
Class to manage customers orders.
Class to manage standard extra fields.
Class to manage suppliers invoices.
Class to manage invoices.
Class to manage generation of HTML components Only common components must be here.
Class to manage emailings module.
Class to manage products or services.
Class to manage proposals.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
$conffile
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
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_delete_dir($dir, $nophperrors=0)
Remove a directory (not recursive, so content must be empty).
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
dol_is_dir($folder)
Test if filename is a directory.
dol_html_entity_decode($a, $b, $c='UTF-8', $keepsomeentities=0)
Replace html_entity_decode functions to manage errors.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
getDoliDBInstance($type, $host, $user, $pass, $name, $port, $forcenew=false)
Return a DoliDB instance (database handler).
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getMultidirOutput($object, $module='', $forobject=0, $mode='output')
Return the full path of the directory where a module (or an object of a module) stores its files.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
isModEnabled($module)
Is Dolibarr module enabled.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_htmloutput_events($disabledoutputofmessages=0)
Print formatted messages to output (Used to show messages on html output).
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
pHeader($subtitle, $next, $action='set', $param='', $forcejqueryurl='', $csstable='main-inside')
Show HTML header of install pages.
Definition inc.php:553
pFooter($nonext=0, $setuplang='', $jscheckfunction='', $withpleasewait=0, $morehtml='')
Print HTML footer of install pages.
Definition inc.php:647
dolibarr_install_syslog($message, $level=LOG_DEBUG)
Log function for install pages.
Definition inc.php:711
clean_data_ecm_directories()
Clean data into ecm_directories table.
repairEcmFiles($db, $entity, $documentroot, $confirmed=false, $maxdelete=100)
Check an entity's ECM index against the filesystem, optionally removing missing-file entries.
repairImagePathIsSafe($path, $directory, $documentroot)
Check an image repair path, including a missing destination, against its owner's directory.
dol_decode($chain, $key='1')
Decode a base 64 encoded + specific delta change.
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.