dolibarr  20.0.0-beta
export.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2005-2011 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
4  * Copyright (C) 2012 Charles-Fr BENKE <charles.fr@benke.fr>
5  * Copyright (C) 2016 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 <https://www.gnu.org/licenses/>.
19  */
20 
31 class Export
32 {
36  public $db;
37 
41  public $id;
42 
43  public $array_export_icon;
44 
45  public $array_export_perms;
46 
47 
51  public $error;
55  public $errno;
59  public $errors;
60 
61  public $array_export_code = array(); // Tableau de "idmodule_numexportprofile"
62  public $array_export_code_for_sort = array(); // Tableau de "idmodule_numexportprofile"
63  public $array_export_module = array(); // Tableau de "nom de modules"
64  public $array_export_label = array(); // Tableau de "libelle de lots"
65  public $array_export_sql_start = array(); // Tableau des "requetes sql"
66  public $array_export_sql_end = array(); // Tableau des "requetes sql"
67  public $array_export_sql_order = array(); // Tableau des "requetes sql"
68 
69  public $array_export_fields = array(); // Tableau des listes de champ+libelle a exporter
70  public $array_export_TypeFields = array(); // Tableau des listes de champ+Type de filtre
71  public $array_export_FilterValue = array(); // Tableau des listes de champ+Valeur a filtrer
72  public $array_export_entities = array(); // Tableau des listes de champ+alias a exporter
73  public $array_export_dependencies = array(); // array of list of entities that must take care of the DISTINCT if a field is added into export
74  public $array_export_special = array(); // array of special operations to do on field
75  public $array_export_examplevalues = array(); // array with examples for fields
76  public $array_export_help = array(); // array with tooltip help for fields
77 
78  // To store export templates
79  public $hexa; // List of fields in the export profile
80  public $hexafiltervalue; // List of search criteria in the export profile
81  public $datatoexport;
82  public $model_name; // Name of export profile
83  public $fk_user;
84 
85  public $sqlusedforexport;
86 
87 
93  public function __construct($db)
94  {
95  $this->db = $db;
96  }
97 
98 
99  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
107  public function load_arrays($user, $filter = '')
108  {
109  // phpcs:enable
110  global $langs, $conf, $mysoc;
111 
112  dol_syslog(get_class($this)."::load_arrays user=".$user->id." filter=".$filter);
113 
114  $i = 0;
115 
116  // Define list of modules directories into modulesdir
117  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
118 
119  $modulesdir = dolGetModulesDirs();
120 
121  foreach ($modulesdir as $dir) {
122  // Search available exports
123  $handle = @opendir(dol_osencode($dir));
124  if (is_resource($handle)) {
125  // Search module files
126  while (($file = readdir($handle)) !== false) {
127  $reg = array();
128  if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) {
129  $modulename = $reg[1];
130 
131  // Defined if module is enabled
132  $enabled = true;
133  $part = strtolower(preg_replace('/^mod/i', '', $modulename));
134  if ($part == 'propale') {
135  $part = 'propal';
136  }
137  if (empty($conf->$part->enabled)) {
138  $enabled = false;
139  }
140 
141  if ($enabled) {
142  // Loading Class
143  $file = $dir.$modulename.".class.php";
144  $classname = $modulename;
145  require_once $file;
146  $module = new $classname($this->db);
147 
148  if (isset($module->export_code) && is_array($module->export_code)) {
149  foreach ($module->export_code as $r => $value) {
150  //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).'<br>';
151  if ($filter && ($filter != $module->export_code[$r])) {
152  continue;
153  }
154 
155  // Test if condition to show are ok
156  if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) {
157  continue;
158  }
159 
160  // Test if permissions are ok
161  $bool = true;
162  if (isset($module->export_permission)) {
163  foreach ($module->export_permission[$r] as $val) {
164  $perm = $val;
165  //print_r("$perm[0]-$perm[1]-$perm[2]<br>");
166  if (!empty($perm[2])) {
167  $bool = isset($user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]}) ? $user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]} : false;
168  } elseif (!empty($perm[1])) {
169  $bool = isset($user->rights->{$perm[0]}->{$perm[1]}) ? $user->rights->{$perm[0]}->{$perm[1]} : false;
170  } else {
171  $bool = false;
172  }
173  if ($perm[0] == 'user' && $user->admin) {
174  $bool = true;
175  }
176  if (!$bool) {
177  break;
178  }
179  }
180  }
181  //print $bool." $perm[0]"."<br>";
182 
183  // Permissions ok
184  // if ($bool)
185  // {
186  // Charge fichier lang en rapport
187  $langtoload = $module->getLangFilesArray();
188  if (is_array($langtoload)) {
189  foreach ($langtoload as $key) {
190  $langs->load($key);
191  }
192  }
193 
194 
195  // Module
196  $this->array_export_module[$i] = $module;
197  // Permission
198  $this->array_export_perms[$i] = $bool;
199  // Icon
200  $this->array_export_icon[$i] = (isset($module->export_icon[$r]) ? $module->export_icon[$r] : $module->picto);
201  // Code of the export dataset / Code du dataset export
202  $this->array_export_code[$i] = $module->export_code[$r];
203  // Define a key for sort
204  $this->array_export_code_for_sort[$i] = $module->module_position.'_'.$module->export_code[$r]; // Add a key into the module
205  // Export Dataset Label / Libelle du dataset export
206  $this->array_export_label[$i] = $module->getExportDatasetLabel($r);
207  // Table of fields to export / Tableau des champ a exporter (cle=champ, valeur=libelle)
208  $this->array_export_fields[$i] = $module->export_fields_array[$r];
209  // Table of fields to be filtered (key=field, value1=data type) Verifies that the module has filters
210  $this->array_export_TypeFields[$i] = (isset($module->export_TypeFields_array[$r]) ? $module->export_TypeFields_array[$r] : '');
211  // Table of entities to export (key=field, value=entity)
212  $this->array_export_entities[$i] = $module->export_entities_array[$r];
213  // Table of entities requiring to abandon DISTINCT (key=entity, valeur=field id child records)
214  $this->array_export_dependencies[$i] = (!empty($module->export_dependencies_array[$r]) ? $module->export_dependencies_array[$r] : '');
215  // Table of special field operations / Tableau des operations speciales sur champ
216  $this->array_export_special[$i] = (!empty($module->export_special_array[$r]) ? $module->export_special_array[$r] : '');
217  // Array of examples
218  $this->array_export_examplevalues[$i] = (!empty($module->export_examplevalues_array[$r]) ? $module->export_examplevalues_array[$r] : null);
219  // Array of help tooltips
220  $this->array_export_help[$i] = (!empty($module->export_help_array[$r]) ? $module->export_help_array[$r] : '');
221 
222  // SQL dataset query / Requete SQL du dataset
223  $this->array_export_sql_start[$i] = $module->export_sql_start[$r];
224  $this->array_export_sql_end[$i] = $module->export_sql_end[$r];
225  $this->array_export_sql_order[$i] = (!empty($module->export_sql_order[$r]) ? $module->export_sql_order[$r] : null);
226  //$this->array_export_sql[$i]=$module->export_sql[$r];
227 
228  dol_syslog(get_class($this)."::load_arrays loaded for module ".$modulename." with index ".$i.", dataset=".$module->export_code[$r].", nb of fields=".(!empty($module->export_fields_code[$r]) ? count($module->export_fields_code[$r]) : ''));
229  $i++;
230  // }
231  }
232  }
233  }
234  }
235  }
236  closedir($handle);
237  }
238  }
239 
240  return 1;
241  }
242 
243 
244  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
254  public function build_sql($indice, $array_selected, $array_filterValue)
255  {
256  // phpcs:enable
257  // Build the sql request
258  $sql = $this->array_export_sql_start[$indice];
259  $i = 0;
260 
261  //print_r($array_selected);
262  foreach ($this->array_export_fields[$indice] as $key => $value) {
263  if (!array_key_exists($key, $array_selected)) {
264  continue; // Field not selected
265  }
266  if (preg_match('/^none\./', $key)) {
267  continue; // A field that must not appears into SQL
268  }
269  if ($i > 0) {
270  $sql .= ', ';
271  } else {
272  $i++;
273  }
274 
275  if (strpos($key, ' as ') === false) {
276  $newfield = $key.' as '.str_replace(array('.', '-', '(', ')'), '_', $key);
277  } else {
278  $newfield = $key;
279  }
280 
281  $sql .= $newfield;
282  }
283  $sql .= $this->array_export_sql_end[$indice];
284 
285  // Add the WHERE part. Filtering into sql if a filtering array is provided
286  if (is_array($array_filterValue) && !empty($array_filterValue)) {
287  $sqlWhere = '';
288  // Loop on each condition to add
289  foreach ($array_filterValue as $key => $value) {
290  if (preg_match('/GROUP_CONCAT/i', $key)) {
291  continue;
292  }
293  if ($value != '') {
294  $sqlWhere .= " AND ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
295  }
296  }
297  $sql .= $sqlWhere;
298  }
299 
300  // Add the sort order
301  $sql .= $this->array_export_sql_order[$indice];
302 
303  // Add the HAVING part.
304  if (is_array($array_filterValue) && !empty($array_filterValue)) {
305  // Loop on each condition to add
306  foreach ($array_filterValue as $key => $value) {
307  if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') {
308  $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
309  }
310  }
311  }
312 
313  return $sql;
314  }
315 
316  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
325  public function build_filterQuery($TypeField, $NameField, $ValueField)
326  {
327  // phpcs:enable
328  $NameField = sanitizeVal($NameField, 'aZ09');
329  $szFilterQuery = '';
330 
331  //print $TypeField." ".$NameField." ".$ValueField;
332  $InfoFieldList = explode(":", $TypeField);
333  // build the input field on depend of the type of file
334  switch ($InfoFieldList[0]) {
335  case 'Text':
336  if (!(strpos($ValueField, '%') === false)) {
337  $szFilterQuery = " ".$NameField." LIKE '".$this->db->escape($ValueField)."'";
338  } else {
339  $szFilterQuery = " ".$NameField." = '".$this->db->escape($ValueField)."'";
340  }
341  break;
342  case 'Date':
343  if (strpos($ValueField, "+") > 0) {
344  // mode plage
345  $ValueArray = explode("+", $ValueField);
346  $szFilterQuery = "(".$this->conditionDate($NameField, trim($ValueArray[0]), ">=");
347  $szFilterQuery .= " AND ".$this->conditionDate($NameField, trim($ValueArray[1]), "<=").")";
348  } else {
349  if (is_numeric(substr($ValueField, 0, 1))) {
350  $szFilterQuery = $this->conditionDate($NameField, trim($ValueField), "=");
351  } else {
352  $szFilterQuery = $this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1));
353  }
354  }
355  break;
356  case 'Duree':
357  break;
358  case 'Numeric':
359  // if there is a signe +
360  if (strpos($ValueField, "+") > 0) {
361  // mode plage
362  $ValueArray = explode("+", $ValueField);
363  $szFilterQuery = "(".$NameField." >= ".((float) $ValueArray[0]);
364  $szFilterQuery .= " AND ".$NameField." <= ".((float) $ValueArray[1]).")";
365  } else {
366  if (is_numeric(substr($ValueField, 0, 1))) {
367  $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
368  } else {
369  $szFilterQuery = " ".$NameField.substr($ValueField, 0, 1).((float) substr($ValueField, 1));
370  }
371  }
372  break;
373  case 'Boolean':
374  $szFilterQuery = " ".$NameField."=".(is_numeric($ValueField) ? $ValueField : ($ValueField == 'yes' ? 1 : 0));
375  break;
376  case 'FormSelect':
377  if (is_numeric($ValueField) && $ValueField > 0) {
378  $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
379  } else {
380  $szFilterQuery = " 1=1"; // Test always true
381  }
382  break;
383  case 'Status':
384  case 'List':
385  if (is_numeric($ValueField)) {
386  $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
387  } else {
388  if (!(strpos($ValueField, '%') === false)) {
389  $szFilterQuery = " ".$NameField." LIKE '".$this->db->escape($ValueField)."'";
390  } else {
391  $szFilterQuery = " ".$NameField." = '".$this->db->escape($ValueField)."'";
392  }
393  }
394  break;
395  default:
396  dol_syslog("Error we try to forge an sql export request with a condition on a field with type ".$InfoFieldList[0]." (defined into module descriptor) but this type is unknown/not supported. It looks like a bug into module descriptor.", LOG_ERR);
397  }
398 
399  return $szFilterQuery;
400  }
401 
410  public function conditionDate($Field, $Value, $Sens)
411  {
412  // TODO date_format is forbidden, not performant and not portable. Use instead $Value to forge the range date.
413  if (strlen($Value) == 4) {
414  $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$this->db->escape($Value)."'";
415  } elseif (strlen($Value) == 6) {
416  $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$this->db->escape($Value)."'";
417  } else {
418  $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." '".$this->db->escape($Value)."'";
419  }
420  return $Condition;
421  }
422 
423  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
432  public function build_filterField($TypeField, $NameField, $ValueField)
433  {
434  // phpcs:enable
435  global $conf, $langs, $form;
436 
437  $szFilterField = '';
438  $InfoFieldList = explode(":", $TypeField);
439 
440  // build the input field on depend of the type of file
441  switch ($InfoFieldList[0]) {
442  case 'Text':
443  case 'Date':
444  $szFilterField = '<input type="text" name="'.$NameField.'" value="'.$ValueField.'">';
445  break;
446  case 'Duree':
447  case 'Numeric':
448  case 'Number':
449  // Must be a string text to allow to use comparison strings like "<= 99.9"
450  $szFilterField = '<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
451  break;
452  case 'Status':
453  $szFilterField = '<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
454  break;
455  case 'Boolean':
456  $szFilterField = '<select name="'.$NameField.'" class="flat">';
457  $szFilterField .= '<option ';
458  if ($ValueField == '') {
459  $szFilterField .= ' selected ';
460  }
461  $szFilterField .= ' value="">&nbsp;</option>';
462 
463  $szFilterField .= '<option ';
464  if ($ValueField == 'yes' || $ValueField == '1') {
465  $szFilterField .= ' selected ';
466  }
467  $szFilterField .= ' value="1">'.yn(1).'</option>';
468 
469  $szFilterField .= '<option ';
470  if ($ValueField == 'no' || $ValueField == '0') {
471  $szFilterField .= ' selected ';
472  }
473  $szFilterField .= ' value="0">'.yn(0).'</option>';
474  $szFilterField .= "</select>";
475  break;
476  case 'FormSelect':
477  //var_dump($NameField);
478  if ($InfoFieldList[1] == 'select_company') {
479  $szFilterField .= $form->select_company('', $NameField, '', 1, 0, 0, [], 0, 'maxwidth200');
480  } elseif ($InfoFieldList[1] == 'selectcontacts') {
481  //$szFilterField .= $form->selectcontacts(0, '', $NameField, '&nbsp;', '', '', 0, 'maxwidth200');
482  $szFilterField .= $form->select_contact(0, '', $NameField, '&nbsp;', '', '', 0, 'minwidth100imp maxwidth200', true);
483  } elseif ($InfoFieldList[1] == 'select_dolusers') {
484  $szFilterField .= $form->select_dolusers('', $NameField, 1, null, 0, '', '', '', 0, 0, "", 0, "", "maxwidth200");
485  }
486  break;
487  case 'List':
488  // 0 : Type of the field / Type du champ
489  // 1 : Name of the table / Nom de la table
490  // 2 : Name of the field containing the label / Nom du champ contenant le libelle
491  // 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list.
492  // 4 : Name of element for getEntity().
493 
494  if (!empty($InfoFieldList[3])) {
495  $keyList = $InfoFieldList[3];
496  } else {
497  $keyList = 'rowid';
498  }
499  $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3]." as code");
500  if ($InfoFieldList[1] == 'c_stcomm') {
501  $sql = "SELECT id as id, ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3].' as code');
502  }
503  if ($InfoFieldList[1] == 'c_country') {
504  $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label, code as code";
505  }
506  $sql .= " FROM ".MAIN_DB_PREFIX.$InfoFieldList[1];
507  if (!empty($InfoFieldList[4])) {
508  $sql .= ' WHERE entity IN ('.getEntity($InfoFieldList[4]).')';
509  }
510 
511  $resql = $this->db->query($sql);
512  if ($resql) {
513  $szFilterField = '<select class="flat" name="'.$NameField.'">';
514  $szFilterField .= '<option value="0">&nbsp;</option>';
515  $num = $this->db->num_rows($resql);
516 
517  $i = 0;
518  if ($num) {
519  while ($i < $num) {
520  $obj = $this->db->fetch_object($resql);
521  if ($obj->label == '-') {
522  // Discard entry '-'
523  $i++;
524  continue;
525  }
526  //var_dump($InfoFieldList[1]);
527  $labeltoshow = dol_trunc($obj->label, 18);
528  if ($InfoFieldList[1] == 'c_stcomm') {
529  $langs->load("companies");
530  $labeltoshow = (($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id) ? $langs->trans("StatusProspect".$obj->id) : $obj->label);
531  }
532  if ($InfoFieldList[1] == 'c_country') {
533  //var_dump($sql);
534  $langs->load("dict");
535  $labeltoshow = (($langs->trans("Country".$obj->code) != "Country".$obj->code) ? $langs->trans("Country".$obj->code) : $obj->label);
536  }
537  if (!empty($ValueField) && $ValueField == $obj->rowid) {
538  $szFilterField .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
539  } else {
540  $szFilterField .= '<option value="'.$obj->rowid.'" >'.$labeltoshow.'</option>';
541  }
542  $i++;
543  }
544  }
545  $szFilterField .= "</select>";
546 
547  $this->db->free($resql);
548  } else {
549  dol_print_error($this->db);
550  }
551  break;
552  }
553 
554  return $szFilterField;
555  }
556 
563  public function genDocFilter($TypeField)
564  {
565  global $langs;
566 
567  $szMsg = '';
568  $InfoFieldList = explode(":", $TypeField);
569  // build the input field on depend of the type of file
570  switch ($InfoFieldList[0]) {
571  case 'Text':
572  $szMsg = $langs->trans('ExportStringFilter');
573  break;
574  case 'Date':
575  $szMsg = $langs->trans('ExportDateFilter');
576  break;
577  case 'Duree':
578  break;
579  case 'Numeric':
580  $szMsg = $langs->trans('ExportNumericFilter');
581  break;
582  case 'Boolean':
583  break;
584  case 'List':
585  break;
586  }
587  return $szMsg;
588  }
589 
590  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
605  public function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '', $separator = '')
606  {
607  // phpcs:enable
608  global $conf, $langs, $mysoc;
609 
610  $indice = 0;
611  asort($array_selected);
612 
613  dol_syslog(__METHOD__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected));
614 
615  // Check parameters or context properties
616  if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) {
617  $this->error = "ErrorBadParameter";
618  dol_syslog($this->error, LOG_ERR);
619  return -1;
620  }
621 
622  // Creation of class to export using model ExportXXX
623  $dir = DOL_DOCUMENT_ROOT."/core/modules/export/";
624  $file = "export_".$model.".modules.php";
625  $classname = "Export".$model;
626  require_once $dir.$file;
627  $objmodel = new $classname($this->db);
628 
629  if (in_array($model, array('csvutf8', 'csviso')) && !empty($separator)) {
630  $objmodel->separator = $separator;
631  }
632 
633  if (!empty($sqlquery)) {
634  $sql = $sqlquery;
635  } else {
636  // Define value for indice from $datatoexport
637  $foundindice = 0;
638  foreach ($this->array_export_code as $key => $dataset) {
639  if ($datatoexport == $dataset) {
640  $indice = $key;
641  $foundindice++;
642  //print "Found indice = ".$indice." for dataset=".$datatoexport."\n";
643  break;
644  }
645  }
646  if (empty($foundindice)) {
647  $this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
648  return -1;
649  }
650  $sql = $this->build_sql($indice, $array_selected, $array_filterValue);
651  }
652 
653  // Run the SQL
654  $this->sqlusedforexport = $sql;
655  dol_syslog(__METHOD__, LOG_DEBUG);
656  $resql = $this->db->query($sql);
657  if ($resql) {
658  //$this->array_export_label[$indice]
659  if (getDolGlobalString('EXPORT_PREFIX_SPEC')) {
660  $filename = getDolGlobalString('EXPORT_PREFIX_SPEC') . "_".$datatoexport;
661  } else {
662  $filename = "export_".$datatoexport;
663  }
664  if (getDolGlobalString('EXPORT_NAME_WITH_DT')) {
665  $filename .= dol_print_date(dol_now(), '%Y%m%d%_%H%M');
666  }
667  $filename .= '.'.$objmodel->getDriverExtension();
668  $dirname = $conf->export->dir_temp.'/'.$user->id;
669 
670  $outputlangs = clone $langs; // We clone to have an object we can modify (for example to change output charset by csv handler) without changing original value
671 
672  // Open file
673  dol_mkdir($dirname);
674  $result = $objmodel->open_file($dirname."/".$filename, $outputlangs);
675 
676  if ($result >= 0) {
677  // Generate header
678  $objmodel->write_header($outputlangs);
679 
680  // Generate title line
681  $objmodel->write_title($this->array_export_fields[$indice], $array_selected, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
682 
683  while ($obj = $this->db->fetch_object($resql)) {
684  // Process special operations
685  if (!empty($this->array_export_special[$indice])) {
686  foreach ($this->array_export_special[$indice] as $key => $value) {
687  if (!array_key_exists($key, $array_selected)) {
688  continue; // Field not selected
689  }
690  // Operation NULLIFNEG
691  if ($this->array_export_special[$indice][$key] == 'NULLIFNEG') {
692  //$alias=$this->array_export_alias[$indice][$key];
693  $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
694  if ($obj->$alias < 0) {
695  $obj->$alias = '';
696  }
697  } elseif ($this->array_export_special[$indice][$key] == 'ZEROIFNEG') {
698  // Operation ZEROIFNEG
699  //$alias=$this->array_export_alias[$indice][$key];
700  $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
701  if ($obj->$alias < 0) {
702  $obj->$alias = '0';
703  }
704  } elseif ($this->array_export_special[$indice][$key] == 'getNumOpenDays') {
705  // Operation GETNUMOPENDAYS (for Holiday module)
706  include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
707  //$alias=$this->array_export_alias[$indice][$key];
708  $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
709  $obj->$alias = num_open_day(dol_stringtotime($obj->d_date_debut, 1), dol_stringtotime($obj->d_date_fin, 1), 0, 1, $obj->d_halfday, $mysoc->country_code);
710  } elseif ($this->array_export_special[$indice][$key] == 'getRemainToPay') {
711  // Operation INVOICEREMAINTOPAY
712  //$alias=$this->array_export_alias[$indice][$key];
713  $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
714  $remaintopay = '';
715  if ($obj->f_rowid > 0) {
716  global $tmpobjforcomputecall;
717  if (!is_object($tmpobjforcomputecall)) {
718  include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
719  $tmpobjforcomputecall = new Facture($this->db);
720  }
721  $tmpobjforcomputecall->id = $obj->f_rowid;
722  $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
723  $tmpobjforcomputecall->close_code = $obj->f_close_code;
724  $remaintopay = $tmpobjforcomputecall->getRemainToPay();
725  }
726  $obj->$alias = $remaintopay;
727  } elseif (is_array($this->array_export_special[$indice][$key]) &&
728  !empty($this->array_export_special[$indice][$key]['rule']) &&
729  $this->array_export_special[$indice][$key]['rule'] == 'compute'
730  ) {
731  // Custom compute
732  $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
733  $value = '';
734  if (!empty($this->array_export_special[$indice][$key]['class']) &&
735  !empty($this->array_export_special[$indice][$key]['classfile']) &&
736  !empty($this->array_export_special[$indice][$key]['method'])
737  ) {
738  if (!dol_include_once($this->array_export_special[$indice][$key]['classfile'])) {
739  $this->error = "Computed field bad configuration: {$this->array_export_special[$indice][$key]['classfile']} not found";
740  return -1;
741  }
742 
743  if (!class_exists($this->array_export_special[$indice][$key]['class'])) {
744  $this->error = "Computed field bad configuration: {$this->array_export_special[$indice][$key]['class']} class doesn't exist";
745  return -1;
746  }
747 
748  $className = $this->array_export_special[$indice][$key]['class'];
749  $tmpObject = new $className($this->db);
750  if (!method_exists($tmpObject, $this->array_export_special[$indice][$key]['method'])) {
751  $this->error = "Computed field bad configuration: {$this->array_export_special[$indice][$key]['method']} method doesn't exist";
752  return -1;
753  }
754 
755  $methodName = $this->array_export_special[$indice][$key]['method'];
756  $params = [];
757  if (!empty($this->array_export_special[$indice][$key]['method_params'])) {
758  foreach ($this->array_export_special[$indice][$key]['method_params'] as $paramName) {
759  $params[] = $obj->$paramName ?? null;
760  }
761  }
762  $value = $tmpObject->$methodName(...$params);
763  }
764  $obj->$alias = $value;
765  } else {
766  // TODO FIXME
767  // Export of compute field does not work. $obj contains $obj->alias_field and formula may contains $obj->field
768  // Also the formula may contains objects of class that are not loaded.
769  $computestring = $this->array_export_special[$indice][$key];
770  //$tmp = (string) dol_eval($computestring, 1, 0, '2');
771  //$obj->$alias = $tmp;
772 
773  $this->error = "ERROPNOTSUPPORTED. Operation ".$computestring." not supported. Export of 'computed' extrafields is not yet supported, please remove field.";
774  return -1;
775  }
776  }
777  }
778  // end of special operation processing
779  $objmodel->write_record($array_selected, $obj, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
780  }
781 
782  // Generate Footer
783  $objmodel->write_footer($outputlangs);
784 
785  // Close file
786  $objmodel->close_file();
787 
788  return 1;
789  } else {
790  $this->error = $objmodel->error;
791  dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
792  return -1;
793  }
794  } else {
795  $this->error = $this->db->error()." - sql=".$sql;
796  return -1;
797  }
798  }
799 
806  public function create($user)
807  {
808  dol_syslog("Export.class.php::create");
809 
810  $this->db->begin();
811 
812  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'export_model (';
813  $sql .= 'label,';
814  $sql .= 'type,';
815  $sql .= 'field,';
816  $sql .= 'fk_user,';
817  $sql .= 'filter';
818  $sql .= ') VALUES (';
819  $sql .= "'".$this->db->escape($this->model_name)."',";
820  $sql .= " '".$this->db->escape($this->datatoexport)."',";
821  $sql .= " '".$this->db->escape($this->hexa)."',";
822  $sql .= ' '.(isset($this->fk_user) ? (int) $this->fk_user : 'null').",";
823  $sql .= " '".$this->db->escape($this->hexafiltervalue)."'";
824  $sql .= ")";
825 
826  $resql = $this->db->query($sql);
827  if ($resql) {
828  $this->db->commit();
829  return 1;
830  } else {
831  $this->error = $this->db->lasterror();
832  $this->errno = $this->db->lasterrno();
833  $this->db->rollback();
834  return -1;
835  }
836  }
837 
844  public function fetch($id)
845  {
846  $sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter';
847  $sql .= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
848  $sql .= ' WHERE em.rowid = '.((int) $id);
849 
850  dol_syslog("Export::fetch", LOG_DEBUG);
851  $result = $this->db->query($sql);
852  if ($result) {
853  $obj = $this->db->fetch_object($result);
854  if ($obj) {
855  $this->id = $obj->rowid;
856  $this->model_name = $obj->label;
857  $this->datatoexport = $obj->type;
858 
859  $this->hexa = $obj->field;
860  $this->hexafiltervalue = $obj->filter;
861 
862  return 1;
863  } else {
864  $this->error = "ModelNotFound";
865  return -2;
866  }
867  } else {
868  dol_print_error($this->db);
869  return -3;
870  }
871  }
872 
873 
881  public function delete($user, $notrigger = 0)
882  {
883  global $conf, $langs;
884  $error = 0;
885 
886  $sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model";
887  $sql .= " WHERE rowid=".((int) $this->id);
888 
889  $this->db->begin();
890 
891  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
892  $resql = $this->db->query($sql);
893  if (!$resql) {
894  $error++;
895  $this->errors[] = "Error ".$this->db->lasterror();
896  }
897 
898  // Commit or rollback
899  if ($error) {
900  foreach ($this->errors as $errmsg) {
901  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
902  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
903  }
904  $this->db->rollback();
905  return -1 * $error;
906  } else {
907  $this->db->commit();
908  return 1;
909  }
910  }
911 
912  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
919  public function list_export_model()
920  {
921  // phpcs:enable
922  global $conf, $langs;
923 
924  $sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter";
925  $sql .= " FROM ".MAIN_DB_PREFIX."export_model as em";
926  $sql .= " ORDER BY rowid";
927 
928  $result = $this->db->query($sql);
929  if ($result) {
930  $num = $this->db->num_rows($result);
931  $i = 0;
932  while ($i < $num) {
933  $obj = $this->db->fetch_object($result);
934  $keyModel = array_search($obj->type, $this->array_export_code);
935  print "<tr>";
936  print '<td><a href=export.php?step=2&action=select_model&exportmodelid='.$obj->rowid.'&datatoexport='.$obj->type.'>'.$obj->label.'</a></td>';
937  print '<td>';
938  print img_object($this->array_export_module[$keyModel]->getName(), $this->array_export_icon[$keyModel]).' ';
939  print $this->array_export_module[$keyModel]->getName().' - ';
940  // recover export name / recuperation du nom de l'export
941 
942  $string = $langs->trans($this->array_export_label[$keyModel]);
943  print($string != $this->array_export_label[$keyModel] ? $string : $this->array_export_label[$keyModel]);
944  print '</td>';
945  //print '<td>'.$obj->type.$keyModel.'</td>';
946  print '<td>'.str_replace(',', ' , ', $obj->field).'</td>';
947  if (!empty($obj->filter)) {
948  $filter = json_decode($obj->filter, true);
949  print '<td>'.str_replace(',', ' , ', $filter['field']).'</td>';
950  print '<td>'.str_replace(',', ' , ', $filter['value']).'</td>';
951  }
952  // remove export / suppression de l'export
953  print '<td class="right">';
954  print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteprof&token='.newToken().'&id='.$obj->rowid.'">';
955  print img_delete();
956  print '</a>';
957  print "</tr>";
958 
959  $i++;
960  }
961  } else {
962  dol_print_error($this->db);
963  }
964  }
965 }
Class to manage exports.
fetch($id)
Load an export profil from database.
build_sql($indice, $array_selected, $array_filterValue)
Build the sql export request.
build_filterField($TypeField, $NameField, $ValueField)
Build an input field used to filter the query.
build_filterQuery($TypeField, $NameField, $ValueField)
Build the conditional string from filter the query.
conditionDate($Field, $Value, $Sens)
conditionDate
list_export_model()
Output list all export models –TODO Move this into a class htmlxxx.class.php–.
create($user)
Save an export model in database.
__construct($db)
Constructor.
load_arrays($user, $filter='')
Load an exportable dataset.
build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery='', $separator='')
Build export file.
genDocFilter($TypeField)
Build an input field used to filter the query.
Class to manage invoices.
if(isModEnabled('invoice') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD') && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')) if(isModEnabled('invoice') &&isModEnabled('order') && $user->hasRight("commande", "lire") &&!getDolGlobalString('WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER')) $sql
Social contributions to pay.
Definition: index.php:745
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $country_code='')
Function to return number of working days (and text of units) between two dates (working days)
Definition: date.lib.php:1039
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition: date.lib.php:427
dolGetModulesDirs($subdir='')
Return list of directories that contain modules.
verifCond($strToEvaluate, $onlysimplestring='1')
Verify if condition in string is ok or not.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_now($mode='auto')
Return date for now.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
div float
Buy price without taxes.
Definition: style.css.php:960