dolibarr 24.0.0-beta
export.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2005-2011 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2012 Charles-Fr BENKE <charles.fr@benke.fr>
5 * Copyright (C) 2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
6 * Copyright (C) 2024-2026 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(); // Array of "idmodule_numexportprofile"
77 public $array_export_code_for_sort = array(); // Array of "idmodule_numexportprofile"
81 public $array_export_module = array(); // Array of Module Names
85 public $array_export_label = array(); // Array of "Translation key" to use for each export profile
89 public $array_export_sql_start = array(); // Array of SQL queries ("start")
93 public $array_export_sql_end = array(); // Array of SQL queries ("end")
97 public $array_export_sql_order = array(); // Array of SQL queries ("order")
98
102 public $array_export_fields = array(); // Array of lists of fields and labels to export
106 public $array_export_TypeFields = array(); // Array of lists of fields & filter types
110 public $array_export_FilterValue = array(); // Array of lists of fields & values to filter
114 public $array_export_entities = array(); // Array of lists of fields & aliases to export
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->buildFilterQuery($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->buildFilterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
388 }
389 }
390 }
391
392 return $sql;
393 }
394
404 public function buildFilterQuery($TypeField, $NameField, $ValueField)
405 {
406 $NameField = sanitizeVal($NameField, 'aZ09');
407 $szFilterQuery = '';
408
409 //print $TypeField." ".$NameField." ".$ValueField;
410 $InfoFieldList = explode(":", $TypeField);
411 // build the input field on depend of the type of file
412 switch ($InfoFieldList[0]) {
413 case 'Text':
414 if (!(strpos($ValueField, '%') === false)) {
415 $szFilterQuery = " ".$this->db->sanitize($NameField)." LIKE '".$this->db->escape($ValueField)."'";
416 } else {
417 $szFilterQuery = " ".$this->db->sanitize($NameField)." = '".$this->db->escape($ValueField)."'";
418 }
419 break;
420 case 'Date':
421 if (strpos($ValueField, "+") > 0) {
422 // mode plage
423 $ValueArray = explode("+", $ValueField);
424 $szFilterQuery = "(".$this->conditionDate($NameField, trim($ValueArray[0]), ">=");
425 $szFilterQuery .= " AND ".$this->conditionDate($NameField, trim($ValueArray[1]), "<=").")";
426 } else {
427 if (is_numeric(substr($ValueField, 0, 1))) {
428 $szFilterQuery = $this->conditionDate($NameField, trim($ValueField), "=");
429 } else {
430 $szFilterQuery = $this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1));
431 }
432 }
433 break;
434 case 'Duree':
435 case 'Numeric':
436 // if there is a sign +
437 if (strpos($ValueField, "+") > 0) {
438 // mode range
439 $ValueArray = explode("+", $ValueField);
440 $szFilterQuery = "(".$this->db->sanitize($NameField)." >= ".((float) $ValueArray[0]);
441 $szFilterQuery .= " AND ".$this->db->sanitize($NameField)." <= ".((float) $ValueArray[1]).")";
442 } else {
443 if (is_numeric(substr($ValueField, 0, 1))) {
444 $szFilterQuery = " ".$this->db->sanitize($NameField)." = ".((float) $ValueField);
445 } else { // Example '<100' o' < 100'
446 $szFilterQuery = " ".$this->db->sanitize($NameField).substr($ValueField, 0, 1).((float) substr($ValueField, 1));
447 }
448 }
449 break;
450 case 'Boolean':
451 $szFilterQuery = " ".$this->db->sanitize($NameField)." = ".(is_numeric($ValueField) ? $ValueField : ($ValueField == 'yes' ? 1 : 0));
452 break;
453 case 'FormSelect':
454 if (is_numeric($ValueField) && $ValueField > 0) {
455 $szFilterQuery = " ".$this->db->sanitize($NameField)." = ".((float) $ValueField);
456 } else {
457 $szFilterQuery = " 1=1"; // Test always true
458 }
459 break;
460 case 'Status':
461 case 'List':
462 if (is_numeric($ValueField)) {
463 $szFilterQuery = " ".$this->db->sanitize($NameField)." = ".((float) $ValueField);
464 } else {
465 if (!(strpos($ValueField, '%') === false)) {
466 $szFilterQuery = " ".$this->db->sanitize($NameField)." LIKE '".$this->db->escape($ValueField)."'";
467 } else {
468 $szFilterQuery = " ".$this->db->sanitize($NameField)." = '".$this->db->escape($ValueField)."'";
469 }
470 }
471 break;
472 default:
473 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);
474 }
475
476 return $szFilterQuery;
477 }
478
487 public function conditionDate($Field, $Value, $Sens)
488 {
489 // TODO date_format is forbidden, not performant and not portable. Use instead $Value to forge the range date.
490 if (strlen($Value) == 4) {
491 $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$this->db->escape($Value)."'";
492 } elseif (strlen($Value) == 6) {
493 $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$this->db->escape($Value)."'";
494 } else {
495 $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." '".$this->db->escape($Value)."'";
496 }
497 return $Condition;
498 }
499
500 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
509 public function build_filterField($TypeField, $NameField, $ValueField)
510 {
511 // phpcs:enable
512 global $langs, $form;
513
514 $szFilterField = '';
515 $InfoFieldList = explode(":", $TypeField);
516
517 // build the input field on depend of the type of file
518 switch ($InfoFieldList[0]) {
519 case 'Text':
520 case 'Date':
521 $szFilterField = '<input type="text" name="'.$NameField.'" value="'.$ValueField.'">';
522 break;
523 case 'Duree':
524 case 'Numeric':
525 case 'Number':
526 // Must be a string text to allow to use comparison strings like "<= 99.9"
527 $szFilterField = '<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
528 break;
529 case 'Status':
530 $szFilterField = '<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
531 break;
532 case 'Boolean':
533 $szFilterField = '<select name="'.$NameField.'" id="'.dol_escape_all($NameField).'" class="flat width75 maxwidth75">';
534 $szFilterField .= '<option ';
535 if ($ValueField == '') {
536 $szFilterField .= ' selected ';
537 }
538 $szFilterField .= ' value="">&nbsp;</option>';
539
540 $szFilterField .= '<option ';
541 if ($ValueField == 'yes' || $ValueField == '1') {
542 $szFilterField .= ' selected ';
543 }
544 $szFilterField .= ' value="1">'.yn(1).'</option>';
545
546 $szFilterField .= '<option ';
547 if ($ValueField == 'no' || $ValueField == '0') {
548 $szFilterField .= ' selected ';
549 }
550 $szFilterField .= ' value="0">'.yn(0).'</option>';
551 $szFilterField .= "</select>";
552 $szFilterField .= ajax_combobox(dol_escape_all($NameField));
553 break;
554 case 'FormSelect':
555 //var_dump($NameField);
556 if ($InfoFieldList[1] == 'select_company') {
557 $szFilterField .= $form->select_company('', $NameField, '', 1, 0, 0, [], 0, 'maxwidth200');
558 } elseif ($InfoFieldList[1] == 'selectcontacts') {
559 //$szFilterField .= $form->selectcontacts(0, '', $NameField, '&nbsp;', '', '', 0, 'maxwidth200');
560 $szFilterField .= $form->select_contact(0, '', $NameField, '&nbsp;', '', '', 0, 'minwidth100imp maxwidth200', true);
561 } elseif ($InfoFieldList[1] == 'select_dolusers') {
562 $szFilterField .= $form->select_dolusers('', $NameField, 1, null, 0, '', '', '', 0, 0, "", 0, "", "maxwidth200");
563 }
564 break;
565 case 'List':
566 // 0 : Type of the field / Type du champ
567 // 1 : Name of the table / Nom de la table
568 // 2 : Name of the field containing the label / Nom du champ contenant le libelle
569 // 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list.
570 // 4 : Name of element for getEntity().
571
572 if (!empty($InfoFieldList[3])) {
573 $keyList = $InfoFieldList[3];
574 } else {
575 $keyList = 'rowid';
576 }
577 $sql = "SELECT ".$this->db->sanitize($keyList)." as rowid, ".$this->db->sanitize($InfoFieldList[2])." as label".(empty($InfoFieldList[3]) ? "" : ", ".$this->db->sanitize($InfoFieldList[3])." as code");
578 if ($InfoFieldList[1] == 'c_stcomm') {
579 $sql = "SELECT id as id, ".$this->db->sanitize($keyList)." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$this->db->sanitize($InfoFieldList[3]).' as code');
580 }
581 if ($InfoFieldList[1] == 'c_country') {
582 $sql = "SELECT ".$this->db->sanitize($keyList)." as rowid, ".$this->db->sanitize($InfoFieldList[2])." as label, code as code";
583 }
584 $sql .= " FROM ".MAIN_DB_PREFIX.$this->db->sanitize($InfoFieldList[1]);
585 if (!empty($InfoFieldList[4])) {
586 $sql .= ' WHERE entity IN ('.getEntity($InfoFieldList[4]).')';
587 }
588
589 $resql = $this->db->query($sql);
590 if ($resql) {
591 $szFilterField = '<select class="minwidth300 maxwidth500" name="'.$NameField.'" id="'.dol_escape_all($NameField).'">';
592 $szFilterField .= '<option value="0">&nbsp;</option>';
593 $num = $this->db->num_rows($resql);
594
595 $i = 0;
596 if ($num) {
597 while ($i < $num) {
598 $obj = $this->db->fetch_object($resql);
599 if ($obj->label == '-') {
600 // Discard entry '-'
601 $i++;
602 continue;
603 }
604 //var_dump($InfoFieldList[1]);
605 $labeltoshow = $obj->label;
606 if ($InfoFieldList[1] == 'c_stcomm') {
607 $langs->load("companies");
608 $labeltoshow = (($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id) ? $langs->trans("StatusProspect".$obj->id) : $obj->label);
609 }
610 if ($InfoFieldList[1] == 'c_country') {
611 //var_dump($sql);
612 $langs->load("dict");
613 $labeltoshow = (($langs->trans("Country".$obj->code) != "Country".$obj->code) ? $langs->trans("Country".$obj->code) : $obj->label);
614 }
615 if (!empty($ValueField) && $ValueField == $obj->rowid) {
616 $szFilterField .= '<option value="'.$obj->rowid.'" selected data-html="'.dolPrintHTMLForAttribute($labeltoshow).'">'.dolPrintHTML($labeltoshow).'</option>';
617 } else {
618 $szFilterField .= '<option value="'.$obj->rowid.'" data-html="'.dolPrintHTMLForAttribute($labeltoshow).'">'.$labeltoshow.'</option>';
619 }
620 $i++;
621 }
622 }
623 $szFilterField .= "</select>";
624 $szFilterField .= ajax_combobox(dol_escape_all($NameField));
625
626 $this->db->free($resql);
627 } else {
628 dol_print_error($this->db);
629 }
630 break;
631 }
632
633 return $szFilterField;
634 }
635
642 public function genDocFilter($TypeField)
643 {
644 global $langs;
645
646 $szMsg = '';
647 $InfoFieldList = explode(":", $TypeField);
648 // build the input field on depend of the type of file
649 switch ($InfoFieldList[0]) {
650 case 'Text':
651 $szMsg = $langs->trans('ExportStringFilter');
652 break;
653 case 'Date':
654 $szMsg = $langs->trans('ExportDateFilter');
655 break;
656 case 'Duree':
657 case 'Numeric':
658 $szMsg = $langs->trans('ExportNumericFilter');
659 break;
660 case 'Boolean':
661 break;
662 case 'List':
663 break;
664 }
665 return $szMsg;
666 }
667
668 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
683 public function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '', $separator = '')
684 {
685 // phpcs:enable
686 global $conf, $langs, $mysoc;
687
688 $indice = 0;
689 asort($array_selected);
690
691 dol_syslog(__METHOD__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected));
692
693 // Check parameters or context properties
694 if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) {
695 $this->error = "ErrorBadParameter";
696 dol_syslog($this->error, LOG_ERR);
697 return -1;
698 }
699
700 // Creation of class to export using model ExportXXX
701 $dir = DOL_DOCUMENT_ROOT."/core/modules/export/";
702 $file = "export_".$model.".modules.php";
703 $classname = "Export".$model;
704 require_once $dir.$file;
705 $objmodel = new $classname($this->db);
707 '@phan-var-force ModeleExports $objmodel';
708
709 if (in_array($model, array('csvutf8', 'csviso')) && !empty($separator) && empty($objmodel->separator)) {
710 $objmodel->separator = $separator;
711 }
712
713 if (!empty($sqlquery)) {
714 $sql = $sqlquery;
715 } else {
716 // Define value for indice from $datatoexport
717 $foundindice = 0;
718 foreach ($this->array_export_code as $key => $dataset) {
719 if ($datatoexport == $dataset) {
720 $indice = $key;
721 $foundindice++;
722 //print "Found indice = ".$indice." for dataset=".$datatoexport."\n";
723 break;
724 }
725 }
726 if (empty($foundindice)) {
727 $this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
728 return -1;
729 }
730 $sql = $this->build_sql($indice, $array_selected, $array_filterValue);
731 }
732
733 // Run the SQL
734 $this->sqlusedforexport = $sql;
735 dol_syslog(__METHOD__, LOG_DEBUG);
736 $resql = $this->db->query($sql);
737 if ($resql) {
738 //$this->array_export_label[$indice]
739 if (getDolGlobalString('EXPORT_PREFIX_SPEC')) {
740 $filename = getDolGlobalString('EXPORT_PREFIX_SPEC') . "_".$datatoexport;
741 } else {
742 $filename = "export_".$datatoexport;
743 }
744 if (getDolGlobalString('EXPORT_NAME_WITH_DT')) {
745 $filename .= dol_print_date(dol_now(), '%Y%m%d%_%H%M');
746 }
747 $filename .= '.'.$objmodel->getDriverExtension();
748 $dirname = $conf->export->dir_temp.'/'.$user->id;
749
750 $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
751
752 // Open file
753 dol_mkdir($dirname);
754 $result = $objmodel->open_file($dirname."/".$filename, $outputlangs);
755
756 if ($result >= 0) {
757 // Generate header
758 $objmodel->write_header($outputlangs);
759
760 // Generate title line
761 $objmodel->write_title($this->array_export_fields[$indice], $array_selected, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
762
763 //$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
764 $counterlineexported = 0;
765 while ($obj = $this->db->fetch_object($resql)) {
766 $counterlineexported++;
767 /*if ($MAXFORTEST && $counterlineexported >= $MAXFORTEST) {
768 break;
769 }*/
770
771 // Process special operations
772 if (!empty($this->array_export_special[$indice])) {
773 foreach ($this->array_export_special[$indice] as $key => $value) {
774 if (!array_key_exists($key, $array_selected)) {
775 continue; // Field not selected
776 }
777
778 // TODO: Not sure why the original was not using $value directly.
779 $item = $this->array_export_special[$indice][$key];
780 // Operation NULLIFNEG
781 if (is_string($item) && $item == 'NULLIFNEG') { // @phan-suppress-current-line PhanTypeComparisonFromArray
782 //$alias=$this->array_export_alias[$indice][$key];
783 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
784 if ($obj->$alias < 0) {
785 $obj->$alias = '';
786 }
787 } elseif (is_string($item) && $item == 'ZEROIFNEG') {
788 // Operation ZEROIFNEG
789 //$alias=$this->array_export_alias[$indice][$key];
790 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
791 if ($obj->$alias < 0) {
792 $obj->$alias = '0';
793 }
794 } elseif (is_string($item) && $item == 'getNumOpenDays') {
795 // Operation GETNUMOPENDAYS (for Holiday module)
796 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
797
798 //$alias=$this->array_export_alias[$indice][$key];
799 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
800 $country_id = $mysoc->country_id;
801 if ($obj->u_fk_country > 0) { // When special field getNumOpenDays is set, we must have a u.fk_country in field list.
802 $country_id = $obj->u_fk_country;
803 }
804
805 $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);
806 } elseif (is_string($item) && $item == 'getRemainToPay') {
807 // Operation INVOICEREMAINTOPAY
808 //$alias=$this->array_export_alias[$indice][$key];
809 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
810 $remaintopay = '';
811 if ($obj->f_rowid > 0) {
812 global $tmpobjforcomputecall;
813 if (!is_object($tmpobjforcomputecall)) {
814 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
815 $tmpobjforcomputecall = new Facture($this->db);
816 }
817 $tmpobjforcomputecall->id = $obj->f_rowid;
818 $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
819 $tmpobjforcomputecall->close_code = $obj->f_close_code;
820 $remaintopay = $tmpobjforcomputecall->getRemainToPay();
821 }
822 $obj->$alias = $remaintopay;
823 } elseif (is_array($item) && array_key_exists('rule', $item) && $item['rule'] == 'compute') {
824 // Custom compute
825 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
826 $value = '';
827 if (!empty($item['class']) &&
828 !empty($item['classfile']) &&
829 !empty($item['method'])
830 ) {
831 if (!dol_include_once($item['classfile'])) {
832 $this->error = "Computed field bad configuration: {$item['classfile']} not found";
833 return -1;
834 }
835
836 if (!class_exists($item['class'])) {
837 $this->error = "Computed field bad configuration: {$item['class']} class doesn't exist";
838 return -1;
839 }
840
841 $className = $item['class'];
842 $tmpObject = new $className($this->db);
843 '@phan-var-force CommonObject $tmpObject';
844
845 if (!method_exists($tmpObject, $item['method'])) {
846 $this->error = "Computed field bad configuration: {$item['method']} method doesn't exist";
847 return -1;
848 }
849
850 $methodName = dol_escape_all($item['method']);
851 $params = [];
852 if (!empty($item['method_params'])) {
853 // Example used for export of "Stocks and location (warehouse) with batch" in field "Date of last movement"
854 foreach ($item['method_params'] as $paramName) {
855 if (property_exists($obj, $paramName)) {
856 $params[] = $obj->$paramName;
857 } else {
858 $params[] = $paramName;
859 }
860 }
861 }
862 //var_dump($tmpObject);var_dump($methodName);var_dump($params);exit;
863 $value = $tmpObject->$methodName(...$params);
864 }
865 $obj->$alias = $value;
866 } else {
867 // TODO FIXME
868 // Export of computed extra field does not work. $obj contains $obj->alias_field and formula may contains $obj->field
869 // Also the formula may contains objects of class that are not loaded.
870 //$computestring = is_string($item) ? $item : json_encode($item);
871 //$tmp = (string) dol_eval((string) $computestring, 1, 0, '2');
872 //$obj->$alias = $tmp;
873
874 $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.";
875 return -1;
876 }
877 }
878 }
879 // end of special operation processing
880 $objmodel->write_record($array_selected, $obj, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
881 }
882
883 // Generate Footer
884 $objmodel->write_footer($outputlangs);
885
886 // Close file
887 $objmodel->close_file();
888
889 return 1;
890 } else {
891 $this->error = $objmodel->error;
892 dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
893 return -1;
894 }
895 } else {
896 $this->error = $this->db->error()." - sql=".$sql;
897 return -1;
898 }
899 }
900
907 public function create($user)
908 {
909 dol_syslog("Export.class.php::create");
910
911 $this->db->begin();
912
913 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'export_model (';
914 $sql .= 'label,';
915 $sql .= 'type,';
916 $sql .= 'field,';
917 $sql .= 'fk_user,';
918 $sql .= 'filter';
919 $sql .= ') VALUES (';
920 $sql .= "'".$this->db->escape($this->model_name)."',";
921 $sql .= " '".$this->db->escape($this->datatoexport)."',";
922 $sql .= " '".$this->db->escape($this->hexa)."',";
923 $sql .= ' '.(isset($this->fk_user) ? (int) $this->fk_user : 'null').",";
924 $sql .= " '".$this->db->escape($this->hexafiltervalue)."'";
925 $sql .= ")";
926
927 $resql = $this->db->query($sql);
928 if ($resql) {
929 $this->db->commit();
930 return 1;
931 } else {
932 $this->error = $this->db->lasterror();
933 $this->errno = $this->db->lasterrno();
934 $this->db->rollback();
935 return -1;
936 }
937 }
938
945 public function fetch($id)
946 {
947 $sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter';
948 $sql .= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
949 $sql .= ' WHERE em.rowid = '.((int) $id);
950
951 dol_syslog("Export::fetch", LOG_DEBUG);
952 $result = $this->db->query($sql);
953 if ($result) {
954 $obj = $this->db->fetch_object($result);
955 if ($obj) {
956 $this->id = $obj->rowid;
957 $this->model_name = $obj->label;
958 $this->datatoexport = $obj->type;
959
960 $this->hexa = $obj->field;
961 $this->hexafiltervalue = $obj->filter;
962
963 return 1;
964 } else {
965 $this->error = "ModelNotFound";
966 return -2;
967 }
968 } else {
969 dol_print_error($this->db);
970 return -3;
971 }
972 }
973
974
982 public function delete($user, $notrigger = 0)
983 {
984 $error = 0;
985
986 $sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model";
987 $sql .= " WHERE rowid=".((int) $this->id);
988
989 $this->db->begin();
990
991 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
992 $resql = $this->db->query($sql);
993 if (!$resql) {
994 $error++;
995 $this->errors[] = "Error ".$this->db->lasterror();
996 }
997
998 // Commit or rollback
999 if ($error) {
1000 foreach ($this->errors as $errmsg) {
1001 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1002 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1003 }
1004 $this->db->rollback();
1005 return -1 * $error;
1006 } else {
1007 $this->db->commit();
1008 return 1;
1009 }
1010 }
1011
1012 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1019 public function list_export_model()
1020 {
1021 // phpcs:enable
1022 global $langs;
1023
1024 $sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter";
1025 $sql .= " FROM ".MAIN_DB_PREFIX."export_model as em";
1026 $sql .= " ORDER BY rowid";
1027
1028 $result = $this->db->query($sql);
1029 if ($result) {
1030 $num = $this->db->num_rows($result);
1031 $i = 0;
1032 while ($i < $num) {
1033 $obj = $this->db->fetch_object($result);
1034 $keyModel = array_search($obj->type, $this->array_export_code);
1035 print "<tr>";
1036 print '<td><a href=export.php?step=2&action=select_model&exportmodelid='.$obj->rowid.'&datatoexport='.$obj->type.'>'.$obj->label.'</a></td>';
1037 print '<td>';
1038 print img_object($this->array_export_module[$keyModel]->getName(), $this->array_export_icon[$keyModel]).' ';
1039 print $this->array_export_module[$keyModel]->getName().' - ';
1040 // Recover export name
1041
1042 $string = $langs->trans($this->array_export_label[$keyModel]);
1043 print($string != $this->array_export_label[$keyModel] ? $string : $this->array_export_label[$keyModel]);
1044 print '</td>';
1045 //print '<td>'.$obj->type.$keyModel.'</td>';
1046 print '<td>'.str_replace(',', ' , ', $obj->field).'</td>';
1047 if (!empty($obj->filter)) {
1048 $filter = json_decode($obj->filter, true);
1049 print '<td>'.str_replace(',', ' , ', $filter['field']).'</td>';
1050 print '<td>'.str_replace(',', ' , ', $filter['value']).'</td>';
1051 }
1052 // Remove export
1053 print '<td class="right">';
1054 print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteprof&token='.newToken().'&id='.$obj->rowid.'">';
1055 print img_delete();
1056 print '</a>';
1057 print "</tr>";
1058
1059 $i++;
1060 }
1061 } else {
1062 dol_print_error($this->db);
1063 }
1064 }
1065}
$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:476
Class to manage exports.
fetch($id)
Load an export profil from database.
buildFilterQuery($TypeField, $NameField, $ValueField)
Build the conditional string from filter the query.
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.
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='', $user_id=0)
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:435
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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.
dolPrintHTML($s, $allowiframe=0, $moreallowedtags=array())
Return a string (that can be on several lines) ready to be output on a HTML page.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
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.
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)