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