dolibarr 25.0.0-alpha
customreports.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2020-2024 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
4 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
48'
49@phan-var-force ?int[] $toselect
50';
51
52// Initialise values
53$tabfamily = null;
54$objecttype = null;
55
56if (!defined('USE_CUSTOM_REPORT_AS_INCLUDE')) {
57 require '../main.inc.php';
58
59 // Get parameters
60 $action = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
61 $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
62
63 $mode = GETPOST('mode', 'alpha');
64 $objecttype = (string) GETPOST('objecttype', 'aZ09arobase');
65 if ($objecttype == '-1') { // -1 is the empty value of the combo of object types
66 $objecttype = '';
67 }
68 $tabfamily = GETPOST('tabfamily', 'aZ09');
69
70 $search_measures = GETPOST('search_measures', 'array:alphanohtml');
71
72 if (GETPOST('search_xaxis', 'alpha') && GETPOST('search_xaxis', 'alpha') != '-1') {
73 $search_xaxis = array(GETPOST('search_xaxis', 'alpha'));
74 } else {
75 $search_xaxis = array();
76 }
77 if (GETPOST('search_groupby', 'alpha') && GETPOST('search_groupby', 'alpha') != '-1') {
78 $search_groupby = array(GETPOST('search_groupby', 'alpha'));
79 } else {
80 $search_groupby = array();
81 }
82 '@phan-var-force string[] $search_groupby';
83
84 $search_yaxis = GETPOST('search_yaxis', 'array:alphanohtml');
85 $search_graph = (string) GETPOST('search_graph', 'restricthtml');
86
93 function sanititzekey($value)
94 {
95 return preg_replace('/[^a-z0-9\._\-]+/', '', $value);
96 }
97
98 $sanitized_search_measures = array_map('sanititzekey', $search_measures);
99 $sanitized_search_xaxis = array_map('sanititzekey', $search_xaxis);
100 $sanitized_search_yaxis = array_map('sanititzekey', $search_yaxis);
101 $sanitized_search_groupby = array_map('sanititzekey', $search_groupby);
102
103 // Load variable for pagination
104 $limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
105 $sortfield = GETPOST('sortfield', 'aZ09comma');
106 $sortorder = GETPOST('sortorder', 'aZ09comma');
107 $page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
108 if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) {
109 $page = 0;
110 } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action
111 $offset = $limit * $page;
112 $pageprev = $page - 1;
113 $pagenext = $page + 1;
114
115 $object = null;
116} else {
117 // When included into a main page
127 '
128 @phan-var-force int<0,1> $SHOWLEGEND
129 @phan-var-force string $customreportkey
130 @phan-var-force ?string $customsql
131 @phan-var-force ?string[] $sanitized_search_groupby Array with the third dimension
132 @phan-var-force int $page
133 @phan-var-force string $sortfield
134 @phan-var-force string $sortorder
135 ';
136
137 // $sanitized_search_measures, $sanitized_search_xaxis or $sanitized_search_yaxis may have been defined by the parent.
138
139 if (empty($user) || empty($user->id)) {
140 print 'Page is called as an include but $user and its permission loaded with loadRights() are not defined. We stop here.';
141 exit(1);
142 }
143 if (empty($object)) {
144 print 'Page is called as an include but $object is not defined. We stop here.';
145 exit(1);
146 }
147}
148
149// In customreport context, we force the protection to avoid forging of criteria including bind SQL injection
150global $dolibarr_allow_unsecured_select_in_extrafields_filter;
151$dolibarr_allow_unsecured_select_in_extrafields_filter = 0;
152
153if (empty($mode)) {
154 $mode = 'graph';
155}
156if (!isset($sanitized_search_measures)) {
157 $sanitized_search_measures = array(0 => 't.count');
158}
159if (!isset($sanitized_search_xaxis)) {
160 // Ensure value is set and not null.
161 $sanitized_search_xaxis = array();
162}
163if (!isset($sanitized_search_yaxis)) {
164 // Ensure value is set and not null.
165 $sanitized_search_yaxis = array();
166}
167if (!isset($sanitized_search_groupby)) {
168 // Ensure value is set and not null.
169 $sanitized_search_groupby = array();
170}
171if (!isset($search_graph)) {
172 // Ensure value is set and not null
173 $search_graph = '';
174}
175if (!empty($object)) {
176 $objecttype = $object->element.($object->module ? '@'.$object->module : '');
177}
178if (!is_string($objecttype)) { // No object type is preselected
179 $objecttype = '';
180}
181/*if ((!is_string($objecttype) || empty($objecttype)) && isModEnabled('societe')) {
182 $objecttype = 'thirdparty';
183}*/
184'@phan-var-force string $objecttype'; // Help phan that suggests $objecttype can be null
185
186require_once DOL_DOCUMENT_ROOT."/core/class/extrafields.class.php";
187require_once DOL_DOCUMENT_ROOT."/core/class/html.form.class.php";
188require_once DOL_DOCUMENT_ROOT."/core/lib/admin.lib.php";
189require_once DOL_DOCUMENT_ROOT."/core/lib/company.lib.php";
190require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
191require_once DOL_DOCUMENT_ROOT."/core/lib/customreports.lib.php";
192require_once DOL_DOCUMENT_ROOT."/core/class/dolgraph.class.php";
193require_once DOL_DOCUMENT_ROOT."/core/class/doleditor.class.php";
194require_once DOL_DOCUMENT_ROOT."/core/class/html.formother.class.php";
195
196// Load traductions files requiredby by page (stocks is for labels of linked warehouses in tables of fields)
197$langs->loadLangs(array("companies", "other", "exports", "sendings", "stocks"));
198
199$extrafields = new ExtraFields($db);
200
201$hookmanager->initHooks(array('customreport')); // Note that conf->hooks_modules contains array
202
203$title = '';
204$picto = '';
205$errormessage = null;
206$keyforlabeloffield = null;
207$head = array();
208$ObjectClassName = '';
209// Objects available by default
210$arrayoftype = array(
211 'thirdparty' => array('label' => 'ThirdParties', 'picto' => 'company', 'ObjectClassName' => 'Societe', 'enabled' => isModEnabled('societe'), 'ClassPath' => "/societe/class/societe.class.php", 'langs' => 'companies'),
212 'contact' => array('label' => 'Contacts', 'picto' => 'contact', 'ObjectClassName' => 'Contact', 'enabled' => isModEnabled('societe'), 'ClassPath' => "/contact/class/contact.class.php"),
213 'proposal' => array('label' => 'Proposals', 'picto' => 'proposal', 'ObjectClassName' => 'Propal', 'enabled' => isModEnabled('propal'), 'ClassPath' => "/comm/propal/class/propal.class.php", 'langs' => 'propal'),
214 'proposaldet' => array('label' => 'ProposalLines', 'picto' => 'proposal', 'ObjectClassName' => 'PropaleLigne', 'enabled' => isModEnabled('propal'), 'ClassPath' => "/comm/propal/class/propaleligne.class.php", 'langs' => 'propal'),
215 'order' => array('label' => 'Orders', 'picto' => 'order', 'ObjectClassName' => 'Commande', 'enabled' => isModEnabled('order'), 'ClassPath' => "/commande/class/commande.class.php", 'langs' => 'orders'),
216 'orderdet' => array('label' => 'SaleOrderLines', 'picto' => 'order', 'ObjectClassName' => 'OrderLine', 'enabled' => isModEnabled('order'), 'ClassPath' => "/commande/class/orderline.class.php", 'langs' => 'orders'),
217 'invoice' => array('label' => 'Invoices', 'picto' => 'bill', 'ObjectClassName' => 'Facture', 'enabled' => isModEnabled('invoice'), 'ClassPath' => "/compta/facture/class/facture.class.php", 'langs' => 'bills'),
218 'invoice_template' => array('label' => 'PredefinedInvoices', 'picto' => 'bill', 'ObjectClassName' => 'FactureRec', 'enabled' => isModEnabled('invoice'), 'ClassPath' => "/compta/facture/class/facture-rec.class.php", 'langs' => 'bills'),
219 'contract' => array('label' => 'Contracts', 'picto' => 'contract', 'ObjectClassName' => 'Contrat', 'enabled' => isModEnabled('contract'), 'ClassPath' => "/contrat/class/contrat.class.php", 'langs' => 'contracts'),
220 'contractdet' => array('label' => 'ContractLines', 'picto' => 'contract', 'ObjectClassName' => 'ContratLigne', 'enabled' => isModEnabled('contract'), 'ClassPath' => "/contrat/class/contrat.class.php", 'langs' => 'contracts'),
221 'bom' => array('label' => 'BOM', 'picto' => 'bom', 'ObjectClassName' => 'Bom', 'enabled' => isModEnabled('bom')),
222 'mrp' => array('label' => 'MO', 'picto' => 'mrp', 'ObjectClassName' => 'Mo', 'enabled' => isModEnabled('mrp'), 'ClassPath' => "/mrp/class/mo.class.php"),
223 'ticket' => array('label' => 'Ticket', 'picto' => 'ticket', 'ObjectClassName' => 'Ticket', 'enabled' => isModEnabled('ticket')),
224 'member' => array('langs' => 'members', 'label' => 'Adherent', 'picto' => 'member', 'ObjectClassName' => 'Adherent', 'enabled' => isModEnabled('member'), 'ClassPath' => "/adherents/class/adherent.class.php"),
225 'cotisation' => array('langs' => 'members', 'label' => 'Subscriptions', 'picto' => 'member', 'ObjectClassName' => 'Subscription', 'enabled' => isModEnabled('member'), 'ClassPath' => "/adherents/class/subscription.class.php"),
226);
227
228
229// Complete $arrayoftype by external modules
230$parameters = array('objecttype' => $objecttype, 'tabfamily' => $tabfamily);
231// @phan-suppress-next-line PhanTypeMismatchArgumentNullable
232$reshook = $hookmanager->executeHooks('loadDataForCustomReports', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
233if ($reshook < 0) {
234 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
235} elseif (is_array($hookmanager->resArray)) {
236 if (!empty($hookmanager->resArray['title'])) { // Add entries for tabs
237 $title = $hookmanager->resArray['title'];
238 }
239 if (!empty($hookmanager->resArray['picto'])) { // Add entries for tabs
240 $picto = $hookmanager->resArray['picto'];
241 }
242 if (!empty($hookmanager->resArray['head'])) { // Add entries for tabs
243 $head = array_merge($head, $hookmanager->resArray['head']);
244 }
245 if (!empty($hookmanager->resArray['arrayoftype'])) { // Add entries from hook
246 foreach ($hookmanager->resArray['arrayoftype'] as $key => $val) {
247 $arrayoftype[$key] = $val;
248 }
249 }
250}
251
252// Load the main $object for statistics
253if ($objecttype) {
254 try {
255 if (!empty($arrayoftype[$objecttype]['ClassPath'])) {
256 $fileforclass = $arrayoftype[$objecttype]['ClassPath'];
257 } else {
258 $fileforclass = "/".$objecttype."/class/".$objecttype.".class.php";
259 }
260 $ObjectClassName = null;
261
262 if ($fileforclass !== null) {
263 dol_include_once($fileforclass);
264
265 $ObjectClassName = $arrayoftype[$objecttype]['ObjectClassName'];
266 }
267 if (!empty($ObjectClassName)) {
268 if (class_exists($ObjectClassName)) {
269 $object = new $ObjectClassName($db);
270 } else {
271 print 'Failed to load class for type '.$objecttype.'. Class file found but Class object named '.$ObjectClassName.' not found.';
272 }
273 } else {
274 print 'Failed to load class for type '.$objecttype.'. Class file name is unknown.';
275 }
276 } catch (Exception $e) {
277 print 'Failed to load class for type '.$objecttype.'. Class path not found.';
278 }
279}
280
281'@phan-var-force CommonObject $object';
282
283// Security check
284//$socid = 0;
285if ($user->socid > 0) { // Protection if external user
286 //$socid = $user->socid;
287 accessforbidden('Access forbidden to external users');
288}
289
290// Fetch optionals attributes and labels
291$extrafields->fetch_name_optionals_label('all'); // We load all extrafields definitions for all objects
292//$extrafields->fetch_name_optionals_label($object->table_element_line);
293
294if (!empty($object->table_element)) {
295 $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
296} else {
297 $search_array_options = array();
298}
299
300$search_component_params = array('');
301$search_component_params_hidden = trim(GETPOST('search_component_params_hidden', 'alphanohtml'));
302$search_component_params_input = trim(GETPOST('search_component_params_input', 'alphanohtml'));
303//var_dump($search_component_params_hidden);
304//var_dump($search_component_params_input);
305
306// If string is not an universal filter string, we try to convert it into universal filter syntax string
307$errorstr = '';
308forgeSQLFromUniversalSearchCriteria($search_component_params_input, $errorstr); // Try conversion UFS->SQL
309//var_dump($errorstr);
310if ($errorstr) {
311 $value = $search_component_params_input;
312
313 $value = preg_replace('/([a-z0-9_\.]+)\s*([!<>=]+|in|notin|like|notlike)\s*/', '\1:\2:', $value); // Clean string 'x < 10' into 'x:<:10' so we can then explode on space to get all AND tests to do
314 $value = preg_replace('/\s*\|\s*/', '|', $value);
315 //var_dump($value);
316
317 $crits = explode(' ', trim($value)); // the string after the name of the field. Explode on each AND
318 $res = '';
319
320 $i1 = 0; // count the nb of and criteria added (all fields / criteria)
321 foreach ($crits as $crit) { // Loop on each AND criteria
322 $crit = trim($crit);
323
324 $i2 = 0; // count the nb of valid criteria added for this first criteria
325 $newres = '';
326 $tmpcrits = explode('|', $crit);
327 $i3 = 0; // count the nb of valid criteria added for this current field
328 foreach ($tmpcrits as $tmpcrit) {
329 if ($tmpcrit !== '0' && empty($tmpcrit)) {
330 continue;
331 }
332 $tmpcrit = trim($tmpcrit);
333 //var_dump($tmpcrit);
334
335 $errorstr = '';
336 $parenthesislevel = 0;
337 $rescheckfilter = dolCheckFilters($tmpcrit, $errorstr, $parenthesislevel);
338 if ($rescheckfilter) {
339 while ($parenthesislevel > 0) {
340 $tmpcrit = preg_replace('/^\‍(/', '', preg_replace('/\‍)$/', '', $tmpcrit));
341 $parenthesislevel--;
342 }
343 }
344
345 $field = preg_replace('/(:[!<>=\s]+:|:in:|:notin:|:like:|:notlike:).*$/', '', $tmpcrit); // the name of the field
346 $tmpcrit = preg_replace('/^.*(:[!<>=\s]+:|:in:|:notin:|:like:|:notlike:)/', '\1', $tmpcrit); // the condition after the name of the field
347 //var_dump($field); var_dump($tmpcrit); var_dump($i3);
348
349 $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
350
351 $operator = '=';
352 $newcrit = preg_replace('/(:[!<>=\s]+:|:in:|:notin:|:like:|:notlike:)/', '', $tmpcrit);
353 //var_dump($newcrit);
354
355 $reg = array();
356 preg_match('/:([!<>=\s]+|in|notin|like|notlike):/', $tmpcrit, $reg);
357 if (!empty($reg[1])) {
358 $operator = $reg[1];
359 }
360 if ($newcrit != '') {
361 if (!preg_match('/^\'[^\']*\'$/', $newcrit)) {
362 $numnewcrit = price2num($newcrit);
363 $newres .= '('.$field.':'.$operator.':'.((float) $numnewcrit).')';
364 } else {
365 $newres .= '('.$field.':'.$operator.":".((string) $newcrit).')';
366 }
367 $i3++; // a criteria was added to string
368 }
369 }
370 $i2++; // a criteria for 1 more field was added to string
371
372 if ($newres) {
373 $res = $res.($res ? ' AND ' : '').($i3 > 1 ? '(' : '').$newres.($i3 > 1 ? ')' : '');
374 }
375 $i1++;
376 }
377 $res = "(".$res.")";
378
379 //var_dump($res);exit;
380 $search_component_params_input = $res;
381}
382
383$arrayofandtagshidden = dolForgeExplodeAnd($search_component_params_hidden);
384$arrayofandtagsinput = dolForgeExplodeAnd($search_component_params_input);
385
386$search_component_params_hidden = implode(' AND ', array_merge($arrayofandtagshidden, $arrayofandtagsinput));
387//var_dump($search_component_params_hidden);
388
389$MAXUNIQUEVALFORGROUP = 20;
390$MAXMEASURESINBARGRAPH = 20;
391$SHOWLEGEND = (isset($SHOWLEGEND) ? $SHOWLEGEND : 1);
392
393$YYYY = substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1).substr($langs->trans("Year"), 0, 1);
394$MM = substr($langs->trans("Month"), 0, 1).substr($langs->trans("Month"), 0, 1);
395$DD = substr($langs->trans("Day"), 0, 1).substr($langs->trans("Day"), 0, 1);
396$HH = substr($langs->trans("Hour"), 0, 1).substr($langs->trans("Hour"), 0, 1);
397$MI = substr($langs->trans("Minute"), 0, 1).substr($langs->trans("Minute"), 0, 1);
398$SS = substr($langs->trans("Second"), 0, 1).substr($langs->trans("Second"), 0, 1);
399
400$arrayoffilterfields = array();
401$arrayofmesures = array();
402$arrayofxaxis = array();
403$arrayofgroupby = array();
404$arrayofyaxis = array();
405$arrayofvaluesforgroupby = array();
406
407$features = '';
408if (!empty($object->element)) {
409 $features = $object->element;
410} else {
411 $features = '';
412}
413if (!empty($object->element_for_permission)) {
414 $features = $object->element_for_permission;
415} else {
416 $features .= (empty($object->module) ? '' : '@'.$object->module);
417}
418
419// $arrayoftype contains several features
420// Test on permission can be done on a given selected feature only
421
422// Security check (do not stop here, get only result to show message later)
423if ($features) {
424 $resultcheck = restrictedArea($user, $features, 0, '', '', 'fk_soc', 'rowid', 0, 1);
425} else {
426 $resultcheck = 1; // No object type selected yet, so there is no data to protect
427}
428
429
430/*
431 * Actions
432 */
433
434// None
435
436
437
438/*
439 * View
440 */
441
442$form = new Form($db);
443$formother = new FormOther($db);
444
445if (!defined('USE_CUSTOM_REPORT_AS_INCLUDE')) {
446 llxHeader('', $langs->transnoentitiesnoconv('CustomReports'), '');
447
448 if (empty($head)) {
449 print dol_get_fiche_head($head, 'customreports', $title, -2, $picto);
450 } else {
451 print dol_get_fiche_head($head, 'customreports', $title, -1, $picto);
452 }
453}
454
455// Define $newarrayoftype that is array of object available for report
456$newarrayoftype = array();
457foreach ($arrayoftype as $key => $val) {
458 if (dol_eval((string) $val['enabled'], 1, 1, '1')) {
459 $newarrayoftype[$key] = $arrayoftype[$key];
460 }
461 if (!empty($val['langs'])) {
462 $langs->load($val['langs']);
463 }
464}
465
466$count = 0;
467$label = '';
468if (array_key_exists($objecttype, $newarrayoftype)) {
469 $label = $langs->trans($newarrayoftype[$objecttype]['label']);
470}
471$arrayoffilterfields = fillArrayOfFilterFields($object, 't', $label, $arrayoffilterfields, 0, $count);
472$arrayoffilterfields = dol_sort_array($arrayoffilterfields, 'position', 'asc', 0, 0, 1);
473
474$count = 0;
475$arrayofmesures = fillArrayOfMeasures($object, 't', $label, $arrayofmesures, 0, $count);
476$arrayofmesures = dol_sort_array($arrayofmesures, 'position', 'asc', 0, 0, 1);
477
478$count = 0;
479$arrayofxaxis = fillArrayOfXAxis($object, 't', $label, $arrayofxaxis, 0, $count);
480$arrayofxaxis = dol_sort_array($arrayofxaxis, 'position', 'asc', 0, 0, 1);
481
482$count = 0;
483$arrayofgroupby = fillArrayOfGroupBy($object, 't', $label, $arrayofgroupby, 0, $count);
484$arrayofgroupby = dol_sort_array($arrayofgroupby, 'position', 'asc', 0, 0, 1);
485
486
487// Check parameters
488if ($action == 'viewgraph') {
489 if (!count($sanitized_search_measures)) {
490 setEventMessages($langs->trans("AtLeastOneMeasureIsRequired"), null, 'warnings');
491 } elseif ($mode == 'graph' && is_array($sanitized_search_xaxis) && count($sanitized_search_xaxis) > 1) {
492 setEventMessages($langs->trans("OnlyOneFieldForXAxisIsPossible"), null, 'warnings');
493 $sanitized_search_xaxis = array(0 => $sanitized_search_xaxis[0]);
494 }
495 if (count($sanitized_search_groupby) >= 2) {
496 setEventMessages($langs->trans("ErrorOnlyOneFieldForGroupByIsPossible"), null, 'warnings');
497 $sanitized_search_groupby = array(0 => $sanitized_search_groupby[0]);
498 }
499 if (!count($sanitized_search_xaxis)) {
500 setEventMessages($langs->trans("AtLeastOneXAxisIsRequired"), null, 'warnings');
501 } elseif ($mode == 'graph' && $search_graph == 'bars' && count($sanitized_search_measures) > $MAXMEASURESINBARGRAPH) {
502 $langs->load("errors");
503 setEventMessages($langs->trans("GraphInBarsAreLimitedToNMeasures", $MAXMEASURESINBARGRAPH), null, 'warnings');
504 $search_graph = 'lines';
505 }
506}
507
508// Get all possible values of fields when a 'group by' is set, and save this into $arrayofvaluesforgroupby
509// $arrayofvaluesforgroupby will be used to forge lael of each grouped series
510if (count($sanitized_search_groupby)) {
511 $fieldtocount = '';
512 foreach ($sanitized_search_groupby as $gkey => $sanitized_gval) {
513 $gvalwithoutprefix = preg_replace('/^[a-z]+\./i', '', $sanitized_gval);
514 $gvalsanitized = preg_replace('/[^a-z0-9\._\-]+/i', '', $sanitized_gval);
515
516 $sanitizedfieldtocount = '';
517
518 if (preg_match('/\-year$/', $gvalsanitized)) {
519 $tmpval = preg_replace('/\-year$/', '', $gvalsanitized);
520 $sanitizedfieldtocount .= 'DATE_FORMAT('.$tmpval.", '%Y')";
521 } elseif (preg_match('/\-month$/', $gvalsanitized)) {
522 $tmpval = preg_replace('/\-month$/', '', $gvalsanitized);
523 $sanitizedfieldtocount .= 'DATE_FORMAT('.$tmpval.", '%Y-%m')";
524 } elseif (preg_match('/\-day$/', $gvalsanitized)) {
525 $tmpval = preg_replace('/\-day$/', '', $gvalsanitized);
526 $sanitizedfieldtocount .= 'DATE_FORMAT('.$tmpval.", '%Y-%m-%d')";
527 } else {
528 $sanitizedfieldtocount = $gvalsanitized;
529 }
530
531 $fieldtocount = $sanitizedfieldtocount;
532 $sql = "SELECT DISTINCT ".$sanitizedfieldtocount." as val"; // $fieldtocount has been sanitized by previous lines as we can't use db->sanitize()
533
534 if (strpos($fieldtocount, 'te') === 0) {
535 $tabletouse = $object->table_element;
536 $tablealiastouse = 'te';
537 if (!empty($arrayofgroupby[$sanitized_gval])) {
538 $tmpval = explode('.', $sanitized_gval);
539 $tabletouse = $arrayofgroupby[$sanitized_gval]['table'];
540 $tablealiastouse = $tmpval[0];
541 }
542 //var_dump($tablealiastouse);exit;
543
544 //$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element."_extrafields as te";
545 $sql .= " FROM ".MAIN_DB_PREFIX.$tabletouse."_extrafields as ".$tablealiastouse;
546 } else {
547 $tabletouse = $object->table_element;
548 $tablealiastouse = 't';
549 if (!empty($arrayofgroupby[$sanitized_gval])) {
550 $tmpval = explode('.', $sanitized_gval);
551 $tabletouse = $arrayofgroupby[$sanitized_gval]['table'];
552 $tablealiastouse = $tmpval[0];
553 }
554 $sql .= " FROM ".MAIN_DB_PREFIX.$tabletouse." as ".$tablealiastouse;
555 }
556
557 // Add a where here keeping only the criteria on $tabletouse
558 /* TODO
559 if ($search_component_params_hidden) {
560 $errormessage = '';
561 $sql .= forgeSQLFromUniversalSearchCriteria($search_component_params_hidden, $errormessage);
562 }
563 */
564 // Add the AND parts of the filter that use only the field of the group by, so the count of distinct values takes them into account
565 if ($search_component_params_hidden) {
566 $fieldofgroupby = preg_replace('/\-(year|month|day)$/', '', $gvalsanitized);
567 $sqlwhere = '';
568 foreach (dolForgeExplodeAnd($search_component_params_hidden) as $andpart) {
569 $matches = array();
570 preg_match_all('/\‍(([a-zA-Z0-9_\.]+):[<>!=insotlke]+:/i', $andpart, $matches);
571 if (!empty($matches[1]) && count(array_unique($matches[1])) == 1 && $matches[1][0] == $fieldofgroupby) {
572 $errormessage = '';
573 $tmpsql = forgeSQLFromUniversalSearchCriteria($andpart, $errormessage, 0, 0, 1);
574 if (!$errormessage) {
575 $sqlwhere .= $tmpsql;
576 }
577 }
578 }
579 if ($sqlwhere) {
580 $sql .= " WHERE 1 = 1".$sqlwhere;
581 }
582 }
583
584 $sql .= " LIMIT ".((int) ($MAXUNIQUEVALFORGROUP + 1));
585
586 //print $sql;
587 $resql = $db->query($sql);
588 if (!$resql) {
589 dol_print_error($db);
590 }
591
592 while ($obj = $db->fetch_object($resql)) {
593 if (is_null($obj->val)) {
594 $keytouse = '__NULL__';
595 $valuetranslated = $langs->transnoentitiesnoconv("NotDefined");
596 } elseif ($obj->val === '') {
597 $keytouse = '';
598 $valuetranslated = $langs->transnoentitiesnoconv("Empty");
599 } else {
600 $keytouse = (string) $obj->val;
601 $valuetranslated = $obj->val;
602 }
603
604 $regs = array();
605 if (isset($object->fields[$gvalwithoutprefix])) {
606 if (!empty($object->fields[$gvalwithoutprefix]['arrayofkeyval'])) {
607 $valuetranslated = $object->fields[$gvalwithoutprefix]['arrayofkeyval'][$obj->val];
608 if (is_null($valuetranslated)) {
609 $valuetranslated = $langs->transnoentitiesnoconv("UndefinedKey");
610 }
611 $valuetranslated = $langs->trans($valuetranslated);
612 } elseif (preg_match('/integer:([^:]+):([^:]+)$/', $object->fields[$gvalwithoutprefix]['type'], $regs)) {
613 $classname = $regs[1];
614 $classpath = $regs[2];
615 dol_include_once($classpath);
616 if (class_exists($classname)) {
617 $tmpobject = new $classname($db);
618 '@phan-var-force CommonObject $tmpobject';
619 $tmpobject->fetch($obj->val);
620 foreach ($tmpobject->fields as $fieldkey => $field) {
621 if ($field['showoncombobox']) {
622 $valuetranslated = $tmpobject->$fieldkey;
623 //if ($valuetranslated == '-') $valuetranslated = $langs->transnoentitiesnoconv("Unknown")
624 break;
625 }
626 }
627 //$valuetranslated = $tmpobject->ref.'eee';
628 }
629 }
630 }
631
632 $arrayofvaluesforgroupby['g_'.$gkey][$keytouse] = $valuetranslated;
633 }
634 // Add also the possible NULL value if field is a parent field that is not a strict join
635 $tmpfield = explode('.', $sanitized_gval);
636 if ($tmpfield[0] != 't' || (isset($object->fields[$tmpfield[1]]) && is_array($object->fields[$tmpfield[1]]) && empty($object->fields[$tmpfield[1]]['notnull']))) {
637 dol_syslog("The group by field ".$sanitized_gval." may be null (because field is null or it is a left join), so we add __NULL__ entry in list of possible values");
638 //var_dump($sanitized_gval); var_dump($object->fields);
639 $arrayofvaluesforgroupby['g_'.$gkey]['__NULL__'] = $langs->transnoentitiesnoconv("NotDefined");
640 }
641
642 if (is_array($arrayofvaluesforgroupby['g_'.$gkey])) {
643 asort($arrayofvaluesforgroupby['g_'.$gkey]);
644 }
645
646 // Add a protection/error to refuse the request if number of differentr values for the group by is higher than $MAXUNIQUEVALFORGROUP
647 if (is_array($arrayofvaluesforgroupby['g_'.$gkey]) && count($arrayofvaluesforgroupby['g_'.$gkey]) > $MAXUNIQUEVALFORGROUP) {
648 $langs->load("errors");
649
650 if (strpos($fieldtocount, 'te') === 0) { // This is a field of an extrafield
651 //if (!empty($extrafields->attributes[$object->table_element]['langfile'][$gvalwithoutprefix])) {
652 // $langs->load($extrafields->attributes[$object->table_element]['langfile'][$gvalwithoutprefix]);
653 //}
654 $keyforlabeloffield = $extrafields->attributes[$object->table_element]['label'][$gvalwithoutprefix];
655 $labeloffield = $langs->transnoentitiesnoconv($keyforlabeloffield);
656 } elseif (strpos($fieldtocount, 't__') === 0) { // This is a field of a foreign key
657 $reg = array();
658 if (preg_match('/^(.*)\.(.*)/', $gvalwithoutprefix, $reg)) {
659 /*
660 $gvalwithoutprefix = preg_replace('/\..*$/', '', $gvalwithoutprefix);
661 $gvalwithoutprefix = preg_replace('/^t__/', '', $gvalwithoutprefix);
662 $keyforlabeloffield = $object->fields[$gvalwithoutprefix]['label'];
663 $labeloffield = $langs->transnoentitiesnoconv($keyforlabeloffield).'-'.$reg[2];
664 */
665 $labeloffield = $arrayofgroupby[$fieldtocount]['labelnohtml'];
666 } else {
667 $labeloffield = 'FK_ISSUE'; // $langs->transnoentitiesnoconv($keyforlabeloffield);
668 }
669 } else { // This is a common field
670 $reg = array();
671 if (preg_match('/^(.*)\-(year|month|day)/', $gvalwithoutprefix, $reg)) {
672 $gvalwithoutprefix = preg_replace('/\-(year|month|day)/', '', $gvalwithoutprefix);
673 $keyforlabeloffield = $object->fields[$gvalwithoutprefix]['label'];
674 $labeloffield = $langs->transnoentitiesnoconv($keyforlabeloffield).'-'.$reg[2];
675 } else {
676 $keyforlabeloffield = $object->fields[$gvalwithoutprefix]['label'];
677 $labeloffield = $langs->transnoentitiesnoconv($keyforlabeloffield);
678 }
679 }
680 //var_dump($labeloffield);
681 setEventMessages($langs->transnoentitiesnoconv("ErrorTooManyDifferentValueForSelectedGroupBy", (string) $MAXUNIQUEVALFORGROUP, (string) $labeloffield), null, 'warnings');
682 $sanitized_search_groupby = array();
683 }
684
685 $db->free($resql);
686 }
687}
688//var_dump($arrayofvaluesforgroupby);exit;
689
690
691if (!$resultcheck) {
692 print '<div class="error">';
693 print $langs->trans("NotEnoughPermissions");
694 print '</div>';
695}
696
697
698
699//$tmparray = dol_getdate(dol_now());
700//$endyear = $tmparray['year'];
701//$endmonth = $tmparray['mon'];
702//$datelastday = dol_get_last_day($endyear, $endmonth, 1);
703//$startyear = $endyear - 2;
704
705$param = '';
706
707
708if (!defined('MAIN_CUSTOM_REPORT_KEEP_GRAPH_ONLY')) {
709 print '<form method="post" action="'.$_SERVER['PHP_SELF'].'" autocomplete="off">';
710 print '<input type="hidden" name="token" value="'.newToken().'">';
711 print '<input type="hidden" name="action" value="viewgraph">';
712 print '<input type="hidden" name="tabfamily" value="'.(string) $tabfamily.'">';
713
714 $viewmode = '';
715
716 $viewmode .= '<div class="divadvancedsearchfield">';
717 $arrayofgraphs = array('bars' => 'Bars', 'lines' => 'Lines'); // also 'pies'
718 $viewmode .= '<div class="inline-block opacitymedium"><span class="fas fa-chart-area paddingright" title="'.$langs->trans("Graph").'"></span>'.$langs->trans("Graph").'</div> ';
719 // The class onrightofpage allows to align the popup list on the right of the select component (so it can't go out of screen on the right).
720 // For this the select must also be inside a parent with class parentonrightofpage (and a fixed width to avoid the parent to be enlarged when the dropdown list is open).
721 $viewmode .= '<div class="inline-block width100 parentonrightofpage">';
722 $viewmode .= $form->selectarray('search_graph', $arrayofgraphs, $search_graph, 0, 0, 0, '', 1, 0, 0, '', 'graphtype width100 onrightofpage');
723 $viewmode .= '</div>';
724 $viewmode .= '</div>';
725
726 $num = 0;
727 $massactionbutton = '';
728 $nav = '';
729 $newcardbutton = '';
730 $limit = 0;
731
732 print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, -1, 'object_action', 0, $nav.'<span class="marginleftonly"></span>'.$newcardbutton, '', $limit, 1, 0, 1, $viewmode);
733
734
735 foreach ($newarrayoftype as $tmpkey => $tmpval) {
736 $newarrayoftype[$tmpkey]['data-html'] = img_picto('', $tmpval['picto'], 'class="pictofixedwidth"').$langs->trans($tmpval['label']);
737 $newarrayoftype[$tmpkey]['label'] = $langs->trans($tmpval['label']);
738 }
739
740 print '<div class="liste_titre liste_titre_bydiv liste_titre_bydiv_inlineblock liste_titre_bydiv_nothingafter centpercent">';
741
742 // Select object
743 print '<div class="divadvancedsearchfield floatnone">';
744 //print '<div class="inline-block"><span class="opacitymedium">'.$langs->trans("StatisticsOn").'</span></div> ';
745 print img_picto('', 'generic', 'class="paddingright pictofixedwidth linkobject boxfilter"');
746 print $form->selectarray('objecttype', $newarrayoftype, $objecttype, $langs->trans("StatisticsOn"), 0, 0, '', 1, 0, 0, '', 'minwidth250 customreportsobjecttype noborderfocus', 1, '', 0, 1);
747 if (empty($conf->use_javascript_ajax)) {
748 print '<input type="submit" class="button buttongen button-save nomargintop" name="changeobjecttype" value="'.$langs->trans("Refresh").'">';
749 } else {
750 print '<!-- js code to reload page with good object type -->
751 <script nonce="'.getNonce().'" type="text/javascript">
752 jQuery(document).ready(function() {
753 jQuery("#objecttype").change(function() {
754 console.log("Reload for "+jQuery("#objecttype").val());
755 location.href = "'.$_SERVER["PHP_SELF"].'?objecttype="+jQuery("#objecttype").val()+"&focusonfilter=1'.($tabfamily ? '&tabfamily='.urlencode($tabfamily) : '').(GETPOSTINT('show_search_component_params_hidden') ? '&show_search_component_params_hidden='.((int) GETPOSTINT('show_search_component_params_hidden')) : '').'";
756 });
757 });
758 </script>';
759 }
760 // When no object type is selected, the focus goes on the combo of object types
761 if (empty($objecttype)) {
762 print '<script nonce="'.getNonce().'">jQuery(document).ready(function() {
763 var objecttypeselection = jQuery("#objecttype").next(".select2").find(".select2-selection");
764 (objecttypeselection.length ? objecttypeselection : jQuery("#objecttype")).trigger("focus");
765 });</script>';
766 }
767 print '</div><div class="clearboth"></div>';
768
769 // The components to select the filter, measures, X axis and group by are shown only once an object type is selected
770 if (!empty($newarrayoftype) && !empty($object)) {
771 // Filter (you can use param &show_search_component_params_hidden=1 for debug)
772 if (!empty($object)) {
773 print '<div class="divadvancedsearchfield divadvancedsearchfieldusf">';
774 print $form->searchComponent(array($object->element => $object->fields), $search_component_params, array(), $search_component_params_hidden, $arrayoffilterfields);
775 print '</div>';
776 // After a change of the object type, the page is reloaded with focusonfilter=1 so the focus goes on the filter
777 if (GETPOSTINT('focusonfilter')) {
778 print '<script nonce="'.getNonce().'">jQuery(document).ready(function() { jQuery("#search_component_params_input").trigger("focus"); });</script>';
779 }
780 }
781
782 // YAxis (add measures into array)
783 $count = 0;
784 //var_dump($arrayofmesures);
785 print '<div class="divadvancedsearchfield clearboth">';
786 print '<!-- measureComponent -->'."\n";
787 print '<div class="divadvancedsearchfieldcomp centpercent inline-block">';
788 print '<span class="inline-block"><span class="fas fa-ruler-combined paddingright pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("Measures")).'"></span><span class="fas fa-caret-left caretleftaxis" title="'.dol_escape_htmltag($langs->trans("Measures")).'"></span></span>';
789 $simplearrayofmesures = array();
790 foreach ($arrayofmesures as $key => $val) {
791 $simplearrayofmesures[$key] = $arrayofmesures[$key]['label'];
792 }
793 if (empty($conf->use_javascript_ajax)) {
794 print $form->multiselectarray('search_measures', $simplearrayofmesures, $sanitized_search_measures, 0, 0, 'minwidth200 maxwidth300 combolargelist', 1, 0, '', '', $langs->transnoentitiesnoconv("Measures")); // Fill the array $arrayofmeasures with possible fields
795 } else {
796 print customReportsSelectMeasures('search_measures', $arrayofmesures, $sanitized_search_measures, $langs->transnoentitiesnoconv("Measures"));
797 }
798 print '</div>';
799 print '</div>';
800
801 // XAxis
802 $count = 0;
803 print '<div class="divadvancedsearchfield">';
804 print '<div class="inline-block"><span class="fas fa-ruler-combined paddingright pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("XAxis")).'"></span><span class="fas fa-caret-down caretdownaxis" title="'.dol_escape_htmltag($langs->trans("XAxis")).'"></span></div>';
805 //var_dump($arrayofxaxis);
806 if (empty($conf->use_javascript_ajax)) {
807 print $formother->selectXAxisField($object, $sanitized_search_xaxis, $arrayofxaxis, $langs->trans("XAxis"), 'minwidth200 maxwidth300 combolargelist'); // Fill the array $arrayofxaxis with possible fields
808 } else {
809 print customReportsSelectXAxis('search_xaxis', $arrayofxaxis, $sanitized_search_xaxis, $langs->transnoentitiesnoconv("XAxis"));
810 }
811 print '</div>';
812
813 // Group by
814 $count = 0;
815 print '<div class="divadvancedsearchfield">';
816 print '<div class="inline-block opacitymedium"><span class="fas fa-ruler-horizontal paddingright pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("GroupBy")).'"></span></div>';
817 if (empty($conf->use_javascript_ajax)) {
818 print $formother->selectGroupByField($object, $sanitized_search_groupby, $arrayofgroupby, 'minwidth200 maxwidth300 combolargelist', $langs->trans("GroupBy")); // Fill the array $arrayofgroupby with possible fields
819 } else {
820 print customReportsSelectGroupBy('search_groupby', $arrayofgroupby, $sanitized_search_groupby, $langs->transnoentitiesnoconv("GroupBy"));
821 }
822 print '</div>';
823 }
824
825 if ($mode == 'grid' && !empty($object)) {
826 // YAxis
827 print '<div class="divadvancedsearchfield">';
828 foreach ($object->fields as $key => $val) {
829 if (empty($val['measure']) && (!isset($val['enabled']) || dol_eval((string) $val['enabled'], 1, 1, '1'))) {
830 if (in_array($key, array('id', 'rowid', 'entity', 'last_main_doc', 'extraparams'))) {
831 continue;
832 }
833 if (preg_match('/^fk_/', $key)) {
834 continue;
835 }
836 if (in_array($val['type'], array('html', 'text'))) {
837 continue;
838 }
839 if (in_array($val['type'], array('timestamp', 'date', 'datetime'))) {
840 $arrayofyaxis['t.'.$key.'-year'] = array(
841 'label' => $langs->trans($val['label']).' ('.$YYYY.')',
842 'position' => $val['position'],
843 'table' => $object->table_element
844 );
845 $arrayofyaxis['t.'.$key.'-month'] = array(
846 'label' => $langs->trans($val['label']).' ('.$YYYY.'-'.$MM.')',
847 'position' => $val['position'],
848 'table' => $object->table_element
849 );
850 $arrayofyaxis['t.'.$key.'-day'] = array(
851 'label' => $langs->trans($val['label']).' ('.$YYYY.'-'.$MM.'-'.$DD.')',
852 'position' => $val['position'],
853 'table' => $object->table_element
854 );
855 } else {
856 $arrayofyaxis['t.'.$key] = array(
857 'label' => $val['label'],
858 'position' => (int) $val['position'],
859 'table' => $object->table_element
860 );
861 }
862 }
863 }
864 // Add measure from extrafields
865 if ($object->isextrafieldmanaged) {
866 foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
867 if (!empty($extrafields->attributes[$object->table_element]['totalizable'][$key]) && (!isset($extrafields->attributes[$object->table_element]['enabled'][$key]) || dol_eval((string) $extrafields->attributes[$object->table_element]['enabled'][$key], 1, 1, '1'))) {
868 $arrayofyaxis['te.'.$key] = array(
869 'label' => $extrafields->attributes[$object->table_element]['label'][$key],
870 'position' => (int) $extrafields->attributes[$object->table_element]['pos'][$key],
871 'table' => $object->table_element
872 );
873 }
874 }
875 }
876 $arrayofyaxis = dol_sort_array($arrayofyaxis, 'position');
877 $arrayofyaxislabel = array();
878 foreach ($arrayofyaxis as $key => $val) {
879 $arrayofyaxislabel[$key] = $val['label'];
880 }
881 print '<div class="inline-block opacitymedium"><span class="fas fa-ruler-vertical paddingright" title="'.$langs->trans("YAxis").'"></span>'.$langs->trans("YAxis").'</div> ';
882 print $form->multiselectarray('search_yaxis', $arrayofyaxislabel, $sanitized_search_yaxis != null ? $sanitized_search_yaxis : array(), 0, 0, 'minwidth100', 1);
883 print '</div>';
884 }
885
886 if (!empty($newarrayoftype) && !empty($object)) {
887 print '<div class="divadvancedsearchfield">';
888 print '<button type="submit" class="butAction nomargintop customreportsrefresh">'.$langs->trans("Refresh").'</button>';
889 print '</div>';
890 }
891
892 print '</div>';
893 print '</form>';
894}
895
896// Generate the SQL request
897$sql = '';
898if (!empty($sanitized_search_measures) && !empty($sanitized_search_xaxis)) {
899 $errormessage = '';
900
901 $fieldid = 'rowid';
902
903 $sql = "SELECT ";
904 foreach ($sanitized_search_xaxis as $sql_key => $sql_val) {
905 if (preg_match('/\-year$/', $sql_val)) {
906 $sql_tmpval = preg_replace('/\-year$/', '', $sql_val);
907 $sql .= "DATE_FORMAT(".$sql_tmpval.", '%Y') as x_".$sql_key.', ';
908 } elseif (preg_match('/\-month$/', $sql_val)) {
909 $sql_tmpval = preg_replace('/\-month$/', '', $sql_val);
910 $sql .= "DATE_FORMAT(".$sql_tmpval.", '%Y-%m') as x_".$sql_key.', ';
911 } elseif (preg_match('/\-day$/', $sql_val)) {
912 $sql_tmpval = preg_replace('/\-day$/', '', $sql_val);
913 $sql .= "DATE_FORMAT(".$sql_tmpval.", '%Y-%m-%d') as x_".$sql_key.', ';
914 } else {
915 $sql .= $sql_val." as x_".$sql_key.", ";
916 }
917 }
918 if (!empty($sanitized_search_groupby)) {
919 foreach ($sanitized_search_groupby as $sql_key => $sql_val) {
920 if (preg_match('/\-year$/', $sql_val)) {
921 $sql_tmpval = preg_replace('/\-year$/', '', $sql_val);
922 $sql .= "DATE_FORMAT(".$sql_tmpval.", '%Y') as g_".$sql_key.', ';
923 } elseif (preg_match('/\-month$/', $sql_val)) {
924 $sql_tmpval = preg_replace('/\-month$/', '', $sql_val);
925 $sql .= "DATE_FORMAT(".$sql_tmpval.", '%Y-%m') as g_".$sql_key.', ';
926 } elseif (preg_match('/\-day$/', $sql_val)) {
927 $sql_tmpval = preg_replace('/\-day$/', '', $sql_val);
928 $sql .= "DATE_FORMAT(".$sql_tmpval.", '%Y-%m-%d') as g_".$sql_key.', ';
929 } else {
930 $sql .= $sql_val." as g_".$sql_key.", ";
931 }
932 }
933 }
934 foreach ($sanitized_search_measures as $sql_key => $sql_val) {
935 if ($sql_val == 't.count') {
936 $sql .= "COUNT(t.".$fieldid.") as y_".$sql_key.', ';
937 } elseif (preg_match('/\-sum$/', $sql_val)) {
938 $sql_tmpval = preg_replace('/\-sum$/', '', $sql_val);
939 $sql .= "SUM(".$db->ifsql($sql_tmpval.' IS NULL', '0', $sql_tmpval).") as y_".$sql_key.", ";
940 } elseif (preg_match('/\-average$/', $sql_val)) {
941 $sql_tmpval = preg_replace('/\-average$/', '', $sql_val);
942 $sql .= "AVG(".$db->ifsql($sql_tmpval.' IS NULL', '0', $sql_tmpval).") as y_".$sql_key.", ";
943 } elseif (preg_match('/\-min$/', $sql_val)) {
944 $sql_tmpval = preg_replace('/\-min$/', '', $sql_val);
945 $sql .= "MIN(".$db->ifsql($sql_tmpval.' IS NULL', '0', $sql_tmpval).") as y_".$sql_key.", ";
946 } elseif (preg_match('/\-max$/', $sql_val)) {
947 $sql_tmpval = preg_replace('/\-max$/', '', $sql_val);
948 $sql .= "MAX(".$db->ifsql($sql_tmpval.' IS NULL', '0', $sql_tmpval).") as y_".$sql_key.", ";
949 } elseif (preg_match('/\-stddevpop$/', $sql_val)) {
950 $sql_tmpval = preg_replace('/\-stddevpop$/', '', $sql_val);
951 $sql .= "STDDEV_POP(".$db->ifsql($sql_tmpval.' IS NULL', '0', $sql_tmpval).") as y_".$sql_key.", ";
952 }
953 }
954 $sql = preg_replace('/,\s*$/', '', $sql);
955 $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
956 // Add measure from extrafields
957 if ($object->isextrafieldmanaged) {
958 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as te ON te.fk_object = t.".$fieldid;
959 }
960 // Add table for link on multientity
961 if ($object->ismultientitymanaged) { // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
962 if ($object->ismultientitymanaged == 1) {
963 // No table to add here
964 } else {
965 $tmparray = explode('@', $object->ismultientitymanaged);
966 $sql .= " INNER JOIN ".MAIN_DB_PREFIX.$db->sanitize($tmparray[1])." as parenttableforentity ON t.".$db->sanitize($tmparray[0])." = parenttableforentity.rowid";
967 $sql .= " AND parenttableforentity.entity IN (".getEntity($tmparray[1]).")";
968 }
969 }
970
971 // Init the list of tables added. We include by default always the main table.
972 $listoftablesalreadyadded = array('t' => 't'); // List of table aliases already joined (the same table may be joined several times with different aliases)
973
974 // Add LEFT JOIN for all parent tables mentioned into the Xaxis
975 //var_dump($arrayofxaxis); var_dump($sanitized_search_xaxis);
976 foreach ($sanitized_search_xaxis as $key => $val) {
977 if (!empty($arrayofxaxis[$val])) {
978 $tmpval = explode('.', $val);
979 //var_dump($arrayofgroupby);
980 $tmpforloop = explode(',', $arrayofxaxis[$val]['tablefromt']);
981 foreach ($tmpforloop as $tmptableandalias) {
982 list($tmptable, $tmptablealias) = array_pad(explode('=', $tmptableandalias, 2), 2, '');
983 if (! in_array($tmptablealias, $listoftablesalreadyadded)) { // We do not add join for main table and tables already added
984 $tmpforexplode = explode('__', $tmptablealias);
985 $endpart = end($tmpforexplode);
986 $parenttableandfield = preg_replace('/__'.$endpart.'$/', '', $tmptablealias).'.'.$endpart;
987
988 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable." as ".$db->sanitize($tmptablealias)." ON ".$db->sanitize($parenttableandfield)." = ".$db->sanitize($tmptablealias).".rowid";
989 $listoftablesalreadyadded[$tmptablealias] = $tmptablealias;
990
991 if (preg_match('/^te/', $tmpval[0]) && preg_replace('/^t_/', 'te_', $tmptablealias) == $tmpval[0]) {
992 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable."_extrafields as ".$db->sanitize($tmpval[0])." ON ".$db->sanitize($tmpval[0]).".fk_object = ".$db->sanitize($tmptablealias).".rowid";
993 $listoftablesalreadyadded[$tmptablealias] = $tmptablealias;
994 }
995 }
996 }
997 } else {
998 $errormessage = 'Found a key into search_xaxis not found into arrayofxaxis';
999 }
1000 }
1001
1002 // Add LEFT JOIN for all parent tables mentioned into the Group by
1003 //var_dump($arrayofgroupby); var_dump($sanitized_search_groupby);
1004 foreach ($sanitized_search_groupby as $key => $val) {
1005 if (!empty($arrayofgroupby[$val])) {
1006 $tmpval = explode('.', $val);
1007 //var_dump($arrayofgroupby[$val]); var_dump($tmpval);
1008 $tmpforloop = explode(',', $arrayofgroupby[$val]['tablefromt']);
1009 foreach ($tmpforloop as $tmptableandalias) {
1010 list($tmptable, $tmptablealias) = array_pad(explode('=', $tmptableandalias, 2), 2, '');
1011 if (! in_array($tmptablealias, $listoftablesalreadyadded)) { // We do not add join for main table and tables already added
1012 $tmpforexplode = explode('__', $tmptablealias);
1013 $endpart = end($tmpforexplode);
1014 $parenttableandfield = preg_replace('/__'.$endpart.'$/', '', $tmptablealias).'.'.$endpart;
1015
1016 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable." as ".$db->sanitize($tmptablealias)." ON ".$db->sanitize($parenttableandfield)." = ".$db->sanitize($tmptablealias).".rowid";
1017 $listoftablesalreadyadded[$tmptablealias] = $tmptablealias;
1018
1019 if (preg_match('/^te/', $tmpval[0]) && preg_replace('/^t_/', 'te_', $tmptablealias) == $tmpval[0]) {
1020 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable."_extrafields as ".$db->sanitize($tmpval[0])." ON ".$db->sanitize($tmpval[0]).".fk_object = ".$db->sanitize($tmptablealias).".rowid";
1021 $listoftablesalreadyadded[$tmptablealias] = $tmptablealias;
1022 }
1023 }
1024 }
1025 } else {
1026 $errormessage = 'Found a key into search_groupby not found into arrayofgroupby';
1027 }
1028 }
1029
1030 // Add LEFT JOIN for all parent tables mentioned into the Yaxis
1031 //var_dump($arrayofgroupby); var_dump($sanitized_search_groupby);
1032 foreach ($sanitized_search_measures as $key => $val) {
1033 if (!empty($arrayofmesures[$val])) {
1034 $tmpval = explode('.', $val);
1035 //var_dump($arrayofgroupby);
1036 $tmpforloop = explode(',', $arrayofmesures[$val]['tablefromt']);
1037 foreach ($tmpforloop as $tmptableandalias) {
1038 list($tmptable, $tmptablealias) = array_pad(explode('=', $tmptableandalias, 2), 2, '');
1039 if (! in_array($tmptablealias, $listoftablesalreadyadded)) { // We do not add join for main table and tables already added
1040 $tmpforexplode = explode('__', $tmptablealias);
1041 $endpart = end($tmpforexplode);
1042 $parenttableandfield = preg_replace('/__'.$endpart.'$/', '', $tmptablealias).'.'.$endpart;
1043
1044 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable." as ".$db->sanitize($tmptablealias)." ON ".$db->sanitize($parenttableandfield)." = ".$db->sanitize($tmptablealias).".rowid";
1045 $listoftablesalreadyadded[$tmptablealias] = $tmptablealias;
1046
1047 if (preg_match('/^te/', $tmpval[0]) && preg_replace('/^t_/', 'te_', $tmptablealias) == $tmpval[0]) {
1048 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable."_extrafields as ".$db->sanitize($tmpval[0])." ON ".$db->sanitize($tmpval[0]).".fk_object = ".$db->sanitize($tmptablealias).".rowid";
1049 $listoftablesalreadyadded[$tmptablealias] = $tmptablealias;
1050 }
1051 }
1052 }
1053 } else {
1054 $errormessage = 'Found a key into search_measures not found into arrayofmesures';
1055 }
1056 }
1057
1058 // Add LEFT JOIN for all tables mentioned into filter
1059 if (!empty($search_component_params_hidden)) {
1060 // Get all fields used into the filter
1061 $matches = array();
1062 preg_match_all('/\b(t[\w]*_[\w]*)\.(\w+(-\w+)?)/', $search_component_params_hidden, $matches);
1063 $fieldsUsedInFilter = array_unique($matches[0]);
1064
1065 // Remove fields used before to avoid double join
1066 $fieldsToRemove = array_merge($sanitized_search_measures, $sanitized_search_groupby, $sanitized_search_xaxis);
1067 $fieldsUsedInFilter = array_diff($fieldsUsedInFilter, $fieldsToRemove);
1068
1069 foreach ($fieldsUsedInFilter as $key => $val) {
1070 if (!empty($arrayoffilterfields[$val])) {
1071 $tmpval = explode('.', $val);
1072 $tmpforloop = explode(',', $arrayoffilterfields[$val]['tablefromt']);
1073 foreach ($tmpforloop as $tmptableandalias) {
1074 list($tmptable, $tmptablealias) = array_pad(explode('=', $tmptableandalias, 2), 2, '');
1075 if (! in_array($tmptablealias, $listoftablesalreadyadded)) { // We do not add join for main table and tables already added
1076 $tmpforexplode = explode('__', $tmptablealias);
1077 $endpart = end($tmpforexplode);
1078 $parenttableandfield = preg_replace('/__'.$endpart.'$/', '', $tmptablealias).'.'.$endpart;
1079
1080 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable." as ".$db->sanitize($tmptablealias)." ON ".$db->sanitize($parenttableandfield)." = ".$db->sanitize($tmptablealias).".rowid";
1081 $listoftablesalreadyadded[$tmptablealias] = $tmptablealias;
1082
1083 if (preg_match('/^te/', $tmpval[0]) && preg_replace('/^t_/', 'te_', $tmptablealias) == $tmpval[0]) {
1084 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmptable."_extrafields as ".$db->sanitize($tmpval[0])." ON ".$db->sanitize($tmpval[0]).".fk_object = ".$db->sanitize($tmptablealias).".rowid";
1085 $listoftablesalreadyadded[$tmptablealias] = $tmptablealias;
1086 }
1087 }
1088 }
1089 } else {
1090 $errormessage = 'Found a key into search_filterfields not found into arrayoffilterfields';
1091 }
1092 }
1093 }
1094
1095 $sql .= " WHERE 1 = 1";
1096 if ($object->ismultientitymanaged == 1) { // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
1097 $sql .= " AND t.entity IN (".getEntity($object->element).")";
1098 }
1099 // Add the where here
1100 if ($search_component_params_hidden) {
1101 $sql .= forgeSQLFromUniversalSearchCriteria($search_component_params_hidden, $errormessage, 0, 0, 1);
1102
1103 // Replace date values by $db->idate(dol_mktime(...)) @phan-suppress-next-line SqlInjection
1104 $sql = preg_replace_callback(
1105 "/(\w+)\.(\w+)\s*(=|!=|<>|<|>|<=|>=)\s*'(\d{4})-(\d{2})-(\d{2})'/",
1110 static function (array $matches): string {
1111 global $db;
1112 '@phan-var-force DoliDB $db';
1113 $column = $matches[1] . '.' . $matches[2];
1114 $operator = $matches[3];
1115 $year = (int) $matches[4];
1116 $month = (int) $matches[5];
1117 $day = (int) $matches[6];
1118
1119 $startOfDay = $db->idate(dol_mktime(0, 0, 0, $month, $day, $year));
1120 $endOfDay = $db->idate(dol_mktime(23, 59, 59, $month, $day, $year));
1121
1122 switch ($operator) {
1123 case "=":
1124 return "($column >= '$startOfDay' AND $column <= '$endOfDay')";
1125 case "!=":
1126 case "<>":
1127 return "NOT ($column >= '$startOfDay' AND $column <= '$endOfDay')";
1128 case "<":
1129 return "$column < '$startOfDay'";
1130 case ">":
1131 return "$column > '$endOfDay'";
1132 case "<=":
1133 return "$column <= '$endOfDay'";
1134 case ">=":
1135 return "$column >= '$startOfDay'";
1136 default:
1137 return "";
1138 }
1139 },
1140 $sql
1141 );
1142 }
1143 $sql .= " GROUP BY ";
1144 foreach ($sanitized_search_xaxis as $key => $sanitized_val) {
1145 if (preg_match('/\-year$/', $sanitized_val)) {
1146 $sanitized_tmpval = preg_replace('/\-year$/', '', $sanitized_val);
1147 $sql .= "DATE_FORMAT(".$sanitized_tmpval.", '%Y'), ";
1148 } elseif (preg_match('/\-month$/', $sanitized_val)) {
1149 $sanitized_tmpval = preg_replace('/\-month$/', '', $sanitized_val);
1150 $sql .= "DATE_FORMAT(".$sanitized_tmpval.", '%Y-%m'), ";
1151 } elseif (preg_match('/\-day$/', $sanitized_val)) {
1152 $sanitized_tmpval = preg_replace('/\-day$/', '', $sanitized_val);
1153 $sql .= "DATE_FORMAT(".$sanitized_tmpval.", '%Y-%m-%d'), ";
1154 } else {
1155 $sql .= $sanitized_val.", ";
1156 }
1157 }
1158 if (!empty($sanitized_search_groupby)) {
1159 foreach ($sanitized_search_groupby as $key => $sanitized_val) {
1160 if (preg_match('/\-year$/', $sanitized_val)) {
1161 $sanitized_tmpval = preg_replace('/\-year$/', '', $sanitized_val);
1162 $sql .= "DATE_FORMAT(".$sanitized_tmpval.", '%Y'), ";
1163 } elseif (preg_match('/\-month$/', $sanitized_val)) {
1164 $sanitized_tmpval = preg_replace('/\-month$/', '', $sanitized_val);
1165 $sql .= "DATE_FORMAT(".$sanitized_tmpval.", '%Y-%m'), ";
1166 } elseif (preg_match('/\-day$/', $sanitized_val)) {
1167 $sanitized_tmpval = preg_replace('/\-day$/', '', $sanitized_val);
1168 $sql .= "DATE_FORMAT(".$sanitized_tmpval.", '%Y-%m-%d'), ";
1169 } else {
1170 $sql .= $sanitized_val.', ';
1171 }
1172 }
1173 }
1174 $sql = preg_replace('/,\s*$/', '', $sql);
1175 $sql .= ' ORDER BY ';
1176 foreach ($sanitized_search_xaxis as $key => $sanitized_val) {
1177 if (preg_match('/\-year$/', $sanitized_val)) {
1178 $sanitized_tmpval = preg_replace('/\-year$/', '', $sanitized_val);
1179 $sql .= "DATE_FORMAT(".$sanitized_tmpval.", '%Y'), ";
1180 } elseif (preg_match('/\-month$/', $sanitized_val)) {
1181 $sanitized_tmpval = preg_replace('/\-month$/', '', $sanitized_val);
1182 $sql .= "DATE_FORMAT(".$sanitized_tmpval.", '%Y-%m'), ";
1183 } elseif (preg_match('/\-day$/', $sanitized_val)) {
1184 $sanitized_tmpval = preg_replace('/\-day$/', '', $sanitized_val);
1185 $sql .= "DATE_FORMAT(".$sanitized_tmpval.", '%Y-%m-%d'), ";
1186 } else {
1187 $sql .= $sanitized_val.', ';
1188 }
1189 }
1190 if (!empty($sanitized_search_groupby)) {
1191 foreach ($sanitized_search_groupby as $key => $sanitized_val) {
1192 if (preg_match('/\-year$/', $sanitized_val)) {
1193 $sanitized_tmpval = preg_replace('/\-year$/', '', $sanitized_val);
1194 $sql .= "DATE_FORMAT(".$sanitized_tmpval.", '%Y'), ";
1195 } elseif (preg_match('/\-month$/', $sanitized_val)) {
1196 $sanitized_tmpval = preg_replace('/\-month$/', '', $sanitized_val);
1197 $sql .= "DATE_FORMAT(".$sanitized_tmpval.", '%Y-%m'), ";
1198 } elseif (preg_match('/\-day$/', $sanitized_val)) {
1199 $sanitized_tmpval = preg_replace('/\-day$/', '', $sanitized_val);
1200 $sql .= "DATE_FORMAT(".$sanitized_tmpval.", '%Y-%m-%d'), ";
1201 } else {
1202 $sql .= $sanitized_val.', ';
1203 }
1204 }
1205 }
1206 $sql = preg_replace('/,\s*$/', '', $sql);
1207
1208 // Can overwrite the SQL with a custom SQL string (when used as an include)
1209 if (!empty($customsql)) {
1210 $sql = $customsql;
1211 }
1212}
1213//print $sql;
1214
1215if ($errormessage) {
1216 print '<div class="warning">';
1217 print dol_escape_htmltag($errormessage);
1218 //print '<br>'.dol_escape_htmltag('SQL is '.$sql);
1219 print '</div>';
1220 $sql = '';
1221}
1222
1223$legend = array();
1224foreach ($sanitized_search_measures as $key => $val) {
1225 $legend[] = $langs->trans($arrayofmesures[$val]['label']);
1226}
1227
1228$useagroupby = count($sanitized_search_groupby);
1229//var_dump($useagroupby);
1230//var_dump($arrayofvaluesforgroupby);
1231
1232// Execute the SQL request
1233$totalnbofrecord = 0;
1234$data = array();
1235if ($sql) {
1236 $resql = $db->query($sql);
1237 if (!$resql) {
1238 print '<div class="warning">';
1239 print dol_escape_htmltag($db->lasterror());
1240 //print '<br>'.dol_escape_htmltag('SQL is '.$sql);
1241 print '</div>';
1242 } else {
1243 $ifetch = 0;
1244 $xi = 0;
1245 $oldlabeltouse = '';
1246 while ($obj = $db->fetch_object($resql)) {
1247 $ifetch++;
1248 if ($useagroupby) {
1249 $xval = $sanitized_search_xaxis[0];
1250 $fieldforxkey = 'x_0';
1251 $xlabel = $obj->$fieldforxkey;
1252 $xvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $xval);
1253
1254 // Define $xlabel
1255 if (!empty($object->fields[$xvalwithoutprefix]['arrayofkeyval'])) {
1256 $xlabel = $object->fields[$xvalwithoutprefix]['arrayofkeyval'][$obj->$fieldforxkey];
1257 }
1258 $labeltouse = (($xlabel || $xlabel == '0') ? dol_trunc($xlabel, 20, 'middle') : ($xlabel === '' ? $langs->transnoentitiesnoconv("Empty") : $langs->transnoentitiesnoconv("NotDefined")));
1259
1260 if ($oldlabeltouse !== '' && ($labeltouse != $oldlabeltouse)) {
1261 $xi++; // Increase $xi
1262 }
1263 //var_dump($labeltouse.' '.$oldlabeltouse.' '.$xi);
1264 $oldlabeltouse = $labeltouse;
1265
1266 /* Example of value for $arrayofvaluesforgroupby
1267 * array (size=1)
1268 * 'g_0' =>
1269 * array (size=6)
1270 * 0 => string '0' (length=1)
1271 * '' => string 'Empty' (length=5)
1272 * '__NULL__' => string 'Not defined' (length=11)
1273 * 'done' => string 'done' (length=4)
1274 * 'processing' => string 'processing' (length=10)
1275 * 'undeployed' => string 'undeployed' (length=10)
1276 */
1277 foreach ($sanitized_search_measures as $key => $val) {
1278 $gi = 0;
1279 foreach ($sanitized_search_groupby as $gkey => $gval) {
1280 //var_dump('*** Fetch #'.$ifetch.' for labeltouse='.$labeltouse.' measure number '.$key.' and group g_'.$gi);
1281 //var_dump($arrayofvaluesforgroupby);
1282 foreach ($arrayofvaluesforgroupby['g_'.$gi] as $gvaluepossiblekey => $gvaluepossiblelabel) {
1283 $ykeysuffix = $gvaluepossiblelabel;
1284 $gvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $gval);
1285
1286 $fieldfory = 'y_'.$key;
1287 $fieldforg = 'g_'.$gi;
1288 $fieldforybis = 'y_'.$key.'_'.$ykeysuffix;
1289 //var_dump('gvaluepossiblekey='.$gvaluepossiblekey.' gvaluepossiblelabel='.$gvaluepossiblelabel.' ykeysuffix='.$ykeysuffix.' gval='.$gval.' gvalwithoutsuffix='.$gvalwithoutprefix);
1290 //var_dump('fieldforg='.$fieldforg.' obj->$fieldforg='.$obj->$fieldforg.' fieldfory='.$fieldfory.' obj->$fieldfory='.$obj->$fieldfory.' fieldforybis='.$fieldforybis);
1291
1292 if (!array_key_exists($xi, $data)) {
1293 $data[$xi] = array();
1294 }
1295
1296 if (!array_key_exists('label', $data[$xi])) {
1297 $data[$xi] = array();
1298 $data[$xi]['label'] = $labeltouse;
1299 }
1300
1301 $objfieldforg = $obj->$fieldforg;
1302 if (is_null($objfieldforg)) {
1303 $objfieldforg = '__NULL__';
1304 }
1305
1306 if ($gvaluepossiblekey == '0') { // $gvaluepossiblekey can have type int or string. So we create a special if, used when value is '0'
1307 //var_dump($objfieldforg.' == \'0\' -> '.($objfieldforg == '0'));
1308 if ($objfieldforg == '0') {
1309 // The record we fetch is for this group
1310 $data[$xi][$fieldforybis] = $obj->$fieldfory;
1311 } elseif (!isset($data[$xi][$fieldforybis])) {
1312 // The record we fetch is not for this group
1313 $data[$xi][$fieldforybis] = '0';
1314 }
1315 } else {
1316 //var_dump((string) $objfieldforg.' === '.(string) $gvaluepossiblekey.' -> '.((string) $objfieldforg === (string) $gvaluepossiblekey));
1317 if ((string) $objfieldforg === (string) $gvaluepossiblekey) {
1318 // The record we fetch is for this group
1319 $data[$xi][$fieldforybis] = $obj->$fieldfory;
1320 } elseif (!isset($data[$xi][$fieldforybis])) {
1321 // The record we fetch is not for this group
1322 $data[$xi][$fieldforybis] = '0';
1323 }
1324 }
1325 }
1326 //var_dump($data[$xi]);
1327 $gi++;
1328 }
1329 }
1330 } else { // No group by
1331 $xval = $sanitized_search_xaxis[0];
1332 $fieldforxkey = 'x_0';
1333 $xlabel = $obj->$fieldforxkey;
1334 $xvalwithoutprefix = preg_replace('/^[a-z]+\./', '', $xval);
1335
1336 // Define $xlabel
1337 if (!empty($object->fields[$xvalwithoutprefix]['arrayofkeyval'])) {
1338 $xlabel = $object->fields[$xvalwithoutprefix]['arrayofkeyval'][$obj->$fieldforxkey];
1339 }
1340
1341 $labeltouse = (($xlabel || $xlabel == '0') ? dol_trunc($xlabel, 20, 'middle') : ($xlabel === '' ? $langs->transnoentitiesnoconv("Empty") : $langs->transnoentitiesnoconv("NotDefined")));
1342 $xarrayforallseries = array('label' => $labeltouse);
1343 foreach ($sanitized_search_measures as $key => $val) {
1344 $fieldfory = 'y_'.$key;
1345 $xarrayforallseries[$fieldfory] = $obj->$fieldfory;
1346 }
1347 $data[$xi] = $xarrayforallseries;
1348 $xi++;
1349 }
1350 }
1351
1352 $totalnbofrecord = count($data);
1353 }
1354}
1355//var_dump($data);
1356
1357print '<!-- Section to show the result -->'."\n";
1358print '<div class="customreportsoutput'.($totalnbofrecord ? '' : ' customreportsoutputnotdata').'">';
1359
1360if (empty($newarrayoftype)) {
1361 $langs->load("admin");
1362 print info_admin($langs->trans("NoSupportedModulesHaveBeenActivated").' '.$langs->trans("YouCanEnableModulesFrom"), 0, 0, 'info');
1363}
1364
1365if ($mode == 'grid') {
1366 // TODO
1367}
1368
1369if ($mode == 'graph') {
1370 $WIDTH = '80%';
1371 $HEIGHT = (empty($_SESSION['dol_screenheight']) ? 400 : $_SESSION['dol_screenheight'] - 500);
1372
1373 // Show graph
1374 $px1 = new DolGraph();
1375 $mesg = $px1->isGraphKo();
1376 if (!$mesg) {
1377 //var_dump($legend);
1378 //var_dump($data);
1379 $px1->SetData($data);
1380 unset($data);
1381
1382 $arrayoftypes = array();
1383 foreach ($sanitized_search_measures as $key => $val) {
1384 $arrayoftypes[] = $search_graph;
1385 }
1386
1387 $px1->SetLegend($legend);
1388 $px1->setShowLegend($SHOWLEGEND);
1389 $px1->SetMinValue((int) $px1->GetFloorMinValue());
1390 $px1->SetMaxValue($px1->GetCeilMaxValue());
1391 $px1->SetWidth($WIDTH);
1392 $px1->SetHeight($HEIGHT);
1393 $px1->SetYLabel($langs->trans("Y"));
1394 $px1->SetShading(3);
1395 $px1->SetHorizTickIncrement(1);
1396 $px1->SetCssPrefix("cssboxes");
1397 $px1->SetType($arrayoftypes);
1398 $px1->mode = 'depth';
1399 $px1->SetTitle('');
1400
1401 $dir = $conf->user->dir_temp;
1402 dol_mkdir($dir);
1403 // $customreportkey may be defined when using customreports.php as an include
1404 if (!empty($object->element)) {
1405 $filenamekey = $dir.'/customreport_'.$object->element.(empty($customreportkey) ? '' : $customreportkey).'.png';
1406 $fileurlkey = DOL_URL_ROOT.'/viewimage.php?modulepart=user&file=customreport_'.$object->element.(empty($customreportkey) ? '' : $customreportkey).'.png';
1407 }
1408
1409 if (isset($filenamekey) && isset($fileurlkey)) {
1410 $px1->draw($filenamekey, $fileurlkey);
1411 }
1412
1413 $texttoshow = $langs->trans("NoRecordFound");
1414 if (!GETPOSTISSET('search_measures') || !GETPOSTISSET('search_xaxis')) {
1415 $texttoshow = $langs->trans("SelectYourGraphOptionsFirst");
1416 }
1417
1418 print $px1->show($totalnbofrecord ? 0 : $texttoshow);
1419 }
1420}
1421
1422print '</div>';
1423
1424if ($sql && !defined('MAIN_CUSTOM_REPORT_KEEP_GRAPH_ONLY')) {
1425 // Show admin info
1426 print '<br>'.info_admin($langs->trans("SQLUsedForExport").':<br> '.$sql, 0, 0, '1', '', 'TechnicalInformation');
1427}
1428
1429
1430if (!defined('USE_CUSTOM_REPORT_AS_INCLUDE')) {
1431 print dol_get_fiche_end();
1432
1433 llxFooter();
1434 // End of page
1435
1436 $db->close();
1437}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to build graphs.
Class to manage standard extra fields.
Class to manage generation of HTML components Only common components must be here.
Class to help generate other html components Only common components are here.
fillArrayOfGroupBy($object, $tablealias, $labelofobject, &$arrayofgroupby, $level=0, &$count=0, &$tablepath='')
Fill arrayofgroupby for an object.
fillArrayOfFilterFields($object, $tablealias, $labelofobject, &$arrayoffields, $level=0, &$count=0, &$tablepath='')
Fill array of possible filter fields for an object.
customReportsSelectGroupBy($htmlname, $arrayofgroupby, $selected, $placeholder='')
Return HTML of the combo to select the group by field (see customReportsSelectFieldCombo()).
customReportsSelectMeasures($htmlname, $arrayofmesures, $selected, $placeholder='')
Return HTML of the component to select measures.
fillArrayOfMeasures($object, $tablealias, $labelofobject, &$arrayofmesures, $level=0, &$count=0, &$tablepath='')
Fill arrayofmesures for an object.
customReportsSelectXAxis($htmlname, $arrayofxaxis, $selected, $placeholder='')
Return HTML of the combo to select the X axis (see customReportsSelectFieldCombo())
fillArrayOfXAxis($object, $tablealias, $labelofobject, &$arrayofxaxis, $level=0, &$count=0, &$tablepath='')
Fill arrayofmesures for an object.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
dolCheckFilters($sqlfilters, &$error='', &$parenthesislevel=0)
Return if a $sqlfilters parameter has a valid balance of parenthesis.
dolForgeExplodeAnd($sqlfilters)
Explode an universal search string with AND parts.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
isModEnabled($module)
Is Dolibarr module enabled.
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)
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
Definition html.lib.php:542
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition html.lib.php:740
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='', $cssfordropdown='info_admin')
Show information in HTML for admin users or standard users.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
Check permissions of a user to show a page and an object.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.