dolibarr 19.0.4
export.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2005-2011 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2012 Charles-Fr BENKE <charles.fr@benke.fr>
5 * Copyright (C) 2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
31class Export
32{
36 public $db;
37
41 public $id;
42
43 public $array_export_icon;
44
45 public $array_export_perms;
46
47
51 public $error;
55 public $errno;
59 public $errors;
60
61 public $array_export_code = array(); // Tableau de "idmodule_numexportprofile"
62 public $array_export_code_for_sort = array(); // Tableau de "idmodule_numexportprofile"
63 public $array_export_module = array(); // Tableau de "nom de modules"
64 public $array_export_label = array(); // Tableau de "libelle de lots"
65 public $array_export_sql_start = array(); // Tableau des "requetes sql"
66 public $array_export_sql_end = array(); // Tableau des "requetes sql"
67 public $array_export_sql_order = array(); // Tableau des "requetes sql"
68
69 public $array_export_fields = array(); // Tableau des listes de champ+libelle a exporter
70 public $array_export_TypeFields = array(); // Tableau des listes de champ+Type de filtre
71 public $array_export_FilterValue = array(); // Tableau des listes de champ+Valeur a filtrer
72 public $array_export_entities = array(); // Tableau des listes de champ+alias a exporter
73 public $array_export_dependencies = array(); // array of list of entities that must take care of the DISTINCT if a field is added into export
74 public $array_export_special = array(); // array of special operations to do on field
75 public $array_export_examplevalues = array(); // array with examples for fields
76 public $array_export_help = array(); // array with tooltip help for fields
77
78 // To store export templates
79 public $hexa; // List of fields in the export profile
80 public $hexafiltervalue; // List of search criteria in the export profile
81 public $datatoexport;
82 public $model_name; // Name of export profile
83 public $fk_user;
84
85 public $sqlusedforexport;
86
87
93 public function __construct($db)
94 {
95 $this->db = $db;
96 }
97
98
99 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
107 public function load_arrays($user, $filter = '')
108 {
109 // phpcs:enable
110 global $langs, $conf, $mysoc;
111
112 dol_syslog(get_class($this)."::load_arrays user=".$user->id." filter=".$filter);
113
114 $i = 0;
115
116 // Define list of modules directories into modulesdir
117 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
118
119 $modulesdir = dolGetModulesDirs();
120
121 foreach ($modulesdir as $dir) {
122 // Search available exports
123 $handle = @opendir(dol_osencode($dir));
124 if (is_resource($handle)) {
125 // Search module files
126 while (($file = readdir($handle)) !== false) {
127 $reg = array();
128 if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) {
129 $modulename = $reg[1];
130
131 // Defined if module is enabled
132 $enabled = true;
133 $part = strtolower(preg_replace('/^mod/i', '', $modulename));
134 if ($part == 'propale') {
135 $part = 'propal';
136 }
137 if (empty($conf->$part->enabled)) {
138 $enabled = false;
139 }
140
141 if ($enabled) {
142 // Loading Class
143 $file = $dir.$modulename.".class.php";
144 $classname = $modulename;
145 require_once $file;
146 $module = new $classname($this->db);
147
148 if (isset($module->export_code) && is_array($module->export_code)) {
149 foreach ($module->export_code as $r => $value) {
150 //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).'<br>';
151 if ($filter && ($filter != $module->export_code[$r])) {
152 continue;
153 }
154
155 // Test if condition to show are ok
156 if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) {
157 continue;
158 }
159
160 // Test if permissions are ok
161 $bool = true;
162 if (isset($module->export_permission)) {
163 foreach ($module->export_permission[$r] as $val) {
164 $perm = $val;
165 //print_r("$perm[0]-$perm[1]-$perm[2]<br>");
166 if (!empty($perm[2])) {
167 $bool = isset($user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]}) ? $user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]} : false;
168 } else {
169 $bool = isset($user->rights->{$perm[0]}->{$perm[1]}) ? $user->rights->{$perm[0]}->{$perm[1]} : false;
170 }
171 if ($perm[0] == 'user' && $user->admin) {
172 $bool = true;
173 }
174 if (!$bool) {
175 break;
176 }
177 }
178 }
179 //print $bool." $perm[0]"."<br>";
180
181 // Permissions ok
182 // if ($bool)
183 // {
184 // Charge fichier lang en rapport
185 $langtoload = $module->getLangFilesArray();
186 if (is_array($langtoload)) {
187 foreach ($langtoload as $key) {
188 $langs->load($key);
189 }
190 }
191
192
193 // Module
194 $this->array_export_module[$i] = $module;
195 // Permission
196 $this->array_export_perms[$i] = $bool;
197 // Icon
198 $this->array_export_icon[$i] = (isset($module->export_icon[$r]) ? $module->export_icon[$r] : $module->picto);
199 // Code of the export dataset / Code du dataset export
200 $this->array_export_code[$i] = $module->export_code[$r];
201 // Define a key for sort
202 $this->array_export_code_for_sort[$i] = $module->module_position.'_'.$module->export_code[$r]; // Add a key into the module
203 // Export Dataset Label / Libelle du dataset export
204 $this->array_export_label[$i] = $module->getExportDatasetLabel($r);
205 // Table of fields to export / Tableau des champ a exporter (cle=champ, valeur=libelle)
206 $this->array_export_fields[$i] = $module->export_fields_array[$r];
207 // Table of fields to be filtered / Tableau des champs a filtrer (cle=champ, valeur1=type de donnees) on verifie que le module a des filtres
208 $this->array_export_TypeFields[$i] = (isset($module->export_TypeFields_array[$r]) ? $module->export_TypeFields_array[$r] : '');
209 // Table of entities for export / Tableau des entites a exporter (cle=champ, valeur=entite)
210 $this->array_export_entities[$i] = $module->export_entities_array[$r];
211 // Table of entities requiring DISTINCT abandonment / Tableau des entites qui requiert abandon du DISTINCT (cle=entite, valeur=champ id child records)
212 $this->array_export_dependencies[$i] = (!empty($module->export_dependencies_array[$r]) ? $module->export_dependencies_array[$r] : '');
213 // Table of special field operations / Tableau des operations speciales sur champ
214 $this->array_export_special[$i] = (!empty($module->export_special_array[$r]) ? $module->export_special_array[$r] : '');
215 // Array of examples
216 $this->array_export_examplevalues[$i] = (!empty($module->export_examplevalues_array[$r]) ? $module->export_examplevalues_array[$r] : null);
217 // Array of help tooltips
218 $this->array_export_help[$i] = (!empty($module->export_help_array[$r]) ? $module->export_help_array[$r] : '');
219
220 // SQL dataset query / Requete SQL du dataset
221 $this->array_export_sql_start[$i] = $module->export_sql_start[$r];
222 $this->array_export_sql_end[$i] = $module->export_sql_end[$r];
223 $this->array_export_sql_order[$i] = (!empty($module->export_sql_order[$r]) ? $module->export_sql_order[$r] : null);
224 //$this->array_export_sql[$i]=$module->export_sql[$r];
225
226 dol_syslog(get_class($this)."::load_arrays loaded for module ".$modulename." with index ".$i.", dataset=".$module->export_code[$r].", nb of fields=".(!empty($module->export_fields_code[$r]) ? count($module->export_fields_code[$r]) : ''));
227 $i++;
228 // }
229 }
230 }
231 }
232 }
233 }
234 closedir($handle);
235 }
236 }
237
238 return 1;
239 }
240
241
242 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
252 public function build_sql($indice, $array_selected, $array_filterValue)
253 {
254 // phpcs:enable
255 // Build the sql request
256 $sql = $this->array_export_sql_start[$indice];
257 $i = 0;
258
259 //print_r($array_selected);
260 foreach ($this->array_export_fields[$indice] as $key => $value) {
261 if (!array_key_exists($key, $array_selected)) {
262 continue; // Field not selected
263 }
264 if (preg_match('/^none\./', $key)) {
265 continue; // A field that must not appears into SQL
266 }
267 if ($i > 0) {
268 $sql .= ', ';
269 } else {
270 $i++;
271 }
272
273 if (strpos($key, ' as ') === false) {
274 $newfield = $key.' as '.str_replace(array('.', '-', '(', ')'), '_', $key);
275 } else {
276 $newfield = $key;
277 }
278
279 $sql .= $newfield;
280 }
281 $sql .= $this->array_export_sql_end[$indice];
282
283 // Add the WHERE part. Filtering into sql if a filtering array is provided
284 if (is_array($array_filterValue) && !empty($array_filterValue)) {
285 $sqlWhere = '';
286 // Loop on each condition to add
287 foreach ($array_filterValue as $key => $value) {
288 if (preg_match('/GROUP_CONCAT/i', $key)) {
289 continue;
290 }
291 if ($value != '') {
292 $sqlWhere .= " AND ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
293 }
294 }
295 $sql .= $sqlWhere;
296 }
297
298 // Add the sort order
299 $sql .= $this->array_export_sql_order[$indice];
300
301 // Add the HAVING part.
302 if (is_array($array_filterValue) && !empty($array_filterValue)) {
303 // Loop on each condition to add
304 foreach ($array_filterValue as $key => $value) {
305 if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') {
306 $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
307 }
308 }
309 }
310
311 return $sql;
312 }
313
314 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
323 public function build_filterQuery($TypeField, $NameField, $ValueField)
324 {
325 // phpcs:enable
326 $NameField = sanitizeVal($NameField, 'aZ09');
327 $szFilterQuery = '';
328
329 //print $TypeField." ".$NameField." ".$ValueField;
330 $InfoFieldList = explode(":", $TypeField);
331 // build the input field on depend of the type of file
332 switch ($InfoFieldList[0]) {
333 case 'Text':
334 if (!(strpos($ValueField, '%') === false)) {
335 $szFilterQuery = " ".$NameField." LIKE '".$this->db->escape($ValueField)."'";
336 } else {
337 $szFilterQuery = " ".$NameField." = '".$this->db->escape($ValueField)."'";
338 }
339 break;
340 case 'Date':
341 if (strpos($ValueField, "+") > 0) {
342 // mode plage
343 $ValueArray = explode("+", $ValueField);
344 $szFilterQuery = "(".$this->conditionDate($NameField, trim($ValueArray[0]), ">=");
345 $szFilterQuery .= " AND ".$this->conditionDate($NameField, trim($ValueArray[1]), "<=").")";
346 } else {
347 if (is_numeric(substr($ValueField, 0, 1))) {
348 $szFilterQuery = $this->conditionDate($NameField, trim($ValueField), "=");
349 } else {
350 $szFilterQuery = $this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1));
351 }
352 }
353 break;
354 case 'Duree':
355 break;
356 case 'Numeric':
357 // if there is a signe +
358 if (strpos($ValueField, "+") > 0) {
359 // mode plage
360 $ValueArray = explode("+", $ValueField);
361 $szFilterQuery = "(".$NameField." >= ".((float) $ValueArray[0]);
362 $szFilterQuery .= " AND ".$NameField." <= ".((float) $ValueArray[1]).")";
363 } else {
364 if (is_numeric(substr($ValueField, 0, 1))) {
365 $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
366 } else {
367 $szFilterQuery = " ".$NameField.substr($ValueField, 0, 1).((float) substr($ValueField, 1));
368 }
369 }
370 break;
371 case 'Boolean':
372 $szFilterQuery = " ".$NameField."=".(is_numeric($ValueField) ? $ValueField : ($ValueField == 'yes' ? 1 : 0));
373 break;
374 case 'FormSelect':
375 if (is_numeric($ValueField) && $ValueField > 0) {
376 $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
377 } else {
378 $szFilterQuery = " 1=1"; // Test always true
379 }
380 break;
381 case 'Status':
382 case 'List':
383 if (is_numeric($ValueField)) {
384 $szFilterQuery = " ".$NameField." = ".((float) $ValueField);
385 } else {
386 if (!(strpos($ValueField, '%') === false)) {
387 $szFilterQuery = " ".$NameField." LIKE '".$this->db->escape($ValueField)."'";
388 } else {
389 $szFilterQuery = " ".$NameField." = '".$this->db->escape($ValueField)."'";
390 }
391 }
392 break;
393 default:
394 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);
395 }
396
397 return $szFilterQuery;
398 }
399
408 public function conditionDate($Field, $Value, $Sens)
409 {
410 // TODO date_format is forbidden, not performant and not portable. Use instead $Value to forge the range date.
411 if (strlen($Value) == 4) {
412 $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$this->db->escape($Value)."'";
413 } elseif (strlen($Value) == 6) {
414 $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$this->db->escape($Value)."'";
415 } else {
416 $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." '".$this->db->escape($Value)."'";
417 }
418 return $Condition;
419 }
420
421 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
430 public function build_filterField($TypeField, $NameField, $ValueField)
431 {
432 // phpcs:enable
433 global $conf, $langs, $form;
434
435 $szFilterField = '';
436 $InfoFieldList = explode(":", $TypeField);
437
438 // build the input field on depend of the type of file
439 switch ($InfoFieldList[0]) {
440 case 'Text':
441 case 'Date':
442 $szFilterField = '<input type="text" name="'.$NameField.'" value="'.$ValueField.'">';
443 break;
444 case 'Duree':
445 case 'Numeric':
446 case 'Number':
447 // Must be a string text to allow to use comparison strings like "<= 99.9"
448 $szFilterField = '<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
449 break;
450 case 'Status':
451 $szFilterField = '<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
452 break;
453 case 'Boolean':
454 $szFilterField = '<select name="'.$NameField.'" class="flat">';
455 $szFilterField .= '<option ';
456 if ($ValueField == '') {
457 $szFilterField .= ' selected ';
458 }
459 $szFilterField .= ' value="">&nbsp;</option>';
460
461 $szFilterField .= '<option ';
462 if ($ValueField == 'yes' || $ValueField == '1') {
463 $szFilterField .= ' selected ';
464 }
465 $szFilterField .= ' value="1">'.yn(1).'</option>';
466
467 $szFilterField .= '<option ';
468 if ($ValueField == 'no' || $ValueField == '0') {
469 $szFilterField .= ' selected ';
470 }
471 $szFilterField .= ' value="0">'.yn(0).'</option>';
472 $szFilterField .= "</select>";
473 break;
474 case 'FormSelect':
475 //var_dump($NameField);
476 if ($InfoFieldList[1] == 'select_company') {
477 $szFilterField .= $form->select_company('', $NameField, '', 1, 0, 0, [], 0, 'maxwidth200');
478 } elseif ($InfoFieldList[1] == 'selectcontacts') {
479 $szFilterField .= $form->selectcontacts(0, '', $NameField, '&nbsp;', '', '', 0, 'maxwidth200');
480 } elseif ($InfoFieldList[1] == 'select_dolusers') {
481 $szFilterField .= $form->select_dolusers('', $NameField, 1, null, 0, '', '', '', 0, 0, "", 0, "", "maxwidth200");
482 }
483 break;
484 case 'List':
485 // 0 : Type of the field / Type du champ
486 // 1 : Name of the table / Nom de la table
487 // 2 : Name of the field containing the label / Nom du champ contenant le libelle
488 // 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list.
489 // 4 : Name of element for getEntity().
490
491 if (!empty($InfoFieldList[3])) {
492 $keyList = $InfoFieldList[3];
493 } else {
494 $keyList = 'rowid';
495 }
496 $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3]." as code");
497 if ($InfoFieldList[1] == 'c_stcomm') {
498 $sql = "SELECT id as id, ".$keyList." as rowid, ".$InfoFieldList[2]." as label".(empty($InfoFieldList[3]) ? "" : ", ".$InfoFieldList[3].' as code');
499 }
500 if ($InfoFieldList[1] == 'c_country') {
501 $sql = "SELECT ".$keyList." as rowid, ".$InfoFieldList[2]." as label, code as code";
502 }
503 $sql .= " FROM ".MAIN_DB_PREFIX.$InfoFieldList[1];
504 if (!empty($InfoFieldList[4])) {
505 $sql .= ' WHERE entity IN ('.getEntity($InfoFieldList[4]).')';
506 }
507
508 $resql = $this->db->query($sql);
509 if ($resql) {
510 $szFilterField = '<select class="flat" name="'.$NameField.'">';
511 $szFilterField .= '<option value="0">&nbsp;</option>';
512 $num = $this->db->num_rows($resql);
513
514 $i = 0;
515 if ($num) {
516 while ($i < $num) {
517 $obj = $this->db->fetch_object($resql);
518 if ($obj->label == '-') {
519 // Discard entry '-'
520 $i++;
521 continue;
522 }
523 //var_dump($InfoFieldList[1]);
524 $labeltoshow = dol_trunc($obj->label, 18);
525 if ($InfoFieldList[1] == 'c_stcomm') {
526 $langs->load("companies");
527 $labeltoshow = (($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id) ? $langs->trans("StatusProspect".$obj->id) : $obj->label);
528 }
529 if ($InfoFieldList[1] == 'c_country') {
530 //var_dump($sql);
531 $langs->load("dict");
532 $labeltoshow = (($langs->trans("Country".$obj->code) != "Country".$obj->code) ? $langs->trans("Country".$obj->code) : $obj->label);
533 }
534 if (!empty($ValueField) && $ValueField == $obj->rowid) {
535 $szFilterField .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
536 } else {
537 $szFilterField .= '<option value="'.$obj->rowid.'" >'.$labeltoshow.'</option>';
538 }
539 $i++;
540 }
541 }
542 $szFilterField .= "</select>";
543
544 $this->db->free($resql);
545 } else {
546 dol_print_error($this->db);
547 }
548 break;
549 }
550
551 return $szFilterField;
552 }
553
560 public function genDocFilter($TypeField)
561 {
562 global $langs;
563
564 $szMsg = '';
565 $InfoFieldList = explode(":", $TypeField);
566 // build the input field on depend of the type of file
567 switch ($InfoFieldList[0]) {
568 case 'Text':
569 $szMsg = $langs->trans('ExportStringFilter');
570 break;
571 case 'Date':
572 $szMsg = $langs->trans('ExportDateFilter');
573 break;
574 case 'Duree':
575 break;
576 case 'Numeric':
577 $szMsg = $langs->trans('ExportNumericFilter');
578 break;
579 case 'Boolean':
580 break;
581 case 'List':
582 break;
583 }
584 return $szMsg;
585 }
586
587 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
602 public function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '', $separator = '')
603 {
604 // phpcs:enable
605 global $conf, $langs, $mysoc;
606
607 $indice = 0;
608 asort($array_selected);
609
610 dol_syslog(__METHOD__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected));
611
612 // Check parameters or context properties
613 if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) {
614 $this->error = "ErrorBadParameter";
615 dol_syslog($this->error, LOG_ERR);
616 return -1;
617 }
618
619 // Creation of class to export using model ExportXXX
620 $dir = DOL_DOCUMENT_ROOT."/core/modules/export/";
621 $file = "export_".$model.".modules.php";
622 $classname = "Export".$model;
623 require_once $dir.$file;
624 $objmodel = new $classname($this->db);
625
626 if (in_array($model, array('csvutf8', 'csviso')) && !empty($separator)) {
627 $objmodel->separator = $separator;
628 }
629
630 if (!empty($sqlquery)) {
631 $sql = $sqlquery;
632 } else {
633 // Define value for indice from $datatoexport
634 $foundindice = 0;
635 foreach ($this->array_export_code as $key => $dataset) {
636 if ($datatoexport == $dataset) {
637 $indice = $key;
638 $foundindice++;
639 //print "Found indice = ".$indice." for dataset=".$datatoexport."\n";
640 break;
641 }
642 }
643 if (empty($foundindice)) {
644 $this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
645 return -1;
646 }
647 $sql = $this->build_sql($indice, $array_selected, $array_filterValue);
648 }
649
650 // Run the SQL
651 $this->sqlusedforexport = $sql;
652 dol_syslog(__METHOD__, LOG_DEBUG);
653 $resql = $this->db->query($sql);
654 if ($resql) {
655 //$this->array_export_label[$indice]
656 if (getDolGlobalString('EXPORT_PREFIX_SPEC')) {
657 $filename = getDolGlobalString('EXPORT_PREFIX_SPEC') . "_".$datatoexport;
658 } else {
659 $filename = "export_".$datatoexport;
660 }
661 if (getDolGlobalString('EXPORT_NAME_WITH_DT')) {
662 $filename .= dol_print_date(dol_now(), '%Y%m%d%_%H%M');
663 }
664 $filename .= '.'.$objmodel->getDriverExtension();
665 $dirname = $conf->export->dir_temp.'/'.$user->id;
666
667 $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
668
669 // Open file
670 dol_mkdir($dirname);
671 $result = $objmodel->open_file($dirname."/".$filename, $outputlangs);
672
673 if ($result >= 0) {
674 // Generate header
675 $objmodel->write_header($outputlangs);
676
677 // Generate title line
678 $objmodel->write_title($this->array_export_fields[$indice], $array_selected, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
679
680 while ($obj = $this->db->fetch_object($resql)) {
681 // Process special operations
682 if (!empty($this->array_export_special[$indice])) {
683 foreach ($this->array_export_special[$indice] as $key => $value) {
684 if (!array_key_exists($key, $array_selected)) {
685 continue; // Field not selected
686 }
687 // Operation NULLIFNEG
688 if ($this->array_export_special[$indice][$key] == 'NULLIFNEG') {
689 //$alias=$this->array_export_alias[$indice][$key];
690 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
691 if ($obj->$alias < 0) {
692 $obj->$alias = '';
693 }
694 } elseif ($this->array_export_special[$indice][$key] == 'ZEROIFNEG') {
695 // Operation ZEROIFNEG
696 //$alias=$this->array_export_alias[$indice][$key];
697 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
698 if ($obj->$alias < 0) {
699 $obj->$alias = '0';
700 }
701 } elseif ($this->array_export_special[$indice][$key] == 'getNumOpenDays') {
702 // Operation GETNUMOPENDAYS (for Holiday module)
703 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
704 //$alias=$this->array_export_alias[$indice][$key];
705 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
706 $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);
707 } elseif ($this->array_export_special[$indice][$key] == 'getRemainToPay') {
708 // Operation INVOICEREMAINTOPAY
709 //$alias=$this->array_export_alias[$indice][$key];
710 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
711 $remaintopay = '';
712 if ($obj->f_rowid > 0) {
713 global $tmpobjforcomputecall;
714 if (!is_object($tmpobjforcomputecall)) {
715 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
716 $tmpobjforcomputecall = new Facture($this->db);
717 }
718 $tmpobjforcomputecall->id = $obj->f_rowid;
719 $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
720 $tmpobjforcomputecall->close_code = $obj->f_close_code;
721 $remaintopay = $tmpobjforcomputecall->getRemainToPay();
722 }
723 $obj->$alias = $remaintopay;
724 } elseif (is_array($this->array_export_special[$indice][$key]) &&
725 !empty($this->array_export_special[$indice][$key]['rule']) &&
726 $this->array_export_special[$indice][$key]['rule'] == 'compute'
727 ) {
728 // Custom compute
729 $alias = str_replace(array('.', '-', '(', ')'), '_', $key);
730 $value = '';
731 if (!empty($this->array_export_special[$indice][$key]['class']) &&
732 !empty($this->array_export_special[$indice][$key]['classfile']) &&
733 !empty($this->array_export_special[$indice][$key]['method'])
734 ) {
735 if (!dol_include_once($this->array_export_special[$indice][$key]['classfile'])) {
736 $this->error = "Computed field bad configuration: {$this->array_export_special[$indice][$key]['classfile']} not found";
737 return -1;
738 }
739
740 if (!class_exists($this->array_export_special[$indice][$key]['class'])) {
741 $this->error = "Computed field bad configuration: {$this->array_export_special[$indice][$key]['class']} class doesn't exist";
742 return -1;
743 }
744
745 $className = $this->array_export_special[$indice][$key]['class'];
746 $tmpObject = new $className($this->db);
747 if (!method_exists($tmpObject, $this->array_export_special[$indice][$key]['method'])) {
748 $this->error = "Computed field bad configuration: {$this->array_export_special[$indice][$key]['method']} method doesn't exist";
749 return -1;
750 }
751
752 $methodName = $this->array_export_special[$indice][$key]['method'];
753 $params = [];
754 if (!empty($this->array_export_special[$indice][$key]['method_params'])) {
755 foreach ($this->array_export_special[$indice][$key]['method_params'] as $paramName) {
756 $params[] = $obj->$paramName ?? null;
757 }
758 }
759 $value = $tmpObject->$methodName(...$params);
760 }
761 $obj->$alias = $value;
762 } else {
763 // TODO FIXME
764 // Export of compute field does not work. $obj contains $obj->alias_field and formula may contains $obj->field
765 // Also the formula may contains objects of class that are not loaded.
766 $computestring = $this->array_export_special[$indice][$key];
767 //$tmp = dol_eval($computestring, 1, 0, '1');
768 //$obj->$alias = $tmp;
769
770 $this->error = "ERROPNOTSUPPORTED. Operation ".$computestring." not supported. Export of 'computed' extrafields is not yet supported, please remove field.";
771 return -1;
772 }
773 }
774 }
775 // end of special operation processing
776 $objmodel->write_record($array_selected, $obj, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null);
777 }
778
779 // Generate Footer
780 $objmodel->write_footer($outputlangs);
781
782 // Close file
783 $objmodel->close_file();
784
785 return 1;
786 } else {
787 $this->error = $objmodel->error;
788 dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
789 return -1;
790 }
791 } else {
792 $this->error = $this->db->error()." - sql=".$sql;
793 return -1;
794 }
795 }
796
803 public function create($user)
804 {
805 global $conf;
806
807 dol_syslog("Export.class.php::create");
808
809 $this->db->begin();
810
811 $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'export_model (';
812 $sql .= 'label,';
813 $sql .= 'type,';
814 $sql .= 'field,';
815 $sql .= 'fk_user,';
816 $sql .= 'filter';
817 $sql .= ') VALUES (';
818 $sql .= "'".$this->db->escape($this->model_name)."',";
819 $sql .= " '".$this->db->escape($this->datatoexport)."',";
820 $sql .= " '".$this->db->escape($this->hexa)."',";
821 $sql .= ' '.(isset($this->fk_user) ? (int) $this->fk_user : 'null').",";
822 $sql .= " '".$this->db->escape($this->hexafiltervalue)."'";
823 $sql .= ")";
824
825 $resql = $this->db->query($sql);
826 if ($resql) {
827 $this->db->commit();
828 return 1;
829 } else {
830 $this->error = $this->db->lasterror();
831 $this->errno = $this->db->lasterrno();
832 $this->db->rollback();
833 return -1;
834 }
835 }
836
843 public function fetch($id)
844 {
845 $sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter';
846 $sql .= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
847 $sql .= ' WHERE em.rowid = '.((int) $id);
848
849 dol_syslog("Export::fetch", LOG_DEBUG);
850 $result = $this->db->query($sql);
851 if ($result) {
852 $obj = $this->db->fetch_object($result);
853 if ($obj) {
854 $this->id = $obj->rowid;
855 $this->model_name = $obj->label;
856 $this->datatoexport = $obj->type;
857
858 $this->hexa = $obj->field;
859 $this->hexafiltervalue = $obj->filter;
860
861 return 1;
862 } else {
863 $this->error = "ModelNotFound";
864 return -2;
865 }
866 } else {
867 dol_print_error($this->db);
868 return -3;
869 }
870 }
871
872
880 public function delete($user, $notrigger = 0)
881 {
882 global $conf, $langs;
883 $error = 0;
884
885 $sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model";
886 $sql .= " WHERE rowid=".((int) $this->id);
887
888 $this->db->begin();
889
890 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
891 $resql = $this->db->query($sql);
892 if (!$resql) {
893 $error++;
894 $this->errors[] = "Error ".$this->db->lasterror();
895 }
896
897 // Commit or rollback
898 if ($error) {
899 foreach ($this->errors as $errmsg) {
900 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
901 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
902 }
903 $this->db->rollback();
904 return -1 * $error;
905 } else {
906 $this->db->commit();
907 return 1;
908 }
909 }
910
911 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
918 public function list_export_model()
919 {
920 // phpcs:enable
921 global $conf, $langs;
922
923 $sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter";
924 $sql .= " FROM ".MAIN_DB_PREFIX."export_model as em";
925 $sql .= " ORDER BY rowid";
926
927 $result = $this->db->query($sql);
928 if ($result) {
929 $num = $this->db->num_rows($result);
930 $i = 0;
931 while ($i < $num) {
932 $obj = $this->db->fetch_object($result);
933 $keyModel = array_search($obj->type, $this->array_export_code);
934 print "<tr>";
935 print '<td><a href=export.php?step=2&action=select_model&exportmodelid='.$obj->rowid.'&datatoexport='.$obj->type.'>'.$obj->label.'</a></td>';
936 print '<td>';
937 print img_object($this->array_export_module[$keyModel]->getName(), $this->array_export_icon[$keyModel]).' ';
938 print $this->array_export_module[$keyModel]->getName().' - ';
939 // recover export name / recuperation du nom de l'export
940
941 $string = $langs->trans($this->array_export_label[$keyModel]);
942 print($string != $this->array_export_label[$keyModel] ? $string : $this->array_export_label[$keyModel]);
943 print '</td>';
944 //print '<td>'.$obj->type.$keyModel.'</td>';
945 print '<td>'.str_replace(',', ' , ', $obj->field).'</td>';
946 if (!empty($obj->filter)) {
947 $filter = json_decode($obj->filter, true);
948 print '<td>'.str_replace(',', ' , ', $filter['field']).'</td>';
949 print '<td>'.str_replace(',', ' , ', $filter['value']).'</td>';
950 }
951 // remove export / suppression de l'export
952 print '<td class="right">';
953 print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteprof&token='.newToken().'&id='.$obj->rowid.'">';
954 print img_delete();
955 print '</a>';
956 print "</tr>";
957
958 $i++;
959 }
960 } else {
961 dol_print_error($this->db);
962 }
963 }
964}
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 conditionnal 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:426
dolGetModulesDirs($subdir='')
Return list of modules directories.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
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.
verifCond($strToEvaluate)
Verify if condition in string is ok or not.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)