dolibarr 21.0.0-beta
stats.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (c) 2008-2013 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2012 Marcos García <marcosgdf@gmail.com>
6 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
7 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
32abstract class Stats
33{
37 protected $db;
41 protected $lastfetchdate = array();
42
46 public $cachefilesuffix = '';
47
51 public $from;
52
56 public $where;
60 public $from_line;
64 public $field_date;
68 public $field;
72 public $field_line;
73
77 public $error;
78
82 public $year;
83
87 public $month;
88
94 abstract protected function getNbByMonth($year, $format = 0);
95
106 public function getNbByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0, $format = 0, $startmonth = 1)
107 {
108 global $conf, $user, $langs;
109
110 if ($startyear > $endyear) {
111 return array();
112 }
113
114 $data = array(); // This is the return value
115 $datay = array(); // This is a work value
116
117 // Search into cache
118 if (!empty($cachedelay)) {
119 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
120 }
121
122 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
123 $newmask = '0644';
124
125 $nowgmt = dol_now();
126
127 $foundintocache = 0;
128 $filedate = -1;
129 if ($cachedelay > 0) {
130 $filedate = dol_filemtime($newpathofdestfile);
131 if ($filedate >= ($nowgmt - $cachedelay)) {
132 $foundintocache = 1;
133
134 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
135 } else {
136 dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
137 }
138 }
139 // Load file into $data
140 if ($foundintocache) { // Cache file found and is not too old
141 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
142 $data = json_decode(file_get_contents($newpathofdestfile), true);
143 '@phan-var-force array<int<0,11>,array{0:int<1,12>,1:int}> $data';
144 } else {
145 $year = $startyear;
146 $sm = $startmonth - 1;
147 if ($sm != 0) {
148 $year -= 1;
149 }
150 while ($year <= $endyear) {
151 $datay[$year] = $this->getNbByMonth($year, $format);
152 $year++;
153 }
154
155 for ($i = 0; $i < 12; $i++) {
156 $data[$i][] = $datay[$endyear][($i + $sm) % 12][0];
157 $year = $startyear;
158 while ($year <= $endyear) {
159 // floor(($i + $sm) / 12)) is 0 if we are after the month start $sm and same year, become 1 when we reach january of next year
160 $data[$i][] = $datay[$year - (1 - (int) floor(($i + $sm) / 12)) + ($sm == 0 ? 1 : 0)][($i + $sm) % 12][1];
161 $year++;
162 }
163 }
164 }
165
166
167 // Save cache file
168 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
169 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
170 if (!dol_is_dir($conf->user->dir_temp)) {
171 dol_mkdir($conf->user->dir_temp);
172 }
173 $fp = @fopen($newpathofdestfile, 'w');
174 if ($fp) {
175 fwrite($fp, json_encode($data));
176 fclose($fp);
177 } else {
178 dol_syslog("Failed to save cache file ".$newpathofdestfile, LOG_ERR);
179 }
180 dolChmod($newpathofdestfile);
181
182 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
183 }
184
185 return $data;
186 }
187
193 abstract protected function getAmountByMonth($year, $format = 0);
194
208 public function getAmountByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0, $format = 0, $startmonth = 1)
209 {
210 global $conf, $user, $langs;
211
212 if ($startyear > $endyear) {
213 return array();
214 }
215
216 $datay = array();
217 $data = array(); // Return value
218
219 // Search into cache
220 if (!empty($cachedelay)) {
221 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
222 }
223
224 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
225 $newmask = '0644';
226
227 $nowgmt = dol_now();
228
229 $foundintocache = 0;
230 $filedate = -1;
231 if ($cachedelay > 0) {
232 $filedate = dol_filemtime($newpathofdestfile);
233 if ($filedate >= ($nowgmt - $cachedelay)) {
234 $foundintocache = 1;
235
236 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
237 } else {
238 dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
239 }
240 }
241
242 // Load file into $data
243 if ($foundintocache) { // Cache file found and is not too old
244 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
245 $data = json_decode(file_get_contents($newpathofdestfile), true);
246 } else {
247 $year = $startyear;
248 $sm = $startmonth - 1;
249 if ($sm != 0) {
250 $year -= 1;
251 }
252 while ($year <= $endyear) {
253 $datay[$year] = $this->getAmountByMonth($year, $format);
254 $year++;
255 }
256
257 // $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
258 for ($i = 0; $i < 12; $i++) {
259 $data[$i][] = isset($datay[$endyear][($i + $sm) % 12]['label']) ? $datay[$endyear][($i + $sm) % 12]['label'] : $datay[$endyear][($i + $sm) % 12][0]; // set label
260 $year = $startyear;
261 while ($year <= $endyear) {
262 // floor(($i + $sm) / 12)) is 0 if we are after the month start $sm and same year, become 1 when we reach january of next year
263 $data[$i][] = $datay[$year - (1 - (int) floor(($i + $sm) / 12)) + ($sm == 0 ? 1 : 0)][($i + $sm) % 12][1]; // set yval for x=i
264 $year++;
265 }
266 }
267 }
268
269 // Save cache file
270 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
271 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
272 if (!dol_is_dir($conf->user->dir_temp)) {
273 dol_mkdir($conf->user->dir_temp);
274 }
275 $fp = @fopen($newpathofdestfile, 'w');
276 if ($fp) {
277 fwrite($fp, json_encode($data));
278 fclose($fp);
279 } else {
280 dol_syslog("Failed to save cache file ".$newpathofdestfile, LOG_ERR);
281 }
282 dolChmod($newpathofdestfile);
283
284 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
285 }
286
287 return $data;
288 }
289
294 abstract protected function getAverageByMonth($year);
295
303 public function getAverageByMonthWithPrevYear($endyear, $startyear)
304 {
305 if ($startyear > $endyear) {
306 return array();
307 }
308
309 $datay = array();
310 $data = array();
311
312 $year = $startyear;
313 while ($year <= $endyear) {
314 $datay[$year] = $this->getAverageByMonth($year);
315 $year++;
316 }
317
318 for ($i = 0; $i < 12; $i++) {
319 $data[$i][] = $datay[$endyear][$i][0];
320 $year = $startyear;
321 while ($year <= $endyear) {
322 $data[$i][] = $datay[$year][$i][1];
323 $year++;
324 }
325 }
326
327 return $data;
328 }
329
338 public function getAllByProductEntry($year, $cachedelay = 0, $limit = 10)
339 {
340 global $conf, $user, $langs;
341
342 $data = array();
343
344 // Search in cache
345 if (!empty($cachedelay)) {
346 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
347 }
348
349 $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
350 $newmask = '0644';
351
352 $nowgmt = dol_now();
353
354 $foundintocache = 0;
355 $filedate = -1;
356 if ($cachedelay > 0) {
357 $filedate = dol_filemtime($newpathofdestfile);
358 if ($filedate >= ($nowgmt - $cachedelay)) {
359 $foundintocache = 1;
360
361 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
362 } else {
363 dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
364 }
365 }
366
367 // Load file into $data
368 if ($foundintocache) { // Cache file found and is not too old
369 dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
370 $data = json_decode(file_get_contents($newpathofdestfile), true);
371 '@phan-var-force array<int<0,11>,array{0:int<1,12>,1:int|float}> $data'; // Phan can't decode json_decode's return value
372 } else {
373 $data = $this->getAllByProduct($year, $limit);
374 }
375
376 // Save cache file
377 if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1)) {
378 dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
379 if (!dol_is_dir($conf->user->dir_temp)) {
380 dol_mkdir($conf->user->dir_temp);
381 }
382 $fp = @fopen($newpathofdestfile, 'w');
383 if ($fp) {
384 fwrite($fp, json_encode($data));
385 fclose($fp);
386 } else {
387 dol_syslog("Failed to save cache file ".$newpathofdestfile, LOG_ERR);
388 }
389 dolChmod($newpathofdestfile);
390
391 $this->lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
392 }
393
394 return $data;
395 }
396
397
398 // Here we have low level of shared code called by XxxStats.class.php
399
400
401 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
408 protected function _getNbByYear($sql)
409 {
410 // phpcs:enable
411 $result = array();
412
413 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
414 $resql = $this->db->query($sql);
415 if ($resql) {
416 $num = $this->db->num_rows($resql);
417 $i = 0;
418 while ($i < $num) {
419 $row = $this->db->fetch_row($resql);
420 $result[$i] = $row;
421 $i++;
422 }
423 $this->db->free($resql);
424 } else {
425 dol_print_error($this->db);
426 }
427 return $result;
428 }
429
430 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
437 protected function _getAllByYear($sql)
438 {
439 // phpcs:enable
440 $result = array();
441
442 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
443 $resql = $this->db->query($sql);
444 if ($resql) {
445 $num = $this->db->num_rows($resql);
446 $i = 0;
447 while ($i < $num) {
448 $row = $this->db->fetch_object($resql);
449 $result[$i]['year'] = $row->year;
450 $result[$i]['nb'] = $row->nb;
451 if ($i > 0 && $row->nb > 0) {
452 $result[$i - 1]['nb_diff'] = ($result[$i - 1]['nb'] - $row->nb) / $row->nb * 100;
453 }
454 // For some $sql only
455 if (property_exists($row, 'total')) {
456 $result[$i]['total'] = $row->total;
457 if ($i > 0 && $row->total > 0) {
458 $result[$i - 1]['total_diff'] = ($result[$i - 1]['total'] - $row->total) / $row->total * 100;
459 }
460 }
461 // For some $sql only
462 if (property_exists($row, 'total')) {
463 $result[$i]['avg'] = $row->avg;
464 if ($i > 0 && $row->avg > 0) {
465 $result[$i - 1]['avg_diff'] = ($result[$i - 1]['avg'] - $row->avg) / $row->avg * 100;
466 }
467 }
468 // For some $sql only
469 if (property_exists($row, 'weighted')) {
470 $result[$i]['weighted'] = $row->weighted;
471 if ($i > 0 && $row->weighted > 0) {
472 $result[$i - 1]['avg_weighted'] = ($result[$i - 1]['weighted'] - $row->weighted) / $row->weighted * 100;
473 }
474 }
475 $i++;
476 }
477 $this->db->free($resql);
478 } else {
479 dol_print_error($this->db);
480 }
481 return $result;
482 }
483
484 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
494 protected function _getNbByMonth($year, $sql, $format = 0)
495 {
496 // phpcs:enable
497 global $langs;
498
499 $result = array();
500 $res = array();
501
502 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
503 $resql = $this->db->query($sql);
504 if ($resql) {
505 $num = $this->db->num_rows($resql);
506 $i = 0;
507 $j = 0;
508 while ($i < $num) {
509 $row = $this->db->fetch_row($resql);
510 $j = $row[0] * 1;
511 $result[$j] = $row[1];
512 $i++;
513 }
514 $this->db->free($resql);
515 } else {
516 dol_print_error($this->db);
517 }
518
519 for ($i = 1; $i < 13; $i++) {
520 $res[$i] = (isset($result[$i]) ? $result[$i] : 0);
521 }
522
523 $data = array();
524
525 for ($i = 1; $i < 13; $i++) {
526 $month = 'unknown';
527 if ($format == 0) {
528 $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
529 } elseif ($format == 1) {
530 $month = $i;
531 } elseif ($format == 2) {
532 $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
533 }
534 //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
535 //$month=dol_substr($month,0,3);
536 $data[$i - 1] = array($month, $res[$i]);
537 }
538
539 return $data;
540 }
541
542 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
551 protected function _getAmountByMonth($year, $sql, $format = 0)
552 {
553 // phpcs:enable
554 global $langs;
555
556 $result = array();
557 $res = array();
558
559 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
560
561 $resql = $this->db->query($sql);
562 if ($resql) {
563 $num = $this->db->num_rows($resql);
564 $i = 0;
565 while ($i < $num) {
566 $row = $this->db->fetch_row($resql);
567 $j = $row[0] * 1;
568 $result[$j] = $row[1];
569 $i++;
570 }
571 $this->db->free($resql);
572 } else {
573 dol_print_error($this->db);
574 }
575
576 for ($i = 1; $i < 13; $i++) {
577 $res[$i] = (int) round((isset($result[$i]) ? $result[$i] : 0));
578 }
579
580 $data = array();
581
582 for ($i = 1; $i < 13; $i++) {
583 $month = 'unknown';
584 if ($format == 0) {
585 $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
586 } elseif ($format == 1) {
587 $month = $i;
588 } elseif ($format == 2) {
589 $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
590 }
591 //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
592 //$month=dol_substr($month,0,3);
593 $data[$i - 1] = array($month, $res[$i]);
594 }
595
596 return $data;
597 }
598
599 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
608 protected function _getAverageByMonth($year, $sql, $format = 0)
609 {
610 // phpcs:enable
611 global $langs;
612
613 $result = array();
614 $res = array();
615
616 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
617 $resql = $this->db->query($sql);
618 if ($resql) {
619 $num = $this->db->num_rows($resql);
620 $i = 0;
621 $j = 0;
622 while ($i < $num) {
623 $row = $this->db->fetch_row($resql);
624 $j = $row[0] * 1;
625 $result[$j] = $row[1];
626 $i++;
627 }
628 $this->db->free($resql);
629 } else {
630 dol_print_error($this->db);
631 }
632
633 for ($i = 1; $i < 13; $i++) {
634 $res[$i] = (isset($result[$i]) ? $result[$i] : 0);
635 }
636
637 $data = array();
638
639 for ($i = 1; $i < 13; $i++) {
640 $month = 'unknown';
641 if ($format == 0) {
642 $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
643 } elseif ($format == 1) {
644 $month = $i;
645 } elseif ($format == 2) {
646 $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
647 }
648 //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
649 //$month=dol_substr($month,0,3);
650 $data[$i - 1] = array($month, $res[$i]);
651 }
652
653 return $data;
654 }
655
656
657 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
665 protected function _getAllByProduct($sql, $limit = 10)
666 {
667 // phpcs:enable
668 global $langs;
669
670 $result = array();
671
672 dol_syslog(get_class($this).'::'.__FUNCTION__, LOG_DEBUG);
673 $resql = $this->db->query($sql);
674 if ($resql) {
675 $num = $this->db->num_rows($resql);
676 $i = 0;
677 $other = 0;
678 while ($i < $num) {
679 $row = $this->db->fetch_row($resql);
680 if ($i < $limit || $num == $limit) {
681 $result[$i] = array($row[0], $row[1]); // Ref of product, nb
682 } else {
683 $other += $row[1];
684 }
685 $i++;
686 }
687 if ($num > $limit) {
688 $result[$i] = array($langs->transnoentitiesnoconv("Other"), $other);
689 }
690 $this->db->free($resql);
691 } else {
692 dol_print_error($this->db);
693 }
694
695 return $result;
696 }
697
698 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
704 protected function _getAmountByYear($sql)
705 {
706 $result = array();
707 $resql = $this->db->query($sql);
708 if ($resql) {
709 $num = $this->db->num_rows($resql);
710 $i = 0;
711 while ($i < $num) {
712 $row = $this->db->fetch_row($resql);
713 $result[] = [
714 0 => (int) $row[0],
715 1 => (int) $row[1],
716 ];
717 $i++;
718 }
719 $this->db->free($resql);
720 }
721 return $result;
722 }
723
724
732 public function getAllByProduct($year, $limit = 0)
733 {
734 // Needs to be implemented in child class when used
735 $msg = get_class($this)."::".__FUNCTION__." not implemented";
736 dol_syslog($msg, LOG_ERR);
737 $l = array(1,0); // Dummy result
738 return array($l,$l,$l,$l,$l,$l,$l,$l,$l,$l,$l,$l);
739 }
740}
Parent class of statistics class.
getNbByMonth($year, $format=0)
getAllByProduct($year, $limit=0)
Return nb, amount of predefined product for year.
getAmountByMonth($year, $format=0)
getAverageByMonth($year)
_getAmountByYear($sql)
Returns the summed amounts per year for a given number of past years ending now.
_getAverageByMonth($year, $sql, $format=0)
Return the amount average par month for a given year.
_getAmountByMonth($year, $sql, $format=0)
Return the amount per month for a given year.
_getNbByYear($sql)
Return nb of elements by year.
_getAllByYear($sql)
Return nb of elements, total amount and avg amount each year.
getAmountByMonthWithPrevYear($endyear, $startyear, $cachedelay=0, $format=0, $startmonth=1)
Return amount of elements by month for several years.
getNbByMonthWithPrevYear($endyear, $startyear, $cachedelay=0, $format=0, $startmonth=1)
Return nb of elements by month for several years.
getAllByProductEntry($year, $cachedelay=0, $limit=10)
Return count, and sum of products.
getAverageByMonthWithPrevYear($endyear, $startyear)
Return average of entity by month for several years.
_getAllByProduct($sql, $limit=10)
Return number or total of product refs.
_getNbByMonth($year, $sql, $format=0)
Renvoie le nombre de documents par mois pour une annee donnee Return number of documents per month fo...
dol_filemtime($pathoffile)
Return time of a file.
dol_is_dir($folder)
Test if filename is a directory.
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_now($mode='auto')
Return date for now.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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)
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79