dolibarr 24.0.3
card.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2001-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2005 Simon TOSSER <simon@kornog-computing.com>
5 * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
6 * Copyright (C) 2010-2013 Juanjo Menent <jmenent@2byte.es>
7 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
8 * Copyright (C) 2014 Cedric GROSS <c.gross@kreiz-it.fr>
9 * Copyright (C) 2015 Alexandre Spangaro <aspangaro@open-dsi.fr>
10 * Copyright (C) 2018-2026 Frédéric France <frederic.france@free.fr>
11 * Copyright (C) 2019 Ferran Marcet <fmarcet@2byte.es>
12 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
13 *
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 3 of the License, or
17 * (at your option) any later version.
18 *
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <https://www.gnu.org/licenses/>.
26 */
27
34// Load Dolibarr environment
35require '../../main.inc.php';
44require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
45require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
46require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
47require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
48require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php';
49require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
50require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
51require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
52require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncommreminder.class.php';
53require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
54require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
55require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
56require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
57require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
58
59// Load translation files required by the page
60$langs->loadLangs(["companies", "other", "commercial", "bills", "orders", "agenda", "mails"]);
61
62// Get Parameters
63$action = GETPOST('action', 'aZ09');
64$cancel = GETPOST('cancel', 'alpha');
65$backtopage = GETPOST('backtopage', 'alpha');
66$socpeopleassigned = GETPOST('socpeopleassigned', 'array');
67$origin = GETPOST('origin', 'alpha');
68$originid = GETPOSTINT('originid');
69$confirm = GETPOST('confirm', 'alpha');
70
71$fulldayevent = GETPOST('fullday', 'alpha');
72
73$aphour = GETPOSTINT('aphour');
74$apmin = GETPOSTINT('apmin');
75$p2hour = GETPOSTINT('p2hour');
76$p2min = GETPOSTINT('p2min');
77
78$addreminder = GETPOST('addreminder', 'alpha');
79$offsetvalue = GETPOSTINT('offsetvalue');
80$offsetunit = GETPOST('offsetunittype_duration', 'aZ09');
81$remindertype = GETPOST('selectremindertype', 'aZ09');
82$modelmail = GETPOSTINT('actioncommsendmodel_mail');
83$complete = GETPOST('complete', 'alpha'); // 'na' must be allowed
84$private = GETPOST('private', 'alphanohtml');
85if ($complete == 'na' || $complete == -2) {
86 $complete = -1;
87}
88
89$tzforfullday = null;
90if ($fulldayevent) {
91 $tzforfullday = getDolGlobalString('MAIN_STORE_FULL_EVENT_IN_GMT');
92 // For "full day" events, we must store date in GMT (It must be viewed as same moment everywhere)
93 $datep = dol_mktime(0, 0, 0, GETPOSTINT("apmonth"), GETPOSTINT("apday"), GETPOSTINT("apyear"), $tzforfullday ? $tzforfullday : 'tzuserrel');
94 $datef = dol_mktime(23, 59, 59, GETPOSTINT("p2month"), GETPOSTINT("p2day"), GETPOSTINT("p2year"), $tzforfullday ? $tzforfullday : 'tzuserrel');
95 //print $db->idate($datep); exit;
96} else {
97 $datep = dol_mktime($aphour, $apmin, 0, GETPOSTINT("apmonth"), GETPOSTINT("apday"), GETPOSTINT("apyear"), 'tzuserrel');
98 $datef = dol_mktime($p2hour, $p2min, 59, GETPOSTINT("p2month"), GETPOSTINT("p2day"), GETPOSTINT("p2year"), 'tzuserrel');
99}
100$reg = [];
101if (GETPOST('datep')) {
102 if (GETPOST('datep') == 'now') {
103 $datep = dol_now();
104 } elseif (preg_match('/^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})$/', GETPOST("datep"), $reg)) { // YYYYMMDDHHMMSS (dayhourlog) - e.g. from /societe/agenda.php "Add event" button
105 $datep = dol_mktime((int) $reg[4], (int) $reg[5], (int) $reg[6], (int) $reg[2], (int) $reg[3], (int) $reg[1], 'tzuserrel');
106 } elseif (preg_match('/^([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])$/', GETPOST("datep"), $reg)) { // YYYYMMDD - try to not use this. Use instead '&datep=now'
107 $datep = dol_mktime(0, 0, 0, (int) $reg[2], (int) $reg[3], (int) $reg[1], 'tzuserrel');
108 }
109}
110
111$currentyear = (int) dol_print_date(dol_now(), '%Y');
112
113if (GETPOSTISSET("limityear") && GETPOSTINT("limityear") < 2100) {
114 $repeateventlimitdate = dol_mktime(23, 59, 59, GETPOSTISSET("limitmonth") ? GETPOSTINT("limitmonth") : 1, GETPOSTISSET("limitday") ? GETPOSTINT("limitday") : 1, GETPOSTINT("limityear"), $tzforfullday ? $tzforfullday : 'tzuserrel');
115} else {
116 $repeateventlimitdate = dol_mktime(23, 59, 59, 12, 31, $currentyear, $tzforfullday ? $tzforfullday : 'tzuserrel');
117}
118
119// Security check
120$socid = GETPOSTINT('socid');
121if (empty($socid)) {
122 $socid = $user->socid; // External users: fall back to their own company (consistent with other card pages)
123}
124$id = GETPOSTINT('id');
125if ($user->socid && ($socid != $user->socid)) {
127}
128
129$error = GETPOST("error");
130$donotclearsession = GETPOST('donotclearsession') ? GETPOST('donotclearsession') : 0;
131// Per-event session keys to avoid cross-tab assignee bleed (see issue #30326).
132// When two tabs edit different events, both used to share the same flat
133// assignedtouser / assignedtoresource session buckets, so saving one event
134// could overwrite its assignees with the working set from the other tab.
135$sessionkeyassignedtouser = 'assignedtouser_'.($id > 0 ? $id : 'new');
136$sessionkeyassignedtoresource = 'assignedtoresource_'.($id > 0 ? $id : 'new');
137
138// Initialize Objects
139$object = new ActionComm($db);
140$cactioncomm = new CActionComm($db);
141$contact = new Contact($db);
142$formfile = new FormFile($db);
143
144$form = new Form($db);
145$formfile = new FormFile($db);
146$formactions = new FormActions($db);
147
148// Load object
149if ($id > 0 && $action != 'add') {
150 $ret = $object->fetch($id);
151 $ret1 = 0;
152 if ($ret > 0) {
153 $ret = $object->fetch_optionals();
154 $ret1 = $object->fetch_userassigned();
155 }
156 if ($ret < 0 || $ret1 < 0) {
157 dol_print_error(null, $object->error);
158 }
159}
160
161// fetch optionals attributes and labels
162$extrafields->fetch_name_optionals_label($object->table_element);
163
164if (empty($action) && empty($object->id)) {
165 $action = 'create';
166}
167
168// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
169$hookmanager->initHooks(['actioncard', 'globalcard']);
170
171$TRemindTypes = [];
172if (getDolGlobalString('AGENDA_REMINDER_BROWSER')) {
173 $TRemindTypes['browser'] = [
174 'label' => $langs->trans('BrowserPush'),
175 'disabled' => (getDolGlobalString('AGENDA_REMINDER_BROWSER') ? 0 : 1),
176 'type' => ActionCommReminder::TYPE_USER,
177 'data-html' => img_picto('', 'globe', 'class="pictofixedwidth"') . $langs->trans('BrowserPush'),
178 ];
179}
180if (getDolGlobalString('AGENDA_REMINDER_EMAIL')) {
181 $TRemindTypes['email'] = [
182 'label' => $langs->trans('EMail'),
183 'disabled' => (getDolGlobalString('AGENDA_REMINDER_EMAIL') ? 0 : 1),
184 'type' => ActionCommReminder::TYPE_USER,
185 'data-html' => img_picto('', 'email', 'class="pictofixedwidth"') . $langs->trans('EMail'),
186 ];
187}
188if (getDolGlobalString('AGENDA_REMINDER_SMS')) {
189 $langs->load('sms');
190 $TRemindTypes['sms'] = [
191 'label' => $langs->trans('Sms'),
192 'disabled' => (getDolGlobalString('MAIN_SMS_SENDMODE') ? 0 : 1),
193 'type' => ActionCommReminder::TYPE_USER,
194 'data-html' => img_picto('', 'phoning_mobile', 'class="pictofixedwidth"') . $langs->trans('Sms'),
195 ];
196}
197$TDurationTypes = $form->getDurationTypes($langs);
198$TDurationTypesExcluded = ['y', 'm', 's'];
199$enablereminders = getDolGlobalString('AGENDA_REMINDER_EMAIL') || getDolGlobalString('AGENDA_REMINDER_BROWSER') || getDolGlobalString('AGENDA_REMINDER_SMS');
200$parameters = [
201 'socid' => $socid,
202 'TRemindTypes' => &$TRemindTypes,
203 'enablereminders' => &$enablereminders,
204 'TDurationTypes' => &$TDurationTypes,
205 'TDurationTypesExcluded' => &$TDurationTypesExcluded,
206];
207$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
208if ($reshook < 0) {
209 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
210}
211
212$result = restrictedArea($user, 'agenda', $object, 'actioncomm&societe', 'myactions|allactions', 'fk_soc', 'id');
213
214$usercancreate = $user->hasRight('agenda', 'allactions', 'create') || ((empty($object->id) || $object->authorid == $user->id || $object->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'));
215$usercandelete = $user->hasRight('agenda', 'allactions', 'delete') || (($object->authorid === $user->id || $object->userownerid === $user->id) && $user->hasRight('agenda', 'myactions', 'delete'));
216
217
218/*
219 * Actions
220 */
221
222$listUserAssignedUpdated = false;
223$listResourceAssignedUpdated = false;
224$assignedtouser = [];
225
226// Remove user to assigned list
227if (empty($reshook) && (GETPOST('removedassigned') || GETPOST('removedassigned') == '0')) {
228 $idtoremove = GETPOST('removedassigned');
229
230 if (!empty($_SESSION[$sessionkeyassignedtouser])) {
231 $tmpassigneduserids = json_decode($_SESSION[$sessionkeyassignedtouser], true);
232 } else {
233 $tmpassigneduserids = [];
234 }
235
236 foreach ($tmpassigneduserids as $key => $val) {
237 if ($val['id'] == $idtoremove || $val['id'] == -1) {
238 unset($tmpassigneduserids[$key]);
239 }
240 }
241
242 $_SESSION[$sessionkeyassignedtouser] = json_encode($tmpassigneduserids);
243 $donotclearsession = 1;
244 if ($action == 'add') { // Test on permission not required here
245 $action = 'create';
246 }
247 if ($action == 'update') { // Test on permission not required here
248 $action = 'edit';
249 }
250
251 $listUserAssignedUpdated = true;
252}
253// Remove resource to assigned list
254if (empty($reshook) && (GETPOST('removedassignedresource') || GETPOST('removedassignedresource') == '0')) {
255 $idtoremove = GETPOST('removedassignedresource');
256
257 if (!empty($_SESSION[$sessionkeyassignedtoresource])) {
258 $tmpassignedresourceids = json_decode($_SESSION[$sessionkeyassignedtoresource], true);
259 } else {
260 $tmpassignedresourceids = [];
261 }
262
263 foreach ($tmpassignedresourceids as $key => $val) {
264 if ($val['id'] == $idtoremove || $val['id'] == -1) {
265 unset($tmpassignedresourceids[$key]);
266 }
267 }
268
269 $_SESSION[$sessionkeyassignedtoresource] = json_encode($tmpassignedresourceids);
270
271 if ($action == 'add' && $usercancreate) {
272 $action = 'create';
273 }
274 if ($action == 'update' && $usercancreate) {
275 $action = 'edit';
276 }
277
278 $listResourceAssignedUpdated = true;
279}
280
281// Add user to assigned list
282if (empty($reshook) && (GETPOST('addassignedtouser') || GETPOST('updateassignedtouser'))) {
283 // Add a new user
284 if (GETPOST('assignedtouser') > 0) {
285 $assignedtouser = [];
286 if (!empty($_SESSION[$sessionkeyassignedtouser])) {
287 $assignedtouser = json_decode($_SESSION[$sessionkeyassignedtouser], true);
288 }
289 $assignedtouser[GETPOST('assignedtouser')] = array('id' => GETPOSTINT('assignedtouser'), 'transparency' => GETPOST('transparency'), 'mandatory' => 1);
290 $_SESSION[$sessionkeyassignedtouser] = json_encode($assignedtouser);
291 }
292 $donotclearsession = 1;
293 if ($action == 'add' && $usercancreate) {
294 $action = 'create';
295 }
296 if ($action == 'update' && $usercancreate) {
297 $action = 'edit';
298 }
299
300 $listUserAssignedUpdated = true;
301}
302
303// Add resource to assigned list
304if (empty($reshook) && (GETPOST('addassignedtoresource') || GETPOST('updateassignedtoresource'))) {
305 // Add a new user
306 if (GETPOST('assignedtoresource') > 0) {
307 $assignedtoresource = [];
308 if (!empty($_SESSION[$sessionkeyassignedtoresource])) {
309 $assignedtoresource = json_decode($_SESSION[$sessionkeyassignedtoresource], true);
310 }
311 $assignedtoresource[GETPOST('assignedtoresource')] = array('id' => GETPOSTINT('assignedtoresource'), 'transparency' => GETPOST('transparency'), 'mandatory' => 1);
312 $_SESSION[$sessionkeyassignedtoresource] = json_encode($assignedtoresource);
313 }
314 $donotclearsession = 1;
315 if ($action == 'add' && $usercancreate) {
316 $action = 'create';
317 }
318 if ($action == 'update' && $usercancreate) {
319 $action = 'edit';
320 }
321
322 $listResourceAssignedUpdated = true;
323}
324
325// Link to a project
326if (empty($reshook) && $action == 'classin' && ($user->hasRight('agenda', 'allactions', 'create') ||
327 (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create')))) {
328 //$object->fetch($id);
329 $object->setProject(GETPOSTINT('projectid'));
330}
331
332// Action clone object
333if (empty($reshook) && $action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) {
334 // @phan-suppress-next-line PhanPluginBothLiteralsBinaryOp
335 if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) {
336 setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
337 } else {
338 if ($id > 0) {
339 //$object->fetch($id);
340 if (!empty($object->socpeopleassigned)) {
341 reset($object->socpeopleassigned);
342 $object->contact_id = (int) key($object->socpeopleassigned);
343 }
344 $result = $object->createFromClone($user, GETPOSTINT('socid'));
345 if ($result > 0) {
346 header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
347 exit();
348 } else {
349 setEventMessages($object->error, $object->errors, 'errors');
350 $action = '';
351 }
352 }
353 }
354}
355
356// Add event
357if (empty($reshook) && $action == 'add' && $usercancreate) {
358 $error = 0;
359
360 if (empty($backtopage)) {
361 if ($socid > 0) {
362 $backtopage = DOL_URL_ROOT.'/societe/agenda.php?socid='.$socid;
363 } else {
364 $backtopage = DOL_URL_ROOT.'/comm/action/index.php';
365 }
366 }
367
368 if (!empty($socpeopleassigned[0])) {
369 $result = $contact->fetch($socpeopleassigned[0]);
370 }
371
372 if ($cancel) {
373 header("Location: ".$backtopage);
374 exit;
375 }
376
377 $percentage = in_array(GETPOST('status'), array(-1, 100)) ? GETPOST('status') : (in_array($complete, array(-1, 100)) ? $complete : GETPOSTINT("percentage")); // If status is -1 or 100, percentage is not defined and we must use status
378
379 // Clean parameters
380 if ($fulldayevent) {
381 $tzforfullday = getDolGlobalString('MAIN_STORE_FULL_EVENT_IN_GMT');
382 // For "full day" events, we must store date in GMT (It must be viewed as same moment everywhere)
383 $datep = dol_mktime(0, 0, 0, GETPOSTINT("apmonth"), GETPOSTINT("apday"), GETPOSTINT("apyear"), $tzforfullday ? $tzforfullday : 'tzuserrel');
384 $datef = dol_mktime(23, 59, 59, GETPOSTINT("p2month"), GETPOSTINT("p2day"), GETPOSTINT("p2year"), $tzforfullday ? $tzforfullday : 'tzuserrel');
385 } else {
386 $datep = dol_mktime(GETPOSTINT("aphour"), GETPOSTINT("apmin"), GETPOSTINT("apsec"), GETPOSTINT("apmonth"), GETPOSTINT("apday"), GETPOSTINT("apyear"), 'tzuserrel');
387 $datef = dol_mktime(GETPOSTINT("p2hour"), GETPOSTINT("p2min"), GETPOSTINT("apsec"), GETPOSTINT("p2month"), GETPOSTINT("p2day"), GETPOSTINT("p2year"), 'tzuserrel');
388 }
389 //set end date to now if percentage is set to 100 and end date not set
390 $datef = (!$datef && $percentage == 100) ? dol_now() : $datef;
391
392 // Check parameters
393 if (!$datef && $percentage == 100) {
394 $error++;
395 $donotclearsession = 1;
396 $action = 'create';
397 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors');
398 }
399
400 if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') && !GETPOST('label')) {
401 $error++;
402 $donotclearsession = 1;
403 $action = 'create';
404 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors');
405 }
406
407 // Initialisation object cactioncomm
408 if (GETPOSTISSET('actioncode') && !GETPOST('actioncode', 'aZ09')) { // actioncode is '0'
409 $error++;
410 $donotclearsession = 1;
411 $action = 'create';
412 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
413 } else {
414 $object->type_code = GETPOST('actioncode', 'aZ09');
415 }
416
417 $listofresourceid = [];
418
419 if (!$error) {
420 // Initialisation of object actioncomm
421 $object->priority = GETPOSTISSET("priority") ? GETPOSTINT("priority") : 0;
422 $object->fulldayevent = ($fulldayevent ? 1 : 0);
423 $object->location = GETPOST("location", 'alphanohtml');
424 $object->label = GETPOST('label', 'alphanohtml');
425
426 if (GETPOST("elementtype", 'alpha')) {
427 $elProp = getElementProperties(GETPOST("elementtype", 'alpha'));
428 $modulecodetouseforpermissioncheck = $elProp['module'];
429 // Keep permission check aligned with rights class aliases (see restrictedArea()).
430 $submodulecodetouseforpermissioncheck = $elProp['subelement'];
431
432 switch ($modulecodetouseforpermissioncheck) {
433 case 'productbatch':
434 $modulecodetouseforpermissioncheck = 'produit';
435 break;
436 case 'eventorganization':
437 // Event organization relies on Project permissions
438 $modulecodetouseforpermissioncheck = 'projet';
439 $submodulecodetouseforpermissioncheck = ''; // Project doesn't use submodules for read
440 break;
441 default:
442 // No mapping needed, keep original values
443 break;
444 }
445
446 $hasPermissionOnLinkedObject = 0;
447 if ($user->hasRight($modulecodetouseforpermissioncheck, 'read')) {
448 $hasPermissionOnLinkedObject = 1;
449 } elseif ($user->hasRight($modulecodetouseforpermissioncheck, $submodulecodetouseforpermissioncheck, 'read')) {
450 $hasPermissionOnLinkedObject = 1;
451 }
452
453 if ($hasPermissionOnLinkedObject) {
454 $object->fk_element = GETPOSTINT("fk_element");
455 $object->elementid = GETPOSTINT("fk_element");
456 $object->elementtype = GETPOST("elementtype", 'alpha');
457 }
458 }
459
460 if (!GETPOST('label')) {
461 if (GETPOST('actioncode', 'aZ09') == 'AC_RDV' && $contact->getFullName($langs)) {
462 $object->label = $langs->transnoentitiesnoconv("TaskRDVWith", $contact->getFullName($langs));
463 } else {
464 if ($langs->trans("Action".$object->type_code) != "Action".$object->type_code) {
465 $object->label = $langs->transnoentitiesnoconv("Action".$object->type_code)."\n";
466 } else {
467 $cactioncomm->fetch($object->type_code);
468 $object->label = $cactioncomm->label;
469 }
470 }
471 }
472 $object->fk_project = GETPOSTISSET("projectid") ? GETPOSTINT("projectid") : 0;
473
474 $taskid = GETPOSTINT('taskid');
475 if (!empty($taskid)) {
476 $taskProject = new Task($db);
477 if ($taskProject->fetch($taskid) > 0) {
478 $object->fk_project = $taskProject->fk_project;
479 }
480
481 $object->fk_element = $taskid;
482 $object->elementid = $taskid;
483 $object->elementtype = 'project_task';
484 }
485
486 $object->datep = $datep;
487 $object->datef = $datef;
488 $object->percentage = $percentage;
489 $object->duree = (((int) GETPOST('dureehour') * 60) + (int) GETPOST('dureemin')) * 60;
490
491 $transparency = (GETPOST("transparency") == 'on' ? 1 : 0);
492
493 $listofuserid = [];
494 if (!empty($_SESSION[$sessionkeyassignedtouser])) {
495 $listofuserid = json_decode($_SESSION[$sessionkeyassignedtouser], true);
496 }
497
498 if (!empty($_SESSION[$sessionkeyassignedtoresource])) {
499 $listofresourceid = json_decode($_SESSION[$sessionkeyassignedtoresource], true);
500 }
501
502 $i = 0;
503 foreach ($listofuserid as $key => $value) {
504 if ($i == 0) { // First entry
505 if ($value['id'] > 0) {
506 $object->userownerid = $value['id'];
507 }
508 $object->transparency = $transparency;
509 }
510
511 $object->userassigned[$value['id']] = array('id' => $value['id'], 'transparency' => $transparency);
512
513 $i++;
514 }
515 }
516
517 $object->note_private = trim(GETPOST("note", "restricthtml"));
518
519 if (GETPOSTISSET("contactid")) {
520 $object->contact_id = GETPOSTINT("contactid");
521 $object->fetch_contact();
522 }
523
524 if (GETPOSTINT('socid') > 0) {
525 $object->socid = GETPOSTINT('socid');
526 $object->fetch_thirdparty();
527 }
528
529 // Check parameters
530 if (empty($object->userownerid) && empty($_SESSION[$sessionkeyassignedtouser])) {
531 $error++;
532 $donotclearsession = 1;
533 $action = 'create';
534 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ActionsOwnedBy")), null, 'errors');
535 }
536 if ($object->type_code == 'AC_RDV' && ($datep == '' || ($datef == '' && empty($fulldayevent)))) {
537 $error++;
538 $donotclearsession = 1;
539 $action = 'create';
540 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors');
541 }
542
543 if (!GETPOST('apyear') && !GETPOST('adyear')) {
544 $error++;
545 $donotclearsession = 1;
546 $action = 'create';
547 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
548 }
549
550 foreach ($socpeopleassigned as $cid) {
551 $object->socpeopleassigned[$cid] = array('id' => $cid);
552 }
553 if (!empty($object->socpeopleassigned)) {
554 reset($object->socpeopleassigned);
555 $object->contact_id = key($object->socpeopleassigned);
556 }
557
558 // Fill array 'array_options' with data from add form
559 $ret = $extrafields->setOptionalsFromPost(null, $object);
560 if ($ret < 0) {
561 $error++;
562 $donotclearsession = 1;
563 $action = 'create';
564 }
565
566
567 if (!$error) {
568 $db->begin();
569
570 $dayinyear = dol_print_date($object->datep, '%m%d');
571 $dayinmonth = dol_print_date($object->datep, '%d');
572 $dayinweek = dol_print_date($object->datep, '%w');
573
574 $selectedrecurrulefreq = 'no';
575 $selectedrecurrulebyyearmonthday = '';
576 $selectedrecurrulebymonthday = '';
577 $selectedrecurrulebyday = '';
578 $object->recurrule = GETPOSTISSET('recurrulefreq') ? "FREQ=".GETPOST('recurrulefreq', 'alpha') : "";
579 $object->recurrule .= (GETPOST('recurrulefreq', 'alpha') == 'YEARLY') ? "_BYYEARMONTHDAY".((int) $dayinyear) : "";
580 $object->recurrule .= (GETPOST('recurrulefreq', 'alpha') == 'MONTHLY') ? "_BYMONTHDAY".((int) $dayinmonth) : "";
581 $object->recurrule .= (GETPOST('recurrulefreq', 'alpha') == 'WEEKLY') ? "_BYDAY".((int) $dayinweek) : "";
582
583 $reg1 = [];
584 $reg2 = [];
585 $reg3 = [];
586 $reg4 = [];
587 if ($object->recurrule && preg_match('/FREQ=([A-Z]+)/i', $object->recurrule, $reg1)) {
588 $selectedrecurrulefreq = $reg1[1];
589 }
590 if ($object->recurrule && preg_match('/FREQ=YEARLY.*BYYEARMONTHDAY(\d+)/i', $object->recurrule, $reg4)) {
591 $selectedrecurrulebyyearmonthday = (int) $reg4[1];
592 }
593 if ($object->recurrule && preg_match('/FREQ=MONTHLY.*BYMONTHDAY(\d+)/i', $object->recurrule, $reg2)) {
594 $selectedrecurrulebymonthday = (int) $reg2[1];
595 }
596 if ($object->recurrule && preg_match('/FREQ=WEEKLY.*BYDAY(\d+)/i', $object->recurrule, $reg3)) {
597 $selectedrecurrulebyday = (int) $reg3[1];
598 }
599
600 // Is event recurrent ?
601 $eventisrecurring = 0;
602 $userepeatevent = (getDolGlobalInt('MAIN_DISABLE_RECURRING_EVENTS') ? 0 : 1);
603 if ($userepeatevent && !empty($selectedrecurrulefreq) && $selectedrecurrulefreq != 'no') {
604 $eventisrecurring = 1;
605 $object->recurid = dol_print_date(dol_now('gmt'), 'dayhourlog', 'gmt');
606 $object->recurdateend = dol_mktime(0, 0, 0, GETPOSTINT('limitmonth'), GETPOSTINT('limitday'), GETPOSTINT('limityear'));
607 } else {
608 unset($object->recurid);
609 unset($object->recurrule);
610 unset($object->recurdateend);
611 }
612
613 // Creation of action/event
614 $idaction = $object->create($user);
615 $moreparam = '';
616
617 if ($idaction > 0) {
618 if (!$object->error) {
619 if (is_array($listofresourceid) && count($listofresourceid)) {
620 foreach ($listofresourceid as $resource_id => $val) {
621 $resource_type = 'dolresource';
622 $busy = 1;//GETPOSTINT('busy');
623
624 // Resources association
625 if (getDolGlobalString('RESOURCE_USED_IN_EVENT_CHECK')) {
626 $eventDateStart = $object->datep;
627 $eventDateEnd = $object->datef;
628 $isFullDayEvent = $object->fulldayevent;
629 if (empty($eventDateEnd)) {
630 if ($isFullDayEvent) {
631 $eventDateStartArr = dol_getdate($eventDateStart);
632 $eventDateStart = dol_mktime(0, 0, 0, $eventDateStartArr['mon'], $eventDateStartArr['mday'], $eventDateStartArr['year']);
633 $eventDateEnd = dol_mktime(23, 59, 59, $eventDateStartArr['mon'], $eventDateStartArr['mday'], $eventDateStartArr['year']);
634 }
635 }
636
637 $sql = "SELECT er.rowid, r.ref as r_ref, ac.id as ac_id, ac.label as ac_label";
638 $sql .= " FROM " . MAIN_DB_PREFIX . "element_resources as er";
639 $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "resource as r ON r.rowid = er.resource_id AND er.resource_type = '" . $db->escape($resource_type) . "'";
640 $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "actioncomm as ac ON ac.id = er.element_id AND er.element_type = '" . $db->escape($object->element) . "'";
641 $sql .= " WHERE er.resource_id = " . ((int) $resource_id);
642 $sql .= " AND er.busy = 1";
643 $sql .= " AND (";
644
645 // event date start between ac.datep and ac.datep2 (if datep2 is null we consider there is no end)
646 $sql .= " (ac.datep <= '" . $db->idate($eventDateStart) . "' AND (ac.datep2 IS NULL OR ac.datep2 >= '" . $db->idate($eventDateStart) . "'))";
647 // event date end between ac.datep and ac.datep2
648 if (!empty($eventDateEnd)) {
649 $sql .= " OR (ac.datep <= '" . $db->idate($eventDateEnd) . "' AND (ac.datep2 >= '" . $db->idate($eventDateEnd) . "'))";
650 }
651 // event date start before ac.datep and event date end after ac.datep2
652 $sql .= " OR (";
653 $sql .= "ac.datep >= '" . $db->idate($eventDateStart) . "'";
654 if (!empty($eventDateEnd)) {
655 $sql .= " AND (ac.datep2 IS NOT NULL AND ac.datep2 <= '" . $db->idate($eventDateEnd) . "')";
656 }
657 $sql .= ")";
658
659 $sql .= ")";
660 $resql = $db->query($sql);
661 if (!$resql) {
662 $error++;
663 $object->error = $db->lasterror();
664 $object->errors[] = $object->error;
665 } else {
666 if ($db->num_rows($resql) > 0) {
667 // Resource already in use
668 $error++;
669 $object->error = $langs->trans('ErrorResourcesAlreadyInUse') . ' : ';
670 while ($obj = $db->fetch_object($resql)) {
671 $object->error .= '<br> - ' . $langs->trans('ErrorResourceUseInEvent', $obj->r_ref, $obj->ac_label . ' [' . $obj->ac_id . ']');
672 }
673 $object->errors[] = $object->error;
674
675 setEventMessages($object->error, null, 'errors');
676 }
677 $db->free($resql);
678 }
679 }
680
681 if (!$error) {
682 $res = $object->add_element_resource($resource_id, $resource_type, $busy, $val['mandatory']);
683 }
684 }
685 }
686
687 unset($_SESSION[$sessionkeyassignedtoresource]);
688
689
690 // Category association
691 if (!$error) {
692 $categories = GETPOST('categories', 'array');
693 $object->setCategories($categories);
694 }
695
696 unset($_SESSION[$sessionkeyassignedtouser]);
697
698 if ($user->id != $object->userownerid) {
699 $moreparam = "filtert=-1"; // We force to remove filter so created record is visible when going back to per user view.
700 }
701
702 // Create reminders
703 if (!$error && $addreminder == 'on') {
704 $actionCommReminder = new ActionCommReminder($db);
705
706 $dateremind = dol_time_plus_duree($datep, -1 * $offsetvalue, $offsetunit);
707
708 $actionCommReminder->dateremind = $dateremind;
709 $actionCommReminder->typeremind = $remindertype;
710 $actionCommReminder->offsetunit = $offsetunit;
711 $actionCommReminder->offsetvalue = $offsetvalue;
712 $actionCommReminder->status = $actionCommReminder::STATUS_TODO;
713 $actionCommReminder->fk_actioncomm = $object->id;
714 if ($remindertype == 'email') {
715 $actionCommReminder->fk_email_template = $modelmail;
716 }
717
718 // the notification must be created for every user assigned to the event
719 foreach ($object->userassigned as $userassigned) {
720 $actionCommReminder->fk_user = $userassigned['id'];
721 $res = $actionCommReminder->create($user);
722
723 if ($res <= 0) {
724 // If error
725 $langs->load("errors");
726 $error++;
727 setEventMessages($langs->trans('ErrorReminderActionCommCreation'), null, 'errors');
728 $action = 'create';
729 $donotclearsession = 1;
730 break;
731 }
732 }
733 }
734
735 // Modify $moreparam so we are sure to see the event we have just created, whatever are the default value of filter on next page.
736 /*$moreparam .= ($moreparam ? '&' : '').'search_actioncode=0';
737 $moreparam .= ($moreparam ? '&' : '').'search_status=-1';
738 $moreparam .= ($moreparam ? '&' : '').'search_filtert='.$object->userownerid;
739 */
740 $moreparam .= ($moreparam ? '&' : '').'disabledefaultvalues=1';
741
742 // if (!empty($backtopage)) {
743 // dol_syslog("Back to ".$backtopage.($moreparam ? (preg_match('/\?/', $backtopage) ? '&'.$moreparam : '?'.$moreparam) : ''));
744 // header("Location: ".$backtopage.($moreparam ? (preg_match('/\?/', $backtopage) ? '&'.$moreparam : '?'.$moreparam) : ''));
745 // } elseif ($idaction) {
746 // header("Location: ".DOL_URL_ROOT.'/comm/action/card.php?id='.$idaction.($moreparam ? '&'.$moreparam : ''));
747 // } else {
748 // header("Location: ".DOL_URL_ROOT.'/comm/action/index.php'.($moreparam ? '?'.$moreparam : ''));
749 // }
750 // exit;
751 } else {
752 // If error
753 $langs->load("errors");
754 $error++;
755 setEventMessages($langs->trans($object->error), null, 'errors');
756 $action = 'create';
757 $donotclearsession = 1;
758 }
759 } else {
760 $error++;
761 setEventMessages($object->error, $object->errors, 'errors');
762 $action = 'create';
763 $donotclearsession = 1;
764 }
765
766 // Manage other events in case of recurring event
767 if (!$error && $eventisrecurring) {
768 $dayoffset = 0;
769 $monthoffset = 0;
770 $yearoffset = 0;
771 // Timezone in which days, months and years are added to build the next occurrences. It must be the
772 // same as the one used by the dol_mktime() calls below. Without it, dol_time_plus_duree() adds the
773 // delay in UTC, so it keeps the elapsed time instead of the wall clock and a series that crosses a
774 // daylight saving time change is shifted by one hour (a weekly 9:00 event becomes 8:00).
775 $tzforrecurrence = 'tzserver';
776 if ($tzforfullday) { // Full day events are stored in GMT, so adding the delay in GMT is correct
777 $tzforrecurrence = 'gmt';
778 } elseif (!empty($_SESSION['dol_tz_string'])) {
779 try {
780 $tmptz = new DateTimeZone($_SESSION['dol_tz_string']);
781 $tzforrecurrence = $tmptz->getName();
782 } catch (Exception $e) { // Fall back on the timezone of the server, like dol_mktime() does
783 dol_syslog("Warning dol_tz_string contains an invalid value ".json_encode($_SESSION['dol_tz_string']), LOG_WARNING);
784 $tzforrecurrence = 'tzserver';
785 }
786 }
787 // We set first date of recurrence and offsets
788 if ($selectedrecurrulefreq == 'WEEKLY' && !empty($selectedrecurrulebyday)) {
789 $firstdatearray = dol_get_first_day_week(GETPOSTINT("apday"), GETPOSTINT("apmonth"), GETPOSTINT("apyear"));
790 $datep = dol_mktime($fulldayevent ? 0 : GETPOSTINT("aphour"), $fulldayevent ? 0 : GETPOSTINT("apmin"), $fulldayevent ? 0 : GETPOSTINT("apsec"), $firstdatearray['month'], $firstdatearray['first_day'], $firstdatearray['year'], $tzforfullday ? $tzforfullday : 'tzuserrel');
791 $datep = dol_time_plus_duree($datep, $selectedrecurrulebyday + 6, 'd', 0, $tzforrecurrence);//We begin the week after
792 $dayoffset = 7;
793 $monthoffset = 0;
794 $yearoffset = 0;
795 } elseif ($selectedrecurrulefreq == 'MONTHLY' && !empty($selectedrecurrulebymonthday)) {
796 $firstday = $selectedrecurrulebymonthday;
797 $firstmonth = GETPOST("apday") > $selectedrecurrulebymonthday ? GETPOSTINT("apmonth") + 1 : GETPOSTINT("apmonth");//We begin the month after
798 $datep = dol_mktime($fulldayevent ? 0 : GETPOSTINT("aphour"), $fulldayevent ? 0 : GETPOSTINT("apmin"), $fulldayevent ? 0 : GETPOSTINT("apsec"), $firstmonth, $firstday, GETPOSTINT("apyear"), $tzforfullday ? $tzforfullday : 'tzuserrel');
799 $datep = dol_time_plus_duree($datep, 1, 'm', 0, $tzforrecurrence);//We begin the month after
800 $dayoffset = 0;
801 $monthoffset = 1;
802 $yearoffset = 0;
803 } elseif ($selectedrecurrulefreq == 'YEARLY' && !empty($selectedrecurrulebyyearmonthday)) {
804 $datep = dol_mktime($fulldayevent ? 0 : GETPOSTINT("aphour"), $fulldayevent ? 0 : GETPOSTINT("apmin"), $fulldayevent ? 0 : GETPOSTINT("apsec"), GETPOSTINT("apmonth"), GETPOSTINT("apday"), GETPOSTINT("apyear"), $tzforfullday ? $tzforfullday : 'tzuserrel');
805 $datep = dol_time_plus_duree($datep, 1, 'y', 0, $tzforrecurrence);//We begin the year after
806 $dayoffset = 0;
807 $monthoffset = 0;
808 $yearoffset = 1;
809 } else {
810 $error++;
811 }
812 // End date
813 // Set date of end of event. The delay is added in the same timezone as the start date, so the
814 // wall clock of the end date is kept too. But when the start date falls into an hour that does
815 // not exist (spring forward), it is moved forward and may end up after the end date, so in that
816 // case only we rebuild the end date from the duration of the submitted event.
817 $durationofevent = (strval($datef) != '' && strval($object->datep) != '') ? ((int) $datef - (int) $object->datep) : 0;
818 $deltatime = num_between_day($object->datep, $datep);
819 // @phan-suppress-next-line PhanPluginSuspiciousParamOrder
820 $datef = dol_time_plus_duree($datef, $deltatime, 'd', 0, $tzforrecurrence);
821 if ($durationofevent > 0 && $datef <= $datep) {
822 $datef = $datep + $durationofevent;
823 }
824
825 while ($datep <= $repeateventlimitdate && !$error) {
826 $finalobject = clone $object;
827
828
829 $finalobject->datep = $datep;
830 $finalobject->datef = $datef;
831 // Creation of action/event
832 $idaction = $finalobject->create($user);
833
834 if ($idaction > 0) {
835 if (!$finalobject->error) {
836 // Category association
837 $categories = GETPOST('categories', 'array');
838 $finalobject->setCategories($categories);
839
840 unset($_SESSION[$sessionkeyassignedtouser]);
841
842 $moreparam = '';
843 if ($user->id != $finalobject->userownerid) {
844 $moreparam = "filtert=-1"; // We force to remove filter so created record is visible when going back to per user view.
845 }
846
847 // Create reminders
848 if ($addreminder == 'on') {
849 $actionCommReminder = new ActionCommReminder($db);
850
851 $dateremind = dol_time_plus_duree($datep, -1 * $offsetvalue, $offsetunit);
852
853 $actionCommReminder->dateremind = $dateremind;
854 $actionCommReminder->typeremind = $remindertype;
855 $actionCommReminder->offsetunit = $offsetunit;
856 $actionCommReminder->offsetvalue = $offsetvalue;
857 $actionCommReminder->status = $actionCommReminder::STATUS_TODO;
858 $actionCommReminder->fk_actioncomm = $finalobject->id;
859 if ($remindertype == 'email') {
860 $actionCommReminder->fk_email_template = $modelmail;
861 }
862
863 // the notification must be created for every user assigned to the event
864 foreach ($finalobject->userassigned as $userassigned) {
865 $actionCommReminder->fk_user = $userassigned['id'];
866 $res = $actionCommReminder->create($user);
867
868 if ($res <= 0) {
869 // If error
870 $error++;
871 $langs->load("errors");
872 setEventMessages($langs->trans('ErrorReminderActionCommCreation'), null, 'errors');
873 $action = 'create';
874 $donotclearsession = 1;
875 break;
876 }
877 }
878 }
879
880 // Modify $moreparam so we are sure to see the event we have just created, whatever are the default value of filter on next page.
881 /*$moreparam .= ($moreparam ? '&' : '').'search_actioncode=0';
882 $moreparam .= ($moreparam ? '&' : '').'search_status=-1';
883 $moreparam .= ($moreparam ? '&' : '').'search_filtert='.$object->userownerid;
884 */
885 $moreparam .= ($moreparam ? '&' : '').'disabledefaultvalues=1';
886 } else {
887 // If error
888 $error++;
889 $langs->load("errors");
890 $error = $langs->trans($finalobject->error);
891 setEventMessages($error, null, 'errors');
892 $action = 'create';
893 $donotclearsession = 1;
894 }
895 } else {
896 $error++;
897 setEventMessages($finalobject->error, $finalobject->errors, 'errors');
898 $action = 'create';
899 $donotclearsession = 1;
900 }
901
902 // If event is not recurrent, we stop here
903 if (!($userepeatevent && GETPOSTISSET('recurrulefreq') && GETPOST('recurrulefreq') != 'no' && GETPOSTISSET("limityear") && GETPOSTISSET("limitmonth") && GETPOSTISSET("limitday"))) {
904 break;
905 }
906
907 // increment date for recurrent events
908 $datep = dol_time_plus_duree($datep, $dayoffset, 'd', 0, $tzforrecurrence);
909 $datep = dol_time_plus_duree($datep, $monthoffset, 'm', 0, $tzforrecurrence); // @phan-suppress-current-line PhanPluginSuspiciousParamOrder
910 $datep = dol_time_plus_duree($datep, $yearoffset, 'y', 0, $tzforrecurrence); // @phan-suppress-current-line PhanPluginSuspiciousParamOrder
911 $datef = dol_time_plus_duree($datef, $dayoffset, 'd', 0, $tzforrecurrence);
912 $datef = dol_time_plus_duree($datef, $monthoffset, 'm', 0, $tzforrecurrence); // @phan-suppress-current-line PhanPluginSuspiciousParamOrder
913 $datef = dol_time_plus_duree($datef, $yearoffset, 'y', 0, $tzforrecurrence); // @phan-suppress-current-line PhanPluginSuspiciousParamOrder
914 if ($durationofevent > 0 && $datef <= $datep) {
915 $datef = $datep + $durationofevent;
916 }
917 }
918 }
919
920 if ($error) {
921 $db->rollback();
922 } else {
923 $db->commit();
924 }
925
926 if (!empty($backtopage) && !$error) {
927 dol_syslog("Back to ".$backtopage.($moreparam ? (preg_match('/\?/', $backtopage) ? '&'.$moreparam : '?'.$moreparam) : ''));
928 header("Location: ".$backtopage.($moreparam ? (preg_match('/\?/', $backtopage) ? '&'.$moreparam : '?'.$moreparam) : ''));
929 } elseif ($idaction) {
930 header("Location: ".DOL_URL_ROOT.'/comm/action/card.php?id='.$idaction.($moreparam ? '&'.$moreparam : ''));
931 } else {
932 header("Location: ".DOL_URL_ROOT.'/comm/action/index.php'.($moreparam ? '?'.$moreparam : ''));
933 }
934 exit;
935 }
936}
937
938// Action update event
939if (empty($reshook) && $action == 'update' && $usercancreate) {
940 if (empty($cancel)) {
941 $fulldayevent = GETPOST('fullday');
942 $aphour = GETPOSTINT('aphour');
943 $apmin = GETPOSTINT('apmin');
944 $p2hour = GETPOSTINT('p2hour');
945 $p2min = GETPOSTINT('p2min');
946 $percentage = in_array(GETPOST('status'), array(-1, 100)) ? GETPOST('status') : (in_array($complete, array(-1, 100)) ? $complete : GETPOSTINT("percentage")); // If status is -1 or 100, percentage is not defined and we must use status
947
948 // Clean parameters
949 if ($aphour == -1) {
950 $aphour = '0';
951 }
952 if ($apmin == -1) {
953 $apmin = '0';
954 }
955 if ($p2hour == -1) {
956 $p2hour = '0';
957 }
958 if ($p2min == -1) {
959 $p2min = '0';
960 }
961
962 $object->fetch($id);
963 $object->fetch_optionals();
964 $object->fetch_userassigned();
965 $object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
966
967 // Clean parameters
968 if ($fulldayevent) {
969 $tzforfullday = getDolGlobalString('MAIN_STORE_FULL_EVENT_IN_GMT');
970 // For "full day" events, we must store date in GMT (It must be viewed as same moment everywhere)
971 $datep = dol_mktime(0, 0, 0, GETPOSTINT("apmonth"), GETPOSTINT("apday"), GETPOSTINT("apyear"), $tzforfullday ? $tzforfullday : 'tzuserrel');
972 $datef = dol_mktime(23, 59, 59, GETPOSTINT("p2month"), GETPOSTINT("p2day"), GETPOSTINT("p2year"), $tzforfullday ? $tzforfullday : 'tzuserrel');
973 } else {
974 if (!GETPOSTISSET('ap') && !GETPOSTISSET('aphour') && !GETPOSTISSET('apmin')) { // If date fields are disabled, we keep old value
975 $datep = $object->datep;
976 } else {
977 $datep = dol_mktime(GETPOSTINT("aphour"), GETPOSTINT("apmin"), GETPOSTINT("apsec"), GETPOSTINT("apmonth"), GETPOSTINT("apday"), GETPOSTINT("apyear"), 'tzuserrel');
978 }
979 if (!GETPOSTISSET('p2') && !GETPOSTISSET('p2hour') && !GETPOSTISSET('p2min')) { // If date fields are disabled, we keep old value
980 $datef = $object->datef;
981 } else {
982 $datef = dol_mktime(GETPOSTINT("p2hour"), GETPOSTINT("p2min"), GETPOSTINT("apsec"), GETPOSTINT("p2month"), GETPOSTINT("p2day"), GETPOSTINT("p2year"), 'tzuserrel');
983 }
984 }
985
986 //set end date to now if percentage is set to 100 and end date not set
987 $datef = (!$datef && $percentage == 100) ? dol_now() : $datef;
988
989 if ($object->elementtype == 'ticket') { // code should be TICKET_MSG, TICKET_MSG_PRIVATE, TICKET_MSG_SENTBYMAIL, TICKET_MSG_PRIVATE_SENTBYMAIL
990 if ($private) {
991 if ($object->code == 'TICKET_MSG') {
992 $object->code = 'TICKET_MSG_PRIVATE';
993 }
994 if ($object->code == 'TICKET_MSG_SENTBYMAIL') {
995 $object->code = 'TICKET_MSG_PRIVATE_SENTBYMAIL';
996 }
997 } else {
998 if ($object->code == 'TICKET_MSG_PRIVATE') {
999 $object->code = 'TICKET_MSG';
1000 }
1001 if ($object->code == 'TICKET_MSG_PRIVATE_SENTBYMAIL') {
1002 $object->code = 'TICKET_MSG_SENTBYMAIL';
1003 }
1004 }
1005 // type_id and type_code is not modified
1006 } else {
1007 $object->type_id = dol_getIdFromCode($db, GETPOST("actioncode", 'aZ09'), 'c_actioncomm');
1008 $object->type_code = GETPOST("actioncode", 'aZ09');
1009 }
1010
1011 $object->label = GETPOST("label", "alphanohtml");
1012 $object->datep = $datep;
1013 $object->datef = $datef;
1014 $object->percentage = $percentage;
1015 $object->priority = GETPOSTINT("priority");
1016 $object->fulldayevent = GETPOST("fullday") ? 1 : 0;
1017 $object->location = GETPOST('location', "alphanohtml");
1018 $object->socid = GETPOSTINT("socid");
1019 $socpeopleassigned = GETPOST("socpeopleassigned", 'array');
1020 $object->socpeopleassigned = [];
1021 foreach ($socpeopleassigned as $cid) {
1022 $object->socpeopleassigned[$cid] = array('id' => $cid);
1023 }
1024 $object->contact_id = GETPOSTINT("contactid");
1025 if (empty($object->contact_id) && !empty($object->socpeopleassigned)) {
1026 reset($object->socpeopleassigned);
1027 $object->contact_id = (int) key($object->socpeopleassigned);
1028 }
1029 $object->fk_project = GETPOSTINT("projectid");
1030 $taskid = GETPOSTINT('taskid');
1031 if (!empty($taskid)) {
1032 $taskProject = new Task($db);
1033 if ($taskProject->fetch($taskid) > 0) {
1034 $object->fk_project = $taskProject->fk_project;
1035 }
1036
1037 $object->fk_element = $taskid;
1038 $object->elementid = $taskid;
1039 $object->elementtype = 'project_task';
1040 }
1041
1042 $object->note_private = trim(GETPOST("note", "restricthtml"));
1043
1044 if (GETPOST("elementtype", 'alpha')) {
1045 $elProp = getElementProperties(GETPOST("elementtype", 'alpha'));
1046 $modulecodetouseforpermissioncheck = $elProp['module'];
1047 // Keep permission check aligned with rights class aliases (see restrictedArea()).
1048 $submodulecodetouseforpermissioncheck = $elProp['subelement'];
1049
1050 switch ($modulecodetouseforpermissioncheck) {
1051 case 'productbatch':
1052 $modulecodetouseforpermissioncheck = 'produit';
1053 break;
1054 case 'eventorganization':
1055 // Event organization relies on Project permissions
1056 $modulecodetouseforpermissioncheck = 'projet';
1057 $submodulecodetouseforpermissioncheck = ''; // Project doesn't use submodules for read
1058 break;
1059 default:
1060 // No mapping needed, keep original values
1061 break;
1062 }
1063
1064 $hasPermissionOnLinkedObject = 0;
1065 if ($user->hasRight($modulecodetouseforpermissioncheck, 'read')) {
1066 $hasPermissionOnLinkedObject = 1;
1067 }
1068 if ($hasPermissionOnLinkedObject) {
1069 $object->fk_element = GETPOSTINT("fk_element");
1070 $object->elementid = GETPOSTINT("fk_element");
1071 $object->elementtype = GETPOST("elementtype", 'alpha');
1072 }
1073 }
1074
1075
1076 $transparency = (GETPOST("transparency") == 'on' ? 1 : 0);
1077
1078 // Users
1079 $listofuserid = [];
1080 if (!empty($_SESSION[$sessionkeyassignedtouser])) { // Now concat assigned users
1081 // Restore array with key with same value than param 'id'
1082 $tmplist1 = json_decode($_SESSION[$sessionkeyassignedtouser], true);
1083 foreach ($tmplist1 as $key => $val) {
1084 if ($val['id'] > 0 && $val['id'] != $assignedtouser) {
1085 $listofuserid[$val['id']] = $val;
1086 }
1087 }
1088 } else {
1089 $assignedtouser = (!empty($object->userownerid) && $object->userownerid > 0 ? $object->userownerid : 0);
1090 if ($assignedtouser) {
1091 $listofuserid[$assignedtouser] = array('id' => $assignedtouser, 'mandatory' => 0, 'transparency' => ($user->id == $assignedtouser ? $transparency : '')); // Owner first
1092 }
1093 }
1094 $object->userassigned = [];
1095 $object->userownerid = 0; // Clear old content
1096 $i = 0;
1097 foreach ($listofuserid as $key => $val) {
1098 if ($i == 0) {
1099 $object->userownerid = $val['id'];
1100 }
1101 $object->userassigned[$val['id']] = array('id' => $val['id'], 'mandatory' => 0, 'transparency' => ($user->id == $val['id'] ? $transparency : ''));
1102 $i++;
1103 }
1104
1105 $object->transparency = $transparency; // We set transparency on event (even if we can also store it on each user, standard says this property is for event)
1106 // TODO store also transparency on owner user
1107
1108 // Check parameters
1109 if (GETPOSTISSET('actioncode') && !GETPOST('actioncode', 'aZ09')) { // actioncode is '0'
1110 $error++;
1111 $donotclearsession = 1;
1112 $action = 'edit';
1113 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
1114 } else {
1115 $result = $cactioncomm->fetch(GETPOST('actioncode', 'aZ09'));
1116 }
1117 if (empty($object->userownerid)) {
1118 $error++;
1119 $donotclearsession = 1;
1120 $action = 'edit';
1121 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ActionsOwnedBy")), null, 'errors');
1122 }
1123
1124 // Fill array 'array_options' with data from add form
1125 $ret = $extrafields->setOptionalsFromPost(null, $object, '@GETPOSTISSET');
1126 if ($ret < 0) {
1127 $error++;
1128 }
1129
1130 if (!$error) {
1131 // check if an event resource is already in use
1132 if (getDolGlobalString('RESOURCE_USED_IN_EVENT_CHECK') && $object->element == 'action') {
1133 $eventDateStart = $object->datep;
1134 $eventDateEnd = $object->datef;
1135
1136 $sql = "SELECT er.rowid, r.ref as r_ref, ac.id as ac_id, ac.label as ac_label";
1137 $sql .= " FROM ".MAIN_DB_PREFIX."element_resources as er";
1138 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."resource as r ON r.rowid = er.resource_id AND er.resource_type = 'dolresource'";
1139 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm as ac ON ac.id = er.element_id AND er.element_type = '".$db->escape($object->element)."'";
1140 $sql .= " WHERE ac.id <> ".((int) $object->id);
1141 $sql .= " AND er.resource_id IN (";
1142 $sql .= " SELECT resource_id FROM ".MAIN_DB_PREFIX."element_resources";
1143 $sql .= " WHERE element_id = ".((int) $object->id);
1144 $sql .= " AND element_type = '".$db->escape($object->element)."'";
1145 $sql .= " AND busy = 1";
1146 $sql .= ")";
1147 $sql .= " AND er.busy = 1";
1148 $sql .= " AND (";
1149
1150 // event date start between ac.datep and ac.datep2 (if datep2 is null we consider there is no end)
1151 $sql .= " (ac.datep <= '".$db->idate($eventDateStart)."' AND (ac.datep2 IS NULL OR ac.datep2 >= '".$db->idate($eventDateStart)."'))";
1152 // event date end between ac.datep and ac.datep2
1153 if (!empty($eventDateEnd)) {
1154 $sql .= " OR (ac.datep <= '".$db->idate($eventDateEnd)."' AND (ac.datep2 >= '".$db->idate($eventDateEnd)."'))";
1155 }
1156 // event date start before ac.datep and event date end after ac.datep2
1157 $sql .= " OR (";
1158 $sql .= "ac.datep >= '".$db->idate($eventDateStart)."'";
1159 if (!empty($eventDateEnd)) {
1160 $sql .= " AND (ac.datep2 IS NOT NULL AND ac.datep2 <= '".$db->idate($eventDateEnd)."')";
1161 }
1162 $sql .= ")";
1163
1164 $sql .= ")";
1165 $resql = $db->query($sql);
1166 if (!$resql) {
1167 $error++;
1168 $object->error = $db->lasterror();
1169 $object->errors[] = $object->error;
1170 } else {
1171 if ($db->num_rows($resql) > 0) {
1172 // Resource already in use
1173 $error++;
1174 $object->error = $langs->trans('ErrorResourcesAlreadyInUse').' : ';
1175 while ($obj = $db->fetch_object($resql)) {
1176 $object->error .= '<br> - '.$langs->trans('ErrorResourceUseInEvent', $obj->r_ref, $obj->ac_label.' ['.$obj->ac_id.']');
1177 }
1178 $object->errors[] = $object->error;
1179 }
1180 $db->free($resql);
1181 }
1182
1183 if ($error) {
1184 setEventMessages($object->error, $object->errors, 'errors');
1185 }
1186 }
1187 }
1188
1189 if (!$error) {
1190 $db->begin();
1191
1192 $result = $object->update($user);
1193
1194 if ($result > 0) {
1195 // Category association
1196 $categories = GETPOST('categories', 'array');
1197 $object->setCategories($categories);
1198
1199 $object->loadReminders($remindertype, 0, false);
1200
1201 // If there is reminders, we remove them
1202 if (!empty($object->reminders)) {
1203 foreach ($object->reminders as $reminder) {
1204 if ($reminder->status < 1) { // If already sent, we never remove it
1205 $reminder->delete($user);
1206 }
1207 }
1208 $object->reminders = [];
1209 }
1210
1211 // Create reminders for every assigned user if reminder is on
1212 if ($addreminder == 'on') {
1213 $actionCommReminder = new ActionCommReminder($db);
1214
1215 $dateremind = dol_time_plus_duree($datep, -1 * $offsetvalue, $offsetunit);
1216
1217 $actionCommReminder->dateremind = $dateremind;
1218 $actionCommReminder->typeremind = $remindertype;
1219 $actionCommReminder->offsetunit = $offsetunit;
1220 $actionCommReminder->offsetvalue = $offsetvalue;
1221 $actionCommReminder->status = $actionCommReminder::STATUS_TODO;
1222 $actionCommReminder->fk_actioncomm = $object->id;
1223 if ($remindertype == 'email') {
1224 $actionCommReminder->fk_email_template = $modelmail;
1225 }
1226
1227 // the notification must be created for every user assigned to the event
1228 foreach ($object->userassigned as $userassigned) {
1229 $actionCommReminder->fk_user = $userassigned['id'];
1230
1231 // We update the event, so we recreate the notification event.
1232 // First we delete all reminders for the user and the type of reminding (all offset dates).
1233 $sqldelete = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm_reminder";
1234 $sqldelete .= " WHERE fk_user = ".((int) $actionCommReminder->fk_user)." AND fk_actioncomm = ".((int) $object->id)." AND typeremind = '".$db->escape($remindertype)."'";
1235 $resqldelete = $db->query($sqldelete);
1236
1237 $res = $actionCommReminder->create($user);
1238
1239 if ($res <= 0) {
1240 // If error
1241 $langs->load("errors");
1242 $error = $langs->trans('ErrorReminderActionCommCreation');
1243 setEventMessages($error, null, 'errors');
1244 $action = 'create';
1245 $donotclearsession = 1;
1246 break;
1247 }
1248 }
1249 }
1250
1251 if (!$error) {
1252 unset($_SESSION[$sessionkeyassignedtouser]);
1253 unset($_SESSION[$sessionkeyassignedtoresource]);
1254
1255 $db->commit();
1256 } else {
1257 $db->rollback();
1258 $action = 'edit';
1259 }
1260 } else {
1261 setEventMessages($object->error, $object->errors, 'errors');
1262 $db->rollback();
1263 }
1264 }
1265 }
1266
1267 if (!$error) {
1268 if (!empty($backtopage)) {
1269 unset($_SESSION[$sessionkeyassignedtouser]);
1270 header("Location: ".$backtopage);
1271 exit;
1272 }
1273 }
1274}
1275
1276// Delete event
1277if (empty($reshook) && $action == 'confirm_delete' && GETPOST("confirm") == 'yes' && $usercandelete) {
1278 $object->fetch($id);
1279 $object->fetch_optionals();
1280 $object->fetch_userassigned();
1281 $object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
1282
1283 $result = $object->delete($user);
1284
1285 if ($result >= 0) {
1286 header("Location: index.php");
1287 exit;
1288 } else {
1289 setEventMessages($object->error, $object->errors, 'errors');
1290 }
1291}
1292
1293/*
1294 * Action move update, used when user move an event in calendar by drag'n drop
1295 * TODO Move this into page comm/action/index that trigger this call by the drag and drop of event.
1296 */
1297if (empty($reshook) && GETPOST('actionmove', 'alpha') == 'mupdate' && $usercancreate) {
1298 $error = 0;
1299
1300 $shour = (int) dol_print_date($object->datep, "%H", 'tzuserrel'); // We take the date visible by user $newdate is also date visible by user.
1301 $smin = (int) dol_print_date($object->datep, "%M", 'tzuserrel');
1302
1303 $newdate = GETPOST('newdate', 'alpha');
1304 if (empty($newdate) || strpos($newdate, 'dayevent_') !== 0) {
1305 header("Location: ".$backtopage, true, 307);
1306 exit;
1307 }
1308
1309 $datep = dol_mktime($shour, $smin, 0, (int) substr($newdate, 13, 2), (int) substr($newdate, 15, 2), (int) substr($newdate, 9, 4), 'tzuserrel');
1310 //print dol_print_date($datep, 'dayhour');exit;
1311
1312 if ($datep != $object->datep) {
1313 if (!empty($object->datef)) {
1314 $object->datef += (int) $datep - $object->datep;
1315 }
1316 $object->datep = $datep;
1317
1318 if (!$error) {
1319 // check if an event resource is already in use
1320 if (getDolGlobalString('RESOURCE_USED_IN_EVENT_CHECK') && $object->element == 'action') {
1321 $eventDateStart = $object->datep;
1322 $eventDateEnd = $object->datef;
1323
1324 $sql = "SELECT er.rowid, r.ref as r_ref, ac.id as ac_id, ac.label as ac_label";
1325 $sql .= " FROM ".MAIN_DB_PREFIX."element_resources as er";
1326 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."resource as r ON r.rowid = er.resource_id AND er.resource_type = 'dolresource'";
1327 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm as ac ON ac.id = er.element_id AND er.element_type = '".$db->escape($object->element)."'";
1328 $sql .= " WHERE ac.id <> ".((int) $object->id);
1329 $sql .= " AND er.resource_id IN (";
1330 $sql .= " SELECT resource_id FROM ".MAIN_DB_PREFIX."element_resources";
1331 $sql .= " WHERE element_id = ".((int) $object->id);
1332 $sql .= " AND element_type = '".$db->escape($object->element)."'";
1333 $sql .= " AND busy = 1";
1334 $sql .= ")";
1335 $sql .= " AND er.busy = 1";
1336 $sql .= " AND (";
1337
1338 // event date start between ac.datep and ac.datep2 (if datep2 is null we consider there is no end)
1339 $sql .= " (ac.datep <= '".$db->idate($eventDateStart)."' AND (ac.datep2 IS NULL OR ac.datep2 >= '".$db->idate($eventDateStart)."'))";
1340 // event date end between ac.datep and ac.datep2
1341 if (!empty($eventDateEnd)) {
1342 $sql .= " OR (ac.datep <= '".$db->idate($eventDateEnd)."' AND (ac.datep2 >= '".$db->idate($eventDateEnd)."'))";
1343 }
1344 // event date start before ac.datep and event date end after ac.datep2
1345 $sql .= " OR (";
1346 $sql .= "ac.datep >= '".$db->idate($eventDateStart)."'";
1347 if (!empty($eventDateEnd)) {
1348 $sql .= " AND (ac.datep2 IS NOT NULL AND ac.datep2 <= '".$db->idate($eventDateEnd)."')";
1349 }
1350 $sql .= ")";
1351
1352 $sql .= ")";
1353 $resql = $db->query($sql);
1354 if (!$resql) {
1355 $error++;
1356 $object->error = $db->lasterror();
1357 $object->errors[] = $object->error;
1358 } else {
1359 if ($db->num_rows($resql) > 0) {
1360 // Resource already in use
1361 $error++;
1362 $object->error = $langs->trans('ErrorResourcesAlreadyInUse').' : ';
1363 while ($obj = $db->fetch_object($resql)) {
1364 $object->error .= '<br> - '.$langs->trans('ErrorResourceUseInEvent', $obj->r_ref, $obj->ac_label.' ['.$obj->ac_id.']');
1365 }
1366 $object->errors[] = $object->error;
1367 }
1368 $db->free($resql);
1369 }
1370
1371 if ($error) {
1372 setEventMessages($object->error, $object->errors, 'errors');
1373 }
1374 }
1375 }
1376
1377 if (!$error) {
1378 $db->begin();
1379 $result = $object->update($user);
1380 if ($result < 0) {
1381 $error++;
1382 setEventMessages($object->error, $object->errors, 'errors');
1383 $db->rollback();
1384 } else {
1385 $db->commit();
1386 }
1387 }
1388 }
1389 if (!empty($backtopage)) {
1390 header("Location: ".$backtopage, true, 307);
1391 exit;
1392 } else {
1393 $action = '';
1394 }
1395}
1396
1397// Actions to delete doc
1398$upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref);
1399$permissiontoadd = ($user->hasRight('agenda', 'allactions', 'create') || (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create')));
1400if (empty($reshook)) {
1401 include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
1402}
1403
1404
1405/*
1406 * View
1407 */
1408
1409$form = new Form($db);
1410$formproject = new FormProjets($db);
1411
1412$arrayrecurrulefreq = array(
1413 'no' => $langs->trans("OnceOnly"),
1414 'YEARLY' => $langs->trans("EveryYear"),
1415 'MONTHLY' => $langs->trans("EveryMonth"),
1416 'WEEKLY' => $langs->trans("EveryWeek")
1417 // 'DAILY'=>$langs->trans("EveryDay")
1418);
1419
1420
1421$help_url = 'EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda|DE:Modul_Terminplanung';
1422llxHeader('', $langs->trans("Agenda"), $help_url);
1423
1424if ($action == 'create') {
1425 $contact = new Contact($db);
1426
1427 $socpeopleassigned = GETPOST("socpeopleassigned", 'array');
1428 if (!empty($socpeopleassigned[0])) {
1429 $result = $contact->fetch($socpeopleassigned[0]);
1430 if ($result < 0) {
1431 dol_print_error($db, $contact->error);
1432 }
1433 }
1434
1435 dol_set_focus("#label");
1436
1437 if (!empty($conf->use_javascript_ajax)) {
1438 print "\n".'<script type="text/javascript">';
1439 print '$(document).ready(function () {
1440 function setdatefields()
1441 {
1442 if ($("#fullday:checked").val() == null) {
1443 $(".fulldaystarthour").removeAttr("disabled");
1444 $(".fulldaystartmin").removeAttr("disabled");
1445 $(".fulldayendhour").removeAttr("disabled");
1446 $(".fulldayendmin").removeAttr("disabled");
1447 $("#p2").removeAttr("disabled");
1448 } else {
1449 $(".fulldaystarthour").prop("disabled", true).val("00");
1450 $(".fulldaystartmin").prop("disabled", true).val("00");
1451 $(".fulldayendhour").prop("disabled", true).val("23");
1452 $(".fulldayendmin").prop("disabled", true).val("59");
1453 $("#p2").removeAttr("disabled");
1454 }
1455 }
1456 $("#fullday").change(function() {
1457 console.log("setdatefields");
1458 setdatefields();
1459 });
1460 var old_startdate = null;
1461 $("#ap").focus(function() {
1462 old_startdate = new Date($("#apyear").val(), $("#apmonth").val() - 1, $("#apday").val());
1463 });
1464 $("#ap").next(".ui-datepicker-trigger").click(function() {
1465 old_startdate = new Date($("#apyear").val(), $("#apmonth").val() - 1, $("#apday").val());
1466 });
1467 $("#ap").change(function() {
1468 setTimeout(function() {
1469 if ($("#p2").val() !== "") {
1470 var new_startdate = new Date($("#apyear").val(), $("#apmonth").val() - 1, $("#apday").val());
1471 var old_enddate = new Date($("#p2year").val(), $("#p2month").val() - 1, $("#p2day").val());
1472 if (new_startdate > old_enddate) {
1473 var timeDiff = old_enddate - old_startdate;
1474 var new_enddate = new Date(new_startdate.getTime() + timeDiff);
1475 $("#p2").val(formatDate(new_enddate, "' . $langs->trans('FormatDateShortJavaInput') . '"));
1476 $("#p2day").val(new_enddate.getDate());
1477 $("#p2month").val(new_enddate.getMonth() + 1);
1478 $("#p2year").val(new_enddate.getFullYear());
1479 }
1480 }
1481 }, 0);
1482 });
1483 $("#actioncode").change(function() {
1484 if ($("#actioncode").val() == \'AC_RDV\') $("#dateend").addClass("fieldrequired");
1485 else $("#dateend").removeClass("fieldrequired");
1486 });
1487 $("#aphour,#apmin").change(function() {
1488 if ($("#actioncode").val() == \'AC_RDV\') {
1489 var oldhour = parseInt($("#aphour").val());
1490 var oldmin = parseInt($("#apmin").val());
1491 var oldday = parseInt($("#apday").val());
1492 var oldmonth = $("#apmonth").val();
1493 var oldyear = $("#apyear").val();
1494
1495 var newhour = oldhour + 1;
1496 var newday = oldday;
1497 var newmonth = oldmonth;
1498 var newyear = oldyear;
1499 if (newhour >= 24) {
1500 newhour = 0;
1501 newday = oldday + 1;
1502 }
1503 console.log("Start date was changed, we modify end date "+oldhour+" "+oldmin+" -> "+newhour+" "+oldmin);
1504 $("#p2hour").val(("00" + newhour).substr(-2,2));
1505 $("#p2min").val(("00" + oldmin).substr(-2,2));
1506 $("#p2day").val(newday);
1507 $("#p2month").val(newmonth);
1508 $("#p2year").val(newyear);
1509 $("#p2").val($("#ap").val());
1510 }
1511 });
1512 if ($("#actioncode").val() == \'AC_RDV\') $("#dateend").addClass("fieldrequired");
1513 else $("#dateend").removeClass("fieldrequired");
1514 setdatefields();
1515 })';
1516 print '</script>'."\n";
1517 }
1518
1519 print '<form name="formaction" action="'.$_SERVER['PHP_SELF'].'" method="POST">';
1520 print '<input type="hidden" name="token" value="'.newToken().'">';
1521 print '<input type="hidden" name="action" value="add">';
1522 print '<input type="hidden" name="donotclearsession" value="1">';
1523 print '<input type="hidden" name="page_y" value="">';
1524 if ($backtopage) {
1525 print '<input type="hidden" name="backtopage" value="'.($backtopage != '1' ? $backtopage : '').'">';
1526 }
1527 if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
1528 print '<input type="hidden" name="actioncode" value="'.dol_getIdFromCode($db, 'AC_OTH', 'c_actioncomm').'">';
1529 }
1530
1531 print load_fiche_titre($langs->trans("AddAnAction"), '', 'title_agenda');
1532
1533 print dol_get_fiche_head();
1534
1535 print '<div class="divcreate">';
1536 print '<table class="border centpercent nobottom">';
1537
1538 // Title
1539 print '<tr><td'.(getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? ' class="fieldrequired"' : ' class="fieldrequired titlefieldcreate"').'>'.$langs->trans("Title").'</td><td><input type="text" id="label" name="label" class="soixantepercent" value="'.GETPOST('label').'"></td></tr>';
1540
1541 // Type of event
1542 if (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
1543 print '<tr><td class="titlefieldcreate"><span class="fieldrequired">'.$langs->trans("Type").'</span></b></td><td>';
1544 $default = getDolGlobalString('AGENDA_USE_EVENT_TYPE_DEFAULT', 'AC_OTH');
1545 if (empty($default)) {
1546 $default = 'AC_OTH';
1547 }
1548 print img_picto($langs->trans("ActionType"), 'square', 'class="fawidth30 inline-block" style="color: #ddd;"');
1549 $selectedvalue = GETPOSTISSET("actioncode") ? GETPOST("actioncode", 'aZ09') : ($object->type_code ? $object->type_code : $default);
1550 print $formactions->select_type_actions($selectedvalue, "actioncode", "systemauto", 0, -1, 0, 1); // TODO Replace 0 with -2 in onlyautoornot
1551 print '</td></tr>';
1552 }
1553
1554 // Full day
1555 print '<tr><td><span class="fieldrequired">'.$langs->trans("Date").'</span></td>';
1556 print '<td class="valignmiddle height30">';
1557 print '<div>';
1558 print '<input class="valignmiddle" type="checkbox" id="fullday" name="fullday" '.(GETPOST('fullday') ? ' checked' : '').'><label for="fullday" class="valignmiddle small">'.$langs->trans("EventOnFullDay").'</label>';
1559 print '</div>';
1560 print '</td></tr>';
1561
1562 $datep = ($datep ? $datep : (is_null($object->datep) ? '' : $object->datep));
1563 if (GETPOST('datep', 'alpha', 1)) {
1564 $datep = dol_stringtotime(GETPOST('datep', 'alpha', 1), 'tzuserrel');
1565 }
1566 $datef = ($datef ? $datef : $object->datef);
1567 if (GETPOST('datef', 'alpha', 1)) {
1568 $datef = dol_stringtotime(GETPOST('datef', 'alpha', 1), 'tzuserrel');
1569 }
1570 if (empty($datef) && !empty($datep)) {
1571 if (GETPOST("actioncode", 'aZ09') == 'AC_RDV' || (!getDolGlobalString('AGENDA_USE_EVENT_TYPE_DEFAULT') || getDolGlobalString('AGENDA_USE_EVENT_TYPE_DEFAULT') == '-1')) {
1572 $datef = dol_time_plus_duree($datep, getDolGlobalInt('AGENDA_AUTOSET_END_DATE_WITH_DELTA_HOURS', 1), 'h');
1573 }
1574 }
1575
1576 // Date start
1577 print '<tr><td class="nowrap">';
1578 print '</td><td>';
1579 print '<div class="inline-block">';
1580 if (GETPOST("afaire") == 1) {
1581 print $form->selectDate($datep, 'ap', 1, 1, 0, "action", 1, 2, 0, 'fulldaystart', '', '', '', 1, '', '', 'tzuserrel'); // Empty value not allowed for start date and hours if "todo"
1582 } else {
1583 print $form->selectDate($datep, 'ap', 1, 1, 1, "action", 1, 2, 0, 'fulldaystart', '', '', '', 1, '', '', 'tzuserrel');
1584 }
1585 print ' <span class="hideonsmartphone">&nbsp; &nbsp; - &nbsp; &nbsp;</span><br class="showonsmartphone"> ';
1586 print $form->selectDate($datef, 'p2', 1, 1, 1, "action", 1, 0, 0, 'fulldayend', '', '', '', 1, '', '', 'tzuserrel');
1587 print '</div>';
1588
1589 //print '</td></tr>';
1590
1591 // Recurring event
1592 $userepeatevent = (getDolGlobalInt('MAIN_DISABLE_RECURRING_EVENTS') ? 0 : 1);
1593 if ($userepeatevent) {
1594 //print '<tr><td></td><td>';
1595 print '<div class="clearbothonsmartphone hideonsmartphone inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div>';
1596
1597 // Repeat
1598 print '<div class="inline-block small" data-html="repeat">';
1599 print '<span class="opacitymedium">';
1600 print img_picto($langs->trans("Recurrence"), 'recurring', 'style="margin-left: 3px" class="paddingright"');
1601 print '<input type="hidden" name="recurid" value="'.(empty($object->recurid) ? '' : $object->recurid).'">';
1602
1603 $selectedrecurrulefreq = 'no';
1604 $selectedrecurrulebyyearmonthday = '';
1605 $selectedrecurrulebymonthday = '';
1606 $selectedrecurrulebyday = '';
1607 $object->recurrule = GETPOSTISSET('recurrulefreq') ? "FREQ=".GETPOST('recurrulefreq', 'alpha') : "";
1608 $object->recurrule .= GETPOSTISSET('BYYEARMONTHDAY') ? "_BYYEARMONTHDAY".GETPOST('BYYEARMONTHDAY', 'alpha') : "";
1609 $object->recurrule .= GETPOSTISSET('BYMONTHDAY') ? "_BYMONTHDAY".GETPOST('BYMONTHDAY', 'alpha') : "";
1610 $object->recurrule .= GETPOSTISSET('BYDAY') ? "_BYDAY".GETPOST('BYDAY', 'alpha') : "";
1611
1612
1613 $reg = [];
1614 if ($object->recurrule && preg_match('/FREQ=([A-Z]+)/i', $object->recurrule, $reg)) {
1615 $selectedrecurrulefreq = $reg[1];
1616 }
1617 if ($object->recurrule && preg_match('/FREQ=YEARLY.*BYYEARMONTHDAY(\d+)/i', $object->recurrule, $reg)) {
1618 $selectedrecurrulebyyearmonthday = (int) $reg[1];
1619 }
1620 if ($object->recurrule && preg_match('/FREQ=MONTHLY.*BYMONTHDAY(\d+)/i', $object->recurrule, $reg)) {
1621 $selectedrecurrulebymonthday = (int) $reg[1];
1622 }
1623 if ($object->recurrule && preg_match('/FREQ=WEEKLY.*BYDAY(\d+)/i', $object->recurrule, $reg)) {
1624 $selectedrecurrulebyday = (int) $reg[1];
1625 }
1626
1627 print $form->selectarray('recurrulefreq', $arrayrecurrulefreq, $selectedrecurrulefreq, 0, 0, 0, '', 0, 0, 0, '', 'marginrightonly minwidth125 maxwidth150');
1628 print '</span>';
1629 // print '<script>console.log("recurrule: " +'.$object->recurrule.')</script>';
1630 // For recursive event
1631
1632
1633 // If recurrulefreq is MONTHLY
1634 /*
1635 print '<div class="hidden marginrightonly inline-block repeateventBYMONTHDAY">';
1636 print $langs->trans("DayOfMonth").': <input type="input" size="2" name="BYMONTHDAY" value="'.$selectedrecurrulebymonthday.'">';
1637 print '</div>';
1638 // If recurrulefreq is WEEKLY
1639 print '<div class="hidden marginrightonly inline-block repeateventBYDAY">';
1640 print $langs->trans("DayOfWeek").': <input type="input" size="4" name="BYDAY" value="'.$selectedrecurrulebyday.'">';
1641 print '</div>';
1642 */
1643
1644 // limit date
1645 $repeateventlimitdate = empty($repeateventlimitdate) ? (dol_now() + ((24 * 3600 * 365) + 1)) : $repeateventlimitdate;
1646
1647 print '<div class="hidden marginrightonly inline-block repeateventlimitdate">';
1648 print $langs->trans("Until")." ";
1649 print $form->selectDate($repeateventlimitdate, 'limit', 0, 0, 0, "action", 1, 0, 0, '', '', '', '', 1, '', '', 'tzuserrel');
1650 print '</div>';
1651 ?>
1652 <script type="text/javascript">
1653 jQuery(document).ready(function() {
1654 function init_repeat() {
1655 console.log("recurrule: " + "<?php echo $object->recurrule; ?>");
1656 console.log("reg1: " + "<?php echo $selectedrecurrulefreq; ?>");
1657 console.log("reg2: " + "<?php echo $selectedrecurrulebymonthday; ?>");
1658 console.log("reg3: " + "<?php echo $selectedrecurrulebyday; ?>");
1659 console.log("reg4: " + "<?php echo $selectedrecurrulebyyearmonthday; ?>");
1660 console.log("selectedrulefreq: " + "<?php echo $selectedrecurrulefreq; ?>");
1661 if (jQuery("#recurrulefreq").val() == 'YEARLY') {
1662 /* jQuery(".repeateventBYYEARMONTHDAY").css("display", "inline-block"); */ /* use this instead of show because we want inline-block and not block */
1663 jQuery(".repeateventlimitdate").css("display", "inline-block");
1664 jQuery(".repeateventBYMONTHDAY").hide();
1665 jQuery(".repeateventBYDAY").hide();
1666 } else if (jQuery("#recurrulefreq").val() == 'MONTHLY') {
1667 /* jQuery(".repeateventBYMONTHDAY").css("display", "inline-block"); */ /* use this instead of show because we want inline-block and not block */
1668 jQuery(".repeateventlimitdate").css("display", "inline-block");
1669 jQuery(".repeateventBYYEARMONTHDAY").hide();
1670 jQuery(".repeateventBYDAY").hide();
1671 } else if (jQuery("#recurrulefreq").val() == 'WEEKLY') {
1672 jQuery(".repeateventBYYEARMONTHDAY").hide();
1673 jQuery(".repeateventBYMONTHDAY").hide();
1674 /* jQuery(".repeateventBYDAY").css("display", "inline-block"); */ /* use this instead of show because we want inline-block and not block */
1675 jQuery(".repeateventlimitdate").css("display", "inline-block");
1676 } else {
1677 jQuery(".repeateventBYYEARMONTHDAY").hide();
1678 jQuery(".repeateventBYMONTHDAY").hide();
1679 jQuery(".repeateventBYDAY").hide();
1680 jQuery(".repeateventlimitdate").hide();
1681 }
1682 }
1683 init_repeat();
1684 jQuery("#recurrulefreq").change(function() {
1685 init_repeat();
1686 });
1687 });
1688 </script>
1689 <?php
1690 print '</div>';
1691 // print '</td></tr>';
1692 }
1693
1694 print '</td></tr>';
1695
1696
1697 // Location
1698 if (!getDolGlobalString('AGENDA_DISABLE_LOCATION')) {
1699 print '<tr><td class="titlefieldcreate">'.$langs->trans("Location").'</td><td>';
1700 print img_picto('', 'map-marker-alt', 'class="pictofixedwidth"');
1701 print '<input type="text" name="location" class="minwidth300 maxwidth150onsmartphone" value="'.(GETPOST('location') ? GETPOST('location') : $object->location).'"></td></tr>';
1702 }
1703
1704 print '</table>';
1705 print '</div>';
1706
1707 print '<br>';
1708
1709 print '<div class="divcreate">';
1710 print '<table class="border centpercent nobottom">';
1711
1712 // Assigned to user
1713 print '<tr><td class="nowrap titlefieldcreate"><span>';
1714 print $langs->trans("AssignedTo");
1715 print '</span></td><td>';
1716 $listofuserid = [];
1717 $listofcontactid = [];
1718 $listofotherid = [];
1719
1720 if (empty($donotclearsession)) {
1721 $assignedtouser = GETPOST("assignedtouser") ? GETPOST("assignedtouser") : (!empty($object->userownerid) && $object->userownerid > 0 ? $object->userownerid : $user->id);
1722 if ($assignedtouser) {
1723 $listofuserid[$assignedtouser] = array('id' => $assignedtouser, 'mandatory' => 0); // Owner first
1724 }
1725 //$listofuserid[$user->id] = array('id'=>$user->id, 'mandatory'=>0, 'transparency'=>(GETPOSTISSET('transparency') ? GETPOST('transparency', 'alpha') : 1)); // 1 by default at first init
1726 $listofuserid[$assignedtouser]['transparency'] = (GETPOSTISSET('transparency') ? GETPOST('transparency', 'alpha') : 1); // 1 by default at first init
1727 $_SESSION[$sessionkeyassignedtouser] = json_encode($listofuserid);
1728 } else {
1729 if (!empty($_SESSION[$sessionkeyassignedtouser])) {
1730 $listofuserid = json_decode($_SESSION[$sessionkeyassignedtouser], true);
1731 }
1732 if (!is_array($listofuserid)) {
1733 $listofuserid = [];
1734 }
1735 $firstelem = reset($listofuserid);
1736 if (isset($listofuserid[$firstelem['id']])) {
1737 $listofuserid[$firstelem['id']]['transparency'] = (GETPOSTISSET('transparency') ? GETPOST('transparency', 'alpha') : 0); // 0 by default when refreshing
1738 }
1739 }
1740 print '<!-- list of user to assign -->'."\n";
1741 print '<div class="assignedtouser">';
1742 print $form->select_dolusers_forevent(($action == 'create' ? 'add' : 'update'), 'assignedtouser', 1, [], 0, '', [], '0', 0, 0, 'u.statut:<>:0', 1, $listofuserid, $listofcontactid, $listofotherid);
1743 print '</div>';
1744 print '</td></tr>';
1745
1746 if (isModEnabled('resource')) {
1747 // Resources
1748 print '<tr><td class="tdtop nowrap">'.$langs->trans("Resource").'</td><td>';
1749
1750 $listofresourceid = [];
1751 if (empty($donotclearsession)) {
1752 $assignedtoresource = GETPOST("assignedtoresource");
1753 if ($assignedtoresource) {
1754 $listofresourceid[$assignedtoresource] = array('id' => $assignedtoresource, 'mandatory' => 0); // Owner first
1755 }
1756 $_SESSION[$sessionkeyassignedtoresource] = json_encode($listofresourceid);
1757 } else {
1758 if (!empty($_SESSION[$sessionkeyassignedtoresource])) {
1759 $listofresourceid = json_decode($_SESSION[$sessionkeyassignedtoresource], true);
1760 }
1761 if (!is_array($listofresourceid)) {
1762 $listofresourceid = [];
1763 }
1764 $firstelem = reset($listofresourceid);
1765 if ($firstelem && isset($listofresourceid[$firstelem['id']])) {
1766 $listofresourceid[$firstelem['id']]['transparency'] = (GETPOSTISSET('transparency') ? GETPOST('transparency', 'alpha') : 0); // 0 by default when refreshing
1767 }
1768 }
1769 print '<div class="assignedtoresource">';
1770 print $form->select_dolresources_forevent(($action == 'create' ? 'add' : 'update'), 'assignedtoresource', 1, [], 0, '', [], '0', 0, 0, 'AND u.statut != 0', 1, $listofresourceid);
1771 print '</div>';
1772 print '</td></tr>';
1773 }
1774
1775 if (isModEnabled('category')) {
1776 // Categories
1777 print '<tr><td>'.$langs->trans("Categories").'</td><td>';
1778 print $form->selectCategories(Categorie::TYPE_ACTIONCOMM, 'categories', $object);
1779 print "</td></tr>";
1780 }
1781
1782 print '</table>';
1783 print '</div>';
1784
1785
1786 print '<br>';
1787
1788 print '<div class="divcreate">';
1789 print '<table class="border centpercent nobottom">';
1790
1791 // Status
1792 print '<tr><td>'.$langs->trans("Status").' / '.$langs->trans("Progression").'</td>';
1793 print '<td>';
1794 $percent = $complete !== '' ? $complete : -1;
1795 if (GETPOSTISSET('status')) {
1796 $percent = GETPOST('status');
1797 } elseif (GETPOSTISSET('percentage')) {
1798 $percent = GETPOSTINT('percentage');
1799 } else {
1800 if ($complete == '0' || GETPOST("afaire") == 1) {
1801 $percent = '0';
1802 } elseif ($complete == 100 || GETPOST("afaire") == 2) {
1803 $percent = 100;
1804 }
1805 }
1806 print $formactions->form_select_status_action('formaction', $percent, 1, 'complete', 0, 0, 'minwidth150 maxwidth300', 1);
1807 print '</td></tr>';
1808
1809 if (isModEnabled("societe")) {
1810 // Related company
1811 print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("ActionOnCompany").'</td><td>';
1812 if (GETPOSTINT('socid') > 0) {
1813 $societe = new Societe($db);
1814 $societe->fetch(GETPOSTINT('socid'));
1815 print $societe->getNomUrl(1);
1816 print '<input type="hidden" id="socid" name="socid" value="'.GETPOSTINT('socid').'">';
1817 } else {
1818 $events = [];
1819 $events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php?showempty=1&token='.currentToken(), 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled'));
1820 //For external user force the company to user company
1821 if (!empty($user->socid)) {
1822 print img_picto('', 'company', 'class="pictofixedwidth"').$form->select_company($user->socid, 'socid', '', 1, 1, 0, $events, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
1823 } else {
1824 print img_picto('', 'company', 'class="pictofixedwidth"').$form->select_company('', 'socid', '', $langs->trans('SelectThirdParty'), 1, 0, $events, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
1825 }
1826 }
1827 print '</td></tr>';
1828
1829 // Related contact
1830 print '<tr><td class="nowrap">'.$langs->trans("ActionOnContact").'</td><td>';
1831 $preselectedids = GETPOST('socpeopleassigned', 'array:int');
1832 if (GETPOSTINT('contactid')) {
1833 $preselectedids[GETPOSTINT('contactid')] = GETPOSTINT('contactid');
1834 }
1835 if ($origin == 'contact') {
1836 $preselectedids[GETPOSTINT('originid')] = GETPOSTINT('originid');
1837 }
1838 // select "all" or "none" contact by default
1839 if (getDolGlobalInt('MAIN_ACTIONCOM_CAN_ADD_ANY_CONTACT')) {
1840 // Warning: MAIN_ACTIONCOM_CAN_ADD_ANY_CONTACT will hangs on large databases
1841 $select_contact_default = 0; // select "all" contacts by default : avoid to use it if there is a lot of contacts
1842 } else {
1843 $select_contact_default = -1; // select "none" by default
1844 }
1845 print img_picto('', 'contact', 'class="pictofixedwidth"');
1846
1847 if (getDolGlobalString('CONTACT_USE_SEARCH_TO_SELECT') && $conf->use_javascript_ajax) {
1848 // FIXME Use a select without the "multiple" (not supported when CONTACT_USE_SEARCH_TO_SELECT is on) or allow use only when $object->socid is set...
1849 /*
1850 $selected = array_keys($object->socpeopleassigned);
1851 print $form->select_contact(getDolGlobalString('MAIN_ACTIONCOM_CAN_ADD_ANY_CONTACT') ? 0 : $object->socid, $selected, 'socpeopleassigned', 1, '', '', 1, 'minwidth300 widthcentpercentminusx', false, 0, 0, []);
1852 */
1853 $sav = getDolGlobalString('CONTACT_USE_SEARCH_TO_SELECT');
1854 $conf->global->CONTACT_USE_SEARCH_TO_SELECT = 0;
1855 print $form->selectcontacts(GETPOSTISSET('socid') ? GETPOSTINT('socid') : $select_contact_default, $preselectedids, 'socpeopleassigned[]', 1, '', '', 0, 'minwidth300 widthcentpercentminusxx maxwidth500', 0, 0, 0, [], 'multiple', 'contactid');
1856 $conf->global->CONTACT_USE_SEARCH_TO_SELECT = $sav;
1857 } else {
1858 print $form->selectcontacts(GETPOSTISSET('socid') ? GETPOSTINT('socid') : $select_contact_default, $preselectedids, 'socpeopleassigned[]', 1, '', '', 0, 'minwidth300 widthcentpercentminusxx maxwidth500', 0, 0, 0, [], 'multiple', 'contactid');
1859 }
1860
1861 print '</td></tr>';
1862 }
1863
1864 // Project
1865 if (isModEnabled('project')) {
1866 $langs->load("projects");
1867
1868 $projectid = GETPOSTINT('projectid');
1869
1870 print '<tr><td class="titlefieldcreate">'.$langs->trans("Project").'</td><td id="project-input-container">';
1871 print img_picto('', 'project', 'class="pictofixedwidth"');
1872 print $formproject->select_projects(($object->socid > 0 ? $object->socid : -1), (string) $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx maxwidth500');
1873
1874 print '&nbsp;<a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.(empty($societe->id) ? '' : $societe->id).'&action=create&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'">';
1875 print '<span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddProject").'"></span></a>';
1876 $urloption = '?action=create&donotclearsession=1';
1877 $url = dol_buildpath('comm/action/card.php', 2).$urloption;
1878
1879 // update task list
1880 ?>
1881 <script type="text/javascript">
1882 $(document).ready(function () {
1883 $("#projectid").change(function () {
1884 var url = "<?php echo DOL_URL_ROOT; ?>/projet/ajax/projects.php?mode=gettasks&socid="+$("#search_socid").val()+"&projectid="+$("#projectid").val();
1885 console.log("Call url to get the new list of tasks: "+url);
1886 $.get(url, function(data) {
1887 console.log(data);
1888 if (data) $("#taskid").html(data).select2();
1889 })
1890 });
1891 });
1892 </script>
1893 <?php
1894
1895 print '</td></tr>';
1896
1897 // Task
1898 print '<tr><td class="titlefieldcreate">'.$langs->trans("Task").'</td><td id="project-task-input-container" >';
1899 print img_picto('', 'projecttask', 'class="pictofixedwidth"');
1900 $projectsListId = '';
1901 if (!empty($projectid)) {
1902 $projectsListId = $projectid;
1903 }
1904
1905 $tid = GETPOSTISSET("projecttaskid") ? GETPOSTINT("projecttaskid") : (GETPOSTISSET("taskid") ? GETPOSTINT("taskid") : '');
1906
1907 if (empty($projectsListId)) {
1908 print '<select class="valignmiddle flat maxwidth500 widthcentpercentminusxx minwidth150imp" id="taskid" name="taskid">';
1909 print '<option class="opacitymedium">&nbsp;</option>';
1910 print '<option class="opacitymedium" disabled data-html="'.dolPrintHTMLForAttribute($langs->trans("SelectAProjectFirst")).'">'.$langs->trans("SelectAProjectFirst").'</option>';
1911 print '</select>';
1912 print ajax_combobox('taskid');
1913 } else {
1914 print $formproject->selectTasks((!empty($societe->id) ? $societe->id : -1), $tid, 'taskid', 64, 0, '1', 1, 0, 0, 'maxwidth500 widthcentpercentminusxx', (string) $projectsListId, 'all', null, 1);
1915 }
1916 print '</td></tr>';
1917 }
1918
1919 // Object linked
1920 if (!empty($origin) && !empty($originid)) {
1921 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1922
1923 $hasPermissionOnLinkedObject = 0;
1924
1925 $elProp = getElementProperties($origin);
1926 $modulecodetouseforpermissioncheck = $elProp['module'];
1927 // Keep permission check aligned with rights class aliases (see restrictedArea()).
1928 $submodulecodetouseforpermissioncheck = $elProp['subelement'];
1929
1930 switch ($modulecodetouseforpermissioncheck) {
1931 case 'productbatch':
1932 $modulecodetouseforpermissioncheck = 'produit';
1933 break;
1934 case 'eventorganization':
1935 // Event organization relies on Project permissions
1936 $modulecodetouseforpermissioncheck = 'projet';
1937 $submodulecodetouseforpermissioncheck = ''; // Project doesn't use submodules for read
1938 break;
1939 default:
1940 // No mapping needed, keep original values
1941 break;
1942 }
1943
1944 if ($user->hasRight($modulecodetouseforpermissioncheck, 'read') || $user->hasRight($modulecodetouseforpermissioncheck, $elProp['element'], 'read')) {
1945 $hasPermissionOnLinkedObject = 1;
1946 }
1947 //var_dump('origin='.$origin.' originid='.$originid.' hasPermissionOnLinkedObject='.$hasPermissionOnLinkedObject);
1948
1949 if (! in_array($origin, array('societe', 'project', 'project_task', 'user'))) {
1950 // We do not use link for object that already contains a hard coded field to make links with agenda events
1951 print '<tr><td class="titlefieldcreate">'.$langs->trans("LinkedObject").'</td>';
1952 print '<td colspan="3">';
1953 if ($hasPermissionOnLinkedObject) {
1954 print dolGetElementUrl($originid, $origin, 1);
1955 print '<input type="hidden" name="fk_element" value="'.$originid.'">';
1956 print '<input type="hidden" name="elementtype" value="'.$origin.'">';
1957 print '<input type="hidden" name="originid" value="'.$originid.'">';
1958 print '<input type="hidden" name="origin" value="'.$origin.'">';
1959 } else {
1960 print '<!-- no permission on object to link '.$origin.' id '.$originid.' -->';
1961 }
1962 print '</td></tr>';
1963 }
1964 }
1965
1966 // Priority
1967 if (getDolGlobalString('AGENDA_SUPPORT_PRIORITY_IN_EVENTS')) {
1968 print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("Priority").'</td><td colspan="3">';
1969 print '<input type="text" name="priority" value="'.(GETPOSTISSET('priority') ? GETPOSTINT('priority') : ($object->priority ? $object->priority : '')).'" size="5">';
1970 print '</td></tr>';
1971 }
1972
1973 // Description
1974 print '<tr><td class="tdtop">'.$langs->trans("Description").'</td><td>';
1975 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1976 $doleditor = new DolEditor('note', (GETPOSTISSET('note') ? GETPOST('note', 'restricthtml') : $object->note_private), '', 200, 'dolibarr_notes', 'In', true, true, isModEnabled('fckeditor'), ROWS_4, '90%');
1977 $doleditor->Create();
1978 print '</td></tr>';
1979
1980 // Other attributes
1981 $parameters = [];
1982 $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1983 print $hookmanager->resPrint;
1984 if (empty($reshook)) {
1985 print $object->showOptionals($extrafields, 'create', $parameters);
1986 }
1987
1988 print '</table>';
1989 print '</div>';
1990
1991 if ($enablereminders) {
1992 //checkbox create reminder
1993 print '<hr>';
1994
1995 print '<label for="addreminder">'.img_picto('', 'bell', 'class="pictofixedwidth"').$langs->trans("AddReminder").'</label> <input type="checkbox" id="addreminder" name="addreminder"'.(empty(GETPOST('addreminder')) ? '' : 'checked').'><br>';
1996
1997 print '<div class="reminderparameters" '.(empty(GETPOST('addreminder')) ? 'style="display: none;' : '').' ">';
1998 print '<br>';
1999
2000 print '<table class="border centpercent">';
2001
2002 //Reminder
2003 print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("ReminderTime").'</td><td colspan="3">';
2004 print '<input class="width50" type="number" name="offsetvalue" value="'.(GETPOSTISSET('offsetvalue') ? GETPOSTINT('offsetvalue') : getDolGlobalInt('AGENDA_REMINDER_DEFAULT_OFFSET', 30)).'"> ';
2005
2006 print $form->selectTypeDuration('offsetunit', (empty($offsetunit) ? 'i' : $offsetunit), $TDurationTypesExcluded);
2007 print '</td></tr>';
2008
2009 //Reminder Type
2010 print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("ReminderType").'</td><td colspan="3">';
2011 print $form->selectarray('selectremindertype', $TRemindTypes, '', 0, 0, 0, '', 0, 0, 0, '', 'minwidth200 maxwidth500', 1);
2012 print '</td></tr>';
2013
2014 //Mail Model
2015 if (getDolGlobalString('AGENDA_REMINDER_EMAIL')) {
2016 print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("EMailTemplates").'</td><td colspan="3">';
2017 print $form->selectModelMail('actioncommsend', 'actioncomm_send', 1, 1, (empty($modelmail) ? 0 : $modelmail));
2018 print '</td></tr>';
2019 }
2020
2021 print '</table>';
2022 print '</div>';
2023
2024 $reminderDefaultEventTypes = getDolGlobalString('AGENDA_DEFAULT_REMINDER_EVENT_TYPES', '');
2025 $reminderDefaultOffset = getDolGlobalInt('AGENDA_DEFAULT_REMINDER_OFFSET', 30);
2026 $reminderDefaultUnit = getDolGlobalString('AGENDA_DEFAULT_REMINDER_OFFSET_UNIT');
2027 $reminderDefaultEmailModel = getDolGlobalInt('AGENDA_DEFAULT_REMINDER_EMAIL_MODEL');
2028
2029 print "\n".'<script type="text/javascript">';
2030 print '$(document).ready(function () {
2031 const reminderDefaultEventTypes = \''.dol_escape_js($reminderDefaultEventTypes).'\';
2032 $("#actioncode").change(function(){
2033 var selected_event_type = $("#actioncode option:selected").val();
2034
2035 if (reminderDefaultEventTypes.includes(selected_event_type)) {
2036 $(".reminderparameters").show();
2037 $("#addreminder").prop("checked", true);
2038
2039 // Set period with default reminder period
2040 $("[name=\"offsetvalue\"]").val(\'' . dol_escape_js((string) $reminderDefaultOffset) . '\');
2041 $("#select_offsetunittype_duration").select2("destroy");
2042 $("#select_offsetunittype_duration").val(\''.dol_escape_js($reminderDefaultUnit).'\');
2043 $("#select_offsetunittype_duration").select2();
2044
2045 $("#selectremindertype").select2("destroy");
2046 $("#selectremindertype").val("email");
2047 $("#selectremindertype").select2();
2048
2049 // Set default reminder mail model
2050 $("#select_actioncommsendmodel_mail").closest("tr").show();
2051 $("#select_actioncommsendmodel_mail").select2("destroy");
2052 $("#select_actioncommsendmodel_mail").val(\''.dol_escape_js((string) $reminderDefaultEmailModel).'\');
2053 $("#select_actioncommsendmodel_mail").select2();
2054 }
2055 });
2056 })';
2057 print '</script>'."\n";
2058
2059 print "\n".'<script type="text/javascript">';
2060 print '$(document).ready(function () {
2061 function toggle_reminder_part(evt) {
2062 console.log("Toggle reminder part");
2063 if ($("#addreminder").is(":checked")) {
2064 $(".reminderparameters").show();
2065 } else {
2066 $(".reminderparameters").hide();
2067 }
2068 $("#selectremindertype").select2("destroy");
2069 $("#selectremindertype").select2();
2070 $("#select_offsetunittype_duration").select2("destroy");
2071 $("#select_offsetunittype_duration").select2();
2072 selectremindertype();
2073 }
2074
2075 toggle_reminder_part();
2076 $("#addreminder").click(toggle_reminder_part);
2077
2078 $("#selectremindertype").change(function(){
2079 selectremindertype();
2080 });
2081
2082 function selectremindertype() {
2083 console.log("Call selectremindertype");
2084 var selected_option = $("#selectremindertype option:selected").val();
2085 if(selected_option == "email") {
2086 $("#select_actioncommsendmodel_mail").closest("tr").show();
2087 } else {
2088 $("#select_actioncommsendmodel_mail").closest("tr").hide();
2089 }
2090 }
2091
2092 })';
2093 print '</script>'."\n";
2094 }
2095
2096 print dol_get_fiche_end();
2097
2098 print $form->buttonsSaveCancel("Create");
2099
2100 print "</form>";
2101}
2102
2103// View or edit
2104if ($id > 0 && $action != 'create') {
2105 $result1 = $object->fetch($id);
2106 if ($result1 <= 0) {
2107 recordNotFound('', 0);
2108 }
2109
2110 $result2 = $object->fetch_thirdparty();
2111 $result2 = $object->fetchProject();
2112 $result3 = $object->fetch_contact();
2113 $result4 = $object->fetch_userassigned();
2114 $result5 = $object->fetch_optionals();
2115
2116 if ($listUserAssignedUpdated || $donotclearsession) {
2117 $percentage = in_array(GETPOST('status'), array(-1, 100)) ? GETPOST('status') : (in_array($complete, array(-1, 100)) ? $complete : GETPOSTINT("percentage")); // If status is -1 or 100, percentage is not defined and we must use status
2118
2119 $datep = dol_mktime($fulldayevent ? 0 : $aphour, $fulldayevent ? 0 : $apmin, 0, GETPOSTINT("apmonth"), GETPOSTINT("apday"), GETPOSTINT("apyear"), 'tzuserrel');
2120 $datef = dol_mktime($fulldayevent ? 23 : $p2hour, $fulldayevent ? 59 : $p2min, $fulldayevent ? 59 : 0, GETPOSTINT("p2month"), GETPOSTINT("p2day"), GETPOSTINT("p2year"), 'tzuserrel');
2121
2122 $object->type_id = dol_getIdFromCode($db, GETPOST("actioncode", 'aZ09'), 'c_actioncomm');
2123 $object->label = GETPOST("label", "alphanohtml");
2124 $object->datep = $datep;
2125 $object->datef = $datef;
2126 $object->percentage = $percentage;
2127 $object->priority = GETPOSTINT("priority");
2128 $object->fulldayevent = GETPOST("fullday") ? 1 : 0;
2129 $object->location = GETPOST('location', "alphanohtml");
2130 $object->socid = GETPOSTINT("socid");
2131 $socpeopleassigned = GETPOST("socpeopleassigned", 'array');
2132 foreach ($socpeopleassigned as $tmpid) {
2133 $object->socpeopleassigned[$id] = array('id' => $tmpid);
2134 }
2135 $object->contact_id = GETPOSTINT("contactid");
2136 $object->fk_project = GETPOSTINT("projectid");
2137
2138 $object->note_private = GETPOST("note", 'restricthtml');
2139 }
2140
2141 if ($result2 < 0 || $result3 < 0 || $result4 < 0 || $result5 < 0) {
2142 dol_print_error($db, $object->error);
2143 exit;
2144 }
2145
2146
2147 /*
2148 * Show tabs
2149 */
2150
2151 $head = actions_prepare_head($object);
2152
2153 $now = dol_now();
2154 $delay_warning = getDolGlobalInt('MAIN_DELAY_ACTIONS_TODO') * 24 * 60 * 60;
2155
2156
2157 // Deletion confirmation action
2158 if ($action == 'delete') {
2159 print $form->formconfirm("card.php?id=".urlencode((string) ($id)), $langs->trans("DeleteAction"), $langs->trans("ConfirmDeleteAction"), "confirm_delete", '', '', 1);
2160 }
2161
2162 if ($action == 'edit') {
2163 $caneditdateorowner = ($object->type != 'systemauto');
2164
2165 if (!empty($conf->use_javascript_ajax)) {
2166 print "\n".'<script type="text/javascript">';
2167 print '$(document).ready(function () {
2168 function setdatefields()
2169 {
2170 if ($("#fullday:checked").val() == null) {
2171 $(".fulldaystarthour").removeAttr("disabled");
2172 $(".fulldaystartmin").removeAttr("disabled");
2173 $(".fulldayendhour").removeAttr("disabled");
2174 $(".fulldayendmin").removeAttr("disabled");
2175 } else {
2176 $(".fulldaystarthour").prop("disabled", true).val("00");
2177 $(".fulldaystartmin").prop("disabled", true).val("00");
2178 $(".fulldayendhour").prop("disabled", true).val("23");
2179 $(".fulldayendmin").prop("disabled", true).val("59");
2180 }
2181 }
2182
2183 '.($caneditdateorowner ? ' setdatefields();' : '').'
2184
2185 $("#fullday").change(function() {
2186 setdatefields();
2187 });
2188 var old_startdate = null;
2189 $("#ap").focus(function() {
2190 old_startdate = new Date($("#apyear").val(), $("#apmonth").val() - 1, $("#apday").val());
2191 });
2192 $("#ap").next(".ui-datepicker-trigger").click(function() {
2193 old_startdate = new Date($("#apyear").val(), $("#apmonth").val() - 1, $("#apday").val());
2194 });
2195 $("#ap").change(function() {
2196 setTimeout(function() {
2197 if ($("#p2").val() !== "") {
2198 var new_startdate = new Date($("#apyear").val(), $("#apmonth").val() - 1, $("#apday").val());
2199 var old_enddate = new Date($("#p2year").val(), $("#p2month").val() - 1, $("#p2day").val());
2200 if (new_startdate > old_enddate) {
2201 var timeDiff = old_enddate - old_startdate;
2202 var new_enddate = new Date(new_startdate.getTime() + timeDiff);
2203 $("#p2").val(formatDate(new_enddate, "' . $langs->trans('FormatDateShortJavaInput') . '"));
2204 $("#p2day").val(new_enddate.getDate());
2205 $("#p2month").val(new_enddate.getMonth() + 1);
2206 $("#p2year").val(new_enddate.getFullYear());
2207 }
2208 }
2209 }, 0);
2210 });
2211 $("#actioncode").change(function() {
2212 if ($("#actioncode").val() == \'AC_RDV\') $("#dateend").addClass("fieldrequired");
2213 else $("#dateend").removeClass("fieldrequired");
2214 });
2215 })';
2216 print '</script>'."\n";
2217 }
2218
2219 print '<form name="formaction" action="'.$_SERVER['PHP_SELF'].'" method="POST">';
2220 print '<input type="hidden" name="token" value="'.newToken().'">';
2221 print '<input type="hidden" name="action" value="update">';
2222 print '<input type="hidden" name="id" value="'.$id.'">';
2223 print '<input type="hidden" name="ref_ext" value="'.$object->ref_ext.'">';
2224 print '<input type="hidden" name="page_y" value="">';
2225 if ($backtopage) {
2226 print '<input type="hidden" name="backtopage" value="'.($backtopage != '1' ? $backtopage : '').'">';
2227 }
2228 if (!getDolGlobalString('AGENDA_USE_EVENT_TYPE') && ! preg_match('/^TICKET_MSG_PRIVATE/', $object->code)) {
2229 print '<input type="hidden" name="actioncode" value="'.$object->type_code.'">';
2230 }
2231
2232 print dol_get_fiche_head($head, 'card', $langs->trans("Action"), 0, 'action');
2233
2234 print '<table class="border tableforfield centpercent">';
2235
2236 // Ref
2237 print '<tr><td class="titlefieldcreate">'.$langs->trans("Ref").'</td><td>'.$object->id.'</td></tr>';
2238
2239 // Title
2240 print '<tr><td class="fieldrequired'.(!getDolGlobalString('AGENDA_USE_EVENT_TYPE') ? ' titlefieldcreate' : '').'">'.$langs->trans("Title").'</td><td><input type="text" name="label" class="soixantepercent" value="'.$object->label.'"></td></tr>';
2241
2242 // Type of event
2243 if (getDolGlobalString('AGENDA_USE_EVENT_TYPE') && $object->elementtype != "ticket") {
2244 print '<tr><td class="fieldrequired">'.$langs->trans("Type").'</td><td>';
2245 if ($object->type_code != 'AC_OTH_AUTO') {
2246 print img_picto($langs->trans("ActionType"), 'square', 'class="fawidth30 inline-block" style="color: #ddd;"');
2247 print $formactions->select_type_actions(GETPOST("actioncode", 'aZ09') ? GETPOST("actioncode", 'aZ09') : $object->type_code, "actioncode", "systemauto", 0, 0, 0, 1);
2248 } else {
2249 print '<input type="hidden" name="actioncode" value="'.$object->type_code.'">';
2250 print $object->getTypePicto();
2251 print $langs->trans("Action".$object->type_code);
2252 }
2253 print '</td></tr>';
2254 }
2255
2256 // Private
2257 if ($object->elementtype == 'ticket') {
2258 print '<tr><td>'.$langs->trans("MarkMessageAsPrivate");
2259 print ' '.$form->textwithpicto('', $langs->trans("TicketMessagePrivateHelp"), 1, 'help');
2260 print '</td><td><input type="checkbox" id="private" name="private" '.(preg_match('/^TICKET_MSG_PRIVATE/', $object->code) ? ' checked' : '').'></td></tr>';
2261 }
2262
2263 // Full day event
2264 print '<tr><td><span class="fieldrequired">'.$langs->trans("Date").'</span></td><td class="valignmiddle height30 small">';
2265 print '<input '.($caneditdateorowner ? '' : ' disabled').' type="checkbox" id="fullday" name="fullday" '.($object->fulldayevent ? ' checked' : '').'>';
2266 print '<label for="fullday">'.$langs->trans("EventOnFullDay").'</label>';
2267
2268 // // Recurring event
2269 // $userepeatevent = (getDolGlobalInt('MAIN_DISABLE_RECURRING_EVENTS') ? 0 : 1);
2270 // if ($userepeatevent) {
2271 // // Repeat
2272 // //print '<tr><td></td><td colspan="3">';
2273 // print ' &nbsp; &nbsp; &nbsp; &nbsp; <div class="opacitymedium inline-block">';
2274 // print img_picto($langs->trans("Recurrence"), 'recurring', 'class="paddingright2"');
2275 // print '<input type="hidden" name="recurid" value="'.$object->recurid.'">';
2276 // $selectedrecurrulefreq = 'no';
2277 // $selectedrecurrulebymonthday = '';
2278 // $selectedrecurrulebyday = '';
2279 // if ($object->recurrule && preg_match('/FREQ=([A-Z]+)/i', $object->recurrule, $reg)) {
2280 // $selectedrecurrulefreq = $reg[1];
2281 // }
2282 // if ($object->recurrule && preg_match('/FREQ=MONTHLY.*BYMONTHDAY=(\d+)/i', $object->recurrule, $reg)) {
2283 // $selectedrecurrulebymonthday = $reg[1];
2284 // }
2285 // if ($object->recurrule && preg_match('/FREQ=WEEKLY.*BYDAY(\d+)/i', $object->recurrule, $reg)) {
2286 // $selectedrecurrulebyday = $reg[1];
2287 // }
2288 // print $form->selectarray('recurrulefreq', $arrayrecurrulefreq, $selectedrecurrulefreq, 0, 0, 0, '', 0, 0, 0, '', 'marginrightonly');
2289 // // If recurrulefreq is MONTHLY
2290 // print '<div class="hidden marginrightonly inline-block repeateventBYMONTHDAY">';
2291 // print $langs->trans("DayOfMonth").': <input type="input" size="2" name="BYMONTHDAY" value="'.$selectedrecurrulebymonthday.'">';
2292 // print '</div>';
2293 // // If recurrulefreq is WEEKLY
2294 // print '<div class="hidden marginrightonly inline-block repeateventBYDAY">';
2295 // print $langs->trans("DayOfWeek").': <input type="input" size="4" name="BYDAY" value="'.$selectedrecurrulebyday.'">';
2296 // print '</div>';
2297 // print '<script type="text/javascript">
2298 // jQuery(document).ready(function() {
2299 // function init_repeat()
2300 // {
2301 // if (jQuery("#recurrulefreq").val() == \'MONTHLY\')
2302 // {
2303 // jQuery(".repeateventBYMONTHDAY").css("display", "inline-block"); /* use this instead of show because we want inline-block and not block */
2304 // jQuery(".repeateventBYDAY").hide();
2305 // }
2306 // else if (jQuery("#recurrulefreq").val() == \'WEEKLY\')
2307 // {
2308 // jQuery(".repeateventBYMONTHDAY").hide();
2309 // jQuery(".repeateventBYDAY").css("display", "inline-block"); /* use this instead of show because we want inline-block and not block */
2310 // }
2311 // else
2312 // {
2313 // jQuery(".repeateventBYMONTHDAY").hide();
2314 // jQuery(".repeateventBYDAY").hide();
2315 // }
2316 // }
2317 // init_repeat();
2318 // jQuery("#recurrulefreq").change(function() {
2319 // init_repeat();
2320 // });
2321 // });
2322 // </script>';
2323 // print '</div>';
2324 // //print '</td></tr>';
2325 // }
2326 print '</td></tr>';
2327
2328 // Date start - end
2329 print '<tr><td class="nowrap">';
2330 print '</td><td>';
2331 $tzforfullday = getDolGlobalString('MAIN_STORE_FULL_EVENT_IN_GMT');
2332 print $form->selectDate($datep ? $datep : $object->datep, 'ap', 1, 1, 0, "action", 1, 2, ($caneditdateorowner ? 0 : 1), 'fulldaystart', '', '', '', 1, '', '', $object->fulldayevent ? ($tzforfullday ? $tzforfullday : 'tzuserrel') : 'tzuserrel');
2333 print ' <span class="hideonsmartphone">&nbsp; &nbsp; - &nbsp; &nbsp;</span> ';
2334 print $form->selectDate($datef ? $datef : $object->datef, 'p2', 1, 1, 1, "action", 1, 2, ($caneditdateorowner ? 0 : 1), 'fulldayend', '', '', '', 1, '', '', $object->fulldayevent ? ($tzforfullday ? $tzforfullday : 'tzuserrel') : 'tzuserrel');
2335 print '</td></tr>';
2336
2337 // Location
2338 if (!getDolGlobalString('AGENDA_DISABLE_LOCATION')) {
2339 print '<tr><td>'.$langs->trans("Location").'</td><td>';
2340 print img_picto('', 'map-marker-alt', 'class="pictofixedwidth"');
2341 print '<input type="text" name="location" class="minwidth300 maxwidth150onsmartphone" value="'.$object->location.'"></td></tr>';
2342 }
2343
2344 print '<tr class="tdsmallheight"><td class="tdsmallheight">&nbsp;</td><td class="tdsmallheight"></td></tr>';
2345
2346 // Assigned to
2347 $listofuserid = []; // User assigned
2348 if (empty($donotclearsession)) {
2349 if ($object->userownerid > 0) {
2350 $listofuserid[$object->userownerid] = array(
2351 'id' => $object->userownerid,
2352 'type' => 'user',
2353 //'transparency'=>$object->userassigned[$user->id]['transparency'],
2354 'transparency' => $object->transparency, // Force transparency on ownerfrom event
2355 'answer_status' => (isset($object->userassigned[$object->userownerid]['answer_status']) ? $object->userassigned[$object->userownerid]['answer_status'] : null),
2356 'mandatory' => (isset($object->userassigned[$object->userownerid]['mandatory']) ? $object->userassigned[$object->userownerid]['mandatory'] : null)
2357 );
2358 }
2359 if (!empty($object->userassigned)) { // Now concat assigned users
2360 // Restore array with key with same value than param 'id'
2361 $tmplist1 = $object->userassigned;
2362 foreach ($tmplist1 as $key => $val) {
2363 if ($val['id'] && $val['id'] != $object->userownerid) {
2364 $listofuserid[$val['id']] = $val;
2365 }
2366 }
2367 }
2368 $_SESSION[$sessionkeyassignedtouser] = json_encode($listofuserid);
2369 } else {
2370 if (!empty($_SESSION[$sessionkeyassignedtouser])) {
2371 $listofuserid = json_decode($_SESSION[$sessionkeyassignedtouser], true);
2372 }
2373 }
2374
2375 $listofcontactid = $object->socpeopleassigned; // Contact assigned
2376 $listofotherid = $object->otherassigned; // Other undefined email (not used yet)
2377
2378 print '<tr><td class="nowrap fieldrequired">'.$langs->trans("ActionAssignedTo").'</td><td>';
2379 print '<div class="assignedtouser">';
2380 print $form->select_dolusers_forevent(($action == 'create' ? 'add' : 'update'), 'assignedtouser', 1, [], 0, '', [], '0', 0, 0, 'u.statut:<>:0', 1, $listofuserid, $listofcontactid, $listofotherid, (int) $caneditdateorowner);
2381 print '</div>';
2382 /*if (in_array($user->id,array_keys($listofuserid)))
2383 {
2384 print '<div class="myavailability">';
2385 print $langs->trans("MyAvailability").': <input id="transparency" type="checkbox" name="transparency"'.($listofuserid[$user->id]['transparency']?' checked':'').'>'.$langs->trans("Busy");
2386 print '</div>';
2387 }*/
2388 print '</td></tr>';
2389
2390 // Tags-Categories
2391 if (isModEnabled('category')) {
2392 print '<tr><td>'.$langs->trans("Categories").'</td><td>';
2393 print $form->selectCategories(Categorie::TYPE_ACTIONCOMM, 'categories', $object);
2394 print "</td></tr>";
2395 }
2396
2397 print '</table>';
2398
2399
2400 print '<br>';
2401
2402
2403 print '<table class="border tableforfield centpercent">';
2404
2405 // Status
2406 print '<tr><td class="nowrap">'.$langs->trans("Status").' / '.$langs->trans("Progression").'</td><td colspan="3">';
2407 $percent = GETPOSTISSET("percentage") ? GETPOSTINT("percentage") : $object->percentage;
2408 $formactions->form_select_status_action('formaction', (string) $percent, 1, 'complete', 0, 0, 'minwidth150 maxwidth300');
2409 print '</td></tr>';
2410
2411 if (isModEnabled("societe")) {
2412 // Related company
2413 print '<tr><td class="titlefieldcreate">'.$langs->trans("ActionOnCompany").'</td>';
2414 print '<td>';
2415 print '<div>';
2416 $events = []; // 'method'=parameter action of url, 'url'=url to call that return new list of contacts
2417 $events[] = array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php?showempty=1&token='.currentToken(), 1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled'));
2418 // TODO Refresh also list of project if conf PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY not defined with list linked to socid ?
2419 // FIXME If we change company, we may get a project that does not match
2420 print img_picto('', 'company', 'class="pictofixedwidth"').$form->select_company($object->socid, 'socid', '', 'SelectThirdParty', 1, 0, $events, 0, 'minwidth300');
2421 print '</div>';
2422 print '</td></tr>';
2423
2424 // Related contact
2425 print '<tr><td>'.$langs->trans("ActionOnContact").'</td><td>';
2426 print '<div class="maxwidth200onsmartphone">';
2427
2428 print img_picto('', 'contact', 'class="paddingrightonly"');
2429 if (getDolGlobalString('CONTACT_USE_SEARCH_TO_SELECT') && $conf->use_javascript_ajax) {
2430 // FIXME Use the select_contact supporting the "multiple"
2431 /*
2432 $selected = array_keys($object->socpeopleassigned);
2433 print $form->select_contact(getDolGlobalString('MAIN_ACTIONCOM_CAN_ADD_ANY_CONTACT') ? 0 : $object->socid, $selected, 'socpeopleassigned', 1, '', '', 1, 'minwidth300 widthcentpercentminusx', false, 0, 0, []);
2434 */
2435 $sav = getDolGlobalString('CONTACT_USE_SEARCH_TO_SELECT');
2436 $conf->global->CONTACT_USE_SEARCH_TO_SELECT = 0;
2437 print $form->selectcontacts(getDolGlobalString('MAIN_ACTIONCOM_CAN_ADD_ANY_CONTACT') ? 0 : ($object->socid > 0 ? $object->socid : -1), array_keys($object->socpeopleassigned), 'socpeopleassigned[]', 1, '', '', 1, 'minwidth300 widthcentpercentminusx', 0, 0, 0, [], 'multiple', 'contactid');
2438 $conf->global->CONTACT_USE_SEARCH_TO_SELECT = $sav;
2439 } else {
2440 // Warning: MAIN_ACTIONCOM_CAN_ADD_ANY_CONTACT will hangs on large databases
2441 print $form->selectcontacts(getDolGlobalString('MAIN_ACTIONCOM_CAN_ADD_ANY_CONTACT') ? 0 : $object->socid, array_keys($object->socpeopleassigned), 'socpeopleassigned[]', 1, '', '', 1, 'minwidth300 widthcentpercentminusx', 0, 0, 0, [], 'multiple', 'contactid');
2442 }
2443 print '</div>';
2444 print '</td>';
2445 print '</tr>';
2446 }
2447
2448 // Project
2449 if (isModEnabled('project')) {
2450 $langs->load("projects");
2451
2452 print '<tr><td class="titlefieldcreate">'.$langs->trans("Project").'</td><td>';
2453 print img_picto('', 'project', 'class="pictofixedwidth"');
2454 $numprojet = $formproject->select_projects(($object->socid > 0 ? $object->socid : -1), (string) $object->fk_project, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0, 0, 'maxwidth500 widthcentpercentminusxx');
2455 if ($numprojet == 0) {
2456 print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$object->socid.'&action=create&token='.newToken().'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddProject").'"></span></a>';
2457 }
2458 print '</td></tr>';
2459 }
2460
2461 // Priority
2462 if (getDolGlobalString('AGENDA_SUPPORT_PRIORITY_IN_EVENTS')) {
2463 print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("Priority").'</td><td>';
2464 print '<input type="text" name="priority" value="'.($object->priority ? $object->priority : '').'" size="5">';
2465 print '</td></tr>';
2466 }
2467
2468 // Object linked
2469 if ($object->fk_project || (!empty($object->elementid) && !empty($object->elementtype))) {
2470 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
2471 print '<tr>';
2472 print '<td>'.$langs->trans("LinkedObject").'</td>';
2473
2474 if ($object->elementtype == 'project_task' && isModEnabled('project')) {
2475 print '<td id="project-task-input-container" >';
2476
2477 $urloption = '?action=create&donotclearsession=1'; // we use create not edit for more flexibility
2478 $url = DOL_URL_ROOT.'/comm/action/card.php'.$urloption;
2479
2480 // update task list
2481 ?>
2482 <script type="text/javascript" >
2483 $(document).ready(function () {
2484 $("#projectid").change(function () {
2485 var url = "<?php echo $url; ?>&projectid="+$("#projectid").val();
2486 $.get(url, function(data) {
2487 console.log($( data ).find("#fk_element").html());
2488 if (data) $("#fk_element").html( $( data ).find("#taskid").html() ).select2();
2489 })
2490 });
2491 });
2492 </script>
2493 <?php
2494
2495 print $formproject->selectTasks((!empty($societe->id) ? $societe->id : -1), $object->elementid, 'fk_element', 64, 0, '', 1, 0, 0, 'maxwidth500', (string) $object->fk_project, 'all', null, 1);
2496 print '<input type="hidden" name="elementtype" value="'.$object->elementtype.'">';
2497
2498 print '</td>';
2499 } else {
2500 if (empty($object->elementtype) && empty($object->elementid) && $object->fk_project) {
2501 $projectsListId = GETPOSTINT('projectid') ? GETPOSTINT('projectid') : $object->fk_project;
2502
2503 print '<td id="project-task-input-container" >';
2504
2505 // update task list
2506 ?>
2507 <script type="text/javascript">
2508 $(document).ready(function () {
2509 $("#projectid").change(function () {
2510 var url = "<?php echo DOL_URL_ROOT; ?>/projet/ajax/projects.php?mode=gettasks&socid="+$("#search_socid").val()+"&projectid="+$("#projectid").val();
2511 console.log("Call url to get new list of tasks: "+url);
2512 $.get(url, function(data) {
2513 console.log(data);
2514 if (data) $("#taskid").html(data).select2();
2515 })
2516 });
2517 });
2518 </script>
2519 <?php
2520
2521 $tid = '';
2522 if (GETPOSTISSET("projecttaskid") && GETPOSTINT("projecttaskid") > 0) {
2523 $tid = GETPOSTINT("projecttaskid");
2524 } elseif (GETPOSTISSET("taskid") && GETPOSTINT("taskid") > 0) {
2525 $tid = GETPOSTINT("taskid");
2526 }
2527
2528 print $formproject->selectTasks((!empty($societe->id) ? $societe->id : -1), $tid, 'taskid', 64, 0, '1', 1, 0, 0, 'maxwidth500 widthcentpercentminusxx', (string) $projectsListId, 'all', null, 1);
2529
2530 print '</td>';
2531 } else {
2532 print '<td>';
2533 print dolGetElementUrl($object->elementid, $object->elementtype, 1);
2534 print '<input type="hidden" name="fk_element" value="'.$object->elementid.'">';
2535 print '<input type="hidden" name="elementtype" value="'.$object->elementtype.'">';
2536 print '</td>';
2537 }
2538 }
2539
2540 print '</tr>';
2541 }
2542
2543 // Description
2544 print '<tr><td class="tdtop">'.$langs->trans("Description").'</td><td>';
2545 // Wysiwyg editor
2546 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
2547 $doleditor = new DolEditor('note', $object->note_private, '', 200, 'dolibarr_notes', 'In', true, true, isModEnabled('fckeditor'), ROWS_4, '90%');
2548 $doleditor->Create();
2549 print '</td></tr>';
2550
2551 // Other attributes
2552 $parameters = [];
2553 $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2554 print $hookmanager->resPrint;
2555 if (empty($reshook)) {
2556 print $object->showOptionals($extrafields, 'edit', $parameters);
2557 }
2558
2559 print '</table>';
2560
2561 // Reminders
2562 if ($enablereminders) {
2563 $filteruserid = $user->id;
2564 if ($user->hasRight('agenda', 'allactions', 'read')) {
2565 $filteruserid = 0;
2566 }
2567 $object->loadReminders('', $filteruserid, false);
2568
2569 print '<hr>';
2570
2571 if (count($object->reminders) > 0) {
2572 $checked = 'checked';
2573 $keys = array_keys($object->reminders);
2574 $firstreminderId = array_shift($keys);
2575
2576 $actionCommReminder = $object->reminders[$firstreminderId];
2577 } else {
2578 $checked = '';
2579 $actionCommReminder = new ActionCommReminder($db);
2580 $actionCommReminder->offsetvalue = getDolGlobalInt('AGENDA_REMINDER_DEFAULT_OFFSET', 30);
2581 $actionCommReminder->offsetunit = 'i';
2582 $actionCommReminder->typeremind = 'email';
2583 }
2584 $disabled = '';
2585 /*
2586 if ($object->datep < dol_now()) {
2587 //$disabled = 'disabled title="'.dol_escape_htmltag($langs->trans("EventExpired")).'"';
2588 }
2589 */
2590
2591 print '<label for="addreminder">'.img_picto('', 'bell', 'class="pictofixedwidth"').$langs->trans("AddReminder").'</label> <input type="checkbox" id="addreminder" name="addreminder"'.($checked ? ' '.$checked : '').($disabled ? ' '.$disabled : '').'><br>';
2592
2593 print '<div class="reminderparameters" '.(empty($checked) ? 'style="display: none;"' : '').'>';
2594
2595 print '<br>';
2596
2597 print '<table class="border centpercent">';
2598
2599 // Reminder
2600 print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("ReminderTime").'</td><td colspan="3">';
2601 print '<input type="number" name="offsetvalue" class="width50" value="'.$actionCommReminder->offsetvalue.'"> ';
2602 print $form->selectTypeDuration('offsetunit', $actionCommReminder->offsetunit, $TDurationTypesExcluded);
2603 print '</td></tr>';
2604
2605 // Reminder Type
2606 print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("ReminderType").'</td><td colspan="3">';
2607 print $form->selectarray('selectremindertype', $TRemindTypes, $actionCommReminder->typeremind, 0, 0, 0, '', 0, 0, 0, '', 'minwidth200', 1);
2608 print '</td></tr>';
2609
2610 $hide = '';
2611 if ($actionCommReminder->typeremind == 'browser') {
2612 $hide = 'style="display:none;"';
2613 }
2614
2615 // Mail Model
2616 if (getDolGlobalString('AGENDA_REMINDER_EMAIL')) {
2617 print '<tr '.$hide.'><td class="titlefieldcreate nowrap">'.$langs->trans("EMailTemplates").'</td><td colspan="3">';
2618 print $form->selectModelMail('actioncommsend', 'actioncomm_send', 1, 1, (string) $actionCommReminder->fk_email_template);
2619 print '</td></tr>';
2620 }
2621
2622 print '</table>';
2623 ?>
2624 <script type="text/javascript">
2625 $(document).ready(function () {
2626 $("#addreminder").click(function(){
2627 if (this.checked) {
2628 $(".reminderparameters").show();
2629 } else {
2630 $(".reminderparameters").hide();
2631 }
2632 });
2633 $("#selectremindertype").change(function(){
2634 var selected_option = $("#selectremindertype option:selected").val();
2635 if(selected_option == "email") {
2636 $("#select_actioncommsendmodel_mail").closest("tr").show();
2637 } else {
2638 $("#select_actioncommsendmodel_mail").closest("tr").hide();
2639 }
2640 });
2641 });
2642 </script>
2643 <?php
2644
2645 $reminderDefaultEventTypes = getDolGlobalString('AGENDA_DEFAULT_REMINDER_EVENT_TYPES', '');
2646 $reminderDefaultOffset = getDolGlobalString('AGENDA_DEFAULT_REMINDER_OFFSET', 30);
2647 $reminderDefaultUnit = getDolGlobalString('AGENDA_DEFAULT_REMINDER_OFFSET_UNIT');
2648 $reminderDefaultEmailModel = getDolGlobalString('AGENDA_DEFAULT_REMINDER_EMAIL_MODEL');
2649
2650 print "\n".'<script type="text/javascript">';
2651 print '$(document).ready(function () {
2652 const reminderDefaultEventTypes = \''.dol_escape_js($reminderDefaultEventTypes).'\';
2653 $("#actioncode").change(function(){
2654 var selected_event_type = $("#actioncode option:selected").val();
2655
2656 if (reminderDefaultEventTypes.includes(selected_event_type)) {
2657 $(".reminderparameters").show();
2658 $("#addreminder").prop("checked", true);
2659
2660 // Set period with default reminder period
2661 $("#offsetvalue").val(\''.dol_escape_js($reminderDefaultOffset).'\');
2662 $("#select_offsetunittype_duration").select2("destroy");
2663 $("#select_offsetunittype_duration").val(\''.dol_escape_js($reminderDefaultUnit).'\');
2664 $("#select_offsetunittype_duration").select2();
2665
2666 $("#selectremindertype").select2("destroy");
2667 $("#selectremindertype").val("email");
2668 $("#selectremindertype").select2();
2669
2670 // Set default reminder mail model
2671 $("#select_actioncommsendmodel_mail").closest("tr").show();
2672 $("#select_actioncommsendmodel_mail").select2("destroy");
2673 $("#select_actioncommsendmodel_mail").val(\''.dol_escape_js($reminderDefaultEmailModel).'\');
2674 $("#select_actioncommsendmodel_mail").select2();
2675 }
2676 });
2677 })';
2678 print '</script>'."\n";
2679 print '</div>'; // End of div for reminderparameters
2680 }
2681
2682 print dol_get_fiche_end();
2683
2684 print $form->buttonsSaveCancel();
2685
2686 print '</form>';
2687 } else {
2688 print dol_get_fiche_head($head, 'card', $langs->trans("Action"), -1, 'action');
2689
2690 $formconfirm = '';
2691
2692 // Clone event
2693 if ($action == 'clone') {
2694 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.GETPOST('id'), $langs->trans('ToClone'), $langs->trans('ConfirmCloneEvent', $object->label), 'confirm_clone', [], 'yes', 1);
2695 }
2696
2697 // Call Hook formConfirm
2698 $parameters = [];
2699 $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2700 if (empty($reshook)) {
2701 $formconfirm .= $hookmanager->resPrint;
2702 } elseif ($reshook > 0) {
2703 $formconfirm = $hookmanager->resPrint;
2704 }
2705
2706 // Print form confirm
2707 print $formconfirm;
2708
2709 $linkback = '';
2710 // Link to other agenda views
2711 $linkback .= '<a href="'.DOL_URL_ROOT.'/comm/action/list.php?mode=show_list&restore_lastsearch_values=1">';
2712 $linkback .= img_picto($langs->trans("BackToList"), 'object_calendarlist', 'class="pictoactionview pictofixedwidth"');
2713 $linkback .= '<span class="hideonsmartphone">'.$langs->trans("BackToList").'</span>';
2714 $linkback .= '</a>';
2715 $linkback .= '</li>';
2716 $linkback .= '<li class="noborder litext">';
2717 $linkback .= '<a href="'.DOL_URL_ROOT.'/comm/action/index.php?mode=show_month&year='.dol_print_date($object->datep, '%Y').'&month='.dol_print_date($object->datep, '%m').'&day='.dol_print_date($object->datep, '%d').'">';
2718 $linkback .= img_picto($langs->trans("ViewCal"), 'object_calendar', 'class="pictoactionview pictofixedwidth"');
2719 $linkback .= '<span class="hideonsmartphone">'.$langs->trans("ViewCal").'</span>';
2720 $linkback .= '</a>';
2721 $linkback .= '</li>';
2722 $linkback .= '<li class="noborder litext">';
2723 $linkback .= '<a href="'.DOL_URL_ROOT.'/comm/action/index.php?mode=show_week&year='.dol_print_date($object->datep, '%Y').'&month='.dol_print_date($object->datep, '%m').'&day='.dol_print_date($object->datep, '%d').'">';
2724 $linkback .= img_picto($langs->trans("ViewWeek"), 'object_calendarweek', 'class="pictoactionview pictofixedwidth"');
2725 $linkback .= '<span class="hideonsmartphone">'.$langs->trans("ViewWeek").'</span>';
2726 $linkback .= '</a>';
2727 $linkback .= '</li>';
2728 $linkback .= '<li class="noborder litext">';
2729 $linkback .= '<a href="'.DOL_URL_ROOT.'/comm/action/index.php?mode=show_day&year='.dol_print_date($object->datep, '%Y').'&month='.dol_print_date($object->datep, '%m').'&day='.dol_print_date($object->datep, '%d').'">';
2730 $linkback .= img_picto($langs->trans("ViewDay"), 'object_calendarday', 'class="pictoactionview pictofixedwidth"');
2731 $linkback .= '<span class="hideonsmartphone">'.$langs->trans("ViewDay").'</span>';
2732 $linkback .= '</a>';
2733 $linkback .= '</li>';
2734 $linkback .= '<li class="noborder litext">';
2735 $linkback .= '<a href="'.DOL_URL_ROOT.'/comm/action/peruser.php?mode=show_peruser&year='.dol_print_date($object->datep, '%Y').'&month='.dol_print_date($object->datep, '%m').'&day='.dol_print_date($object->datep, '%d').'">';
2736 $linkback .= img_picto($langs->trans("ViewPerUser"), 'object_calendarperuser', 'class="pictoactionview pictofixedwidth"');
2737 $linkback .= '<span class="hideonsmartphone">'.$langs->trans("ViewPerUser").'</span>';
2738 $linkback .= '</a>';
2739
2740 // Add more views from hooks
2741 $parameters = [];
2742 $reshook = $hookmanager->executeHooks('addCalendarView', $parameters, $object, $action);
2743 if (empty($reshook)) {
2744 $linkback .= $hookmanager->resPrint;
2745 } elseif ($reshook > 1) {
2746 $linkback = $hookmanager->resPrint;
2747 }
2748
2749 //$linkback.=$out;
2750
2751 $morehtmlref = '<div class="refidno">';
2752 // Thirdparty
2753 //$morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
2754 // Project
2755 if (isModEnabled('project')) {
2756 $langs->load("projects");
2757 //$morehtmlref .= '<br>';
2758 if ($usercancreate) {
2759 $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
2760 if ($action != 'classify') {
2761 $morehtmlref .= '<a class="editfielda" href="'.dolBuildUrl($_SERVER['PHP_SELF'], ['action' => 'classify', 'id' => $object->id], true).'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> ';
2762 }
2763 $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, (string) $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
2764 } else {
2765 if (!empty($object->fk_project)) {
2766 $proj = new Project($db);
2767 $proj->fetch($object->fk_project);
2768 $morehtmlref .= $proj->getNomUrl(1);
2769 if ($proj->title) {
2770 $morehtmlref .= '<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).'</span>';
2771 }
2772 }
2773 }
2774 }
2775 $morehtmlref .= '</div>';
2776
2777
2778 dol_banner_tab($object, 'id', $linkback, ($user->socid ? 0 : 1), 'id', 'ref', $morehtmlref);
2779
2780 print '<div class="fichecenter">';
2781 print '<div class="fichehalfleft">';
2782
2783 print '<div class="underbanner clearboth"></div>';
2784
2785 // Show event in view mode
2786 print '<table class="border tableforfield centpercent">';
2787
2788 // Type
2789 if (getDolGlobalString('AGENDA_USE_EVENT_TYPE')) {
2790 print '<tr><td class="titlefieldmiddle">'.$langs->trans("Type").'</td><td>';
2791 $labeltype = ($langs->transnoentities("Action".$object->type_code) != "Action".$object->type_code) ? $langs->transnoentities("Action".$object->type_code) : $object->type_label;
2792 $labeltoshow = $labeltype;
2793 if ($object->code) {
2794 $labeltoshow .= ' ('.$object->code.')';
2795 }
2796 print $object->getTypePicto('pictofixedwidth paddingright', $labeltoshow);
2797 print $labeltype;
2798 print '</td></tr>';
2799 }
2800
2801 // Full day event
2802 print '<tr><td class="titlefieldmiddle">'.$langs->trans("EventOnFullDay").'</td><td>'.yn($object->fulldayevent ? 1 : 0, 3).'</td></tr>';
2803
2804 $rowspan = 4;
2805 if (!getDolGlobalString('AGENDA_DISABLE_LOCATION')) {
2806 $rowspan++;
2807 }
2808
2809 // Date start
2810 print '<tr><td>'.$langs->trans("DateActionStart").'</td><td title="'.dol_print_date($object->datep, 'dayhoursec', 'tzuserrel').'">';
2811 // Test a date before the 27 march and one after
2812 //print dol_print_date($object->datep, 'dayhour', 'gmt');
2813 //print dol_print_date($object->datep, 'dayhour', 'tzuser');
2814 //print dol_print_date($object->datep, 'dayhour', 'tzuserrel');
2815 if (empty($object->fulldayevent)) {
2816 print dol_print_date($object->datep, 'dayhour', 'tzuserrel');
2817 } else {
2818 $tzforfullday = getDolGlobalString('MAIN_STORE_FULL_EVENT_IN_GMT');
2819 print dol_print_date($object->datep, 'day', ($tzforfullday ? $tzforfullday : 'tzuserrel'));
2820 }
2821 if ($object->percentage == 0 && $object->datep && $object->datep < ($now - $delay_warning)) {
2822 print img_warning($langs->trans("Late"));
2823 }
2824 print '</td>';
2825 print '</tr>';
2826
2827 // Date end
2828 print '<tr><td>'.$langs->trans("DateActionEnd").'</td><td title="'.dol_print_date($object->datef, 'dayhoursec', 'tzuserrel').'">';
2829 if (empty($object->fulldayevent)) {
2830 print dol_print_date($object->datef, 'dayhour', 'tzuserrel');
2831 } else {
2832 $tzforfullday = getDolGlobalString('MAIN_STORE_FULL_EVENT_IN_GMT');
2833 print dol_print_date($object->datef, 'day', ($tzforfullday ? $tzforfullday : 'tzuserrel'));
2834 }
2835 if ($object->percentage > 0 && $object->percentage < 100 && $object->datef && $object->datef < ($now - $delay_warning)) {
2836 print img_warning($langs->trans("Late"));
2837 }
2838 print '</td></tr>';
2839
2840 // Recurring event (into a series)
2841 if ($object->recurid) {
2842 print '<tr><td class="titlefieldmiddle">'.$langs->trans("RecurringEvent").'</td><td>';
2843 print img_picto($langs->trans("EventPartOfARecurringSerie", $object->recurid), 'recurring', 'class="pictofixedwidth"');
2844 $reg = [];
2845 if (preg_match('/FREQ=MONTHLY_BYMONTHDAY(\d+)/', $object->recurrule, $reg)) {
2846 print $langs->trans("EveryMonth").' <span class="opacitymedium small">('.$langs->trans("DayOfMonth").' '.$reg[1].' - '.$langs->trans("Until").' '.dol_print_date($object->recurdateend, 'day').')</span>';
2847 }
2848 if (preg_match('/FREQ=YEARLY_BYYEARMONTHDAY(\d+)/', $object->recurrule, $reg)) {
2849 print $langs->trans("EveryYear").' <span class="opacitymedium small">('.$langs->trans("DayOfYear").' '.$reg[1].' - '.$langs->trans("Until").' '.dol_print_date($object->recurdateend, 'day').')</span>';
2850 }
2851 print '</td></tr>';
2852 }
2853
2854 // Location
2855 if (!getDolGlobalString('AGENDA_DISABLE_LOCATION')) {
2856 print '<tr><td>'.$langs->trans("Location").'</td><td>'.$object->location.'</td></tr>';
2857 }
2858
2859 // Assigned to user
2860 print '<tr><td class="nowrap">'.$langs->trans("ActionAssignedTo").'</td><td>';
2861 $listofuserid = [];
2862 if (empty($donotclearsession)) {
2863 if ($object->userownerid > 0) {
2864 $listofuserid[$object->userownerid] = array(
2865 'id' => $object->userownerid,
2866 'transparency' => $object->transparency, // Force transparency on owner from property of event
2867 'answer_status' => $object->userassigned[$object->userownerid]['answer_status'],
2868 'mandatory' => $object->userassigned[$object->userownerid]['mandatory']
2869 );
2870 }
2871 if (!empty($object->userassigned)) { // Now concat assigned users
2872 // Restore array with key with same value than param 'id'
2873 $tmplist1 = $object->userassigned;
2874 foreach ($tmplist1 as $key => $val) {
2875 if ($val['id'] && $val['id'] != $object->userownerid) {
2876 $listofuserid[$val['id']] = $val;
2877 }
2878 }
2879 }
2880 $_SESSION[$sessionkeyassignedtouser] = json_encode($listofuserid);
2881 } else {
2882 if (!empty($_SESSION[$sessionkeyassignedtouser])) {
2883 $listofuserid = json_decode($_SESSION[$sessionkeyassignedtouser], true);
2884 }
2885 }
2886
2887 $listofcontactid = []; // not used yet
2888 $listofotherid = []; // not used yet
2889 print '<div class="assignedtouser">';
2890 print $form->select_dolusers_forevent('view', 'assignedtouser', 1, [], 0, '', [], '0', 0, 0, '', ($object->datep != $object->datef) ? 1 : 0, $listofuserid, $listofcontactid, $listofotherid);
2891 print '</div>';
2892 /*
2893 if ($object->datep != $object->datef && in_array($user->id,array_keys($listofuserid)))
2894 {
2895 print '<div class="myavailability">';
2896 print $langs->trans("MyAvailability").': '.(($object->userassigned[$user->id]['transparency'] > 0)?$langs->trans("Busy"):$langs->trans("Available")); // We show nothing if event is assigned to nobody
2897 print '</div>';
2898 }
2899 */
2900 print ' </td></tr>';
2901
2902 // Categories
2903 if (isModEnabled('category')) {
2904 print '<tr><td class="valignmiddle">'.$langs->trans("Categories").'</td><td>';
2905 print $form->showCategories($object->id, Categorie::TYPE_ACTIONCOMM, 1);
2906 print "</td></tr>";
2907 }
2908
2909 print '</table>';
2910
2911 print '</div>';
2912
2913 print '<div class="fichehalfright">';
2914
2915 print '<div class="underbanner clearboth"></div>';
2916 print '<table class="border tableforfield centpercent">';
2917
2918 if (isModEnabled("societe")) {
2919 // Related company
2920 print '<tr><td class="titlefield">'.$langs->trans("ActionOnCompany").'</td>';
2921 print '<td>'.(is_object($object->thirdparty) && $object->thirdparty->id ? $object->thirdparty->getNomUrl(1) : ('<span class="opacitymedium">'.$langs->trans("None").'</span>'));
2922 if (is_object($object->thirdparty) && $object->thirdparty->id > 0 && $object->type_code == 'AC_TEL') {
2923 if ($object->thirdparty->fetch($object->thirdparty->id)) {
2924 print "<br>".dol_print_phone($object->thirdparty->phone);
2925 }
2926 }
2927 print '</td></tr>';
2928
2929 // Related contact
2930 print '<tr><td>'.$langs->trans("ActionOnContact").'</td>';
2931 print '<td>';
2932
2933 if (!empty($object->socpeopleassigned)) {
2934 foreach ($object->socpeopleassigned as $cid => $Tab) {
2935 $contact = new Contact($db);
2936 $result = $contact->fetch($cid);
2937
2938 if ($result < 0) {
2939 dol_print_error($db, $contact->error);
2940 }
2941
2942 if ($result > 0) {
2943 print $contact->getNomUrl(1);
2944 if ($object->type_code == 'AC_TEL') {
2945 if (!empty($contact->phone_pro)) {
2946 print '('.dol_print_phone($contact->phone_pro).')';
2947 }
2948 }
2949 print '<div class="paddingright"></div>';
2950 }
2951 }
2952 } else {
2953 print '<span class="opacitymedium">'.$langs->trans("None").'</span>';
2954 }
2955 print '</td></tr>';
2956 }
2957
2958 // Priority
2959 if (getDolGlobalString('AGENDA_SUPPORT_PRIORITY_IN_EVENTS')) {
2960 print '<tr><td class="nowrap" class="titlefield">' . $langs->trans("Priority") . '</td><td>';
2961 print($object->priority ? $object->priority : '');
2962 print '</td></tr>';
2963 }
2964
2965 // Object linked (if link is for thirdparty, contact, project it is a recording error. We should not have links in link table
2966 // for such objects because there is already a dedicated field into table llx_actioncomm.
2967 if (!empty($object->elementid) && !empty($object->elementtype) && !in_array($object->elementtype, array('societe', 'contact', 'project'))) {
2968 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
2969 print '<tr><td>'.$langs->trans("LinkedObject").'</td>';
2970 $link = dolGetElementUrl($object->elementid, $object->elementtype, ($object->elementtype == 'user' ? -1 : 1));
2971 print '<td>';
2972 if (empty($link)) {
2973 print '<span class="opacitymedium">'.$langs->trans("ObjectDeleted").'</span>';
2974 } else {
2975 print $link;
2976 }
2977 print '</td></tr>';
2978 }
2979
2980 //mail information
2981 if (!empty($object->email_msgid)) {
2982 print '<tr><td>'.$langs->trans('MailTopic').'</td>';
2983 print '<td>'.dol_escape_htmltag($object->email_subject).'</td></tr>';
2984 print '<tr><td>'.$langs->trans('MailFrom').'</td>';
2985 print '<td>'.dol_escape_htmltag($object->email_from).'</td></tr>';
2986 print '<tr><td>'.$langs->trans('MailTo').'</td>';
2987 print '<td>'.dol_escape_htmltag($object->email_to).'</td></tr>';
2988 if (!empty($object->email_tocc)) {
2989 print '<tr><td>'.$langs->trans('MailCC').'</td>';
2990 print '<td>'.dol_escape_htmltag($object->email_tocc).'</td></tr>';
2991 }
2992 }
2993
2994 // Description
2995 print '<tr><td class="tdtop">'.$langs->trans("Description").'</td><td class="wordbreak sensiblehtmlcontent">';
2996 print dol_string_onlythesehtmltags(dol_htmlentitiesbr($object->note_private));
2997 print '</td></tr>';
2998
2999 // Other attributes
3000 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
3001
3002 // Reminders
3003 if ($enablereminders) {
3004 $filteruserid = $user->id;
3005 if ($user->hasRight('agenda', 'allactions', 'read')) {
3006 $filteruserid = 0;
3007 }
3008 $object->loadReminders('', $filteruserid, false);
3009
3010 print '<tr><td class="titlefieldcreate nowrap">'.$langs->trans("Reminders").'</td><td>';
3011
3012 if (count($object->reminders) > 0) {
3013 $tmpuserstatic = new User($db);
3014
3015 foreach ($object->reminders as $actioncommreminderid => $actioncommreminder) {
3016 print $TRemindTypes[$actioncommreminder->typeremind]['label'];
3017 if ($actioncommreminder->fk_user > 0) {
3018 $tmpuserstatic->fetch($actioncommreminder->fk_user);
3019 print ' ('.$tmpuserstatic->getNomUrl(0, '', 0, 0, 16).')';
3020 }
3021 print ' - '.$actioncommreminder->offsetvalue.' '.$TDurationTypes[$actioncommreminder->offsetunit];
3022
3023 if ($actioncommreminder->status == $actioncommreminder::STATUS_TODO) {
3024 print ' - <span class="opacitymedium">';
3025 print $langs->trans("NotSent");
3026 print ' </span>';
3027 } elseif ($actioncommreminder->status == $actioncommreminder::STATUS_DONE) {
3028 print ' - <span class="opacitymedium">';
3029 print $langs->trans("Done");
3030 print ' </span>';
3031 } elseif ($actioncommreminder->status == $actioncommreminder::STATUS_ERROR) {
3032 print ' - <span class="opacitymedium">';
3033 print $form->textwithpicto($langs->trans("Error"), $actioncommreminder->lasterror);
3034 print ' </span>';
3035 }
3036 print '<br>';
3037 }
3038 }
3039
3040 print '</td></tr>';
3041 }
3042
3043 print '</table>';
3044
3045 print '</div>';
3046 print '</div>';
3047 print '<div class="clearboth"></div>';
3048
3049 print dol_get_fiche_end();
3050 }
3051
3052
3053 /*
3054 * Action bar
3055 */
3056 print '<div class="tabsAction">';
3057
3058 $parameters = [];
3059 $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
3060 if (empty($reshook)) {
3061 if ($action != 'edit') {
3062 if ($user->hasRight('agenda', 'allactions', 'create') ||
3063 (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'))) {
3064 print '<div class="inline-block divButAction"><a class="butAction" href="card.php?action=edit&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Modify").'</a></div>';
3065 } else {
3066 print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans("Modify").'</a></div>';
3067 }
3068
3069 if ($user->hasRight('agenda', 'allactions', 'create') ||
3070 (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->hasRight('agenda', 'myactions', 'create'))) {
3071 print '<div class="inline-block divButAction"><a class="butAction butActionClone" href="card.php?action=clone&token='.newToken().'&object='.$object->element.'&id='.$object->id.'">'.$langs->trans("ToClone").'</a></div>';
3072 } else {
3073 print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans("ToClone").'</a></div>';
3074 }
3075
3076 if ($usercandelete) {
3077 print '<div class="inline-block divButAction"><a class="butActionDelete" href="card.php?action=delete&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Delete").'</a></div>';
3078 } else {
3079 print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans("Delete").'</a></div>';
3080 }
3081 }
3082 }
3083
3084 print '</div>';
3085
3086 if ($action != 'edit') {
3087 if (!getDolGlobalString('AGENDA_DISABLE_BUILDDOC')) {
3088 print '<div class="clearboth"></div><div class="fichecenter"><div class="fichehalfleft">';
3089 print '<a name="builddoc"></a>'; // ancre
3090
3091 // Generated documents
3092 $filedir = $conf->agenda->multidir_output[$conf->entity].'/'.$object->id;
3093 $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
3094
3095 $genallowed = $user->hasRight('agenda', 'myactions', 'read');
3096 $delallowed = $user->hasRight('agenda', 'myactions', 'create');
3097
3098 print $formfile->showdocuments('actions', (string) $object->id, $filedir, $urlsource, $genallowed, $delallowed, '', 0, 0, 0, 0, 0, '', '', '', $langs->getDefaultLang());
3099
3100 if (getDolGlobalString('AGENDA_ENABLE_LINKED_ELEMENTS')) {
3101 // Show links to link elements
3102 $tmparray = $form->showLinkToObjectBlock($object, [], array('myobject'), 1);
3103 if (is_array($tmparray)) {
3104 $linktoelem = $tmparray['linktoelem'];
3105 $htmltoenteralink = $tmparray['htmltoenteralink'];
3106 print $htmltoenteralink;
3107 $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
3108 } else {
3109 // backward compatibility
3110 $somethingshown = $form->showLinkedObjectBlock($object, $tmparray);
3111 }
3112 }
3113 print '</div><div class="fichehalfright">';
3114
3115 print '</div></div>';
3116 }
3117 }
3118}
3119
3120// End of page
3121llxFooter();
3122$db->close();
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:476
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
$object ref
Definition info.php:90
Class to manage agenda events (actions)
Class for ActionCommReminder.
Class to manage different types of events.
Class to manage contact/addresses.
Class to manage a WYSIWYG editor.
Class to manage building of HTML components.
Class to offer components to list and upload files.
Class to manage generation of HTML components Only common components must be here.
Class to manage building of HTML components.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage tasks.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
dol_get_first_day_week($day, $month, $year, $gm=false)
Return first day of week for a date.
Definition date.lib.php:695
num_between_day($timestampStart, $timestampEnd, $lastday=0)
Function to return number of days between two dates (date must be UTC date !) Example: 2012-01-01 201...
dol_stringtotime($string, $gm=1)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:451
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:129
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dolGetElementUrl($objectid, $objecttype, $withpicto=0, $option='')
Return link url to an object.
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
currentToken()
Return the value of token currently saved into session with name 'token'.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getElementProperties($elementType)
Get an array with properties of an element.
dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
Returns text escaped for inclusion into JavaScript code.
dol_set_focus($selector)
Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a 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.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
treeview li table
No Email.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:141
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition repair.php:137
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:140
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
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.