dolibarr  16.0.1
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-2021 Frédéric France <frederic.france@netlogic.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program. If not, see <https://www.gnu.org/licenses/>.
21  */
22 
28 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
29 
30 
34 class Holiday extends CommonObject
35 {
39  public $element = 'holiday';
40 
44  public $table_element = 'holiday';
45 
50  public $ismultientitymanaged = 0;
51 
55  public $fk_element = 'fk_holiday';
56 
60  public $picto = 'holiday';
61 
66  public $rowid;
67 
71  public $fk_user;
72 
73  public $date_create = '';
74 
78  public $description;
79 
80  public $date_debut = ''; // Date start in PHP server TZ
81  public $date_fin = ''; // Date end in PHP server TZ
82  public $date_debut_gmt = ''; // Date start in GMT
83  public $date_fin_gmt = ''; // Date end in GMT
84  public $halfday = ''; // 0:Full days, 2:Start afternoon end morning, -1:Start afternoon end afternoon, 1:Start morning end morning
85  public $statut = ''; // 1=draft, 2=validated, 3=approved
86 
90  public $fk_validator;
91 
95  public $date_valid = '';
96 
100  public $fk_user_valid;
101 
105  public $date_approbation;
106 
110  public $date_refuse = '';
111 
115  public $fk_user_refuse;
116 
120  public $date_cancel = '';
121 
125  public $fk_user_cancel;
126 
127 
128  public $detail_refuse = '';
129 
133  public $fk_type;
134 
135  public $holiday = array();
136  public $events = array();
137  public $logs = array();
138 
139  public $optName = '';
140  public $optValue = '';
141  public $optRowid = '';
142 
146  const STATUS_DRAFT = 1;
150  const STATUS_VALIDATED = 2;
154  const STATUS_APPROVED = 3;
158  const STATUS_CANCELED = 4;
162  const STATUS_REFUSED = 5;
163 
164 
170  public function __construct($db)
171  {
172  $this->db = $db;
173  }
174 
175 
183  public function getNextNumRef($objsoc)
184  {
185  global $langs, $conf;
186  $langs->load("order");
187 
188  if (empty($conf->global->HOLIDAY_ADDON)) {
189  $conf->global->HOLIDAY_ADDON = 'mod_holiday_madonna';
190  }
191 
192  if (!empty($conf->global->HOLIDAY_ADDON)) {
193  $mybool = false;
194 
195  $file = $conf->global->HOLIDAY_ADDON.".php";
196  $classname = $conf->global->HOLIDAY_ADDON;
197 
198  // Include file with class
199  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
200  foreach ($dirmodels as $reldir) {
201  $dir = dol_buildpath($reldir."core/modules/holiday/");
202 
203  // Load file with numbering class (if found)
204  $mybool |= @include_once $dir.$file;
205  }
206 
207  if ($mybool === false) {
208  dol_print_error('', "Failed to include file ".$file);
209  return '';
210  }
211 
212  $obj = new $classname();
213  $numref = $obj->getNextValue($objsoc, $this);
214 
215  if ($numref != "") {
216  return $numref;
217  } else {
218  $this->error = $obj->error;
219  //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
220  return "";
221  }
222  } else {
223  print $langs->trans("Error")." ".$langs->trans("Error_HOLIDAY_ADDON_NotDefined");
224  return "";
225  }
226  }
227 
233  public function updateBalance()
234  {
235  $this->db->begin();
236 
237  // Update sold of vocations
238  $result = $this->updateSoldeCP();
239 
240  // Check nb of users into table llx_holiday_users and update with empty lines
241  //if ($result > 0) $result = $this->verifNbUsers($this->countActiveUsersWithoutCP(), $this->getConfCP('nbUser'));
242 
243  if ($result >= 0) {
244  $this->db->commit();
245  return 0; // for cronjob use (0 is OK, any other value is an error code)
246  } else {
247  $this->db->rollback();
248  return -1;
249  }
250  }
251 
259  public function create($user, $notrigger = 0)
260  {
261  global $conf;
262  $error = 0;
263 
264  $now = dol_now();
265 
266  // Check parameters
267  if (empty($this->fk_user) || !is_numeric($this->fk_user) || $this->fk_user < 0) {
268  $this->error = "ErrorBadParameterFkUser"; return -1;
269  }
270  if (empty($this->fk_validator) || !is_numeric($this->fk_validator) || $this->fk_validator < 0) {
271  $this->error = "ErrorBadParameterFkValidator"; return -1;
272  }
273  if (empty($this->fk_type) || !is_numeric($this->fk_type) || $this->fk_type < 0) {
274  $this->error = "ErrorBadParameterFkType"; return -1;
275  }
276 
277  // Insert request
278  $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday(";
279  $sql .= "ref,";
280  $sql .= "fk_user,";
281  $sql .= "date_create,";
282  $sql .= "description,";
283  $sql .= "date_debut,";
284  $sql .= "date_fin,";
285  $sql .= "halfday,";
286  $sql .= "statut,";
287  $sql .= "fk_validator,";
288  $sql .= "fk_type,";
289  $sql .= "fk_user_create,";
290  $sql .= "entity";
291  $sql .= ") VALUES (";
292  $sql .= "'(PROV)',";
293  $sql .= " ".((int) $this->fk_user).",";
294  $sql .= " '".$this->db->idate($now)."',";
295  $sql .= " '".$this->db->escape($this->description)."',";
296  $sql .= " '".$this->db->idate($this->date_debut)."',";
297  $sql .= " '".$this->db->idate($this->date_fin)."',";
298  $sql .= " ".((int) $this->halfday).",";
299  $sql .= " '1',";
300  $sql .= " ".((int) $this->fk_validator).",";
301  $sql .= " ".((int) $this->fk_type).",";
302  $sql .= " ".((int) $user->id).",";
303  $sql .= " ".((int) $conf->entity);
304  $sql .= ")";
305 
306  $this->db->begin();
307 
308  dol_syslog(get_class($this)."::create", LOG_DEBUG);
309  $resql = $this->db->query($sql);
310  if (!$resql) {
311  $error++; $this->errors[] = "Error ".$this->db->lasterror();
312  }
313 
314  if (!$error) {
315  $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday");
316 
317  if ($this->id) {
318  // update ref
319  $initialref = '(PROV'.$this->id.')';
320  if (!empty($this->ref)) {
321  $initialref = $this->ref;
322  }
323 
324  $sql = 'UPDATE '.MAIN_DB_PREFIX."holiday SET ref='".$this->db->escape($initialref)."' WHERE rowid=".((int) $this->id);
325  if ($this->db->query($sql)) {
326  $this->ref = $initialref;
327 
328  if (!$error) {
329  $result = $this->insertExtraFields();
330  if ($result < 0) {
331  $error++;
332  }
333  }
334 
335  if (!$error && !$notrigger) {
336  // Call trigger
337  $result = $this->call_trigger('HOLIDAY_CREATE', $user);
338  if ($result < 0) {
339  $error++;
340  }
341  // End call triggers
342  }
343  }
344  }
345  }
346 
347  // Commit or rollback
348  if ($error) {
349  foreach ($this->errors as $errmsg) {
350  dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
351  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
352  }
353  $this->db->rollback();
354  return -1 * $error;
355  } else {
356  $this->db->commit();
357  return $this->id;
358  }
359  }
360 
361 
369  public function fetch($id, $ref = '')
370  {
371  global $langs;
372 
373  $sql = "SELECT";
374  $sql .= " cp.rowid,";
375  $sql .= " cp.ref,";
376  $sql .= " cp.fk_user,";
377  $sql .= " cp.date_create,";
378  $sql .= " cp.description,";
379  $sql .= " cp.date_debut,";
380  $sql .= " cp.date_fin,";
381  $sql .= " cp.halfday,";
382  $sql .= " cp.statut,";
383  $sql .= " cp.fk_validator,";
384  $sql .= " cp.date_valid,";
385  $sql .= " cp.fk_user_valid,";
386  $sql .= " cp.date_refuse,";
387  $sql .= " cp.fk_user_refuse,";
388  $sql .= " cp.date_cancel,";
389  $sql .= " cp.fk_user_cancel,";
390  $sql .= " cp.detail_refuse,";
391  $sql .= " cp.note_private,";
392  $sql .= " cp.note_public,";
393  $sql .= " cp.fk_user_create,";
394  $sql .= " cp.fk_type,";
395  $sql .= " cp.entity";
396  $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp";
397  if ($id > 0) {
398  $sql .= " WHERE cp.rowid = ".((int) $id);
399  } else {
400  $sql .= " WHERE cp.ref = '".$this->db->escape($ref)."'";
401  }
402 
403  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
404  $resql = $this->db->query($sql);
405  if ($resql) {
406  if ($this->db->num_rows($resql)) {
407  $obj = $this->db->fetch_object($resql);
408 
409  $this->id = $obj->rowid;
410  $this->ref = ($obj->ref ? $obj->ref : $obj->rowid);
411  $this->fk_user = $obj->fk_user;
412  $this->date_create = $this->db->jdate($obj->date_create);
413  $this->description = $obj->description;
414  $this->date_debut = $this->db->jdate($obj->date_debut);
415  $this->date_fin = $this->db->jdate($obj->date_fin);
416  $this->date_debut_gmt = $this->db->jdate($obj->date_debut, 1);
417  $this->date_fin_gmt = $this->db->jdate($obj->date_fin, 1);
418  $this->halfday = $obj->halfday;
419  $this->statut = $obj->statut;
420  $this->fk_validator = $obj->fk_validator;
421  $this->date_valid = $this->db->jdate($obj->date_valid);
422  $this->fk_user_valid = $obj->fk_user_valid;
423  $this->date_refuse = $this->db->jdate($obj->date_refuse);
424  $this->fk_user_refuse = $obj->fk_user_refuse;
425  $this->date_cancel = $this->db->jdate($obj->date_cancel);
426  $this->fk_user_cancel = $obj->fk_user_cancel;
427  $this->detail_refuse = $obj->detail_refuse;
428  $this->note_private = $obj->note_private;
429  $this->note_public = $obj->note_public;
430  $this->fk_user_create = $obj->fk_user_create;
431  $this->fk_type = $obj->fk_type;
432  $this->entity = $obj->entity;
433 
434  $this->fetch_optionals();
435 
436  $result = 1;
437  } else {
438  $result = 0;
439  }
440  $this->db->free($resql);
441 
442  return $result;
443  } else {
444  $this->error = "Error ".$this->db->lasterror();
445  return -1;
446  }
447  }
448 
457  public function fetchByUser($user_id, $order = '', $filter = '')
458  {
459  global $langs, $conf;
460 
461  $sql = "SELECT";
462  $sql .= " cp.rowid,";
463  $sql .= " cp.ref,";
464 
465  $sql .= " cp.fk_user,";
466  $sql .= " cp.fk_type,";
467  $sql .= " cp.date_create,";
468  $sql .= " cp.description,";
469  $sql .= " cp.date_debut,";
470  $sql .= " cp.date_fin,";
471  $sql .= " cp.halfday,";
472  $sql .= " cp.statut,";
473  $sql .= " cp.fk_validator,";
474  $sql .= " cp.date_valid,";
475  $sql .= " cp.fk_user_valid,";
476  $sql .= " cp.date_refuse,";
477  $sql .= " cp.fk_user_refuse,";
478  $sql .= " cp.date_cancel,";
479  $sql .= " cp.fk_user_cancel,";
480  $sql .= " cp.detail_refuse,";
481 
482  $sql .= " uu.lastname as user_lastname,";
483  $sql .= " uu.firstname as user_firstname,";
484  $sql .= " uu.login as user_login,";
485  $sql .= " uu.statut as user_statut,";
486  $sql .= " uu.photo as user_photo,";
487 
488  $sql .= " ua.lastname as validator_lastname,";
489  $sql .= " ua.firstname as validator_firstname,";
490  $sql .= " ua.login as validator_login,";
491  $sql .= " ua.statut as validator_statut,";
492  $sql .= " ua.photo as validator_photo";
493 
494  $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
495  $sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
496  $sql .= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid"; // Hack pour la recherche sur le tableau
497  $sql .= " AND cp.fk_user IN (".$this->db->sanitize($user_id).")";
498 
499  // Selection filter
500  if (!empty($filter)) {
501  $sql .= $filter;
502  }
503 
504  // Order of display of the result
505  if (!empty($order)) {
506  $sql .= $order;
507  }
508 
509  dol_syslog(get_class($this)."::fetchByUser", LOG_DEBUG);
510  $resql = $this->db->query($sql);
511 
512  // If no SQL error
513  if ($resql) {
514  $i = 0;
515  $tab_result = $this->holiday;
516  $num = $this->db->num_rows($resql);
517 
518  // If no registration
519  if (!$num) {
520  return 2;
521  }
522 
523  // List the records and add them to the table
524  while ($i < $num) {
525  $obj = $this->db->fetch_object($resql);
526 
527  $tab_result[$i]['rowid'] = $obj->rowid;
528  $tab_result[$i]['ref'] = ($obj->ref ? $obj->ref : $obj->rowid);
529 
530  $tab_result[$i]['fk_user'] = $obj->fk_user;
531  $tab_result[$i]['fk_type'] = $obj->fk_type;
532  $tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
533  $tab_result[$i]['description'] = $obj->description;
534  $tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
535  $tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
536  $tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut, 1);
537  $tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin, 1);
538  $tab_result[$i]['halfday'] = $obj->halfday;
539  $tab_result[$i]['statut'] = $obj->statut;
540  $tab_result[$i]['fk_validator'] = $obj->fk_validator;
541  $tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
542  $tab_result[$i]['fk_user_valid'] = $obj->fk_user_valid;
543  $tab_result[$i]['date_refuse'] = $this->db->jdate($obj->date_refuse);
544  $tab_result[$i]['fk_user_refuse'] = $obj->fk_user_refuse;
545  $tab_result[$i]['date_cancel'] = $this->db->jdate($obj->date_cancel);
546  $tab_result[$i]['fk_user_cancel'] = $obj->fk_user_cancel;
547  $tab_result[$i]['detail_refuse'] = $obj->detail_refuse;
548 
549  $tab_result[$i]['user_firstname'] = $obj->user_firstname;
550  $tab_result[$i]['user_lastname'] = $obj->user_lastname;
551  $tab_result[$i]['user_login'] = $obj->user_login;
552  $tab_result[$i]['user_statut'] = $obj->user_statut;
553  $tab_result[$i]['user_photo'] = $obj->user_photo;
554 
555  $tab_result[$i]['validator_firstname'] = $obj->validator_firstname;
556  $tab_result[$i]['validator_lastname'] = $obj->validator_lastname;
557  $tab_result[$i]['validator_login'] = $obj->validator_login;
558  $tab_result[$i]['validator_statut'] = $obj->validator_statut;
559  $tab_result[$i]['validator_photo'] = $obj->validator_photo;
560 
561  $i++;
562  }
563 
564  // Returns 1 with the filled array
565  $this->holiday = $tab_result;
566  return 1;
567  } else {
568  // SQL Error
569  $this->error = "Error ".$this->db->lasterror();
570  return -1;
571  }
572  }
573 
581  public function fetchAll($order, $filter)
582  {
583  global $langs;
584 
585  $sql = "SELECT";
586  $sql .= " cp.rowid,";
587  $sql .= " cp.ref,";
588 
589  $sql .= " cp.fk_user,";
590  $sql .= " cp.fk_type,";
591  $sql .= " cp.date_create,";
592  $sql .= " cp.tms as date_update,";
593  $sql .= " cp.description,";
594  $sql .= " cp.date_debut,";
595  $sql .= " cp.date_fin,";
596  $sql .= " cp.halfday,";
597  $sql .= " cp.statut,";
598  $sql .= " cp.fk_validator,";
599  $sql .= " cp.date_valid,";
600  $sql .= " cp.fk_user_valid,";
601  $sql .= " cp.date_refuse,";
602  $sql .= " cp.fk_user_refuse,";
603  $sql .= " cp.date_cancel,";
604  $sql .= " cp.fk_user_cancel,";
605  $sql .= " cp.detail_refuse,";
606 
607  $sql .= " uu.lastname as user_lastname,";
608  $sql .= " uu.firstname as user_firstname,";
609  $sql .= " uu.login as user_login,";
610  $sql .= " uu.statut as user_statut,";
611  $sql .= " uu.photo as user_photo,";
612 
613  $sql .= " ua.lastname as validator_lastname,";
614  $sql .= " ua.firstname as validator_firstname,";
615  $sql .= " ua.login as validator_login,";
616  $sql .= " ua.statut as validator_statut,";
617  $sql .= " ua.photo as validator_photo";
618 
619  $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp, ".MAIN_DB_PREFIX."user as uu, ".MAIN_DB_PREFIX."user as ua";
620  $sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
621  $sql .= " AND cp.fk_user = uu.rowid AND cp.fk_validator = ua.rowid "; // Hack pour la recherche sur le tableau
622 
623  // Selection filtering
624  if (!empty($filter)) {
625  $sql .= $filter;
626  }
627 
628  // order of display
629  if (!empty($order)) {
630  $sql .= $order;
631  }
632 
633  dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG);
634  $resql = $this->db->query($sql);
635 
636  // If no SQL error
637  if ($resql) {
638  $i = 0;
639  $tab_result = $this->holiday;
640  $num = $this->db->num_rows($resql);
641 
642  // If no registration
643  if (!$num) {
644  return 2;
645  }
646 
647  // List the records and add them to the table
648  while ($i < $num) {
649  $obj = $this->db->fetch_object($resql);
650 
651  $tab_result[$i]['rowid'] = $obj->rowid;
652  $tab_result[$i]['ref'] = ($obj->ref ? $obj->ref : $obj->rowid);
653  $tab_result[$i]['fk_user'] = $obj->fk_user;
654  $tab_result[$i]['fk_type'] = $obj->fk_type;
655  $tab_result[$i]['date_create'] = $this->db->jdate($obj->date_create);
656  $tab_result[$i]['date_update'] = $this->db->jdate($obj->date_update);
657  $tab_result[$i]['description'] = $obj->description;
658  $tab_result[$i]['date_debut'] = $this->db->jdate($obj->date_debut);
659  $tab_result[$i]['date_fin'] = $this->db->jdate($obj->date_fin);
660  $tab_result[$i]['date_debut_gmt'] = $this->db->jdate($obj->date_debut, 1);
661  $tab_result[$i]['date_fin_gmt'] = $this->db->jdate($obj->date_fin, 1);
662  $tab_result[$i]['halfday'] = $obj->halfday;
663  $tab_result[$i]['statut'] = $obj->statut;
664  $tab_result[$i]['fk_validator'] = $obj->fk_validator;
665  $tab_result[$i]['date_valid'] = $this->db->jdate($obj->date_valid);
666  $tab_result[$i]['fk_user_valid'] = $obj->fk_user_valid;
667  $tab_result[$i]['date_refuse'] = $obj->date_refuse;
668  $tab_result[$i]['fk_user_refuse'] = $obj->fk_user_refuse;
669  $tab_result[$i]['date_cancel'] = $obj->date_cancel;
670  $tab_result[$i]['fk_user_cancel'] = $obj->fk_user_cancel;
671  $tab_result[$i]['detail_refuse'] = $obj->detail_refuse;
672 
673  $tab_result[$i]['user_firstname'] = $obj->user_firstname;
674  $tab_result[$i]['user_lastname'] = $obj->user_lastname;
675  $tab_result[$i]['user_login'] = $obj->user_login;
676  $tab_result[$i]['user_statut'] = $obj->user_statut;
677  $tab_result[$i]['user_photo'] = $obj->user_photo;
678 
679  $tab_result[$i]['validator_firstname'] = $obj->validator_firstname;
680  $tab_result[$i]['validator_lastname'] = $obj->validator_lastname;
681  $tab_result[$i]['validator_login'] = $obj->validator_login;
682  $tab_result[$i]['validator_statut'] = $obj->validator_statut;
683  $tab_result[$i]['validator_photo'] = $obj->validator_photo;
684 
685  $i++;
686  }
687  // Returns 1 and adds the array to the variable
688  $this->holiday = $tab_result;
689  return 1;
690  } else {
691  // SQL Error
692  $this->error = "Error ".$this->db->lasterror();
693  return -1;
694  }
695  }
696 
697 
705  public function validate($user = null, $notrigger = 0)
706  {
707  global $conf, $langs;
708  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
709  $error = 0;
710 
711  $checkBalance = getDictionaryValue('c_holiday_types', 'block_if_negative', $this->fk_type);
712 
713  if ($checkBalance > 0) {
714  $balance = $this->getCPforUser($this->fk_user, $this->fk_type);
715 
716  if ($balance < 0) {
717  $this->error = 'LeaveRequestCreationBlockedBecauseBalanceIsNegative';
718  return -1;
719  }
720  }
721 
722  // Define new ref
723  if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref) || $this->ref == $this->id)) {
724  $num = $this->getNextNumRef(null);
725  } else {
726  $num = $this->ref;
727  }
728  $this->newref = dol_sanitizeFileName($num);
729 
730  // Update status
731  $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
732  if (!empty($this->statut) && is_numeric($this->statut)) {
733  $sql .= " statut = ".((int) $this->statut).",";
734  } else {
735  $error++;
736  }
737  $sql .= " ref = '".$this->db->escape($num)."'";
738  $sql .= " WHERE rowid = ".((int) $this->id);
739 
740  $this->db->begin();
741 
742  dol_syslog(get_class($this)."::validate", LOG_DEBUG);
743  $resql = $this->db->query($sql);
744  if (!$resql) {
745  $error++; $this->errors[] = "Error ".$this->db->lasterror();
746  }
747 
748  if (!$error) {
749  if (!$notrigger) {
750  // Call trigger
751  $result = $this->call_trigger('HOLIDAY_VALIDATE', $user);
752  if ($result < 0) {
753  $error++;
754  }
755  // End call triggers
756  }
757  }
758 
759  if (!$error) {
760  $this->oldref = $this->ref;
761 
762  // Rename directory if dir was a temporary ref
763  if (preg_match('/^[\(]?PROV/i', $this->ref)) {
764  // Now we rename also files into index
765  $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) . "'";
766  $sql .= " WHERE filename LIKE '" . $this->db->escape($this->ref) . "%' AND filepath = 'holiday/" . $this->db->escape($this->ref) . "' and entity = " . ((int) $conf->entity);
767  $resql = $this->db->query($sql);
768  if (!$resql) {
769  $error++;
770  $this->error = $this->db->lasterror();
771  }
772 
773  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
774  $oldref = dol_sanitizeFileName($this->ref);
775  $newref = dol_sanitizeFileName($num);
776  $dirsource = $conf->holiday->multidir_output[$this->entity] . '/' . $oldref;
777  $dirdest = $conf->holiday->multidir_output[$this->entity] . '/' . $newref;
778  if (!$error && file_exists($dirsource)) {
779  dol_syslog(get_class($this) . "::validate rename dir " . $dirsource . " into " . $dirdest);
780  if (@rename($dirsource, $dirdest)) {
781  dol_syslog("Rename ok");
782  // Rename docs starting with $oldref with $newref
783  $listoffiles = dol_dir_list($dirdest, 'files', 1, '^' . preg_quote($oldref, '/'));
784  foreach ($listoffiles as $fileentry) {
785  $dirsource = $fileentry['name'];
786  $dirdest = preg_replace('/^' . preg_quote($oldref, '/') . '/', $newref, $dirsource);
787  $dirsource = $fileentry['path'] . '/' . $dirsource;
788  $dirdest = $fileentry['path'] . '/' . $dirdest;
789  @rename($dirsource, $dirdest);
790  }
791  }
792  }
793  }
794  }
795 
796 
797  // Commit or rollback
798  if ($error) {
799  foreach ($this->errors as $errmsg) {
800  dol_syslog(get_class($this)."::validate ".$errmsg, LOG_ERR);
801  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
802  }
803  $this->db->rollback();
804  return -1 * $error;
805  } else {
806  $this->db->commit();
807  return 1;
808  }
809  }
810 
811 
819  public function approve($user = null, $notrigger = 0)
820  {
821  global $conf, $langs;
822  $error = 0;
823 
824  $checkBalance = getDictionaryValue('c_holiday_types', 'block_if_negative', $this->fk_type);
825 
826  if ($checkBalance > 0) {
827  $balance = $this->getCPforUser($this->fk_user, $this->fk_type);
828 
829  if ($balance < 0) {
830  $this->error = 'LeaveRequestCreationBlockedBecauseBalanceIsNegative';
831  return -1;
832  }
833  }
834 
835  // Update request
836  $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
837 
838  $sql .= " description= '".$this->db->escape($this->description)."',";
839 
840  if (!empty($this->date_debut)) {
841  $sql .= " date_debut = '".$this->db->idate($this->date_debut)."',";
842  } else {
843  $error++;
844  }
845  if (!empty($this->date_fin)) {
846  $sql .= " date_fin = '".$this->db->idate($this->date_fin)."',";
847  } else {
848  $error++;
849  }
850  $sql .= " halfday = ".((int) $this->halfday).",";
851  if (!empty($this->statut) && is_numeric($this->statut)) {
852  $sql .= " statut = ".((int) $this->statut).",";
853  } else {
854  $error++;
855  }
856  if (!empty($this->fk_validator)) {
857  $sql .= " fk_validator = '".$this->db->escape($this->fk_validator)."',";
858  } else {
859  $error++;
860  }
861  if (!empty($this->date_valid)) {
862  $sql .= " date_valid = '".$this->db->idate($this->date_valid)."',";
863  } else {
864  $sql .= " date_valid = NULL,";
865  }
866  if (!empty($this->fk_user_valid)) {
867  $sql .= " fk_user_valid = '".$this->db->escape($this->fk_user_valid)."',";
868  } else {
869  $sql .= " fk_user_valid = NULL,";
870  }
871  if (!empty($this->date_refuse)) {
872  $sql .= " date_refuse = '".$this->db->idate($this->date_refuse)."',";
873  } else {
874  $sql .= " date_refuse = NULL,";
875  }
876  if (!empty($this->fk_user_refuse)) {
877  $sql .= " fk_user_refuse = '".$this->db->escape($this->fk_user_refuse)."',";
878  } else {
879  $sql .= " fk_user_refuse = NULL,";
880  }
881  if (!empty($this->date_cancel)) {
882  $sql .= " date_cancel = '".$this->db->idate($this->date_cancel)."',";
883  } else {
884  $sql .= " date_cancel = NULL,";
885  }
886  if (!empty($this->fk_user_cancel)) {
887  $sql .= " fk_user_cancel = '".$this->db->escape($this->fk_user_cancel)."',";
888  } else {
889  $sql .= " fk_user_cancel = NULL,";
890  }
891  if (!empty($this->detail_refuse)) {
892  $sql .= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'";
893  } else {
894  $sql .= " detail_refuse = NULL";
895  }
896  $sql .= " WHERE rowid = ".((int) $this->id);
897 
898  $this->db->begin();
899 
900  dol_syslog(get_class($this)."::approve", LOG_DEBUG);
901  $resql = $this->db->query($sql);
902  if (!$resql) {
903  $error++; $this->errors[] = "Error ".$this->db->lasterror();
904  }
905 
906  if (!$error) {
907  if (!$notrigger) {
908  // Call trigger
909  $result = $this->call_trigger('HOLIDAY_APPROVE', $user);
910  if ($result < 0) {
911  $error++;
912  }
913  // End call triggers
914  }
915  }
916 
917  // Commit or rollback
918  if ($error) {
919  foreach ($this->errors as $errmsg) {
920  dol_syslog(get_class($this)."::approve ".$errmsg, LOG_ERR);
921  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
922  }
923  $this->db->rollback();
924  return -1 * $error;
925  } else {
926  $this->db->commit();
927  return 1;
928  }
929  }
930 
938  public function update($user = null, $notrigger = 0)
939  {
940  global $conf, $langs;
941  $error = 0;
942 
943  $checkBalance = getDictionaryValue('c_holiday_types', 'block_if_negative', $this->fk_type);
944 
945  if ($checkBalance > 0 && $this->statut != self::STATUS_DRAFT) {
946  $balance = $this->getCPforUser($this->fk_user, $this->fk_type);
947 
948  if ($balance < 0) {
949  $this->error = 'LeaveRequestCreationBlockedBecauseBalanceIsNegative';
950  return -1;
951  }
952  }
953 
954  // Update request
955  $sql = "UPDATE ".MAIN_DB_PREFIX."holiday SET";
956 
957  $sql .= " description= '".$this->db->escape($this->description)."',";
958 
959  if (!empty($this->date_debut)) {
960  $sql .= " date_debut = '".$this->db->idate($this->date_debut)."',";
961  } else {
962  $error++;
963  }
964  if (!empty($this->date_fin)) {
965  $sql .= " date_fin = '".$this->db->idate($this->date_fin)."',";
966  } else {
967  $error++;
968  }
969  $sql .= " halfday = ".$this->halfday.",";
970  if (!empty($this->statut) && is_numeric($this->statut)) {
971  $sql .= " statut = ".$this->statut.",";
972  } else {
973  $error++;
974  }
975  if (!empty($this->fk_validator)) {
976  $sql .= " fk_validator = '".$this->db->escape($this->fk_validator)."',";
977  } else {
978  $error++;
979  }
980  if (!empty($this->date_valid)) {
981  $sql .= " date_valid = '".$this->db->idate($this->date_valid)."',";
982  } else {
983  $sql .= " date_valid = NULL,";
984  }
985  if (!empty($this->fk_user_valid)) {
986  $sql .= " fk_user_valid = '".$this->db->escape($this->fk_user_valid)."',";
987  } else {
988  $sql .= " fk_user_valid = NULL,";
989  }
990  if (!empty($this->date_refuse)) {
991  $sql .= " date_refuse = '".$this->db->idate($this->date_refuse)."',";
992  } else {
993  $sql .= " date_refuse = NULL,";
994  }
995  if (!empty($this->fk_user_refuse)) {
996  $sql .= " fk_user_refuse = '".$this->db->escape($this->fk_user_refuse)."',";
997  } else {
998  $sql .= " fk_user_refuse = NULL,";
999  }
1000  if (!empty($this->date_cancel)) {
1001  $sql .= " date_cancel = '".$this->db->idate($this->date_cancel)."',";
1002  } else {
1003  $sql .= " date_cancel = NULL,";
1004  }
1005  if (!empty($this->fk_user_cancel)) {
1006  $sql .= " fk_user_cancel = '".$this->db->escape($this->fk_user_cancel)."',";
1007  } else {
1008  $sql .= " fk_user_cancel = NULL,";
1009  }
1010  if (!empty($this->detail_refuse)) {
1011  $sql .= " detail_refuse = '".$this->db->escape($this->detail_refuse)."'";
1012  } else {
1013  $sql .= " detail_refuse = NULL";
1014  }
1015 
1016  $sql .= " WHERE rowid = ".((int) $this->id);
1017 
1018  $this->db->begin();
1019 
1020  dol_syslog(get_class($this)."::update", LOG_DEBUG);
1021  $resql = $this->db->query($sql);
1022  if (!$resql) {
1023  $error++; $this->errors[] = "Error ".$this->db->lasterror();
1024  }
1025 
1026  if (!$error) {
1027  if (!$notrigger) {
1028  // Call trigger
1029  $result = $this->call_trigger('HOLIDAY_MODIFY', $user);
1030  if ($result < 0) {
1031  $error++;
1032  }
1033  // End call triggers
1034  }
1035  }
1036 
1037  // Commit or rollback
1038  if ($error) {
1039  foreach ($this->errors as $errmsg) {
1040  dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
1041  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1042  }
1043  $this->db->rollback();
1044  return -1 * $error;
1045  } else {
1046  $this->db->commit();
1047  return 1;
1048  }
1049  }
1050 
1051 
1059  public function delete($user, $notrigger = 0)
1060  {
1061  global $conf, $langs;
1062  $error = 0;
1063 
1064  $sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday";
1065  $sql .= " WHERE rowid=".((int) $this->id);
1066 
1067  $this->db->begin();
1068 
1069  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1070  $resql = $this->db->query($sql);
1071  if (!$resql) {
1072  $error++; $this->errors[] = "Error ".$this->db->lasterror();
1073  }
1074 
1075  if (!$error) {
1076  if (!$notrigger) {
1077  // Call trigger
1078  $result = $this->call_trigger('HOLIDAY_DELETE', $user);
1079  if ($result < 0) {
1080  $error++;
1081  }
1082  // End call triggers
1083  }
1084  }
1085 
1086  // Commit or rollback
1087  if ($error) {
1088  foreach ($this->errors as $errmsg) {
1089  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
1090  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
1091  }
1092  $this->db->rollback();
1093  return -1 * $error;
1094  } else {
1095  $this->db->commit();
1096  return 1;
1097  }
1098  }
1099 
1113  public function verifDateHolidayCP($fk_user, $dateStart, $dateEnd, $halfday = 0)
1114  {
1115  $this->fetchByUser($fk_user, '', '');
1116 
1117  foreach ($this->holiday as $infos_CP) {
1118  if ($infos_CP['statut'] == 4) {
1119  continue; // ignore not validated holidays
1120  }
1121  if ($infos_CP['statut'] == 5) {
1122  continue; // ignore not validated holidays
1123  }
1124  //var_dump("--");
1125  //var_dump("old: ".dol_print_date($infos_CP['date_debut'],'dayhour').' '.dol_print_date($infos_CP['date_fin'],'dayhour').' '.$infos_CP['halfday']);
1126  //var_dump("new: ".dol_print_date($dateStart,'dayhour').' '.dol_print_date($dateEnd,'dayhour').' '.$halfday);
1127 
1128  if ($halfday == 0) {
1129  if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1130  return false;
1131  }
1132  if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1133  return false;
1134  }
1135  } elseif ($halfday == -1) {
1136  // new start afternoon, new end afternoon
1137  if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1138  if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) {
1139  return false;
1140  }
1141  }
1142  if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1143  if ($dateStart < $dateEnd) {
1144  return false;
1145  }
1146  if ($dateEnd < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) {
1147  return false;
1148  }
1149  }
1150  } elseif ($halfday == 1) {
1151  // new start morning, new end morning
1152  if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1153  if ($dateStart < $dateEnd) {
1154  return false;
1155  }
1156  if ($dateStart > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) {
1157  return false;
1158  }
1159  }
1160  if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1161  if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) {
1162  return false;
1163  }
1164  }
1165  } elseif ($halfday == 2) {
1166  // new start afternoon, new end morning
1167  if ($dateStart >= $infos_CP['date_debut'] && $dateStart <= $infos_CP['date_fin']) {
1168  if ($dateStart < $infos_CP['date_fin'] || in_array($infos_CP['halfday'], array(0, -1))) {
1169  return false;
1170  }
1171  }
1172  if ($dateEnd <= $infos_CP['date_fin'] && $dateEnd >= $infos_CP['date_debut']) {
1173  if ($dateEnd > $infos_CP['date_debut'] || in_array($infos_CP['halfday'], array(0, 1))) {
1174  return false;
1175  }
1176  }
1177  } else {
1178  dol_print_error('', 'Bad value of parameter halfday when calling function verifDateHolidayCP');
1179  }
1180  }
1181 
1182  return true;
1183  }
1184 
1185 
1195  public function verifDateHolidayForTimestamp($fk_user, $timestamp, $status = '-1')
1196  {
1197  global $langs, $conf;
1198 
1199  $isavailablemorning = true;
1200  $isavailableafternoon = true;
1201 
1202  // Check into leave requests
1203  $sql = "SELECT cp.rowid, cp.date_debut as date_start, cp.date_fin as date_end, cp.halfday, cp.statut";
1204  $sql .= " FROM ".MAIN_DB_PREFIX."holiday as cp";
1205  $sql .= " WHERE cp.entity IN (".getEntity('holiday').")";
1206  $sql .= " AND cp.fk_user = ".(int) $fk_user;
1207  $sql .= " AND cp.date_debut <= '".$this->db->idate($timestamp)."' AND cp.date_fin >= '".$this->db->idate($timestamp)."'";
1208  if ($status != '-1') {
1209  $sql .= " AND cp.statut IN (".$this->db->sanitize($status).")";
1210  }
1211 
1212  $resql = $this->db->query($sql);
1213  if ($resql) {
1214  $num_rows = $this->db->num_rows($resql); // Note, we can have 2 records if on is morning and the other one is afternoon
1215  if ($num_rows > 0) {
1216  $arrayofrecord = array();
1217  $i = 0;
1218  while ($i < $num_rows) {
1219  $obj = $this->db->fetch_object($resql);
1220 
1221  // Note: $obj->halfday is 0:Full days, 2:Sart afternoon end morning, -1:Start afternoon, 1:End morning
1222  $arrayofrecord[$obj->rowid] = array('date_start'=>$this->db->jdate($obj->date_start), 'date_end'=>$this->db->jdate($obj->date_end), 'halfday'=>$obj->halfday);
1223  $i++;
1224  }
1225 
1226  // We found a record, user is on holiday by default, so is not available is true.
1227  $isavailablemorning = true;
1228  foreach ($arrayofrecord as $record) {
1229  if ($timestamp == $record['date_start'] && $record['halfday'] == 2) {
1230  continue;
1231  }
1232  if ($timestamp == $record['date_start'] && $record['halfday'] == -1) {
1233  continue;
1234  }
1235  $isavailablemorning = false;
1236  break;
1237  }
1238  $isavailableafternoon = true;
1239  foreach ($arrayofrecord as $record) {
1240  if ($timestamp == $record['date_end'] && $record['halfday'] == 2) {
1241  continue;
1242  }
1243  if ($timestamp == $record['date_end'] && $record['halfday'] == 1) {
1244  continue;
1245  }
1246  $isavailableafternoon = false;
1247  break;
1248  }
1249  }
1250  } else {
1251  dol_print_error($this->db);
1252  }
1253 
1254  $result = array('morning'=>$isavailablemorning, 'afternoon'=>$isavailableafternoon);
1255  if (!$isavailablemorning) {
1256  $result['morning_reason'] = 'leave_request';
1257  }
1258  if (!$isavailableafternoon) {
1259  $result['afternoon_reason'] = 'leave_request';
1260  }
1261  return $result;
1262  }
1263 
1264 
1273  public function getNomUrl($withpicto = 0, $save_lastsearch_value = -1, $notooltip = 0)
1274  {
1275  global $langs, $hookmanager;
1276 
1277  $result = '';
1278 
1279  $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Holiday").'</u>';
1280  if (isset($this->statut)) {
1281  $label .= ' '.$this->getLibStatut(5);
1282  }
1283  $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1284 
1285  $url = DOL_URL_ROOT.'/holiday/card.php?id='.$this->id;
1286 
1287  //if ($option != 'nolink')
1288  //{
1289  // Add param to save lastsearch_values or not
1290  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1291  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1292  $add_save_lastsearch_values = 1;
1293  }
1294  if ($add_save_lastsearch_values) {
1295  $url .= '&save_lastsearch_values=1';
1296  }
1297  //}
1298 
1299  $linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1300  $linkend = '</a>';
1301 
1302  $result .= $linkstart;
1303  if ($withpicto) {
1304  $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1305  }
1306  if ($withpicto != 2) {
1307  $result .= $this->ref;
1308  }
1309  $result .= $linkend;
1310  global $action;
1311  $hookmanager->initHooks(array($this->element . 'dao'));
1312  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
1313  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1314  if ($reshook > 0) {
1315  $result = $hookmanager->resPrint;
1316  } else {
1317  $result .= $hookmanager->resPrint;
1318  }
1319  return $result;
1320  }
1321 
1322 
1329  public function getLibStatut($mode = 0)
1330  {
1331  return $this->LibStatut($this->statut, $mode, $this->date_debut);
1332  }
1333 
1334  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1343  public function LibStatut($status, $mode = 0, $startdate = '')
1344  {
1345  // phpcs:enable
1346  global $langs;
1347 
1348  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1349  global $langs;
1350  //$langs->load("mymodule");
1351  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('DraftCP');
1352  $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ToReviewCP');
1353  $this->labelStatus[self::STATUS_APPROVED] = $langs->transnoentitiesnoconv('ApprovedCP');
1354  $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('CancelCP');
1355  $this->labelStatus[self::STATUS_REFUSED] = $langs->transnoentitiesnoconv('RefuseCP');
1356  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('DraftCP');
1357  $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ToReviewCP');
1358  $this->labelStatusShort[self::STATUS_APPROVED] = $langs->transnoentitiesnoconv('ApprovedCP');
1359  $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('CancelCP');
1360  $this->labelStatusShort[self::STATUS_REFUSED] = $langs->transnoentitiesnoconv('RefuseCP');
1361  }
1362 
1363  $params = array();
1364  $statusType = 'status6';
1365  if (!empty($startdate) && $startdate >= dol_now()) { // If not yet passed, we use a green "in live" color
1366  $statusType = 'status4';
1367  $params = array('tooltip'=>$this->labelStatus[$status].' - '.$langs->trans("Forthcoming"));
1368  }
1369  if ($status == self::STATUS_DRAFT) {
1370  $statusType = 'status0';
1371  }
1372  if ($status == self::STATUS_VALIDATED) {
1373  $statusType = 'status1';
1374  }
1375  if ($status == self::STATUS_CANCELED) {
1376  $statusType = 'status5';
1377  }
1378  if ($status == self::STATUS_REFUSED) {
1379  $statusType = 'status5';
1380  }
1381 
1382  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode, '', $params);
1383  }
1384 
1385 
1394  public function selectStatutCP($selected = '', $htmlname = 'select_statut', $morecss = 'minwidth125')
1395  {
1396  global $langs;
1397 
1398  // Liste des statuts
1399  $name = array('DraftCP', 'ToReviewCP', 'ApprovedCP', 'CancelCP', 'RefuseCP');
1400  $nb = count($name) + 1;
1401 
1402  // Select HTML
1403  $out = '<select name="'.$htmlname.'" id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'">'."\n";
1404  $out .= '<option value="-1">&nbsp;</option>'."\n";
1405 
1406  // Boucle des statuts
1407  for ($i = 1; $i < $nb; $i++) {
1408  if ($i == $selected) {
1409  $out .= '<option value="'.$i.'" selected>'.$langs->trans($name[$i - 1]).'</option>'."\n";
1410  } else {
1411  $out .= '<option value="'.$i.'">'.$langs->trans($name[$i - 1]).'</option>'."\n";
1412  }
1413  }
1414 
1415  $out .= '</select>'."\n";
1416  $out .= ajax_combobox($htmlname);
1417 
1418  print $out;
1419  }
1420 
1428  public function updateConfCP($name, $value)
1429  {
1430 
1431  $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1432  $sql .= " value = '".$this->db->escape($value)."'";
1433  $sql .= " WHERE name = '".$this->db->escape($name)."'";
1434 
1435  dol_syslog(get_class($this).'::updateConfCP name='.$name.'', LOG_DEBUG);
1436  $result = $this->db->query($sql);
1437  if ($result) {
1438  return true;
1439  }
1440 
1441  return false;
1442  }
1443 
1452  public function getConfCP($name, $createifnotfound = '')
1453  {
1454  $sql = "SELECT value";
1455  $sql .= " FROM ".MAIN_DB_PREFIX."holiday_config";
1456  $sql .= " WHERE name = '".$this->db->escape($name)."'";
1457 
1458  dol_syslog(get_class($this).'::getConfCP name='.$name.' createifnotfound='.$createifnotfound, LOG_DEBUG);
1459  $result = $this->db->query($sql);
1460 
1461  if ($result) {
1462  $obj = $this->db->fetch_object($result);
1463  // Return value
1464  if (empty($obj)) {
1465  if ($createifnotfound) {
1466  $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_config(name, value)";
1467  $sql .= " VALUES('".$this->db->escape($name)."', '".$this->db->escape($createifnotfound)."')";
1468  $result = $this->db->query($sql);
1469  if ($result) {
1470  return $createifnotfound;
1471  } else {
1472  $this->error = $this->db->lasterror();
1473  return -2;
1474  }
1475  } else {
1476  return '';
1477  }
1478  } else {
1479  return $obj->value;
1480  }
1481  } else {
1482  // Erreur SQL
1483  $this->error = $this->db->lasterror();
1484  return -1;
1485  }
1486  }
1487 
1496  public function updateSoldeCP($userID = '', $nbHoliday = '', $fk_type = '')
1497  {
1498  global $user, $langs;
1499 
1500  $error = 0;
1501 
1502  if (empty($userID) && empty($nbHoliday) && empty($fk_type)) {
1503  $langs->load("holiday");
1504 
1505  // Si mise à jour pour tout le monde en début de mois
1506  $now = dol_now();
1507 
1508  $month = date('m', $now);
1509  $newdateforlastupdate = dol_print_date($now, '%Y%m%d%H%M%S');
1510 
1511  // Get month of last update
1512  $lastUpdate = $this->getConfCP('lastUpdate', $newdateforlastupdate);
1513  $monthLastUpdate = $lastUpdate[4].$lastUpdate[5];
1514  //print 'month: '.$month.' lastUpdate:'.$lastUpdate.' monthLastUpdate:'.$monthLastUpdate;exit;
1515 
1516  // 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.
1517  if ($month != $monthLastUpdate) {
1518  $this->db->begin();
1519 
1520  $users = $this->fetchUsers(false, false, ' AND u.statut > 0');
1521  $nbUser = count($users);
1522 
1523  $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET";
1524  $sql .= " value = '".$this->db->escape($newdateforlastupdate)."'";
1525  $sql .= " WHERE name = 'lastUpdate'";
1526  $result = $this->db->query($sql);
1527 
1528  $typeleaves = $this->getTypes(1, 1);
1529 
1530  // Update each user counter
1531  foreach ($users as $userCounter) {
1532  $nbDaysToAdd = (isset($typeleaves[$userCounter['type']]['newbymonth']) ? $typeleaves[$userCounter['type']]['newbymonth'] : 0);
1533  if (empty($nbDaysToAdd)) {
1534  continue;
1535  }
1536 
1537  dol_syslog("We update leave type id ".$userCounter['type']." for user id ".$userCounter['rowid'], LOG_DEBUG);
1538 
1539  $nowHoliday = $userCounter['nb_holiday'];
1540  $newSolde = $nowHoliday + $nbDaysToAdd;
1541 
1542  // We add a log for each user
1543  $this->addLogCP($user->id, $userCounter['rowid'], $langs->trans('HolidaysMonthlyUpdate'), $newSolde, $userCounter['type']);
1544 
1545  $result = $this->updateSoldeCP($userCounter['rowid'], $newSolde, $userCounter['type'], $langs->trans('HolidaysMonthlyUpdate'));
1546 
1547  if ($result < 0) {
1548  $error++;
1549  break;
1550  }
1551  }
1552 
1553  if (!$error) {
1554  $this->db->commit();
1555  return 1;
1556  } else {
1557  $this->db->rollback();
1558  return -1;
1559  }
1560  }
1561 
1562  return 0;
1563  } else {
1564  // Mise à jour pour un utilisateur
1565  $nbHoliday = price2num($nbHoliday, 5);
1566 
1567  $sql = "SELECT nb_holiday FROM ".MAIN_DB_PREFIX."holiday_users";
1568  $sql .= " WHERE fk_user = ".(int) $userID." AND fk_type = ".(int) $fk_type;
1569  $resql = $this->db->query($sql);
1570  if ($resql) {
1571  $num = $this->db->num_rows($resql);
1572 
1573  if ($num > 0) {
1574  // Update for user
1575  $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET";
1576  $sql .= " nb_holiday = ".((float) $nbHoliday);
1577  $sql .= " WHERE fk_user = ".(int) $userID." AND fk_type = ".(int) $fk_type;
1578  $result = $this->db->query($sql);
1579  if (!$result) {
1580  $error++;
1581  $this->errors[] = $this->db->lasterror();
1582  }
1583  } else {
1584  // Insert for user
1585  $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users(nb_holiday, fk_user, fk_type) VALUES (";
1586  $sql .= ((float) $nbHoliday);
1587  $sql .= ", ".(int) $userID.", ".(int) $fk_type.")";
1588  $result = $this->db->query($sql);
1589  if (!$result) {
1590  $error++;
1591  $this->errors[] = $this->db->lasterror();
1592  }
1593  }
1594  } else {
1595  $this->errors[] = $this->db->lasterror();
1596  $error++;
1597  }
1598 
1599  if (!$error) {
1600  return 1;
1601  } else {
1602  return -1;
1603  }
1604  }
1605  }
1606 
1613  public function getCheckOption($name)
1614  {
1615 
1616  $sql = "SELECT value";
1617  $sql .= " FROM ".MAIN_DB_PREFIX."holiday_config";
1618  $sql .= " WHERE name = '".$this->db->escape($name)."'";
1619 
1620  $result = $this->db->query($sql);
1621 
1622  if ($result) {
1623  $obj = $this->db->fetch_object($result);
1624 
1625  // Si la valeur est 1 on retourne checked
1626  if ($obj->value) {
1627  return 'checked';
1628  }
1629  }
1630  }
1631 
1632 
1640  public function createCPusers($single = false, $userid = '')
1641  {
1642  // do we have to add balance for all users ?
1643  if (!$single) {
1644  dol_syslog(get_class($this).'::createCPusers');
1645  $arrayofusers = $this->fetchUsers(false, true);
1646 
1647  foreach ($arrayofusers as $users) {
1648  $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users";
1649  $sql .= " (fk_user, nb_holiday)";
1650  $sql .= " VALUES (".((int) $users['rowid'])."', '0')";
1651 
1652  $resql = $this->db->query($sql);
1653  if (!$resql) {
1654  dol_print_error($this->db);
1655  }
1656  }
1657  } else {
1658  $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_users";
1659  $sql .= " (fk_user, nb_holiday)";
1660  $sql .= " VALUES (".((int) $userid)."', '0')";
1661 
1662  $resql = $this->db->query($sql);
1663  if (!$resql) {
1664  dol_print_error($this->db);
1665  }
1666  }
1667  }
1668 
1675  public function deleteCPuser($user_id)
1676  {
1677 
1678  $sql = "DELETE FROM ".MAIN_DB_PREFIX."holiday_users";
1679  $sql .= " WHERE fk_user = ".((int) $user_id);
1680 
1681  $this->db->query($sql);
1682  }
1683 
1684 
1692  public function getCPforUser($user_id, $fk_type = 0)
1693  {
1694  $sql = "SELECT nb_holiday";
1695  $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users";
1696  $sql .= " WHERE fk_user = ".(int) $user_id;
1697  if ($fk_type > 0) {
1698  $sql .= " AND fk_type = ".(int) $fk_type;
1699  }
1700 
1701  dol_syslog(get_class($this).'::getCPforUser user_id='.$user_id.' type_id='.$fk_type, LOG_DEBUG);
1702  $result = $this->db->query($sql);
1703  if ($result) {
1704  $obj = $this->db->fetch_object($result);
1705  //return number_format($obj->nb_holiday,2);
1706  if ($obj) {
1707  return $obj->nb_holiday;
1708  } else {
1709  return null;
1710  }
1711  } else {
1712  return null;
1713  }
1714  }
1715 
1724  public function fetchUsers($stringlist = true, $type = true, $filters = '')
1725  {
1726  global $conf;
1727 
1728  dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG);
1729 
1730  if ($stringlist) {
1731  if ($type) {
1732  // If user of Dolibarr
1733  $sql = "SELECT";
1734  if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1735  $sql .= " DISTINCT";
1736  }
1737  $sql .= " u.rowid";
1738  $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
1739 
1740  if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1741  $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1742  $sql .= " WHERE ((ug.fk_user = u.rowid";
1743  $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
1744  $sql .= " OR u.entity = 0)"; // Show always superadmin
1745  } else {
1746  $sql .= " WHERE u.entity IN (".getEntity('user').")";
1747  }
1748  $sql .= " AND u.statut > 0";
1749  $sql .= " AND u.employee = 1"; // We only want employee users for holidays
1750  if ($filters) {
1751  $sql .= $filters;
1752  }
1753 
1754  $resql = $this->db->query($sql);
1755 
1756  // Si pas d'erreur SQL
1757  if ($resql) {
1758  $i = 0;
1759  $num = $this->db->num_rows($resql);
1760  $stringlist = '';
1761 
1762  // Boucles du listage des utilisateurs
1763  while ($i < $num) {
1764  $obj = $this->db->fetch_object($resql);
1765 
1766  if ($i == 0) {
1767  $stringlist .= $obj->rowid;
1768  } else {
1769  $stringlist .= ', '.$obj->rowid;
1770  }
1771 
1772  $i++;
1773  }
1774  // Retoune le tableau des utilisateurs
1775  return $stringlist;
1776  } else {
1777  // Erreur SQL
1778  $this->error = "Error ".$this->db->lasterror();
1779  return -1;
1780  }
1781  } else {
1782  // We want only list of vacation balance for user ids
1783  $sql = "SELECT DISTINCT cpu.fk_user";
1784  $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
1785  $sql .= " WHERE cpu.fk_user = u.rowid";
1786  if ($filters) {
1787  $sql .= $filters;
1788  }
1789 
1790  $resql = $this->db->query($sql);
1791 
1792  // Si pas d'erreur SQL
1793  if ($resql) {
1794  $i = 0;
1795  $num = $this->db->num_rows($resql);
1796  $stringlist = '';
1797 
1798  // Boucles du listage des utilisateurs
1799  while ($i < $num) {
1800  $obj = $this->db->fetch_object($resql);
1801 
1802  if ($i == 0) {
1803  $stringlist .= $obj->fk_user;
1804  } else {
1805  $stringlist .= ', '.$obj->fk_user;
1806  }
1807 
1808  $i++;
1809  }
1810  // Retoune le tableau des utilisateurs
1811  return $stringlist;
1812  } else {
1813  // Erreur SQL
1814  $this->error = "Error ".$this->db->lasterror();
1815  return -1;
1816  }
1817  }
1818  } else {
1819  // Si faux donc return array
1820  // List for Dolibarr users
1821  if ($type) {
1822  // If we need users of Dolibarr
1823  $sql = "SELECT";
1824  if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1825  $sql .= " DISTINCT";
1826  }
1827  $sql .= " u.rowid, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut, u.fk_user";
1828  $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
1829 
1830  if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1831  $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
1832  $sql .= " WHERE ((ug.fk_user = u.rowid";
1833  $sql .= " AND ug.entity IN (".getEntity('usergroup')."))";
1834  $sql .= " OR u.entity = 0)"; // Show always superadmin
1835  } else {
1836  $sql .= " WHERE u.entity IN (".getEntity('user').")";
1837  }
1838 
1839  $sql .= " AND u.statut > 0";
1840  $sql .= " AND u.employee = 1"; // We only want employee users for holidays
1841  if ($filters) {
1842  $sql .= $filters;
1843  }
1844 
1845  $resql = $this->db->query($sql);
1846 
1847  // Si pas d'erreur SQL
1848  if ($resql) {
1849  $i = 0;
1850  $tab_result = $this->holiday;
1851  $num = $this->db->num_rows($resql);
1852 
1853  // Boucles du listage des utilisateurs
1854  while ($i < $num) {
1855  $obj = $this->db->fetch_object($resql);
1856 
1857  $tab_result[$i]['rowid'] = $obj->rowid; // rowid of user
1858  $tab_result[$i]['name'] = $obj->lastname; // deprecated
1859  $tab_result[$i]['lastname'] = $obj->lastname;
1860  $tab_result[$i]['firstname'] = $obj->firstname;
1861  $tab_result[$i]['gender'] = $obj->gender;
1862  $tab_result[$i]['status'] = $obj->statut;
1863  $tab_result[$i]['employee'] = $obj->employee;
1864  $tab_result[$i]['photo'] = $obj->photo;
1865  $tab_result[$i]['fk_user'] = $obj->fk_user; // rowid of manager
1866  //$tab_result[$i]['type'] = $obj->type;
1867  //$tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
1868 
1869  $i++;
1870  }
1871  // Retoune le tableau des utilisateurs
1872  return $tab_result;
1873  } else {
1874  // Erreur SQL
1875  $this->errors[] = "Error ".$this->db->lasterror();
1876  return -1;
1877  }
1878  } else {
1879  // List of vacation balance users
1880  $sql = "SELECT cpu.fk_type, cpu.nb_holiday, u.rowid, u.lastname, u.firstname, u.gender, u.photo, u.employee, u.statut, u.fk_user";
1881  $sql .= " FROM ".MAIN_DB_PREFIX."holiday_users as cpu, ".MAIN_DB_PREFIX."user as u";
1882  $sql .= " WHERE cpu.fk_user = u.rowid";
1883  if ($filters) {
1884  $sql .= $filters;
1885  }
1886 
1887  $resql = $this->db->query($sql);
1888 
1889  // Si pas d'erreur SQL
1890  if ($resql) {
1891  $i = 0;
1892  $tab_result = $this->holiday;
1893  $num = $this->db->num_rows($resql);
1894 
1895  // Boucles du listage des utilisateurs
1896  while ($i < $num) {
1897  $obj = $this->db->fetch_object($resql);
1898 
1899  $tab_result[$i]['rowid'] = $obj->rowid; // rowid of user
1900  $tab_result[$i]['name'] = $obj->lastname; // deprecated
1901  $tab_result[$i]['lastname'] = $obj->lastname;
1902  $tab_result[$i]['firstname'] = $obj->firstname;
1903  $tab_result[$i]['gender'] = $obj->gender;
1904  $tab_result[$i]['status'] = $obj->statut;
1905  $tab_result[$i]['employee'] = $obj->employee;
1906  $tab_result[$i]['photo'] = $obj->photo;
1907  $tab_result[$i]['fk_user'] = $obj->fk_user; // rowid of manager
1908 
1909  $tab_result[$i]['type'] = $obj->fk_type;
1910  $tab_result[$i]['nb_holiday'] = $obj->nb_holiday;
1911 
1912  $i++;
1913  }
1914  // Retoune le tableau des utilisateurs
1915  return $tab_result;
1916  } else {
1917  // Erreur SQL
1918  $this->error = "Error ".$this->db->lasterror();
1919  return -1;
1920  }
1921  }
1922  }
1923  }
1924 
1925 
1926  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1934  {
1935  // phpcs:enable
1936  $users_validator = array();
1937 
1938  $sql = "SELECT DISTINCT ur.fk_user";
1939  $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
1940  $sql .= " WHERE ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'"; // Permission 'Approve';
1941  $sql .= "UNION";
1942  $sql .= " SELECT DISTINCT ugu.fk_user";
1943  $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_user as ugu, ".MAIN_DB_PREFIX."usergroup_rights as ur, ".MAIN_DB_PREFIX."rights_def as rd";
1944  $sql .= " WHERE ugu.fk_usergroup = ur.fk_usergroup AND ur.fk_id = rd.id and rd.module = 'holiday' AND rd.perms = 'approve'"; // Permission 'Approve';
1945  //print $sql;
1946 
1947  dol_syslog(get_class($this)."::fetch_users_approver_holiday sql=".$sql);
1948  $result = $this->db->query($sql);
1949  if ($result) {
1950  $num_rows = $this->db->num_rows($result); $i = 0;
1951  while ($i < $num_rows) {
1952  $objp = $this->db->fetch_object($result);
1953  array_push($users_validator, $objp->fk_user);
1954  $i++;
1955  }
1956  return $users_validator;
1957  } else {
1958  $this->error = $this->db->lasterror();
1959  dol_syslog(get_class($this)."::fetch_users_approver_holiday Error ".$this->error, LOG_ERR);
1960  return -1;
1961  }
1962  }
1963 
1964 
1970  public function countActiveUsers()
1971  {
1972  $sql = "SELECT count(u.rowid) as compteur";
1973  $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
1974  $sql .= " WHERE u.statut > 0";
1975 
1976  $result = $this->db->query($sql);
1977  $objet = $this->db->fetch_object($result);
1978 
1979  return $objet->compteur;
1980  }
1986  public function countActiveUsersWithoutCP()
1987  {
1988 
1989  $sql = "SELECT count(u.rowid) as compteur";
1990  $sql .= " FROM ".MAIN_DB_PREFIX."user as u LEFT OUTER JOIN ".MAIN_DB_PREFIX."holiday_users hu ON (hu.fk_user=u.rowid)";
1991  $sql .= " WHERE u.statut > 0 AND hu.fk_user IS NULL";
1992 
1993  $result = $this->db->query($sql);
1994  $objet = $this->db->fetch_object($result);
1995 
1996  return $objet->compteur;
1997  }
1998 
2006  public function verifNbUsers($userDolibarrWithoutCP, $userCP)
2007  {
2008  if (empty($userCP)) {
2009  $userCP = 0;
2010  }
2011  dol_syslog(get_class($this).'::verifNbUsers userDolibarr='.$userDolibarrWithoutCP.' userCP='.$userCP);
2012  return 1;
2013  }
2014 
2015 
2026  public function addLogCP($fk_user_action, $fk_user_update, $label, $new_solde, $fk_type)
2027  {
2028  global $conf, $langs;
2029 
2030  $error = 0;
2031 
2032  $prev_solde = price2num($this->getCPforUser($fk_user_update, $fk_type), 5);
2033  $new_solde = price2num($new_solde, 5);
2034  //print "$prev_solde == $new_solde";
2035 
2036  if ($prev_solde == $new_solde) {
2037  return 0;
2038  }
2039 
2040  $this->db->begin();
2041 
2042  // Insert request
2043  $sql = "INSERT INTO ".MAIN_DB_PREFIX."holiday_logs (";
2044  $sql .= "date_action,";
2045  $sql .= "fk_user_action,";
2046  $sql .= "fk_user_update,";
2047  $sql .= "type_action,";
2048  $sql .= "prev_solde,";
2049  $sql .= "new_solde,";
2050  $sql .= "fk_type";
2051  $sql .= ") VALUES (";
2052  $sql .= " '".$this->db->idate(dol_now())."',";
2053  $sql .= " ".((int) $fk_user_action).",";
2054  $sql .= " ".((int) $fk_user_update).",";
2055  $sql .= " '".$this->db->escape($label)."',";
2056  $sql .= " ".((float) $prev_solde).",";
2057  $sql .= " ".((float) $new_solde).",";
2058  $sql .= " ".((int) $fk_type);
2059  $sql .= ")";
2060 
2061  $resql = $this->db->query($sql);
2062  if (!$resql) {
2063  $error++; $this->errors[] = "Error ".$this->db->lasterror();
2064  }
2065 
2066  if (!$error) {
2067  $this->optRowid = $this->db->last_insert_id(MAIN_DB_PREFIX."holiday_logs");
2068  }
2069 
2070  // Commit or rollback
2071  if ($error) {
2072  foreach ($this->errors as $errmsg) {
2073  dol_syslog(get_class($this)."::addLogCP ".$errmsg, LOG_ERR);
2074  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
2075  }
2076  $this->db->rollback();
2077  return -1 * $error;
2078  } else {
2079  $this->db->commit();
2080  return $this->optRowid;
2081  }
2082  }
2083 
2091  public function fetchLog($order, $filter)
2092  {
2093  $sql = "SELECT";
2094  $sql .= " cpl.rowid,";
2095  $sql .= " cpl.date_action,";
2096  $sql .= " cpl.fk_user_action,";
2097  $sql .= " cpl.fk_user_update,";
2098  $sql .= " cpl.type_action,";
2099  $sql .= " cpl.prev_solde,";
2100  $sql .= " cpl.new_solde,";
2101  $sql .= " cpl.fk_type";
2102  $sql .= " FROM ".MAIN_DB_PREFIX."holiday_logs as cpl";
2103  $sql .= " WHERE cpl.rowid > 0"; // To avoid error with other search and criteria
2104 
2105  // Filtrage de séléction
2106  if (!empty($filter)) {
2107  $sql .= " ".$filter;
2108  }
2109 
2110  // Ordre d'affichage
2111  if (!empty($order)) {
2112  $sql .= " ".$order;
2113  }
2114 
2115  dol_syslog(get_class($this)."::fetchLog", LOG_DEBUG);
2116  $resql = $this->db->query($sql);
2117 
2118  // Si pas d'erreur SQL
2119  if ($resql) {
2120  $i = 0;
2121  $tab_result = $this->logs;
2122  $num = $this->db->num_rows($resql);
2123 
2124  // Si pas d'enregistrement
2125  if (!$num) {
2126  return 2;
2127  }
2128 
2129  // On liste les résultats et on les ajoutent dans le tableau
2130  while ($i < $num) {
2131  $obj = $this->db->fetch_object($resql);
2132 
2133  $tab_result[$i]['rowid'] = $obj->rowid;
2134  $tab_result[$i]['date_action'] = $obj->date_action;
2135  $tab_result[$i]['fk_user_action'] = $obj->fk_user_action;
2136  $tab_result[$i]['fk_user_update'] = $obj->fk_user_update;
2137  $tab_result[$i]['type_action'] = $obj->type_action;
2138  $tab_result[$i]['prev_solde'] = $obj->prev_solde;
2139  $tab_result[$i]['new_solde'] = $obj->new_solde;
2140  $tab_result[$i]['fk_type'] = $obj->fk_type;
2141 
2142  $i++;
2143  }
2144  // Retourne 1 et ajoute le tableau à la variable
2145  $this->logs = $tab_result;
2146  return 1;
2147  } else {
2148  // Erreur SQL
2149  $this->error = "Error ".$this->db->lasterror();
2150  return -1;
2151  }
2152  }
2153 
2154 
2162  public function getTypes($active = -1, $affect = -1)
2163  {
2164  global $mysoc;
2165 
2166  $sql = "SELECT rowid, code, label, affect, delay, newbymonth";
2167  $sql .= " FROM ".MAIN_DB_PREFIX."c_holiday_types";
2168  $sql .= " WHERE (fk_country IS NULL OR fk_country = ".((int) $mysoc->country_id).')';
2169  if ($active >= 0) {
2170  $sql .= " AND active = ".((int) $active);
2171  }
2172  if ($affect >= 0) {
2173  $sql .= " AND affect = ".((int) $affect);
2174  }
2175  $sql .= " ORDER BY sortorder";
2176 
2177  $result = $this->db->query($sql);
2178  if ($result) {
2179  $num = $this->db->num_rows($result);
2180  if ($num) {
2181  while ($obj = $this->db->fetch_object($result)) {
2182  $types[$obj->rowid] = array('rowid'=> $obj->rowid, 'code'=> $obj->code, 'label'=>$obj->label, 'affect'=>$obj->affect, 'delay'=>$obj->delay, 'newbymonth'=>$obj->newbymonth);
2183  }
2184 
2185  return $types;
2186  }
2187  } else {
2188  dol_print_error($this->db);
2189  }
2190 
2191  return array();
2192  }
2193 
2194 
2201  public function info($id)
2202  {
2203  global $conf;
2204 
2205  $sql = "SELECT f.rowid, f.statut as status,";
2206  $sql .= " f.date_create as datec,";
2207  $sql .= " f.tms as date_modification,";
2208  $sql .= " f.date_valid as datev,";
2209  $sql .= " f.date_approve as datea,";
2210  $sql .= " f.date_refuse as dater,";
2211  $sql .= " f.fk_user_create as fk_user_creation,";
2212  $sql .= " f.fk_user_modif as fk_user_modification,";
2213  $sql .= " f.fk_user_valid as fk_user_approve_done,";
2214  $sql .= " f.fk_validator as fk_user_approve_expected,";
2215  $sql .= " f.fk_user_refuse as fk_user_refuse";
2216  $sql .= " FROM ".MAIN_DB_PREFIX."holiday as f";
2217  $sql .= " WHERE f.rowid = ".((int) $id);
2218  $sql .= " AND f.entity = ".$conf->entity;
2219 
2220  $resql = $this->db->query($sql);
2221  if ($resql) {
2222  if ($this->db->num_rows($resql)) {
2223  $obj = $this->db->fetch_object($resql);
2224 
2225  $this->id = $obj->rowid;
2226 
2227  $this->date_creation = $this->db->jdate($obj->datec);
2228  $this->date_modification = $this->db->jdate($obj->date_modification);
2229  $this->date_validation = $this->db->jdate($obj->datev);
2230  $this->date_approbation = $this->db->jdate($obj->datea);
2231 
2232  if (!empty($obj->fk_user_creation)) {
2233  $cuser = new User($this->db);
2234  $cuser->fetch($obj->fk_user_creation);
2235  $this->user_creation = $cuser;
2236  }
2237  if (!empty($obj->fk_user_approve_done)) {
2238  $vuser = new User($this->db);
2239  $vuser->fetch($obj->fk_user_approve_done);
2240  $this->user_validation = $vuser;
2241  }
2242  if (!empty($obj->fk_user_modification)) {
2243  $muser = new User($this->db);
2244  $muser->fetch($obj->fk_user_modification);
2245  $this->user_modification = $muser;
2246  }
2247 
2248  if ($obj->status == Holiday::STATUS_APPROVED || $obj->status == Holiday::STATUS_CANCELED) {
2249  if ($obj->fk_user_approve_done) {
2250  $auser = new User($this->db);
2251  $auser->fetch($obj->fk_user_approve_done);
2252  $this->user_approve = $auser;
2253  }
2254  } else {
2255  if (!empty($obj->fk_user_approve_expected)) {
2256  $auser = new User($this->db);
2257  $auser->fetch($obj->fk_user_approve_expected);
2258  $this->user_approve = $auser;
2259  }
2260  }
2261  }
2262  $this->db->free($resql);
2263  } else {
2264  dol_print_error($this->db);
2265  }
2266  }
2267 
2268 
2276  public function initAsSpecimen()
2277  {
2278  global $user, $langs;
2279 
2280  // Initialise parameters
2281  $this->id = 0;
2282  $this->specimen = 1;
2283 
2284  $this->fk_user = $user->id;
2285  $this->description = 'SPECIMEN description';
2286  $this->date_debut = dol_now();
2287  $this->date_fin = dol_now() + (24 * 3600);
2288  $this->date_valid = dol_now();
2289  $this->fk_validator = $user->id;
2290  $this->halfday = 0;
2291  $this->fk_type = 1;
2292  $this->statut = Holiday::STATUS_VALIDATED;
2293  }
2294 
2295  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2301  public function load_state_board()
2302  {
2303  // phpcs:enable
2304  global $user;
2305 
2306  $this->nb = array();
2307 
2308  $sql = "SELECT count(h.rowid) as nb";
2309  $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
2310  $sql .= " WHERE h.statut > 1";
2311  $sql .= " AND h.entity IN (".getEntity('holiday').")";
2312  if (empty($user->rights->expensereport->readall)) {
2313  $userchildids = $user->getAllChildIds(1);
2314  $sql .= " AND (h.fk_user IN (".$this->db->sanitize(join(',', $userchildids)).")";
2315  $sql .= " OR h.fk_validator IN (".$this->db->sanitize(join(',', $userchildids))."))";
2316  }
2317 
2318  $resql = $this->db->query($sql);
2319  if ($resql) {
2320  while ($obj = $this->db->fetch_object($resql)) {
2321  $this->nb["holidays"] = $obj->nb;
2322  }
2323  $this->db->free($resql);
2324  return 1;
2325  } else {
2326  dol_print_error($this->db);
2327  $this->error = $this->db->error();
2328  return -1;
2329  }
2330  }
2331 
2332  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2339  public function load_board($user)
2340  {
2341  // phpcs:enable
2342  global $conf, $langs;
2343 
2344  if ($user->socid) {
2345  return -1; // protection pour eviter appel par utilisateur externe
2346  }
2347 
2348  $now = dol_now();
2349 
2350  $sql = "SELECT h.rowid, h.date_debut";
2351  $sql .= " FROM ".MAIN_DB_PREFIX."holiday as h";
2352  $sql .= " WHERE h.statut = 2";
2353  $sql .= " AND h.entity IN (".getEntity('holiday').")";
2354  if (empty($user->rights->expensereport->read_all)) {
2355  $userchildids = $user->getAllChildIds(1);
2356  $sql .= " AND (h.fk_user IN (".$this->db->sanitize(join(',', $userchildids)).")";
2357  $sql .= " OR h.fk_validator IN (".$this->db->sanitize(join(',', $userchildids))."))";
2358  }
2359 
2360  $resql = $this->db->query($sql);
2361  if ($resql) {
2362  $langs->load("members");
2363 
2364  $response = new WorkboardResponse();
2365  $response->warning_delay = $conf->holiday->approve->warning_delay / 60 / 60 / 24;
2366  $response->label = $langs->trans("HolidaysToApprove");
2367  $response->labelShort = $langs->trans("ToApprove");
2368  $response->url = DOL_URL_ROOT.'/holiday/list.php?search_status=2&amp;mainmenu=hrm&amp;leftmenu=holiday';
2369  $response->img = img_object('', "holiday");
2370 
2371  while ($obj = $this->db->fetch_object($resql)) {
2372  $response->nbtodo++;
2373 
2374  if ($this->db->jdate($obj->date_debut) < ($now - $conf->holiday->approve->warning_delay)) {
2375  $response->nbtodolate++;
2376  }
2377  }
2378 
2379  return $response;
2380  } else {
2381  dol_print_error($this->db);
2382  $this->error = $this->db->error();
2383  return -1;
2384  }
2385  }
2386 }
getNextNumRef($objsoc)
Returns the reference to the following non used Order depending on the active numbering module define...
validate($user=null, $notrigger=0)
Validate leave request.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield= 'rowid')
Return the value of a filed into a dictionary for the record $id.
Class of the module paid holiday.
load_board($user)
Load indicators for dashboard (this-&gt;nbtodo and this-&gt;nbtodolate)
getTypes($active=-1, $affect=-1)
Return array with list of types.
fetchUsers($stringlist=true, $type=true, $filters= '')
Get list of Users or list of vacation balance.
$conf db
API class for accounts.
Definition: inc.php:41
getLibStatut($mode=0)
Returns the label status.
getCPforUser($user_id, $fk_type=0)
Return balance of holiday for one user.
dol_now($mode= 'auto')
Return date for now.
deleteCPuser($user_id)
Supprime un utilisateur du module Congés Payés.
Class to manage Dolibarr users.
Definition: user.class.php:44
updateConfCP($name, $value)
Met à jour une option du module Holiday Payés.
updateSoldeCP($userID= '', $nbHoliday= '', $fk_type= '')
Met à jour le timestamp de la dernière mise à jour du solde des CP.
getConfCP($name, $createifnotfound= '')
Return value of a conf parameter for leave module TODO Move this into llx_const table.
update($user=null, $notrigger=0)
Update database.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags= '', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...
updateBalance()
Update balance of vacations and check table of users for holidays is complete.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
initAsSpecimen()
Initialise an instance with random values.
fetch($id, $ref= '')
Load object in memory from database.
insertExtraFields($trigger= '', $userused=null)
Add/Update all extra fields values for the current object.
fetchLog($order, $filter)
Liste le log des congés payés.
const STATUS_DRAFT
Draft status.
info($id)
Load information on object.
fetchByUser($user_id, $order= '', $filter= '')
List holidays for a particular user or list of users.
countActiveUsers()
Compte le nombre d&#39;utilisateur actifs dans Dolibarr.
create($user, $notrigger=0)
Créer un congés payés dans la base de données.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
selectStatutCP($selected= '', $htmlname= 'select_statut', $morecss= 'minwidth125')
Affiche un select HTML des statuts de congés payés.
approve($user=null, $notrigger=0)
Approve leave request.
verifDateHolidayForTimestamp($fk_user, $timestamp, $status= '-1')
Check that a user is not on holiday for a particular timestamp.
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
const STATUS_APPROVED
Approved.
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
verifDateHolidayCP($fk_user, $dateStart, $dateEnd, $halfday=0)
Check if a user is on holiday (partially or completely) into a period.
fetchAll($order, $filter)
List all holidays of all users.
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this-&gt;array_options This method is in most cases call...
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete= 'resolve', $idforemptyvalue= '-1')
Convert a html select field into an ajax combobox.
Definition: ajax.lib.php:429
load_state_board()
Load this-&gt;nb for dashboard.
if(isModEnabled('facture')&&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur')&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)&&$user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice')&&$user->rights->supplier_invoice->lire)) if(isModEnabled('don')&&!empty($user->rights->don->lire)) if(isModEnabled('tax')&&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture')&&isModEnabled('commande')&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
addLogCP($fk_user_action, $fk_user_update, $label, $new_solde, $fk_type)
addLogCP
div float
Buy price without taxes.
Definition: style.css.php:809
print *****$script_file(".$version.") pid cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
call_trigger($triggerName, $user)
Call trigger based on this instance.
getNomUrl($withpicto=0, $save_lastsearch_value=-1, $notooltip=0)
Return clicable name (with picto eventually)
const STATUS_VALIDATED
Validated status.
$object ref
Definition: info.php:77
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
verifNbUsers($userDolibarrWithoutCP, $userCP)
Compare le nombre d&#39;utilisateur actif de Dolibarr à celui des utilisateurs des congés payés...
dolGetStatus($statusLabel= '', $statusLabelShort= '', $html= '', $statusType= 'status0', $displayMode=0, $url= '', $params=array())
Output the badge of a status.
__construct($db)
Constructor.
const STATUS_CANCELED
Canceled.
const STATUS_REFUSED
Refused.
countActiveUsersWithoutCP()
Compte le nombre d&#39;utilisateur actifs dans Dolibarr sans CP.
createCPusers($single=false, $userid= '')
Créer les entrées pour chaque utilisateur au moment de la configuration.
getCheckOption($name)
Retourne un checked si vrai.
fetch_users_approver_holiday()
Return list of people with permission to validate leave requests.
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
LibStatut($status, $mode=0, $startdate= '')
Returns the label of a status.