dolibarr 23.0.3
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 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
7 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
34class Export
35{
39 public $db;
40
44 public $id;
45
49 public $array_export_icon;
50
54 public $array_export_perms;
55
56
60 public $error;
64 public $errno;
68 public $errors;
69
73 public $array_export_code = array(); // Tableau de "idmodule_numexportprofile"
77 public $array_export_code_for_sort = array(); // Tableau de "idmodule_numexportprofile"
81 public $array_export_module = array(); // Tableau de "nom de modules"
85 public $array_export_label = array(); // Array of "Translation key" to use for each export profile
89 public $array_export_sql_start = array(); // Tableau des "requetes sql"
93 public $array_export_sql_end = array(); // Tableau des "requetes sql"
97 public $array_export_sql_order = array(); // Tableau des "requetes sql"
98
102 public $array_export_fields = array(); // Tableau des listes de champ+libelle a exporter
106 public $array_export_TypeFields = array(); // Tableau des listes de champ+Type de filtre
110 public $array_export_FilterValue = array(); // Tableau des listes de champ+Valeur a filtrer
114 public $array_export_entities = array(); // Tableau des listes de champ+alias a exporter
118 public $array_export_dependencies = array(); // array of list of entities that must take care of the DISTINCT if a field is added into export
122 public $array_export_special = array(); // array of special operations to do on fields
126 public $array_export_examplevalues = array(); // array with examples for fields
130 public $array_export_help = array(); // array with tooltip help for fields
131
132 // To store export templates
136 public $hexa;
140 public $hexafiltervalue;
144 public $datatoexport;
148 public $model_name;
152 public $fk_user;
153
157 public $sqlusedforexport;
158
159
165 public function __construct($db)
166 {
167 $this->db = $db;
168 }
169
170
171 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
179 public function load_arrays($user, $filter = '')
180 {
181 // phpcs:enable
182 global $langs, $conf, $mysoc;
183
184 dol_syslog(get_class($this)."::load_arrays user=".$user->id." filter=".$filter);
185
186 $i = 0;
187
188 // Define list of modules directories into modulesdir
189 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
190
191 $modulesdir = dolGetModulesDirs();
192
193 foreach ($modulesdir as $dir) {
194 // Search available exports
195 $handle = @opendir(dol_osencode($dir));
196 if (is_resource($handle)) {
197 // Search module files
198 while (($file = readdir($handle)) !== false) {
199 // Ignore Module Builder backup files (*.php.back)
200 if (preg_match('/\.back$/i', $file)) {
201 continue;
202 }
203
204 $reg = array();
205 if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) {
206 $modulename = $reg[1];
207
208 // Defined if module is enabled
209 $enabled = true;
210 $part = strtolower(preg_replace('/^mod/i', '', $modulename));
211 if ($part == 'propale') {
212 $part = 'propal';
213 }
214 if (empty($conf->$part->enabled)) {
215 $enabled = false;
216 }
217
218 if ($enabled) {
219 // Loading Class
220 $file = $dir.$modulename.".class.php";
221 $classname = $modulename;
222 require_once $file;
223 $module = new $classname($this->db);
224 '@phan-var-force DolibarrModules $module';
225
226 if (isset($module->export_code) && is_array($module->export_code)) {
227 foreach ($module->export_code as $r => $value) {
228 //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).'<br>';
229 if ($filter && ($filter != $module->export_code[$r])) {
230 continue;
231 }
232
233 // Test if condition to show are ok
234 if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) {
235 continue;
236 }
237
238 // Test if permissions are ok
239 $bool = true;
240 if (isset($module->export_permission)) {
241 foreach ($module->export_permission[$r] as $val) {
242 $perm = $val;
243 //print_r("$perm[0]-$perm[1]-$perm[2]<br>");
244 if (!empty($perm[2])) {
245 $bool = isset($user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]}) ? $user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]} : false;
246 } elseif (!empty($perm[1])) {
247 $bool = isset($user->rights->{$perm[0]}->{$perm[1]}) ? $user->rights->{$perm[0]}->{$perm[1]} : false;
248 } else {
249 $bool = false;
250 }
251 if ($perm[0] == 'user' && $user->admin) {
252 $bool = true;
253 }
254 if (!$bool) {
255 break;
256 }
257 }
258 }
259 //print $bool." $perm[0]"."<br>";
260
261 // Permissions ok
262 // if ($bool)
263 // {
264 // Charge fichier lang en rapport
265 $langtoload = $module->getLangFilesArray();
266 if (is_array($langtoload)) {
267 foreach ($langtoload as $key) {
268 $langs->load($key);
269 }
270 }
271
272
273 // Module
274 $this->array_export_module[$i] = $module;
275 // Permission
276 $this->array_export_perms[$i] = $bool;
277 // Icon
278 $this->array_export_icon[$i] = (isset($module->export_icon[$r]) ? $module->export_icon[$r] : $module->picto);
279 // Code of the export dataset
280 $this->array_export_code[$i] = $module->export_code[$r];
281 // Define a key for sort
282 $this->array_export_code_for_sort[$i] = $module->module_position.'_'.$module->export_code[$r]; // Add a key into the module
283 // Export Dataset Label
284 $this->array_export_label[$i] = $module->getExportDatasetLabel($r);
285 // Table of fields to export
286 $this->array_export_fields[$i] = (isset($module->export_fields_array[$r]) ? $module->export_fields_array[$r] : []);
287 // Table of fields to be filtered (key=field, value1=data type) Verifies that the module has filters
288 $this->array_export_TypeFields[$i] = (isset($module->export_TypeFields_array[$r]) ? $module->export_TypeFields_array[$r] : '');
289 // Table of entities to export (key=field, value=entity)
290 $this->array_export_entities[$i] = (isset($module->export_entities_array[$r]) ? $module->export_entities_array[$r] : '');
291 // Table of entities requiring to abandon DISTINCT (key=entity, valeur=field id child records)
292 $this->array_export_dependencies[$i] = (!empty($module->export_dependencies_array[$r]) ? $module->export_dependencies_array[$r] : '');
293 // Table of special field operations
294 $this->array_export_special[$i] = (!empty($module->export_special_array[$r]) ? $module->export_special_array[$r] : '');
295 // Array of examples
296 $this->array_export_examplevalues[$i] = (!empty($module->export_examplevalues_array[$r]) ? $module->export_examplevalues_array[$r] : null);
297 // Array of help tooltips
298 $this->array_export_help[$i] = (!empty($module->export_help_array[$r]) ? $module->export_help_array[$r] : '');
299
300 // SQL dataset query / Requete SQL du dataset
301 $this->array_export_sql_start[$i] = $module->export_sql_start[$r];
302 $this->array_export_sql_end[$i] = $module->export_sql_end[$r];
303 $this->array_export_sql_order[$i] = (!empty($module->export_sql_order[$r]) ? $module->export_sql_order[$r] : null);
304 //$this->array_export_sql[$i]=$module->export_sql[$r];
305
306 // @phan-suppress-next-line PhanUndeclaredProperty
307 dol_syslog(get_class($this)."::load_arrays loaded for module ".$modulename." with index ".$i.", dataset=".$module->export_code[$r].", nb of fields=".(property_exists($module, 'export_fields_code') && !empty($module->export_fields_code[$r]) ? count($module->export_fields_code[$r]) : ''));
308 $i++;
309 // }
310 }
311 }
312 }
313 }
314 }
315 closedir($handle);
316 }
317 }
318
319 return 1;
320 }
321
322
323 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
333 public function build_sql($indice, $array_selected, $array_filterValue)
334 {
335 // phpcs:enable
336 // Build the sql request
337 $sql = $this->array_export_sql_start[$indice];
338 $i = 0;
339
340 //print_r($array_selected);
341 foreach ($this->array_export_fields[$indice] as $key => $value) {
342 if (!array_key_exists($key, $array_selected)) {
343 continue; // Field not selected
344 }
345 if (preg_match('/^none\./', $key)) {
346 continue; // A field that must not appears into SQL
347 }
348 if ($i > 0) {
349 $sql .= ', ';
350 } else {
351 $i++;
352 }
353
354 if (strpos($key, ' as ') === false) {
355 $newfield = $key.' as '.str_replace(array('.', '-', '(', ')'), '_', $key);
356 } else {
357 $newfield = $key;
358 }
359
360 $sql .= $newfield;
361 }
362 $sql .= $this->array_export_sql_end[$indice];
363
364 // Add the WHERE part. Filtering into sql if a filtering array is provided
365 if (is_array($array_filterValue) && !empty($array_filterValue)) {
366 $sqlWhere = '';
367 // Loop on each condition to add
368 foreach ($array_filterValue as $key => $value) {
369 if (preg_match('/GROUP_CONCAT/i', $key)) {
370 continue;
371 }
372 if ($value != '') {
373 $sqlWhere .= " AND ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
374 }
375 }
376 $sql .= $sqlWhere;
377 }
378
379 // Add the sort order
380 $sql .= $this->array_export_sql_order[$indice];
381
382 // Add the HAVING part.
383 if (is_array($array_filterValue) && !empty($array_filterValue)) {
384 // Loop on each condition to add
385 foreach ($array_filterValue as $key => $value) {
386 if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') {
387 $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
388 }
389 }
390 }
391
392 return $sql;
393 }
394
395 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
404 public function build_filterQuery($TypeField, $NameField, $ValueField)
405 {
406 // phpcs:enable
407 $NameField = sanitizeVal($NameField, 'aZ09');
408 $szFilterQuery = '';
409
410 //print $TypeField." ".$NameField." ".$ValueField;
411 $InfoFieldList = explode(":", $TypeField);
412 // build the input field on depend of the type of file
413 switch ($InfoFieldList[0]) {
414 case 'Text':
415 if (!(strpos($ValueField, '%') === false)) {
416 $szFilterQuery = " ".$this->db->sanitize($NameField)." LIKE '".$this->db->escape($ValueField)."'";
417 } else {
418 $szFilterQuery = " ".$this->db->sanitize($NameField)." = '".$this->db->escape($ValueField)."'";
419 }
420 break;
421 case 'Date':
422 if (strpos($ValueField, "+") > 0) {
423 // mode plage
424 $ValueArray = explode("+", $ValueField);
425 $szFilterQuery = "(".$this->conditionDate($NameField, trim($ValueArray[0]), ">=");
426 $szFilterQuery .= " AND ".$this->conditionDate($NameField, trim($ValueArray[1]), "<=").")";
427 } else {
428 if (is_numeric(substr($ValueField, 0, 1))) {
429 $szFilterQuery = $this->conditionDate($NameField, trim($ValueField), "=");
430 } else {
431 $szFilterQuery = $this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1));
432 }
433 }
434 break;
435 case 'Duree':
436 case 'Numeric':
437 // if there is a signe +
438 if (strpos($ValueField, "+") > 0) {
439 // mode plage
440 $ValueArray = explode("+", $ValueField);
441 $szFilterQuery = "(".$NameField." >= ".((float) $ValueArray[0]);
442 $szFilterQuery .= " AND ".$NameField." <= ".((float) $ValueArray[1]).")";
443 } else {
444 if (is_numeric(substr($ValueField, 0, 1))) {
445 $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
446 } else {
447 $szFilterQuery = " ".$NameField.substr($ValueField, 0, 1).((float) substr($ValueField, 1));
448 }
449 }
450 break;
451 case 'Boolean':
452 $szFilterQuery = " ".$NameField."=".(is_numeric($ValueField) ? $ValueField : ($ValueField == 'yes' ? 1 : 0));
453 break;
454 case 'FormSelect':
455 if (is_numeric($ValueField) && $ValueField > 0) {
456 $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
457 } else {
458 $szFilterQuery = " 1=1"; // Test always true
459 }
460 break;
461 case 'Status':
462 case 'List':
463 if (is_numeric($ValueField)) {
464 $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
465 } else {
466 if (!(strpos($ValueField, '%') === false)) {
467 $szFilterQuery = " ".$NameField." LIKE '".$this->db->escape($ValueField)."'";
468 } else {
469 $szFilterQuery = " ".$NameField." = '".$this->db->escape($ValueField)."'";
470 }
471 }
472 break;
473 default:
474 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);
475 }
476
477 return $szFilterQuery;
478 }
479
488 public function conditionDate($Field, $Value, $Sens)
489 {
490 // TODO date_format is forbidden, not performant and not portable. Use instead $Value to forge the range date.
491 if (strlen($Value) == 4) {
492 $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$this->db->escape($Value)."'";
493 } elseif (strlen($Value) == 6) {
494 $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$this->db->escape($Value)."'";
495 } else {
496 $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." '".$this->db->escape($Value)."'";
497 }
498 return $Condition;
499 }
500
501 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
510 public function build_filterField($TypeField, $NameField, $ValueField)
511 {
512 // phpcs:enable
513 global $langs, $form;
514
515 $szFilterField = '';
516 $InfoFieldList = explode(":", $TypeField);
517
518 // build the input field on depend of the type of file
519 switch ($InfoFieldList[0]) {
520 case 'Text':
521 case 'Date':
522 $szFilterField = '<input type="text" name="'.$NameField.'" value="'.$ValueField.'">';
523 break;
524 case 'Duree':
525 case 'Numeric':
526 case 'Number':
527 // Must be a string text to allow to use comparison strings like "<= 99.9"
528 $szFilterField = '<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
529 break;
530 case 'Status':
531 $szFilterField = '<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
532 break;
533 case 'Boolean':
534 $szFilterField = '<select name="'.$NameField.'" id="'.dol_escape_all($NameField).'" class="flat width75 maxwidth75">';
535 $szFilterField .= '<option ';
536 if ($ValueField == '') {
537 $szFilterField .= ' selected ';
538 }
539 $szFilterField .= ' value="">&nbsp;</option>';
540
541 $szFilterField .= '<option ';
542 if ($ValueField == 'yes' || $ValueField == '1') {
543 $szFilterField .= ' selected ';
544 }
545 $szFilterField .= ' value="1">'.yn(1).'</option>';
546
547 $szFilterField .= '<option ';
548 if ($ValueField == 'no' || $ValueField == '0') {
549 $szFilterField .= ' selected ';
550 }
551 $szFilterField .= ' value="0">'.yn(0).'</option>';
552 $szFilterField .= "</select>";
553 $szFilterField .= ajax_combobox(dol_escape_all($NameField));
554 break;
555 case 'FormSelect':
556 //var_dump($NameField);
557 if ($InfoFieldList[1] == 'select_company') {
558 $szFilterField .= $form->select_company('', $NameField, '', 1, 0, 0, [], 0, 'maxwidth200');
559 } elseif ($InfoFieldList[1] == 'selectcontacts') {
560 //$szFilterField .= $form->selectcontacts(0, '', $NameField, '&nbsp;', '', '', 0, 'maxwidth200');
561 $szFilterField .= $form->select_contact(0, '', $NameField, '&nbsp;', '', '', 0, 'minwidth100imp maxwidth200', true);
562 } elseif ($InfoFieldList[1] == 'select_dolusers') {
563 $szFilterField .= $form->select_dolusers('', $NameField, 1, null, 0, '', '', '', 0, 0, "", 0, "", "maxwidth200");
564 }
565 break;
566 case 'List':
567 // 0 : Type of the field / Type du champ
568 // 1 : Name of the table / Nom de la table
569 // 2 : Name of the field containing the label / Nom du champ contenant le libelle
570 // 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list.
571 // 4 : Name of element for getEntity().
572
573 if (!empty($InfoFieldList[3])) {
574 $keyList = $InfoFieldList[3];
575 } else {
576 $keyList = 'rowid';
577 }
578 $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3]." as code");
579 if ($InfoFieldList[1] == 'c_stcomm') {
580 $sql = "SELECT id as id, ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3].' as code');
581 }
582 if ($InfoFieldList[1] == 'c_country') {
583 $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label, code as code";
584 }
585 $sql .= " FROM ".MAIN_DB_PREFIX.$InfoFieldList[1];
586 if (!empty($InfoFieldList[4])) {
587 $sql .= ' WHERE entity IN ('.getEntity($InfoFieldList[4]).')';
588 }
589
590 $resql = $this->db->query($sql);
591 if ($resql) {
592 $szFilterField = '<select class="minwidth300 maxwidth500" name="'.$NameField.'" id="'.dol_escape_all($NameField).'">';
593 $szFilterField .= '<option value="0">&nbsp;</option>';
594 $num = $this->db->num_rows($resql);
595
596 $i = 0;
597 if ($num) {
598 while ($i < $num) {
599 $obj = $this->db->fetch_object($resql);
600 if ($obj->label == '-') {
601 // Discard entry '-'
602 $i++;
603 continue;
604 }
605 //var_dump($InfoFieldList[1]);
606 $labeltoshow = $obj->label;
607 if ($InfoFieldList[1] == 'c_stcomm') {
608 $langs->load("companies");
609 $labeltoshow = (($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id) ? $langs->trans("StatusProspect".$obj->id) : $obj->label);
610 }
611 if ($InfoFieldList[1] == 'c_country') {
612 //var_dump($sql);
613 $langs->load("dict");
614 $labeltoshow = (($langs->trans("Country".$obj->code) != "Country".$obj->code) ? $langs->trans("Country".$obj->code) : $obj->label);
615 }
616 if (!empty($ValueField) && $ValueField == $obj->rowid) {
617 $szFilterField .= '<option value="'.$obj->rowid.'" selected data-html="'.dolPrintHTMLForAttribute($labeltoshow).'">'.dolPrintHTML($labeltoshow).'</option>';
618 } else {
619 $szFilterField .= '<option value="'.$obj->rowid.'" data-html="'.dolPrintHTMLForAttribute($labeltoshow).'">'.$labeltoshow.'</option>';
620 }
621 $i++;
622 }
623 }
624 $szFilterField .= "</select>";
625 $szFilterField .= ajax_combobox(dol_escape_all($NameField));
626
627 $this->db->free($resql);
628 } else {
629 dol_print_error($this->db);
630 }
631 break;
632 }
633
634 return $szFilterField;
635 }
636
643 public function genDocFilter($TypeField)
644 {
645 global $langs;
646
647 $szMsg = '';
648 $InfoFieldList = explode(":", $TypeField);
649 // build the input field on depend of the type of file
650 switch ($InfoFieldList[0]) {
651 case 'Text':
652 $szMsg = $langs->trans('ExportStringFilter');
653 break;
654 case 'Date':
655 $szMsg = $langs->trans('ExportDateFilter');
656 break;
657 case 'Duree':
658 case 'Numeric':
659 $szMsg = $langs->trans('ExportNumericFilter');
660 break;
661 case 'Boolean':
662 break;
663 case 'List':
664 break;
665 }
666 return $szMsg;
667 }
668
669 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
684 public function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '', $separator = '')
685 {
686 // phpcs:enable
687 global $conf, $langs, $mysoc;
688
689 $indice = 0;
690 asort($array_selected);
691
692 dol_syslog(__METHOD__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected));
693
694 // Check parameters or context properties
695 if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) {
696 $this->error = "ErrorBadParameter";
697 dol_syslog($this->error, LOG_ERR);
698 return -1;
699 }
700
701 // Creation of class to export using model ExportXXX
702 $dir = DOL_DOCUMENT_ROOT."/core/modules/export/";
703 $file = "export_".$model.".modules.php";
704 $classname = "Export".$model;
705 require_once $dir.$file;
706 $objmodel = new $classname($this->db);
708 '@phan-var-force ModeleExports $objmodel';
709
710 if (in_array($model, array('csvutf8', 'csviso')) && !empty($separator) && empty($objmodel->separator)) {
711 $objmodel->separator = $separator;
712 }
713
714 if (!empty($sqlquery)) {
715 $sql = $sqlquery;
716 } else {
717 // Define value for indice from $datatoexport
718 $foundindice = 0;
719 foreach ($this->array_export_code as $key => $dataset) {
720 if ($datatoexport == $dataset) {
721 $indice = $key;
722 $foundindice++;
723 //print "Found indice = ".$indice." for dataset=".$datatoexport."\n";
724 break;
725 }
726 }
727 if (empty($foundindice)) {
728 $this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
729 return -1;
730 }
731 $sql = $this->build_sql($indice, $array_selected, $array_filterValue);
732 }
733
734 // Run the SQL
735 $this->sqlusedforexport = $sql;
736 dol_syslog(__METHOD__, LOG_DEBUG);
737 $resql = $this->db->query($sql);
738 if ($resql) {
739 //$this->array_export_label[$indice]
740 if (getDolGlobalString('EXPORT_PREFIX_SPEC')) {
741 $filename = getDolGlobalString('EXPORT_PREFIX_SPEC') . "_".$datatoexport;
742 } else {
743 $filename = "export_".$datatoexport;
744 }
745 if (getDolGlobalString('EXPORT_NAME_WITH_DT')) {
746 $filename .= dol_print_date(dol_now(), '%Y%m%d%_%H%M');
747 }
748 $filename .= '.'.$objmodel->getDriverExtension();
749 $dirname = $conf->export->dir_temp.'/'.$user->id;
750
751 $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
752
753 // Open file
754 dol_mkdir($dirname);
755 $result = $objmodel->open_file($dirname."/".$filename, $outputlangs);
756
757 if ($result >= 0) {
758 // Generate header
759 $objmodel->write_header($outputlangs);
760
761 // Generate title line
762 $objmodel->write_title($this->array_export_fields[$indice], $array_selected, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
763
764 //$MAXFORTEST = getDolGlobalInt('MAX_FOR_TEST_EXPORT'); // For test on large database, we can set it to a non zero value and uncomment code that use it later to limit the export size
765 $counterlineexported = 0;
766 while ($obj = $this->db->fetch_object($resql)) {
767 $counterlineexported++;
768 /*if ($MAXFORTEST && $counterlineexported >= $MAXFORTEST) {
769 break;
770 }*/
771
772 // Process special operations
773 if (!empty($this->array_export_special[$indice])) {
774 foreach ($this->array_export_special[$indice] as $key => $value) {
775 if (!array_key_exists($key, $array_selected)) {
776 continue; // Field not selected
777 }
778
779 // TODO: Not sure why the original was not using $value directly.
780 $item = $this->array_export_special[$indice][$key];
781 // Operation NULLIFNEG
782 if (is_string($item) && $item == 'NULLIFNEG') { // @phan-suppress-current-line PhanTypeComparisonFromArray
783 //$alias=$this->array_export_alias[$indice][$key];
784 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
785 if ($obj->$alias < 0) {
786 $obj->$alias = '';
787 }
788 } elseif (is_string($item) && $item == 'ZEROIFNEG') {
789 // Operation ZEROIFNEG
790 //$alias=$this->array_export_alias[$indice][$key];
791 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
792 if ($obj->$alias < 0) {
793 $obj->$alias = '0';
794 }
795 } elseif (is_string($item) && $item == 'getNumOpenDays') {
796 // Operation GETNUMOPENDAYS (for Holiday module)
797 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
798
799 //$alias=$this->array_export_alias[$indice][$key];
800 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
801 $country_id = $mysoc->country_id;
802 if ($obj->u_fk_country > 0) { // When special field getNumOpenDays is set, we must have a u.fk_country in field list.
803 $country_id = $obj->u_fk_country;
804 }
805
806 $obj->$alias = num_open_day(dol_stringtotime($obj->d_date_debut, 1), dol_stringtotime($obj->d_date_fin, 1), 0, 1, $obj->d_halfday, $country_id);
807 } elseif (is_string($item) && $item == 'getRemainToPay') {
808 // Operation INVOICEREMAINTOPAY
809 //$alias=$this->array_export_alias[$indice][$key];
810 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
811 $remaintopay = '';
812 if ($obj->f_rowid > 0) {
813 global $tmpobjforcomputecall;
814 if (!is_object($tmpobjforcomputecall)) {
815 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
816 $tmpobjforcomputecall = new Facture($this->db);
817 }
818 $tmpobjforcomputecall->id = $obj->f_rowid;
819 $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
820 $tmpobjforcomputecall->close_code = $obj->f_close_code;
821 $remaintopay = $tmpobjforcomputecall->getRemainToPay();
822 }
823 $obj->$alias = $remaintopay;
824 } elseif (is_array($item) && array_key_exists('rule', $item) && $item['rule'] == 'compute') {
825 // Custom compute
826 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
827 $value = '';
828 if (!empty($item['class']) &&
829 !empty($item['classfile']) &&
830 !empty($item['method'])
831 ) {
832 if (!dol_include_once($item['classfile'])) {
833 $this->error = "Computed field bad configuration: {$item['classfile']} not found";
834 return -1;
835 }
836
837 if (!class_exists($item['class'])) {
838 $this->error = "Computed field bad configuration: {$item['class']} class doesn't exist";
839 return -1;
840 }
841
842 $className = $item['class'];
843 $tmpObject = new $className($this->db);
844 '@phan-var-force CommonObject $tmpObject';
845
846 if (!method_exists($tmpObject, $item['method'])) {
847 $this->error = "Computed field bad configuration: {$item['method']} method doesn't exist";
848 return -1;
849 }
850
851 $methodName = dol_escape_all($item['method']);
852 $params = [];
853 if (!empty($item['method_params'])) {
854 // Example used for export of "Stocks and location (warehouse) with batch" in field "Date of last movement"
855 foreach ($item['method_params'] as $paramName) {
856 if (property_exists($obj, $paramName)) {
857 $params[] = $obj->$paramName;
858 } else {
859 $params[] = $paramName;
860 }
861 }
862 }
863 //var_dump($tmpObject);var_dump($methodName);var_dump($params);exit;
864 $value = $tmpObject->$methodName(...$params);
865 }
866 $obj->$alias = $value;
867 } else {
868 // TODO FIXME
869 // Export of computed extra field does not work. $obj contains $obj->alias_field and formula may contains $obj->field
870 // Also the formula may contains objects of class that are not loaded.
871 //$computestring = is_string($item) ? $item : json_encode($item);
872 //$tmp = (string) dol_eval((string) $computestring, 1, 0, '2');
873 //$obj->$alias = $tmp;
874
875 $this->error = "ERRORNOTSUPPORTED. Operation not supported. Export of ".var_export($key, true).' '.var_export($item, true)." computed extrafields is not yet supported, please remove field.";
876 return -1;
877 }
878 }
879 }
880 // end of special operation processing
881 $objmodel->write_record($array_selected, $obj, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
882 }
883
884 // Generate Footer
885 $objmodel->write_footer($outputlangs);
886
887 // Close file
888 $objmodel->close_file();
889
890 return 1;
891 } else {
892 $this->error = $objmodel->error;
893 dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
894 return -1;
895 }
896 } else {
897 $this->error = $this->db->error()." - sql=".$sql;
898 return -1;
899 }
900 }
901
908 public function create($user)
909 {
910 dol_syslog("Export.class.php::create");
911
912 $this->db->begin();
913
914 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'export_model (';
915 $sql .= 'label,';
916 $sql .= 'type,';
917 $sql .= 'field,';
918 $sql .= 'fk_user,';
919 $sql .= 'filter';
920 $sql .= ') VALUES (';
921 $sql .= "'".$this->db->escape($this->model_name)."',";
922 $sql .= " '".$this->db->escape($this->datatoexport)."',";
923 $sql .= " '".$this->db->escape($this->hexa)."',";
924 $sql .= ' '.(isset($this->fk_user) ? (int) $this->fk_user : 'null').",";
925 $sql .= " '".$this->db->escape($this->hexafiltervalue)."'";
926 $sql .= ")";
927
928 $resql = $this->db->query($sql);
929 if ($resql) {
930 $this->db->commit();
931 return 1;
932 } else {
933 $this->error = $this->db->lasterror();
934 $this->errno = $this->db->lasterrno();
935 $this->db->rollback();
936 return -1;
937 }
938 }
939
946 public function fetch($id)
947 {
948 $sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter';
949 $sql .= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
950 $sql .= ' WHERE em.rowid = '.((int) $id);
951
952 dol_syslog("Export::fetch", LOG_DEBUG);
953 $result = $this->db->query($sql);
954 if ($result) {
955 $obj = $this->db->fetch_object($result);
956 if ($obj) {
957 $this->id = $obj->rowid;
958 $this->model_name = $obj->label;
959 $this->datatoexport = $obj->type;
960
961 $this->hexa = $obj->field;
962 $this->hexafiltervalue = $obj->filter;
963
964 return 1;
965 } else {
966 $this->error = "ModelNotFound";
967 return -2;
968 }
969 } else {
970 dol_print_error($this->db);
971 return -3;
972 }
973 }
974
975
983 public function delete($user, $notrigger = 0)
984 {
985 $error = 0;
986
987 $sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model";
988 $sql .= " WHERE rowid=".((int) $this->id);
989
990 $this->db->begin();
991
992 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
993 $resql = $this->db->query($sql);
994 if (!$resql) {
995 $error++;
996 $this->errors[] = "Error ".$this->db->lasterror();
997 }
998
999 // Commit or rollback
1000 if ($error) {
1001 foreach ($this->errors as $errmsg) {
1002 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1003 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1004 }
1005 $this->db->rollback();
1006 return -1 * $error;
1007 } else {
1008 $this->db->commit();
1009 return 1;
1010 }
1011 }
1012
1013 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1020 public function list_export_model()
1021 {
1022 // phpcs:enable
1023 global $langs;
1024
1025 $sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter";
1026 $sql .= " FROM ".MAIN_DB_PREFIX."export_model as em";
1027 $sql .= " ORDER BY rowid";
1028
1029 $result = $this->db->query($sql);
1030 if ($result) {
1031 $num = $this->db->num_rows($result);
1032 $i = 0;
1033 while ($i < $num) {
1034 $obj = $this->db->fetch_object($result);
1035 $keyModel = array_search($obj->type, $this->array_export_code);
1036 print "<tr>";
1037 print '<td><a href=export.php?step=2&action=select_model&exportmodelid='.$obj->rowid.'&datatoexport='.$obj->type.'>'.$obj->label.'</a></td>';
1038 print '<td>';
1039 print img_object($this->array_export_module[$keyModel]->getName(), $this->array_export_icon[$keyModel]).' ';
1040 print $this->array_export_module[$keyModel]->getName().' - ';
1041 // recover export name / recuperation du nom de l'export
1042
1043 $string = $langs->trans($this->array_export_label[$keyModel]);
1044 print($string != $this->array_export_label[$keyModel] ? $string : $this->array_export_label[$keyModel]);
1045 print '</td>';
1046 //print '<td>'.$obj->type.$keyModel.'</td>';
1047 print '<td>'.str_replace(',', ' , ', $obj->field).'</td>';
1048 if (!empty($obj->filter)) {
1049 $filter = json_decode($obj->filter, true);
1050 print '<td>'.str_replace(',', ' , ', $filter['field']).'</td>';
1051 print '<td>'.str_replace(',', ' , ', $filter['value']).'</td>';
1052 }
1053 // remove export / suppression de l'export
1054 print '<td class="right">';
1055 print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteprof&token='.newToken().'&id='.$obj->rowid.'">';
1056 print img_delete();
1057 print '</a>';
1058 print "</tr>";
1059
1060 $i++;
1061 }
1062 } else {
1063 dol_print_error($this->db);
1064 }
1065 }
1066}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:475
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.
genDocFilter($TypeField)
Build an input field used to filter the query.
Class to manage invoices.
global $mysoc
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $countryCodeOrId='')
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:434
dolGetModulesDirs($subdir='')
Return list of directories that contain modules.
dol_now($mode='gmt')
Return date for now.
verifCond($strToEvaluate, $onlysimplestring='1')
Verify if condition in string is ok or not.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dolPrintHTML($s, $allowiframe=0)
Return a string (that can be on several lines) ready to be output on a HTML page.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
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'.
dolPrintHTMLForAttribute($s, $escapeonlyhtmltags=0, $allowothertags=array())
Return a string ready to be output into an HTML attribute (alt, title, data-html, ....
dol_escape_all($stringtoescape)
Returns text escaped for all protocols (so only alpha chars and numbers)
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a 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)