repair.php 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678
  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 Frédéric France <frederic.france@free.fr>
  7. * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  21. */
  22. /**
  23. * \file htdocs/install/repair.php
  24. * \brief Run repair script
  25. */
  26. include_once 'inc.php';
  27. if (file_exists($conffile)) {
  28. include_once $conffile;
  29. }
  30. require_once $dolibarr_main_document_root.'/core/lib/admin.lib.php';
  31. include_once $dolibarr_main_document_root.'/core/lib/images.lib.php';
  32. require_once $dolibarr_main_document_root.'/core/class/extrafields.class.php';
  33. require_once 'lib/repair.lib.php';
  34. $step = 2;
  35. $ok = 0;
  36. // Cette page peut etre longue. On augmente le delai autorise.
  37. // Ne fonctionne que si on est pas en safe_mode.
  38. $err = error_reporting();
  39. error_reporting(0);
  40. @set_time_limit(120);
  41. error_reporting($err);
  42. $setuplang = GETPOST("selectlang", 'aZ09', 3) ? GETPOST("selectlang", 'aZ09', 3) : 'auto';
  43. $langs->setDefaultLang($setuplang);
  44. $langs->loadLangs(array("admin", "install", "other"));
  45. if ($dolibarr_main_db_type == "mysqli") {
  46. $choix = 1;
  47. }
  48. if ($dolibarr_main_db_type == "pgsql") {
  49. $choix = 2;
  50. }
  51. if ($dolibarr_main_db_type == "mssql") {
  52. $choix = 3;
  53. }
  54. dolibarr_install_syslog("--- repair: entering upgrade.php page");
  55. if (!is_object($conf)) {
  56. dolibarr_install_syslog("repair: conf file not initialized", LOG_ERR);
  57. }
  58. /*
  59. * View
  60. */
  61. pHeader('', "upgrade2", GETPOST('action', 'aZ09'));
  62. // Action to launch the repair script
  63. $actiondone = 1;
  64. print '<h3>'.$langs->trans("Repair").'</h3>';
  65. print 'Option standard (\'test\' or \'confirmed\') is '.(GETPOST('standard', 'alpha') ? GETPOST('standard', 'alpha') : 'undefined').'<br>'."\n";
  66. // Disable modules
  67. print 'Option force_disable_of_modules_not_found (\'test\' or \'confirmed\') is '.(GETPOST('force_disable_of_modules_not_found', 'alpha') ? GETPOST('force_disable_of_modules_not_found', 'alpha') : 'undefined').'<br>'."\n";
  68. // Files
  69. print 'Option restore_thirdparties_logos (\'test\' or \'confirmed\') is '.(GETPOST('restore_thirdparties_logos', 'alpha') ? GETPOST('restore_thirdparties_logos', 'alpha') : 'undefined').'<br>'."\n";
  70. print 'Option restore_user_pictures (\'test\' or \'confirmed\') is '.(GETPOST('restore_user_pictures', 'alpha') ? GETPOST('restore_user_pictures', 'alpha') : 'undefined').'<br>'."\n";
  71. print 'Option rebuild_product_thumbs (\'test\' or \'confirmed\') is '.(GETPOST('rebuild_product_thumbs', 'alpha') ? GETPOST('rebuild_product_thumbs', 'alpha') : 'undefined').'<br>'."\n";
  72. // Clean tables and data
  73. print 'Option clean_linked_elements (\'test\' or \'confirmed\') is '.(GETPOST('clean_linked_elements', 'alpha') ? GETPOST('clean_linked_elements', 'alpha') : 'undefined').'<br>'."\n";
  74. print 'Option clean_menus (\'test\' or \'confirmed\') is '.(GETPOST('clean_menus', 'alpha') ? GETPOST('clean_menus', 'alpha') : 'undefined').'<br>'."\n";
  75. print 'Option clean_orphelin_dir (\'test\' or \'confirmed\') is '.(GETPOST('clean_orphelin_dir', 'alpha') ? GETPOST('clean_orphelin_dir', 'alpha') : 'undefined').'<br>'."\n";
  76. print 'Option clean_product_stock_batch (\'test\' or \'confirmed\') is '.(GETPOST('clean_product_stock_batch', 'alpha') ? GETPOST('clean_product_stock_batch', 'alpha') : 'undefined').'<br>'."\n";
  77. print 'Option clean_perm_table (\'test\' or \'confirmed\') is '.(GETPOST('clean_perm_table', 'alpha') ? GETPOST('clean_perm_table', 'alpha') : 'undefined').'<br>'."\n";
  78. print 'Option repair_link_dispatch_lines_supplier_order_lines, (\'test\' or \'confirmed\') is '.(GETPOST('repair_link_dispatch_lines_supplier_order_lines', 'alpha') ? GETPOST('repair_link_dispatch_lines_supplier_order_lines', 'alpha') : 'undefined').'<br>'."\n";
  79. // Init data
  80. print 'Option set_empty_time_spent_amount (\'test\' or \'confirmed\') is '.(GETPOST('set_empty_time_spent_amount', 'alpha') ? GETPOST('set_empty_time_spent_amount', 'alpha') : 'undefined').'<br>'."\n";
  81. // Structure
  82. print 'Option force_utf8_on_tables (force utf8 + row=dynamic), for mysql/mariadb only (\'test\' or \'confirmed\') is '.(GETPOST('force_utf8_on_tables', 'alpha') ? GETPOST('force_utf8_on_tables', 'alpha') : 'undefined').'<br>'."\n";
  83. print "Option force_utf8mb4_on_tables (force utf8mb4 + row=dynamic, EXPERIMENTAL!), for mysql/mariadb only ('test' or 'confirmed') is ".(GETPOST('force_utf8mb4_on_tables', 'alpha') ? GETPOST('force_utf8mb4_on_tables', 'alpha') : 'undefined')."<br>\n";
  84. print "Option force_collation_from_conf_on_tables (force ".$conf->db->character_set."/".$conf->db->dolibarr_main_db_collation." + row=dynamic), for mysql/mariadb only ('test' or 'confirmed') is ".(GETPOST('force_collation_from_conf_on_tables', 'alpha') ? GETPOST('force_collation_from_conf_on_tables', 'alpha') : 'undefined')."<br>\n";
  85. // Rebuild sequence
  86. print 'Option rebuild_sequences, for postgresql only (\'test\' or \'confirmed\') is '.(GETPOST('rebuild_sequences', 'alpha') ? GETPOST('rebuild_sequences', 'alpha') : 'undefined').'<br>'."\n";
  87. print '<br>';
  88. print '<table cellspacing="0" cellpadding="1" border="0" width="100%">';
  89. $error = 0;
  90. // If password is encoded, we decode it
  91. if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) {
  92. require_once $dolibarr_main_document_root.'/core/lib/security.lib.php';
  93. if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) {
  94. $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass);
  95. $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass);
  96. $dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially crypted
  97. } else {
  98. $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass);
  99. }
  100. }
  101. // $conf is already instancied inside inc.php
  102. $conf->db->type = $dolibarr_main_db_type;
  103. $conf->db->host = $dolibarr_main_db_host;
  104. $conf->db->port = $dolibarr_main_db_port;
  105. $conf->db->name = $dolibarr_main_db_name;
  106. $conf->db->user = $dolibarr_main_db_user;
  107. $conf->db->pass = $dolibarr_main_db_pass;
  108. // For encryption
  109. $conf->db->dolibarr_main_db_encryption = isset($dolibarr_main_db_encryption) ? $dolibarr_main_db_encryption : '';
  110. $conf->db->dolibarr_main_db_cryptkey = isset($dolibarr_main_db_cryptkey) ? $dolibarr_main_db_cryptkey : '';
  111. $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, (int) $conf->db->port);
  112. if ($db->connected) {
  113. print '<tr><td class="nowrap">';
  114. print $langs->trans("ServerConnection")." : $dolibarr_main_db_host</td><td class=\"right\">".$langs->trans("OK")."</td></tr>";
  115. dolibarr_install_syslog("repair: ".$langs->transnoentities("ServerConnection").": ".$dolibarr_main_db_host.$langs->transnoentities("OK"));
  116. $ok = 1;
  117. } else {
  118. print "<tr><td>".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name)."</td><td class=\"right\">".$langs->transnoentities("Error")."</td></tr>";
  119. dolibarr_install_syslog("repair: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name));
  120. $ok = 0;
  121. }
  122. if ($ok) {
  123. if ($db->database_selected) {
  124. print '<tr><td class="nowrap">';
  125. print $langs->trans("DatabaseConnection")." : ".$dolibarr_main_db_name."</td><td class=\"right\">".$langs->trans("OK")."</td></tr>";
  126. dolibarr_install_syslog("repair: database connection successful: ".$dolibarr_main_db_name);
  127. $ok = 1;
  128. } else {
  129. print "<tr><td>".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name)."</td><td class=\"right\">".$langs->trans("Error")."</td></tr>";
  130. dolibarr_install_syslog("repair: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name));
  131. $ok = 0;
  132. }
  133. }
  134. // Show database version
  135. if ($ok) {
  136. $version = $db->getVersion();
  137. $versionarray = $db->getVersionArray();
  138. print '<tr><td>'.$langs->trans("ServerVersion").'</td>';
  139. print '<td class="right">'.$version.'</td></tr>';
  140. dolibarr_install_syslog("repair: ".$langs->transnoentities("ServerVersion").": ".$version);
  141. //print '<td class="right">'.join('.',$versionarray).'</td></tr>';
  142. }
  143. $conf->setValues($db);
  144. // Reset forced setup after the setValues
  145. if (defined('SYSLOG_FILE')) {
  146. $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
  147. }
  148. $conf->global->MAIN_ENABLE_LOG_TO_HTML = 1;
  149. /* Start action here */
  150. $oneoptionset = 0;
  151. $oneoptionset = (GETPOST('standard', 'alpha') || GETPOST('restore_thirdparties_logos', 'alpha') || GETPOST('clean_linked_elements', 'alpha') || GETPOST('clean_menus', 'alpha')
  152. || GETPOST('clean_orphelin_dir', 'alpha') || GETPOST('clean_product_stock_batch', 'alpha') || GETPOST('set_empty_time_spent_amount', 'alpha') || GETPOST('rebuild_product_thumbs', 'alpha')
  153. || GETPOST('clean_perm_table', 'alpha')
  154. || GETPOST('force_disable_of_modules_not_found', 'alpha')
  155. || GETPOST('force_utf8_on_tables', 'alpha') || GETPOST('force_utf8mb4_on_tables', 'alpha') || GETPOST('force_collation_from_conf_on_tables', 'alpha')
  156. || GETPOST('rebuild_sequences', 'alpha'));
  157. if ($ok && $oneoptionset) {
  158. // Show wait message
  159. print '<tr><td colspan="2">'.$langs->trans("PleaseBePatient").'<br><br></td></tr>';
  160. flush();
  161. }
  162. // run_sql: Run repair SQL file
  163. if ($ok && GETPOST('standard', 'alpha')) {
  164. $dir = "mysql/migration/";
  165. $filelist = array();
  166. $i = 0;
  167. $ok = 0;
  168. // Recupere list fichier
  169. $filesindir = array();
  170. $handle = opendir($dir);
  171. if (is_resource($handle)) {
  172. while (($file = readdir($handle)) !== false) {
  173. if (preg_match('/\.sql$/i', $file)) {
  174. $filesindir[] = $file;
  175. }
  176. }
  177. }
  178. sort($filesindir);
  179. foreach ($filesindir as $file) {
  180. if (preg_match('/repair/i', $file)) {
  181. $filelist[] = $file;
  182. }
  183. }
  184. // Loop on each file
  185. foreach ($filelist as $file) {
  186. print '<tr><td class="nowrap">*** ';
  187. print $langs->trans("Script").'</td><td class="right">'.$file.'</td></tr>';
  188. $name = substr($file, 0, dol_strlen($file) - 4);
  189. // Run sql script
  190. $ok = run_sql($dir.$file, 0, '', 1);
  191. }
  192. }
  193. // sync_extrafields: Search list of fields declared and list of fields created into databases, then create fields missing
  194. if ($ok && GETPOST('standard', 'alpha')) {
  195. $extrafields = new ExtraFields($db);
  196. // List of tables that has an extrafield table
  197. $listofmodulesextra = array('societe'=>'societe', 'adherent'=>'adherent', 'product'=>'product',
  198. 'socpeople'=>'socpeople', 'propal'=>'propal', 'commande'=>'commande',
  199. 'facture'=>'facture', 'facturedet'=>'facturedet', 'facture_rec'=>'facture_rec', 'facturedet_rec'=>'facturedet_rec',
  200. 'supplier_proposal'=>'supplier_proposal', 'commande_fournisseur'=>'commande_fournisseur',
  201. 'facture_fourn'=>'facture_fourn', 'facture_fourn_rec'=>'facture_fourn_rec', 'facture_fourn_det'=>'facture_fourn_det', 'facture_fourn_det_rec'=>'facture_fourn_det_rec',
  202. 'fichinter'=>'fichinter', 'fichinterdet'=>'fichinterdet',
  203. 'inventory'=>'inventory',
  204. 'actioncomm'=>'actioncomm', 'bom_bom'=>'bom_bom', 'mrp_mo'=>'mrp_mo',
  205. 'adherent_type'=>'adherent_type', 'user'=>'user', 'partnership'=>'partnership', 'projet'=>'projet', 'projet_task'=>'projet_task', 'ticket'=>'ticket');
  206. //$listofmodulesextra = array('fichinter'=>'fichinter');
  207. print '<tr><td colspan="2"><br>*** Check fields into extra table structure match table of definition. If not add column into table</td></tr>';
  208. foreach ($listofmodulesextra as $tablename => $elementtype) {
  209. // Get list of fields
  210. $tableextra = MAIN_DB_PREFIX.$tablename.'_extrafields';
  211. // Define $arrayoffieldsdesc
  212. $arrayoffieldsdesc = $extrafields->fetch_name_optionals_label($elementtype);
  213. // Define $arrayoffieldsfound
  214. $arrayoffieldsfound = array();
  215. $resql = $db->DDLDescTable($tableextra);
  216. if ($resql) {
  217. print '<tr><td>Check availability of extra field for '.$tableextra;
  218. $i = 0;
  219. while ($obj = $db->fetch_object($resql)) {
  220. $fieldname = $fieldtype = '';
  221. if (preg_match('/mysql/', $db->type)) {
  222. $fieldname = $obj->Field;
  223. $fieldtype = $obj->Type;
  224. } else {
  225. $fieldname = isset($obj->Key) ? $obj->Key : $obj->attname;
  226. $fieldtype = isset($obj->Type) ? $obj->Type : 'varchar';
  227. }
  228. if (empty($fieldname)) {
  229. continue;
  230. }
  231. if (in_array($fieldname, array('rowid', 'tms', 'fk_object', 'import_key'))) {
  232. continue;
  233. }
  234. $arrayoffieldsfound[$fieldname] = array('type'=>$fieldtype);
  235. }
  236. print ' - Found '.count($arrayoffieldsfound).' fields into table';
  237. if (count($arrayoffieldsfound) > 0) {
  238. print ' <span class="opacitymedium">('.join(', ', array_keys($arrayoffieldsfound)).')</span>';
  239. }
  240. print '<br>'."\n";
  241. // If it does not match, we create fields
  242. foreach ($arrayoffieldsdesc as $code => $label) {
  243. if (!in_array($code, array_keys($arrayoffieldsfound))) {
  244. print 'Found field '.$code.' declared into '.MAIN_DB_PREFIX.'extrafields table but not found into desc of table '.$tableextra." -> ";
  245. $type = $extrafields->attributes[$elementtype]['type'][$code];
  246. $length = $extrafields->attributes[$elementtype]['size'][$code];
  247. $attribute = '';
  248. $default = '';
  249. $extra = '';
  250. $null = 'null';
  251. if ($type == 'boolean') {
  252. $typedb = 'int';
  253. $lengthdb = '1';
  254. } elseif ($type == 'price') {
  255. $typedb = 'double';
  256. $lengthdb = '24,8';
  257. } elseif ($type == 'phone') {
  258. $typedb = 'varchar';
  259. $lengthdb = '20';
  260. } elseif ($type == 'mail') {
  261. $typedb = 'varchar';
  262. $lengthdb = '128';
  263. } elseif (($type == 'select') || ($type == 'sellist') || ($type == 'radio') || ($type == 'checkbox') || ($type == 'chkbxlst')) {
  264. $typedb = 'text';
  265. $lengthdb = '';
  266. } elseif ($type == 'link') {
  267. $typedb = 'int';
  268. $lengthdb = '11';
  269. } else {
  270. $typedb = $type;
  271. $lengthdb = $length;
  272. }
  273. $field_desc = array(
  274. 'type'=>$typedb,
  275. 'value'=>$lengthdb,
  276. 'attribute'=>$attribute,
  277. 'default'=>$default,
  278. 'extra'=>$extra,
  279. 'null'=>$null
  280. );
  281. //var_dump($field_desc);exit;
  282. $result = 0;
  283. if (GETPOST('standard', 'alpha') == 'confirmed') {
  284. $result = $db->DDLAddField($tableextra, $code, $field_desc, "");
  285. if ($result < 0) {
  286. print "KO ".$db->lasterror."<br>\n";
  287. } else {
  288. print "OK<br>\n";
  289. }
  290. } else {
  291. print ' - Mode test, no column added.';
  292. }
  293. }
  294. }
  295. print "</td><td>&nbsp;</td></tr>\n";
  296. } else {
  297. print '<tr><td>Table '.$tableextra.' is not found</td><td></td></tr>'."\n";
  298. }
  299. }
  300. }
  301. // clean_data_ecm_dir: Clean data into ecm_directories table
  302. if ($ok && GETPOST('standard', 'alpha')) {
  303. clean_data_ecm_directories();
  304. }
  305. // clean declaration constants
  306. if ($ok && GETPOST('standard', 'alpha')) {
  307. print '<tr><td colspan="2"><br>*** Clean constant record of modules not enabled</td></tr>';
  308. $sql = "SELECT name, entity, value";
  309. $sql .= " FROM ".MAIN_DB_PREFIX."const as c";
  310. $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'";
  311. $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'";
  312. $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_%'";
  313. $sql .= " OR name LIKE 'MAIN_MODULE_%_MODULEFOREXTERNAL'";
  314. $sql .= " ORDER BY name, entity";
  315. $resql = $db->query($sql);
  316. if ($resql) {
  317. $num = $db->num_rows($resql);
  318. if ($num) {
  319. $db->begin();
  320. $i = 0;
  321. while ($i < $num) {
  322. $obj = $db->fetch_object($resql);
  323. $reg = array();
  324. if (preg_match('/MAIN_MODULE_([^_]+)_(.+)/i', $obj->name, $reg)) {
  325. $name = $reg[1];
  326. $type = $reg[2];
  327. $sql2 = "SELECT COUNT(*) as nb";
  328. $sql2 .= " FROM ".MAIN_DB_PREFIX."const as c";
  329. $sql2 .= " WHERE name = 'MAIN_MODULE_".$name."'";
  330. $sql2 .= " AND entity = ".((int) $obj->entity);
  331. $resql2 = $db->query($sql2);
  332. if ($resql2) {
  333. $obj2 = $db->fetch_object($resql2);
  334. if ($obj2 && $obj2->nb == 0) {
  335. // Module not found, so we can remove entry
  336. $sqldelete = "DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = '".$db->escape($obj->name)."' AND entity = ".((int) $obj->entity);
  337. if (GETPOST('standard', 'alpha') == 'confirmed') {
  338. $db->query($sqldelete);
  339. 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>';
  340. } else {
  341. 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>';
  342. }
  343. } else {
  344. //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>';
  345. }
  346. }
  347. }
  348. $i++;
  349. }
  350. $db->commit();
  351. }
  352. } else {
  353. dol_print_error($db);
  354. }
  355. }
  356. // clean box of not enabled modules
  357. if ($ok && GETPOST('standard', 'alpha')) {
  358. print '<tr><td colspan="2"><br>*** Clean definition of boxes of modules not enabled</td></tr>';
  359. $sql = "SELECT file, entity FROM ".MAIN_DB_PREFIX."boxes_def";
  360. $sql .= " WHERE file like '%@%'";
  361. $resql = $db->query($sql);
  362. if ($resql) {
  363. $num = $db->num_rows($resql);
  364. if ($num) {
  365. $db->begin();
  366. $i = 0;
  367. while ($i < $num) {
  368. $obj = $db->fetch_object($resql);
  369. $reg = array();
  370. if (preg_match('/^(.+)@(.+)$/i', $obj->file, $reg)) {
  371. $name = $reg[1];
  372. $module = $reg[2];
  373. $sql2 = "SELECT COUNT(*) as nb";
  374. $sql2 .= " FROM ".MAIN_DB_PREFIX."const as c";
  375. $sql2 .= " WHERE name = 'MAIN_MODULE_".strtoupper($module)."'";
  376. $sql2 .= " AND entity = ".((int) $obj->entity);
  377. $sql2 .= " AND value <> 0";
  378. $resql2 = $db->query($sql2);
  379. if ($resql2) {
  380. $obj2 = $db->fetch_object($resql2);
  381. if ($obj2 && $obj2->nb == 0) {
  382. // Module not found, so we canremove entry
  383. $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).")";
  384. $sqldeleteb = "DELETE FROM ".MAIN_DB_PREFIX."boxes_def WHERE file = '".$db->escape($obj->file)."' AND entity = ".((int) $obj->entity);
  385. if (GETPOST('standard', 'alpha') == 'confirmed') {
  386. $db->query($sqldeletea);
  387. $db->query($sqldeleteb);
  388. 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>';
  389. } else {
  390. 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>';
  391. }
  392. } else {
  393. //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>';
  394. }
  395. }
  396. }
  397. $i++;
  398. }
  399. $db->commit();
  400. }
  401. }
  402. }
  403. // restore_thirdparties_logos: Move logos to correct new directory.
  404. if ($ok && GETPOST('restore_thirdparties_logos')) {
  405. //$exts=array('gif','png','jpg');
  406. $ext = '';
  407. print '<tr><td colspan="2"><br>*** Restore thirdparties logo<br>';
  408. $sql = "SELECT s.rowid, s.nom as name, s.logo FROM ".MAIN_DB_PREFIX."societe as s ORDER BY s.nom";
  409. $resql = $db->query($sql);
  410. if ($resql) {
  411. $num = $db->num_rows($resql);
  412. $i = 0;
  413. while ($i < $num) {
  414. $obj = $db->fetch_object($resql);
  415. /*
  416. $name=preg_replace('/é/','',$obj->name);
  417. $name=preg_replace('/ /','_',$name);
  418. $name=preg_replace('/\'/','',$name);
  419. */
  420. $tmp = explode('.', $obj->logo);
  421. $name = $tmp[0];
  422. if (isset($tmp[1])) {
  423. $ext = '.'.$tmp[1];
  424. }
  425. if (!empty($name)) {
  426. $filetotest = $dolibarr_main_data_root.'/societe/logos/'.$name.$ext;
  427. $filetotestsmall = $dolibarr_main_data_root.'/societe/logos/thumbs/'.$name.'_small'.$ext;
  428. $exists = dol_is_file($filetotest);
  429. print 'Check thirdparty '.$obj->rowid.' name='.$obj->name.' logo='.$obj->logo.' file '.$filetotest." exists=".$exists."<br>\n";
  430. if ($exists) {
  431. $filetarget = $dolibarr_main_data_root.'/societe/'.$obj->rowid.'/logos/'.$name.$ext;
  432. $filetargetsmall = $dolibarr_main_data_root.'/societe/'.$obj->rowid.'/logos/thumbs/'.$name.'_small'.$ext;
  433. $existt = dol_is_file($filetarget);
  434. if (!$existt) {
  435. if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') {
  436. dol_mkdir($dolibarr_main_data_root.'/societe/'.$obj->rowid.'/logos');
  437. }
  438. print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotest." -> ".$filetarget."<br>\n";
  439. if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') {
  440. dol_copy($filetotest, $filetarget, '', 0);
  441. }
  442. }
  443. $existtt = dol_is_file($filetargetsmall);
  444. if (!$existtt) {
  445. if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') {
  446. dol_mkdir($dolibarr_main_data_root.'/societe/'.$obj->rowid.'/logos/thumbs');
  447. }
  448. print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotestsmall." -> ".$filetargetsmall."<br>\n";
  449. if (GETPOST('restore_thirdparties_logos', 'alpha') == 'confirmed') {
  450. dol_copy($filetotestsmall, $filetargetsmall, '', 0);
  451. }
  452. }
  453. }
  454. }
  455. $i++;
  456. }
  457. } else {
  458. $ok = 0;
  459. dol_print_error($db);
  460. }
  461. print '</td></tr>';
  462. }
  463. // restore_user_pictures: Move pictures to correct new directory.
  464. if ($ok && GETPOST('restore_user_pictures', 'alpha')) {
  465. //$exts=array('gif','png','jpg');
  466. $ext = '';
  467. print '<tr><td colspan="2"><br>*** Restore user pictures<br>';
  468. $sql = "SELECT s.rowid, s.firstname, s.lastname, s.login, s.photo FROM ".MAIN_DB_PREFIX."user as s ORDER BY s.rowid";
  469. $resql = $db->query($sql);
  470. if ($resql) {
  471. $num = $db->num_rows($resql);
  472. $i = 0;
  473. while ($i < $num) {
  474. $obj = $db->fetch_object($resql);
  475. /*
  476. $name=preg_replace('/é/','',$obj->name);
  477. $name=preg_replace('/ /','_',$name);
  478. $name=preg_replace('/\'/','',$name);
  479. */
  480. $tmp = explode('.', $obj->photo);
  481. $name = $tmp[0];
  482. if (isset($tmp[1])) {
  483. $ext = '.'.$tmp[1];
  484. }
  485. if (!empty($name)) {
  486. $filetotest = $dolibarr_main_data_root.'/users/'.substr(sprintf('%08d', $obj->rowid), -1, 1).'/'.substr(sprintf('%08d', $obj->rowid), -2, 1).'/'.$name.$ext;
  487. $filetotestsmall = $dolibarr_main_data_root.'/users/'.substr(sprintf('%08d', $obj->rowid), -1, 1).'/'.substr(sprintf('%08d', $obj->rowid), -2, 1).'/thumbs/'.$name.'_small'.$ext;
  488. $filetotestmini = $dolibarr_main_data_root.'/users/'.substr(sprintf('%08d', $obj->rowid), -1, 1).'/'.substr(sprintf('%08d', $obj->rowid), -2, 1).'/thumbs/'.$name.'_mini'.$ext;
  489. $exists = dol_is_file($filetotest);
  490. print 'Check user '.$obj->rowid.' lastname='.$obj->lastname.' firstname='.$obj->firstname.' photo='.$obj->photo.' file '.$filetotest." exists=".$exists."<br>\n";
  491. if ($exists) {
  492. $filetarget = $dolibarr_main_data_root.'/users/'.$obj->rowid.'/'.$name.$ext;
  493. $filetargetsmall = $dolibarr_main_data_root.'/users/'.$obj->rowid.'/thumbs/'.$name.'_small'.$ext;
  494. $filetargetmini = $dolibarr_main_data_root.'/users/'.$obj->rowid.'/thumbs/'.$name.'_mini'.$ext;
  495. $existt = dol_is_file($filetarget);
  496. if (!$existt) {
  497. if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') {
  498. dol_mkdir($dolibarr_main_data_root.'/users/'.$obj->rowid);
  499. }
  500. print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotest." -> ".$filetarget."<br>\n";
  501. if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') {
  502. dol_copy($filetotest, $filetarget, '', 0);
  503. }
  504. }
  505. $existtt = dol_is_file($filetargetsmall);
  506. if (!$existtt) {
  507. if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') {
  508. dol_mkdir($dolibarr_main_data_root.'/users/'.$obj->rowid.'/thumbs');
  509. }
  510. print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotestsmall." -> ".$filetargetsmall."<br>\n";
  511. if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') {
  512. dol_copy($filetotestsmall, $filetargetsmall, '', 0);
  513. }
  514. }
  515. $existtt = dol_is_file($filetargetmini);
  516. if (!$existtt) {
  517. if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') {
  518. dol_mkdir($dolibarr_main_data_root.'/users/'.$obj->rowid.'/thumbs');
  519. }
  520. print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotestmini." -> ".$filetargetmini."<br>\n";
  521. if (GETPOST('restore_user_pictures', 'alpha') == 'confirmed') {
  522. dol_copy($filetotestmini, $filetargetmini, '', 0);
  523. }
  524. }
  525. }
  526. }
  527. $i++;
  528. }
  529. } else {
  530. $ok = 0;
  531. dol_print_error($db);
  532. }
  533. print '</td></tr>';
  534. }
  535. // rebuild_product_thumbs: Rebuild thumbs for product files
  536. if ($ok && GETPOST('rebuild_product_thumbs', 'alpha')) {
  537. $ext = '';
  538. global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
  539. print '<tr><td colspan="2"><br>*** Rebuild product thumbs<br>';
  540. $sql = "SELECT s.rowid, s.ref FROM ".MAIN_DB_PREFIX."product as s ORDER BY s.ref";
  541. $resql = $db->query($sql);
  542. if ($resql) {
  543. $num = $db->num_rows($resql);
  544. $i = 0;
  545. while ($i < $num) {
  546. $obj = $db->fetch_object($resql);
  547. if (!empty($obj->ref)) {
  548. $files = dol_dir_list($dolibarr_main_data_root.'/produit/'.$obj->ref, 'files', 0);
  549. foreach ($files as $file) {
  550. // Generate thumbs.
  551. if (image_format_supported($file['fullname']) == 1) {
  552. $imgThumbSmall = 'notbuild';
  553. if (GETPOST('rebuild_product_thumbs', 'alpha') == 'confirmed') {
  554. // Used on logon for example
  555. $imgThumbSmall = vignette($file['fullname'], $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
  556. }
  557. print 'Check product '.$obj->rowid.", file ".$file['fullname']." -> ".$imgThumbSmall." maxwidthsmall=".$maxwidthsmall." maxheightsmall=".$maxheightsmall."<br>\n";
  558. $imgThumbMini = 'notbuild';
  559. if (GETPOST('rebuild_product_thumbs', 'alpha') == 'confirmed') {
  560. // Create mini thumbs for image (Ratio is near 16/9)
  561. // Used on menu or for setup page for example
  562. $imgThumbMini = vignette($file['fullname'], $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
  563. }
  564. print 'Check product '.$obj->rowid.", file ".$file['fullname']." -> ".$imgThumbMini." maxwidthmini=".$maxwidthmini." maxheightmini=".$maxheightmini."<br>\n";
  565. }
  566. }
  567. }
  568. $i++;
  569. }
  570. } else {
  571. $ok = 0;
  572. dol_print_error($db);
  573. }
  574. print '</td></tr>';
  575. }
  576. // clean_linked_elements: Check and clean linked elements
  577. if ($ok && GETPOST('clean_linked_elements', 'alpha')) {
  578. print '<tr><td colspan="2"><br>*** Check table of linked elements and delete orphelins links</td></tr>';
  579. // propal => order
  580. print '<tr><td colspan="2">'.checkLinkedElements('propal', 'commande')."</td></tr>\n";
  581. // propal => invoice
  582. print '<tr><td colspan="2">'.checkLinkedElements('propal', 'facture')."</td></tr>\n";
  583. // order => invoice
  584. print '<tr><td colspan="2">'.checkLinkedElements('commande', 'facture')."</td></tr>\n";
  585. // order => shipping
  586. print '<tr><td colspan="2">'.checkLinkedElements('commande', 'shipping')."</td></tr>\n";
  587. // shipping => delivery
  588. print '<tr><td colspan="2">'.checkLinkedElements('shipping', 'delivery')."</td></tr>\n";
  589. // order_supplier => invoice_supplier
  590. print '<tr><td colspan="2">'.checkLinkedElements('order_supplier', 'invoice_supplier')."</td></tr>\n";
  591. }
  592. // clean_menus: Check orphelins menus
  593. if ($ok && GETPOST('clean_menus', 'alpha')) {
  594. print '<tr><td colspan="2"><br>*** Clean menu entries coming from disabled modules</td></tr>';
  595. $sql = "SELECT rowid, module";
  596. $sql .= " FROM ".MAIN_DB_PREFIX."menu as c";
  597. $sql .= " WHERE module IS NOT NULL AND module <> ''";
  598. $sql .= " ORDER BY module";
  599. $resql = $db->query($sql);
  600. if ($resql) {
  601. $num = $db->num_rows($resql);
  602. if ($num) {
  603. $i = 0;
  604. while ($i < $num) {
  605. $obj = $db->fetch_object($resql);
  606. $modulecond = $obj->module;
  607. $modulecondarray = explode('|', $obj->module); // Name of module
  608. print '<tr><td>';
  609. print $modulecond;
  610. $db->begin();
  611. if ($modulecond) { // And menu entry for module $modulecond was found in database.
  612. $moduleok = 0;
  613. foreach ($modulecondarray as $tmpname) {
  614. if ($tmpname == 'margins') {
  615. $tmpname = 'margin'; // TODO Remove this when normalized
  616. }
  617. $result = 0;
  618. if (!empty($conf->$tmpname)) {
  619. $result = $conf->$tmpname->enabled;
  620. }
  621. if ($result) {
  622. $moduleok++;
  623. }
  624. }
  625. if (!$moduleok && $modulecond) {
  626. print ' - Module condition '.$modulecond.' seems ko, we delete menu entry.';
  627. if (GETPOST('clean_menus') == 'confirmed') {
  628. $sql2 = "DELETE FROM ".MAIN_DB_PREFIX."menu WHERE module = '".$db->escape($modulecond)."'";
  629. $resql2 = $db->query($sql2);
  630. if (!$resql2) {
  631. $error++;
  632. dol_print_error($db);
  633. } else {
  634. print ' - <span class="warning">Cleaned</span>';
  635. }
  636. } else {
  637. print ' - <span class="warning">Canceled (test mode)</span>';
  638. }
  639. } else {
  640. print ' - Module condition '.$modulecond.' is ok, we do nothing.';
  641. }
  642. }
  643. if (!$error) {
  644. $db->commit();
  645. } else {
  646. $db->rollback();
  647. }
  648. print'</td></tr>';
  649. if ($error) {
  650. break;
  651. }
  652. $i++;
  653. }
  654. } else {
  655. print '<tr><td>No menu entries of disabled menus found</td></tr>';
  656. }
  657. } else {
  658. dol_print_error($db);
  659. }
  660. }
  661. // clean_orphelin_dir: Run purge of directory
  662. if ($ok && GETPOST('clean_orphelin_dir', 'alpha')) {
  663. $listmodulepart = array('company', 'invoice', 'invoice_supplier', 'propal', 'order', 'order_supplier', 'contract', 'tax');
  664. foreach ($listmodulepart as $modulepart) {
  665. $filearray = array();
  666. $upload_dir = isset($conf->$modulepart->dir_output) ? $conf->$modulepart->dir_output : '';
  667. if ($modulepart == 'company') {
  668. $upload_dir = $conf->societe->dir_output; // TODO change for multicompany sharing
  669. }
  670. if ($modulepart == 'invoice') {
  671. $upload_dir = $conf->facture->dir_output;
  672. }
  673. if ($modulepart == 'invoice_supplier') {
  674. $upload_dir = $conf->fournisseur->facture->dir_output;
  675. }
  676. if ($modulepart == 'order') {
  677. $upload_dir = $conf->commande->dir_output;
  678. }
  679. if ($modulepart == 'order_supplier') {
  680. $upload_dir = $conf->fournisseur->commande->dir_output;
  681. }
  682. if ($modulepart == 'contract') {
  683. $upload_dir = $conf->contrat->dir_output;
  684. }
  685. if (empty($upload_dir)) {
  686. continue;
  687. }
  688. print '<tr><td colspan="2"><br>*** Clean orphelins files into files '.$upload_dir.'</td></tr>';
  689. $filearray = dol_dir_list($upload_dir, "files", 1, '', array('^SPECIMEN\.pdf$', '^\.', '(\.meta|_preview.*\.png)$', '^temp$', '^payments$', '^CVS$', '^thumbs$'), '', SORT_DESC, 1, true);
  690. // To show ref or specific information according to view to show (defined by $module)
  691. if ($modulepart == 'company') {
  692. include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  693. $object_instance = new Societe($db);
  694. }
  695. if ($modulepart == 'invoice') {
  696. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  697. $object_instance = new Facture($db);
  698. } elseif ($modulepart == 'invoice_supplier') {
  699. include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  700. $object_instance = new FactureFournisseur($db);
  701. } elseif ($modulepart == 'propal') {
  702. include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  703. $object_instance = new Propal($db);
  704. } elseif ($modulepart == 'order') {
  705. include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  706. $object_instance = new Commande($db);
  707. } elseif ($modulepart == 'order_supplier') {
  708. include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  709. $object_instance = new CommandeFournisseur($db);
  710. } elseif ($modulepart == 'contract') {
  711. include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
  712. $object_instance = new Contrat($db);
  713. } elseif ($modulepart == 'tax') {
  714. include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
  715. $object_instance = new ChargeSociales($db);
  716. }
  717. foreach ($filearray as $key => $file) {
  718. if (!is_dir($file['name'])
  719. && $file['name'] != '.'
  720. && $file['name'] != '..'
  721. && $file['name'] != 'CVS'
  722. ) {
  723. // Define relative path used to store the file
  724. $relativefile = preg_replace('/'.preg_quote($upload_dir.'/', '/').'/', '', $file['fullname']);
  725. //var_dump($file);
  726. $id = 0;
  727. $ref = '';
  728. $object_instance->id = 0;
  729. $object_instance->ref = '';
  730. $label = '';
  731. // To show ref or specific information according to view to show (defined by $module)
  732. if ($modulepart == 'invoice') {
  733. preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg);
  734. $ref = $reg[1];
  735. }
  736. if ($modulepart == 'invoice_supplier') {
  737. preg_match('/(\d+)\/[^\/]+$/', $relativefile, $reg);
  738. $id = empty($reg[1]) ? '' : $reg[1];
  739. }
  740. if ($modulepart == 'propal') {
  741. preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg);
  742. $ref = $reg[1];
  743. }
  744. if ($modulepart == 'order') {
  745. preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg);
  746. $ref = $reg[1];
  747. }
  748. if ($modulepart == 'order_supplier') {
  749. preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg);
  750. $ref = $reg[1];
  751. }
  752. if ($modulepart == 'contract') {
  753. preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg);
  754. $ref = $reg[1];
  755. }
  756. if ($modulepart == 'tax') {
  757. preg_match('/(\d+)\/[^\/]+$/', $relativefile, $reg);
  758. $id = $reg[1];
  759. }
  760. if ($id || $ref) {
  761. //print 'Fetch '.$id.' or '.$ref.'<br>';
  762. $result = $object_instance->fetch($id, $ref);
  763. //print $result.'<br>';
  764. if ($result == 0) { // Not found but no error
  765. // Clean of orphelins directories are done into repair.php
  766. print '<tr><td colspan="2">';
  767. print 'Delete orphelins file '.$file['fullname'].'<br>';
  768. if (GETPOST('clean_orphelin_dir', 'alpha') == 'confirmed') {
  769. dol_delete_file($file['fullname'], 1, 1, 1);
  770. dol_delete_dir(dirname($file['fullname']), 1);
  771. }
  772. print "</td></tr>";
  773. } elseif ($result < 0) {
  774. print 'Error in '.get_class($object_instance).'.fetch of id'.$id.' ref='.$ref.', result='.$result.'<br>';
  775. }
  776. }
  777. }
  778. }
  779. }
  780. }
  781. // clean_linked_elements: Check and clean linked elements
  782. if ($ok && GETPOST('clean_product_stock_batch', 'alpha')) {
  783. $methodtofix = GETPOST('methodtofix', 'alpha') ? GETPOST('methodtofix', 'alpha') : 'updatestock';
  784. print '<tr><td colspan="2"><br>*** Clean table product_batch, methodtofix='.$methodtofix.' (possible values: updatestock or updatebatch)</td></tr>';
  785. $sql = "SELECT p.rowid, p.ref, p.tobatch, ps.rowid as psrowid, ps.fk_entrepot, ps.reel, SUM(pb.qty) as reelbatch";
  786. $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";
  787. $sql .= " WHERE p.rowid = ps.fk_product";
  788. $sql .= " GROUP BY p.rowid, p.ref, p.tobatch, ps.rowid, ps.fk_entrepot, ps.reel";
  789. $sql .= " HAVING (SUM(pb.qty) IS NOT NULL AND reel != SUM(pb.qty)) OR (SUM(pb.qty) IS NULL AND p.tobatch > 0)";
  790. print $sql;
  791. $resql = $db->query($sql);
  792. if ($resql) {
  793. $num = $db->num_rows($resql);
  794. if ($num) {
  795. $i = 0;
  796. while ($i < $num) {
  797. $obj = $db->fetch_object($resql);
  798. 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)';
  799. // Fix is required
  800. if ($obj->reel != $obj->reelbatch) {
  801. if (empty($obj->tobatch)) {
  802. // If product is not a product that support batches, we can clean stock by deleting the product batch lines
  803. print ' -> Delete qty '.$obj->reelbatch.' for any lot linked to fk_product_stock='.$obj->psrowid;
  804. $sql2 = "DELETE FROM ".MAIN_DB_PREFIX."product_batch";
  805. $sql2 .= " WHERE fk_product_stock = ".((int) $obj->psrowid);
  806. print '<br>'.$sql2;
  807. if (GETPOST('clean_product_stock_batch') == 'confirmed') {
  808. $resql2 = $db->query($sql2);
  809. if (!$resql2) {
  810. $error++;
  811. dol_print_error($db);
  812. }
  813. }
  814. } else {
  815. if ($methodtofix == 'updatebatch') {
  816. // Method 1
  817. print ' -> Insert qty '.($obj->reel - $obj->reelbatch).' with lot 000000 linked to fk_product_stock='.$obj->psrowid;
  818. $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."product_batch(fk_product_stock, batch, qty)";
  819. $sql2 .= "VALUES(".((int) $obj->psrowid).", '000000', ".((float) ($obj->reel - $obj->reelbatch)).")";
  820. print '<br>'.$sql2;
  821. if (GETPOST('clean_product_stock_batch') == 'confirmed') {
  822. $resql2 = $db->query($sql2);
  823. if (!$resql2) {
  824. // TODO If it fails, we must make update
  825. //$sql2 ="UPDATE ".MAIN_DB_PREFIX."product_batch";
  826. //$sql2.=" SET ".$obj->psrowid.", '000000', ".($obj->reel - $obj->reelbatch).")";
  827. //$sql2.=" WHERE fk_product_stock = ".((int) $obj->psrowid)
  828. }
  829. }
  830. }
  831. if ($methodtofix == 'updatestock') {
  832. // Method 2
  833. print ' -> Update qty of product_stock with qty = '.($obj->reelbatch ? ((float) $obj->reelbatch) : '0').' for ps.rowid = '.((int) $obj->psrowid);
  834. $sql2 = "UPDATE ".MAIN_DB_PREFIX."product_stock";
  835. $sql2 .= " SET reel = ".($obj->reelbatch ? ((float) $obj->reelbatch) : '0')." WHERE rowid = ".((int) $obj->psrowid);
  836. print '<br>'.$sql2;
  837. if (GETPOST('clean_product_stock_batch') == 'confirmed') {
  838. $error = 0;
  839. $db->begin();
  840. $resql2 = $db->query($sql2);
  841. if ($resql2) {
  842. // We update product_stock, so we must fill p.stock into product too.
  843. $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)';
  844. $resql3 = $db->query($sql3);
  845. if (!$resql3) {
  846. $error++;
  847. dol_print_error($db);
  848. }
  849. } else {
  850. $error++;
  851. dol_print_error($db);
  852. }
  853. if (!$error) {
  854. $db->commit();
  855. } else {
  856. $db->rollback();
  857. }
  858. }
  859. }
  860. }
  861. }
  862. print'</td></tr>';
  863. $i++;
  864. }
  865. } else {
  866. print '<tr><td colspan="2">Nothing to do</td></tr>';
  867. }
  868. } else {
  869. dol_print_error($db);
  870. }
  871. }
  872. // clean_product_stock_negative_if_batch
  873. if ($ok && GETPOST('clean_product_stock_negative_if_batch', 'alpha')) {
  874. print '<tr><td colspan="2"><br>Clean table product_batch, methodtofix='.$methodtofix.' (possible values: updatestock or updatebatch)</td></tr>';
  875. $sql = "SELECT p.rowid, p.ref, p.tobatch, ps.rowid as psrowid, ps.fk_entrepot, ps.reel, SUM(pb.qty) as reelbatch";
  876. $sql .= " FROM ".MAIN_DB_PREFIX."product as p, ".MAIN_DB_PREFIX."product_stock as ps, ".MAIN_DB_PREFIX."product_batch as pb";
  877. $sql .= " WHERE p.rowid = ps.fk_product AND ps.rowid = pb.fk_product_stock";
  878. $sql .= " AND p.tobatch > 0";
  879. $sql .= " GROUP BY p.rowid, p.ref, p.tobatch, ps.rowid, ps.fk_entrepot, ps.reel";
  880. $sql .= " HAVING reel != SUM(pb.qty)";
  881. $resql = $db->query($sql);
  882. if ($resql) {
  883. $num = $db->num_rows($resql);
  884. if ($num) {
  885. $i = 0;
  886. while ($i < $num) {
  887. $obj = $db->fetch_object($resql);
  888. print '<tr><td>'.$obj->rowid.'-'.$obj->ref.'-'.$obj->fk_entrepot.' -> '.$obj->psrowid.': '.$obj->reel.' != '.$obj->reelbatch;
  889. // TODO
  890. }
  891. }
  892. }
  893. }
  894. // set_empty_time_spent_amount
  895. if ($ok && GETPOST('set_empty_time_spent_amount', 'alpha')) {
  896. print '<tr><td colspan="2"><br>*** Set value of time spent without amount</td></tr>';
  897. $sql = "SELECT COUNT(ptt.rowid) as nb, u.rowid as user_id, u.login, u.thm as user_thm";
  898. $sql .= " FROM ".MAIN_DB_PREFIX."element_time as ptt, ".MAIN_DB_PREFIX."user as u";
  899. $sql .= " WHERE ptt.fk_user = u.rowid";
  900. $sql .= " AND ptt.thm IS NULL and u.thm > 0";
  901. $sql .= " GROUP BY u.rowid, u.login, u.thm";
  902. $resql = $db->query($sql);
  903. if ($resql) {
  904. $num = $db->num_rows($resql);
  905. if ($num) {
  906. $i = 0;
  907. while ($i < $num) {
  908. $obj = $db->fetch_object($resql);
  909. print '<tr><td>'.$obj->login.'-'.$obj->user_id.' ('.$obj->nb.' lines to fix) -> '.$obj->user_thm;
  910. $db->begin();
  911. if (GETPOST('set_empty_time_spent_amount') == 'confirmed') {
  912. $sql2 = "UPDATE ".MAIN_DB_PREFIX."element_time";
  913. $sql2 .= " SET thm = ".$obj->user_thm." WHERE thm IS NULL AND fk_user = ".((int) $obj->user_id);
  914. $resql2 = $db->query($sql2);
  915. if (!$resql2) {
  916. $error++;
  917. dol_print_error($db);
  918. }
  919. }
  920. if (!$error) {
  921. $db->commit();
  922. } else {
  923. $db->rollback();
  924. }
  925. print'</td></tr>';
  926. if ($error) {
  927. break;
  928. }
  929. $i++;
  930. }
  931. } else {
  932. print '<tr><td>No time spent with empty line on users with a hourly rate defined</td></tr>';
  933. }
  934. } else {
  935. dol_print_error($db);
  936. }
  937. }
  938. // force_disable_of_modules_not_found
  939. if ($ok && GETPOST('force_disable_of_modules_not_found', 'alpha')) {
  940. print '<tr><td colspan="2"><br>*** Force modules not found physicaly to be disabled (only modules adding js, css or hooks can be detected as removed physicaly)</td></tr>';
  941. $arraylistofkey = array('hooks', 'js', 'css');
  942. foreach ($arraylistofkey as $key) {
  943. $sql = "SELECT DISTINCT name, value";
  944. $sql .= " FROM ".MAIN_DB_PREFIX."const as c";
  945. $sql .= " WHERE name LIKE 'MAIN_MODULE_%_".strtoupper($key)."'";
  946. $sql .= " ORDER BY name";
  947. $resql = $db->query($sql);
  948. if ($resql) {
  949. $num = $db->num_rows($resql);
  950. if ($num) {
  951. $i = 0;
  952. while ($i < $num) {
  953. $obj = $db->fetch_object($resql);
  954. $constantname = $obj->name; // Name of constant for hook or js or css declaration
  955. print '<tr><td>';
  956. print dol_escape_htmltag($constantname);
  957. $db->begin();
  958. $reg = array();
  959. if (preg_match('/MAIN_MODULE_(.*)_'.strtoupper($key).'/i', $constantname, $reg)) {
  960. $name = strtolower($reg[1]);
  961. if ($name) { // An entry for key $key and module $name was found in database.
  962. $reloffile = '';
  963. $result = 'found';
  964. if ($key == 'hooks') {
  965. $reloffile = $name.'/class/actions_'.$name.'.class.php';
  966. }
  967. if ($key == 'js') {
  968. $value = $obj->value;
  969. $valuearray = (array) json_decode($value); // Force cast into array because sometimes it is a stdClass
  970. $reloffile = $valuearray[0];
  971. $reloffile = preg_replace('/^\//', '', $valuearray[0]);
  972. }
  973. if ($key == 'css') {
  974. $value = $obj->value;
  975. $valuearray = (array) json_decode($value); // Force cast into array because sometimes it is a stdClass
  976. if ($value && (!is_array($valuearray) || count($valuearray) == 0)) {
  977. $valuearray = array();
  978. $valuearray[0] = $value; // If value was not a json array but a string
  979. }
  980. $reloffile = preg_replace('/^\//', '', $valuearray[0]);
  981. }
  982. if ($reloffile) {
  983. //var_dump($key.' - '.$value.' - '.$reloffile);
  984. try {
  985. $result = dol_buildpath($reloffile, 0, 2);
  986. } catch (Exception $e) {
  987. $result = 'found'; // If error, we force like if we found to avoid any deletion
  988. }
  989. } else {
  990. $result = 'found'; //
  991. }
  992. if (!$result) {
  993. print ' - File of '.$key.' ('.$reloffile.') NOT found, we disable the module.';
  994. if (GETPOST('force_disable_of_modules_not_found') == 'confirmed') {
  995. $sql2 = "DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = 'MAIN_MODULE_".strtoupper($name)."_".strtoupper($key)."'";
  996. $resql2 = $db->query($sql2);
  997. if (!$resql2) {
  998. $error++;
  999. dol_print_error($db);
  1000. }
  1001. $sql3 = "DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = 'MAIN_MODULE_".strtoupper($name)."'";
  1002. $resql3 = $db->query($sql3);
  1003. if (!$resql3) {
  1004. $error++;
  1005. dol_print_error($db);
  1006. } else {
  1007. print ' - <span class="warning">Cleaned</span>';
  1008. }
  1009. } else {
  1010. print ' - <span class="warning">Canceled (test mode)</span>';
  1011. }
  1012. } else {
  1013. print ' - File of '.$key.' ('.$reloffile.') found, we do nothing.';
  1014. }
  1015. }
  1016. if (!$error) {
  1017. $db->commit();
  1018. } else {
  1019. $db->rollback();
  1020. }
  1021. }
  1022. print'</td></tr>';
  1023. if ($error) {
  1024. break;
  1025. }
  1026. $i++;
  1027. }
  1028. } else {
  1029. print '<tr><td>No active module with missing files found by searching on MAIN_MODULE_(.*)_'.strtoupper($key).'</td></tr>';
  1030. }
  1031. } else {
  1032. dol_print_error($db);
  1033. }
  1034. }
  1035. }
  1036. // clean_old_module_entries: Clean data into const when files of module were removed without being
  1037. if ($ok && GETPOST('clean_perm_table', 'alpha')) {
  1038. print '<tr><td colspan="2"><br>*** Clean table user_rights from lines of external modules no more enabled</td></tr>';
  1039. $listofmods = '';
  1040. foreach ($conf->modules as $key => $val) {
  1041. $listofmods .= ($listofmods ? ',' : '')."'".$db->escape($val)."'";
  1042. }
  1043. $sql = "SELECT id, libelle as label, module from ".MAIN_DB_PREFIX."rights_def WHERE module NOT IN (".$db->sanitize($listofmods, 1).") AND id > 100000";
  1044. $resql = $db->query($sql);
  1045. if ($resql) {
  1046. $num = $db->num_rows($resql);
  1047. if ($num) {
  1048. $i = 0;
  1049. while ($i < $num) {
  1050. $obj = $db->fetch_object($resql);
  1051. if ($obj->id > 0) {
  1052. print '<tr><td>Found line with id '.$obj->id.', label "'.$obj->label.'" of module "'.$obj->module.'" to delete';
  1053. if (GETPOST('clean_perm_table', 'alpha') == 'confirmed') {
  1054. $sqldelete = "DELETE FROM ".MAIN_DB_PREFIX."rights_def WHERE id = ".((int) $obj->id);
  1055. $resqldelete = $db->query($sqldelete);
  1056. if (!$resqldelete) {
  1057. dol_print_error($db);
  1058. }
  1059. print ' - deleted';
  1060. }
  1061. print '</td></tr>';
  1062. }
  1063. $i++;
  1064. }
  1065. } else {
  1066. print '<tr><td>No lines of a disabled external module (with id > 100000) found into table rights_def</td></tr>';
  1067. }
  1068. } else {
  1069. dol_print_error($db);
  1070. }
  1071. }
  1072. // force utf8 on tables
  1073. if ($ok && GETPOST('force_utf8_on_tables', 'alpha')) {
  1074. 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>';
  1075. if ($db->type == "mysql" || $db->type == "mysqli") {
  1076. $force_utf8_on_tables = GETPOST('force_utf8_on_tables', 'alpha');
  1077. $listoftables = $db->DDLListTablesFull($db->database_name);
  1078. // Disable foreign key checking for avoid errors
  1079. if ($force_utf8_on_tables == 'confirmed') {
  1080. $sql = 'SET FOREIGN_KEY_CHECKS=0';
  1081. print '<!-- '.$sql.' -->';
  1082. $resql = $db->query($sql);
  1083. }
  1084. foreach ($listoftables as $table) {
  1085. // do not convert llx_const if mysql encrypt/decrypt is used
  1086. if ($conf->db->dolibarr_main_db_encryption != 0 && preg_match('/\_const$/', $table[0])) {
  1087. continue;
  1088. }
  1089. if ($table[1] == 'VIEW') {
  1090. print '<tr><td colspan="2">'.$table[0].' is a '.$table[1].' (Skipped)</td></tr>';
  1091. continue;
  1092. }
  1093. print '<tr><td colspan="2">';
  1094. print $table[0];
  1095. $sql1 = "ALTER TABLE ".$table[0]." ROW_FORMAT=dynamic";
  1096. $sql2 = "ALTER TABLE ".$table[0]." CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  1097. print '<!-- '.$sql1.' -->';
  1098. print '<!-- '.$sql2.' -->';
  1099. if ($force_utf8_on_tables == 'confirmed') {
  1100. $resql1 = $db->query($sql1);
  1101. if ($resql1) {
  1102. $resql2 = $db->query($sql2);
  1103. } else {
  1104. $resql2 = false;
  1105. }
  1106. print ' - Done ('.(($resql1 && $resql2) ? 'OK' : 'KO').')';
  1107. } else {
  1108. print ' - Disabled';
  1109. }
  1110. print '</td></tr>';
  1111. }
  1112. // Enable foreign key checking
  1113. if ($force_utf8_on_tables == 'confirmed') {
  1114. $sql = 'SET FOREIGN_KEY_CHECKS=1';
  1115. print '<!-- '.$sql.' -->';
  1116. $resql = $db->query($sql);
  1117. }
  1118. } else {
  1119. print '<tr><td colspan="2">Not available with database type '.$db->type.'</td></tr>';
  1120. }
  1121. }
  1122. // force utf8mb4 on tables EXPERIMENTAL !
  1123. if ($ok && GETPOST('force_utf8mb4_on_tables', 'alpha')) {
  1124. print '<tr><td colspan="2"><br>*** Force page code and collation of tables into utf8mb4/utf8mb4_unicode_ci (for mysql/mariadb only)</td></tr>';
  1125. if ($db->type == "mysql" || $db->type == "mysqli") {
  1126. $force_utf8mb4_on_tables = GETPOST('force_utf8mb4_on_tables', 'alpha');
  1127. $listoftables = $db->DDLListTablesFull($db->database_name);
  1128. // Disable foreign key checking for avoid errors
  1129. if ($force_utf8mb4_on_tables == 'confirmed') {
  1130. $sql = 'SET FOREIGN_KEY_CHECKS=0';
  1131. print '<!-- '.$sql.' -->';
  1132. $resql = $db->query($sql);
  1133. }
  1134. foreach ($listoftables as $table) {
  1135. // do not convert llx_const if mysql encrypt/decrypt is used
  1136. if ($conf->db->dolibarr_main_db_encryption != 0 && preg_match('/\_const$/', $table[0])) {
  1137. continue;
  1138. }
  1139. if ($table[1] == 'VIEW') {
  1140. print '<tr><td colspan="2">'.$table[0].' is a '.$table[1].' (Skipped)</td></tr>';
  1141. continue;
  1142. }
  1143. print '<tr><td colspan="2">';
  1144. print $table[0];
  1145. $sql1 = "ALTER TABLE ".$table[0]." ROW_FORMAT=dynamic";
  1146. $sql2 = "ALTER TABLE ".$table[0]." CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci";
  1147. print '<!-- '.$sql1.' -->';
  1148. print '<!-- '.$sql2.' -->';
  1149. if ($force_utf8mb4_on_tables == 'confirmed') {
  1150. $resql1 = $db->query($sql1);
  1151. if ($resql1) {
  1152. $resql2 = $db->query($sql2);
  1153. } else {
  1154. $resql2 = false;
  1155. }
  1156. print ' - Done ('.(($resql1 && $resql2) ? 'OK' : 'KO').')';
  1157. } else {
  1158. print ' - Disabled';
  1159. }
  1160. print '</td></tr>';
  1161. flush();
  1162. ob_flush();
  1163. }
  1164. // Enable foreign key checking
  1165. if ($force_utf8mb4_on_tables == 'confirmed') {
  1166. $sql = 'SET FOREIGN_KEY_CHECKS=1';
  1167. print '<!-- '.$sql.' -->';
  1168. $resql = $db->query($sql);
  1169. }
  1170. } else {
  1171. print '<tr><td colspan="2">Not available with database type '.$db->type.'</td></tr>';
  1172. }
  1173. }
  1174. if ($ok && GETPOST('force_collation_from_conf_on_tables', 'alpha')) {
  1175. 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>';
  1176. if ($db->type == "mysql" || $db->type == "mysqli") {
  1177. $force_collation_from_conf_on_tables = GETPOST('force_collation_from_conf_on_tables', 'alpha');
  1178. $listoftables = $db->DDLListTablesFull($db->database_name);
  1179. // Disable foreign key checking for avoid errors
  1180. if ($force_collation_from_conf_on_tables == 'confirmed') {
  1181. $sql = 'SET FOREIGN_KEY_CHECKS=0';
  1182. print '<!-- '.$sql.' -->';
  1183. $resql = $db->query($sql);
  1184. }
  1185. foreach ($listoftables as $table) {
  1186. // do not convert llx_const if mysql encrypt/decrypt is used
  1187. if ($conf->db->dolibarr_main_db_encryption != 0 && preg_match('/\_const$/', $table[0])) {
  1188. continue;
  1189. }
  1190. if ($table[1] == 'VIEW') {
  1191. print '<tr><td colspan="2">'.$table[0].' is a '.$table[1].' (Skipped)</td></tr>';
  1192. continue;
  1193. }
  1194. print '<tr><td colspan="2">';
  1195. print $table[0];
  1196. $sql1 = "ALTER TABLE ".$table[0]." ROW_FORMAT=dynamic";
  1197. $sql2 = "ALTER TABLE ".$table[0]." CONVERT TO CHARACTER SET ".$conf->db->character_set." COLLATE ".$conf->db->dolibarr_main_db_collation;
  1198. print '<!-- '.$sql1.' -->';
  1199. print '<!-- '.$sql2.' -->';
  1200. if ($force_collation_from_conf_on_tables == 'confirmed') {
  1201. $resql1 = $db->query($sql1);
  1202. if ($resql1) {
  1203. $resql2 = $db->query($sql2);
  1204. } else {
  1205. $resql2 = false;
  1206. }
  1207. print ' - Done ('.(($resql1 && $resql2) ? 'OK' : 'KO').')';
  1208. } else {
  1209. print ' - Disabled';
  1210. }
  1211. print '</td></tr>';
  1212. }
  1213. // Enable foreign key checking
  1214. if ($force_collation_from_conf_on_tables == 'confirmed') {
  1215. $sql = 'SET FOREIGN_KEY_CHECKS=1';
  1216. print '<!-- '.$sql.' -->';
  1217. $resql = $db->query($sql);
  1218. }
  1219. } else {
  1220. print '<tr><td colspan="2">Not available with database type '.$db->type.'</td></tr>';
  1221. }
  1222. }
  1223. // rebuild sequences for pgsql
  1224. if ($ok && GETPOST('rebuild_sequences', 'alpha')) {
  1225. print '<tr><td colspan="2"><br>*** Force to rebuild sequences (for postgresql only)</td></tr>';
  1226. if ($db->type == "pgsql") {
  1227. $rebuild_sequence = GETPOST('rebuild_sequences', 'alpha');
  1228. if ($rebuild_sequence == 'confirmed') {
  1229. $sql = "SELECT dol_util_rebuild_sequences();";
  1230. print '<!-- '.$sql.' -->';
  1231. $resql = $db->query($sql);
  1232. }
  1233. } else {
  1234. print '<tr><td colspan="2">Not available with database type '.$db->type.'</td></tr>';
  1235. }
  1236. }
  1237. //
  1238. if ($ok && GETPOST('repair_link_dispatch_lines_supplier_order_lines')) {
  1239. /*
  1240. * This script is meant to be run when upgrading from a dolibarr version < 3.8
  1241. * to a newer version.
  1242. *
  1243. * Version 3.8 introduces a new column in llx_commande_fournisseur_dispatch, which
  1244. * matches the dispatch to a specific supplier order line (so that if there are
  1245. * several with the same product, the user can specifically tell which products of
  1246. * which line were dispatched where).
  1247. *
  1248. * However when migrating, the new column has a default value of 0, which means that
  1249. * old supplier orders whose lines were dispatched using the old dolibarr version
  1250. * have unspecific dispatch lines, which are not taken into account by the new version,
  1251. * thus making the order look like it was never dispatched at all.
  1252. *
  1253. * This scripts sets this foreign key to the first matching supplier order line whose
  1254. * product (and supplier order of course) are the same as the dispatch’s.
  1255. *
  1256. * If the dispatched quantity is more than indicated on the order line (this happens if
  1257. * there are several order lines for the same product), it creates new dispatch lines
  1258. * pointing to the other order lines accordingly, until all the dispatched quantity is
  1259. * accounted for.
  1260. */
  1261. $repair_link_dispatch_lines_supplier_order_lines = GETPOST('repair_link_dispatch_lines_supplier_order_lines', 'alpha');
  1262. echo '<tr><th>Repair llx_commande_fournisseur_dispatch.fk_commandefourndet</th></tr>';
  1263. echo '<tr><td>Repair in progress. This may take a while.</td></tr>';
  1264. $sql_dispatch = 'SELECT * FROM '.MAIN_DB_PREFIX.'commande_fournisseur_dispatch WHERE COALESCE(fk_commandefourndet, 0) = 0';
  1265. $db->begin();
  1266. $resql_dispatch = $db->query($sql_dispatch);
  1267. $n_processed_rows = 0;
  1268. $errors = array();
  1269. if ($resql_dispatch) {
  1270. if ($db->num_rows($resql_dispatch) == 0) {
  1271. echo '<tr><td>Nothing to do.</td></tr>';
  1272. exit;
  1273. }
  1274. while ($obj_dispatch = $db->fetch_object($resql_dispatch)) {
  1275. $sql_line = 'SELECT line.rowid, line.qty FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet AS line';
  1276. $sql_line .= ' WHERE line.fk_commande = '.((int) $obj_dispatch->fk_commande);
  1277. $sql_line .= ' AND line.fk_product = '.((int) $obj_dispatch->fk_product);
  1278. $resql_line = $db->query($sql_line);
  1279. // s’il y a plusieurs lignes avec le même produit sur cette commande fournisseur,
  1280. // on divise la ligne de dispatch en autant de lignes qu’on en a sur la commande pour le produit
  1281. // et on met la quantité de la ligne dans la limite du "budget" indiqué par dispatch.qty
  1282. $remaining_qty = $obj_dispatch->qty;
  1283. $first_iteration = true;
  1284. if (!$resql_line) {
  1285. echo '<tr><td>Unable to find a matching supplier order line for dispatch #'.$obj_dispatch->rowid.'</td></tr>';
  1286. $errors[] = $sql_line;
  1287. $n_processed_rows++;
  1288. continue;
  1289. }
  1290. if ($db->num_rows($resql_line) == 0) {
  1291. continue;
  1292. }
  1293. while ($obj_line = $db->fetch_object($resql_line)) {
  1294. if (!$remaining_qty) {
  1295. break;
  1296. }
  1297. if (!$obj_line->rowid) {
  1298. continue;
  1299. }
  1300. $qty_for_line = min($remaining_qty, $obj_line->qty);
  1301. if ($first_iteration) {
  1302. $sql_attach = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur_dispatch';
  1303. $sql_attach .= ' SET fk_commandefourndet = '.((int) $obj_line->rowid).', qty = '.((float) $qty_for_line);
  1304. $sql_attach .= ' WHERE rowid = '.((int) $obj_dispatch->rowid);
  1305. $first_iteration = false;
  1306. } else {
  1307. $sql_attach_values = array(
  1308. ((int) $obj_dispatch->fk_commande),
  1309. ((int) $obj_dispatch->fk_product),
  1310. ((int) $obj_line->rowid),
  1311. ((float) $qty_for_line),
  1312. ((int) $obj_dispatch->fk_entrepot),
  1313. ((int) $obj_dispatch->fk_user),
  1314. $obj_dispatch->datec ? "'".$db->idate($db->jdate($obj_dispatch->datec))."'" : 'NULL',
  1315. $obj_dispatch->comment ? "'".$db->escape($obj_dispatch->comment)."'" : 'NULL',
  1316. $obj_dispatch->status ? ((int) $obj_dispatch->status) : 'NULL',
  1317. $obj_dispatch->tms ? "'".$db->idate($db->jdate($obj_dispatch->tms))."'" : 'NULL',
  1318. $obj_dispatch->batch ? "'".$db->escape($obj_dispatch->batch)."'" : 'NULL',
  1319. $obj_dispatch->eatby ? "'".$db->escape($obj_dispatch->eatby)."'" : 'NULL',
  1320. $obj_dispatch->sellby ? "'".$db->escape($obj_dispatch->sellby)."'" : 'NULL'
  1321. );
  1322. $sql_attach_values = join(', ', $sql_attach_values);
  1323. $sql_attach = 'INSERT INTO '.MAIN_DB_PREFIX.'commande_fournisseur_dispatch';
  1324. $sql_attach .= ' (fk_commande, fk_product, fk_commandefourndet, qty, fk_entrepot, fk_user, datec, comment, status, tms, batch, eatby, sellby)';
  1325. $sql_attach .= " VALUES (".$sql_attach_values.")";
  1326. }
  1327. if ($repair_link_dispatch_lines_supplier_order_lines == 'confirmed') {
  1328. $resql_attach = $db->query($sql_attach);
  1329. } else {
  1330. $resql_attach = true; // Force success in test mode
  1331. }
  1332. if ($resql_attach) {
  1333. $remaining_qty -= $qty_for_line;
  1334. } else {
  1335. $errors[] = $sql_attach;
  1336. }
  1337. $first_iteration = false;
  1338. }
  1339. $n_processed_rows++;
  1340. // report progress every 256th row
  1341. if (!($n_processed_rows & 0xff)) {
  1342. echo '<tr><td>Processed '.$n_processed_rows.' rows with '.count($errors).' errors…'."</td></tr>\n";
  1343. flush();
  1344. ob_flush();
  1345. }
  1346. }
  1347. } else {
  1348. echo '<tr><td>Unable to find any dispatch without an fk_commandefourndet.'."</td></tr>\n";
  1349. echo $sql_dispatch."\n";
  1350. }
  1351. echo '<tr><td>Fixed '.$n_processed_rows.' rows with '.count($errors).' errors…'."</td></tr>\n";
  1352. echo '<tr><td>DONE.'."</td></tr>\n";
  1353. if (count($errors)) {
  1354. $db->rollback();
  1355. echo '<tr><td>The transaction was rolled back due to errors: nothing was changed by the script.</td></tr>';
  1356. } else {
  1357. $db->commit();
  1358. }
  1359. $db->close();
  1360. echo '<tr><td><h3>SQL queries with errors:</h3></tr></td>';
  1361. echo '<tr><td>'.join('</td></tr><tr><td>', $errors).'</td></tr>';
  1362. }
  1363. // Repair llx_commande_fournisseur to eleminate duplicate reference
  1364. if ($ok && GETPOST('repair_supplier_order_duplicate_ref')) {
  1365. require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.commande.class.php';
  1366. include_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  1367. $db->begin();
  1368. $err = 0;
  1369. // Query to find all duplicate supplier orders
  1370. $sql = "SELECT * FROM " . MAIN_DB_PREFIX . "commande_fournisseur";
  1371. $sql .= " WHERE ref IN (SELECT cf.ref FROM " . MAIN_DB_PREFIX . "commande_fournisseur cf GROUP BY cf.ref, cf.entity HAVING COUNT(cf.rowid) > 1)";
  1372. // Build a list of ref => []CommandeFournisseur
  1373. $duplicateSupplierOrders = [];
  1374. $resql = $db->query($sql);
  1375. if ($resql) {
  1376. while ($rawSupplierOrder = $db->fetch_object($resql)) {
  1377. $supplierOrder = new CommandeFournisseur($db);
  1378. $supplierOrder->setVarsFromFetchObj($rawSupplierOrder);
  1379. $duplicateSupplierOrders[$rawSupplierOrder->ref] [] = $supplierOrder;
  1380. }
  1381. } else {
  1382. $err++;
  1383. }
  1384. // Process all duplicate supplier order and regenerate the reference for all except the first one
  1385. foreach ($duplicateSupplierOrders as $ref => $supplierOrders) {
  1386. /** @var CommandeFournisseur $supplierOrder */
  1387. foreach (array_slice($supplierOrders, 1) as $supplierOrder) {
  1388. // Definition of supplier order numbering model name
  1389. $soc = new Societe($db);
  1390. $soc->fetch($supplierOrder->fourn_id);
  1391. $newRef = $supplierOrder->getNextNumRef($soc);
  1392. $sql = "UPDATE " . MAIN_DB_PREFIX . "commande_fournisseur cf SET cf.ref = '" . $db->escape($newRef) . "' WHERE cf.rowid = " . (int) $supplierOrder->id;
  1393. if (!$db->query($sql)) {
  1394. $err++;
  1395. }
  1396. }
  1397. }
  1398. if ($err == 0) {
  1399. $db->commit();
  1400. } else {
  1401. $db->rollback();
  1402. }
  1403. }
  1404. print '</table>';
  1405. if (empty($actiondone)) {
  1406. print '<div class="error">'.$langs->trans("ErrorWrongParameters").'</div>';
  1407. }
  1408. if ($oneoptionset) {
  1409. print '<div class="center" style="padding-top: 10px"><a href="../index.php?mainmenu=home&leftmenu=home'.(GETPOSTISSET("login") ? '&username='.urlencode(GETPOST("login")) : '').'">';
  1410. print $langs->trans("GoToDolibarr");
  1411. print '</a></div>';
  1412. } else {
  1413. print '<div class="center warning" style="padding-top: 10px">';
  1414. print $langs->trans("SetAtLeastOneOptionAsUrlParameter");
  1415. print '</div>';
  1416. }
  1417. dolibarr_install_syslog("--- repair: end");
  1418. pFooter(1, $setuplang);
  1419. if ($db->connected) {
  1420. $db->close();
  1421. }
  1422. // Return code if ran from command line
  1423. if (!$ok && isset($argv[1])) {
  1424. exit(1);
  1425. }