dolibarr 21.0.0-alpha
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(); // Tableau de "libelle de lots"
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 field
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 $reg = array();
198 if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) {
199 $modulename = $reg[1];
200
201 // Defined if module is enabled
202 $enabled = true;
203 $part = strtolower(preg_replace('/^mod/i', '', $modulename));
204 if ($part == 'propale') {
205 $part = 'propal';
206 }
207 if (empty($conf->$part->enabled)) {
208 $enabled = false;
209 }
210
211 if ($enabled) {
212 // Loading Class
213 $file = $dir.$modulename.".class.php";
214 $classname = $modulename;
215 require_once $file;
216 $module = new $classname($this->db);
217 '@phan-var-force DolibarrModules $module';
218
219 if (isset($module->export_code) && is_array($module->export_code)) {
220 foreach ($module->export_code as $r => $value) {
221 //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).'<br>';
222 if ($filter && ($filter != $module->export_code[$r])) {
223 continue;
224 }
225
226 // Test if condition to show are ok
227 if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) {
228 continue;
229 }
230
231 // Test if permissions are ok
232 $bool = true;
233 if (isset($module->export_permission)) {
234 foreach ($module->export_permission[$r] as $val) {
235 $perm = $val;
236 //print_r("$perm[0]-$perm[1]-$perm[2]<br>");
237 if (!empty($perm[2])) {
238 $bool = isset($user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]}) ? $user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]} : false;
239 } elseif (!empty($perm[1])) {
240 $bool = isset($user->rights->{$perm[0]}->{$perm[1]}) ? $user->rights->{$perm[0]}->{$perm[1]} : false;
241 } else {
242 $bool = false;
243 }
244 if ($perm[0] == 'user' && $user->admin) {
245 $bool = true;
246 }
247 if (!$bool) {
248 break;
249 }
250 }
251 }
252 //print $bool." $perm[0]"."<br>";
253
254 // Permissions ok
255 // if ($bool)
256 // {
257 // Charge fichier lang en rapport
258 $langtoload = $module->getLangFilesArray();
259 if (is_array($langtoload)) {
260 foreach ($langtoload as $key) {
261 $langs->load($key);
262 }
263 }
264
265
266 // Module
267 $this->array_export_module[$i] = $module;
268 // Permission
269 $this->array_export_perms[$i] = $bool;
270 // Icon
271 $this->array_export_icon[$i] = (isset($module->export_icon[$r]) ? $module->export_icon[$r] : $module->picto);
272 // Code of the export dataset / Code du dataset export
273 $this->array_export_code[$i] = $module->export_code[$r];
274 // Define a key for sort
275 $this->array_export_code_for_sort[$i] = $module->module_position.'_'.$module->export_code[$r]; // Add a key into the module
276 // Export Dataset Label / Libelle du dataset export
277 $this->array_export_label[$i] = $module->getExportDatasetLabel($r);
278 // Table of fields to export / Tableau des champ a exporter (cle=champ, valeur=libelle)
279 $this->array_export_fields[$i] = $module->export_fields_array[$r];
280 // Table of fields to be filtered (key=field, value1=data type) Verifies that the module has filters
281 $this->array_export_TypeFields[$i] = (isset($module->export_TypeFields_array[$r]) ? $module->export_TypeFields_array[$r] : '');
282 // Table of entities to export (key=field, value=entity)
283 $this->array_export_entities[$i] = $module->export_entities_array[$r];
284 // Table of entities requiring to abandon DISTINCT (key=entity, valeur=field id child records)
285 $this->array_export_dependencies[$i] = (!empty($module->export_dependencies_array[$r]) ? $module->export_dependencies_array[$r] : '');
286 // Table of special field operations / Tableau des operations speciales sur champ
287 $this->array_export_special[$i] = (!empty($module->export_special_array[$r]) ? $module->export_special_array[$r] : '');
288 // Array of examples
289 $this->array_export_examplevalues[$i] = (!empty($module->export_examplevalues_array[$r]) ? $module->export_examplevalues_array[$r] : null);
290 // Array of help tooltips
291 $this->array_export_help[$i] = (!empty($module->export_help_array[$r]) ? $module->export_help_array[$r] : '');
292
293 // SQL dataset query / Requete SQL du dataset
294 $this->array_export_sql_start[$i] = $module->export_sql_start[$r];
295 $this->array_export_sql_end[$i] = $module->export_sql_end[$r];
296 $this->array_export_sql_order[$i] = (!empty($module->export_sql_order[$r]) ? $module->export_sql_order[$r] : null);
297 //$this->array_export_sql[$i]=$module->export_sql[$r];
298
299 // @phan-suppress-next-line PhanUndeclaredProperty
300 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]) : ''));
301 $i++;
302 // }
303 }
304 }
305 }
306 }
307 }
308 closedir($handle);
309 }
310 }
311
312 return 1;
313 }
314
315
316 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
326 public function build_sql($indice, $array_selected, $array_filterValue)
327 {
328 // phpcs:enable
329 // Build the sql request
330 $sql = $this->array_export_sql_start[$indice];
331 $i = 0;
332
333 //print_r($array_selected);
334 foreach ($this->array_export_fields[$indice] as $key => $value) {
335 if (!array_key_exists($key, $array_selected)) {
336 continue; // Field not selected
337 }
338 if (preg_match('/^none\./', $key)) {
339 continue; // A field that must not appears into SQL
340 }
341 if ($i > 0) {
342 $sql .= ', ';
343 } else {
344 $i++;
345 }
346
347 if (strpos($key, ' as ') === false) {
348 $newfield = $key.' as '.str_replace(array('.', '-', '(', ')'), '_', $key);
349 } else {
350 $newfield = $key;
351 }
352
353 $sql .= $newfield;
354 }
355 $sql .= $this->array_export_sql_end[$indice];
356
357 // Add the WHERE part. Filtering into sql if a filtering array is provided
358 if (is_array($array_filterValue) && !empty($array_filterValue)) {
359 $sqlWhere = '';
360 // Loop on each condition to add
361 foreach ($array_filterValue as $key => $value) {
362 if (preg_match('/GROUP_CONCAT/i', $key)) {
363 continue;
364 }
365 if ($value != '') {
366 $sqlWhere .= " AND ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
367 }
368 }
369 $sql .= $sqlWhere;
370 }
371
372 // Add the sort order
373 $sql .= $this->array_export_sql_order[$indice];
374
375 // Add the HAVING part.
376 if (is_array($array_filterValue) && !empty($array_filterValue)) {
377 // Loop on each condition to add
378 foreach ($array_filterValue as $key => $value) {
379 if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') {
380 $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
381 }
382 }
383 }
384
385 return $sql;
386 }
387
388 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
397 public function build_filterQuery($TypeField, $NameField, $ValueField)
398 {
399 // phpcs:enable
400 $NameField = sanitizeVal($NameField, 'aZ09');
401 $szFilterQuery = '';
402
403 //print $TypeField." ".$NameField." ".$ValueField;
404 $InfoFieldList = explode(":", $TypeField);
405 // build the input field on depend of the type of file
406 switch ($InfoFieldList[0]) {
407 case 'Text':
408 if (!(strpos($ValueField, '%') === false)) {
409 $szFilterQuery = " ".$NameField." LIKE '".$this->db->escape($ValueField)."'";
410 } else {
411 $szFilterQuery = " ".$NameField." = '".$this->db->escape($ValueField)."'";
412 }
413 break;
414 case 'Date':
415 if (strpos($ValueField, "+") > 0) {
416 // mode plage
417 $ValueArray = explode("+", $ValueField);
418 $szFilterQuery = "(".$this->conditionDate($NameField, trim($ValueArray[0]), ">=");
419 $szFilterQuery .= " AND ".$this->conditionDate($NameField, trim($ValueArray[1]), "<=").")";
420 } else {
421 if (is_numeric(substr($ValueField, 0, 1))) {
422 $szFilterQuery = $this->conditionDate($NameField, trim($ValueField), "=");
423 } else {
424 $szFilterQuery = $this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1));
425 }
426 }
427 break;
428 case 'Duree':
429 break;
430 case 'Numeric':
431 // if there is a signe +
432 if (strpos($ValueField, "+") > 0) {
433 // mode plage
434 $ValueArray = explode("+", $ValueField);
435 $szFilterQuery = "(".$NameField." >= ".((float) $ValueArray[0]);
436 $szFilterQuery .= " AND ".$NameField." <= ".((float) $ValueArray[1]).")";
437 } else {
438 if (is_numeric(substr($ValueField, 0, 1))) {
439 $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
440 } else {
441 $szFilterQuery = " ".$NameField.substr($ValueField, 0, 1).((float) substr($ValueField, 1));
442 }
443 }
444 break;
445 case 'Boolean':
446 $szFilterQuery = " ".$NameField."=".(is_numeric($ValueField) ? $ValueField : ($ValueField == 'yes' ? 1 : 0));
447 break;
448 case 'FormSelect':
449 if (is_numeric($ValueField) && $ValueField > 0) {
450 $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
451 } else {
452 $szFilterQuery = " 1=1"; // Test always true
453 }
454 break;
455 case 'Status':
456 case 'List':
457 if (is_numeric($ValueField)) {
458 $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
459 } else {
460 if (!(strpos($ValueField, '%') === false)) {
461 $szFilterQuery = " ".$NameField." LIKE '".$this->db->escape($ValueField)."'";
462 } else {
463 $szFilterQuery = " ".$NameField." = '".$this->db->escape($ValueField)."'";
464 }
465 }
466 break;
467 default:
468 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);
469 }
470
471 return $szFilterQuery;
472 }
473
482 public function conditionDate($Field, $Value, $Sens)
483 {
484 // TODO date_format is forbidden, not performant and not portable. Use instead $Value to forge the range date.
485 if (strlen($Value) == 4) {
486 $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$this->db->escape($Value)."'";
487 } elseif (strlen($Value) == 6) {
488 $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$this->db->escape($Value)."'";
489 } else {
490 $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." '".$this->db->escape($Value)."'";
491 }
492 return $Condition;
493 }
494
495 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
504 public function build_filterField($TypeField, $NameField, $ValueField)
505 {
506 // phpcs:enable
507 global $conf, $langs, $form;
508
509 $szFilterField = '';
510 $InfoFieldList = explode(":", $TypeField);
511
512 // build the input field on depend of the type of file
513 switch ($InfoFieldList[0]) {
514 case 'Text':
515 case 'Date':
516 $szFilterField = '<input type="text" name="'.$NameField.'" value="'.$ValueField.'">';
517 break;
518 case 'Duree':
519 case 'Numeric':
520 case 'Number':
521 // Must be a string text to allow to use comparison strings like "<= 99.9"
522 $szFilterField = '<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
523 break;
524 case 'Status':
525 $szFilterField = '<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
526 break;
527 case 'Boolean':
528 $szFilterField = '<select name="'.$NameField.'" class="flat">';
529 $szFilterField .= '<option ';
530 if ($ValueField == '') {
531 $szFilterField .= ' selected ';
532 }
533 $szFilterField .= ' value="">&nbsp;</option>';
534
535 $szFilterField .= '<option ';
536 if ($ValueField == 'yes' || $ValueField == '1') {
537 $szFilterField .= ' selected ';
538 }
539 $szFilterField .= ' value="1">'.yn(1).'</option>';
540
541 $szFilterField .= '<option ';
542 if ($ValueField == 'no' || $ValueField == '0') {
543 $szFilterField .= ' selected ';
544 }
545 $szFilterField .= ' value="0">'.yn(0).'</option>';
546 $szFilterField .= "</select>";
547 break;
548 case 'FormSelect':
549 //var_dump($NameField);
550 if ($InfoFieldList[1] == 'select_company') {
551 $szFilterField .= $form->select_company('', $NameField, '', 1, 0, 0, [], 0, 'maxwidth200');
552 } elseif ($InfoFieldList[1] == 'selectcontacts') {
553 //$szFilterField .= $form->selectcontacts(0, '', $NameField, '&nbsp;', '', '', 0, 'maxwidth200');
554 $szFilterField .= $form->select_contact(0, '', $NameField, '&nbsp;', '', '', 0, 'minwidth100imp maxwidth200', true);
555 } elseif ($InfoFieldList[1] == 'select_dolusers') {
556 $szFilterField .= $form->select_dolusers('', $NameField, 1, null, 0, '', '', '', 0, 0, "", 0, "", "maxwidth200");
557 }
558 break;
559 case 'List':
560 // 0 : Type of the field / Type du champ
561 // 1 : Name of the table / Nom de la table
562 // 2 : Name of the field containing the label / Nom du champ contenant le libelle
563 // 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list.
564 // 4 : Name of element for getEntity().
565
566 if (!empty($InfoFieldList[3])) {
567 $keyList = $InfoFieldList[3];
568 } else {
569 $keyList = 'rowid';
570 }
571 $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3]." as code");
572 if ($InfoFieldList[1] == 'c_stcomm') {
573 $sql = "SELECT id as id, ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3].' as code');
574 }
575 if ($InfoFieldList[1] == 'c_country') {
576 $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label, code as code";
577 }
578 $sql .= " FROM ".MAIN_DB_PREFIX.$InfoFieldList[1];
579 if (!empty($InfoFieldList[4])) {
580 $sql .= ' WHERE entity IN ('.getEntity($InfoFieldList[4]).')';
581 }
582
583 $resql = $this->db->query($sql);
584 if ($resql) {
585 $szFilterField = '<select class="flat" name="'.$NameField.'">';
586 $szFilterField .= '<option value="0">&nbsp;</option>';
587 $num = $this->db->num_rows($resql);
588
589 $i = 0;
590 if ($num) {
591 while ($i < $num) {
592 $obj = $this->db->fetch_object($resql);
593 if ($obj->label == '-') {
594 // Discard entry '-'
595 $i++;
596 continue;
597 }
598 //var_dump($InfoFieldList[1]);
599 $labeltoshow = dol_trunc($obj->label, 18);
600 if ($InfoFieldList[1] == 'c_stcomm') {
601 $langs->load("companies");
602 $labeltoshow = (($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id) ? $langs->trans("StatusProspect".$obj->id) : $obj->label);
603 }
604 if ($InfoFieldList[1] == 'c_country') {
605 //var_dump($sql);
606 $langs->load("dict");
607 $labeltoshow = (($langs->trans("Country".$obj->code) != "Country".$obj->code) ? $langs->trans("Country".$obj->code) : $obj->label);
608 }
609 if (!empty($ValueField) && $ValueField == $obj->rowid) {
610 $szFilterField .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
611 } else {
612 $szFilterField .= '<option value="'.$obj->rowid.'" >'.$labeltoshow.'</option>';
613 }
614 $i++;
615 }
616 }
617 $szFilterField .= "</select>";
618
619 $this->db->free($resql);
620 } else {
621 dol_print_error($this->db);
622 }
623 break;
624 }
625
626 return $szFilterField;
627 }
628
635 public function genDocFilter($TypeField)
636 {
637 global $langs;
638
639 $szMsg = '';
640 $InfoFieldList = explode(":", $TypeField);
641 // build the input field on depend of the type of file
642 switch ($InfoFieldList[0]) {
643 case 'Text':
644 $szMsg = $langs->trans('ExportStringFilter');
645 break;
646 case 'Date':
647 $szMsg = $langs->trans('ExportDateFilter');
648 break;
649 case 'Duree':
650 break;
651 case 'Numeric':
652 $szMsg = $langs->trans('ExportNumericFilter');
653 break;
654 case 'Boolean':
655 break;
656 case 'List':
657 break;
658 }
659 return $szMsg;
660 }
661
662 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
677 public function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '', $separator = '')
678 {
679 // phpcs:enable
680 global $conf, $langs, $mysoc;
681
682 $indice = 0;
683 asort($array_selected);
684
685 dol_syslog(__METHOD__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected));
686
687 // Check parameters or context properties
688 if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) {
689 $this->error = "ErrorBadParameter";
690 dol_syslog($this->error, LOG_ERR);
691 return -1;
692 }
693
694 // Creation of class to export using model ExportXXX
695 $dir = DOL_DOCUMENT_ROOT."/core/modules/export/";
696 $file = "export_".$model.".modules.php";
697 $classname = "Export".$model;
698 require_once $dir.$file;
699 $objmodel = new $classname($this->db);
700 '@phan-var-force ModeleExports $objmodel';
701
702 if (in_array($model, array('csvutf8', 'csviso')) && !empty($separator) && property_exists($objmodel, 'separator')) {
703 // @phan-suppress-next-line PhanUndeclaredProperty
704 $objmodel->separator = $separator;
705 }
706
707 if (!empty($sqlquery)) {
708 $sql = $sqlquery;
709 } else {
710 // Define value for indice from $datatoexport
711 $foundindice = 0;
712 foreach ($this->array_export_code as $key => $dataset) {
713 if ($datatoexport == $dataset) {
714 $indice = $key;
715 $foundindice++;
716 //print "Found indice = ".$indice." for dataset=".$datatoexport."\n";
717 break;
718 }
719 }
720 if (empty($foundindice)) {
721 $this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
722 return -1;
723 }
724 $sql = $this->build_sql($indice, $array_selected, $array_filterValue);
725 }
726
727 // Run the SQL
728 $this->sqlusedforexport = $sql;
729 dol_syslog(__METHOD__, LOG_DEBUG);
730 $resql = $this->db->query($sql);
731 if ($resql) {
732 //$this->array_export_label[$indice]
733 if (getDolGlobalString('EXPORT_PREFIX_SPEC')) {
734 $filename = getDolGlobalString('EXPORT_PREFIX_SPEC') . "_".$datatoexport;
735 } else {
736 $filename = "export_".$datatoexport;
737 }
738 if (getDolGlobalString('EXPORT_NAME_WITH_DT')) {
739 $filename .= dol_print_date(dol_now(), '%Y%m%d%_%H%M');
740 }
741 $filename .= '.'.$objmodel->getDriverExtension();
742 $dirname = $conf->export->dir_temp.'/'.$user->id;
743
744 $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
745
746 // Open file
747 dol_mkdir($dirname);
748 $result = $objmodel->open_file($dirname."/".$filename, $outputlangs);
749
750 if ($result >= 0) {
751 // Generate header
752 $objmodel->write_header($outputlangs);
753
754 // Generate title line
755 $objmodel->write_title($this->array_export_fields[$indice], $array_selected, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
756
757 while ($obj = $this->db->fetch_object($resql)) {
758 // Process special operations
759 if (!empty($this->array_export_special[$indice])) {
760 foreach ($this->array_export_special[$indice] as $key => $value) {
761 if (!array_key_exists($key, $array_selected)) {
762 continue; // Field not selected
763 }
764
765 // TODO: Not sure why the original was not using $value directly.
766 $item = $this->array_export_special[$indice][$key];
767 // Operation NULLIFNEG
768 if (is_string($item) && $item == 'NULLIFNEG') { // @phan-suppress-current-line PhanTypeComparisonFromArray
769 //$alias=$this->array_export_alias[$indice][$key];
770 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
771 if ($obj->$alias < 0) {
772 $obj->$alias = '';
773 }
774 } elseif (is_string($item) && $item == 'ZEROIFNEG') {
775 // Operation ZEROIFNEG
776 //$alias=$this->array_export_alias[$indice][$key];
777 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
778 if ($obj->$alias < 0) {
779 $obj->$alias = '0';
780 }
781 } elseif (is_string($item) && $item == 'getNumOpenDays') {
782 // Operation GETNUMOPENDAYS (for Holiday module)
783 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
784 //$alias=$this->array_export_alias[$indice][$key];
785 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
786 $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);
787 } elseif (is_string($item) && $item == 'getRemainToPay') {
788 // Operation INVOICEREMAINTOPAY
789 //$alias=$this->array_export_alias[$indice][$key];
790 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
791 $remaintopay = '';
792 if ($obj->f_rowid > 0) {
793 global $tmpobjforcomputecall;
794 if (!is_object($tmpobjforcomputecall)) {
795 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
796 $tmpobjforcomputecall = new Facture($this->db);
797 }
798 $tmpobjforcomputecall->id = $obj->f_rowid;
799 $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
800 $tmpobjforcomputecall->close_code = $obj->f_close_code;
801 $remaintopay = $tmpobjforcomputecall->getRemainToPay();
802 }
803 $obj->$alias = $remaintopay;
804 } elseif (is_array($item) &&
805 array_key_exists('rule', $item) &&
806 $item['rule'] == 'compute'
807 ) {
808 // Custom compute
809 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
810 $value = '';
811 if (!empty($item['class']) &&
812 !empty($item['classfile']) &&
813 !empty($item['method'])
814 ) {
815 if (!dol_include_once($item['classfile'])) {
816 $this->error = "Computed field bad configuration: {$item['classfile']} not found";
817 return -1;
818 }
819
820 if (!class_exists($item['class'])) {
821 $this->error = "Computed field bad configuration: {$item['class']} class doesn't exist";
822 return -1;
823 }
824
825 $className = $item['class'];
826 $tmpObject = new $className($this->db);
827 '@phan-var-force CommonObject $tmpObject';
828
829 if (!method_exists($tmpObject, $item['method'])) {
830 $this->error = "Computed field bad configuration: {$item['method']} method doesn't exist";
831 return -1;
832 }
833
834 $methodName = $item['method'];
835 $params = [];
836 if (!empty($item['method_params'])) {
837 foreach ($item['method_params'] as $paramName) {
838 $params[] = $obj->$paramName ?? null;
839 }
840 }
841 $value = $tmpObject->$methodName(...$params);
842 }
843 $obj->$alias = $value;
844 } else {
845 // TODO FIXME
846 // Export of compute field does not work. $obj contains $obj->alias_field and formula may contains $obj->field
847 // Also the formula may contains objects of class that are not loaded.
848 $computestring = is_string($item) ? $item : json_encode($item);
849 //$tmp = (string) dol_eval($computestring, 1, 0, '2');
850 //$obj->$alias = $tmp;
851
852 $this->error = "ERROPNOTSUPPORTED. Operation ".$computestring." not supported. Export of 'computed' extrafields is not yet supported, please remove field.";
853 return -1;
854 }
855 }
856 }
857 // end of special operation processing
858 $objmodel->write_record($array_selected, $obj, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
859 }
860
861 // Generate Footer
862 $objmodel->write_footer($outputlangs);
863
864 // Close file
865 $objmodel->close_file();
866
867 return 1;
868 } else {
869 $this->error = $objmodel->error;
870 dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
871 return -1;
872 }
873 } else {
874 $this->error = $this->db->error()." - sql=".$sql;
875 return -1;
876 }
877 }
878
885 public function create($user)
886 {
887 dol_syslog("Export.class.php::create");
888
889 $this->db->begin();
890
891 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'export_model (';
892 $sql .= 'label,';
893 $sql .= 'type,';
894 $sql .= 'field,';
895 $sql .= 'fk_user,';
896 $sql .= 'filter';
897 $sql .= ') VALUES (';
898 $sql .= "'".$this->db->escape($this->model_name)."',";
899 $sql .= " '".$this->db->escape($this->datatoexport)."',";
900 $sql .= " '".$this->db->escape($this->hexa)."',";
901 $sql .= ' '.(isset($this->fk_user) ? (int) $this->fk_user : 'null').",";
902 $sql .= " '".$this->db->escape($this->hexafiltervalue)."'";
903 $sql .= ")";
904
905 $resql = $this->db->query($sql);
906 if ($resql) {
907 $this->db->commit();
908 return 1;
909 } else {
910 $this->error = $this->db->lasterror();
911 $this->errno = $this->db->lasterrno();
912 $this->db->rollback();
913 return -1;
914 }
915 }
916
923 public function fetch($id)
924 {
925 $sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter';
926 $sql .= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
927 $sql .= ' WHERE em.rowid = '.((int) $id);
928
929 dol_syslog("Export::fetch", LOG_DEBUG);
930 $result = $this->db->query($sql);
931 if ($result) {
932 $obj = $this->db->fetch_object($result);
933 if ($obj) {
934 $this->id = $obj->rowid;
935 $this->model_name = $obj->label;
936 $this->datatoexport = $obj->type;
937
938 $this->hexa = $obj->field;
939 $this->hexafiltervalue = $obj->filter;
940
941 return 1;
942 } else {
943 $this->error = "ModelNotFound";
944 return -2;
945 }
946 } else {
947 dol_print_error($this->db);
948 return -3;
949 }
950 }
951
952
960 public function delete($user, $notrigger = 0)
961 {
962 global $conf, $langs;
963 $error = 0;
964
965 $sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model";
966 $sql .= " WHERE rowid=".((int) $this->id);
967
968 $this->db->begin();
969
970 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
971 $resql = $this->db->query($sql);
972 if (!$resql) {
973 $error++;
974 $this->errors[] = "Error ".$this->db->lasterror();
975 }
976
977 // Commit or rollback
978 if ($error) {
979 foreach ($this->errors as $errmsg) {
980 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
981 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
982 }
983 $this->db->rollback();
984 return -1 * $error;
985 } else {
986 $this->db->commit();
987 return 1;
988 }
989 }
990
991 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
998 public function list_export_model()
999 {
1000 // phpcs:enable
1001 global $conf, $langs;
1002
1003 $sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter";
1004 $sql .= " FROM ".MAIN_DB_PREFIX."export_model as em";
1005 $sql .= " ORDER BY rowid";
1006
1007 $result = $this->db->query($sql);
1008 if ($result) {
1009 $num = $this->db->num_rows($result);
1010 $i = 0;
1011 while ($i < $num) {
1012 $obj = $this->db->fetch_object($result);
1013 $keyModel = array_search($obj->type, $this->array_export_code);
1014 print "<tr>";
1015 print '<td><a href=export.php?step=2&action=select_model&exportmodelid='.$obj->rowid.'&datatoexport='.$obj->type.'>'.$obj->label.'</a></td>';
1016 print '<td>';
1017 print img_object($this->array_export_module[$keyModel]->getName(), $this->array_export_icon[$keyModel]).' ';
1018 print $this->array_export_module[$keyModel]->getName().' - ';
1019 // recover export name / recuperation du nom de l'export
1020
1021 $string = $langs->trans($this->array_export_label[$keyModel]);
1022 print($string != $this->array_export_label[$keyModel] ? $string : $this->array_export_label[$keyModel]);
1023 print '</td>';
1024 //print '<td>'.$obj->type.$keyModel.'</td>';
1025 print '<td>'.str_replace(',', ' , ', $obj->field).'</td>';
1026 if (!empty($obj->filter)) {
1027 $filter = json_decode($obj->filter, true);
1028 print '<td>'.str_replace(',', ' , ', $filter['field']).'</td>';
1029 print '<td>'.str_replace(',', ' , ', $filter['value']).'</td>';
1030 }
1031 // remove export / suppression de l'export
1032 print '<td class="right">';
1033 print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteprof&token='.newToken().'&id='.$obj->rowid.'">';
1034 print img_delete();
1035 print '</a>';
1036 print "</tr>";
1037
1038 $i++;
1039 }
1040 } else {
1041 dol_print_error($this->db);
1042 }
1043 }
1044}
$id
Definition account.php:39
Class to manage exports.
fetch($id)
Load an export profil from database.
build_sql($indice, $array_selected, $array_filterValue)
Build the sql export request.
build_filterField($TypeField, $NameField, $ValueField)
Build an input field used to filter the query.
build_filterQuery($TypeField, $NameField, $ValueField)
Build the conditional string from filter the query.
conditionDate($Field, $Value, $Sens)
conditionDate
list_export_model()
Output list all export models –TODO Move this into a class htmlxxx.class.php–.
create($user)
Save an export model in database.
__construct($db)
Constructor.
load_arrays($user, $filter='')
Load an exportable dataset.
build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery='', $separator='')
Build export file.
genDocFilter($TypeField)
Build an input field used to filter the query.
Class to manage invoices.
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $country_code='')
Function to return number of working days (and text of units) between two dates (working days)
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:427
dolGetModulesDirs($subdir='')
Return list of directories that contain modules.
verifCond($strToEvaluate, $onlysimplestring='1')
Verify if condition in string is ok or not.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_now($mode='auto')
Return date for now.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getDolGlobalString($key, $default='')
Return 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)