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