dolibarr 20.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
31class 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 case 'Numeric':
358 // if there is a signe +
359 if (strpos($ValueField, "+") > 0) {
360 // mode plage
361 $ValueArray = explode("+", $ValueField);
362 $szFilterQuery = "(".$NameField." >= ".((float) $ValueArray[0]);
363 $szFilterQuery .= " AND ".$NameField." <= ".((float) $ValueArray[1]).")";
364 } else {
365 if (is_numeric(substr($ValueField, 0, 1))) {
366 $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
367 } else {
368 $szFilterQuery = " ".$NameField.substr($ValueField, 0, 1).((float) substr($ValueField, 1));
369 }
370 }
371 break;
372 case 'Boolean':
373 $szFilterQuery = " ".$NameField."=".(is_numeric($ValueField) ? $ValueField : ($ValueField == 'yes' ? 1 : 0));
374 break;
375 case 'FormSelect':
376 if (is_numeric($ValueField) && $ValueField > 0) {
377 $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
378 } else {
379 $szFilterQuery = " 1=1"; // Test always true
380 }
381 break;
382 case 'Status':
383 case 'List':
384 if (is_numeric($ValueField)) {
385 $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
386 } else {
387 if (!(strpos($ValueField, '%') === false)) {
388 $szFilterQuery = " ".$NameField." LIKE '".$this->db->escape($ValueField)."'";
389 } else {
390 $szFilterQuery = " ".$NameField." = '".$this->db->escape($ValueField)."'";
391 }
392 }
393 break;
394 default:
395 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);
396 }
397
398 return $szFilterQuery;
399 }
400
409 public function conditionDate($Field, $Value, $Sens)
410 {
411 // TODO date_format is forbidden, not performant and not portable. Use instead $Value to forge the range date.
412 if (strlen($Value) == 4) {
413 $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$this->db->escape($Value)."'";
414 } elseif (strlen($Value) == 6) {
415 $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$this->db->escape($Value)."'";
416 } else {
417 $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." '".$this->db->escape($Value)."'";
418 }
419 return $Condition;
420 }
421
422 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
431 public function build_filterField($TypeField, $NameField, $ValueField)
432 {
433 // phpcs:enable
434 global $conf, $langs, $form;
435
436 $szFilterField = '';
437 $InfoFieldList = explode(":", $TypeField);
438
439 // build the input field on depend of the type of file
440 switch ($InfoFieldList[0]) {
441 case 'Text':
442 case 'Date':
443 $szFilterField = '<input type="text" name="'.$NameField.'" value="'.$ValueField.'">';
444 break;
445 case 'Duree':
446 case 'Numeric':
447 case 'Number':
448 // Must be a string text to allow to use comparison strings like "<= 99.9"
449 $szFilterField = '<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
450 break;
451 case 'Status':
452 $szFilterField = '<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
453 break;
454 case 'Boolean':
455 $szFilterField = '<select name="'.$NameField.'" class="flat">';
456 $szFilterField .= '<option ';
457 if ($ValueField == '') {
458 $szFilterField .= ' selected ';
459 }
460 $szFilterField .= ' value="">&nbsp;</option>';
461
462 $szFilterField .= '<option ';
463 if ($ValueField == 'yes' || $ValueField == '1') {
464 $szFilterField .= ' selected ';
465 }
466 $szFilterField .= ' value="1">'.yn(1).'</option>';
467
468 $szFilterField .= '<option ';
469 if ($ValueField == 'no' || $ValueField == '0') {
470 $szFilterField .= ' selected ';
471 }
472 $szFilterField .= ' value="0">'.yn(0).'</option>';
473 $szFilterField .= "</select>";
474 break;
475 case 'FormSelect':
476 //var_dump($NameField);
477 if ($InfoFieldList[1] == 'select_company') {
478 $szFilterField .= $form->select_company('', $NameField, '', 1, 0, 0, [], 0, 'maxwidth200');
479 } elseif ($InfoFieldList[1] == 'selectcontacts') {
480 //$szFilterField .= $form->selectcontacts(0, '', $NameField, '&nbsp;', '', '', 0, 'maxwidth200');
481 $szFilterField .= $form->select_contact(0, '', $NameField, '&nbsp;', '', '', 0, 'minwidth100imp maxwidth200', true);
482 } elseif ($InfoFieldList[1] == 'select_dolusers') {
483 $szFilterField .= $form->select_dolusers('', $NameField, 1, null, 0, '', '', '', 0, 0, "", 0, "", "maxwidth200");
484 }
485 break;
486 case 'List':
487 // 0 : Type of the field / Type du champ
488 // 1 : Name of the table / Nom de la table
489 // 2 : Name of the field containing the label / Nom du champ contenant le libelle
490 // 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list.
491 // 4 : Name of element for getEntity().
492
493 if (!empty($InfoFieldList[3])) {
494 $keyList = $InfoFieldList[3];
495 } else {
496 $keyList = 'rowid';
497 }
498 $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3]." as code");
499 if ($InfoFieldList[1] == 'c_stcomm') {
500 $sql = "SELECT id as id, ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3].' as code');
501 }
502 if ($InfoFieldList[1] == 'c_country') {
503 $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label, code as code";
504 }
505 $sql .= " FROM ".MAIN_DB_PREFIX.$InfoFieldList[1];
506 if (!empty($InfoFieldList[4])) {
507 $sql .= ' WHERE entity IN ('.getEntity($InfoFieldList[4]).')';
508 }
509
510 $resql = $this->db->query($sql);
511 if ($resql) {
512 $szFilterField = '<select class="flat" name="'.$NameField.'">';
513 $szFilterField .= '<option value="0">&nbsp;</option>';
514 $num = $this->db->num_rows($resql);
515
516 $i = 0;
517 if ($num) {
518 while ($i < $num) {
519 $obj = $this->db->fetch_object($resql);
520 if ($obj->label == '-') {
521 // Discard entry '-'
522 $i++;
523 continue;
524 }
525 //var_dump($InfoFieldList[1]);
526 $labeltoshow = dol_trunc($obj->label, 18);
527 if ($InfoFieldList[1] == 'c_stcomm') {
528 $langs->load("companies");
529 $labeltoshow = (($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id) ? $langs->trans("StatusProspect".$obj->id) : $obj->label);
530 }
531 if ($InfoFieldList[1] == 'c_country') {
532 //var_dump($sql);
533 $langs->load("dict");
534 $labeltoshow = (($langs->trans("Country".$obj->code) != "Country".$obj->code) ? $langs->trans("Country".$obj->code) : $obj->label);
535 }
536 if (!empty($ValueField) && $ValueField == $obj->rowid) {
537 $szFilterField .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
538 } else {
539 $szFilterField .= '<option value="'.$obj->rowid.'" >'.$labeltoshow.'</option>';
540 }
541 $i++;
542 }
543 }
544 $szFilterField .= "</select>";
545
546 $this->db->free($resql);
547 } else {
548 dol_print_error($this->db);
549 }
550 break;
551 }
552
553 return $szFilterField;
554 }
555
562 public function genDocFilter($TypeField)
563 {
564 global $langs;
565
566 $szMsg = '';
567 $InfoFieldList = explode(":", $TypeField);
568 // build the input field on depend of the type of file
569 switch ($InfoFieldList[0]) {
570 case 'Text':
571 $szMsg = $langs->trans('ExportStringFilter');
572 break;
573 case 'Date':
574 $szMsg = $langs->trans('ExportDateFilter');
575 break;
576 case 'Duree':
577 case 'Numeric':
578 $szMsg = $langs->trans('ExportNumericFilter');
579 break;
580 case 'Boolean':
581 break;
582 case 'List':
583 break;
584 }
585 return $szMsg;
586 }
587
588 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
603 public function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '', $separator = '')
604 {
605 // phpcs:enable
606 global $conf, $langs, $mysoc;
607
608 $indice = 0;
609 asort($array_selected);
610
611 dol_syslog(__METHOD__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected));
612
613 // Check parameters or context properties
614 if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) {
615 $this->error = "ErrorBadParameter";
616 dol_syslog($this->error, LOG_ERR);
617 return -1;
618 }
619
620 // Creation of class to export using model ExportXXX
621 $dir = DOL_DOCUMENT_ROOT."/core/modules/export/";
622 $file = "export_".$model.".modules.php";
623 $classname = "Export".$model;
624 require_once $dir.$file;
625 $objmodel = new $classname($this->db);
626
627 if (in_array($model, array('csvutf8', 'csviso')) && !empty($separator)) {
628 $objmodel->separator = $separator;
629 }
630
631 if (!empty($sqlquery)) {
632 $sql = $sqlquery;
633 } else {
634 // Define value for indice from $datatoexport
635 $foundindice = 0;
636 foreach ($this->array_export_code as $key => $dataset) {
637 if ($datatoexport == $dataset) {
638 $indice = $key;
639 $foundindice++;
640 //print "Found indice = ".$indice." for dataset=".$datatoexport."\n";
641 break;
642 }
643 }
644 if (empty($foundindice)) {
645 $this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
646 return -1;
647 }
648 $sql = $this->build_sql($indice, $array_selected, $array_filterValue);
649 }
650
651 // Run the SQL
652 $this->sqlusedforexport = $sql;
653 dol_syslog(__METHOD__, LOG_DEBUG);
654 $resql = $this->db->query($sql);
655 if ($resql) {
656 //$this->array_export_label[$indice]
657 if (getDolGlobalString('EXPORT_PREFIX_SPEC')) {
658 $filename = getDolGlobalString('EXPORT_PREFIX_SPEC') . "_".$datatoexport;
659 } else {
660 $filename = "export_".$datatoexport;
661 }
662 if (getDolGlobalString('EXPORT_NAME_WITH_DT')) {
663 $filename .= dol_print_date(dol_now(), '%Y%m%d%_%H%M');
664 }
665 $filename .= '.'.$objmodel->getDriverExtension();
666 $dirname = $conf->export->dir_temp.'/'.$user->id;
667
668 $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
669
670 // Open file
671 dol_mkdir($dirname);
672 $result = $objmodel->open_file($dirname."/".$filename, $outputlangs);
673
674 if ($result >= 0) {
675 // Generate header
676 $objmodel->write_header($outputlangs);
677
678 // Generate title line
679 $objmodel->write_title($this->array_export_fields[$indice], $array_selected, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
680
681 while ($obj = $this->db->fetch_object($resql)) {
682 // Process special operations
683 if (!empty($this->array_export_special[$indice])) {
684 foreach ($this->array_export_special[$indice] as $key => $value) {
685 if (!array_key_exists($key, $array_selected)) {
686 continue; // Field not selected
687 }
688 // Operation NULLIFNEG
689 if ($this->array_export_special[$indice][$key] == 'NULLIFNEG') {
690 //$alias=$this->array_export_alias[$indice][$key];
691 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
692 if ($obj->$alias < 0) {
693 $obj->$alias = '';
694 }
695 } elseif ($this->array_export_special[$indice][$key] == 'ZEROIFNEG') {
696 // Operation ZEROIFNEG
697 //$alias=$this->array_export_alias[$indice][$key];
698 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
699 if ($obj->$alias < 0) {
700 $obj->$alias = '0';
701 }
702 } elseif ($this->array_export_special[$indice][$key] == 'getNumOpenDays') {
703 // Operation GETNUMOPENDAYS (for Holiday module)
704 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
705 //$alias=$this->array_export_alias[$indice][$key];
706 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
707 $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);
708 } elseif ($this->array_export_special[$indice][$key] == 'getRemainToPay') {
709 // Operation INVOICEREMAINTOPAY
710 //$alias=$this->array_export_alias[$indice][$key];
711 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
712 $remaintopay = '';
713 if ($obj->f_rowid > 0) {
714 global $tmpobjforcomputecall;
715 if (!is_object($tmpobjforcomputecall)) {
716 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
717 $tmpobjforcomputecall = new Facture($this->db);
718 }
719 $tmpobjforcomputecall->id = $obj->f_rowid;
720 $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
721 $tmpobjforcomputecall->close_code = $obj->f_close_code;
722 $remaintopay = $tmpobjforcomputecall->getRemainToPay();
723 }
724 $obj->$alias = $remaintopay;
725 } elseif (is_array($this->array_export_special[$indice][$key]) &&
726 !empty($this->array_export_special[$indice][$key]['rule']) &&
727 $this->array_export_special[$indice][$key]['rule'] == 'compute'
728 ) {
729 // Custom compute
730 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
731 $value = '';
732 if (!empty($this->array_export_special[$indice][$key]['class']) &&
733 !empty($this->array_export_special[$indice][$key]['classfile']) &&
734 !empty($this->array_export_special[$indice][$key]['method'])
735 ) {
736 if (!dol_include_once($this->array_export_special[$indice][$key]['classfile'])) {
737 $this->error = "Computed field bad configuration: {$this->array_export_special[$indice][$key]['classfile']} not found";
738 return -1;
739 }
740
741 if (!class_exists($this->array_export_special[$indice][$key]['class'])) {
742 $this->error = "Computed field bad configuration: {$this->array_export_special[$indice][$key]['class']} class doesn't exist";
743 return -1;
744 }
745
746 $className = $this->array_export_special[$indice][$key]['class'];
747 $tmpObject = new $className($this->db);
748 if (!method_exists($tmpObject, $this->array_export_special[$indice][$key]['method'])) {
749 $this->error = "Computed field bad configuration: {$this->array_export_special[$indice][$key]['method']} method doesn't exist";
750 return -1;
751 }
752
753 $methodName = $this->array_export_special[$indice][$key]['method'];
754 $params = [];
755 if (!empty($this->array_export_special[$indice][$key]['method_params'])) {
756 foreach ($this->array_export_special[$indice][$key]['method_params'] as $paramName) {
757 $params[] = $obj->$paramName ?? null;
758 }
759 }
760 $value = $tmpObject->$methodName(...$params);
761 }
762 $obj->$alias = $value;
763 } else {
764 // TODO FIXME
765 // Export of compute field does not work. $obj contains $obj->alias_field and formula may contains $obj->field
766 // Also the formula may contains objects of class that are not loaded.
767 $computestring = $this->array_export_special[$indice][$key];
768 //$tmp = (string) dol_eval($computestring, 1, 0, '2');
769 //$obj->$alias = $tmp;
770
771 $this->error = "ERROPNOTSUPPORTED. Operation ".$computestring." not supported. Export of 'computed' extrafields is not yet supported, please remove field.";
772 return -1;
773 }
774 }
775 }
776 // end of special operation processing
777 $objmodel->write_record($array_selected, $obj, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
778 }
779
780 // Generate Footer
781 $objmodel->write_footer($outputlangs);
782
783 // Close file
784 $objmodel->close_file();
785
786 return 1;
787 } else {
788 $this->error = $objmodel->error;
789 dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
790 return -1;
791 }
792 } else {
793 $this->error = $this->db->error()." - sql=".$sql;
794 return -1;
795 }
796 }
797
804 public function create($user)
805 {
806 dol_syslog("Export.class.php::create");
807
808 $this->db->begin();
809
810 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'export_model (';
811 $sql .= 'label,';
812 $sql .= 'type,';
813 $sql .= 'field,';
814 $sql .= 'fk_user,';
815 $sql .= 'filter';
816 $sql .= ') VALUES (';
817 $sql .= "'".$this->db->escape($this->model_name)."',";
818 $sql .= " '".$this->db->escape($this->datatoexport)."',";
819 $sql .= " '".$this->db->escape($this->hexa)."',";
820 $sql .= ' '.(isset($this->fk_user) ? (int) $this->fk_user : 'null').",";
821 $sql .= " '".$this->db->escape($this->hexafiltervalue)."'";
822 $sql .= ")";
823
824 $resql = $this->db->query($sql);
825 if ($resql) {
826 $this->db->commit();
827 return 1;
828 } else {
829 $this->error = $this->db->lasterror();
830 $this->errno = $this->db->lasterrno();
831 $this->db->rollback();
832 return -1;
833 }
834 }
835
842 public function fetch($id)
843 {
844 $sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter';
845 $sql .= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
846 $sql .= ' WHERE em.rowid = '.((int) $id);
847
848 dol_syslog("Export::fetch", LOG_DEBUG);
849 $result = $this->db->query($sql);
850 if ($result) {
851 $obj = $this->db->fetch_object($result);
852 if ($obj) {
853 $this->id = $obj->rowid;
854 $this->model_name = $obj->label;
855 $this->datatoexport = $obj->type;
856
857 $this->hexa = $obj->field;
858 $this->hexafiltervalue = $obj->filter;
859
860 return 1;
861 } else {
862 $this->error = "ModelNotFound";
863 return -2;
864 }
865 } else {
866 dol_print_error($this->db);
867 return -3;
868 }
869 }
870
871
879 public function delete($user, $notrigger = 0)
880 {
881 global $conf, $langs;
882 $error = 0;
883
884 $sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model";
885 $sql .= " WHERE rowid=".((int) $this->id);
886
887 $this->db->begin();
888
889 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
890 $resql = $this->db->query($sql);
891 if (!$resql) {
892 $error++;
893 $this->errors[] = "Error ".$this->db->lasterror();
894 }
895
896 // Commit or rollback
897 if ($error) {
898 foreach ($this->errors as $errmsg) {
899 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
900 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
901 }
902 $this->db->rollback();
903 return -1 * $error;
904 } else {
905 $this->db->commit();
906 return 1;
907 }
908 }
909
910 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
917 public function list_export_model()
918 {
919 // phpcs:enable
920 global $conf, $langs;
921
922 $sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter";
923 $sql .= " FROM ".MAIN_DB_PREFIX."export_model as em";
924 $sql .= " ORDER BY rowid";
925
926 $result = $this->db->query($sql);
927 if ($result) {
928 $num = $this->db->num_rows($result);
929 $i = 0;
930 while ($i < $num) {
931 $obj = $this->db->fetch_object($result);
932 $keyModel = array_search($obj->type, $this->array_export_code);
933 print "<tr>";
934 print '<td><a href=export.php?step=2&action=select_model&exportmodelid='.$obj->rowid.'&datatoexport='.$obj->type.'>'.$obj->label.'</a></td>';
935 print '<td>';
936 print img_object($this->array_export_module[$keyModel]->getName(), $this->array_export_icon[$keyModel]).' ';
937 print $this->array_export_module[$keyModel]->getName().' - ';
938 // recover export name / recuperation du nom de l'export
939
940 $string = $langs->trans($this->array_export_label[$keyModel]);
941 print($string != $this->array_export_label[$keyModel] ? $string : $this->array_export_label[$keyModel]);
942 print '</td>';
943 //print '<td>'.$obj->type.$keyModel.'</td>';
944 print '<td>'.str_replace(',', ' , ', $obj->field).'</td>';
945 if (!empty($obj->filter)) {
946 $filter = json_decode($obj->filter, true);
947 print '<td>'.str_replace(',', ' , ', $filter['field']).'</td>';
948 print '<td>'.str_replace(',', ' , ', $filter['value']).'</td>';
949 }
950 // remove export / suppression de l'export
951 print '<td class="right">';
952 print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteprof&token='.newToken().'&id='.$obj->rowid.'">';
953 print img_delete();
954 print '</a>';
955 print "</tr>";
956
957 $i++;
958 }
959 } else {
960 dol_print_error($this->db);
961 }
962 }
963}
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.
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)
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.
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).
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
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)