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