dolibarr 24.0.3
holiday.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2011 Dimitri Mouillard <dmouillard@teclib.com>
3 * Copyright (C) 2012-2014 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2012-2016 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
6 * Copyright (C) 2016 Juanjo Menent <jmenent@2byte.es>
7 * Copyright (C) 2018-2026 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
9 * Copyright (C) 2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 */
24
30require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
31
32
36class Holiday extends CommonObject
37{
41 public $element = 'holiday';
42
47 public $TRIGGER_PREFIX = 'HOLIDAY';
48
52 public $table_element = 'holiday';
53
57 public $fk_element = 'fk_holiday';
58
62 public $picto = 'holiday';
63
67 public $fk_user;
68
72 public $date_create = '';
73
77 public $description;
78
82 public $date_debut = '';
83
87 public $date_fin = '';
88
92 public $date_debut_gmt = '';
93
97 public $date_fin_gmt = '';
98
102 public $halfday = '';
103
108 public $statut = 0;
109
113 public $fk_validator;
114
118 public $date_valid = 0;
119
123 public $fk_user_valid;
124
128 public $date_approval;
129
133 public $fk_user_approve;
134
138 public $user_approve_id;
139
143 public $date_refuse = 0;
144
148 public $fk_user_refuse;
149
153 public $date_cancel = 0;
154
158 public $fk_user_cancel;
159
163 public $fk_user_create;
164
168 public $detail_refuse = '';
169
173 public $fk_type;
174
178 public $holiday = array();
179
180 public $events = array();
181
185 public $logs = array();
186
187
191 const STATUS_DRAFT = 1;
207 const STATUS_REFUSED = 5;
208
209
215 public function __construct($db)
216 {
217 $this->db = $db;
218
219 $this->ismultientitymanaged = 0;
220 }
221
222
230 public function getNextNumRef($objsoc)
231 {
232 global $langs, $conf;
233 $langs->load("order");
234
235 if (!getDolGlobalString('HOLIDAY_ADDON')) {
236 $conf->global->HOLIDAY_ADDON = 'mod_holiday_madonna';
237 }
238
239 if (getDolGlobalString('HOLIDAY_ADDON')) {
240 $mybool = false;
241
242 $file = getDolGlobalString('HOLIDAY_ADDON') . ".php";
243 $classname = getDolGlobalString('HOLIDAY_ADDON');
244
245 // Include file with class
246 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
247 foreach ($dirmodels as $reldir) {
248 $dir = dol_buildpath($reldir."core/modules/holiday/");
249
250 // Load file with numbering class (if found)
251 $mybool = ((bool) @include_once $dir.$file) || $mybool;
252 }
253
254 if (!$mybool) {
255 dol_print_error(null, "Failed to include file ".$file);
256 return '';
257 }
258
259 $obj = new $classname();
260 '@phan-var-force ModelNumRefHolidays $obj';
262 $numref = $obj->getNextValue($objsoc, $this);
263
264 if ($numref != "") {
265 return $numref;
266 } else {
267 $this->error = $obj->error;
268 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
269 return "";
270 }
271 } else {
272 print $langs->trans("Error")." ".$langs->trans("Error_HOLIDAY_ADDON_NotDefined");
273 return "";
274 }
275 }
276
282 public function updateBalance()
283 {
284 $this->db->begin();
285
286 // Update sold of vocations
287 $result = $this->updateSoldeCP();
288
289 // Check nb of users into table llx_holiday_users and update with empty lines
290 //if ($result > 0) $result = $this->verifNbUsers($this->countActiveUsersWithoutCP(), $this->getConfCP('nbUser'));
291
292 if ($result >= 0) {
293 $this->db->commit();
294 return 0; // for cronjob use (0 is OK, any other value is an error code)
295 } else {
296 $this->db->rollback();
297 return -1;
298 }
299 }
300
308 public function create($user, $notrigger = 0)
309 {
310 global $conf;
311 $error = 0;
312
313 $now = dol_now();
314
315 // Check parameters
316 if (empty($this->fk_user) || !is_numeric($this->fk_user) || $this->fk_user < 0) {
317 $this->error = "ErrorBadParameterFkUser";
318 return -1;
319 }
320 if (empty($this->fk_validator) || !is_numeric($this->fk_validator) || $this->fk_validator < 0) {
321 $this->error = "ErrorBadParameterFkValidator";
322 return -1;
323 }
324 if (empty($this->fk_type) || !is_numeric($this->fk_type) || $this->fk_type < 0) {
325 $this->error = "ErrorBadParameterFkType";
326 return -1;
327 }
328
329 // Insert request
330 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday(";
331 $sql .= "ref,";
332 $sql .= "fk_user,";
333 $sql .= "date_create,";
334 $sql .= "description,";
335 $sql .= "date_debut,";
336 $sql .= "date_fin,";
337 $sql .= "halfday,";
338 $sql .= "statut,";
339 $sql .= "fk_validator,";
340 $sql .= "fk_type,";
341 $sql .= "fk_user_create,";
342 $sql .= "entity";
343 $sql .= ") VALUES (";
344 $sql .= "'(PROV)',";
345 $sql .= " ".((int) $this->fk_user).",";
346 $sql .= " '".$this->db->idate($now)."',";
347 $sql .= " '".$this->db->escape($this->description)."',";
348 $sql .= " '".$this->db->idate($this->date_debut)."',";
349 $sql .= " '".$this->db->idate($this->date_fin)."',";
350 $sql .= " ".((int) $this->halfday).",";
351 $sql .= " '1',";
352 $sql .= " ".((int) $this->fk_validator).",";
353 $sql .= " ".((int) $this->fk_type).",";
354 $sql .= " ".((int) $user->id).",";
355 $sql .= " ".((int) $conf->entity);
356 $sql .= ")";
357
358 $this->db->begin();
359
360 dol_syslog(get_class($this)."::create", LOG_DEBUG);
361 $resql = $this->db->query($sql);
362 if (!$resql) {
363 $error++;
364 $this->errors[] = "Error ".$this->db->lasterror();
365 }
366
367 if (!$error) {
368 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday");
369
370 if ($this->id) {
371 // update ref
372 $initialref = '(PROV'.$this->id.')';
373 if (!empty($this->ref)) {
374 $initialref = $this->ref;
375 }
376
377 $sql = 'UPDATE '.MAIN_DB_PREFIX."holiday SET ref='".$this->db->escape($initialref)."' WHERE rowid=".((int) $this->id);
378 if ($this->db->query($sql)) {
379 $this->ref = $initialref;
380 $result = $this->insertExtraFields();
381 if ($result < 0) {
382 $error++;
383 }
384
385 if (!$error && !$notrigger) {
386 // Call trigger
387 $result = $this->call_trigger('HOLIDAY_CREATE', $user);
388 if ($result < 0) {
389 $error++;
390 }
391 // End call triggers
392 }
393 }
394 }
395 }
396
397 // Commit or rollback
398 if ($error) {
399 foreach ($this->errors as $errmsg) {
400 dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
401 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
402 }
403 $this->db->rollback();
404 return -1 * $error;
405 } else {
406 $this->db->commit();
407 return $this->id;
408 }
409 }
410
411
419 public function fetch($id, $ref = '')
420 {
421 $sql = "SELECT";
422 $sql .= " cp.rowid,";
423 $sql .= " cp.ref,";
424 $sql .= " cp.fk_user,";
425 $sql .= " cp.date_create,";
426 $sql .= " cp.description,";
427 $sql .= " cp.date_debut,";
428 $sql .= " cp.date_fin,";
429 $sql .= " cp.halfday,";
430 $sql .= " cp.statut as status,";
431 $sql .= " cp.fk_validator,";
432 $sql .= " cp.date_valid,";
433 $sql .= " cp.fk_user_valid,";
434 $sql .= " cp.date_approval,";
435 $sql .= " cp.fk_user_approve,";
436 $sql .= " cp.date_refuse,";
437 $sql .= " cp.fk_user_refuse,";
438 $sql .= " cp.date_cancel,";
439 $sql .= " cp.fk_user_cancel,";
440 $sql .= " cp.detail_refuse,";
441 $sql .= " cp.note_private,";
442 $sql .= " cp.note_public,";
443 $sql .= " cp.fk_user_create,";
444 $sql .= " cp.fk_type,";
445 $sql .= " cp.entity";
446 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp";
447 if ($id > 0) {
448 $sql .= " WHERE cp.rowid = ".((int) $id);
449 } else {
450 $sql .= " WHERE cp.ref = '".$this->db->escape($ref)."'";
451 }
452
453 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
454 $resql = $this->db->query($sql);
455 if ($resql) {
456 if ($this->db->num_rows($resql)) {
457 $obj = $this->db->fetch_object($resql);
458
459 $this->id = (int) $obj->rowid;
460 $this->ref = (string) ($obj->ref ? $obj->ref : $obj->rowid);
461 $this->fk_user = (int) $obj->fk_user;
462 $this->date_create = $this->db->jdate($obj->date_create);
463 $this->description = $obj->description;
464 $this->date_debut = $this->db->jdate($obj->date_debut);
465 $this->date_fin = $this->db->jdate($obj->date_fin);
466 $this->date_debut_gmt = $this->db->jdate($obj->date_debut, 1);
467 $this->date_fin_gmt = $this->db->jdate($obj->date_fin, 1);
468 $this->halfday = (int) $obj->halfday;
469 $this->status = (int) $obj->status;
470 $this->statut = (int) $obj->status; // deprecated
471 $this->fk_validator = $obj->fk_validator;
472 $this->date_valid = $this->db->jdate($obj->date_valid);
473 $this->fk_user_valid = $obj->fk_user_valid;
474 $this->user_validation_id = $obj->fk_user_valid;
475 $this->date_approval = $this->db->jdate($obj->date_approval);
476 $this->fk_user_approve = $obj->fk_user_approve;
477 $this->date_refuse = $this->db->jdate($obj->date_refuse);
478 $this->fk_user_refuse = $obj->fk_user_refuse;
479 $this->date_cancel = $this->db->jdate($obj->date_cancel);
480 $this->fk_user_cancel = $obj->fk_user_cancel;
481 $this->detail_refuse = $obj->detail_refuse;
482 $this->note_private = $obj->note_private;
483 $this->note_public = $obj->note_public;
484 $this->fk_user_create = $obj->fk_user_create;
485 $this->fk_type = $obj->fk_type;
486 $this->entity = $obj->entity;
487
488 $this->fetch_optionals();
489
490 $result = 1;
491 } else {
492 $result = 0;
493 }
494 $this->db->free($resql);
495
496 return $result;
497 } else {
498 $this->error = "Error ".$this->db->lasterror();
499 return -1;
500 }
501 }
502
511 public function fetchByUser($user_id, $order = '', $filter = '')
512 {
513 $this->holiday = [];
514 $sql = "SELECT";
515 $sql .= " cp.rowid,";
516 $sql .= " cp.ref,";
517
518 $sql .= " cp.fk_user,";
519 $sql .= " cp.fk_type,";
520 $sql .= " cp.date_create,";
521 $sql .= " cp.tms as date_modification,";
522 $sql .= " cp.description,";
523 $sql .= " cp.date_debut,";
524 $sql .= " cp.date_fin,";
525 $sql .= " cp.halfday,";
526 $sql .= " cp.statut as status,";
527 $sql .= " cp.fk_validator,";
528 $sql .= " cp.date_valid,";
529 $sql .= " cp.fk_user_valid,";
530 $sql .= " cp.date_approval,";
531 $sql .= " cp.fk_user_approve,";
532 $sql .= " cp.date_refuse,";
533 $sql .= " cp.fk_user_refuse,";
534 $sql .= " cp.date_cancel,";
535 $sql .= " cp.fk_user_cancel,";
536 $sql .= " cp.detail_refuse,";
537
538 $sql .= " uu.lastname as user_lastname,";
539 $sql .= " uu.firstname as user_firstname,";
540 $sql .= " uu.login as user_login,";
541 $sql .= " uu.statut as user_status,";
542 $sql .= " uu.photo as user_photo,";
543 $sql .= " uu.fk_country as country_id,";
544
545 $sql .= " ua.lastname as validator_lastname,";
546 $sql .= " ua.firstname as validator_firstname,";
547 $sql .= " ua.login as validator_login,";
548 $sql .= " ua.statut as validator_status,";
549 $sql .= " ua.photo as validator_photo";
550
551 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
552 $sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
553 $sql .= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid"; // Hack needed for search on the list
554 $sql .= " AND cp.fk_user IN (".$this->db->sanitize($user_id).")";
555
556 // Selection filter
557 if (!empty($filter)) {
558 $sql .= $filter; // @phan-suppress-current-line SqlInjection
559 }
560
561 // Order of display of the result
562 if (!empty($order)) {
563 $sql .= $order; // @phan-suppress-current-line SqlInjection
564 }
565
566 dol_syslog(get_class($this)."::fetchByUser", LOG_DEBUG);
567 $resql = $this->db->query($sql);
568
569 // If no SQL error
570 if ($resql) {
571 $i = 0;
572 $tab_result = $this->holiday;
573 $num = $this->db->num_rows($resql);
574
575 // If no registration
576 if (!$num) {
577 return 2;
578 }
579
580 // List the records and add them to the table
581 while ($i < $num) {
582 $obj = $this->db->fetch_object($resql);
583
584 $tab_result[$i]['rowid'] = (int) $obj->rowid;
585 $tab_result[$i]['id'] = (int) $obj->rowid;
586 $tab_result[$i]['ref'] = (string) ($obj->ref ? $obj->ref : $obj->rowid);
587
588 $tab_result[$i]['fk_user'] = (int) $obj->fk_user;
589 $tab_result[$i]['fk_type'] = (int) $obj->fk_type;
590 $tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
591 $tab_result[$i]['date_modification'] = $this->db->jdate($obj->date_modification);
592 $tab_result[$i]['description'] = (string) $obj->description;
593 $tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
594 $tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
595 $tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut, 1);
596 $tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin, 1);
597 $tab_result[$i]['halfday'] = (int) $obj->halfday;
598 $tab_result[$i]['statut'] = (int) $obj->status;
599 $tab_result[$i]['status'] = (int) $obj->status;
600 $tab_result[$i]['fk_validator'] = (int) $obj->fk_validator;
601 $tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
602 $tab_result[$i]['fk_user_valid'] = (int) $obj->fk_user_valid;
603 $tab_result[$i]['date_approval'] = $this->db->jdate($obj->date_approval);
604 $tab_result[$i]['fk_user_approve'] = (int) $obj->fk_user_approve;
605 $tab_result[$i]['date_refuse'] = $this->db->jdate($obj->date_refuse);
606 $tab_result[$i]['fk_user_refuse'] = (int) $obj->fk_user_refuse;
607 $tab_result[$i]['date_cancel'] = $this->db->jdate($obj->date_cancel);
608 $tab_result[$i]['fk_user_cancel'] = (int) $obj->fk_user_cancel;
609 $tab_result[$i]['detail_refuse'] = (string) $obj->detail_refuse;
610
611 $tab_result[$i]['user_firstname'] = (string) $obj->user_firstname;
612 $tab_result[$i]['user_lastname'] = (string) $obj->user_lastname;
613 $tab_result[$i]['user_login'] = (string) $obj->user_login;
614 $tab_result[$i]['user_statut'] = (int) $obj->user_status;
615 $tab_result[$i]['user_status'] = (int) $obj->user_status;
616 $tab_result[$i]['user_photo'] = (string) $obj->user_photo;
617
618 $tab_result[$i]['validator_firstname'] = (string) $obj->validator_firstname;
619 $tab_result[$i]['validator_lastname'] = (string) $obj->validator_lastname;
620 $tab_result[$i]['validator_login'] = (string) $obj->validator_login;
621 $tab_result[$i]['validator_statut'] = (int) $obj->validator_status;
622 $tab_result[$i]['validator_status'] = (int) $obj->validator_status;
623 $tab_result[$i]['validator_photo'] = (string) $obj->validator_photo;
624
625 $tab_result[$i]['country_id'] = (int) $obj->country_id; // id of country of user
626
627 $i++;
628 }
629
630 // Returns 1 with the filled array
631 $this->holiday = $tab_result;
632 return 1;
633 } else {
634 // SQL Error
635 $this->error = "Error ".$this->db->lasterror();
636 return -1;
637 }
638 }
639
647 public function fetchAll($sqlOrder, $sqlFilter)
648 {
649 $sql = "SELECT";
650 $sql .= " cp.rowid,";
651 $sql .= " cp.ref,";
652 $sql .= " cp.fk_user,";
653 $sql .= " cp.fk_type,";
654 $sql .= " cp.date_create,";
655 $sql .= " cp.tms as date_modification,";
656 $sql .= " cp.description,";
657 $sql .= " cp.date_debut,";
658 $sql .= " cp.date_fin,";
659 $sql .= " cp.halfday,";
660 $sql .= " cp.statut as status,";
661 $sql .= " cp.fk_validator,";
662 $sql .= " cp.date_valid,";
663 $sql .= " cp.fk_user_valid,";
664 $sql .= " cp.date_approval,";
665 $sql .= " cp.fk_user_approve,";
666 $sql .= " cp.date_refuse,";
667 $sql .= " cp.fk_user_refuse,";
668 $sql .= " cp.date_cancel,";
669 $sql .= " cp.fk_user_cancel,";
670 $sql .= " cp.detail_refuse,";
671
672 $sql .= " uu.lastname as user_lastname,";
673 $sql .= " uu.firstname as user_firstname,";
674 $sql .= " uu.login as user_login,";
675 $sql .= " uu.statut as user_status,";
676 $sql .= " uu.photo as user_photo,";
677
678 $sql .= " ua.lastname as validator_lastname,";
679 $sql .= " ua.firstname as validator_firstname,";
680 $sql .= " ua.login as validator_login,";
681 $sql .= " ua.statut as validator_status,";
682 $sql .= " ua.photo as validator_photo";
683
684 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
685 $sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
686 $sql .= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid "; // Hack needed for search on the list
687
688 // Selection filtering
689 if (!empty($sqlFilter)) {
690 $sql .= $sqlFilter;
691 }
692
693 // order of display
694 if (!empty($sqlOrder)) {
695 $sql .= $sqlOrder;
696 }
697
698 dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG);
699 $resql = $this->db->query($sql);
700
701 // If no SQL error
702 if ($resql) {
703 $i = 0;
704 $tab_result = $this->holiday;
705 $num = $this->db->num_rows($resql);
706
707 // If no registration
708 if (!$num) {
709 return 2;
710 }
711
712 // List the records and add them to the table
713 while ($i < $num) {
714 $obj = $this->db->fetch_object($resql);
715
716 $tab_result[$i]['rowid'] = (int) $obj->rowid;
717 $tab_result[$i]['id'] = (int) $obj->rowid;
718 $tab_result[$i]['ref'] = (string) ($obj->ref ? $obj->ref : $obj->rowid);
719
720 $tab_result[$i]['fk_user'] = (int) $obj->fk_user;
721 $tab_result[$i]['fk_type'] = (int) $obj->fk_type;
722 $tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
723 $tab_result[$i]['date_modification'] = $this->db->jdate($obj->date_modification);
724 $tab_result[$i]['description'] = (string) $obj->description;
725 $tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
726 $tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
727 $tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut, 1);
728 $tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin, 1);
729 $tab_result[$i]['halfday'] = (int) $obj->halfday;
730 $tab_result[$i]['statut'] = (int) $obj->status;
731 $tab_result[$i]['status'] = (int) $obj->status;
732 $tab_result[$i]['fk_validator'] = (int) $obj->fk_validator;
733 $tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
734 $tab_result[$i]['fk_user_valid'] = (int) $obj->fk_user_valid;
735 $tab_result[$i]['date_approval'] = $this->db->jdate($obj->date_approval);
736 $tab_result[$i]['fk_user_approve'] = (int) $obj->fk_user_approve;
737 $tab_result[$i]['date_refuse'] = $this->db->jdate($obj->date_refuse);
738 $tab_result[$i]['fk_user_refuse'] = (int) $obj->fk_user_refuse;
739 $tab_result[$i]['date_cancel'] = $this->db->jdate($obj->date_cancel);
740 $tab_result[$i]['fk_user_cancel'] = (int) $obj->fk_user_cancel;
741 $tab_result[$i]['detail_refuse'] = (string) $obj->detail_refuse;
742
743 $tab_result[$i]['user_firstname'] = (string) $obj->user_firstname;
744 $tab_result[$i]['user_lastname'] = (string) $obj->user_lastname;
745 $tab_result[$i]['user_login'] = (string) $obj->user_login;
746 $tab_result[$i]['user_statut'] = (int) $obj->user_status;
747 $tab_result[$i]['user_status'] = (int) $obj->user_status;
748 $tab_result[$i]['user_photo'] = (string) $obj->user_photo;
749
750 $tab_result[$i]['validator_firstname'] = (string) $obj->validator_firstname;
751 $tab_result[$i]['validator_lastname'] = (string) $obj->validator_lastname;
752 $tab_result[$i]['validator_login'] = (string) $obj->validator_login;
753 $tab_result[$i]['validator_statut'] = (int) $obj->validator_status;
754 $tab_result[$i]['validator_status'] = (int) $obj->validator_status;
755 $tab_result[$i]['validator_photo'] = (string) $obj->validator_photo;
756
757 $i++;
758 }
759 // Returns 1 and adds the array to the variable
760 $this->holiday = $tab_result;
761 return 1;
762 } else {
763 // SQL Error
764 $this->error = "Error ".$this->db->lasterror();
765 return -1;
766 }
767 }
768
769
777 public function validate($user = null, $notrigger = 0)
778 {
779 global $conf, $langs;
780 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
781 $error = 0;
782
783
784 $checkBalance = getDictionaryValue('c_holiday_types', 'block_if_negative', $this->fk_type, true);
785
786 if ($checkBalance > 0) {
787 $balance = $this->getCPforUser($this->fk_user, $this->fk_type);
788
789 // Use the GMT variants: num_public_holiday(), called by num_open_day(), refuses a range whose
790 // length is not a whole number of days, and a range spanning a DST transition is 23h or 25h
791 // long in the server timezone. It then returns a string and the subtraction fatals.
792 $datedebutforcount = !empty($this->date_debut_gmt) ? $this->date_debut_gmt : $this->date_debut;
793 $datefinforcount = !empty($this->date_fin_gmt) ? $this->date_fin_gmt : $this->date_fin;
794 $daysAsked = num_open_day($datedebutforcount, $datefinforcount, 0, 1, (int) $this->halfday, '', $this->fk_user);
795
796 if (($balance - $daysAsked) < 0) {
797 $this->error = 'LeaveRequestCreationBlockedBecauseBalanceIsNegative';
798 return -1;
799 }
800 }
801
802 // Define new ref
803 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref) || $this->ref == $this->id) {
804 $num = $this->getNextNumRef(null);
805 } else {
806 $num = (string) $this->ref;
807 }
808 $this->newref = dol_sanitizeFileName($num);
809
810 // Update status
811 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
812 $sql .= " fk_user_valid = ".((int) $user->id).",";
813 $sql .= " date_valid = '".$this->db->idate(dol_now())."',";
814 if (!empty($this->status) && is_numeric($this->status)) {
815 $sql .= " statut = ".((int) $this->status).",";
816 } else {
817 $this->error = 'Property status must be a numeric value';
818 $error++;
819 }
820 $sql .= " ref = '".$this->db->escape($num)."'";
821 $sql .= " WHERE rowid = ".((int) $this->id);
822
823 $this->db->begin();
824
825 dol_syslog(get_class($this)."::validate", LOG_DEBUG);
826 $resql = $this->db->query($sql);
827 if (!$resql) {
828 $error++;
829 $this->errors[] = "Error ".$this->db->lasterror();
830 }
831
832 if (!$error) {
833 if (!$notrigger) {
834 // Call trigger
835 $result = $this->call_trigger('HOLIDAY_VALIDATE', $user);
836 if ($result < 0) {
837 $error++;
838 }
839 // End call triggers
840 }
841 }
842
843 if (!$error) {
844 $this->oldref = $this->ref;
845
846 // Rename directory if dir was a temporary ref
847 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
848 // Now we rename also files into index
849 $sql = 'UPDATE ' . MAIN_DB_PREFIX . "ecm_files set filename = CONCAT('" . $this->db->escape($this->newref) . "', SUBSTR(filename, " . (strlen($this->ref) + 1) . ")), filepath = 'holiday/" . $this->db->escape($this->newref) . "'";
850 $sql .= " WHERE filename LIKE '" . $this->db->escape($this->ref) . "%' AND filepath = 'holiday/" . $this->db->escape($this->ref) . "' and entity = " . ((int) $conf->entity);
851 $resql = $this->db->query($sql);
852 if (!$resql) {
853 $error++;
854 $this->error = $this->db->lasterror();
855 }
856 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'holiday/".$this->db->escape($this->newref)."'";
857 $sql .= " WHERE filepath = 'holiday/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
858 $resql = $this->db->query($sql);
859 if (!$resql) {
860 $error++;
861 $this->error = $this->db->lasterror();
862 }
863
864 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
865 $oldref = dol_sanitizeFileName($this->ref);
866 $newref = dol_sanitizeFileName($num);
867 $dirsource = $conf->holiday->multidir_output[$this->entity] . '/' . $oldref;
868 $dirdest = $conf->holiday->multidir_output[$this->entity] . '/' . $newref;
869 if (!$error && file_exists($dirsource)) {
870 dol_syslog(get_class($this) . "::validate rename dir " . $dirsource . " into " . $dirdest);
871 if (@rename($dirsource, $dirdest)) {
872 dol_syslog("Rename ok");
873 // Rename docs starting with $oldref with $newref
874 $listoffiles = dol_dir_list($dirdest, 'files', 1, '^' . preg_quote($oldref, '/'));
875 foreach ($listoffiles as $fileentry) {
876 $dirsource = $fileentry['name'];
877 $dirdest = preg_replace('/^' . preg_quote($oldref, '/') . '/', $newref, $dirsource);
878 $dirsource = $fileentry['path'] . '/' . $dirsource;
879 $dirdest = $fileentry['path'] . '/' . $dirdest;
880 @rename($dirsource, $dirdest);
881 }
882 }
883 }
884 }
885 }
886
887
888 // Commit or rollback
889 if ($error) {
890 foreach ($this->errors as $errmsg) {
891 dol_syslog(get_class($this)."::validate ".$errmsg, LOG_ERR);
892 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
893 }
894 $this->db->rollback();
895 return -1 * $error;
896 } else {
897 $this->db->commit();
898 return 1;
899 }
900 }
901
902
910 public function approve($user = null, $notrigger = 0)
911 {
912 $error = 0;
913
914 $checkBalance = getDictionaryValue('c_holiday_types', 'block_if_negative', $this->fk_type, true);
915
916 if ($checkBalance > 0) {
917 $balance = $this->getCPforUser($this->fk_user, $this->fk_type);
918
919 // Use the GMT variants: num_public_holiday(), called by num_open_day(), refuses a range whose
920 // length is not a whole number of days, and a range spanning a DST transition is 23h or 25h
921 // long in the server timezone. It then returns a string and the subtraction fatals.
922 $datedebutforcount = !empty($this->date_debut_gmt) ? $this->date_debut_gmt : $this->date_debut;
923 $datefinforcount = !empty($this->date_fin_gmt) ? $this->date_fin_gmt : $this->date_fin;
924 $daysAsked = num_open_day($datedebutforcount, $datefinforcount, 0, 1, (int) $this->halfday, '', $this->fk_user);
925
926 if (($balance - $daysAsked) < 0) {
927 $this->error = 'LeaveRequestCreationBlockedBecauseBalanceIsNegative';
928 return -1;
929 }
930 }
931
932 // Update request
933 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
934 $sql .= " description= '".$this->db->escape($this->description)."',";
935 if (!empty($this->date_debut)) {
936 $sql .= " date_debut = '".$this->db->idate($this->date_debut)."',";
937 } else {
938 $error++;
939 }
940 if (!empty($this->date_fin)) {
941 $sql .= " date_fin = '".$this->db->idate($this->date_fin)."',";
942 } else {
943 $error++;
944 }
945 $sql .= " halfday = ".((int) $this->halfday).",";
946 if (!empty($this->status) && is_numeric($this->status)) {
947 $sql .= " statut = ".((int) $this->status).",";
948 } else {
949 $error++;
950 }
951 if (!empty($this->fk_validator)) {
952 $sql .= " fk_validator = ".((int) $this->fk_validator).",";
953 } else {
954 $error++;
955 }
956 if (!empty($this->date_valid)) {
957 $sql .= " date_valid = '".$this->db->idate($this->date_valid)."',";
958 } else {
959 $sql .= " date_valid = NULL,";
960 }
961 if (!empty($this->fk_user_valid)) {
962 $sql .= " fk_user_valid = ".((int) $this->fk_user_valid).",";
963 } else {
964 $sql .= " fk_user_valid = NULL,";
965 }
966 if (!empty($this->date_approval)) {
967 $sql .= " date_approval = '".$this->db->idate($this->date_approval)."',";
968 } else {
969 $sql .= " date_approval = NULL,";
970 }
971 if (!empty($this->fk_user_approve)) {
972 $sql .= " fk_user_approve = ".((int) $this->fk_user_approve).",";
973 } else {
974 $sql .= " fk_user_approve = NULL,";
975 }
976 if (!empty($this->date_refuse)) {
977 $sql .= " date_refuse = '".$this->db->idate($this->date_refuse)."',";
978 } else {
979 $sql .= " date_refuse = NULL,";
980 }
981 if (!empty($this->fk_user_refuse)) {
982 $sql .= " fk_user_refuse = ".((int) $this->fk_user_refuse).",";
983 } else {
984 $sql .= " fk_user_refuse = NULL,";
985 }
986 if (!empty($this->date_cancel)) {
987 $sql .= " date_cancel = '".$this->db->idate($this->date_cancel)."',";
988 } else {
989 $sql .= " date_cancel = NULL,";
990 }
991 if (!empty($this->fk_user_cancel)) {
992 $sql .= " fk_user_cancel = ".((int) $this->fk_user_cancel).",";
993 } else {
994 $sql .= " fk_user_cancel = NULL,";
995 }
996 if (!empty($this->detail_refuse)) {
997 $sql .= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'";
998 } else {
999 $sql .= " detail_refuse = NULL";
1000 }
1001 $sql .= " WHERE rowid = ".((int) $this->id);
1002
1003 $this->db->begin();
1004
1005 dol_syslog(get_class($this)."::approve", LOG_DEBUG);
1006 $resql = $this->db->query($sql);
1007 if (!$resql) {
1008 $error++;
1009 $this->errors[] = "Error ".$this->db->lasterror();
1010 }
1011
1012 if (!$error) {
1013 if (!$notrigger) {
1014 // Call trigger
1015 $result = $this->call_trigger('HOLIDAY_APPROVE', $user);
1016 if ($result < 0) {
1017 $error++;
1018 }
1019 // End call triggers
1020 }
1021 }
1022
1023 // Commit or rollback
1024 if ($error) {
1025 foreach ($this->errors as $errmsg) {
1026 dol_syslog(get_class($this)."::approve ".$errmsg, LOG_ERR);
1027 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1028 }
1029 $this->db->rollback();
1030 return -1 * $error;
1031 } else {
1032 $this->db->commit();
1033 return 1;
1034 }
1035 }
1036
1044 public function update($user = null, $notrigger = 0)
1045 {
1046 $error = 0;
1047
1048 $checkBalance = getDictionaryValue('c_holiday_types', 'block_if_negative', $this->fk_type, true);
1049 if ($this->status == self::STATUS_REFUSED || $this->status == self::STATUS_APPROVED) {
1050 $checkBalance = 0; // No balance check to refuse a request, nor on an approved request (its days are already debited)
1051 }
1052
1053 if ($checkBalance > 0 && $this->status != self::STATUS_DRAFT && $this->status != self::STATUS_CANCELED) {
1054 $balance = $this->getCPforUser($this->fk_user, $this->fk_type);
1055
1056 // Use the GMT variants: num_public_holiday(), called by num_open_day(), refuses a range whose
1057 // length is not a whole number of days, and a range spanning a DST transition is 23h or 25h
1058 // long in the server timezone. It then returns a string and the subtraction fatals.
1059 $datedebutforcount = !empty($this->date_debut_gmt) ? $this->date_debut_gmt : $this->date_debut;
1060 $datefinforcount = !empty($this->date_fin_gmt) ? $this->date_fin_gmt : $this->date_fin;
1061 $daysAsked = num_open_day($datedebutforcount, $datefinforcount, 0, 1, (int) $this->halfday, '', $this->fk_user);
1062
1063 if (($balance - $daysAsked) < 0) {
1064 $this->error = 'LeaveRequestCreationBlockedBecauseBalanceIsNegative';
1065 return -1;
1066 }
1067 }
1068
1069 // Update request
1070 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
1071
1072 $sql .= " description= '".$this->db->escape($this->description)."',";
1073
1074 if (!empty($this->date_create)) {
1075 $sql .= " date_create = '".$this->db->idate($this->date_create)."',";
1076 } else {
1077 $error++;
1078 }
1079 if (!empty($this->date_debut)) {
1080 $sql .= " date_debut = '".$this->db->idate($this->date_debut)."',";
1081 } else {
1082 $error++;
1083 }
1084 if (!empty($this->date_fin)) {
1085 $sql .= " date_fin = '".$this->db->idate($this->date_fin)."',";
1086 } else {
1087 $error++;
1088 }
1089 $sql .= " halfday = ".((int) $this->halfday).",";
1090 if (!empty($this->status) && is_numeric($this->status)) {
1091 $sql .= " statut = ".((int) $this->status).",";
1092 } else {
1093 $error++;
1094 }
1095 if (!empty($this->fk_validator)) {
1096 $sql .= " fk_validator = ".((int) $this->fk_validator).",";
1097 } else {
1098 $error++;
1099 }
1100 if (!empty($this->date_valid)) {
1101 $sql .= " date_valid = '".$this->db->idate($this->date_valid)."',";
1102 } else {
1103 $sql .= " date_valid = NULL,";
1104 }
1105 if (!empty($this->fk_user_valid)) {
1106 $sql .= " fk_user_valid = ".((int) $this->fk_user_valid).",";
1107 } else {
1108 $sql .= " fk_user_valid = NULL,";
1109 }
1110 if (!empty($this->date_approval)) {
1111 $sql .= " date_approval = '".$this->db->idate($this->date_approval)."',";
1112 } else {
1113 $sql .= " date_approval = NULL,";
1114 }
1115 if (!empty($this->fk_user_approve)) {
1116 $sql .= " fk_user_approve = ".((int) $this->fk_user_approve).",";
1117 } else {
1118 $sql .= " fk_user_approve = NULL,";
1119 }
1120 if (!empty($this->date_refuse)) {
1121 $sql .= " date_refuse = '".$this->db->idate($this->date_refuse)."',";
1122 } else {
1123 $sql .= " date_refuse = NULL,";
1124 }
1125 if (!empty($this->fk_user_refuse)) {
1126 $sql .= " fk_user_refuse = ".((int) $this->fk_user_refuse).",";
1127 } else {
1128 $sql .= " fk_user_refuse = NULL,";
1129 }
1130 if (!empty($this->date_cancel)) {
1131 $sql .= " date_cancel = '".$this->db->idate($this->date_cancel)."',";
1132 } else {
1133 $sql .= " date_cancel = NULL,";
1134 }
1135 if (!empty($this->fk_user_cancel)) {
1136 $sql .= " fk_user_cancel = ".((int) $this->fk_user_cancel).",";
1137 } else {
1138 $sql .= " fk_user_cancel = NULL,";
1139 }
1140 if (!empty($this->detail_refuse)) {
1141 $sql .= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'";
1142 } else {
1143 $sql .= " detail_refuse = NULL";
1144 }
1145
1146 $sql .= " WHERE rowid = ".((int) $this->id);
1147
1148 $this->db->begin();
1149
1150 dol_syslog(get_class($this)."::update", LOG_DEBUG);
1151 $resql = $this->db->query($sql);
1152 if (!$resql) {
1153 $error++;
1154 $this->errors[] = "Error ".$this->db->lasterror();
1155 }
1156
1157 if (!$error) {
1158 $result = $this->insertExtraFields();
1159 if ($result < 0) {
1160 $error++;
1161 }
1162 }
1163
1164 if (!$error) {
1165 if (!$notrigger && $user !== null) {
1166 // Call trigger
1167 $result = $this->call_trigger('HOLIDAY_MODIFY', $user);
1168 if ($result < 0) {
1169 $error++;
1170 }
1171 // End call triggers
1172 }
1173 }
1174
1175 // Commit or rollback
1176 if ($error) {
1177 foreach ($this->errors as $errmsg) {
1178 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1179 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1180 }
1181 $this->db->rollback();
1182 return -1 * $error;
1183 } else {
1184 $this->db->commit();
1185 return 1;
1186 }
1187 }
1188
1189
1197 public function delete($user, $notrigger = 0)
1198 {
1199 global $conf, $langs;
1200 $error = 0;
1201
1202 $sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday";
1203 $sql .= " WHERE rowid=".((int) $this->id);
1204
1205 $this->db->begin();
1206
1207 // Delete extrafields before the leave request
1208 $result = $this->deleteExtraFields();
1209 if ($result < 0) {
1210 $error++;
1211 }
1212
1213 if (!$error) {
1214 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1215 $resql = $this->db->query($sql);
1216 if (!$resql) {
1217 $error++;
1218 $this->errors[] = "Error ".$this->db->lasterror();
1219 }
1220 }
1221
1222 if (!$error) {
1223 if (!$notrigger) {
1224 // Call trigger
1225 $result = $this->call_trigger('HOLIDAY_DELETE', $user);
1226 if ($result < 0) {
1227 $error++;
1228 }
1229 // End call triggers
1230 }
1231 }
1232
1233 // Commit or rollback
1234 if ($error) {
1235 foreach ($this->errors as $errmsg) {
1236 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1237 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1238 }
1239 $this->db->rollback();
1240 return -1 * $error;
1241 } else {
1242 $this->db->commit();
1243 return 1;
1244 }
1245 }
1246
1260 public function verifDateHolidayCP($fk_user, $dateStart, $dateEnd, $halfday = 0)
1261 {
1262 $this->fetchByUser($fk_user, '', '');
1263
1264 foreach ($this->holiday as $infos_CP) {
1265 if ($infos_CP['statut'] == Holiday::STATUS_CANCELED) {
1266 continue; // ignore not validated holidays
1267 }
1268 if ($infos_CP['statut'] == Holiday::STATUS_REFUSED) {
1269 continue; // ignore refused holidays
1270 }
1271 //var_dump("--");
1272 //var_dump("old: ".dol_print_date($infos_CP['date_debut'],'dayhour').' '.dol_print_date($infos_CP['date_fin'],'dayhour').' '.$infos_CP['halfday']);
1273 //var_dump("new: ".dol_print_date($dateStart,'dayhour').' '.dol_print_date($dateEnd,'dayhour').' '.$halfday);
1274
1275 // A new leave can fully contain an existing leave, so neither endpoint is inside the existing range.
1276 if ($dateStart < $infos_CP['date_debut'] && $dateEnd > $infos_CP['date_fin']) {
1277 return false;
1278 }
1279
1280 if ($halfday == 0) {
1281 if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1282 return false;
1283 }
1284 if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1285 return false;
1286 }
1287 } elseif ($halfday == -1) {
1288 // new start afternoon, new end afternoon
1289 if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1290 if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) {
1291 return false;
1292 }
1293 }
1294 if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1295 if ($dateStart < $dateEnd) {
1296 return false;
1297 }
1298 if ($dateEnd < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) {
1299 return false;
1300 }
1301 }
1302 } elseif ($halfday == 1) {
1303 // new start morning, new end morning
1304 if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1305 if ($dateStart < $dateEnd) {
1306 return false;
1307 }
1308 if ($dateStart > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) {
1309 return false;
1310 }
1311 }
1312 if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1313 if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) {
1314 return false;
1315 }
1316 }
1317 } elseif ($halfday == 2) {
1318 // new start afternoon, new end morning
1319 if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1320 if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) {
1321 return false;
1322 }
1323 }
1324 if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1325 if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) {
1326 return false;
1327 }
1328 }
1329 } else {
1330 dol_print_error(null, 'Bad value of parameter halfday when calling function verifDateHolidayCP');
1331 }
1332 }
1333
1334 return true;
1335 }
1336
1337
1347 public function verifDateHolidayForTimestamp($fk_user, $timestamp, $status = '-1')
1348 {
1349 $isavailablemorning = true;
1350 $isavailableafternoon = true;
1351
1352 // Check into leave requests
1353 $sql = "SELECT cp.rowid, cp.date_debut as date_start, cp.date_fin as date_end, cp.halfday, cp.statut as status";
1354 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp";
1355 $sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
1356 $sql .= " AND cp.fk_user = ".(int) $fk_user;
1357 $sql .= " AND cp.date_debut <= '".$this->db->idate($timestamp)."' AND cp.date_fin >= '".$this->db->idate($timestamp)."'";
1358 if ($status != '-1') {
1359 $sql .= " AND cp.statut IN (".$this->db->sanitize($status).")";
1360 }
1361
1362 $resql = $this->db->query($sql);
1363 if ($resql) {
1364 $num_rows = $this->db->num_rows($resql); // Note, we can have 2 records if on is morning and the other one is afternoon
1365 if ($num_rows > 0) {
1366 $arrayofrecord = array();
1367 $i = 0;
1368 while ($i < $num_rows) {
1369 $obj = $this->db->fetch_object($resql);
1370
1371 // Note: $obj->halfday is 0:Full days, 2:Start afternoon end morning, -1:Start afternoon, 1:End morning
1372 $arrayofrecord[$obj->rowid] = array('date_start' => $this->db->jdate($obj->date_start), 'date_end' => $this->db->jdate($obj->date_end), 'halfday' => $obj->halfday, 'status' => $obj->status);
1373 $i++;
1374 }
1375
1376 // We found a record, user is on holiday by default, so is not available is true.
1377 $isavailablemorning = true;
1378 foreach ($arrayofrecord as $record) {
1379 if ($timestamp == $record['date_start'] && $record['halfday'] == 2) {
1380 continue;
1381 }
1382 if ($timestamp == $record['date_start'] && $record['halfday'] == -1) {
1383 continue;
1384 }
1385 $isavailablemorning = false;
1386 break;
1387 }
1388 $isavailableafternoon = true;
1389 foreach ($arrayofrecord as $record) {
1390 if ($timestamp == $record['date_end'] && $record['halfday'] == 2) {
1391 continue;
1392 }
1393 if ($timestamp == $record['date_end'] && $record['halfday'] == 1) {
1394 continue;
1395 }
1396 $isavailableafternoon = false;
1397 break;
1398 }
1399 }
1400 } else {
1401 dol_print_error($this->db);
1402 }
1403
1404 $result = array('morning' => (int) $isavailablemorning, 'afternoon' => (int) $isavailableafternoon);
1405 if (!$isavailablemorning) {
1406 $result['morning_reason'] = 'leave_request';
1407 }
1408 if (!$isavailableafternoon) {
1409 $result['afternoon_reason'] = 'leave_request';
1410 }
1411 return $result;
1412 }
1413
1420 public function getTooltipContentArray($params)
1421 {
1422 global $langs;
1423
1424 $langs->load('holiday');
1425 $nofetch = !empty($params['nofetch']);
1426
1427 $datas = array();
1428 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Holiday").'</u>';
1429 if (isset($this->status)) {
1430 $datas['picto'] .= ' '.$this->getLibStatut(5);
1431 }
1432 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1433 // show type for this record only in ajax to not overload lists
1434 if (!$nofetch && !empty($this->fk_type)) {
1435 $typeleaves = $this->getTypes(1, -1);
1436 if (empty($typeleaves[$this->fk_type])) {
1437 $labeltoshow = $langs->trans("TypeWasDisabledOrRemoved", $this->fk_type);
1438 } else {
1439 $labeltoshow = (($typeleaves[$this->fk_type]['code'] && $langs->trans($typeleaves[$this->fk_type]['code']) != $typeleaves[$this->fk_type]['code']) ? $langs->trans($typeleaves[$this->fk_type]['code']) : $typeleaves[$this->fk_type]['label']);
1440 }
1441 $datas['type'] = '<br><b>'.$langs->trans("Type") . ':</b> ' . $labeltoshow;
1442 }
1443 if (isset($this->halfday) && !empty($this->date_debut) && !empty($this->date_fin)) {
1444 $listhalfday = array(
1445 'morning' => $langs->trans("Morning"),
1446 "afternoon" => $langs->trans("Afternoon")
1447 );
1448 $starthalfday = ($this->halfday == -1 || $this->halfday == 2) ? 'afternoon' : 'morning';
1449 $endhalfday = ($this->halfday == 1 || $this->halfday == 2) ? 'morning' : 'afternoon';
1450 $datas['date_start'] = '<br><b>'.$langs->trans('DateDebCP') . '</b>: '. dol_print_date($this->date_debut, 'day') . '&nbsp;&nbsp;<span class="opacitymedium">'.$langs->trans($listhalfday[$starthalfday]).'</span>';
1451 $datas['date_end'] = '<br><b>'.$langs->trans('DateFinCP') . '</b>: '. dol_print_date($this->date_fin, 'day') . '&nbsp;&nbsp;<span class="opacitymedium">'.$langs->trans($listhalfday[$endhalfday]).'</span>';
1452 }
1453
1454
1455 return $datas;
1456 }
1457
1467 public function getNomUrl($withpicto = 0, $save_lastsearch_value = -1, $notooltip = 0, $morecss = '')
1468 {
1469 global $conf, $langs, $hookmanager;
1470
1471 if (!empty($conf->dol_no_mouse_hover)) {
1472 $notooltip = 1; // Force disable tooltips
1473 }
1474
1475 $result = '';
1476 $params = [
1477 'id' => $this->id,
1478 'objecttype' => $this->element,
1479 'nofetch' => 1,
1480 ];
1481 $classfortooltip = 'classfortooltip';
1482 $dataparams = '';
1483 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1484 $classfortooltip = 'classforajaxtooltip';
1485 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1486 $label = '';
1487 } else {
1488 $label = implode($this->getTooltipContentArray($params));
1489 }
1490
1491 $url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id;
1492
1493 //if ($option != 'nolink')
1494 //{
1495 // Add param to save lastsearch_values or not
1496 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1497 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1498 $add_save_lastsearch_values = 1;
1499 }
1500 if ($add_save_lastsearch_values) {
1501 $url .= '&save_lastsearch_values=1';
1502 }
1503 //}
1504
1505 $linkclose = '';
1506 if (empty($notooltip)) {
1507 if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1508 $label = $langs->trans("ShowMyObject");
1509 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1510 }
1511 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1512 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1513 } else {
1514 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1515 }
1516
1517 $linkstart = '<a href="'.$url.'"';
1518 $linkstart .= $linkclose.'>';
1519 $linkend = '</a>';
1520
1521 $result .= $linkstart;
1522
1523 if ($withpicto) {
1524 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
1525 }
1526 if ($withpicto != 2) {
1527 $result .= $this->ref;
1528 }
1529 $result .= $linkend;
1530
1531 global $action;
1532 $hookmanager->initHooks(array($this->element . 'dao'));
1533 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1534 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1535 if ($reshook > 0) {
1536 $result = $hookmanager->resPrint;
1537 } else {
1538 $result .= $hookmanager->resPrint;
1539 }
1540 return $result;
1541 }
1542
1543
1550 public function getLibStatut($mode = 0)
1551 {
1552 return $this->LibStatut($this->status, $mode, $this->date_debut);
1553 }
1554
1555 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1564 public function LibStatut($status, $mode = 0, $startdate = '')
1565 {
1566 // phpcs:enable
1567 global $langs;
1568
1569 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1570 global $langs;
1571 //$langs->load("mymodule");
1572 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('DraftCP');
1573 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ToReviewCP');
1574 $this->labelStatus[self::STATUS_APPROVED] = $langs->transnoentitiesnoconv('ApprovedCP');
1575 $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('CancelCP');
1576 $this->labelStatus[self::STATUS_REFUSED] = $langs->transnoentitiesnoconv('RefuseCP');
1577 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('DraftCP');
1578 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ToReviewCP');
1579 $this->labelStatusShort[self::STATUS_APPROVED] = $langs->transnoentitiesnoconv('ApprovedCP');
1580 $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('CancelCP');
1581 $this->labelStatusShort[self::STATUS_REFUSED] = $langs->transnoentitiesnoconv('RefuseCP');
1582 }
1583
1584 $params = array();
1585 $statusType = 'status6';
1586 if (!empty($startdate) && $startdate >= dol_now()) { // If not yet passed, we use a green "in live" color
1587 $statusType = 'status4';
1588 $params = array('tooltip' => $this->labelStatus[$status].' - '.$langs->trans("Forthcoming"));
1589 }
1590 if ($status == self::STATUS_DRAFT) {
1591 $statusType = 'status0';
1592 }
1593 if ($status == self::STATUS_VALIDATED) {
1594 $statusType = 'status1';
1595 }
1596 if ($status == self::STATUS_CANCELED) {
1597 $statusType = 'status9';
1598 }
1599 if ($status == self::STATUS_REFUSED) {
1600 $statusType = 'status9';
1601 }
1602
1603 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode, '', $params);
1604 }
1605
1606
1615 public function selectStatutCP($selected = 0, $htmlname = 'select_statut', $morecss = 'minwidth125')
1616 {
1617 global $langs;
1618
1619 // List of status label
1620 $name = array('DraftCP', 'ToReviewCP', 'ApprovedCP', 'CancelCP', 'RefuseCP');
1621 $nb = count($name) + 1;
1622
1623 // Select HTML
1624 $out = '<select name="'.$htmlname.'" id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'">'."\n";
1625 $out .= '<option value="-1">&nbsp;</option>'."\n";
1626
1627 // Loop on status
1628 for ($i = 1; $i < $nb; $i++) {
1629 if ($i == $selected) {
1630 $out .= '<option value="'.$i.'" selected>'.$langs->trans($name[$i - 1]).'</option>'."\n";
1631 } else {
1632 $out .= '<option value="'.$i.'">'.$langs->trans($name[$i - 1]).'</option>'."\n";
1633 }
1634 }
1635
1636 $out .= "</select>\n";
1637
1638 $showempty = 0;
1639 $out .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', ($showempty < 0 ? (string) $showempty : '-1'), $morecss);
1640
1641 return $out;
1642 }
1643
1651 public function updateConfCP($name, $value)
1652 {
1653 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1654 $sql .= " value = '".$this->db->escape($value)."'";
1655 $sql .= " WHERE name = '".$this->db->escape($name)."'";
1656
1657 dol_syslog(get_class($this).'::updateConfCP name='.$name, LOG_DEBUG);
1658 $result = $this->db->query($sql);
1659 if ($result) {
1660 return true;
1661 }
1662
1663 return false;
1664 }
1665
1674 public function getConfCP($name, $createifnotfound = '')
1675 {
1676 $sql = "SELECT value";
1677 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_config";
1678 $sql .= " WHERE name = '".$this->db->escape($name)."'";
1679
1680 dol_syslog(get_class($this).'::getConfCP name='.$name.' createifnotfound='.$createifnotfound, LOG_DEBUG);
1681 $result = $this->db->query($sql);
1682
1683 if ($result) {
1684 $obj = $this->db->fetch_object($result);
1685 // Return value
1686 if (empty($obj)) {
1687 if ($createifnotfound) {
1688 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_config(name, value)";
1689 $sql .= " VALUES('".$this->db->escape($name)."', '".$this->db->escape($createifnotfound)."')";
1690 $result = $this->db->query($sql);
1691 if ($result) {
1692 return $createifnotfound;
1693 } else {
1694 $this->error = $this->db->lasterror();
1695 return -2;
1696 }
1697 } else {
1698 return '';
1699 }
1700 } else {
1701 return $obj->value;
1702 }
1703 } else {
1704 // Erreur SQL
1705 $this->error = $this->db->lasterror();
1706 return -1;
1707 }
1708 }
1709
1718 public function updateSoldeCP($userID = 0, $nbHoliday = 0, $fk_type = 0)
1719 {
1720 global $user, $langs;
1721
1722 $error = 0;
1723
1724 if (empty($userID) && empty($nbHoliday) && empty($fk_type)) {
1725 include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
1726 $langs->load("holiday");
1727
1728 $decrease = getDolGlobalInt('HOLIDAY_DECREASE_AT_END_OF_MONTH');
1729
1730 // If updated for everyone at the beginning of the month
1731 $now = dol_now();
1732
1733 // Get month of last update
1734 $stringInDBForLastUpdate = $this->getConfCP('lastUpdate', dol_print_date($now, '%Y%m%d%H%M%S')); // Example '20200101120000'
1735 // The lastUpdate config row is created empty (value NULL) at install, so getConfCP() returns an empty value
1736 // the first time. Treat an empty value as "start from now" instead of a very old date, otherwise the catch-up
1737 // loop below would credit every user with years of monthly accrual at once. Store it, because the loop is the
1738 // only other place that writes it: an empty value would stay empty and no month would ever be credited.
1739 if (empty($stringInDBForLastUpdate)) {
1740 $stringInDBForLastUpdate = dol_print_date($now, '%Y%m%d%H%M%S');
1741
1742 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1743 $sql .= " value = '".$this->db->escape($stringInDBForLastUpdate)."'";
1744 $sql .= " WHERE name = 'lastUpdate'";
1745 $result = $this->db->query($sql);
1746 if (!$result) {
1747 $this->error = $this->db->lasterror();
1748 return -1;
1749 }
1750 }
1751 // Protection when $lastUpdate has a not valid value
1752 if ($stringInDBForLastUpdate < '20000101000000') {
1753 $stringInDBForLastUpdate = '20000101000000';
1754 }
1755 $lastUpdate = dol_stringtotime($stringInDBForLastUpdate);
1756 //print 'lastUpdate:'.$lastUpdate;exit;
1757
1758 $yearMonthLastUpdate = dol_print_date($lastUpdate, '%Y%m');
1759 $yearMonthNow = dol_print_date($now, '%Y%m');
1760 //print 'yearMonthLastUpdate='.$yearMonthLastUpdate.' yearMonthNow='.$yearMonthNow;
1761
1762 // If month date is not same than the one of last update (the one we saved in database), then we update the timestamp and balance of each open user,
1763 // catching up to the current month if a gap is detected
1764 while ($yearMonthLastUpdate < $yearMonthNow) {
1765 $this->db->begin();
1766
1767 $year = dol_print_date($lastUpdate, '%Y');
1768 $month = dol_print_date($lastUpdate, '%m');
1769
1770 $users = $this->fetchUsers(false, false, ' AND u.statut > 0');
1771 $nbUser = count($users);
1772
1773 $typeleaves = $this->getTypes(1, 1);
1774
1775 // Update each user counter
1776 foreach ($users as $userCounter) {
1777 $nbDaysToAdd = (isset($typeleaves[$userCounter['type']]['newbymonth']) ? $typeleaves[$userCounter['type']]['newbymonth'] : 0);
1778 if (empty($nbDaysToAdd)) {
1779 continue;
1780 }
1781
1782 dol_syslog("We update leave type id ".$userCounter['type']." for user id ".$userCounter['rowid'], LOG_DEBUG);
1783
1784 $nowHoliday = (float) $userCounter['nb_holiday'];
1785 $newSolde = $nowHoliday + $nbDaysToAdd;
1786
1787 // We add a log for each user when its balance gets increased
1788 $this->addLogCP($user->id, $userCounter['rowid'], $langs->trans('HolidayMonthlyCredit'), $newSolde, $userCounter['type']);
1789
1790 $result = $this->updateSoldeCP($userCounter['rowid'], $newSolde, $userCounter['type']);
1791
1792 if ($result < 0) {
1793 $this->db->rollback();
1794 return -1;
1795 }
1796
1797 if (empty($decrease)) {
1798 continue;
1799 }
1800
1801 // We fetch a user's holiday in the current month and then calculate the number of days to deduct if he has at least one registered
1802 $filter = " AND cp.statut = ".((int) self::STATUS_APPROVED);
1803 $filter .= " AND cp.date_fin >= '".$this->db->idate(dol_stringtotime(dol_print_date($lastUpdate, '%Y-%m-01')))."'";
1804 $filter .= " AND cp.date_debut <= '".$this->db->idate(dol_stringtotime(dol_print_date($lastUpdate, '%Y-%m-t')))."'";
1805 $filter .= " AND cp.fk_type = ".((int) $userCounter['type']);
1806 $this->fetchByUser($userCounter['id'], '', $filter);
1807
1808 if (empty($this->holiday)) {
1809 continue;
1810 }
1811
1812 $startOfMonth = dol_mktime(0, 0, 0, (int) $month, 1, (int) $year, 1);
1813 $endOfMonth = dol_mktime(0, 0, 0, (int) $month, (int) dol_print_date($lastUpdate, 't'), (int) $year, 1);
1814
1815 foreach ($this->holiday as $obj) {
1816 $startDate = $obj['date_debut_gmt'];
1817 $endDate = $obj['date_fin_gmt'];
1818
1819 if ($startDate <= $endOfMonth && $startDate < $startOfMonth) {
1820 $startDate = $startOfMonth;
1821 }
1822
1823 if ($startOfMonth <= $endDate && $endDate > $endOfMonth) {
1824 $endDate = $endOfMonth;
1825 }
1826
1827 $nbDaysToDeduct = (float) num_open_day($startDate, $endDate, 0, 1, $obj['halfday'], $obj['country_id'], $obj['fk_user']);
1828
1829 if ($nbDaysToDeduct <= 0) {
1830 continue;
1831 }
1832
1833 $newSolde -= $nbDaysToDeduct;
1834
1835 // We add a log for each user when its balance gets decreased
1836 $this->addLogCP($user->id, $userCounter['rowid'], $obj['ref'].' - '.$langs->trans('HolidayConsumption'), $newSolde, $userCounter['type']);
1837
1838 $result = $this->updateSoldeCP($userCounter['rowid'], $newSolde, $userCounter['type']);
1839
1840 if ($result < 0) {
1841 $this->db->rollback();
1842 return -1;
1843 }
1844 }
1845 }
1846
1847 // Updating the date of the last monthly balance update
1848 $newMonth = dol_get_next_month((int) dol_print_date($lastUpdate, '%m'), (int) dol_print_date($lastUpdate, '%Y'));
1849 $lastUpdate = dol_mktime(0, 0, 0, (int) $newMonth['month'], 1, (int) $newMonth['year']);
1850
1851 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1852 $sql .= " value = '".$this->db->escape(dol_print_date($lastUpdate, '%Y%m%d%H%M%S'))."'";
1853 $sql .= " WHERE name = 'lastUpdate'";
1854 $result = $this->db->query($sql);
1855
1856 if (!$result) {
1857 $this->db->rollback();
1858 return -1;
1859 }
1860
1861 $this->db->commit();
1862
1863 $yearMonthLastUpdate = dol_print_date($lastUpdate, '%Y%m');
1864 }
1865
1866 return 1;
1867 } else {
1868 // Update for one user
1869 $nbHoliday = price2num($nbHoliday, 5);
1870
1871 $sql = "SELECT nb_holiday FROM ".MAIN_DB_PREFIX."holiday_users";
1872 $sql .= " WHERE fk_user = ".(int) $userID." AND fk_type = ".(int) $fk_type;
1873 $resql = $this->db->query($sql);
1874 if ($resql) {
1875 $num = $this->db->num_rows($resql);
1876
1877 if ($num > 0) {
1878 // Update for user
1879 $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET";
1880 $sql .= " nb_holiday = ".((float) $nbHoliday);
1881 $sql .= " WHERE fk_user = ".(int) $userID." AND fk_type = ".(int) $fk_type;
1882 $result = $this->db->query($sql);
1883 if (!$result) {
1884 $error++;
1885 $this->errors[] = $this->db->lasterror();
1886 }
1887 } else {
1888 // Insert for user
1889 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users(nb_holiday, fk_user, fk_type) VALUES (";
1890 $sql .= ((float) $nbHoliday);
1891 $sql .= ", ".(int) $userID.", ".(int) $fk_type.")";
1892 $result = $this->db->query($sql);
1893 if (!$result) {
1894 $error++;
1895 $this->errors[] = $this->db->lasterror();
1896 }
1897 }
1898 } else {
1899 $this->errors[] = $this->db->lasterror();
1900 $error++;
1901 }
1902
1903 if (!$error) {
1904 return 1;
1905 } else {
1906 return -1;
1907 }
1908 }
1909 }
1910
1918 public function createCPusers($single = false, $userid = 0)
1919 {
1920 // do we have to add balance for all users ?
1921 if (!$single) {
1922 dol_syslog(get_class($this).'::createCPusers');
1923 $arrayofusers = $this->fetchUsers(false, true);
1924
1925 foreach ($arrayofusers as $users) {
1926 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users";
1927 $sql .= " (fk_user, nb_holiday)";
1928 $sql .= " VALUES (".((int) $users['rowid'])."', '0')";
1929
1930 $resql = $this->db->query($sql);
1931 if (!$resql) {
1932 dol_print_error($this->db);
1933 }
1934 }
1935 } else {
1936 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users";
1937 $sql .= " (fk_user, nb_holiday)";
1938 $sql .= " VALUES (".((int) $userid)."', '0')";
1939
1940 $resql = $this->db->query($sql);
1941 if (!$resql) {
1942 dol_print_error($this->db);
1943 }
1944 }
1945 }
1946
1954 public function getCPforUser($user_id, $fk_type = 0)
1955 {
1956 $sql = "SELECT nb_holiday";
1957 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users";
1958 $sql .= " WHERE fk_user = ".(int) $user_id;
1959 if ($fk_type > 0) {
1960 $sql .= " AND fk_type = ".(int) $fk_type;
1961 }
1962
1963 dol_syslog(get_class($this).'::getCPforUser user_id='.$user_id.' type_id='.$fk_type, LOG_DEBUG);
1964 $result = $this->db->query($sql);
1965 if ($result) {
1966 $obj = $this->db->fetch_object($result);
1967 //return number_format($obj->nb_holiday,2);
1968 if ($obj) {
1969 return $obj->nb_holiday;
1970 } else {
1971 return null;
1972 }
1973 } else {
1974 return null;
1975 }
1976 }
1977
1986 public function fetchUsers($stringlist = true, $type = true, $sqlFilters = '')
1987 {
1988 dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG);
1989
1990 if ($stringlist) {
1991 if ($type) {
1992 // If user of Dolibarr
1993 $sql = "SELECT";
1994 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
1995 $sql .= " DISTINCT";
1996 }
1997 $sql .= " u.rowid";
1998 $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
1999
2000 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2001 $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2002 $sql .= " WHERE ((ug.fk_user = u.rowid";
2003 $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
2004 $sql .= " OR u.entity = 0)"; // Show always superadmin
2005 } else {
2006 $sql .= " WHERE u.entity IN (".getEntity('user').")";
2007 }
2008 $sql .= " AND u.statut > 0";
2009 $sql .= " AND u.employee = 1"; // We only want employee users for holidays
2010 if ($sqlFilters) {
2011 $sql .= $sqlFilters;
2012 }
2013
2014 $resql = $this->db->query($sql);
2015
2016 // If no SQL error
2017 if ($resql) {
2018 $i = 0;
2019 $num = $this->db->num_rows($resql);
2020 $stringlist = '';
2021
2022 // User listing loops
2023 while ($i < $num) {
2024 $obj = $this->db->fetch_object($resql);
2025
2026 if ($i == 0) {
2027 $stringlist .= $obj->rowid;
2028 } else {
2029 $stringlist .= ', '.$obj->rowid;
2030 }
2031
2032 $i++;
2033 }
2034 // Returns the user table
2035 return $stringlist;
2036 } else {
2037 // SQL error
2038 $this->error = "Error ".$this->db->lasterror();
2039 return -1;
2040 }
2041 } else {
2042 // We want only list of vacation balance for user ids
2043 $sql = "SELECT DISTINCT cpu.fk_user";
2044 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
2045 $sql .= " WHERE cpu.fk_user = u.rowid";
2046 if ($sqlFilters) {
2047 $sql .= $sqlFilters;
2048 }
2049
2050 $resql = $this->db->query($sql);
2051
2052 // If no SQL error
2053 if ($resql) {
2054 $i = 0;
2055 $num = $this->db->num_rows($resql);
2056 $stringlist = '';
2057
2058 // User listing loops
2059 while ($i < $num) {
2060 $obj = $this->db->fetch_object($resql);
2061
2062 if ($i == 0) {
2063 $stringlist .= $obj->fk_user;
2064 } else {
2065 $stringlist .= ', '.$obj->fk_user;
2066 }
2067
2068 $i++;
2069 }
2070 // Returns the user table
2071 return $stringlist;
2072 } else {
2073 // SQL error
2074 $this->error = "Error ".$this->db->lasterror();
2075 return -1;
2076 }
2077 }
2078 } else {
2079 // If false, return array
2080 // List for Dolibarr users
2081 if ($type) {
2082 // If we need users of Dolibarr
2083 $sql = "SELECT";
2084 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2085 $sql .= " DISTINCT";
2086 }
2087 $sql .= " u.rowid, u.lastname, u.firstname, u.gender, u.fk_country as country_id, u.photo, u.employee, u.statut as status, u.fk_user";
2088 $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
2089
2090 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE')) {
2091 $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
2092 $sql .= " WHERE ((ug.fk_user = u.rowid";
2093 $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
2094 $sql .= " OR u.entity = 0)"; // Show always superadmin
2095 } else {
2096 $sql .= " WHERE u.entity IN (".getEntity('user').")";
2097 }
2098
2099 $sql .= " AND u.statut > 0";
2100 $sql .= " AND u.employee = 1"; // We only want employee users for holidays
2101 if ($sqlFilters) {
2102 $sql .= $sqlFilters;
2103 }
2104
2105 $resql = $this->db->query($sql);
2106
2107 // If no SQL error
2108 if ($resql) {
2109 $i = 0;
2110 $tab_result = $this->holiday;
2111 $num = $this->db->num_rows($resql);
2112
2113 // User listing loops
2114 while ($i < $num) {
2115 $obj = $this->db->fetch_object($resql);
2116
2117 $tab_result[$i]['rowid'] = (int) $obj->rowid; // rowid of user
2118 $tab_result[$i]['id'] = (int) $obj->rowid; // id of user
2119 $tab_result[$i]['name'] = $obj->lastname; // deprecated
2120 $tab_result[$i]['lastname'] = $obj->lastname;
2121 $tab_result[$i]['firstname'] = $obj->firstname;
2122 $tab_result[$i]['gender'] = $obj->gender;
2123 $tab_result[$i]['status'] = (int) $obj->status;
2124 $tab_result[$i]['employee'] = (int) $obj->employee;
2125 $tab_result[$i]['photo'] = $obj->photo;
2126 $tab_result[$i]['fk_user'] = (int) $obj->fk_user; // rowid of manager
2127 $tab_result[$i]['country_id'] = (int) $obj->country_id; // id of country of user
2128 //$tab_result[$i]['type'] = $obj->type;
2129 //$tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
2130
2131 $i++;
2132 }
2133 // Returns the user table
2134 return $tab_result;
2135 } else {
2136 // SQL error
2137 $this->errors[] = "Error ".$this->db->lasterror();
2138 return -1;
2139 }
2140 } else {
2141 // List of vacation balance users
2142 $sql = "SELECT cpu.fk_type, cpu.nb_holiday, u.rowid, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut as status, u.fk_user";
2143 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
2144 $sql .= " WHERE cpu.fk_user = u.rowid";
2145 if ($sqlFilters) {
2146 $sql .= $sqlFilters;
2147 }
2148
2149 $resql = $this->db->query($sql);
2150
2151 // If no SQL error
2152 if ($resql) {
2153 $i = 0;
2154 $tab_result = $this->holiday;
2155 $num = $this->db->num_rows($resql);
2156
2157 // User listing loops
2158 while ($i < $num) {
2159 $obj = $this->db->fetch_object($resql);
2160
2161 $tab_result[$i]['rowid'] = $obj->rowid; // rowid of user
2162 $tab_result[$i]['id'] = $obj->rowid; // id of user
2163 $tab_result[$i]['name'] = $obj->lastname; // deprecated
2164 $tab_result[$i]['lastname'] = $obj->lastname;
2165 $tab_result[$i]['firstname'] = $obj->firstname;
2166 $tab_result[$i]['gender'] = $obj->gender;
2167 $tab_result[$i]['status'] = $obj->status;
2168 $tab_result[$i]['employee'] = $obj->employee;
2169 $tab_result[$i]['photo'] = $obj->photo;
2170 $tab_result[$i]['fk_user'] = $obj->fk_user; // rowid of manager
2171
2172 $tab_result[$i]['type'] = $obj->fk_type;
2173 $tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
2174
2175 $i++;
2176 }
2177 // Returns the user table
2178 return $tab_result;
2179 } else {
2180 // SQL error
2181 $this->error = "Error ".$this->db->lasterror();
2182 return -1;
2183 }
2184 }
2185 }
2186 }
2187
2188
2189 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2197 {
2198 // phpcs:enable
2199 $users_validator = array();
2200
2201 $sql = "SELECT DISTINCT ur.fk_user";
2202 $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2203 $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'"; // Permission 'Approve';
2204 $sql .= "UNION";
2205 $sql .= " SELECT DISTINCT ugu.fk_user";
2206 $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
2207 $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'"; // Permission 'Approve';
2208 //print $sql;
2209
2210 dol_syslog(get_class($this)."::fetch_users_approver_holiday sql=".$sql);
2211 $result = $this->db->query($sql);
2212 if ($result) {
2213 $num_rows = $this->db->num_rows($result);
2214 $i = 0;
2215 while ($i < $num_rows) {
2216 $objp = $this->db->fetch_object($result);
2217 array_push($users_validator, $objp->fk_user);
2218 $i++;
2219 }
2220 return $users_validator;
2221 } else {
2222 $this->error = $this->db->lasterror();
2223 dol_syslog(get_class($this)."::fetch_users_approver_holiday Error ".$this->error, LOG_ERR);
2224 return -1;
2225 }
2226 }
2227
2228
2234 public function countActiveUsers()
2235 {
2236 $sql = "SELECT count(u.rowid) as compteur";
2237 $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
2238 $sql .= " WHERE u.statut > 0";
2239
2240 $result = $this->db->query($sql);
2241 $object = $this->db->fetch_object($result);
2242
2243 return $object->compteur;
2244 }
2251 {
2252 $sql = "SELECT count(u.rowid) as compteur";
2253 $sql .= " FROM ".MAIN_DB_PREFIX."user as u LEFT JOIN ".MAIN_DB_PREFIX."holiday_users hu ON (hu.fk_user=u.rowid)";
2254 $sql .= " WHERE u.statut > 0 AND hu.fk_user IS NULL";
2255
2256 $result = $this->db->query($sql);
2257 $object = $this->db->fetch_object($result);
2258
2259 return $object->compteur;
2260 }
2261
2269 public function verifNbUsers($userDolibarrWithoutCP, $userCP)
2270 {
2271 if (empty($userCP)) {
2272 $userCP = 0;
2273 }
2274 dol_syslog(get_class($this).'::verifNbUsers userDolibarr='.$userDolibarrWithoutCP.' userCP='.$userCP);
2275 return 1;
2276 }
2277
2278
2289 public function addLogCP($fk_user_action, $fk_user_update, $label, $new_solde, $fk_type)
2290 {
2291 $error = 0;
2292
2293 $prev_solde = price2num((float) $this->getCPforUser($fk_user_update, $fk_type), 5);
2294 $new_solde = price2num($new_solde, 5);
2295 //print "$prev_solde == $new_solde";
2296
2297 if ($prev_solde == $new_solde) {
2298 return 0;
2299 }
2300
2301 $this->db->begin();
2302
2303 // Insert request
2304 $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_logs (";
2305 $sql .= "date_action,";
2306 $sql .= "fk_user_action,";
2307 $sql .= "fk_user_update,";
2308 $sql .= "type_action,";
2309 $sql .= "prev_solde,";
2310 $sql .= "new_solde,";
2311 $sql .= "fk_type";
2312 $sql .= ") VALUES (";
2313 $sql .= " '".$this->db->idate(dol_now())."',";
2314 $sql .= " ".((int) $fk_user_action).",";
2315 $sql .= " ".((int) $fk_user_update).",";
2316 $sql .= " '".$this->db->escape($label)."',";
2317 $sql .= " ".((float) $prev_solde).",";
2318 $sql .= " ".((float) $new_solde).",";
2319 $sql .= " ".((int) $fk_type);
2320 $sql .= ")";
2321
2322 $resql = $this->db->query($sql);
2323 if (!$resql) {
2324 $error++;
2325 $this->errors[] = "Error ".$this->db->lasterror();
2326 }
2327
2328 $optRowid = 0;
2329 if (!$error) {
2330 $optRowid = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday_logs");
2331 }
2332
2333 // Commit or rollback
2334 if ($error) {
2335 foreach ($this->errors as $errmsg) {
2336 dol_syslog(get_class($this)."::addLogCP ".$errmsg, LOG_ERR);
2337 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2338 }
2339 $this->db->rollback();
2340 return -1 * $error;
2341 } else {
2342 $this->db->commit();
2343 return $optRowid;
2344 }
2345 }
2346
2354 public function fetchLog($sqlorder, $sqlwhere)
2355 {
2356 $sql = "SELECT";
2357 $sql .= " cpl.rowid,";
2358 $sql .= " cpl.date_action,";
2359 $sql .= " cpl.fk_user_action,";
2360 $sql .= " cpl.fk_user_update,";
2361 $sql .= " cpl.type_action,";
2362 $sql .= " cpl.prev_solde,";
2363 $sql .= " cpl.new_solde,";
2364 $sql .= " cpl.fk_type";
2365 $sql .= " FROM ".MAIN_DB_PREFIX."holiday_logs as cpl";
2366 $sql .= " WHERE cpl.rowid > 0"; // To avoid error with other search and criteria
2367
2368 // Filter
2369 if (!empty($sqlwhere)) {
2370 $sql .= " ".$sqlwhere;
2371 }
2372
2373 // Order
2374 if (!empty($sqlorder)) {
2375 $sql .= " ".$sqlorder;
2376 }
2377
2378 dol_syslog(get_class($this)."::fetchLog", LOG_DEBUG);
2379 $resql = $this->db->query($sql);
2380
2381 // If no error SQL
2382 if ($resql) {
2383 $i = 0;
2384 $tab_result = $this->logs;
2385 $num = $this->db->num_rows($resql);
2386
2387 // If no record
2388 if (!$num) {
2389 return 2;
2390 }
2391
2392 // Loop on result to fill the array
2393 while ($i < $num) {
2394 $obj = $this->db->fetch_object($resql);
2395
2396 $tab_result[$i]['rowid'] = (int) $obj->rowid;
2397 $tab_result[$i]['id'] = (int) $obj->rowid;
2398 $tab_result[$i]['date_action'] = (string) $obj->date_action;
2399 $tab_result[$i]['fk_user_action'] = (int) $obj->fk_user_action;
2400 $tab_result[$i]['fk_user_update'] = (int) $obj->fk_user_update;
2401 $tab_result[$i]['type_action'] = (string) $obj->type_action;
2402 $tab_result[$i]['prev_solde'] = (float) $obj->prev_solde;
2403 $tab_result[$i]['new_solde'] = (float) $obj->new_solde;
2404 $tab_result[$i]['fk_type'] = (int) $obj->fk_type;
2405
2406 $i++;
2407 }
2408 // Returns 1 and adds the array to the variable
2409 $this->logs = $tab_result;
2410 return 1;
2411 } else {
2412 // SQL error
2413 $this->error = "Error ".$this->db->lasterror();
2414 return -1;
2415 }
2416 }
2417
2418
2426 public function getTypes($active = -1, $affect = -1)
2427 {
2428 global $mysoc;
2429
2430 $sql = "SELECT rowid, code, label, affect, delay, newbymonth";
2431 $sql .= " FROM ".MAIN_DB_PREFIX."c_holiday_types";
2432 $sql .= " WHERE (fk_country IS NULL OR fk_country = ".((int) $mysoc->country_id).')';
2433 $sql .= " AND entity IN (0, ".getEntity('c_holiday_types').")"; // Need entity 0 (holiday types common to all countries= + current entity).
2434 if ($active >= 0) {
2435 $sql .= " AND active = ".((int) $active);
2436 }
2437 if ($affect >= 0) {
2438 $sql .= " AND affect = ".((int) $affect);
2439 }
2440 $sql .= " ORDER BY sortorder";
2441
2442 $result = $this->db->query($sql);
2443 if ($result) {
2444 $num = $this->db->num_rows($result);
2445 if ($num) {
2446 $types = array();
2447 while ($obj = $this->db->fetch_object($result)) {
2448 $types[$obj->rowid] = array(
2449 'id' => $obj->rowid,
2450 'rowid' => $obj->rowid,
2451 'code' => $obj->code,
2452 'label' => $obj->label,
2453 'affect' => $obj->affect,
2454 'delay' => $obj->delay,
2455 'newbymonth' => $obj->newbymonth
2456 );
2457 }
2458
2459 return $types;
2460 }
2461 } else {
2462 dol_print_error($this->db);
2463 }
2464
2465 return array();
2466 }
2467
2468
2475 public function info($id)
2476 {
2477 global $conf;
2478
2479 $sql = "SELECT f.rowid, f.statut as status,";
2480 $sql .= " f.date_create as datec,";
2481 $sql .= " f.tms as date_modification,";
2482 $sql .= " f.date_valid as datev,";
2483 $sql .= " f.date_approval as datea,";
2484 $sql .= " f.date_refuse as dater,";
2485 $sql .= " f.fk_user_create as fk_user_creation,";
2486 $sql .= " f.fk_user_modif as fk_user_modification,";
2487 $sql .= " f.fk_user_valid as fk_user_validation,";
2488 $sql .= " f.fk_user_approve as fk_user_approval_done,";
2489 $sql .= " f.fk_validator as fk_user_approval_expected,";
2490 $sql .= " f.fk_user_refuse as fk_user_refuse";
2491 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as f";
2492 $sql .= " WHERE f.rowid = ".((int) $id);
2493 $sql .= " AND f.entity = ".((int) $conf->entity);
2494
2495 $resql = $this->db->query($sql);
2496 if ($resql) {
2497 if ($this->db->num_rows($resql)) {
2498 $obj = $this->db->fetch_object($resql);
2499
2500 $this->id = $obj->rowid;
2501
2502 $this->date_creation = $this->db->jdate($obj->datec);
2503 $this->date_modification = $this->db->jdate($obj->date_modification);
2504 $this->date_validation = $this->db->jdate($obj->datev);
2505 $this->date_approval = $this->db->jdate($obj->datea);
2506
2507 $this->user_creation_id = $obj->fk_user_creation;
2508 $this->user_validation_id = $obj->fk_user_validation;
2509 $this->user_modification_id = $obj->fk_user_modification;
2510
2511 if ($obj->status == Holiday::STATUS_APPROVED || $obj->status == Holiday::STATUS_CANCELED) {
2512 if ($obj->fk_user_approval_done) {
2513 $this->fk_user_approve = $obj->fk_user_approval_done;
2514 $this->user_approve_id = $obj->fk_user_approval_done;
2515 }
2516 }
2517 }
2518 $this->db->free($resql);
2519 } else {
2520 dol_print_error($this->db);
2521 }
2522 }
2523
2524
2532 public function initAsSpecimen()
2533 {
2534 global $user, $langs;
2535
2536 // Initialise parameters
2537 $this->id = 0;
2538 $this->specimen = 1;
2539
2540 $this->fk_user = $user->id;
2541 $this->description = 'SPECIMEN description';
2542 $this->date_debut = dol_now();
2543 $this->date_fin = dol_now() + (24 * 3600);
2544 $this->date_valid = dol_now();
2545 $this->fk_validator = $user->id;
2546 $this->halfday = 0;
2547 $this->fk_type = 1;
2549
2550 return 1;
2551 }
2552
2558 public function loadStateBoard()
2559 {
2560 global $user;
2561
2562 $this->nb = array();
2563
2564 $sql = "SELECT count(h.rowid) as nb";
2565 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
2566 $sql .= " WHERE h.statut > 1";
2567 $sql .= " AND h.entity IN (".getEntity('holiday').")";
2568 if (!$user->hasRight('holiday', 'readall')) {
2569 $userchildids = $user->getAllChildIds(1);
2570 $sql .= " AND (h.fk_user IN (".$this->db->sanitize(implode(',', $userchildids)).")";
2571 $sql .= " OR h.fk_validator IN (".$this->db->sanitize(implode(',', $userchildids))."))";
2572 }
2573
2574 $resql = $this->db->query($sql);
2575 if ($resql) {
2576 while ($obj = $this->db->fetch_object($resql)) {
2577 $this->nb["holidays"] = $obj->nb;
2578 }
2579 $this->db->free($resql);
2580 return 1;
2581 } else {
2582 dol_print_error($this->db);
2583 $this->error = $this->db->error();
2584 return -1;
2585 }
2586 }
2587
2588 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2595 public function load_board($user)
2596 {
2597 // phpcs:enable
2598 global $conf, $langs;
2599
2600 if ($user->socid) {
2601 return -1; // Protection to prevent calls by external users
2602 }
2603
2604 $now = dol_now();
2605
2606 $sql = "SELECT h.rowid, h.date_debut";
2607 $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
2608 $sql .= " WHERE h.statut = 2";
2609 $sql .= " AND h.entity IN (".getEntity('holiday').")";
2610 if (!$user->hasRight('holiday', 'read_all')) {
2611 $userchildids = $user->getAllChildIds(1);
2612 $sql .= " AND (h.fk_user IN (".$this->db->sanitize(implode(',', $userchildids)).")";
2613 $sql .= " OR h.fk_validator IN (".$this->db->sanitize(implode(',', $userchildids))."))";
2614 }
2615
2616 $resql = $this->db->query($sql);
2617 if ($resql) {
2618 $langs->load("members");
2619
2620 $response = new WorkboardResponse();
2621 $response->warning_delay = $conf->holiday->approve->warning_delay / 60 / 60 / 24;
2622 $response->label = $langs->trans("HolidaysToApprove");
2623 $response->labelShort = $langs->trans("ToApprove");
2624 $response->url = DOL_URL_ROOT.'/holiday/list.php?search_status=2&amp;mainmenu=hrm&amp;leftmenu=holiday';
2625 $response->img = img_object('', "holiday");
2626
2627 while ($obj = $this->db->fetch_object($resql)) {
2628 $response->nbtodo++;
2629
2630 if ($this->db->jdate($obj->date_debut) < ($now - $conf->holiday->approve->warning_delay)) {
2631 $response->nbtodolate++;
2632 }
2633 }
2634
2635 return $response;
2636 } else {
2637 dol_print_error($this->db);
2638 $this->error = $this->db->error();
2639 return -1;
2640 }
2641 }
2649 public function getKanbanView($option = '', $arraydata = null)
2650 {
2651 global $langs;
2652
2653 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2654
2655 $return = '<div class="box-flex-item box-flex-grow-zero">';
2656 $return .= '<div class="info-box info-box-sm">';
2657 $return .= '<span class="info-box-icon bg-infobox-action">';
2658 $return .= img_picto('', $this->picto);
2659 $return .= '</span>';
2660 $return .= '<div class="info-box-content">';
2661 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.$this->getNomUrl().'</span>';
2662 if ($selected >= 0) {
2663 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2664 }
2665 if (property_exists($this, 'fk_type')) {
2666 $return .= '<br>';
2667 //$return .= '<span class="opacitymedium">'.$langs->trans("Type").'</span> : ';
2668 $return .= '<div class="info_box-label tdoverflowmax100" title="'.dol_escape_htmltag($arraydata['labeltype']).'">'.dol_escape_htmltag($arraydata['labeltype']).'</div>';
2669 }
2670 if (property_exists($this, 'date_debut') && property_exists($this, 'date_fin')) {
2671 $return .= '<span class="info-box-label small">'.dol_print_date($this->date_debut, 'day').'</span>';
2672 $return .= ' <span class="opacitymedium small">'.$langs->trans("To").'</span> ';
2673 $return .= '<span class="info-box-label small">'.dol_print_date($this->date_fin, 'day').'</span>';
2674 if (!empty($arraydata['nbopenedday'])) {
2675 $return .= ' ('.$arraydata['nbopenedday'].')';
2676 }
2677 }
2678 if (method_exists($this, 'getLibStatut')) {
2679 $return .= '<div class="info-box-status">'.$this->getLibStatut(3).'</div>';
2680 }
2681 $return .= '</div>';
2682 $return .= '</div>';
2683 $return .= '</div>';
2684 return $return;
2685 }
2686
2697 public function sendPreviousMonthHRInformations($mailto = "", $template = "", $newlang = "")
2698 {
2699 global $conf, $langs, $user;
2700
2701 $outputlangs = $langs;
2702
2703 $error = 0;
2704 $this->output = '';
2705 $this->error = '';
2706 $arrayfields = array(
2707 'user' => 'Employee',
2708 'type' => 'Type',
2709 'date_start' => 'DateDebCP',
2710 'date_end' => 'DateFinCP',
2711 'used_days' => 'NbUseDaysCPShort',
2712 );
2713
2714 if (!empty($newlang)) {
2715 $outputlangs = new Translate("", $conf);
2716 $outputlangs->setDefaultLang($newlang);
2717 }
2718 $outputlangs->loadLangs(array('main', 'holiday', 'hrm'));
2719
2720 if (empty($mailto) || !isValidEmail($mailto)) {
2721 $this->errors[] = 'Bad value for parameter mailto. Must be a valid email address.';
2722 return 1;
2723 }
2724
2725 $typeleaves = $this->getTypes(1, -1);
2726 $arraytypeleaves = array();
2727 foreach ($typeleaves as $val) {
2728 $labeltoshow = ($outputlangs->trans($val['code']) != $val['code'] ? $outputlangs->trans($val['code']) : $val['label']);
2729 $arraytypeleaves[$val['rowid']] = $labeltoshow;
2730 }
2731 $listhalfday = array('morning' => $outputlangs->trans("Morning"), "afternoon" => $outputlangs->trans("Afternoon"));
2732
2733 $datenow = dol_getdate(dol_now());
2734 $prev_month = dol_get_prev_month($datenow["mon"], $datenow["year"]);
2735 $year_month = sprintf("%04d", $prev_month["year"]).'-'.sprintf("%02d", $prev_month["month"]);
2736 $arrayleaves = array();
2737
2738 $sql = "SELECT cp.rowid, cp.ref, cp.fk_user, cp.date_debut, cp.date_fin, cp.fk_type, cp.description, cp.halfday, cp.statut as status";
2739 $sql .= " FROM ".MAIN_DB_PREFIX."holiday cp";
2740 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user u ON cp.fk_user = u.rowid";
2741 $sql .= " WHERE cp.entity IN (".getEntity('holiday').") AND cp.rowid > 0";
2742 $sql .= " AND cp.statut = ".Holiday::STATUS_APPROVED;
2743 $sql .= " AND (";
2744 $sql .= " (date_format(cp.date_debut, '%Y-%m') = '".$this->db->escape($year_month)."' OR date_format(cp.date_fin, '%Y-%m') = '".$this->db->escape($year_month)."')";
2745 $sql .= " OR"; // For leave over several months
2746 $sql .= " (date_format(cp.date_debut, '%Y-%m') < '".$this->db->escape($year_month)."' AND date_format(cp.date_fin, '%Y-%m') > '".$this->db->escape($year_month)."') ";
2747 $sql .= " )";
2748 $sql .= $this->db->order("cp.fk_user, cp.date_debut", "ASC");
2749 $resql = $this->db->query($sql);
2750 if (empty($resql)) {
2751 $this->errors[] = $this->db->lasterror();
2752 return 1;
2753 }
2754 $num = $this->db->num_rows($resql);
2755 if ($num > 0) {
2756 $tmpuser = new User($this->db);
2757 while ($obj = $this->db->fetch_object($resql)) {
2758 $tmpuser->fetch($obj->fk_user);
2759
2760 $date_start = $this->db->jdate($obj->date_debut, true);
2761 $date_end = $this->db->jdate($obj->date_fin, true);
2762
2763 $tmpstart = dol_getdate($date_start);
2764 $tmpend = dol_getdate($date_end);
2765
2766 $starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning';
2767 $endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon';
2768
2769 $halfdayinmonth = $obj->halfday;
2770 $starthalfdayinmonth = $starthalfday;
2771 $endhalfdayinmonth = $endhalfday;
2772
2773 //0:Full days, 2:Start afternoon end morning, -1:Start afternoon end afternoon, 1:Start morning end morning
2774
2775 // Set date_start_gmt and date_end_gmt that are date to show for the selected month
2776 $date_start_inmonth = $this->db->jdate($obj->date_debut, true);
2777 $date_end_inmonth = $this->db->jdate($obj->date_fin, true);
2778 if ($tmpstart['year'] < $prev_month["year"] || $tmpstart['mon'] < $prev_month["month"]) {
2779 $date_start_inmonth = dol_get_first_day($prev_month["year"], $prev_month["month"], true);
2780 $starthalfdayinmonth = 'morning';
2781 if ($halfdayinmonth == 2) {
2782 $halfdayinmonth = 1;
2783 }
2784 if ($halfdayinmonth == -1) {
2785 $halfdayinmonth = 0;
2786 }
2787 }
2788 if ($tmpend['year'] > $prev_month["year"] || $tmpend['mon'] > $prev_month["month"]) {
2789 $date_end_inmonth = dol_get_last_day($prev_month["year"], $prev_month["month"], true) - ((24 * 3600) - 1);
2790 $endhalfdayinmonth = 'afternoon';
2791 if ($halfdayinmonth == 2) {
2792 $halfdayinmonth = -1;
2793 }
2794 if ($halfdayinmonth == 1) {
2795 $halfdayinmonth = 0;
2796 }
2797 }
2798 $arrayleaves[] = array(
2799 "user" => $tmpuser->getNomUrl(0, 'nolink', 0, 0, 24, 1),
2800 "type" => $arraytypeleaves[$obj->fk_type],
2801 "date_start" => dol_print_date($date_start_inmonth, 'day') . ' <span class="opacitymedium">('.$outputlangs->trans($listhalfday[$starthalfdayinmonth]).')</span>',
2802 "date_end" => dol_print_date($date_end_inmonth, 'day') . ' <span class="opacitymedium">('.$outputlangs->trans($listhalfday[$endhalfdayinmonth]).')</span>',
2803 "used_days" => num_open_day($date_start_inmonth, $date_end_inmonth, 0, 1, $halfdayinmonth, $tmpuser->country_id, $obj->fk_user)
2804 );
2805 }
2806 }
2807
2808 $outputarrayleaves = '<br><table style="width: 100%;border-collapse: separate !important;border-spacing: 0px;border-top: 1px solid #b6b6b6;border-left: 1px solid #b6b6b6;border-right: 1px solid #b6b6b6;margin: 0px 0px 20px 0px;">';
2809 $outputarrayleaves .= '<tr>';
2810 foreach ($arrayfields as $key => $label) {
2811 $outputarrayleaves .= '<td style="border-bottom:1px solid #b6b6b6;padding: 6px 10px 6px 12px;">';
2812 $outputarrayleaves .= $outputlangs->trans($label);
2813 if ($key == 'date_end') {
2814 $outputarrayleaves .=" (".$langs->trans("Included").")";
2815 }
2816 $outputarrayleaves .= '</td>';
2817 }
2818 $outputarrayleaves .= '</tr>';
2819
2820 if (!empty($arrayleaves)) {
2821 foreach ($arrayleaves as $fields) {
2822 $outputarrayleaves .= '<tr>';
2823 foreach ($fields as $field => $value) {
2824 $outputarrayleaves .= '<td style="border-bottom:1px solid #b6b6b6;padding: 6px 10px 6px 12px;" id="'.$field.'">';
2825 $outputarrayleaves .= $value;
2826 $outputarrayleaves .= '</td>';
2827 }
2828 $outputarrayleaves .= '</tr>';
2829 }
2830 } else {
2831 $outputarrayleaves .= '<tr>';
2832 $outputarrayleaves .= '<td style="border-bottom:1px solid #b6b6b6;padding: 6px 10px 6px 12px;" colspan="5">';
2833 $outputarrayleaves .= $outputlangs->trans("None");
2834 $outputarrayleaves .= '</td>';
2835 $outputarrayleaves .= '</tr>';
2836 }
2837 $outputarrayleaves .= '</table>';
2838
2839 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
2840 include_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2841
2842 $formmail = new FormMail($this->db);
2843 $templateId = 0;
2844 $templateLabel = '';
2845 if (empty($template) || $template == 'EmailTemplateCode') {
2846 $templateLabel = '(HolidayHrInformationsPreviousMonth)';
2847 } else {
2848 if (is_numeric($template)) {
2849 $templateId = $template;
2850 } else {
2851 $templateLabel = $template;
2852 }
2853 }
2854 $mailtemplate = $formmail->getEMailTemplate($this->db, "holiday", $user, $outputlangs, $templateId, 1, $templateLabel);
2855
2856 if (is_numeric($mailtemplate) || empty($mailtemplate->topic)) {
2857 $this->errors[] = 'No mail template found for code "'.$templateLabel.'" or id "'.$templateId.'".';
2858 $error++;
2859 }
2860
2861 if (!$error) {
2862 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
2863 complete_substitutions_array($substitutionarray, $outputlangs, $this);
2864
2865 $subject = make_substitutions($mailtemplate->topic, $substitutionarray, $outputlangs);
2866 $msg = make_substitutions($mailtemplate->content, $substitutionarray, $outputlangs);
2867 $from = dol_string_nospecial(getDolGlobalString('MAIN_INFO_SOCIETE_NOM'), ' ', array(",")).' <' . getDolGlobalString('MAIN_INFO_SOCIETE_MAIL').'>';
2868
2869 $msg = preg_replace('/__HOLIDAY_ARRAY_PER_EMPLOYEE_FOR_PERIOD__/', $outputarrayleaves, $msg);
2870 $cmail = new CMailFile($subject, $mailto, $from, $msg, array(), array(), array(), '', '', 0, 1);
2871 $result = $cmail->sendfile();
2872 if (!$result || !empty($cmail->error) || !empty($cmail->errors)) {
2873 $this->errors[] = $cmail->error;
2874 if (is_array($cmail->errors) && count($cmail->errors) > 0) {
2875 $this->errors = array_merge($this->errors, $cmail->errors);
2876 $error++;
2877 }
2878 }
2879 }
2880
2881 if (!empty($this->errors)) {
2882 $this->output .= "\n";
2883 // The $this->errors will be concatenated to the output by the function that call this method.
2884 }
2885 return ($error ? 1 : 0);
2886 }
2887}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:476
$object ref
Definition info.php:90
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
deleteExtraFields()
Delete all extra fields values for the current object.
insertExtraFields($trigger='', $userused=null)
Add/Update all extra fields values for the current object.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class of the module paid holiday.
getTypes($active=-1, $affect=-1)
Return array with list of types.
getNomUrl($withpicto=0, $save_lastsearch_value=-1, $notooltip=0, $morecss='')
Return clickable name (with picto eventually)
verifDateHolidayCP($fk_user, $dateStart, $dateEnd, $halfday=0)
Check if a user is on holiday (partially or completely) into a period.
validate($user=null, $notrigger=0)
Validate leave request.
fetchUsers($stringlist=true, $type=true, $sqlFilters='')
Get list of Users or list of vacation balance.
info($id)
Load information on object.
updateBalance()
Update balance of vacations and check table of users for holidays is complete.
updateConfCP($name, $value)
Update an option of the Holiday module.
const STATUS_VALIDATED
Validated status.
const STATUS_DRAFT
Draft status.
fetchAll($sqlOrder, $sqlFilter)
List all holidays of all users.
fetch($id, $ref='')
Load object in memory from database.
addLogCP($fk_user_action, $fk_user_update, $label, $new_solde, $fk_type)
addLogCP
verifNbUsers($userDolibarrWithoutCP, $userCP)
Compare the number of active Dolibarr users to the number of paid leave users.
verifDateHolidayForTimestamp($fk_user, $timestamp, $status='-1')
Check that a user is not on holiday for a particular timestamp.
approve($user=null, $notrigger=0)
Approve leave request.
const STATUS_REFUSED
Refused.
getConfCP($name, $createifnotfound='')
Return value of a conf parameter for leave module TODO Move this into llx_const table.
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
initAsSpecimen()
Initialise an instance with random values.
create($user, $notrigger=0)
Create a paid leave entry in the database.
selectStatutCP($selected=0, $htmlname='select_statut', $morecss='minwidth125')
Show select with list of leave status.
countActiveUsersWithoutCP()
Count number of active users in Dolibarr without Paid leave.
updateSoldeCP($userID=0, $nbHoliday=0, $fk_type=0)
Updates the timestamp of the last CP balance update.
update($user=null, $notrigger=0)
Update database.
getCPforUser($user_id, $fk_type=0)
Return the balance of annual leave of a user.
sendPreviousMonthHRInformations($mailto="", $template="", $newlang="")
Send a mail with previous month Hr information CAN BE A CRON TASK.
fetch_users_approver_holiday()
Return list of people with permission to validate leave requests.
__construct($db)
Constructor.
loadStateBoard()
Load this->nb for dashboard.
getLibStatut($mode=0)
Returns the label status.
createCPusers($single=false, $userid=0)
Create entries for each user at setup step.
const STATUS_CANCELED
Canceled.
fetchLog($sqlorder, $sqlwhere)
List log of leaves.
countActiveUsers()
Count number of active users in Dolibarr.
fetchByUser($user_id, $order='', $filter='')
List holidays for a particular user or list of users.
const STATUS_APPROVED
Approved.
getTooltipContentArray($params)
getTooltipContentArray
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
LibStatut($status, $mode=0, $startdate='')
Returns the label of a status.
Class to manage translations.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
global $mysoc
dol_get_prev_month($month, $year)
Return previous month.
Definition date.lib.php:539
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $countryCodeOrId='', $user_id=0)
Function to return number of working days (and text of units) between two dates (working days)
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:620
dol_get_next_month($month, $year)
Return next month.
Definition date.lib.php:558
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:451
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:639
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:64
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
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...
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
isValidEmail($address, $acceptsupervisorkey=0, $acceptuserkey=0)
Return true if email syntax is ok.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php