dolibarr  16.0.5
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 
38  public $error;
39 
40  public $array_export_code = array(); // Tableau de "idmodule_numexportprofile"
41  public $array_export_code_for_sort = array(); // Tableau de "idmodule_numexportprofile"
42  public $array_export_module = array(); // Tableau de "nom de modules"
43  public $array_export_label = array(); // Tableau de "libelle de lots"
44  public $array_export_sql_start = array(); // Tableau des "requetes sql"
45  public $array_export_sql_end = array(); // Tableau des "requetes sql"
46  public $array_export_sql_order = array(); // Tableau des "requetes sql"
47 
48  public $array_export_fields = array(); // Tableau des listes de champ+libelle a exporter
49  public $array_export_TypeFields = array(); // Tableau des listes de champ+Type de filtre
50  public $array_export_FilterValue = array(); // Tableau des listes de champ+Valeur a filtrer
51  public $array_export_entities = array(); // Tableau des listes de champ+alias a exporter
52  public $array_export_dependencies = array(); // array of list of entities that must take care of the DISTINCT if a field is added into export
53  public $array_export_special = array(); // array of special operations to do on field
54  public $array_export_examplevalues = array(); // array with examples for fields
55  public $array_export_help = array(); // array with tooltip help for fields
56 
57  // To store export templates
58  public $hexa; // List of fields in the export profile
59  public $hexafiltervalue; // List of search criteria in the export profile
60  public $datatoexport;
61  public $model_name; // Name of export profile
62  public $fk_user;
63 
64  public $sqlusedforexport;
65 
66 
72  public function __construct($db)
73  {
74  $this->db = $db;
75  }
76 
77 
78  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
86  public function load_arrays($user, $filter = '')
87  {
88  // phpcs:enable
89  global $langs, $conf, $mysoc;
90 
91  dol_syslog(get_class($this)."::load_arrays user=".$user->id." filter=".$filter);
92 
93  $i = 0;
94 
95  // Define list of modules directories into modulesdir
96  require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
97 
98  $modulesdir = dolGetModulesDirs();
99 
100  foreach ($modulesdir as $dir) {
101  // Search available exports
102  $handle = @opendir(dol_osencode($dir));
103  if (is_resource($handle)) {
104  // Search module files
105  while (($file = readdir($handle)) !== false) {
106  $reg = array();
107  if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) {
108  $modulename = $reg[1];
109 
110  // Defined if module is enabled
111  $enabled = true;
112  $part = strtolower(preg_replace('/^mod/i', '', $modulename));
113  if ($part == 'propale') {
114  $part = 'propal';
115  }
116  if (empty($conf->$part->enabled)) {
117  $enabled = false;
118  }
119 
120  if ($enabled) {
121  // Loading Class
122  $file = $dir.$modulename.".class.php";
123  $classname = $modulename;
124  require_once $file;
125  $module = new $classname($this->db);
126 
127  if (isset($module->export_code) && is_array($module->export_code)) {
128  foreach ($module->export_code as $r => $value) {
129  //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).'<br>';
130  if ($filter && ($filter != $module->export_code[$r])) {
131  continue;
132  }
133 
134  // Test if condition to show are ok
135  if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) {
136  continue;
137  }
138 
139  // Test if permissions are ok
140  $bool = true;
141  if (isset($module->export_permission)) {
142  foreach ($module->export_permission[$r] as $val) {
143  $perm = $val;
144  //print_r("$perm[0]-$perm[1]-$perm[2]<br>");
145  if (!empty($perm[2])) {
146  $bool = isset($user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]}) ? $user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]} : false;
147  } else {
148  $bool = isset($user->rights->{$perm[0]}->{$perm[1]}) ? $user->rights->{$perm[0]}->{$perm[1]} : false;
149  }
150  if ($perm[0] == 'user' && $user->admin) {
151  $bool = true;
152  }
153  if (!$bool) {
154  break;
155  }
156  }
157  }
158  //print $bool." $perm[0]"."<br>";
159 
160  // Permissions ok
161  // if ($bool)
162  // {
163  // Charge fichier lang en rapport
164  $langtoload = $module->getLangFilesArray();
165  if (is_array($langtoload)) {
166  foreach ($langtoload as $key) {
167  $langs->load($key);
168  }
169  }
170 
171 
172  // Module
173  $this->array_export_module[$i] = $module;
174  // Permission
175  $this->array_export_perms[$i] = $bool;
176  // Icon
177  $this->array_export_icon[$i] = (isset($module->export_icon[$r]) ? $module->export_icon[$r] : $module->picto);
178  // Code du dataset export
179  $this->array_export_code[$i] = $module->export_code[$r];
180  // Define a key for sort
181  $this->array_export_code_for_sort[$i] = $module->module_position.'_'.$module->export_code[$r]; // Add a key into the module
182  // Libelle du dataset export
183  $this->array_export_label[$i] = $module->getExportDatasetLabel($r);
184  // Tableau des champ a exporter (cle=champ, valeur=libelle)
185  $this->array_export_fields[$i] = $module->export_fields_array[$r];
186  // Tableau des champs a filtrer (cle=champ, valeur1=type de donnees) on verifie que le module a des filtres
187  $this->array_export_TypeFields[$i] = (isset($module->export_TypeFields_array[$r]) ? $module->export_TypeFields_array[$r] : '');
188  // Tableau des entites a exporter (cle=champ, valeur=entite)
189  $this->array_export_entities[$i] = $module->export_entities_array[$r];
190  // Tableau des entites qui requiert abandon du DISTINCT (cle=entite, valeur=champ id child records)
191  $this->array_export_dependencies[$i] = (!empty($module->export_dependencies_array[$r]) ? $module->export_dependencies_array[$r] : '');
192  // Tableau des operations speciales sur champ
193  $this->array_export_special[$i] = (!empty($module->export_special_array[$r]) ? $module->export_special_array[$r] : '');
194  // Array of examples
195  $this->array_export_examplevalues[$i] = (!empty($module->export_examplevalues_array[$r]) ? $module->export_examplevalues_array[$r] : null);
196  // Array of help tooltips
197  $this->array_export_help[$i] = (!empty($module->export_help_array[$r]) ? $module->export_help_array[$r] : '');
198 
199  // Requete sql du dataset
200  $this->array_export_sql_start[$i] = $module->export_sql_start[$r];
201  $this->array_export_sql_end[$i] = $module->export_sql_end[$r];
202  $this->array_export_sql_order[$i] = (!empty($module->export_sql_order[$r]) ? $module->export_sql_order[$r] : null);
203  //$this->array_export_sql[$i]=$module->export_sql[$r];
204 
205  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]) : ''));
206  $i++;
207  // }
208  }
209  }
210  }
211  }
212  }
213  closedir($handle);
214  }
215  }
216 
217  return 1;
218  }
219 
220 
221  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
231  public function build_sql($indice, $array_selected, $array_filterValue)
232  {
233  // phpcs:enable
234  // Build the sql request
235  $sql = $this->array_export_sql_start[$indice];
236  $i = 0;
237 
238  //print_r($array_selected);
239  foreach ($this->array_export_fields[$indice] as $key => $value) {
240  if (!array_key_exists($key, $array_selected)) {
241  continue; // Field not selected
242  }
243  if (preg_match('/^none\./', $key)) {
244  continue; // A field that must not appears into SQL
245  }
246  if ($i > 0) {
247  $sql .= ', ';
248  } else {
249  $i++;
250  }
251 
252  if (strpos($key, ' as ') === false) {
253  $newfield = $key.' as '.str_replace(array('.', '-', '(', ')'), '_', $key);
254  } else {
255  $newfield = $key;
256  }
257 
258  $sql .= $newfield;
259  }
260  $sql .= $this->array_export_sql_end[$indice];
261 
262  // Add the WHERE part. Filtering into sql if a filtering array is provided
263  if (is_array($array_filterValue) && !empty($array_filterValue)) {
264  $sqlWhere = '';
265  // Loop on each condition to add
266  foreach ($array_filterValue as $key => $value) {
267  if (preg_match('/GROUP_CONCAT/i', $key)) {
268  continue;
269  }
270  if ($value != '') {
271  $sqlWhere .= " AND ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
272  }
273  }
274  $sql .= $sqlWhere;
275  }
276 
277  // Add the order
278  $sql .= $this->array_export_sql_order[$indice];
279 
280  // Add the HAVING part.
281  if (is_array($array_filterValue) && !empty($array_filterValue)) {
282  // Loop on each condition to add
283  foreach ($array_filterValue as $key => $value) {
284  if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') {
285  $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
286  }
287  }
288  }
289 
290  return $sql;
291  }
292 
293  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
302  public function build_filterQuery($TypeField, $NameField, $ValueField)
303  {
304  // phpcs:enable
305  $NameField = sanitizeVal($NameField, 'aZ09');
306  $szFilterQuery = '';
307 
308  //print $TypeField." ".$NameField." ".$ValueField;
309  $InfoFieldList = explode(":", $TypeField);
310  // build the input field on depend of the type of file
311  switch ($InfoFieldList[0]) {
312  case 'Text':
313  if (!(strpos($ValueField, '%') === false)) {
314  $szFilterQuery = " ".$NameField." LIKE '".$this->db->escape($ValueField)."'";
315  } else {
316  $szFilterQuery = " ".$NameField." = '".$this->db->escape($ValueField)."'";
317  }
318  break;
319  case 'Date':
320  if (strpos($ValueField, "+") > 0) {
321  // mode plage
322  $ValueArray = explode("+", $ValueField);
323  $szFilterQuery = "(".$this->conditionDate($NameField, trim($ValueArray[0]), ">=");
324  $szFilterQuery .= " AND ".$this->conditionDate($NameField, trim($ValueArray[1]), "<=").")";
325  } else {
326  if (is_numeric(substr($ValueField, 0, 1))) {
327  $szFilterQuery = $this->conditionDate($NameField, trim($ValueField), "=");
328  } else {
329  $szFilterQuery = $this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1));
330  }
331  }
332  break;
333  case 'Duree':
334  break;
335  case 'Numeric':
336  // if there is a signe +
337  if (strpos($ValueField, "+") > 0) {
338  // mode plage
339  $ValueArray = explode("+", $ValueField);
340  $szFilterQuery = "(".$NameField." >= ".((float) $ValueArray[0]);
341  $szFilterQuery .= " AND ".$NameField." <= ".((float) $ValueArray[1]).")";
342  } else {
343  if (is_numeric(substr($ValueField, 0, 1))) {
344  $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
345  } else {
346  $szFilterQuery = " ".$NameField.substr($ValueField, 0, 1).((float) substr($ValueField, 1));
347  }
348  }
349  break;
350  case 'Boolean':
351  $szFilterQuery = " ".$NameField."=".(is_numeric($ValueField) ? $ValueField : ($ValueField == 'yes' ? 1 : 0));
352  break;
353  case 'FormSelect':
354  if (is_numeric($ValueField) && $ValueField > 0) {
355  $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
356  } else {
357  $szFilterQuery = " 1=1"; // Test always true
358  }
359  break;
360  case 'Status':
361  case 'List':
362  if (is_numeric($ValueField)) {
363  $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
364  } else {
365  if (!(strpos($ValueField, '%') === false)) {
366  $szFilterQuery = " ".$NameField." LIKE '".$this->db->escape($ValueField)."'";
367  } else {
368  $szFilterQuery = " ".$NameField." = '".$this->db->escape($ValueField)."'";
369  }
370  }
371  break;
372  default:
373  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);
374  }
375 
376  return $szFilterQuery;
377  }
378 
387  public function conditionDate($Field, $Value, $Sens)
388  {
389  // TODO date_format is forbidden, not performant and not portable. Use instead $Value to forge the range date.
390  if (strlen($Value) == 4) {
391  $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$this->db->escape($Value)."'";
392  } elseif (strlen($Value) == 6) {
393  $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$this->db->escape($Value)."'";
394  } else {
395  $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." '".$this->db->escape($Value)."'";
396  }
397  return $Condition;
398  }
399 
400  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
409  public function build_filterField($TypeField, $NameField, $ValueField)
410  {
411  // phpcs:enable
412  global $conf, $langs, $form;
413 
414  $szFilterField = '';
415  $InfoFieldList = explode(":", $TypeField);
416 
417  // build the input field on depend of the type of file
418  switch ($InfoFieldList[0]) {
419  case 'Text':
420  case 'Date':
421  $szFilterField = '<input type="text" name="'.$NameField.'" value="'.$ValueField.'">';
422  break;
423  case 'Duree':
424  case 'Numeric':
425  case 'Number':
426  // Must be a string text to allow to use comparison strings like "<= 99.9"
427  $szFilterField = '<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
428  break;
429  case 'Status':
430  $szFilterField = '<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
431  break;
432  case 'Boolean':
433  $szFilterField = '<select name="'.$NameField.'" class="flat">';
434  $szFilterField .= '<option ';
435  if ($ValueField == '') {
436  $szFilterField .= ' selected ';
437  }
438  $szFilterField .= ' value="">&nbsp;</option>';
439 
440  $szFilterField .= '<option ';
441  if ($ValueField == 'yes' || $ValueField == '1') {
442  $szFilterField .= ' selected ';
443  }
444  $szFilterField .= ' value="1">'.yn(1).'</option>';
445 
446  $szFilterField .= '<option ';
447  if ($ValueField == 'no' || $ValueField == '0') {
448  $szFilterField .= ' selected ';
449  }
450  $szFilterField .= ' value="0">'.yn(0).'</option>';
451  $szFilterField .= "</select>";
452  break;
453  case 'FormSelect':
454  //var_dump($NameField);
455  if ($InfoFieldList[1] == 'select_company') {
456  $szFilterField .= $form->select_company('', $NameField, '', 1);
457  } elseif ($InfoFieldList[1] == 'selectcontacts') {
458  $szFilterField .= $form->selectcontacts(0, '', $NameField, '&nbsp;');
459  } elseif ($InfoFieldList[1] == 'select_dolusers') {
460  $szFilterField .= $form->select_dolusers('', $NameField, 1);
461  }
462  break;
463  case 'List':
464  // 0 : Type du champ
465  // 1 : Nom de la table
466  // 2 : Nom du champ contenant le libelle
467  // 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list.
468  // 4 : Name of element for getEntity().
469 
470  if (!empty($InfoFieldList[3])) {
471  $keyList = $InfoFieldList[3];
472  } else {
473  $keyList = 'rowid';
474  }
475  $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3]." as code");
476  if ($InfoFieldList[1] == 'c_stcomm') {
477  $sql = "SELECT id as id, ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3].' as code');
478  }
479  if ($InfoFieldList[1] == 'c_country') {
480  $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label, code as code";
481  }
482  $sql .= " FROM ".MAIN_DB_PREFIX.$InfoFieldList[1];
483  if (!empty($InfoFieldList[4])) {
484  $sql .= ' WHERE entity IN ('.getEntity($InfoFieldList[4]).')';
485  }
486 
487  $resql = $this->db->query($sql);
488  if ($resql) {
489  $szFilterField = '<select class="flat" name="'.$NameField.'">';
490  $szFilterField .= '<option value="0">&nbsp;</option>';
491  $num = $this->db->num_rows($resql);
492 
493  $i = 0;
494  if ($num) {
495  while ($i < $num) {
496  $obj = $this->db->fetch_object($resql);
497  if ($obj->label == '-') {
498  // Discard entry '-'
499  $i++;
500  continue;
501  }
502  //var_dump($InfoFieldList[1]);
503  $labeltoshow = dol_trunc($obj->label, 18);
504  if ($InfoFieldList[1] == 'c_stcomm') {
505  $langs->load("companies");
506  $labeltoshow = (($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id) ? $langs->trans("StatusProspect".$obj->id) : $obj->label);
507  }
508  if ($InfoFieldList[1] == 'c_country') {
509  //var_dump($sql);
510  $langs->load("dict");
511  $labeltoshow = (($langs->trans("Country".$obj->code) != "Country".$obj->code) ? $langs->trans("Country".$obj->code) : $obj->label);
512  }
513  if (!empty($ValueField) && $ValueField == $obj->rowid) {
514  $szFilterField .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
515  } else {
516  $szFilterField .= '<option value="'.$obj->rowid.'" >'.$labeltoshow.'</option>';
517  }
518  $i++;
519  }
520  }
521  $szFilterField .= "</select>";
522 
523  $this->db->free($resql);
524  } else {
525  dol_print_error($this->db);
526  }
527  break;
528  }
529 
530  return $szFilterField;
531  }
532 
539  public function genDocFilter($TypeField)
540  {
541  global $langs;
542 
543  $szMsg = '';
544  $InfoFieldList = explode(":", $TypeField);
545  // build the input field on depend of the type of file
546  switch ($InfoFieldList[0]) {
547  case 'Text':
548  $szMsg = $langs->trans('ExportStringFilter');
549  break;
550  case 'Date':
551  $szMsg = $langs->trans('ExportDateFilter');
552  break;
553  case 'Duree':
554  break;
555  case 'Numeric':
556  $szMsg = $langs->trans('ExportNumericFilter');
557  break;
558  case 'Boolean':
559  break;
560  case 'List':
561  break;
562  }
563  return $szMsg;
564  }
565 
566  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
580  public function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '')
581  {
582  // phpcs:enable
583  global $conf, $langs, $mysoc;
584 
585  $indice = 0;
586  asort($array_selected);
587 
588  dol_syslog(__METHOD__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected));
589 
590  // Check parameters or context properties
591  if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) {
592  $this->error = "ErrorBadParameter";
593  dol_syslog($this->error, LOG_ERR);
594  return -1;
595  }
596 
597  // Creation of class to export using model ExportXXX
598  $dir = DOL_DOCUMENT_ROOT."/core/modules/export/";
599  $file = "export_".$model.".modules.php";
600  $classname = "Export".$model;
601  require_once $dir.$file;
602  $objmodel = new $classname($this->db);
603 
604  if (!empty($sqlquery)) {
605  $sql = $sqlquery;
606  } else {
607  // Define value for indice from $datatoexport
608  $foundindice = 0;
609  foreach ($this->array_export_code as $key => $dataset) {
610  if ($datatoexport == $dataset) {
611  $indice = $key;
612  $foundindice++;
613  //print "Found indice = ".$indice." for dataset=".$datatoexport."\n";
614  break;
615  }
616  }
617  if (empty($foundindice)) {
618  $this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
619  return -1;
620  }
621  $sql = $this->build_sql($indice, $array_selected, $array_filterValue);
622  }
623 
624  // Run the sql
625  $this->sqlusedforexport = $sql;
626  dol_syslog(__METHOD__, LOG_DEBUG);
627  $resql = $this->db->query($sql);
628  if ($resql) {
629  //$this->array_export_label[$indice]
630  if (!empty($conf->global->EXPORT_PREFIX_SPEC)) {
631  $filename = $conf->global->EXPORT_PREFIX_SPEC."_".$datatoexport;
632  } else {
633  $filename = "export_".$datatoexport;
634  }
635  if (!empty($conf->global->EXPORT_NAME_WITH_DT)) {
636  $filename .= dol_print_date(dol_now(), '%Y%m%d%_%H%M');
637  }
638  $filename .= '.'.$objmodel->getDriverExtension();
639  $dirname = $conf->export->dir_temp.'/'.$user->id;
640 
641  $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
642 
643  // Open file
644  dol_mkdir($dirname);
645  $result = $objmodel->open_file($dirname."/".$filename, $outputlangs);
646 
647  if ($result >= 0) {
648  // Genere en-tete
649  $objmodel->write_header($outputlangs);
650 
651  // Genere ligne de titre
652  $objmodel->write_title($this->array_export_fields[$indice], $array_selected, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
653 
654  while ($obj = $this->db->fetch_object($resql)) {
655  // Process special operations
656  if (!empty($this->array_export_special[$indice])) {
657  foreach ($this->array_export_special[$indice] as $key => $value) {
658  if (!array_key_exists($key, $array_selected)) {
659  continue; // Field not selected
660  }
661  // Operation NULLIFNEG
662  if ($this->array_export_special[$indice][$key] == 'NULLIFNEG') {
663  //$alias=$this->array_export_alias[$indice][$key];
664  $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
665  if ($obj->$alias < 0) {
666  $obj->$alias = '';
667  }
668  } elseif ($this->array_export_special[$indice][$key] == 'ZEROIFNEG') {
669  // Operation ZEROIFNEG
670  //$alias=$this->array_export_alias[$indice][$key];
671  $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
672  if ($obj->$alias < 0) {
673  $obj->$alias = '0';
674  }
675  } elseif ($this->array_export_special[$indice][$key] == 'getNumOpenDays') {
676  // Operation GETNUMOPENDAYS (for Holiday module)
677  include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
678  //$alias=$this->array_export_alias[$indice][$key];
679  $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
680  $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);
681  } elseif ($this->array_export_special[$indice][$key] == 'getRemainToPay') {
682  // Operation INVOICEREMAINTOPAY
683  //$alias=$this->array_export_alias[$indice][$key];
684  $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
685  $remaintopay = '';
686  if ($obj->f_rowid > 0) {
687  global $tmpobjforcomputecall;
688  if (!is_object($tmpobjforcomputecall)) {
689  include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
690  $tmpobjforcomputecall = new Facture($this->db);
691  }
692  $tmpobjforcomputecall->id = $obj->f_rowid;
693  $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
694  $tmpobjforcomputecall->close_code = $obj->f_close_code;
695  $remaintopay = $tmpobjforcomputecall->getRemainToPay();
696  }
697  $obj->$alias = $remaintopay;
698  } else {
699  // TODO FIXME
700  // Export of compute field does not work. $obj contains $obj->alias_field and formula may contains $obj->field
701  // Also the formula may contains objects of class that are not loaded.
702  $computestring = $this->array_export_special[$indice][$key];
703  //$tmp = dol_eval($computestring, 1, 0);
704  //$obj->$alias = $tmp;
705 
706  $this->error = "ERROPNOTSUPPORTED. Operation ".$computestring." not supported. Export of 'computed' extrafields is not yet supported, please remove field.";
707  return -1;
708  }
709  }
710  }
711  // end of special operation processing
712  $objmodel->write_record($array_selected, $obj, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
713  }
714 
715  // Genere en-tete
716  $objmodel->write_footer($outputlangs);
717 
718  // Close file
719  $objmodel->close_file();
720 
721  return 1;
722  } else {
723  $this->error = $objmodel->error;
724  dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
725  return -1;
726  }
727  } else {
728  $this->error = $this->db->error()." - sql=".$sql;
729  return -1;
730  }
731  }
732 
739  public function create($user)
740  {
741  global $conf;
742 
743  dol_syslog("Export.class.php::create");
744 
745  $this->db->begin();
746 
747  $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'export_model (';
748  $sql .= 'label,';
749  $sql .= 'type,';
750  $sql .= 'field,';
751  $sql .= 'fk_user,';
752  $sql .= 'filter';
753  $sql .= ') VALUES (';
754  $sql .= "'".$this->db->escape($this->model_name)."',";
755  $sql .= " '".$this->db->escape($this->datatoexport)."',";
756  $sql .= " '".$this->db->escape($this->hexa)."',";
757  $sql .= ' '.(isset($this->fk_user) ? (int) $this->fk_user : 'null').",";
758  $sql .= " '".$this->db->escape($this->hexafiltervalue)."'";
759  $sql .= ")";
760 
761  $resql = $this->db->query($sql);
762  if ($resql) {
763  $this->db->commit();
764  return 1;
765  } else {
766  $this->error = $this->db->lasterror();
767  $this->errno = $this->db->lasterrno();
768  $this->db->rollback();
769  return -1;
770  }
771  }
772 
779  public function fetch($id)
780  {
781  $sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter';
782  $sql .= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
783  $sql .= ' WHERE em.rowid = '.((int) $id);
784 
785  dol_syslog("Export::fetch", LOG_DEBUG);
786  $result = $this->db->query($sql);
787  if ($result) {
788  $obj = $this->db->fetch_object($result);
789  if ($obj) {
790  $this->id = $obj->rowid;
791  $this->model_name = $obj->label;
792  $this->datatoexport = $obj->type;
793 
794  $this->hexa = $obj->field;
795  $this->hexafiltervalue = $obj->filter;
796 
797  return 1;
798  } else {
799  $this->error = "ModelNotFound";
800  return -2;
801  }
802  } else {
803  dol_print_error($this->db);
804  return -3;
805  }
806  }
807 
808 
816  public function delete($user, $notrigger = 0)
817  {
818  global $conf, $langs;
819  $error = 0;
820 
821  $sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model";
822  $sql .= " WHERE rowid=".((int) $this->id);
823 
824  $this->db->begin();
825 
826  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
827  $resql = $this->db->query($sql);
828  if (!$resql) {
829  $error++; $this->errors[] = "Error ".$this->db->lasterror();
830  }
831 
832  // Commit or rollback
833  if ($error) {
834  foreach ($this->errors as $errmsg) {
835  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
836  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
837  }
838  $this->db->rollback();
839  return -1 * $error;
840  } else {
841  $this->db->commit();
842  return 1;
843  }
844  }
845 
846  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
853  public function list_export_model()
854  {
855  // phpcs:enable
856  global $conf, $langs;
857 
858  $sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter";
859  $sql .= " FROM ".MAIN_DB_PREFIX."export_model as em";
860  $sql .= " ORDER BY rowid";
861 
862  $result = $this->db->query($sql);
863  if ($result) {
864  $num = $this->db->num_rows($result);
865  $i = 0;
866  while ($i < $num) {
867  $obj = $this->db->fetch_object($result);
868  $keyModel = array_search($obj->type, $this->array_export_code);
869  print "<tr>";
870  print '<td><a href=export.php?step=2&action=select_model&exportmodelid='.$obj->rowid.'&datatoexport='.$obj->type.'>'.$obj->label.'</a></td>';
871  print '<td>';
872  print img_object($this->array_export_module[$keyModel]->getName(), $this->array_export_icon[$keyModel]).' ';
873  print $this->array_export_module[$keyModel]->getName().' - ';
874  // recuperation du nom de l'export
875 
876  $string = $langs->trans($this->array_export_label[$keyModel]);
877  print ($string != $this->array_export_label[$keyModel] ? $string : $this->array_export_label[$keyModel]);
878  print '</td>';
879  //print '<td>'.$obj->type.$keyModel.'</td>';
880  print '<td>'.str_replace(',', ' , ', $obj->field).'</td>';
881  if (!empty($obj->filter)) {
882  $filter = json_decode($obj->filter, true);
883  print '<td>'.str_replace(',', ' , ', $filter['field']).'</td>';
884  print '<td>'.str_replace(',', ' , ', $filter['value']).'</td>';
885  }
886  // suppression de l'export
887  print '<td class="right">';
888  print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteprof&token='.newToken().'&id='.$obj->rowid.'">';
889  print img_delete();
890  print '</a>';
891  print "</tr>";
892 
893  $i++;
894  }
895  } else {
896  dol_print_error($this->db);
897  }
898  }
899 }
db
$conf db
API class for accounts.
Definition: inc.php:41
num_open_day
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:982
dol_trunc
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.
Definition: functions.lib.php:3805
dol_osencode
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
Definition: functions.lib.php:8499
Export\__construct
__construct($db)
Constructor.
Definition: export.class.php:72
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
Export\build_filterField
build_filterField($TypeField, $NameField, $ValueField)
Build an input field used to filter the query.
Definition: export.class.php:409
Export\load_arrays
load_arrays($user, $filter='')
Load an exportable dataset.
Definition: export.class.php:86
verifCond
verifCond($strToEvaluate)
Verify if condition in string is ok or not.
Definition: functions.lib.php:8582
Export\build_filterQuery
build_filterQuery($TypeField, $NameField, $ValueField)
Build the conditionnal string from filter the query.
Definition: export.class.php:302
$form
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:142
sanitizeVal
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
Definition: functions.lib.php:825
Facture
Class to manage invoices.
Definition: facture.class.php:60
Export\list_export_model
list_export_model()
Output list all export models TODO Move this into a class htmlxxx.class.php.
Definition: export.class.php:853
Export
Class to manage exports.
Definition: export.class.php:31
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2514
Export\conditionDate
conditionDate($Field, $Value, $Sens)
conditionDate
Definition: export.class.php:387
Export\fetch
fetch($id)
Load an export profil from database.
Definition: export.class.php:779
img_delete
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
Definition: functions.lib.php:4429
Export\build_file
build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery='')
Build export file.
Definition: export.class.php:580
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
Export\build_sql
build_sql($indice, $array_selected, $array_filterValue)
Build the sql export request.
Definition: export.class.php:231
newToken
newToken()
Return the value of token currently saved into session with name 'newtoken'.
Definition: functions.lib.php:10878
Export\genDocFilter
genDocFilter($TypeField)
Build an input field used to filter the query.
Definition: export.class.php:539
dolGetModulesDirs
dolGetModulesDirs($subdir='')
Return list of modules directories.
Definition: functions2.lib.php:80
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4211
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2845
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
Export\create
create($user)
Save an export model in database.
Definition: export.class.php:739
dol_mkdir
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
Definition: functions.lib.php:6603
dol_stringtotime
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:383
float
div float
Buy price without taxes.
Definition: style.css.php:809