dolibarr  7.0.0-beta
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@capnetworks.com>
5  * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <http://www.gnu.org/licenses/>.
19  */
20 
26 include_once 'inc.php';
27 if (file_exists($conffile)) include_once $conffile;
28 require_once $dolibarr_main_document_root.'/core/lib/admin.lib.php';
29 include_once $dolibarr_main_document_root.'/core/lib/images.lib.php';
30 require_once $dolibarr_main_document_root.'/core/class/extrafields.class.php';
31 require_once 'lib/repair.lib.php';
32 
33 $grant_query='';
34 $step = 2;
35 $ok = 0;
36 
37 
38 // Cette page peut etre longue. On augmente le delai autorise.
39 // Ne fonctionne que si on est pas en safe_mode.
40 $err=error_reporting();
41 error_reporting(0);
42 @set_time_limit(120);
43 error_reporting($err);
44 
45 $setuplang=GETPOST("selectlang",'',3)?GETPOST("selectlang",'',3):'auto';
46 $langs->setDefaultLang($setuplang);
47 $versionfrom=GETPOST("versionfrom",'',3)?GETPOST("versionfrom",'',3):(empty($argv[1])?'':$argv[1]);
48 $versionto=GETPOST("versionto",'',3)?GETPOST("versionto",'',3):(empty($argv[2])?'':$argv[2]);
49 
50 $langs->loadLangs(array("admin","install","other"));
51 
52 if ($dolibarr_main_db_type == "mysqli") $choix=1;
53 if ($dolibarr_main_db_type == "pgsql") $choix=2;
54 if ($dolibarr_main_db_type == "mssql") $choix=3;
55 
56 
57 dolibarr_install_syslog("--- repair: entering upgrade.php page");
58 if (! is_object($conf)) dolibarr_install_syslog("repair: conf file not initialized", LOG_ERR);
59 
60 
61 /*
62  * View
63  */
64 
65 pHeader('',"upgrade2",GETPOST('action','aZ09'));
66 
67 // Action to launch the repair script
68 $actiondone=1;
69 
70 print '<h3>'.$langs->trans("Repair").'</h3>';
71 
72 print 'Option standard (0 or \'confirmed\') is '.(GETPOST('standard','alpha')?GETPOST('standard','alpha'):'0').'<br>'."\n";
73 print 'Option restore_thirdparties_logos (0 or \'confirmed\') is '.(GETPOST('restore_thirdparties_logos','alpha')?GETPOST('restore_thirdparties_logos','alpha'):'0').'<br>'."\n";
74 print 'Option clean_linked_elements (0 or \'confirmed\') is '.(GETPOST('clean_linked_elements','alpha')?GETPOST('clean_linked_elements','alpha'):'0').'<br>'."\n";
75 print 'Option clean_menus (0 or \'test\' or \'confirmed\') is '.(GETPOST('clean_menus','alpha')?GETPOST('clean_menus','alpha'):'0').'<br>'."\n";
76 print 'Option clean_orphelin_dir (0 or \'test\' or \'confirmed\') is '.(GETPOST('clean_orphelin_dir','alpha')?GETPOST('clean_orphelin_dir','alpha'):'0').'<br>'."\n";
77 print 'Option clean_product_stock_batch (0 or \'test\' or \'confirmed\') is '.(GETPOST('clean_product_stock_batch','alpha')?GETPOST('clean_product_stock_batch','alpha'):'0').'<br>'."\n";
78 print 'Option set_empty_time_spent_amount (0 or \'test\' or \'confirmed\') is '.(GETPOST('set_empty_time_spent_amount','alpha')?GETPOST('set_empty_time_spent_amount','alpha'):'0').'<br>'."\n";
79 print 'Option rebuild_product_thumbs (0 or \'test\' or \'confirmed\') is '.(GETPOST('rebuild_product_thumbs','alpha')?GETPOST('rebuild_product_thumbs','alpha'):'0').'<br>'."\n";
80 print 'Option force_disable_of_modules_not_found (0 or \'test\' or \'confirmed\') is '.(GETPOST('force_disable_of_modules_not_found','alpha')?GETPOST('force_disable_of_modules_not_found','alpha'):'0').'<br>'."\n";
81 print 'Option force_utf8_on_tables, for mysql/mariadb only (0 or \'test\' or \'confirmed\') is '.(GETPOST('force_utf8_on_tables','alpha')?GETPOST('force_utf8_on_tables','alpha'):'0').'<br>'."\n";
82 print '<br>';
83 
84 print '<table cellspacing="0" cellpadding="1" border="0" width="100%">';
85 $error=0;
86 
87 // If password is encoded, we decode it
88 if (preg_match('/crypted:/i',$dolibarr_main_db_pass) || ! empty($dolibarr_main_db_encrypted_pass))
89 {
90  require_once $dolibarr_main_document_root.'/core/lib/security.lib.php';
91  if (preg_match('/crypted:/i',$dolibarr_main_db_pass))
92  {
93  $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass);
94  $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass);
95  $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
96  }
97  else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass);
98 }
99 
100 // $conf is already instancied inside inc.php
101 $conf->db->type = $dolibarr_main_db_type;
102 $conf->db->host = $dolibarr_main_db_host;
103 $conf->db->port = $dolibarr_main_db_port;
104 $conf->db->name = $dolibarr_main_db_name;
105 $conf->db->user = $dolibarr_main_db_user;
106 $conf->db->pass = $dolibarr_main_db_pass;
107 
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 
112 $db=getDoliDBInstance($conf->db->type,$conf->db->host,$conf->db->user,$conf->db->pass,$conf->db->name,$conf->db->port);
113 
114 if ($db->connected)
115 {
116  print '<tr><td class="nowrap">';
117  print $langs->trans("ServerConnection")." : $dolibarr_main_db_host</td><td align=\"right\">".$langs->trans("OK")."</td></tr>";
118  dolibarr_install_syslog("repair: " . $langs->transnoentities("ServerConnection") . ": " . $dolibarr_main_db_host . $langs->transnoentities("OK"));
119  $ok = 1;
120 }
121 else
122 {
123  print "<tr><td>".$langs->trans("ErrorFailedToConnectToDatabase",$dolibarr_main_db_name)."</td><td align=\"right\">".$langs->transnoentities("Error")."</td></tr>";
124  dolibarr_install_syslog("repair: " . $langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name));
125  $ok = 0;
126 }
127 
128 if ($ok)
129 {
130  if($db->database_selected)
131  {
132  print '<tr><td class="nowrap">';
133  print $langs->trans("DatabaseConnection")." : ".$dolibarr_main_db_name."</td><td align=\"right\">".$langs->trans("OK")."</td></tr>";
134  dolibarr_install_syslog("repair: database connection successful: " . $dolibarr_main_db_name);
135  $ok=1;
136  }
137  else
138  {
139  print "<tr><td>".$langs->trans("ErrorFailedToConnectToDatabase",$dolibarr_main_db_name)."</td><td align=\"right\">".$langs->trans("Error")."</td></tr>";
140  dolibarr_install_syslog("repair: " . $langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name));
141  $ok=0;
142  }
143 }
144 
145 // Show database version
146 if ($ok)
147 {
148  $version=$db->getVersion();
149  $versionarray=$db->getVersionArray();
150  print '<tr><td>'.$langs->trans("ServerVersion").'</td>';
151  print '<td align="right">'.$version.'</td></tr>';
152  dolibarr_install_syslog("repair: " . $langs->transnoentities("ServerVersion") . ": " . $version);
153  //print '<td align="right">'.join('.',$versionarray).'</td></tr>';
154 }
155 
156 $conf->setValues($db);
157 
158 
159 
160 /* Start action here */
161 $oneoptionset=0;
162 $oneoptionset=(GETPOST('standard', 'alpha') || GETPOST('restore_thirdparties_logos','alpha') || GETPOST('clean_linked_elements','alpha') || GETPOST('clean_menus','alpha')
163  || GETPOST('clean_orphelin_dir','alpha') || GETPOST('clean_product_stock_batch','alpha') || GETPOST('set_empty_time_spent_amount','alpha') || GETPOST('rebuild_product_thumbs','alpha')
164  || GETPOST('force_disable_of_modules_not_found','alpha') || GETPOST('force_utf8_on_tables','alpha'));
165 
166 if ($ok && $oneoptionset)
167 {
168  // Show wait message
169  print '<tr><td colspan="2">'.$langs->trans("PleaseBePatient").'<br><br></td></tr>';
170  flush();
171 }
172 
173 
174 // run_sql: Run repair SQL file
175 if ($ok && GETPOST('standard', 'alpha'))
176 {
177  $dir = "mysql/migration/";
178 
179  $filelist=array();
180  $i = 0;
181  $ok = 0;
182 
183  // Recupere list fichier
184  $filesindir=array();
185  $handle=opendir($dir);
186  if (is_resource($handle))
187  {
188  while (($file = readdir($handle))!==false)
189  {
190  if (preg_match('/\.sql$/i',$file)) $filesindir[]=$file;
191  }
192  }
193  sort($filesindir);
194 
195  foreach($filesindir as $file)
196  {
197  if (preg_match('/repair/i',$file))
198  {
199  $filelist[]=$file;
200  }
201  }
202 
203  // Loop on each file
204  foreach($filelist as $file)
205  {
206  print '<tr><td class="nowrap">*** ';
207  print $langs->trans("Script").'</td><td align="right">'.$file.'</td></tr>';
208 
209  $name = substr($file, 0, dol_strlen($file) - 4);
210 
211  // Run sql script
212  $ok=run_sql($dir.$file, 0, '', 1);
213  }
214 }
215 
216 
217 // sync_extrafields: Search list of fields declared and list of fields created into databases, then create fields missing
218 
219 if ($ok && GETPOST('standard', 'alpha'))
220 {
221  $extrafields=new ExtraFields($db);
222  $listofmodulesextra=array('societe'=>'societe','adherent'=>'adherent','product'=>'product',
223  'socpeople'=>'socpeople', 'commande'=>'commande', 'facture'=>'facture',
224  'supplier_proposal'=>'supplier_proposal', 'commande_fournisseur'=>'commande_fournisseur', 'facture_fourn'=>'facture_fourn',
225  'actioncomm'=>'actioncomm',
226  'adherent_type'=>'adherent_type','user'=>'user','projet'=>'projet', 'projet_task'=>'projet_task');
227  print '<tr><td colspan="2"><br>*** Check fields into extra table structure match table of definition. If not add column into table</td></tr>';
228  foreach($listofmodulesextra as $tablename => $elementtype)
229  {
230  // Get list of fields
231  $tableextra=MAIN_DB_PREFIX.$tablename.'_extrafields';
232 
233  // Define $arrayoffieldsdesc
234  $arrayoffieldsdesc=$extrafields->fetch_name_optionals_label($elementtype);
235 
236  // Define $arrayoffieldsfound
237  $arrayoffieldsfound=array();
238  $resql=$db->DDLDescTable($tableextra);
239  if ($resql)
240  {
241  print '<tr><td>Check availability of extra field for '.$tableextra."<br>\n";
242  $i=0;
243  while($obj=$db->fetch_object($resql))
244  {
245  $fieldname=$fieldtype='';
246  if (preg_match('/mysql/',$db->type))
247  {
248  $fieldname=$obj->Field;
249  $fieldtype=$obj->Type;
250  }
251  else
252  {
253  $fieldname = isset($obj->Key)?$obj->Key:$obj->attname;
254  $fieldtype = isset($obj->Type)?$obj->Type:'varchar';
255  }
256 
257  if (empty($fieldname)) continue;
258  if (in_array($fieldname,array('rowid','tms','fk_object','import_key'))) continue;
259  $arrayoffieldsfound[$fieldname]=array('type'=>$fieldtype);
260  }
261 
262  // If it does not match, we create fields
263  foreach($arrayoffieldsdesc as $code => $label)
264  {
265  if (! in_array($code,array_keys($arrayoffieldsfound)))
266  {
267  print 'Found field '.$code.' declared into '.MAIN_DB_PREFIX.'extrafields table but not found into desc of table '.$tableextra." -> ";
268  $type=$extrafields->attribute_type[$code]; $length=$extrafields->attribute_size[$code]; $attribute=''; $default=''; $extra=''; $null='null';
269 
270  if ($type=='boolean') {
271  $typedb='int';
272  $lengthdb='1';
273  } elseif($type=='price') {
274  $typedb='double';
275  $lengthdb='24,8';
276  } elseif($type=='phone') {
277  $typedb='varchar';
278  $lengthdb='20';
279  }elseif($type=='mail') {
280  $typedb='varchar';
281  $lengthdb='128';
282  } elseif (($type=='select') || ($type=='sellist') || ($type=='radio') ||($type=='checkbox') ||($type=='chkbxlst')){
283  $typedb='text';
284  $lengthdb='';
285  } elseif ($type=='link') {
286  $typedb='int';
287  $lengthdb='11';
288  } else {
289  $typedb=$type;
290  $lengthdb=$length;
291  }
292 
293  $field_desc=array(
294  'type'=>$typedb,
295  'value'=>$lengthdb,
296  'attribute'=>$attribute,
297  'default'=>$default,
298  'extra'=>$extra,
299  'null'=>$null
300  );
301  //var_dump($field_desc);exit;
302 
303  $result=$db->DDLAddField($tableextra,$code,$field_desc,"");
304  if ($result < 0)
305  {
306  print "KO ".$db->lasterror."<br>\n";
307  }
308  else
309  {
310  print "OK<br>\n";
311  }
312  }
313  }
314 
315  print "</td><td>&nbsp;</td></tr>\n";
316  }
317  else
318  {
319  dol_print_error($db);
320  }
321  }
322 }
323 
324 
325 
326 // clean_data_ecm_dir: Clean data into ecm_directories table
327 if ($ok && GETPOST('standard', 'alpha'))
328 {
330 }
331 
332 
333 
334 
335 /* From here, actions need a parameter */
336 
337 
338 
339 // restore_thirdparties_logos: Move logos to correct new directory.
340 if ($ok && GETPOST('restore_thirdparties_logos'))
341 {
342  //$exts=array('gif','png','jpg');
343 
344  $ext='';
345 
346  print '<tr><td colspan="2"><br>*** Restore thirdparties logo<br>';
347  //foreach($exts as $ext)
348  //{
349  $sql="SELECT s.rowid, s.nom as name, s.logo FROM ".MAIN_DB_PREFIX."societe as s ORDER BY s.nom";
350  $resql=$db->query($sql);
351  if ($resql)
352  {
353  $num=$db->num_rows($resql);
354  $i=0;
355 
356  while($i < $num)
357  {
358  $obj=$db->fetch_object($resql);
359 
360  /*
361  $name=preg_replace('/é/','',$obj->name);
362  $name=preg_replace('/ /','_',$name);
363  $name=preg_replace('/\'/','',$name);
364  */
365 
366  $tmp=explode('.',$obj->logo);
367  $name=$tmp[0];
368  if (isset($tmp[1])) $ext='.'.$tmp[1];
369 
370  if (! empty($name))
371  {
372  $filetotest=$dolibarr_main_data_root.'/societe/logos/'.$name.$ext;
373  $filetotestsmall=$dolibarr_main_data_root.'/societe/logos/thumbs/'.$name.$ext;
374  $exists=dol_is_file($filetotest);
375  print 'Check thirdparty '.$obj->rowid.' name='.$obj->name.' logo='.$obj->logo.' file '.$filetotest." exists=".$exists."<br>\n";
376  if ($exists)
377  {
378  $filetarget=$dolibarr_main_data_root.'/societe/'.$obj->rowid.'/logos/'.$name.$ext;
379  $filetargetsmall=$dolibarr_main_data_root.'/societe/'.$obj->rowid.'/logos/thumbs/'.$name.'_small'.$ext;
380  $existt=dol_is_file($filetarget);
381  if (! $existt)
382  {
383  dol_mkdir($dolibarr_main_data_root.'/societe/'.$obj->rowid.'/logos');
384 
385  print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotest." -> ".$filetarget."<br>\n";
386  dol_copy($filetotest, $filetarget, '', 0);
387  }
388 
389  $existtt=dol_is_file($filetargetsmall);
390  if (! $existtt)
391  {
392  dol_mkdir($dolibarr_main_data_root.'/societe/'.$obj->rowid.'/logos/thumbs');
393 
394  print " &nbsp; &nbsp; &nbsp; -> Copy file ".$filetotestsmall." -> ".$filetargetsmall."<br>\n";
395  dol_copy($filetotestsmall, $filetargetsmall, '', 0);
396  }
397  }
398  }
399 
400  $i++;
401  }
402  }
403  else
404  {
405  $ok=0;
406  dol_print_error($db);
407  }
408 
409  print '</td></tr>';
410  //}
411 }
412 
413 
414 // rebuild_product_thumbs: Rebuild thumbs for product files
415 if ($ok && GETPOST('rebuild_product_thumbs','alpha'))
416 {
417  $ext='';
418  global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
419 
420  print '<tr><td colspan="2"><br>*** Rebuild product thumbs<br>';
421 
422  $sql="SELECT s.rowid, s.ref FROM ".MAIN_DB_PREFIX."product as s ORDER BY s.ref";
423  $resql=$db->query($sql);
424  if ($resql)
425  {
426  $num=$db->num_rows($resql);
427  $i=0;
428 
429  while($i < $num)
430  {
431  $obj=$db->fetch_object($resql);
432 
433  if (! empty($obj->ref))
434  {
435  $files=dol_dir_list($dolibarr_main_data_root.'/produit/'.$obj->ref, 'files', 0);
436  foreach($files as $file)
437  {
438  // Generate thumbs.
439  if (image_format_supported($file['fullname']) == 1)
440  {
441  $imgThumbSmall='notbuild';
442  if (GETPOST('rebuild_product_thumbs','alpha') == 'confirmed')
443  {
444  // Used on logon for example
445  $imgThumbSmall = vignette($file['fullname'], $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
446  }
447  print 'Check product '.$obj->rowid.", file ".$file['fullname']." -> ".$imgThumbSmall." maxwidthsmall=".$maxwidthsmall." maxheightsmall=".$maxheightsmall."<br>\n";
448  $imgThumbMini='notbuild';
449  if (GETPOST('rebuild_product_thumbs','alpha') == 'confirmed')
450  {
451  // Create mini thumbs for image (Ratio is near 16/9)
452  // Used on menu or for setup page for example
453  $imgThumbMini = vignette($file['fullname'], $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
454  }
455  print 'Check product '.$obj->rowid.", file ".$file['fullname']." -> ".$imgThumbMini." maxwidthmini=".$maxwidthmini." maxheightmini=".$maxheightmini."<br>\n";
456  }
457  }
458  }
459 
460  $i++;
461  }
462  }
463  else
464  {
465  $ok=0;
466  dol_print_error($db);
467  }
468 
469  print '</td></tr>';
470 }
471 
472 // clean_linked_elements: Check and clean linked elements
473 if ($ok && GETPOST('clean_linked_elements','alpha'))
474 {
475  print '<tr><td colspan="2"><br>*** Check table of linked elements and delete orphelins links</td></tr>';
476  // propal => order
477  print '<tr><td colspan="2">'.checkLinkedElements('propal', 'commande')."</td></tr>\n";
478 
479  // propal => invoice
480  print '<tr><td colspan="2">'.checkLinkedElements('propal', 'facture')."</td></tr>\n";
481 
482  // order => invoice
483  print '<tr><td colspan="2">'.checkLinkedElements('commande', 'facture')."</td></tr>\n";
484 
485  // order => shipping
486  print '<tr><td colspan="2">'.checkLinkedElements('commande', 'shipping')."</td></tr>\n";
487 
488  // shipping => delivery
489  print '<tr><td colspan="2">'.checkLinkedElements('shipping', 'delivery')."</td></tr>\n";
490 
491  // order_supplier => invoice_supplier
492  print '<tr><td colspan="2">'.checkLinkedElements('order_supplier', 'invoice_supplier')."</td></tr>\n";
493 }
494 
495 
496 // clean_menus: Check orphelins menus
497 if ($ok && GETPOST('clean_menus','alpha'))
498 {
499  print '<tr><td colspan="2"><br>*** Clean menu entries coming from disabled modules</td></tr>';
500 
501  $sql ="SELECT rowid, module";
502  $sql.=" FROM ".MAIN_DB_PREFIX."menu as c";
503  $sql.=" WHERE module IS NOT NULL AND module <> ''";
504  $sql.=" ORDER BY module";
505 
506  $resql = $db->query($sql);
507  if ($resql)
508  {
509  $num = $db->num_rows($resql);
510  if ($num)
511  {
512  $i = 0;
513  while ($i < $num)
514  {
515  $obj=$db->fetch_object($resql);
516 
517  $modulecond=$obj->module;
518  $modulecondarray = explode('|',$obj->module); // Name of module
519 
520  print '<tr><td>';
521  print $modulecond;
522 
523  $db->begin();
524 
525  if ($modulecond) // And menu entry for module $modulecond was found in database.
526  {
527  $moduleok=0;
528  foreach($modulecondarray as $tmpname)
529  {
530  if ($tmpname == 'margins') $tmpname='margin'; // TODO Remove this when normalized
531 
532  $result = 0;
533  if (! empty($conf->$tmpname)) $result = $conf->$tmpname->enabled;
534  if ($result) $moduleok++;
535  }
536 
537  if (! $moduleok && $modulecond)
538  {
539  print ' - Module condition '.$modulecond.' seems ko, we delete menu entry.';
540  if (GETPOST('clean_menus') == 'confirmed')
541  {
542  $sql2 ="DELETE FROM ".MAIN_DB_PREFIX."menu WHERE module = '".$modulecond."'";
543  $resql2=$db->query($sql2);
544  if (! $resql2)
545  {
546  $error++;
547  dol_print_error($db);
548  }
549  else
550  print ' - <font class="warning">Cleaned</font>';
551  }
552  else
553  {
554  print ' - <font class="warning">Canceled (test mode)</font>';
555  }
556  }
557  else
558  {
559  print ' - Module condition '.$modulecond.' is ok, we do nothing.';
560  }
561  }
562 
563  if (!$error) $db->commit();
564  else $db->rollback();
565 
566  print'</td></tr>';
567 
568  if ($error) break;
569 
570  $i++;
571  }
572  }
573  else
574  {
575  print '<tr><td>No menu entries of disabled menus found</td></tr>';
576  }
577  }
578  else
579  {
580  dol_print_error($db);
581  }
582 }
583 
584 
585 
586 // clean_orphelin_dir: Run purge of directory
587 if ($ok && GETPOST('clean_orphelin_dir','alpha'))
588 {
589  $conf->setValues($db);
590 
591  $listmodulepart=array('company','invoice','invoice_supplier','propal','order','order_supplier','contract','tax');
592  foreach ($listmodulepart as $modulepart)
593  {
594  $filearray=array();
595  $upload_dir = isset($conf->$modulepart->dir_output)?$conf->$modulepart->dir_output:'';
596  if ($modulepart == 'company') $upload_dir = $conf->societe->dir_output; // TODO change for multicompany sharing
597  if ($modulepart == 'invoice') $upload_dir = $conf->facture->dir_output;
598  if ($modulepart == 'invoice_supplier') $upload_dir = $conf->fournisseur->facture->dir_output;
599  if ($modulepart == 'order') $upload_dir = $conf->commande->dir_output;
600  if ($modulepart == 'order_supplier') $upload_dir = $conf->fournisseur->commande->dir_output;
601  if ($modulepart == 'contract') $upload_dir = $conf->contrat->dir_output;
602 
603  if (empty($upload_dir)) continue;
604 
605  print '<tr><td colspan="2"><br>*** Clean orphelins files into files '.$upload_dir.'</td></tr>';
606 
607  $filearray=dol_dir_list($upload_dir,"files",1,'',array('^SPECIMEN\.pdf$','^\.','(\.meta|_preview.*\.png)$','^temp$','^payments$','^CVS$','^thumbs$'),'',SORT_DESC,1,true);
608 
609  // To show ref or specific information according to view to show (defined by $module)
610  if ($modulepart == 'company')
611  {
612  include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
613  $object_instance=new Societe($db);
614  }
615  if ($modulepart == 'invoice')
616  {
617  include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
618  $object_instance=new Facture($db);
619  }
620  else if ($modulepart == 'invoice_supplier')
621  {
622  include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
623  $object_instance=new FactureFournisseur($db);
624  }
625  else if ($modulepart == 'propal')
626  {
627  include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
628  $object_instance=new Propal($db);
629  }
630  else if ($modulepart == 'order')
631  {
632  include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
633  $object_instance=new Commande($db);
634  }
635  else if ($modulepart == 'order_supplier')
636  {
637  include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
638  $object_instance=new CommandeFournisseur($db);
639  }
640  else if ($modulepart == 'contract')
641  {
642  include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
643  $object_instance=new Contrat($db);
644  }
645  else if ($modulepart == 'tax')
646  {
647  include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
648  $object_instance=new ChargeSociales($db);
649  }
650 
651  $var=true;
652  foreach($filearray as $key => $file)
653  {
654  if (!is_dir($file['name'])
655  && $file['name'] != '.'
656  && $file['name'] != '..'
657  && $file['name'] != 'CVS'
658  )
659  {
660  // Define relative path used to store the file
661  $relativefile=preg_replace('/'.preg_quote($upload_dir.'/','/').'/','',$file['fullname']);
662 
663  //var_dump($file);
664  $id=0; $ref=''; $object_instance->id=0; $object_instance->ref=''; $label='';
665 
666  // To show ref or specific information according to view to show (defined by $module)
667  if ($modulepart == 'invoice') {
668  preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=$reg[1];
669  }
670  if ($modulepart == 'invoice_supplier') {
671  preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=empty($reg[1])?'':$reg[1];
672  }
673  if ($modulepart == 'propal') {
674  preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=$reg[1];
675  }
676  if ($modulepart == 'order') {
677  preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=$reg[1];
678  }
679  if ($modulepart == 'order_supplier') {
680  preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=$reg[1];
681  }
682  if ($modulepart == 'contract') {
683  preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg); $ref=$reg[1];
684  }
685  if ($modulepart == 'tax') {
686  preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=$reg[1];
687  }
688 
689  if ($id || $ref)
690  {
691  //print 'Fetch '.$id.' or '.$ref.'<br>';
692  $result=$object_instance->fetch($id,$ref);
693  //print $result.'<br>';
694  if ($result == 0) // Not found but no error
695  {
696  // Clean of orphelins directories are done into repair.php
697  print '<tr><td colspan="2">';
698  print 'Delete orphelins file '.$file['fullname'].'<br>';
699  if (GETPOST('clean_orphelin_dir','alpha') == 'confirmed')
700  {
701  dol_delete_file($file['fullname'],1,1,1);
702  dol_delete_dir(dirname($file['fullname']),1);
703  }
704  print "</td></tr>";
705  }
706  else if ($result < 0) print 'Error in '.get_class($object_instance).'.fetch of id'.$id.' ref='.$ref.', result='.$result.'<br>';
707  }
708  }
709  }
710  }
711 }
712 
713 // clean_linked_elements: Check and clean linked elements
714 if ($ok && GETPOST('clean_product_stock_batch','alpha'))
715 {
716  $methodtofix=GETPOST('methodtofix','alpha')?GETPOST('methodtofix','alpha'):'updatestock';
717 
718  print '<tr><td colspan="2"><br>*** Clean table product_batch, methodtofix='.$methodtofix.' (possible values: updatestock or updatebatch)</td></tr>';
719 
720  $sql ="SELECT p.rowid, p.ref, p.tobatch, ps.rowid as psrowid, ps.fk_entrepot, ps.reel, SUM(pb.qty) as reelbatch";
721  $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";
722  $sql.=" WHERE p.rowid = ps.fk_product";
723  $sql.=" AND p.tobatch = 1";
724  $sql.=" GROUP BY p.rowid, p.ref, p.tobatch, ps.rowid, ps.fk_entrepot, ps.reel";
725  $sql.=" HAVING reel != SUM(pb.qty) or SUM(pb.qty) IS NULL";
726  print $sql;
727  $resql = $db->query($sql);
728  if ($resql)
729  {
730  $num = $db->num_rows($resql);
731 
732  if ($num)
733  {
734  $i = 0;
735  while ($i < $num)
736  {
737  $obj=$db->fetch_object($resql);
738  print '<tr><td>Product '.$obj->rowid.'-'.$obj->ref.' in warehose '.$obj->fk_entrepot.' -> '.$obj->psrowid.': '.$obj->reel.' (product_stock.reel) != '.($obj->reelbatch?$obj->reelbatch:'0').' (sum product_batch)';
739 
740  // Fix
741  if ($obj->reel != $obj->reelbatch)
742  {
743  if ($methodtofix == 'updatebatch')
744  {
745  // Method 1
746  print ' -> Insert qty '.($obj->reel - $obj->reelbatch).' with lot 000000 linked to fk_product_stock='.$obj->psrowid;
747  if (GETPOST('clean_product_stock_batch') == 'confirmed')
748  {
749  $sql2 ="INSERT INTO ".MAIN_DB_PREFIX."product_batch(fk_product_stock, batch, qty)";
750  $sql2.="VALUES(".$obj->psrowid.", '000000', ".($obj->reel - $obj->reelbatch).")";
751  $resql2=$db->query($sql2);
752  if (! $resql2)
753  {
754  // TODO If it fails, we must make update
755  //$sql2 ="UPDATE ".MAIN_DB_PREFIX."product_batch";
756  //$sql2.=" SET ".$obj->psrowid.", '000000', ".($obj->reel - $obj->reelbatch).")";
757  //$sql2.=" WHERE fk_product_stock = ".$obj->psrowid"
758  }
759  }
760  }
761  if ($methodtofix == 'updatestock')
762  {
763  // Method 2
764  print ' -> Update qty of product_stock with qty = '.($obj->reelbatch?$obj->reelbatch:'0').' for ps.rowid = '.$obj->psrowid;
765  if (GETPOST('clean_product_stock_batch') == 'confirmed')
766  {
767  $error=0;
768 
769  $db->begin();
770 
771  $sql2 ="UPDATE ".MAIN_DB_PREFIX."product_stock";
772  $sql2.=" SET reel = ".($obj->reelbatch?$obj->reelbatch:'0')." WHERE rowid = ".$obj->psrowid;
773  $resql2=$db->query($sql2);
774  if ($resql2)
775  {
776  // We update product_stock, so we must field stock into product too.
777  $sql3='UPDATE llx_product p SET p.stock= (SELECT SUM(ps.reel) FROM llx_product_stock ps WHERE ps.fk_product = p.rowid)';
778  $resql3=$db->query($sql3);
779  if (! $resql3)
780  {
781  $error++;
782  dol_print_error($db);
783  }
784  }
785  else
786  {
787  $error++;
788  dol_print_error($db);
789  }
790 
791  if (!$error) $db->commit();
792  else $db->rollback();
793  }
794  }
795  }
796 
797  print'</td></tr>';
798 
799  $i++;
800  }
801  }
802  else
803  {
804  print '<tr><td colspan="2">Nothing to do</td></tr>';
805  }
806  }
807  else
808  {
809  dol_print_error($db);
810  }
811 }
812 
813 
814 // clean_linked_elements: Check and clean linked elements
815 if ($ok && GETPOST('clean_product_stock_negative_if_batch','alpha'))
816 {
817  print '<tr><td colspan="2"><br>Clean table product_batch, methodtofix='.$methodtofix.' (possible values: updatestock or updatebatch)</td></tr>';
818 
819  $sql ="SELECT p.rowid, p.ref, p.tobatch, ps.rowid as psrowid, ps.fk_entrepot, ps.reel, SUM(pb.qty) as reelbatch";
820  $sql.=" FROM ".MAIN_DB_PREFIX."product as p, ".MAIN_DB_PREFIX."product_stock as ps, ".MAIN_DB_PREFIX."product_batch as pb";
821  $sql.=" WHERE p.rowid = ps.fk_product AND ps.rowid = pb.fk_product_stock";
822  $sql.=" AND p.tobatch = 1";
823  $sql.=" GROUP BY p.rowid, p.ref, p.tobatch, ps.rowid, ps.fk_entrepot, ps.reel";
824  $sql.=" HAVING reel != SUM(pb.qty)";
825  $resql = $db->query($sql);
826  if ($resql)
827  {
828  $num = $db->num_rows($resql);
829 
830  if ($num)
831  {
832  $i = 0;
833  while ($i < $num)
834  {
835  $obj=$db->fetch_object($resql);
836  print '<tr><td>'.$obj->rowid.'-'.$obj->ref.'-'.$obj->fk_entrepot.' -> '.$obj->psrowid.': '.$obj->reel.' != '.$obj->reelbatch;
837 
838  }
839  }
840  }
841 }
842 
843 // clean_linked_elements: Check and clean linked elements
844 if ($ok && GETPOST('set_empty_time_spent_amount','alpha'))
845 {
846  print '<tr><td colspan="2"><br>*** Set value of time spent without amount</td></tr>';
847 
848  $sql ="SELECT COUNT(ptt.rowid) as nb, u.rowid as user_id, u.login, u.thm as user_thm";
849  $sql.=" FROM ".MAIN_DB_PREFIX."projet_task_time as ptt, ".MAIN_DB_PREFIX."user as u";
850  $sql.=" WHERE ptt.fk_user = u.rowid";
851  $sql.=" AND ptt.thm IS NULL and u.thm > 0";
852  $sql.=" GROUP BY u.rowid, u.login, u.thm";
853 
854  $resql = $db->query($sql);
855  if ($resql)
856  {
857  $num = $db->num_rows($resql);
858 
859  if ($num)
860  {
861  $i = 0;
862  while ($i < $num)
863  {
864  $obj=$db->fetch_object($resql);
865  print '<tr><td>'.$obj->login.'-'.$obj->user_id.' ('.$obj->nb.' lines to fix) -> '.$obj->user_thm;
866 
867  $db->begin();
868 
869  if (GETPOST('set_empty_time_spent_amount') == 'confirmed')
870  {
871  $sql2 ="UPDATE ".MAIN_DB_PREFIX."projet_task_time";
872  $sql2.=" SET thm = ".$obj->user_thm." WHERE thm IS NULL AND fk_user = ".$obj->user_id;
873  $resql2=$db->query($sql2);
874  if (! $resql2)
875  {
876  $error++;
877  dol_print_error($db);
878  }
879  }
880 
881  if (!$error) $db->commit();
882  else $db->rollback();
883 
884  print'</td></tr>';
885 
886  if ($error) break;
887 
888  $i++;
889  }
890  }
891  else
892  {
893  print '<tr><td>No time spent with empty line on users with a hourly rate defined</td></tr>';
894  }
895  }
896  else
897  {
898  dol_print_error($db);
899  }
900 
901 }
902 
903 
904 // clean_old_module_entries: Clean data into const when files of module were removed without being
905 if ($ok && GETPOST('force_disable_of_modules_not_found','alpha'))
906 {
907  print '<tr><td colspan="2"><br>*** Force modules not found to be disabled</td></tr>';
908 
909  $arraylistofkey=array('hooks','js','css');
910 
911  foreach($arraylistofkey as $key)
912  {
913  $sql ="SELECT DISTINCT name, value";
914  $sql.=" FROM ".MAIN_DB_PREFIX."const as c";
915  $sql.=" WHERE name LIKE 'MAIN_MODULE_%_".strtoupper($key)."'";
916  $sql.=" ORDER BY name";
917 
918  $resql = $db->query($sql);
919  if ($resql)
920  {
921  $num = $db->num_rows($resql);
922  if ($num)
923  {
924  $i = 0;
925  while ($i < $num)
926  {
927  $obj=$db->fetch_object($resql);
928  $constantname = $obj->name; // Name of constant for hook or js or css declaration
929 
930  print '<tr><td>';
931  print $constantname;
932 
933  $db->begin();
934 
935  if (preg_match('/MAIN_MODULE_(.*)_'.strtoupper($key).'/i', $constantname, $reg))
936  {
937  $name=strtolower($reg[1]);
938 
939  if ($name) // And entry for key $key and module $name was found in database.
940  {
941  if ($key == 'hooks') $reloffile=$name.'/class/actions_'.$name.'.class.php';
942  if ($key == 'js')
943  {
944  $value=$obj->value;
945  $valuearray=json_decode($value);
946  $reloffile=$valuearray[0];
947  $reloffile=preg_replace('/^\//','',$valuearray[0]);
948  }
949  if ($key == 'css')
950  {
951  $value=$obj->value;
952  $valuearray=json_decode($value);
953  if ($value && count($valuearray)==0) $valuearray[0]=$value; // If value was not a json array but a string
954  $reloffile=preg_replace('/^\//','',$valuearray[0]);
955  }
956 
957  //var_dump($key.' - '.$value.' - '.$reloffile);
958  try {
959  $result = dol_buildpath($reloffile, 0, 2);
960  }
961  catch(Exception $e)
962  {
963  // No catch yet
964  }
965 
966  if (! $result)
967  {
968  print ' - File of '.$key.' ('.$reloffile.') NOT found, we disable the module.';
969  if (GETPOST('force_disable_of_modules_not_found') == 'confirmed')
970  {
971  $sql2 ="DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = 'MAIN_MODULE_".strtoupper($name)."_".strtoupper($key)."'";
972  $resql2=$db->query($sql2);
973  if (! $resql2)
974  {
975  $error++;
976  dol_print_error($db);
977  }
978  $sql2 ="DELETE FROM ".MAIN_DB_PREFIX."const WHERE name = 'MAIN_MODULE_".strtoupper($name)."'";
979  $resql2=$db->query($sql2);
980  if (! $resql2)
981  {
982  $error++;
983  dol_print_error($db);
984  }
985  else
986  print ' - <font class="warning">Cleaned</font>';
987  }
988  else
989  {
990  print ' - <font class="warning">Canceled (test mode)</font>';
991  }
992  }
993  else
994  {
995  print ' - File of '.$key.' ('.$reloffile.') found, we do nothing.';
996  }
997  }
998 
999  if (!$error) $db->commit();
1000  else $db->rollback();
1001  }
1002 
1003  print'</td></tr>';
1004 
1005  if ($error) break;
1006 
1007  $i++;
1008  }
1009  }
1010  else
1011  {
1012  print '<tr><td>No active module with missing files found by searching on MAIN_MODULE_(.*)_'.strtoupper($key).'</td></tr>';
1013  }
1014  }
1015  else
1016  {
1017  dol_print_error($db);
1018  }
1019  }
1020 }
1021 
1022 
1023 
1024 
1025 // clean_linked_elements: Check and clean linked elements
1026 if ($ok && GETPOST('force_utf8_on_tables','alpha'))
1027 {
1028  print '<tr><td colspan="2"><br>*** Force page code and collation of tables into utf8/utf8_unicode_ci (for mysql/mariadb only)</td></tr>';
1029 
1030  if ($db->type == "mysql" || $db->type == "mysqli")
1031  {
1032  $listoftables = $db->DDLListTables($db->database_name);
1033 
1034  foreach($listoftables as $table)
1035  {
1036  print '<tr><td colspan="2">';
1037  print $table;
1038  $sql='ALTER TABLE '.$table.' CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci';
1039  print '<!-- '.$sql.' -->';
1040  if (GETPOST('force_utf8_on_tables','alpha') == 'confirmed')
1041  {
1042  $resql = $db->query($sql);
1043  print ' - Done ('.($resql?'OK':'KO').')';
1044  }
1045  else print ' - Disabled';
1046  print '</td></tr>';
1047  }
1048  }
1049  else
1050  {
1051  print '<tr><td colspan="2">Not available with database type '.$db->type.'</td></tr>';
1052  }
1053 }
1054 
1055 
1056 print '</table>';
1057 
1058 
1059 
1060 if (empty($actiondone))
1061 {
1062  print '<div class="error">'.$langs->trans("ErrorWrongParameters").'</div>';
1063 }
1064 
1065 if ($oneoptionset)
1066 {
1067  print '<div class="center" style="padding-top: 10px"><a href="../index.php?mainmenu=home&leftmenu=home'.(isset($_POST["login"])?'&username='.urlencode($_POST["login"]):'').'">';
1068  print $langs->trans("GoToDolibarr");
1069  print '</a></div>';
1070 }
1071 else
1072 {
1073  print '<div class="center warning" style="padding-top: 10px">';
1074  print $langs->trans("SetAtLeastOneOptionAsUrlParameter");
1075  print '</div>';
1076 }
1077 
1078 dolibarr_install_syslog("--- repair: end");
1079 pFooter(1,$setuplang);
1080 
1081 if ($db->connected) $db->close();
1082 
1083 // Return code if ran from command line
1084 if (! $ok && isset($argv[1])) exit(1);
image_format_supported($file)
Return if a filename is file name of a supported image format.
Definition: images.lib.php:38
dol_copy($srcfile, $destfile, $newmask=0, $overwriteifexists=1)
Copy a file to another file.
Definition: files.lib.php:631
getDoliDBInstance($type, $host, $user, $pass, $name, $port)
Return a DoliDB instance (database handler).
clean_data_ecm_directories()
Clean data into ecm_directories table.
Definition: repair.lib.php:118
if(GETPOST('cancel','alpha')) if(!GETPOST('confirmmassaction','alpha')&&$massaction!= 'presend'&&$massaction!= 'confirm_presend')
Draft customers invoices.
Definition: list.php:147
Class to manage contracts.
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
Class to manage suppliers invoices.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="")
Scan a directory and return a list of files/directories.
Definition: files.lib.php:58
GETPOST($paramname, $check='none', $method=0, $filter=NULL, $options=NULL, $noreplace=0)
Return value of a param into GET or POST supervariable.
dolibarr_install_syslog($message, $level=LOG_DEBUG)
Log function for install pages.
Definition: inc.php:499
pHeader($subtitle, $next, $action='set', $param='', $forcejqueryurl='', $csstable='main-inside')
Show HTML header of install pages.
Definition: inc.php:367
Class to manage standard extra fields.
Class to manage third parties objects (customers, suppliers, prospects...)
dol_decode($chain)
Decode a base 64 encoded + specific string.
Class to manage customers orders.
Class to manage predefined suppliers products.
dol_is_file($pathoffile)
Return if path is a file.
Definition: files.lib.php:427
pFooter($nonext=0, $setuplang='', $jscheckfunction='', $withpleasewait=0)
Print HTML footer of install pages.
Definition: inc.php:442
print
Draft customers invoices.
Definition: index.php:91
dol_mkdir($dir, $dataroot='', $newmask=null)
Creation of a directory (this can create recursive subdir)
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if(!empty($conf->fournisseur->enabled)&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->societe->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if(!empty($conf->fournisseur->enabled)&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1013
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null)
Remove a file or several files with a mask.
Definition: files.lib.php:1103
run_sql($sqlfile, $silent=1, $entity='', $usesavepoint=1, $handler='', $okerror='default')
Launch a sql file.
Definition: admin.lib.php:126
Class to manage invoices.
dol_delete_dir($dir, $nophperrors=0)
Remove a directory (not recursive, so content must be empty).
Definition: files.lib.php:1210
Classe permettant la gestion des paiements des charges La tva collectee n'est calculee que sur les fa...
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Class to manage proposals.
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)...
Definition: images.lib.php:352