dolibarr  20.0.0-beta
card_group.php
1 <?php
2 /* Copyright (C) 2011 Dimitri Mouillard <dmouillard@teclib.com>
3  * Copyright (C) 2012-2016 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2012-2016 Regis Houssin <regis.houssin@inodbox.com>
5  * Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es>
6  * Copyright (C) 2017 Alexandre Spangaro <aspangaro@open-dsi.fr>
7  * Copyright (C) 2014-2017 Ferran Marcet <fmarcet@2byte.es>
8  * Copyright (C) 2018-2024 Frédéric France <frederic.france@free.fr>
9  * Copyright (C) 2020-2021 Udo Tamm <dev@dolibit.de>
10  * Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
11  * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 3 of the License, orwrite
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program. If not, see <https://www.gnu.org/licenses/>.
25  */
26 
33 // Load Dolibarr environment
34 require '../main.inc.php';
35 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
36 require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
37 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
38 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
39 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
40 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
41 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
42 require_once DOL_DOCUMENT_ROOT.'/core/lib/holiday.lib.php';
43 require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
44 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
45 
46 // Get parameters
47 $action = GETPOST('action', 'aZ09');
48 $cancel = GETPOST('cancel', 'alpha');
49 $confirm = GETPOST('confirm', 'alpha');
50 $id = GETPOSTINT('id');
51 $ref = GETPOST('ref', 'alpha');
52 $fuserid = (GETPOSTINT('fuserid') ? GETPOSTINT('fuserid') : $user->id);
53 $users = (GETPOST('users', 'array') ? GETPOST('users', 'array') : array($user->id));
54 $groups = GETPOST('groups', 'array');
55 $socid = GETPOSTINT('socid');
56 $autoValidation = GETPOSTINT('autoValidation');
57 $AutoSendMail = GETPOSTINT('AutoSendMail');
58 // Load translation files required by the page
59 $langs->loadLangs(array("other", "holiday", "mails", "trips"));
60 
61 $error = 0;
62 
63 $now = dol_now();
64 
65 $childids = $user->getAllChildIds(1);
66 
67 $morefilter = '';
68 if (getDolGlobalString('HOLIDAY_HIDE_FOR_NON_SALARIES')) {
69  $morefilter = 'AND employee = 1';
70 }
71 
72 $object = new Holiday($db);
73 
74 $extrafields = new ExtraFields($db);
75 
76 // fetch optionals attributes and labels
77 $extrafields->fetch_name_optionals_label($object->table_element);
78 
79 if (($id > 0) || $ref) {
80  $object->fetch($id, $ref);
81 
82  // Check current user can read this leave request
83  $canread = 0;
84  if ($user->hasRight('holiday', 'readall')) {
85  $canread = 1;
86  }
87  if ($user->hasRight('holiday', 'read') && in_array($object->fk_user, $childids)) {
88  $canread = 1;
89  }
90  if (!$canread) {
92  }
93 }
94 
95 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
96 $hookmanager->initHooks(array('holidaycard', 'globalcard'));
97 
98 $cancreate = 0;
99 $cancreateall = 0;
100 if ($user->hasRight('holiday', 'write') && in_array($fuserid, $childids)) {
101  $cancreate = 1;
102 }
103 if ($user->hasRight('holiday', 'writeall')) {
104  $cancreate = 1;
105  $cancreateall = 1;
106 }
107 
108 $candelete = 0;
109 if ($user->hasRight('holiday', 'delete')) {
110  $candelete = 1;
111 }
112 if ($object->status == Holiday::STATUS_DRAFT && $user->hasRight('holiday', 'write') && in_array($object->fk_user, $childids)) {
113  $candelete = 1;
114 }
115 
116 // Protection if external user
117 if ($user->socid) {
118  $socid = $user->socid;
119 }
120 $result = restrictedArea($user, 'holiday', $object->id, 'holiday', '', '', 'rowid', $object->status);
121 
122 
123 /*
124  * Actions
125  */
126 
127 $parameters = array('socid' => $socid);
128 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
129 if ($reshook < 0) {
130  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
131 }
132 
133 if (empty($reshook)) {
134  $backurlforlist = DOL_URL_ROOT.'/holiday/list.php';
135 
136  if (empty($backtopage) || ($cancel && empty($id))) {
137  if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
138  if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
139  $backtopage = $backurlforlist;
140  } else {
141  $backtopage = DOL_URL_ROOT.'/holiday/card_group.php?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
142  }
143  }
144  }
145 
146  if ($cancel) {
147  if (!empty($backtopageforcancel)) {
148  header("Location: ".$backtopageforcancel);
149  exit;
150  } elseif (!empty($backtopage)) {
151  header("Location: ".$backtopage);
152  exit;
153  }
154  $action = '';
155  }
156 
157  // Add leave request
158  if ($action == 'add') {
159  // If no right to create a request
160  if (!$cancreate) {
161  $error++;
162  setEventMessages($langs->trans('CantCreateCP'), null, 'errors');
163  $action = 'create';
164  }
165 
166  if (!$error) {
167  $users = GETPOST('users', 'array');
168  $groups = GETPOST('groups', 'array');
169 
170  $date_debut = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'));
171  $date_fin = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'));
172  $date_debut_gmt = dol_mktime(0, 0, 0, GETPOST('date_debut_month'), GETPOST('date_debut_day'), GETPOST('date_debut_year'), 1);
173  $date_fin_gmt = dol_mktime(0, 0, 0, GETPOST('date_fin_month'), GETPOST('date_fin_day'), GETPOST('date_fin_year'), 1);
174  $starthalfday = GETPOST('starthalfday');
175  $endhalfday = GETPOST('endhalfday');
176  $type = GETPOSTINT('type');
177 
178  $halfday = 0;
179  if ($starthalfday == 'afternoon' && $endhalfday == 'morning') {
180  $halfday = 2;
181  } elseif ($starthalfday == 'afternoon') {
182  $halfday = -1;
183  } elseif ($endhalfday == 'morning') {
184  $halfday = 1;
185  }
186 
187  $approverid = GETPOSTINT('valideur');
188  $description = trim(GETPOST('description', 'restricthtml'));
189 
190  // Check that leave is for a user inside the hierarchy or advanced permission for all is set
191  if (!$cancreateall) {
192  if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
193  if (!$user->hasRight('holiday', 'write')) {
194  $error++;
195  setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
196  } elseif (!in_array($fuserid, $childids)) {
197  $error++;
198  setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
199  $action = 'create';
200  }
201  } else {
202  if (!$user->hasRight('holiday', 'write') && !$user->hasRight('holiday', 'writeall_advance')) {
203  $error++;
204  setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
205  } elseif (!$user->hasRight('holiday', 'writeall_advance') && !in_array($fuserid, $childids)) {
206  $error++;
207  setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
208  $action = 'create';
209  }
210  }
211  }
212  // If no groups and no users
213  if (empty($groups) && empty($users)) {
214  setEventMessages($langs->trans("ErrorFieldRequiredUserOrGroup"), null, 'errors');
215  //setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UserOrGroup")), null, 'errors');
216  //setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Group")), null, 'errors');
217  $error++;
218  $action = 'create';
219  }
220  // If no type
221  if ($type <= 0) {
222  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
223  $error++;
224  $action = 'create';
225  }
226 
227  // If no start date
228  if (empty($date_debut)) {
229  setEventMessages($langs->trans("NoDateDebut"), null, 'errors');
230  $error++;
231  $action = 'create';
232  }
233  // If no end date
234  if (empty($date_fin)) {
235  setEventMessages($langs->trans("NoDateFin"), null, 'errors');
236  $error++;
237  $action = 'create';
238  }
239  // If start date after end date
240  if ($date_debut > $date_fin) {
241  setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors');
242  $error++;
243  $action = 'create';
244  }
245 
246  // If there is no Business Days within request
247  $nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday);
248  if ($nbopenedday < 0.5) {
249  setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); // No working day
250  $error++;
251  $action = 'create';
252  }
253 
254  // If no validator designated
255  if ($approverid < 1) {
256  setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors');
257  $error++;
258  }
259 
260  $result = 0;
261 
262 
263  if (!$error) {
264  $TusersToProcess = array();
265  // usergroup select
266  // better perf on single sql
268  $sql = ' SELECT DISTINCT u.rowid,u.lastname,u.firstname from ' . MAIN_DB_PREFIX . 'user as u';
269  $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'usergroup_user as ug on ug.fk_user = u.rowid ';
270  $sql .= ' WHERE fk_usergroup in (' .$db->sanitize(implode(',', $groups)) . ')';
271  $resql = $db->query($sql);
272 
273  if ($resql) {
274  while ($obj = $db->fetch_object($resql)) {
275  $TusersToProcess[$obj->rowid] = $obj->rowid;
276  }
277  }
279  if (is_array($users) && count($users) > 0) {
280  foreach ($users as $u) {
281  $TusersToProcess[$u] = $u;
282  }
283  }
284  foreach ($TusersToProcess as $u) {
285  // Check if there is already holiday for this period pour chaque user
286  $verifCP = $object->verifDateHolidayCP($u, $date_debut, $date_fin, $halfday);
287  if (!$verifCP) {
288  //setEventMessages($langs->trans("alreadyCPexist"), null, 'errors');
289 
290  $userError = new User($db);
291  $result = $userError->fetch($u);
292 
293  if ($result) {
294  setEventMessages($langs->trans("UseralreadyCPexist", $userError->firstname . ' '. $userError->lastname), null, 'errors');
295  } else {
296  setEventMessages($langs->trans("ErrorUserFetch", $u), null, 'errors');
297  }
298 
299  $error++;
300  $action = 'create';
301  }
302  }
303 
304  if (!$error) {
305  $db->begin();
306  // non errors we can insert all
307  foreach ($TusersToProcess as $u) {
308  $object = new Holiday($db);
309  $object->fk_user = $u;
310  $object->description = $description;
311  $object->fk_validator = $approverid;
312  $object->fk_type = $type;
313  $object->date_debut = $date_debut;
314  $object->date_fin = $date_fin;
315  $object->halfday = $halfday;
316 
317  $result = $object->create($user);
318 
319  if ($result <= 0) {
320  setEventMessages($object->error, $object->errors, 'errors');
321  $error++;
322  } else {
323  //@TODO changer le nom si validated
324  if ($autoValidation) {
325  $htemp = new Holiday($db);
326  $htemp->fetch($result);
327 
328  $htemp->status = Holiday::STATUS_VALIDATED;
329  $resultValidated = $htemp->update($approverid);
330 
331  if ($resultValidated < 0) {
332  setEventMessages($object->error, $object->errors, 'errors');
333  $error++;
334  }
335  // we can auto send mail if we are in auto validation behavior
336 
337  if ($AutoSendMail && !$error) {
338  // send a mail to the user
339  $returnSendMail = sendMail($result, $cancreate, $now, $autoValidation);
340  if (!empty($returnSendMail->msg)) {
341  setEventMessage($returnSendMail->msg, $returnSendMail->style);
342  }
343  }
344  }
345  }
346  }
347  }
348  // If no SQL error we redirect to the request card
349  if (!$error) {
350  $db->commit();
351  header('Location: '.DOL_URL_ROOT.'/holiday/list.php');
352  exit;
353  } else {
354  $db->rollback();
355  }
356  }
357  }
358  }
359 }
360 
361 
362 
363 /*
364  * View
365  */
366 
367 $form = new Form($db);
368 $object = new Holiday($db);
369 
370 $listhalfday = array('morning' => $langs->trans("Morning"), "afternoon" => $langs->trans("Afternoon"));
371 
372 $title = $langs->trans('Leave');
373 $help_url = 'EN:Module_Holiday';
374 
375 llxHeader('', $title, $help_url);
376 
377 if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') {
378  // If user has no permission to create a leave
379  if ((in_array($fuserid, $childids) && !$user->hasRight('holiday', 'writeall')) || (!in_array($fuserid, $childids) && (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || !$user->hasRight('holiday', 'writeall_advance')))) {
380  $errors[] = $langs->trans('CantCreateCP');
381  } else {
382  // Form to add a leave request
383  print load_fiche_titre($langs->trans('MenuCollectiveAddCP'), '', 'title_hrm.png');
384 
385  // Error management
386  if (GETPOST('error')) {
387  switch (GETPOST('error')) {
388  case 'datefin':
389  $errors[] = $langs->trans('ErrorEndDateCP');
390  break;
391  case 'SQL_Create':
392  $errors[] = $langs->trans('ErrorSQLCreateCP');
393  break;
394  case 'CantCreate':
395  $errors[] = $langs->trans('CantCreateCP');
396  break;
397  case 'Valideur':
398  $errors[] = $langs->trans('InvalidValidatorCP');
399  break;
400  case 'nodatedebut':
401  $errors[] = $langs->trans('NoDateDebut');
402  break;
403  case 'nodatefin':
404  $errors[] = $langs->trans('NoDateFin');
405  break;
406  case 'DureeHoliday':
407  $errors[] = $langs->trans('ErrorDureeCP');
408  break;
409  case 'alreadyCP':
410  $errors[] = $langs->trans('alreadyCPexist');
411  break;
412  }
413 
414  setEventMessages($errors, null, 'errors');
415  }
416 
417 
418  print '<script type="text/javascript">
419  $( document ).ready(function() {
420 
421  if( $("input[name=autoValidation]").is(":checked") ){
422  $("#AutoSendMail").prop("disabled", false);
423  $("#AutoSendMail").prop("checked", true);
424 
425  } else {
426  $("#AutoSendMail").prop("disabled", true);
427  $("#AutoSendMail").prop("checked", false);
428  }
429 
430  $("input[name=autoValidation]").click( function(e) {
431 
432 
433  if( $("input[name=autoValidation]").is(":checked") ){
434  $("#AutoSendMail").prop("disabled", false);
435  $("#AutoSendMail").prop("checked", true);
436  } else {
437  $("#AutoSendMail").prop("disabled", true);
438  $("#AutoSendMail").prop("checked", false);
439  }
440  });
441 
442 
443 
444  $("input.button-save").click("submit", function(e) {
445  console.log("Call valider()");
446  if (document.demandeCP.date_debut_.value != "")
447  {
448  if(document.demandeCP.date_fin_.value != "")
449  {
450  if(document.demandeCP.valideur.value != "-1") {
451  return true;
452  }
453  else {
454  alert("'.dol_escape_js($langs->transnoentities('InvalidValidatorCP')).'");
455  return false;
456  }
457  }
458  else
459  {
460  alert("'.dol_escape_js($langs->transnoentities('NoDateFin')).'");
461  return false;
462  }
463  }
464  else
465  {
466  alert("'.dol_escape_js($langs->transnoentities('NoDateDebut')).'");
467  return false;
468  }
469  })
470 
471  $("#autoValidation").change(function(){
472  if( $("input[name=autoValidation]").is(":checked") ){
473  $("#AutoSendMail").prop("disabled", false);
474  } else {
475  $("#AutoSendMail").prop("disabled", true);
476  $("#AutoSendMail").prop("checked", false);
477  }
478  })
479  });
480  </script>'."\n";
481 
482 
483  // Formulaire de demande
484  print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'" name="demandeCP">'."\n";
485  print '<input type="hidden" name="token" value="'.newToken().'" />'."\n";
486  print '<input type="hidden" name="action" value="add" />'."\n";
487 
488  print dol_get_fiche_head();
489 
490  print '<table class="border centpercent">';
491  print '<tbody>';
492 
493  // Groups of users
494  print '<tr>';
495  print '<td class="titlefield fieldrequired">';
496  print $form->textwithpicto($langs->trans("groups"), $langs->trans("fusionGroupsUsers"));
497  print '</td>';
498  print '<td>';
499  print img_picto($langs->trans("groups"), 'group', 'class="pictofixedwidth"');
500 
501  $sql = ' SELECT rowid, nom from '.MAIN_DB_PREFIX.'usergroup WHERE entity IN ('.getEntity('usergroup').')';
502  $resql = $db->query($sql);
503  $Tgroup = array();
504  while ($obj = $db->fetch_object($resql)) {
505  $Tgroup[$obj->rowid] = $obj->nom;
506  }
507 
508  print $form->multiselectarray('groups', $Tgroup, GETPOST('groups', 'array'), '', 0, 'quatrevingtpercent widthcentpercentminusx', 0, 0);
509 
510  print '</td>';
511 
512  // Users
513  print '<tr>';
514  print '<td class="titlefield fieldrequired">';
515  print $form->textwithpicto($langs->trans("users"), $langs->trans("fusionGroupsUsers"));
516  print '<td>';
517  print img_picto($langs->trans("users"), 'user', 'class="pictofixedwidth"');
518 
519  $sql = ' SELECT u.rowid, u.lastname, u.firstname from '.MAIN_DB_PREFIX.'user as u';
520  $sql .= ' WHERE 1=1';
521  $sql .= !empty($morefilter) ? $morefilter : '';
522 
523  $userlist = array();
524 
525  $resql = $db->query($sql);
526  if ($resql) {
527  while ($obj = $db->fetch_object($resql)) {
528  $userlist[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
529  }
530  }
531 
532  print img_picto('', 'users', 'class="pictofixedwidth"') . $form->multiselectarray('users', $userlist, GETPOST('users', 'array'), '', 0, 'quatrevingtpercent widthcentpercentminusx', 0, 0);
533  print '</td>';
534 
535  // Type
536  print '<tr>';
537  print '<td class="fieldrequired">'.$langs->trans("Type").'</td>';
538  print '<td>';
539  $typeleaves = $object->getTypes(1, -1);
540  $arraytypeleaves = array();
541  foreach ($typeleaves as $key => $val) {
542  $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']);
543  $labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')' : '');
544  $arraytypeleaves[$val['rowid']] = $labeltoshow;
545  }
546  print $form->selectarray('type', $arraytypeleaves, (GETPOST('type', 'alpha') ? GETPOST('type', 'alpha') : ''), 1, 0, 0, '', 0, 0, 0, '', '', true);
547  if ($user->admin) {
548  print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
549  }
550  print '</td>';
551  print '</tr>';
552 
553  // Date start
554  print '<tr>';
555  print '<td class="fieldrequired">';
556  print $form->textwithpicto($langs->trans("DateDebCP"), $langs->trans("FirstDayOfHoliday"));
557  print '</td>';
558  print '<td>';
559  // Si la demande ne vient pas de l'agenda
560  if (!GETPOST('date_debut_')) {
561  print $form->selectDate(-1, 'date_debut_', 0, 0, 0, '', 1, 1);
562  } else {
563  $tmpdate = dol_mktime(0, 0, 0, GETPOSTINT('date_debut_month'), GETPOSTINT('date_debut_day'), GETPOSTINT('date_debut_year'));
564  print $form->selectDate($tmpdate, 'date_debut_', 0, 0, 0, '', 1, 1);
565  }
566  print ' &nbsp; &nbsp; ';
567  print $form->selectarray('starthalfday', $listhalfday, (GETPOST('starthalfday', 'alpha') ? GETPOST('starthalfday', 'alpha') : 'morning'));
568  print '</td>';
569  print '</tr>';
570 
571  // Date end
572  print '<tr>';
573  print '<td class="fieldrequired">';
574  print $form->textwithpicto($langs->trans("DateFinCP"), $langs->trans("LastDayOfHoliday"));
575  print '</td>';
576  print '<td>';
577  if (!GETPOST('date_fin_')) {
578  print $form->selectDate(-1, 'date_fin_', 0, 0, 0, '', 1, 1);
579  } else {
580  $tmpdate = dol_mktime(0, 0, 0, GETPOSTINT('date_fin_month'), GETPOSTINT('date_fin_day'), GETPOSTINT('date_fin_year'));
581  print $form->selectDate($tmpdate, 'date_fin_', 0, 0, 0, '', 1, 1);
582  }
583  print ' &nbsp; &nbsp; ';
584  print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday', 'alpha') ? GETPOST('endhalfday', 'alpha') : 'afternoon'));
585  print '</td>';
586  print '</tr>';
587 
588  // Approver
589  print '<tr>';
590  print '<td class="fieldrequired">'.$langs->trans("ReviewedByCP").'</td>';
591  print '<td>';
592 
593  $object = new Holiday($db);
594  $include_users = $object->fetch_users_approver_holiday();
595  if (empty($include_users)) {
596  print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateHolidays");
597  } else {
598  // Defined default approver (the forced approved of user or the supervisor if no forced value defined)
599  // Note: This use will be set only if the deinfed approvr has permission to approve so is inside include_users
600  $defaultselectuser = (empty($user->fk_user_holiday_validator) ? $user->fk_user : $user->fk_user_holiday_validator);
601  if (getDolGlobalString('HOLIDAY_DEFAULT_VALIDATOR')) {
602  $defaultselectuser = getDolGlobalString('HOLIDAY_DEFAULT_VALIDATOR'); // Can force default approver
603  }
604  if (GETPOSTINT('valideur') > 0) {
605  $defaultselectuser = GETPOSTINT('valideur');
606  }
607  $s = $form->select_dolusers($defaultselectuser, "valideur", 1, '', 0, $include_users, '', '0,'.$conf->entity, 0, 0, '', 0, '', 'minwidth200 maxwidth500');
608  print img_picto('', 'user').$form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate"));
609  }
610 
611 
612  print '</td>';
613  print '</tr>';
614 
615  //auto validation ON CREATE
616  print '<tr><td>'.$langs->trans("AutoValidationOnCreate").'</td><td>';
617  print '<input type="checkbox" id="autoValidation" name="autoValidation" value="1"'.($autoValidation ? ' checked="checked"' : '').'>';
618  print '</td></tr>'."\n";
619 
620 
621  //no auto SEND MAIL
622  print '<tr><td>'.$langs->trans("AutoSendMail").'</td><td>';
623  print '<input type="checkbox" id="AutoSendMail" name="AutoSendMail" value="1"'.($AutoSendMail ? ' checked="checked"' : '').'>';
624  print '</td></tr>'."\n";
625 
626  // Description
627  print '<tr>';
628  print '<td>'.$langs->trans("DescCP").'</td>';
629  print '<td class="tdtop">';
630  $doleditor = new DolEditor('description', GETPOST('description', 'restricthtml'), '', 80, 'dolibarr_notes', 'In', 0, false, isModEnabled('fckeditor'), ROWS_3, '90%');
631  print $doleditor->Create(1);
632  print '</td></tr>';
633 
634  // Other attributes
635  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';
636 
637  print '</tbody>';
638  print '</table>';
639 
640  print dol_get_fiche_end();
641 
642  print $form->buttonsSaveCancel("SendRequestCollectiveCP");
643 
644  print '</from>'."\n";
645  }
646 } else {
647  if ($error) {
648  print '<div class="tabBar">';
649  print $error;
650  print '<br><br><input type="button" value="'.$langs->trans("ReturnCP").'" class="button" onclick="history.go(-1)" />';
651  print '</div>';
652  }
653 }
654 
655 // End of page
656 llxFooter();
657 
658 if (is_object($db)) {
659  $db->close();
660 }
672 function sendMail($id, $cancreate, $now, $autoValidation)
673 {
674  $objStd = new stdClass();
675  $objStd->msg = '';
676  $objStd->status = 'success';
677  $objStd->error = 0;
678  $objStd->style = '';
679 
680  global $db, $user, $conf, $langs;
681 
682  $object = new Holiday($db);
683 
684  $result = $object->fetch($id);
685 
686  if ($result) {
687  // If draft and owner of leave
688  if ($object->status == Holiday::STATUS_VALIDATED && $cancreate) {
689  $object->oldcopy = dol_clone($object, 2);
690 
691  //if ($autoValidation) $object->status = Holiday::STATUS_VALIDATED;
692 
693  $verif = $object->validate($user);
694 
695  if ($verif > 0) {
696  // To
697  $destinataire = new User($db);
698  $destinataire->fetch($object->fk_validator);
699  $emailTo = $destinataire->email;
700 
701 
702  if (!$emailTo) {
703  dol_syslog("Expected validator has no email, so we redirect directly to finished page without sending email");
704 
705  $objStd->error++;
706  $objStd->msg = $langs->trans('ErrorMailRecipientIsEmpty');
707  $objStd->status = 'error';
708  $objStd->style = "warnings";
709  return $objStd;
710  }
711 
712  // From
713  $expediteur = new User($db);
714  $expediteur->fetch($object->fk_user);
715  //$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
716  $emailFrom = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
717 
718  // Subject
719  $societeName = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
720  if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
721  $societeName = getDolGlobalString('MAIN_APPLICATION_TITLE');
722  }
723 
724  $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysToValidate");
725 
726  // Content
727  $message = "<p>".$langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",</p>\n";
728 
729  $message .= "<p>".$langs->transnoentities("HolidaysToValidateBody")."</p>\n";
730 
731 
732  // option to warn the validator in case of too short delay
733  if (!getDolGlobalString('HOLIDAY_HIDE_APPROVER_ABOUT_TOO_LOW_DELAY')) {
734  $delayForRequest = 0; // TODO Set delay depending of holiday leave type
735  if ($delayForRequest) {
736  $nowplusdelay = dol_time_plus_duree($now, $delayForRequest, 'd');
737 
738  if ($object->date_debut < $nowplusdelay) {
739  $message = "<p>".$langs->transnoentities("HolidaysToValidateDelay", $delayForRequest)."</p>\n";
740  }
741  }
742  }
743 
744  // option to notify the validator if the balance is less than the request
745  if (!getDolGlobalString('HOLIDAY_HIDE_APPROVER_ABOUT_NEGATIVE_BALANCE')) {
746  $nbopenedday = num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday);
747 
748  if ($nbopenedday > $object->getCPforUser($object->fk_user, $object->fk_type)) {
749  $message .= "<p>".$langs->transnoentities("HolidaysToValidateAlertSolde")."</p>\n";
750  }
751  }
752 
753  $typeleaves = $object->getTypes(1, -1);
754  $labeltoshow = (($typeleaves[$object->fk_type]['code'] && $langs->trans($typeleaves[$object->fk_type]['code']) != $typeleaves[$object->fk_type]['code']) ? $langs->trans($typeleaves[$object->fk_type]['code']) : $typeleaves[$object->fk_type]['label']);
755 
756  if ($object->halfday == 2) {
757  $starthalfdaykey = "Afternoon";
758  $endhalfdaykey = "Morning";
759  } elseif ($object->halfday == -1) {
760  $starthalfdaykey = "Afternoon";
761  $endhalfdaykey = "Afternoon";
762  } elseif ($object->halfday == 1) {
763  $starthalfdaykey = "Morning";
764  $endhalfdaykey = "Morning";
765  } elseif ($object->halfday == 0 || $object->halfday == 2) {
766  $starthalfdaykey = "Morning";
767  $endhalfdaykey = "Afternoon";
768  }
769 
770  $link = dol_buildpath("/holiday/card.php", 3) . '?id='.$object->id;
771 
772  $message .= "<ul>";
773  $message .= "<li>".$langs->transnoentitiesnoconv("Name")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."</li>\n";
774  $message .= "<li>".$langs->transnoentitiesnoconv("Type")." : ".(empty($labeltoshow) ? $langs->trans("TypeWasDisabledOrRemoved", $object->fk_type) : $labeltoshow)."</li>\n";
775  $message .= "<li>".$langs->transnoentitiesnoconv("Period")." : ".dol_print_date($object->date_debut, 'day')." ".$langs->transnoentitiesnoconv($starthalfdaykey)." ".$langs->transnoentitiesnoconv("To")." ".dol_print_date($object->date_fin, 'day')." ".$langs->transnoentitiesnoconv($endhalfdaykey)."</li>\n";
776  $message .= "<li>".$langs->transnoentitiesnoconv("Link").' : <a href="'.$link.'" target="_blank">'.$link."</a></li>\n";
777  $message .= "</ul>\n";
778 
779  $trackid = 'leav'.$object->id;
780 
781  $sendtobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_HOLIDAY_TO');
782 
783  $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', $sendtobcc, 0, 1, '', '', $trackid);
784 
785  // Sending the email
786  $result = $mail->sendfile();
787 
788  if (!$result) {
789  $objStd->error++;
790  $objStd->msg = $langs->trans('ErrorMailNotSend');
791  $objStd->style = "warnings";
792  $objStd->status = 'error';
793  } else {
794  $objStd->msg = $langs->trans('MailSent');
795  }
796 
797  return $objStd;
798  } else {
799  $objStd->error++;
800  $objStd->msg = $langs->trans('ErrorVerif');
801  $objStd->status = 'error';
802  $objStd->style = "errors";
803  return $objStd;
804  }
805  }
806  } else {
807  $objStd->error++;
808  $objStd->msg = $langs->trans('ErrorloadUserOnSendingMail');
809  $objStd->status = 'error';
810  $objStd->style = "warnings";
811  return $objStd;
812  }
813 
814  return $objStd;
815 }
if($user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition: card.php:58
if(!defined('NOREQUIRESOC')) if(!defined('NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) llxHeader()
Empty header.
Definition: wrapper.php:55
llxFooter()
Empty footer.
Definition: wrapper.php:69
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage a WYSIWYG editor.
Class to manage standard extra fields.
Class to manage generation of HTML components Only common components must be here.
Class of the module paid holiday.
const STATUS_VALIDATED
Validated status.
const STATUS_DRAFT
Draft status.
Class to manage Dolibarr users.
Definition: user.class.php:50
if(isModEnabled('invoice') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD') && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')) if(isModEnabled('invoice') &&isModEnabled('order') && $user->hasRight("commande", "lire") &&!getDolGlobalString('WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER')) $sql
Social contributions to pay.
Definition: index.php:745
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $country_code='')
Function to return number of working days (and text of units) between two dates (working days)
Definition: date.lib.php:1039
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:124
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...
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0)
Show tabs of a record.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0)
Set event message in dol_events session object.
dol_now($mode='auto')
Return date for now.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into javascript code.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='')
Show information in HTML for admin users or standard users.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $mode=0)
Check permissions of a user to show a page and an object.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.