dolibarr/htdocs/holiday/card.php
VIAL-GOUTEYRON Quentin ea54342891
NEW Drag and drop a file on the 23 remaining cards (#39473)
* FIX Drag and drop of a file reports a wrong error, or none at all

The error handler of dragAndDropFileUpload() had three defects that all end on
the user believing the file was attached when it was not.

 - The first assignment of the message was dead code, there was no return after
   the test on the http code 403, so a refusal was reported as a generic error.
 - The key ErrorUploadPermissionDenied it used exists in no language file, so
   the raw key was shown.
 - JSON.parse() was called with no try/catch on an answer that is not always a
   json, a fatal error of the endpoint or a request over post_max_size for
   example. The exception left the user on a page with no message at all.
 - An empty list of files was treated as a success, while it means the endpoint
   stored nothing.

The value of PHP_SELF is also escaped before it is written into the 6 generated
javascript strings. It holds the path info of the request on a server that
accepts it, so it is a user input. dol_escape_js() is called with the mode that
escapes a double quote by a double quote, the strings being delimited by double
quotes, and the sequence '</' is escaped too because the function does not do it
and the path info could otherwise close the script tag and open one of its own.

Adds the key ErrorOnAtLeastOneFileUpload to en_US, used when some files of a
batch failed and some did not.

* FIX getMultidirOutput returns a directory the Documents tab does not read

Four defects of the same function, all ending on a file stored where the user
will never see it, or written outside the documents directory.

 - The ref of the project of a task was only passed through dol_sanitizePathName(),
   which keeps a slash, a colon and the accented chars, while projet/tasks/document.php
   sanitizes it with dol_sanitizeFileName(). A project ref holding a slash even
   created an extra level of directory. Measured on real databases: 304 projects
   over 330 hold a slash on one of them, carrying 701 tasks over 824.
 - The same case calls $object->fetchProject() with no guard, while the signature
   of the function accepts an object that is not a CommonObject, and even a null
   when a module is given. Such a caller gets a fatal error where it expects the
   error string. No core caller is in that case today, an external module or a
   hook can be.
 - The entity of the object may have no declared directory, an object shared by
   another entity for example. The undefined index returned a relative path, so
   the caller read or wrote under the web root. The current entity is used
   instead, and the fallback is logged because the directory is then not the one
   of the entity of the object, which matters for a caller that deletes files.
 - When the current entity has no declared directory either, the fallback
   returned the sub directory alone, again a relative path. The same error than
   for a module that declares no directory at all is now returned.

Adds the sub directory of a partnership and of a stock transfer, which their own
document tabs already read.

* FIX getElementProperties answers wrong properties for 9 elements

A customer payment, a supplier payment, a various payment, a stock transfer and
the 4 objects of the hrm module had no properties at all, or wrong ones, so any
caller that resolves a class, a table or a document directory from an element
failed on them.

 - payment, payment_supplier and payment_various had no branch. The branch of a
   customer payment tests $elementType and not $element, because the rule on the
   elements named myobject_mysubobject rewrites $element to 'payment' for
   'payment_salary' too, which is stored somewhere else.
 - job, position, skill and evaluation answered a wrong table (hrm_job_user for
   a position, and so on) and no sub directory, while their document tabs read
   one named after the element.
 - stocktransfer answered an empty classname, because it is not the ucfirst() of
   the element, so a caller doing new $classname($db) ended on a fatal error.
 - The sub directory was concatenated even when the module is disabled and the
   directory is empty, which answered a path at the root of the file system.
 - A contact and a conference are stored into a sub directory their tab reads.

isModEnabled('invoice') is tested for a customer payment: there is no module
named 'compta', so testing it was always false, while $conf->compta->payment is
set unconditionally by Conf::setValues() and could not be used as a proxy.

* FIX Access refused to everyone on 11 objects of the core

restrictedArea() and checkUserAccessToObject() refuse the access to objects that
no permission and no rule can match, whatever the user, an administrator
included.

 - The hrm module declares no permission at its first level, only 'all', and the
   stocktransfer module only 'stocktransfer'. A check on the module itself
   therefore tests a permission that does not exist. The mapping is the same one
   as into User::hasRight().
 - The module of an event organization declares no permission at all, its whole
   permission block being commented out on purpose, and its cards check the
   parent project instead. The feature is mapped onto that project, with the two
   guards the card has: an external user is refused, and so is a conference with
   no parent project, whose id of 0 would otherwise grant an access with no check
   on the record at all.
 - The default rule of checkUserAccessToObject() builds its sql on the columns
   entity and fk_soc of the table. llx_asset, llx_paiement, llx_paiementfourn and
   llx_workstation_workstation have no fk_soc, and llx_hrm_job, llx_hrm_job_user
   and llx_hrm_skill have neither. The sql failed, so the access was refused to
   every user this rule applies to. These tables are now checked on their entity
   only, which is what the $check rule already does for the same class of tables,
   and the 3 tables of hrm can be checked on nothing at all. The rule is selected
   on the table and not on the element, because $object is an id and not an
   object for most of the callers, the cards of an asset and of a workstation
   included, which are broken today for any user without the permission to see
   all third parties.
 - An external user is refused explicitly on those tables: none of these objects
   is linked to a third party, so the default rule refused him through a link
   that does not exist, and the rules that replace it do not look at the third
   party of the user at all.

Measured on a vanilla instance with 5 profiles, an administrator, an internal
user with every right, one without the permission to see all third parties, one
that is not a sales representative of the third party of the object, and an
external user: the 11 objects go from refused to granted for the internal users
and stay refused for the external one, and the 26 other elements answer exactly
the same for the 5 profiles.

* FIX A file dropped on a card is lost, or reported as refused when it was stored

FileUpload stores the file into a directory that the "Attached files" tab of the
object never reads, so the user attaches a file that no screen will ever show,
and nothing is indexed in database to find it back. Measured on real databases:
216487 thirdparties over 216887 and 157852 products over 280319 are in that case
on the cards that already enable the drag and drop.

 - The directory of the object is now forged with get_exdir(), the way the tabs
   do: it always uses the id for a thirdparty, whose ref is a company name and is
   not unique, and it falls back on the id when the ref is empty. The sub
   directory of the module is read with getMultidirOutput(), which knows the
   elements that store their documents into one. That function does not return
   an empty string when it fails but a string starting with 'error-', so only an
   absolute path is accepted: writing into that string would create the files
   under the web root.
 - fetchObjectByElement() returns an object even when fetch() returned 0. The
   object was then not loaded, and the file was stored at the root of the
   directory of the module, out of any object. The constructor now throws, and
   the endpoint answers the error with the same json contract than a successful
   call so that the caller can show it, instead of a fatal error and an http 500.
 - An attachment of the same name was silently overwritten, dol_move_uploaded_file()
   being called with $allowoverwrite = 1 while the name was checked before the
   ref of the object was added as a prefix. The check is done again on the final
   name, and on the .noexe suffixed name too, which that function appends to an
   executable file.
 - An executable file was renamed with that .noexe suffix and then reported as an
   error, while it was correctly stored.
 - The endpoint called restrictedArea() with an empty feature when the element is
   unknown, and the loop of that function then takes no branch at all and grants
   the access with no check. It refuses before, with the same http code and the
   same message than a refusal, so that a user cannot tell an object that exists
   but is not allowed from an object that does not exist. The refusal of an
   external user on an object of another third party answered a message of its
   own, which allowed the same enumeration.

Comes with the tests of the path resolution, of the fallback of get_exdir(), of
the rejection of the error string of getMultidirOutput(), and of the file name
deduplication.

* FIX Remove the drop area from 13 cards where dropping a file is harmful

Two distinct groups, both of them removing a drop area that only produces a
result the user does not want.

7 pages have no "Attached files" tab at all, so a file dropped on them can be
reached by no screen: a fiscal year and its info page, an accounting model, a
webhook trigger history, an intracomm report, a bookcal calendar and its booking
list. Measured: 4 of them accepted the upload and wrote an orphan file, the
accounting model wrote it at the root of the directory of the module, out of any
object, and the 2 bookcal ones answered an http 500.

6 cards print their tabs inside their edit form, so the drop area covered that
form: a product, an expense report, a VAT payment, a social contribution, a loan
and a salary. Dropping a file there reloads the page, which discards what the
user is typing. A product and an expense report have a second call for the read
only view, so the drop area is only removed from the call of the edit branch;
the 4 others share a single call between both views, so the parameter is now
conditional.

* NEW Drag and drop a file on the 23 remaining cards

Every card of the core that owns an "Attached files" tab can now receive a file
by drag and drop, which was the case of 32 of them only. The 23 added here are
an asset, an event, a various payment, a customer payment, a contact, a donation,
a conference or booth, a shipment, a supplier payment, a leave request, an
evaluation, a job, a position, a skill, a knowledge record, a manufacturing
order, a partnership, a lot, a stock transfer, a task, a reception, a resource
and a workstation.

The tab bar of a leave request and of a resource is printed inside their edit
form, so the drop area is not enabled there: dropping a file reloads the page,
which would discard what the user is typing. The card of a supplier payment
prints its tab bar even when the object was not loaded, so the drop area is only
enabled when it is.

* FIX getMultidirOutput refuses an entity with no directory instead of falling back [skip-claudemd]

The previous revision of this PR fell back on the directory of the current
entity when the entity of the object had none, with a LOG_WARNING. On a
multicompany install that made a caller read, write and above all delete
files in the directory of another entity. Refuse instead: the function
already answers 'error-diroutput-not-defined-for-this-object' when the
module declares no directory at all, so the caller has one behaviour to
handle, not two.

The entity is cast to int, which is what the array index needs and what
silences the four PhanTypeMismatchDimFetchNullable this function reported.

---------

Co-authored-by: Laurent Destailleur <eldy@destailleur.fr>
2026-08-19 02:46:21 +02:00

1747 lines
64 KiB
PHP

<?php
/* Copyright (C) 2011 Dimitri Mouillard <dmouillard@teclib.com>
* Copyright (C) 2012-2016 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2012-2016 Regis Houssin <regis.houssin@inodbox.com>
* Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2017-2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
* Copyright (C) 2014-2017 Ferran Marcet <fmarcet@2byte.es>
* Copyright (C) 2018-2026 Frédéric France <frederic.france@free.fr>
* Copyright (C) 2020-2021 Udo Tamm <dev@dolibit.de>
* Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
* Copyright (C) 2024 Charlene Benke <charlene@patas-monkey.com>
* Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
* Copyright (C) 2025 Julien Marchand <julien.marchand@iouston.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, orwrite
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/holiday/card.php
* \ingroup holiday
* \brief Form and file creation of paid holiday.
*/
// Load Dolibarr environment
require '../main.inc.php';
/**
* @var Conf $conf
* @var DoliDB $db
* @var ExtraFields $extrafields
* @var HookManager $hookmanager
* @var Translate $langs
* @var User $user
*/
require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/holiday.lib.php';
require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
// Get parameters
$action = GETPOST('action', 'aZ09');
$cancel = GETPOST('cancel', 'alpha');
$confirm = GETPOST('confirm', 'alpha');
$backtopage = GETPOST('backtopage', 'alpha');
$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha');
$id = GETPOSTINT('id');
$ref = GETPOST('ref', 'alpha');
$fuserid = (GETPOSTINT('fuserid') ? GETPOSTINT('fuserid') : ($action == 'create' ? $user->id : 0));
$socid = GETPOSTINT('socid');
// Load translation files required by the page
$langs->loadLangs(array("other", "holiday", "mails", "trips"));
$error = 0;
$errors = [];
$now = dol_now();
$childids = $user->getAllChildIds(1);
$morefilter = '';
if (getDolGlobalString('HOLIDAY_HIDE_FOR_NON_SALARIES')) {
$morefilter = 'AND employee = 1';
}
$object = new Holiday($db);
// fetch optionals attributes and labels
$extrafields->fetch_name_optionals_label($object->table_element);
// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
$hookmanager->initHooks(array('holidaycard', 'globalcard'));
$permissiontoapprove = $user->hasRight('holiday', 'approve');
$canread = 0;
if (($id > 0) || $ref) {
$object->fetch($id, $ref);
// Check current user can read this leave request
if ($user->hasRight('holiday', 'readall')) {
$canread = 1;
}
if ($user->hasRight('holiday', 'read') && in_array($object->fk_user, $childids)) {
$canread = 1;
}
if ($permissiontoapprove && $object->fk_validator == $user->id && !getDolGlobalString('HOLIDAY_CAN_APPROVE_ONLY_THE_SUBORDINATES')) { // TODO HOLIDAY_CAN_APPROVE_ONLY_THE_SUBORDINATES not completely implemented
$canread = 1;
}
if (!$canread) {
accessforbidden();
}
if ($fuserid == 0) {
$fuserid = $object->fk_user; // If $fuserid is not defined, set it to the owner of the leave request
}
}
$permissiontoadd = 0;
$permissiontoaddall = 0;
if ($user->hasRight('holiday', 'write') && in_array($fuserid, $childids)) {
$permissiontoadd = 1;
}
if ($user->hasRight('holiday', 'writeall')) {
$permissiontoadd = 1;
$permissiontoaddall = 1;
}
$permissiontoeditextra = $permissiontoadd;
if (GETPOST('attribute', 'aZ09') && isset($extrafields->attributes[$object->table_element]['perms'][GETPOST('attribute', 'aZ09')])) {
// For action 'update_extras', is there a specific permission set for the attribute to update
$permissiontoeditextra = dol_eval((string) $extrafields->attributes[$object->table_element]['perms'][GETPOST('attribute', 'aZ09')]);
}
$candelete = 0;
if ($user->hasRight('holiday', 'delete')) {
$candelete = 1;
}
if (($object->status == Holiday::STATUS_DRAFT || $object->status == Holiday::STATUS_CANCELED || $object->status == Holiday::STATUS_REFUSED) && $user->hasRight('holiday', 'write') && in_array($object->fk_user, $childids)) {
$candelete = 1;
}
// Protection if external user
if ($user->socid) {
$socid = $user->socid;
}
$result = restrictedArea($user, 'holiday', $object->id, 'holiday', '', '', 'rowid', $object->status);
/*
* Actions
*/
$parameters = array('socid' => $socid);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if (empty($reshook)) {
$backurlforlist = DOL_URL_ROOT.'/holiday/list.php';
if (empty($backtopage) || ($cancel && empty($id))) {
if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
$backtopage = $backurlforlist;
} else {
$backtopage = DOL_URL_ROOT.'/holiday/card.php?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
}
}
}
if ($cancel) {
if (!empty($backtopageforcancel)) {
header("Location: ".$backtopageforcancel);
exit;
} elseif (!empty($backtopage)) {
header("Location: ".$backtopage);
exit;
}
$action = '';
}
// Add leave request
if ($action == 'add' && $permissiontoadd) {
$object = new Holiday($db);
$db->begin();
$date_debut = GETPOSTDATE('date_debut_', '00:00:00');
$date_fin = GETPOSTDATE('date_fin_', '00:00:00');
$date_debut_gmt = GETPOSTDATE('date_debut_', '00:00:00', 1);
$date_fin_gmt = GETPOSTDATE('date_fin_', '00:00:00', 1);
$starthalfday = GETPOST('starthalfday');
$endhalfday = GETPOST('endhalfday');
$type = GETPOSTINT('type');
$halfday = 0;
if ($starthalfday == 'afternoon' && $endhalfday == 'morning') {
$halfday = 2;
} elseif ($starthalfday == 'afternoon') {
$halfday = -1;
} elseif ($endhalfday == 'morning') {
$halfday = 1;
}
$approverid = GETPOSTINT('valideur');
$description = trim(GETPOST('description', 'restricthtml'));
// Check that leave is for a user inside the hierarchy or advanced permission for all is set
if (!$permissiontoaddall) {
if (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
if (!$user->hasRight('holiday', 'write')) {
$error++;
setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
} elseif (!in_array($fuserid, $childids)) {
$error++;
setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
$action = 'create';
}
} else {
if (!$user->hasRight('holiday', 'write') && !$user->hasRight('holiday', 'writeall_advance')) {
$error++;
setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
} elseif (!$user->hasRight('holiday', 'writeall_advance') && !in_array($fuserid, $childids)) {
$error++;
setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
$action = 'create';
}
}
}
// If no type
if ($type <= 0) {
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
$error++;
$action = 'create';
}
// If no start date
if (empty($date_debut)) {
setEventMessages($langs->trans("NoDateDebut"), null, 'errors');
$error++;
$action = 'create';
}
// If no end date
if (empty($date_fin)) {
setEventMessages($langs->trans("NoDateFin"), null, 'errors');
$error++;
$action = 'create';
}
// If start date after end date
if ($date_debut > $date_fin) {
setEventMessages($langs->trans("ErrorEndDateCP"), null, 'errors');
$error++;
$action = 'create';
}
// Check if there is already holiday for this period
$verifCP = $object->verifDateHolidayCP($fuserid, $date_debut, $date_fin, $halfday);
if (!$verifCP) {
setEventMessages($langs->trans("alreadyCPexist"), null, 'errors');
$error++;
$action = 'create';
}
$tmpUser = new User($db);
$tmpUser->fetch($fuserid);
// If there is no Business Days within request
$nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday, $tmpUser->country_id, $tmpUser->id);
if ($nbopenedday < 0.5) {
setEventMessages($langs->trans("ErrorDureeCP"), null, 'errors'); // No working day
$error++;
$action = 'create';
}
// If no validator designated
if ($approverid < 1) {
setEventMessages($langs->transnoentitiesnoconv('InvalidValidatorCP'), null, 'errors');
$error++;
}
$approverslist = $object->fetch_users_approver_holiday();
if (!in_array($approverid, $approverslist)) {
setEventMessages($langs->transnoentitiesnoconv('InvalidValidator'), null, 'errors');
$error++;
}
// Fill array 'array_options' with data from add form
$ret = $extrafields->setOptionalsFromPost(null, $object);
if ($ret < 0) {
$error++;
}
$result = 0;
if (!$error) {
$object->fk_user = $fuserid;
$object->description = $description;
$object->fk_validator = $approverid;
$object->fk_type = $type;
$object->date_debut = $date_debut;
$object->date_fin = $date_fin;
$object->halfday = $halfday;
$object->entity = $conf->entity;
$result = $object->create($user);
if ($result <= 0) {
setEventMessages($object->error, $object->errors, 'errors');
$error++;
}
}
// If no SQL error we redirect to the request card
if (!$error) {
$db->commit();
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
exit;
} else {
$db->rollback();
}
}
// If this is an update and we are an approver, we can update to change the expected approver with another one (including himself)
if ($action == 'update' && GETPOSTISSET('savevalidator') && $permissiontoapprove) {
$object->fetch($id);
$object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
$object->fk_validator = GETPOSTINT('valideur');
if ($object->fk_validator != $object->oldcopy->fk_validator) {
$verif = $object->update($user);
if ($verif <= 0) {
setEventMessages($object->error, $object->errors, 'warnings');
$action = 'editvalidator';
} else {
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
exit;
}
}
$action = '';
}
if ($action == 'update' && !GETPOSTISSET('savevalidator')) { // Test on permission done later
$date_debut = GETPOSTDATE('date_debut_', '00:00:00');
$date_fin = GETPOSTDATE('date_fin_', '00:00:00');
$date_debut_gmt = GETPOSTDATE('date_debut_', '00:00:00', 1);
$date_fin_gmt = GETPOSTDATE('date_fin_', '00:00:00', 1);
$starthalfday = GETPOST('starthalfday');
$endhalfday = GETPOST('endhalfday');
$halfday = 0;
if ($starthalfday == 'afternoon' && $endhalfday == 'morning') {
$halfday = 2;
} elseif ($starthalfday == 'afternoon') {
$halfday = -1;
} elseif ($endhalfday == 'morning') {
$halfday = 1;
}
// If no right to modify a request
if (!$permissiontoaddall) {
if ($permissiontoadd) {
if (!in_array($fuserid, $childids)) {
setEventMessages($langs->trans("UserNotInHierachy"), null, 'errors');
header('Location: '.$_SERVER["PHP_SELF"].'?action=create');
exit;
}
} else {
setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
header('Location: '.$_SERVER["PHP_SELF"].'?action=create');
exit;
}
}
$object->fetch($id);
// If under validation
if ($object->status == Holiday::STATUS_DRAFT) {
// If this is the requester or has read/write rights
if ($permissiontoadd) {
$approverid = GETPOSTINT('valideur');
// TODO Check this approver user id has the permission for approval
$description = trim(GETPOST('description', 'restricthtml'));
// If no end date
if (!GETPOST('date_fin_')) {
setEventMessages($langs->trans('NoDateFin'), null, 'warnings');
$error++;
$action = 'edit';
}
// If start date after end date
if ($date_debut > $date_fin) {
setEventMessages($langs->trans('ErrorEndDateCP'), null, 'warnings');
$error++;
$action = 'edit';
}
// If no validator designated
if ($approverid < 1) {
setEventMessages($langs->trans('InvalidValidatorCP'), null, 'warnings');
$error++;
$action = 'edit';
}
$tmpUser = new User($db);
$tmpUser->fetch($fuserid);
// If there is no Business Days within request
$nbopenedday = num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday, $tmpUser->country_id, $tmpUser->id);
if ($nbopenedday < 0.5) {
setEventMessages($langs->trans('ErrorDureeCP'), null, 'warnings');
$error++;
$action = 'edit';
}
$db->begin();
if (!$error) {
$object->description = $description;
$object->date_debut = $date_debut;
$object->date_fin = $date_fin;
$object->fk_validator = $approverid;
$object->halfday = $halfday;
// Update
$verif = $object->update($user);
if ($verif <= 0) {
setEventMessages($object->error, $object->errors, 'warnings');
$error++;
$action = 'edit';
}
}
if (!$error) {
$db->commit();
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
exit;
} else {
$db->rollback();
}
} else {
setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
$action = '';
}
} else {
setEventMessages($langs->trans("ErrorBadStatus"), null, 'errors');
$action = '';
}
}
// If delete of request
if ($action == 'confirm_delete' && GETPOST('confirm') == 'yes' && $candelete) {
$error = 0;
$db->begin();
$object->fetch($id);
// If this is a rough draft, approved, canceled or refused
if ($object->status == Holiday::STATUS_DRAFT || $object->status == Holiday::STATUS_CANCELED || $object->status == Holiday::STATUS_REFUSED) {
$result = $object->delete($user);
} else {
$error++;
setEventMessages($langs->trans('BadStatusOfObject'), null, 'errors');
$action = '';
}
if (!$error) {
$db->commit();
header('Location: list.php?restore_lastsearch_values=1');
exit;
} else {
$db->rollback();
}
}
// Action validate (+ send email for approval to the expected approver)
if ($action == 'confirm_send') { // Test on permission done later
$object->fetch($id);
// If draft and owner of leave
if ($object->status == Holiday::STATUS_DRAFT && $permissiontoadd) {
$object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
$object->status = Holiday::STATUS_VALIDATED;
$verif = $object->validate($user);
// If no SQL error, we redirect to the request form
if ($verif > 0) {
// To
$destinataire = new User($db);
$destinataire->fetch($object->fk_validator);
$emailTo = $destinataire->email;
if (!$emailTo) {
dol_syslog("Expected validator has no email, so we redirect directly to finished page without sending email");
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
exit;
}
// From
$expediteur = new User($db);
$expediteur->fetch($object->fk_user);
//$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
// You can specify a special address from for holiday
$emailFrom = getDolGlobalString('MAIN_MAIL_EMAIL_HOLIDAY_FROM', getDolGlobalString('MAIN_MAIL_EMAIL_FROM'));
// Subject
$societeName = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
$societeName = getDolGlobalString('MAIN_APPLICATION_TITLE');
}
$subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysToValidate");
// Content
$message = "<p>".$langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",</p>\n";
$message .= "<p>".$langs->transnoentities("HolidaysToValidateBody")."</p>\n";
// option to warn the validator in case of too short delay
if (!getDolGlobalString('HOLIDAY_HIDE_APPROVER_ABOUT_TOO_LOW_DELAY')) {
$delayForRequest = getDolGlobalFloat('HOLIDAY_DELAY_TO_APPROVE_FOR_TYPE_'.$object->fk_type); // Set delay depending of holiday leave type
if ($delayForRequest) {
$nowplusdelay = dol_time_plus_duree($now, $delayForRequest, 'd');
if ($object->date_debut < $nowplusdelay) {
$message = "<p>".$langs->transnoentities("HolidaysToValidateDelay", (string) $delayForRequest)."</p>\n";
}
}
}
// option to notify the validator if the balance is less than the request
// (only for leave types that actually use the balance counter)
if (!getDolGlobalString('HOLIDAY_HIDE_APPROVER_ABOUT_NEGATIVE_BALANCE')) {
$affectingtypes = $object->getTypes(1, 1);
if (!empty($affectingtypes[$object->fk_type])) {
$tmpUser = new User($db);
$tmpUser->fetch($object->fk_user);
$nbopenedday = num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday, $tmpUser->country_id, $object->fk_user);
if ($nbopenedday > $object->getCPforUser($object->fk_user, $object->fk_type)) {
$message .= "<p>".$langs->transnoentities("HolidaysToValidateAlertSolde")."</p>\n";
}
}
}
$typeleaves = $object->getTypes(1, -1);
if (empty($typeleaves[$object->fk_type])) {
$labeltoshow = $langs->trans("TypeWasDisabledOrRemoved", $object->fk_type);
} else {
$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']);
}
if ($object->halfday == 2) {
$starthalfdaykey = "Afternoon";
$endhalfdaykey = "Morning";
} elseif ($object->halfday == -1) {
$starthalfdaykey = "Afternoon";
$endhalfdaykey = "Afternoon";
} elseif ($object->halfday == 1) {
$starthalfdaykey = "Morning";
$endhalfdaykey = "Morning";
} elseif ($object->halfday == 0 || $object->halfday == 2) {
$starthalfdaykey = "Morning";
$endhalfdaykey = "Afternoon";
} else {
$starthalfdaykey = "";
$endhalfdaykey = "";
}
$link = dol_buildpath("/holiday/card.php", 3) . '?id='.$object->id;
$message .= "<ul>";
$message .= "<li>".$langs->transnoentitiesnoconv("Name")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."</li>\n";
$message .= "<li>".$langs->transnoentitiesnoconv("Type")." : ".(empty($labeltoshow) ? $langs->trans("TypeWasDisabledOrRemoved", $object->fk_type) : $labeltoshow)."</li>\n";
$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";
$message .= "<li>".$langs->transnoentitiesnoconv("Link").' : <a href="'.$link.'" target="_blank">'.$link."</a></li>\n";
$message .= "</ul>\n";
$trackid = 'leav'.$object->id;
$sendtobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_HOLIDAY_TO');
$mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', $sendtobcc, 0, 1, '', '', $trackid);
// Sending the email
$result = $mail->sendfile();
if (!$result) {
setEventMessages($mail->error, $mail->errors, 'warnings');
$action = '';
} else {
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
exit;
}
} else {
setEventMessages($object->error, $object->errors, 'errors');
$action = '';
}
}
}
if ($action == 'update_extras' && $permissiontoeditextra) {
$object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
$attribute_name = GETPOST('attribute', 'aZ09');
// Fill array 'array_options' with data from update form
$ret = $extrafields->setOptionalsFromPost(null, $object, $attribute_name);
if ($ret < 0) {
$error++;
}
if (!$error) {
$result = $object->updateExtraField($attribute_name, 'HOLIDAY_MODIFY');
if ($result < 0) {
setEventMessages($object->error, $object->errors, 'errors');
$error++;
}
}
if ($error) {
$action = 'edit_extras';
}
}
// Approve leave request
if ($action == 'confirm_valid' && $permissiontoapprove) {
$object->fetch($id);
// If status is waiting approval and approver is also user
if ($object->status == Holiday::STATUS_VALIDATED && ($user->id == $object->fk_validator || $permissiontoaddall)) {
$object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
$object->date_approval = dol_now();
$object->fk_user_approve = $user->id;
$object->statut = Holiday::STATUS_APPROVED;
$object->status = Holiday::STATUS_APPROVED;
$decrease = getDolGlobalInt('HOLIDAY_DECREASE_AT_END_OF_MONTH');
$db->begin();
$verif = $object->approve($user);
if ($verif <= 0) {
setEventMessages($object->error, $object->errors, 'errors');
$error++;
}
// If no SQL error, we redirect to the request form
if (!$error && empty($decrease)) {
$tmpUser = new User($db);
$tmpUser->fetch($object->fk_user);
// Calculate number of days consumed
$nbopenedday = num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, $object->halfday, $tmpUser->country_id, $object->fk_user);
$soldeActuel = $object->getCpforUser($object->fk_user, $object->fk_type);
$newSolde = ($soldeActuel - $nbopenedday);
$label = $object->ref.' - '.$langs->transnoentitiesnoconv("HolidayConsumption");
// The modification is added to the LOG
$result = $object->addLogCP($user->id, $object->fk_user, $label, $newSolde, $object->fk_type);
if ($result < 0) {
$error++;
setEventMessages(null, $object->errors, 'errors');
}
// Update balance
$result = $object->updateSoldeCP($object->fk_user, $newSolde, $object->fk_type);
if ($result < 0) {
$error++;
setEventMessages(null, $object->errors, 'errors');
}
}
if (!$error) {
// To
$destinataire = new User($db);
$destinataire->fetch($object->fk_user);
$emailTo = $destinataire->email;
if (!$emailTo) {
dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email");
} else {
// From
$expediteur = new User($db);
$expediteur->fetch($object->fk_validator);
//$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
$emailFrom = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
// Subject
$societeName = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
$societeName = getDolGlobalString('MAIN_APPLICATION_TITLE');
}
$subject = '['.$societeName."] ".$langs->transnoentitiesnoconv("HolidaysValidated");
// Content
$message = "<p>".$langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",</p>\n";
$message .= "<p>".$langs->transnoentities("HolidaysValidatedBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."</p>\n";
$link = dol_buildpath('/holiday/card.php', 3).'?id='.$object->id;
$message .= "<ul>\n";
$message .= "<li>".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."</li>\n";
$message .= "<li>".$langs->transnoentitiesnoconv("Link").' : <a href="'.$link.'" target="_blank">'.$link."</a></li>\n";
$message .= "</ul>\n";
$trackid = 'leav'.$object->id;
$sendtobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_HOLIDAY_TO');
$mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', $sendtobcc, 0, 1, '', '', $trackid);
// Sending email
$result = $mail->sendfile();
if (!$result) {
setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1
$action = '';
}
}
}
if (!$error) {
$db->commit();
} else {
$db->rollback();
$action = '';
}
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
exit;
}
}
if ($action == 'confirm_refuse' && GETPOST('confirm', 'alpha') == 'yes' && $permissiontoapprove) { // Test on permission done later
if (GETPOST('detail_refuse')) {
$object->fetch($id);
// If status pending validation and validator = user
if ($object->status == Holiday::STATUS_VALIDATED && ($user->id == $object->fk_validator || $permissiontoaddall)) {
$object->date_refuse = dol_now();
$object->fk_user_refuse = $user->id;
$object->statut = Holiday::STATUS_REFUSED;
$object->status = Holiday::STATUS_REFUSED;
$object->detail_refuse = GETPOST('detail_refuse', 'alphanohtml');
$db->begin();
$verif = $object->update($user);
if ($verif <= 0) {
$error++;
setEventMessages($object->error, $object->errors, 'errors');
}
// If no SQL error, we redirect to the request form
if (!$error) {
// To
$destinataire = new User($db);
$destinataire->fetch($object->fk_user);
$emailTo = $destinataire->email;
if (!$emailTo) {
dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email");
} else {
// From
$expediteur = new User($db);
$expediteur->fetch($object->fk_validator);
//$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
$emailFrom = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
// Subject
$societeName = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
$societeName = getDolGlobalString('MAIN_APPLICATION_TITLE');
}
$subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysRefused");
// Content
$message = "<p>".$langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",</p>\n";
$message .= "<p>".$langs->transnoentities("HolidaysRefusedBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."<p>\n";
$message .= "<p>".GETPOST('detail_refuse', 'alpha')."</p>";
$link = dol_buildpath('/holiday/card.php', 3).'?id='.$object->id;
$message .= "<ul>\n";
$message .= "<li>".$langs->transnoentitiesnoconv("ModifiedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."</li>\n";
$message .= "<li>".$langs->transnoentitiesnoconv("Link").' : <a href="'.$link.'" target="_blank">'.$link."</a></li>\n";
$message .= "</ul>";
$trackid = 'leav'.$object->id;
$sendtobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_HOLIDAY_TO');
$mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', $sendtobcc, 0, 1, '', '', $trackid);
// sending email
$result = $mail->sendfile();
if (!$result) {
setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1
$action = '';
}
}
} else {
$action = '';
}
if (!$error) {
$db->commit();
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
exit;
} else {
$db->rollback();
$action = '';
}
}
} else {
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DetailRefusCP")), null, 'errors');
$action = 'refuse';
}
}
// If the request is validated
if ($action == 'confirm_draft' && GETPOST('confirm') == 'yes' && $permissiontoadd) {
$error = 0;
$object->fetch($id);
$oldstatus = $object->status;
$object->statut = Holiday::STATUS_DRAFT;
$object->status = Holiday::STATUS_DRAFT;
$result = $object->update($user);
if ($result < 0) {
$error++;
setEventMessages($langs->trans('ErrorBackToDraft').' '.$object->error, $object->errors, 'errors');
}
if (!$error) {
$db->commit();
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
exit;
} else {
$db->rollback();
}
}
// If confirmation of cancellation
if ($action == 'confirm_cancel' && GETPOST('confirm') == 'yes') { // Test on permission done later
$error = 0;
$object->fetch($id);
// If status pending validation and validator = validator or user, or rights to do for others
if (($object->status == Holiday::STATUS_VALIDATED || $object->status == Holiday::STATUS_APPROVED) &&
($user->id == $object->fk_validator || $permissiontoadd || $permissiontoaddall || $permissiontoapprove)) {
$db->begin();
$oldstatus = $object->status;
$object->date_cancel = dol_now();
$object->fk_user_cancel = $user->id;
$object->statut = Holiday::STATUS_CANCELED;
$object->status = Holiday::STATUS_CANCELED;
$decrease = getDolGlobalInt('HOLIDAY_DECREASE_AT_END_OF_MONTH');
$result = $object->update($user);
if ($result >= 0 && $oldstatus == Holiday::STATUS_APPROVED) { // holiday was already validated, status 3, so we must increase back the balance
// Call trigger
$result = $object->call_trigger('HOLIDAY_CANCEL', $user);
if ($result < 0) {
$error++;
}
$startDate = $object->date_debut_gmt;
$endDate = $object->date_fin_gmt;
if (!empty($decrease)) {
$lastUpdate = strtotime($object->getConfCP('lastUpdate', dol_print_date(dol_now(), '%Y%m%d%H%M%S')));
$date = strtotime('-1 month', $lastUpdate);
$endOfMonthBeforeLastUpdate = dol_mktime(0, 0, 0, (int) date('m', $date), (int) date('t', $date), (int) date('Y', $date), 1);
if ($object->date_debut_gmt < $endOfMonthBeforeLastUpdate && $object->date_fin_gmt > $endOfMonthBeforeLastUpdate) {
$endDate = $endOfMonthBeforeLastUpdate;
} elseif ($object->date_debut_gmt > $endOfMonthBeforeLastUpdate) {
$endDate = $startDate;
}
}
$tmpUser = new User($db);
$tmpUser->fetch($object->fk_user);
// Calculate number of days consumed
$nbopenedday = num_open_day($startDate, $endDate, 0, 1, $object->halfday, $tmpUser->country_id, $object->fk_user);
$soldeActuel = $object->getCpforUser($object->fk_user, $object->fk_type);
$newSolde = ($soldeActuel + $nbopenedday);
// The modification is added to the LOG
$result1 = $object->addLogCP($user->id, $object->fk_user, $object->ref.' - '.$langs->transnoentitiesnoconv("HolidayCreditAfterCancellation"), $newSolde, $object->fk_type);
// Update of the balance
$result2 = $object->updateSoldeCP($object->fk_user, $newSolde, $object->fk_type);
if ($result1 < 0 || $result2 < 0) {
$error++;
setEventMessages($langs->trans('ErrorCantDeleteCP').' '.$object->error, $object->errors, 'errors');
}
}
if (!$error) {
$db->commit();
} else {
$db->rollback();
}
// If no SQL error, we redirect to the request form
if (!$error && $result > 0) {
// To
$destinataire = new User($db);
$destinataire->fetch($object->fk_user);
$emailTo = $destinataire->email;
if (!$emailTo) {
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
exit;
}
// From
$expediteur = new User($db);
$expediteur->fetch($object->fk_user_cancel);
//$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
$emailFrom = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
// Subject
$societeName = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
$societeName = getDolGlobalString('MAIN_APPLICATION_TITLE');
}
$subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysCanceled");
// Content
$message = "<p>".$langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",</p>\n";
$message .= "<p>".$langs->transnoentities("HolidaysCanceledBody", dol_print_date($object->date_debut, 'day'), dol_print_date($object->date_fin, 'day'))."</p>\n";
$link = dol_buildpath('/holiday/card.php', 3).'?id='.$object->id;
$message .= "<ul>\n";
$message .= "<li>".$langs->transnoentitiesnoconv("ModifiedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."</li>\n";
$message .= "<li>".$langs->transnoentitiesnoconv("Link").' : <a href="'.$link.'" target="_blank">'.$link."</a></li>\n";
$message .= "</ul>\n";
$trackid = 'leav'.$object->id;
$sendtobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_HOLIDAY_TO');
$mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', $sendtobcc, 0, 1, '', '', $trackid);
// sending email
$result = $mail->sendfile();
if (!$result) {
setEventMessages($mail->error, $mail->errors, 'warnings');
$action = '';
} else {
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
exit;
}
}
}
}
/*
// Actions when printing a doc from card
include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
// Actions to send emails
$triggersendname = 'HOLIDAY_SENTBYMAIL';
$autocopy='MAIN_MAIL_AUTOCOPY_HOLIDAY_TO';
$trackid='leav'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
// Actions to build doc
$upload_dir = $conf->holiday->dir_output;
$permissiontoadd = $user->rights->holiday->creer;
include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
*/
}
/*
* View
*/
$form = new Form($db);
$formfile = new FormFile($db);
$object = new Holiday($db);
$listhalfday = array('morning' => $langs->trans("Morning"), "afternoon" => $langs->trans("Afternoon"));
$title = $langs->trans('Leave');
$help_url = 'EN:Module_Holiday';
llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-holiday page-card');
$edit = false;
if ((empty($id) && empty($ref)) || $action == 'create' || $action == 'add') {
// If user has no permission to create a leave
if ((in_array($fuserid, $childids) && !$user->hasRight('holiday', 'write')) || (!in_array($fuserid, $childids) && ((getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('holiday', 'writeall_advance') || !$user->hasRight('holiday', 'writeall'))))) {
$errors[] = $langs->trans('CantCreateCP');
} else {
// Form to add a leave request
print load_fiche_titre($langs->trans('MenuAddCP'), '', 'title_hrm.png');
// Error management
if (GETPOST('error')) {
switch (GETPOST('error')) {
case 'datefin':
$errors[] = $langs->trans('ErrorEndDateCP');
break;
case 'SQL_Create':
$errors[] = $langs->trans('ErrorSQLCreateCP');
break;
case 'CantCreate':
$errors[] = $langs->trans('CantCreateCP');
break;
case 'Valideur':
$errors[] = $langs->trans('InvalidValidatorCP');
break;
case 'nodatedebut':
$errors[] = $langs->trans('NoDateDebut');
break;
case 'nodatefin':
$errors[] = $langs->trans('NoDateFin');
break;
case 'DureeHoliday':
$errors[] = $langs->trans('ErrorDureeCP');
break;
case 'alreadyCP':
$errors[] = $langs->trans('alreadyCPexist');
break;
}
setEventMessages(null, $errors, 'errors');
}
print '<script type="text/javascript">
$( document ).ready(function() {
$("input.button-save").click("submit", function(e) {
console.log("Call valider()");
if (document.demandeCP.date_debut_.value != "")
{
if(document.demandeCP.date_fin_.value != "")
{
if(document.demandeCP.valideur.value != "-1") {
return true;
}
else {
alert("'.dol_escape_js($langs->transnoentities('InvalidValidatorCP')).'");
return false;
}
}
else
{
alert("'.dol_escape_js($langs->transnoentities('NoDateFin')).'");
return false;
}
}
else
{
alert("'.dol_escape_js($langs->transnoentities('NoDateDebut')).'");
return false;
}
});
});
</script>'."\n";
// Leave request form
print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'" name="demandeCP">'."\n";
print '<input type="hidden" name="token" value="'.newToken().'" />'."\n";
print '<input type="hidden" name="action" value="add" />'."\n";
print dol_get_fiche_head();
//print '<span>'.$langs->trans('DelayToRequestCP',$object->getConfCP('delayForRequest')).'</span><br><br>';
print '<table class="border centpercent">';
print '<tbody>';
// User for leave request
print '<tr>';
print '<td class="titlefield fieldrequired tdtop">'.$langs->trans("User").'</td>';
print '<td><div class="inline-block">';
if ($permissiontoadd && !$permissiontoaddall) {
print img_picto('', 'user', 'class="pictofixedwidth"').$form->select_dolusers(($fuserid ? $fuserid : $user->id), 'fuserid', 0, null, 0, 'hierarchyme', '', '0,'.$conf->entity, 0, 0, $morefilter, 0, '', 'minwidth200 maxwidth500 inline-block');
//print '<input type="hidden" name="fuserid" value="'.($fuserid?$fuserid:$user->id).'">';
} else {
print img_picto('', 'user', 'class="pictofixedwidth"').$form->select_dolusers($fuserid ? $fuserid : $user->id, 'fuserid', 0, null, 0, '', '', '0,'.$conf->entity, 0, 0, $morefilter, 0, '', 'minwidth200 maxwidth500 inline-block');
}
print '</div>';
if (!getDolGlobalString('HOLIDAY_HIDE_BALANCE')) {
print '<div class="leaveuserbalance paddingtop inline-block floatright badge badge-status0 badge-status margintoponsmartphone">';
$out = '';
$nb_holiday = 0;
$typeleaves = $object->getTypes(1, 1);
foreach ($typeleaves as $key => $val) {
$nb_type = $object->getCPforUser(($fuserid ? $fuserid : $user->id), $val['rowid']);
$nb_holiday += $nb_type;
$out .= ' - '.($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']).': <strong>'.($nb_type ? price2num($nb_type) : 0).'</strong>';
if ($val['newbymonth'] > 0) {
$out .= ' &nbsp; <span class="opacitymedium">+'.$val['newbymonth'].' / '.$langs->trans("Month").'</span>';
}
$out .= '';
$out .= '<br>';
}
print ' &nbsp; &nbsp; ';
$htmltooltip = $langs->trans("Detail").'<br>';
$htmltooltip .= $out;
print $form->textwithtooltip($langs->trans('SoldeCPUser', (string) round($nb_holiday, 5)).' '.img_picto('', 'help'), $htmltooltip);
print '</div>';
if (!empty($conf->use_javascript_ajax)) {
print '<script>';
print '$( document ).ready(function() {
jQuery("#fuserid").change(function() {
console.log("We change to user id "+jQuery("#fuserid").val());
if (jQuery("#fuserid").val() == '.((int) $user->id).') {
jQuery(".leaveuserbalance").show();
} else {
jQuery(".leaveuserbalance").hide();
}
});
});';
print '</script>';
}
} elseif (!is_numeric(getDolGlobalString('HOLIDAY_HIDE_BALANCE'))) {
print '<div class="leaveuserbalance paddingtop">';
print $langs->trans(getDolGlobalString('HOLIDAY_HIDE_BALANCE'));
print '</div>';
}
print '</td>';
print '</tr>';
// Type
print '<tr>';
print '<td class="fieldrequired">'.$langs->trans("Type").'</td>';
print '<td>';
$typeleaves = $object->getTypes(1, -1);
$arraytypeleaves = array();
foreach ($typeleaves as $key => $val) {
$labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']);
$labeltoshow .= ($val['delay'] > 0 ? ' ('.$langs->trans("NoticePeriod").': '.$val['delay'].' '.$langs->trans("days").')' : '');
$arraytypeleaves[$val['rowid']] = $labeltoshow;
}
if (empty($typeleaves)) {
print $langs->trans("PleaseDefineSomeTypeOfHolidayFirst");
} else {
print $form->selectarray('type', $arraytypeleaves, (GETPOST('type', 'alpha') ? GETPOST('type', 'alpha') : ''), 1, 0, 0, '', 0, 0, 0, '', '', 1);
if ($user->admin) {
print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
}
}
print '</td>';
print '</tr>';
// Date start
print '<tr>';
print '<td class="fieldrequired">';
print $form->textwithpicto($langs->trans("DateDebCP"), $langs->trans("FirstDayOfHoliday"));
print '</td>';
print '<td>'.img_picto('', 'action', 'class="pictofixedwidth"');
if (!GETPOST('date_debut_')) { // If visitor does not come from agenda
print $form->selectDate(-1, 'date_debut_', 0, 0, 0, '', 1, 1);
} else {
$tmpdate = GETPOSTDATE('date_debut_', '00:00:00');
print $form->selectDate($tmpdate, 'date_debut_', 0, 0, 0, '', 1, 1);
}
print ' &nbsp; &nbsp; ';
print $form->selectarray('starthalfday', $listhalfday, (GETPOST('starthalfday', 'alpha') ? GETPOST('starthalfday', 'alpha') : 'morning'));
print '</td>';
print '</tr>';
// Date end
print '<tr>';
print '<td class="fieldrequired">';
print $form->textwithpicto($langs->trans("DateFinCP"), $langs->trans("LastDayOfHoliday"));
print '</td>';
print '<td>'.img_picto('', 'action', 'class="pictofixedwidth"');
if (!GETPOST('date_fin_')) {
print $form->selectDate(-1, 'date_fin_', 0, 0, 0, '', 1, 1);
} else {
$tmpdate = GETPOSTDATE('date_fin_', '00:00:00');
print $form->selectDate($tmpdate, 'date_fin_', 0, 0, 0, '', 1, 1);
}
print ' &nbsp; &nbsp; ';
print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday', 'alpha') ? GETPOST('endhalfday', 'alpha') : 'afternoon'));
print '</td>';
print '</tr>';
// Approver
print '<tr>';
print '<td class="fieldrequired">'.$langs->trans("ReviewedByCP").'</td>';
print '<td>';
$object = new Holiday($db);
$include_users = $object->fetch_users_approver_holiday();
if (empty($include_users)) {
print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateHolidays");
} else {
// Defined default approver (the forced approver of edited user or the supervisor of user if no forced value defined)
// Note: This user will be set only if the defined approver has permission to approve so is inside include_users
$defaultselectuser = (empty($user->fk_user_holiday_validator) ? $user->fk_user : $user->fk_user_holiday_validator);
if ($fuserid != $user->id) {
$fuser = new User($db);
$fuser->fetch($fuserid);
$defaultselectuser = (empty($fuser->fk_user_holiday_validator) ? $fuser->fk_user : $fuser->fk_user_holiday_validator);
}
if (getDolGlobalString('HOLIDAY_DEFAULT_VALIDATOR')) {
$defaultselectuser = getDolGlobalString('HOLIDAY_DEFAULT_VALIDATOR'); // Can force default approver
}
if (GETPOSTINT('valideur') > 0) {
$defaultselectuser = GETPOSTINT('valideur');
}
$s = $form->select_dolusers($defaultselectuser, "valideur", 1, null, 0, $include_users, '', '0,'.$conf->entity, 0, 0, '', 0, '', 'minwidth200 maxwidth500');
print img_picto('', 'user', 'class="pictofixedwidth"').$form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate"));
}
//print $form->select_dolusers((GETPOST('valideur','int')>0?GETPOST('valideur','int'):$user->fk_user), "valideur", 1, ($user->admin ? '' : array($user->id)), 0, '', 0, 0, 0, 0, '', 0, '', '', 1); // By default, hierarchical parent
print '</td>';
print '</tr>';
// Description
print '<tr>';
print '<td>'.$langs->trans("DescCP").'</td>';
print '<td class="tdtop">';
$doleditor = new DolEditor('description', GETPOST('description', 'restricthtml'), '', 80, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor'), ROWS_3, '90%');
print $doleditor->Create(1);
print '</td></tr>';
// Other attributes
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';
print '</tbody>';
print '</table>';
print dol_get_fiche_end();
print $form->buttonsSaveCancel("SendRequestCP");
print '</from>'."\n";
}
} else {
if ($error && $action != 'edit') {
print '<div class="tabBar">';
print '<br><br><input type="button" value="'.$langs->trans("ReturnCP").'" class="button" onclick="history.go(-1)" />';
print '</div>';
} else {
// Show page in view or edit mode
if (($id > 0) || $ref) {
$result = $object->fetch($id, $ref);
$approverexpected = new User($db);
$approverexpected->fetch($object->fk_validator); // Use that should be the approver
$userRequest = new User($db);
$userRequest->fetch($object->fk_user);
//print load_fiche_titre($langs->trans('TitreRequestCP'));
// Si il y a une erreur
if (GETPOST('error')) {
switch (GETPOST('error')) {
case 'datefin':
$errors[] = $langs->transnoentitiesnoconv('ErrorEndDateCP');
break;
case 'SQL_Create':
$errors[] = $langs->transnoentitiesnoconv('ErrorSQLCreateCP');
break;
case 'CantCreate':
$errors[] = $langs->transnoentitiesnoconv('CantCreateCP');
break;
case 'Valideur':
$errors[] = $langs->transnoentitiesnoconv('InvalidValidatorCP');
break;
case 'nodatedebut':
$errors[] = $langs->transnoentitiesnoconv('NoDateDebut');
break;
case 'nodatefin':
$errors[] = $langs->transnoentitiesnoconv('NoDateFin');
break;
case 'DureeHoliday':
$errors[] = $langs->transnoentitiesnoconv('ErrorDureeCP');
break;
case 'NoMotifRefuse':
$errors[] = $langs->transnoentitiesnoconv('NoMotifRefuseCP');
break;
case 'mail':
$errors[] = $langs->transnoentitiesnoconv('ErrorMailNotSend');
break;
}
setEventMessages(null, $errors, 'errors');
}
// check if the user has the right to read this request
if ($canread) {
$head = holiday_prepare_head($object);
$editmode = (($action == 'edit' && $object->status == Holiday::STATUS_DRAFT) || ($action == 'editvalidator'));
if ($editmode) {
if ($action == 'edit' && $object->status == Holiday::STATUS_DRAFT) {
$edit = true;
}
print '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'."\n";
print '<input type="hidden" name="token" value="'.newToken().'" />'."\n";
print '<input type="hidden" name="action" value="update"/>'."\n";
print '<input type="hidden" name="id" value="'.$object->id.'" />'."\n";
}
// No drop area in edit mode: these tabs are printed inside the edit form, and dropping a file
// reloads the page, which would discard what the user is typing.
print dol_get_fiche_head($head, 'card', $langs->trans("CPTitreMenu"), -1, 'holiday', 0, '', '', 0, '', ($editmode ? 0 : 1));
$linkback = '<a href="'.DOL_URL_ROOT.'/holiday/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref');
print '<div class="fichecenter">';
print '<div class="fichehalfleft">';
print '<div class="underbanner clearboth"></div>';
print '<table class="border tableforfield centpercent">';
print '<tbody>';
// User
print '<tr>';
print '<td class="titlefield">'.$langs->trans("User").'</td>';
print '<td>';
print $userRequest->getNomUrl(-1, 'leave');
print '</td></tr>';
// Type
print '<tr>';
print '<td>'.$langs->trans("Type").'</td>';
print '<td>';
$typeleaves = $object->getTypes(1, -1);
if (empty($typeleaves[$object->fk_type])) {
$labeltoshow = $langs->trans("TypeWasDisabledOrRemoved", $object->fk_type);
} else {
$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']);
}
print $labeltoshow;
print '</td>';
print '</tr>';
$starthalfday = ($object->halfday == -1 || $object->halfday == 2) ? 'afternoon' : 'morning';
$endhalfday = ($object->halfday == 1 || $object->halfday == 2) ? 'morning' : 'afternoon';
if (!$edit) {
print '<tr>';
print '<td class="nowrap">';
print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday"));
print '</td>';
print '<td>'.dol_print_date($object->date_debut, 'day');
print ' &nbsp; &nbsp; ';
print '<span class="opacitymedium">'.$langs->trans($listhalfday[$starthalfday]).'</span>';
print '</td>';
print '</tr>';
} else {
print '<tr>';
print '<td class="nowrap">';
print $form->textwithpicto($langs->trans('DateDebCP'), $langs->trans("FirstDayOfHoliday"));
print '</td>';
print '<td>';
$tmpdate = GETPOSTDATE('date_debut_', '00:00:00');
print $form->selectDate($tmpdate ? $tmpdate : $object->date_debut, 'date_debut_');
print ' &nbsp; &nbsp; ';
print $form->selectarray('starthalfday', $listhalfday, (GETPOST('starthalfday') ? GETPOST('starthalfday') : $starthalfday));
print '</td>';
print '</tr>';
}
if (!$edit) {
print '<tr>';
print '<td class="nowrap">';
print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday"));
print '</td>';
print '<td>'.dol_print_date($object->date_fin, 'day');
print ' &nbsp; &nbsp; ';
print '<span class="opacitymedium">'.$langs->trans($listhalfday[$endhalfday]).'</span>';
print '</td>';
print '</tr>';
} else {
print '<tr>';
print '<td class="nowrap">';
print $form->textwithpicto($langs->trans('DateFinCP'), $langs->trans("LastDayOfHoliday"));
print '</td>';
print '<td>';
print $form->selectDate($object->date_fin, 'date_fin_');
print ' &nbsp; &nbsp; ';
print $form->selectarray('endhalfday', $listhalfday, (GETPOST('endhalfday') ? GETPOST('endhalfday') : $endhalfday));
print '</td>';
print '</tr>';
}
// Nb of days
print '<tr>';
print '<td>';
$htmlhelp = $langs->trans('NbUseDaysCPHelp');
$includesaturday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SATURDAY', 1);
$includesunday = getDolGlobalInt('MAIN_NON_WORKING_DAYS_INCLUDE_SUNDAY', 1);
if ($includesaturday) {
$htmlhelp .= '<br>'.$langs->trans("DayIsANonWorkingDay", $langs->trans("Saturday"));
}
if ($includesunday) {
$htmlhelp .= '<br>'.$langs->trans("DayIsANonWorkingDay", $langs->trans("Sunday"));
}
print $form->textwithpicto($langs->trans('NbUseDaysCP'), $htmlhelp);
print '</td>';
print '<td>';
print num_open_day($object->date_debut_gmt, $object->date_fin_gmt, 0, 1, (int) $object->halfday, $userRequest->country_id, $object->fk_user);
print '</td>';
print '</tr>';
if ($object->status == Holiday::STATUS_REFUSED) {
print '<tr>';
print '<td>'.$langs->trans('DetailRefusCP').'</td>';
print '<td>'.$object->detail_refuse.'</td>';
print '</tr>';
}
// Description
if (!$edit) {
print '<tr>';
print '<td>'.$langs->trans('DescCP').'</td>';
print '<td>'.nl2br($object->description).'</td>';
print '</tr>';
} else {
print '<tr>';
print '<td>'.$langs->trans('DescCP').'</td>';
print '<td class="tdtop">';
$doleditor = new DolEditor('description', $object->description, '', 80, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor'), ROWS_3, '90%');
print $doleditor->Create(1);
print '</td></tr>';
}
// Other attributes
include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
print '</tbody>';
print '</table>'."\n";
print '</div>';
print '<div class="fichehalfright">';
print '<div class="underbanner clearboth"></div>';
// Info workflow
print '<table class="border tableforfield centpercent">'."\n";
print '<tbody>';
if (!empty($object->fk_user_create)) {
$userCreate = new User($db);
$userCreate->fetch($object->fk_user_create);
print '<tr>';
print '<td class="titlefield">'.$langs->trans('RequestByCP').'</td>';
print '<td>'.$userCreate->getNomUrl(-1).'</td>';
print '</tr>';
}
// Approver
if (!$edit && $action != 'editvalidator') {
print '<tr>';
print '<td class="titlefield">';
if ($object->status == Holiday::STATUS_APPROVED || $object->status == Holiday::STATUS_CANCELED) {
print $langs->trans('ApprovedBy');
} else {
print $langs->trans('ReviewedByCP');
}
print '</td>';
print '<td>';
if ($object->status == Holiday::STATUS_APPROVED || $object->status == Holiday::STATUS_CANCELED) {
if ($object->fk_user_approve > 0) {
$approverdone = new User($db);
$approverdone->fetch($object->fk_user_approve);
print $approverdone->getNomUrl(-1);
}
} else {
print $approverexpected->getNomUrl(-1);
}
$include_users = $object->fetch_users_approver_holiday();
if (is_array($include_users) && in_array($user->id, $include_users) && $object->status == Holiday::STATUS_VALIDATED) {
print '<a class="editfielda paddingleft" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=editvalidator">'.img_edit($langs->trans("Edit")).'</a>';
}
print '</td>';
print '</tr>';
} else {
print '<tr>';
print '<td class="titlefield">'.$langs->trans('ReviewedByCP').'</td>'; // Will be approved by
print '<td>';
$include_users = $object->fetch_users_approver_holiday();
if (!in_array($object->fk_validator, $include_users)) { // Add the current validator to the list to not lose it when editing.
$include_users[] = $object->fk_validator;
}
if (empty($include_users)) {
print img_warning().' '.$langs->trans("NobodyHasPermissionToValidateHolidays");
} else {
$arrayofvalidatorstoexclude = (($user->admin || ($user->id != $userRequest->id)) ? '' : array($user->id)); // We exclude ourself from validator list. Not if we are admin or if we are on the leave of someone else
$s = $form->select_dolusers($object->fk_validator, "valideur", (($action == 'editvalidator') ? 0 : 1), $arrayofvalidatorstoexclude, 0, $include_users);
print $form->textwithpicto($s, $langs->trans("AnyOtherInThisListCanValidate"));
}
if ($action == 'editvalidator') {
print '<input type="submit" class="button button-save" name="savevalidator" value="'.$langs->trans("Save").'">';
print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
}
print '</td>';
print '</tr>';
}
print '<tr>';
print '<td>'.$langs->trans('DateCreation').'</td>';
print '<td>'.dol_print_date($object->date_create, 'dayhour', 'tzuser').'</td>';
print '</tr>';
if ($object->status == Holiday::STATUS_APPROVED || $object->status == Holiday::STATUS_CANCELED) {
print '<tr>';
print '<td>'.$langs->trans('DateValidCP').'</td>';
print '<td>'.dol_print_date($object->date_approval, 'dayhour', 'tzuser').'</td>'; // warning: date_valid is approval date on holiday module
print '</tr>';
}
if ($object->status == Holiday::STATUS_CANCELED) {
print '<tr>';
print '<td>'.$langs->trans('DateCancelCP').'</td>';
print '<td>'.dol_print_date($object->date_cancel, 'dayhour', 'tzuser').'</td>';
print '</tr>';
}
if ($object->status == Holiday::STATUS_REFUSED) {
print '<tr>';
print '<td>'.$langs->trans('DateRefusCP').'</td>';
print '<td>'.dol_print_date($object->date_refuse, 'dayhour', 'tzuser').'</td>';
print '</tr>';
}
print '</tbody>';
print '</table>';
print '</div>';
print '</div>';
print '<div class="clearboth"></div>';
print dol_get_fiche_end();
// Confirmation messages
if ($action == 'delete') {
if ($candelete) {
print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleDeleteCP"), $langs->trans("ConfirmDeleteCP"), "confirm_delete", '', 0, 1);
}
}
// Si envoi en validation
if ($action == 'sendToValidate' && $object->status == Holiday::STATUS_DRAFT) {
print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleToValidCP"), $langs->trans("ConfirmToValidCP"), "confirm_send", '', 1, 1);
}
// If validating the request
if ($action == 'valid') {
print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleValidCP"), $langs->trans("ConfirmValidCP"), "confirm_valid", '', 1, 1);
}
// If refusing the request
if ($action == 'refuse') {
$array_input = array(array('type' => "text", 'label' => $langs->trans('DetailRefusCP'), 'name' => "detail_refuse", 'size' => "50", 'value' => ""));
print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&action=confirm_refuse", $langs->trans("TitleRefuseCP"), $langs->trans('ConfirmRefuseCP'), "confirm_refuse", $array_input, 1, 0);
}
// If cancelling the request
if ($action == 'cancel') {
print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleCancelCP"), $langs->trans("ConfirmCancelCP"), "confirm_cancel", '', 1, 1);
}
// Si back to draft
if ($action == 'backtodraft') {
print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("TitleSetToDraft"), $langs->trans("ConfirmSetToDraft"), "confirm_draft", '', 1, 1);
}
if (($action == 'edit' && $object->status == Holiday::STATUS_DRAFT) || ($action == 'editvalidator')) {
if ($action == 'edit' && $object->status == Holiday::STATUS_DRAFT) {
if ($permissiontoadd && $object->status == Holiday::STATUS_DRAFT) {
print $form->buttonsSaveCancel();
}
}
print '</form>';
}
if (!$edit) {
// Buttons for actions
print '<div class="tabsAction">';
if ($permissiontoadd && $object->status == Holiday::STATUS_DRAFT) {
print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&token='.newToken().'" class="butAction">'.$langs->trans("EditCP").'</a>';
}
if ($permissiontoadd && $object->status == Holiday::STATUS_DRAFT) { // If draft
print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=sendToValidate&token='.newToken().'" class="butAction">'.$langs->trans("Validate").'</a>';
}
if ($object->status == Holiday::STATUS_VALIDATED) { // If validated
// Button Approve / Refuse
if (($user->id == $object->fk_validator || $permissiontoaddall) && $permissiontoapprove) {
print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=valid&token='.newToken().'" class="butAction">'.$langs->trans("Approve").'</a>';
print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=refuse&token='.newToken().'" class="butAction">'.$langs->trans("ActionRefuseCP").'</a>';
} else {
print '<a href="#" class="butActionRefused classfortooltip" title="'.$langs->trans("NotTheAssignedApprover").'">'.$langs->trans("Approve").'</a>';
print '<a href="#" class="butActionRefused classfortooltip" title="'.$langs->trans("NotTheAssignedApprover").'">'.$langs->trans("ActionRefuseCP").'</a>';
// Button Cancel (because we can't approve)
if ($permissiontoadd || $permissiontoaddall) {
if (($object->date_fin > dol_now()) || !empty($user->admin)) {
print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=cancel&token='.newToken().'" class="butAction">'.$langs->trans("ActionCancelCP").'</a>';
} else {
print '<a href="#" class="butActionRefused classfortooltip" title="'.$langs->trans("HolidayStarted").' - '.$langs->trans("NotAllowed").'">'.$langs->trans("ActionCancelCP").'</a>';
}
}
}
}
if ($object->status == Holiday::STATUS_APPROVED) { // If validated and approved
if ($user->id == $object->fk_validator || $user->id == $object->fk_user_approve || $permissiontoadd || $permissiontoaddall || $permissiontoapprove) {
if ((($object->date_fin > dol_now()) && $permissiontoapprove) || $user->id == $object->fk_user_approve) {
print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=cancel&token='.newToken().'" class="butAction">'.$langs->trans("ActionCancelCP").'</a>';
} else {
if ($object->date_fin <= dol_now() && $permissiontoapprove) {
print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=cancel&token='.newToken().'" class="butAction">'.$langs->trans("ActionCancelCP").'</a>';
} else {
print '<a href="#" class="butActionRefused classfortooltip" title="'.$langs->trans("HolidayStarted").' - '.$langs->trans("NotAllowed").'">'.$langs->trans("ActionCancelCP").'</a>';
}
}
} else { // I have no rights on the user of the holiday.
print '<a href="#" class="butActionRefused classfortooltip" title="'.$langs->trans("NotAllowed").'">'.$langs->trans("ActionCancelCP").'</a>';
}
}
if (($permissiontoadd || $permissiontoaddall) && $object->status == Holiday::STATUS_CANCELED) {
print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=backtodraft" class="butAction">'.$langs->trans("SetToDraft").'</a>';
}
if ($candelete) { // If draft or canceled or refused
print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'" class="butActionDelete">'.$langs->trans("DeleteCP").'</a>';
}
print '</div>';
}
} else {
print '<div class="tabBar">';
print $langs->trans('ErrorUserViewCP');
print '<br><br><input type="button" value="'.$langs->trans("ReturnCP").'" class="button" onclick="history.go(-1)" />';
print '</div>';
}
} else {
print '<div class="tabBar">';
print $langs->trans('ErrorIDFicheCP');
print '<br><br><input type="button" value="'.$langs->trans("ReturnCP").'" class="button" onclick="history.go(-1)" />';
print '</div>';
}
// Select mail models is same action as presend
if (GETPOST('modelselected')) {
$action = 'presend';
}
if ($action != 'presend' && $action != 'edit') {
print '<div class="fichecenter"><div class="fichehalfleft">';
print '<a name="builddoc"></a>'; // ancre
// Documents
/* $includedocgeneration = 0;
if ($includedocgeneration) {
$objref = dol_sanitizeFileName($object->ref);
$relativepath = $objref.'/'.$objref.'.pdf';
$filedir = $conf->holiday->dir_output.'/'.$object->element.'/'.$objref;
$urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
$genallowed = ($user->hasRight('holiday', 'read') && $object->fk_user == $user->id) || $user->hasRight('holiday', 'readall'); // If you can read, you can build the PDF to read content
$delallowed = ($user->hasRight('holiday', 'write') && $object->fk_user == $user->id) || $user->hasRight('holiday', 'writeall_advance'); // If you can create/edit, you can remove a file on card
print $formfile->showdocuments('holiday:Holiday', $object->element.'/'.$objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $langs->defaultlang);
} */
// Show links to link elements
//$tmparray = $form->showLinkToObjectBlock($object, null, array('myobject'), 1);
//$somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
print '</div><div class="fichehalfright">';
$MAXEVENT = 10;
// TODO Add the page holiday_agenda.php
//$morehtmlcenter = dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-bars imgforviewmode', DOL_URL_ROOT.'/holiday/holiday_agenda.php?id='.$object->id);
$morehtmlcenter = '';
// List of actions on element
include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
$formactions = new FormActions($db);
$somethingshown = $formactions->showactions($object, $object->element, (is_object($object->thirdparty) ? $object->thirdparty->id : 0), 1, '', $MAXEVENT, '', $morehtmlcenter);
print '</div></div>';
}
}
}
// End of page
llxFooter();
if (is_object($db)) {
$db->close();
}