dolibarr 18.0.7
actions_massactions.inc.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2015-2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2018-2021 Nicolas ZABOURI <info@inovea-conseil.com>
4 * Copyright (C) 2018 Juanjo Menent <jmenent@2byte.es>
5 * Copyright (C) 2019 Ferran Marcet <fmarcet@2byte.es>
6 * Copyright (C) 2019-2021 Frédéric France <frederic.france@netlogic.fr>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * or see https://www.gnu.org/
21 */
22
29// $massaction must be defined
30// $objectclass and $objectlabel must be defined
31// $parameters, $object, $action must be defined for the hook.
32
33// $permissiontoread, $permissiontoadd, $permissiontodelete, $permissiontoclose may be defined
34// $uploaddir may be defined (example to $conf->project->dir_output."/";)
35// $hidedetails, $hidedesc, $hideref and $moreparams may have been set or not.
36// $toselect may be defined
37// $diroutputmassaction may be defined
38
39
40// Protection
41if (empty($objectclass) || empty($uploaddir)) {
42 dol_print_error(null, 'include of actions_massactions.inc.php is done but var $objectclass or $uploaddir was not defined');
43 exit;
44}
45if (empty($massaction)) {
46 $massaction = '';
47}
48$error = 0;
49
50// For backward compatibility
51if (!empty($permtoread) && empty($permissiontoread)) {
52 $permissiontoread = $permtoread;
53}
54if (!empty($permtocreate) && empty($permissiontoadd)) {
55 $permissiontoadd = $permtocreate;
56}
57if (!empty($permtodelete) && empty($permissiontodelete)) {
58 $permissiontodelete = $permtodelete;
59}
60
61// Mass actions. Controls on number of lines checked.
62$maxformassaction = (empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS) ? 1000 : $conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS);
63if ($massaction && is_array($toselect) && count($toselect) < 1) {
64 $error++;
65 setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
66}
67if (!$error && isset($toselect) && is_array($toselect) && count($toselect) > $maxformassaction) {
68 setEventMessages($langs->trans('TooManyRecordForMassAction', $maxformassaction), null, 'errors');
69 $error++;
70}
71
72if (!$error && $massaction == 'confirm_presend' && !GETPOST('sendmail')) { // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
73 $massaction = 'presend';
74}
75if (!$error && $massaction == 'confirm_presend') {
76 $resaction = '';
77 $nbsent = 0;
78 $nbignored = 0;
79 $langs->load("mails");
80 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
81 include_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
82
83 $listofobjectid = array();
84 $listofobjectthirdparties = array();
85 $listofobjectcontacts = array();
86 $listofobjectref = array();
87 $contactidtosend = array();
88 $attachedfilesThirdpartyObj = array();
89 $oneemailperrecipient = (GETPOST('oneemailperrecipient', 'int') ? 1 : 0);
90
91 if (!$error) {
92 $objecttmp = new $objectclass($db);
93
94 // Define object $thirdparty (Societe or User, Adherent, ConferenceOrBoothAttendee...)
95 $thirdparty = new Societe($db);
96 if ($objecttmp->element == 'expensereport') {
97 $thirdparty = new User($db);
98 } elseif ($objecttmp->element == 'contact') {
99 $thirdparty = new Contact($db);
100 } elseif ($objecttmp->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
101 $thirdparty = new Adherent($db);
102 } elseif ($objecttmp->element == 'holiday') {
103 $thirdparty = new User($db);
104 } elseif ($objecttmp->element == 'conferenceorboothattendee') {
105 $thirdparty = new ConferenceOrBoothAttendee($db);
106 }
107
108 foreach ($toselect as $toselectid) {
109 $objecttmp = new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use
110 $result = $objecttmp->fetch($toselectid);
111 if ($result > 0) {
112 $listofobjectid[$toselectid] = $toselectid;
113 $tmpobjectid = ($objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid);
114 if ($objecttmp->element == 'societe') {
115 $tmpobjectid = $objecttmp->id;
116 } elseif ($objecttmp->element == 'contact') {
117 $tmpobjectid = $objecttmp->id;
118 } elseif ($objecttmp->element == 'expensereport') {
119 $tmpobjectid = $objecttmp->fk_user_author;
120 } elseif ($objecttmp->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
121 $tmpobjectid = $objecttmp->fk_member;
122 } elseif ($objecttmp->element == 'holiday') {
123 $tmpobjectid = $objecttmp->fk_user;
124 } elseif ($objecttmp->element == 'conferenceorboothattendee') {
125 $tmpobjectid = $objecttmp->id;
126 }
127 if (empty($tmpobjectid)) {
128 $tmpobjectid = 0;
129 }
130
131 if ($objectclass == 'Facture') {
132 $tmparraycontact = array();
133 $tmparraycontact = $objecttmp->liste_contact(-1, 'external', 0, 'BILLING');
134 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
135 foreach ($tmparraycontact as $data_email) {
136 $listofobjectcontacts[$toselectid][$data_email['id']] = $data_email['email'];
137 }
138 }
139 } elseif ($objectclass == 'CommandeFournisseur') {
140 $tmparraycontact = array();
141 $tmparraycontact = $objecttmp->liste_contact(-1, 'external', 0, 'CUSTOMER');
142 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
143 foreach ($tmparraycontact as $data_email) {
144 $listofobjectcontacts[$toselectid][$data_email['id']] = $data_email['email'];
145 }
146 }
147 }
148
149 $listofobjectthirdparties[$tmpobjectid] = $tmpobjectid;
150 $listofobjectref[$tmpobjectid][$toselectid] = $objecttmp;
151 }
152 }
153 }
154
155 // Check mandatory parameters
156 if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email)) {
157 $error++;
158 setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
159 $massaction = 'presend';
160 }
161
162 $receiver = GETPOST('receiver', 'alphawithlgt');
163 if (!is_array($receiver)) {
164 if (empty($receiver) || $receiver == '-1') {
165 $receiver = array();
166 } else {
167 $receiver = array($receiver);
168 }
169 }
170 if (!trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) { // if only one recipient, receiver is mandatory
171 $error++;
172 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
173 $massaction = 'presend';
174 }
175
176 if (!GETPOST('subject', 'restricthtml')) {
177 $error++;
178 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
179 $massaction = 'presend';
180 }
181
182 // Loop on each recipient (may be a thirdparty but also a user, a conferenceorboothattendee, ...)
183 if (!$error) {
184 foreach ($listofobjectthirdparties as $thirdpartyid) {
185 $result = $thirdparty->fetch($thirdpartyid);
186 if ($result < 0) {
187 dol_print_error($db);
188 exit;
189 }
190
191 $sendto = '';
192 $sendtocc = '';
193 $sendtobcc = '';
194 //$sendtoid = array();
195
196 // Define $sendto
197 $tmparray = array();
198 if (trim($_POST['sendto'])) {
199 // Recipients are provided into free text
200 $tmparray[] = trim(GETPOST('sendto', 'alphawithlgt'));
201 }
202 if (count($receiver) > 0) {
203 foreach ($receiver as $key => $val) {
204 // Recipient was provided from combo list
205 if ($val == 'thirdparty') { // Id of third party or user
206 $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
207 } elseif ($val && method_exists($thirdparty, 'contact_get_property')) { // Id of contact
208 $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
209 //$sendtoid[] = $val;
210 }
211 }
212 }
213 $sendto = implode(',', $tmparray);
214
215 // Define $sendtocc
216 $receivercc = GETPOST('receivercc', 'alphawithlgt');
217 if (!is_array($receivercc)) {
218 if ($receivercc == '-1') {
219 $receivercc = array();
220 } else {
221 $receivercc = array($receivercc);
222 }
223 }
224 $tmparray = array();
225 if (trim($_POST['sendtocc'])) {
226 $tmparray[] = trim(GETPOST('sendtocc', 'alphawithlgt'));
227 }
228 if (count($receivercc) > 0) {
229 foreach ($receivercc as $key => $val) {
230 // Recipient was provided from combo list
231 if ($val == 'thirdparty') { // Id of third party
232 $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
233 } elseif ($val) { // Id du contact
234 $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
235 //$sendtoid[] = $val; TODO Add also id of contact in CC ?
236 }
237 }
238 }
239 $sendtocc = implode(',', $tmparray);
240
241 //var_dump($listofobjectref);exit;
242 $listofqualifiedobj = array();
243 $listofqualifiedref = array();
244 $thirdpartywithoutemail = array();
245
246 foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj) {
247 //var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
248 if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT) {
249 $langs->load("errors");
250 $nbignored++;
251 $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
252 continue; // Payment done or started or canceled
253 }
254 if ($objectclass == 'Commande' && $objectobj->statut == Commande::STATUS_DRAFT) {
255 $langs->load("errors");
256 $nbignored++;
257 $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
258 continue;
259 }
260 if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT) {
261 $langs->load("errors");
262 $nbignored++;
263 $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction', $objectobj->ref).'</div><br>';
264 continue; // Payment done or started or canceled
265 }
266
267 // Test recipient
268 if (empty($sendto)) { // For the case, no recipient were set (multi thirdparties send)
269 if ($objectobj->element == 'societe') {
270 $sendto = $objectobj->email;
271 } elseif ($objectobj->element == 'expensereport') {
272 $fuser = new User($db);
273 $fuser->fetch($objectobj->fk_user_author);
274 $sendto = $fuser->email;
275 } elseif ($objectobj->element == 'contact') {
276 $fcontact = new Contact($db);
277 $fcontact->fetch($objectobj->id);
278 $sendto = $fcontact->email;
279 } elseif ($objectobj->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
280 $fadherent = new Adherent($db);
281 $fadherent->fetch($objectobj->fk_member);
282 $sendto = $fadherent->email;
283 } elseif ($objectobj->element == 'holiday') {
284 $fuser = new User($db);
285 $fuser->fetch($objectobj->fk_user);
286 $sendto = $fuser->email;
287 } elseif ($objectobj->element == 'facture' && !empty($listofobjectcontacts[$objectid])) {
288 $emails_to_sends = array();
289 $objectobj->fetch_thirdparty();
290 $contactidtosend = array();
291 foreach ($listofobjectcontacts[$objectid] as $contactemailid => $contactemailemail) {
292 $emails_to_sends[] = $objectobj->thirdparty->contact_get_property($contactemailid, 'email');
293 if (!in_array($contactemailid, $contactidtosend)) {
294 $contactidtosend[] = $contactemailid;
295 }
296 }
297 if (count($emails_to_sends) > 0) {
298 $sendto = implode(',', $emails_to_sends);
299 }
300 } elseif ($objectobj->element == 'order_supplier' && !empty($listofobjectcontacts[$objectid])) {
301 $emails_to_sends = array();
302 $objectobj->fetch_thirdparty();
303 $contactidtosend = array();
304 foreach ($listofobjectcontacts[$objectid] as $contactemailid => $contactemailemail) {
305 $emails_to_sends[] = $objectobj->thirdparty->contact_get_property($contactemailid, 'email');
306 if (!in_array($contactemailid, $contactidtosend)) {
307 $contactidtosend[] = $contactemailid;
308 }
309 }
310 if (count($emails_to_sends) > 0) {
311 $sendto = implode(',', $emails_to_sends);
312 }
313 } elseif ($objectobj->element == 'conferenceorboothattendee') {
314 $sendto = $objectobj->email;
315 } else {
316 $objectobj->fetch_thirdparty();
317 $sendto = $objectobj->thirdparty->email;
318 }
319 }
320
321 if (empty($sendto)) {
322 if ($objectobj->element == 'societe') {
323 $objectobj->thirdparty = $objectobj; // Hack so following code is comaptible when objectobj is a thirdparty
324 }
325
326 //print "No recipient for thirdparty ".$objectobj->thirdparty->name;
327 $nbignored++;
328 if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id])) {
329 $resaction .= '<div class="error">'.$langs->trans('NoRecipientEmail', $objectobj->thirdparty->name).'</div><br>';
330 }
331 dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
332 $thirdpartywithoutemail[$objectobj->thirdparty->id] = 1;
333 continue;
334 }
335
336 if (GETPOST('addmaindocfile')) {
337 // TODO Use future field $objectobj->fullpathdoc to know where is stored default file
338 // TODO If not defined, use $objectobj->model_pdf (or defaut invoice config) to know what is template to use to regenerate doc.
339 $filename = dol_sanitizeFileName($objectobj->ref).'.pdf';
340 $subdir = '';
341 // TODO Set subdir to be compatible with multi levels dir trees
342 // $subdir = get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element)
343 $filedir = $uploaddir.'/'.$subdir.dol_sanitizeFileName($objectobj->ref);
344 $filepath = $filedir.'/'.$filename;
345
346 // For supplier invoices, we use the file provided by supplier, not the one we generate
347 if ($objectobj->element == 'invoice_supplier') {
348 $fileparams = dol_most_recent_file($uploaddir.'/'.get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element).$objectobj->ref, preg_quote($objectobj->ref, '/').'([^\-])+');
349 $filepath = $fileparams['fullname'];
350 }
351
352 // try to find other files generated for this object (last_main_doc)
353 $filename_found = '';
354 $filepath_found = '';
355 $file_check_list = array();
356 $file_check_list[] = array(
357 'name' => $filename,
358 'path' => $filepath,
359 );
360 if (!empty($conf->global->MAIL_MASS_ACTION_ADD_LAST_IF_MAIN_DOC_NOT_FOUND) && !empty($objectobj->last_main_doc)) {
361 $file_check_list[] = array(
362 'name' => basename($objectobj->last_main_doc),
363 'path' => DOL_DATA_ROOT . '/' . $objectobj->last_main_doc,
364 );
365 }
366 foreach ($file_check_list as $file_check_arr) {
367 if (dol_is_file($file_check_arr['path'])) {
368 $filename_found = $file_check_arr['name'];
369 $filepath_found = $file_check_arr['path'];
370 break;
371 }
372 }
373
374 if ($filepath_found) {
375 // Create form object
376 $attachedfilesThirdpartyObj[$thirdpartyid][$objectid] = array(
377 'paths'=>array($filepath_found),
378 'names'=>array($filename_found),
379 'mimes'=>array(dol_mimetype($filepath_found))
380 );
381 } else {
382 $nbignored++;
383 $langs->load("errors");
384 foreach ($file_check_list as $file_check_arr) {
385 $resaction .= '<div class="error">'.$langs->trans('ErrorCantReadFile', $file_check_arr['path']).'</div><br>';
386 dol_syslog('Failed to read file: '.$file_check_arr['path'], LOG_WARNING);
387 }
388 continue;
389 }
390 }
391
392 // Object of thirdparty qualified, we add it
393 $listofqualifiedobj[$objectid] = $objectobj;
394 $listofqualifiedref[$objectid] = $objectobj->ref;
395
396
397 //var_dump($listofqualifiedref);
398 }
399
400 // Send email if there is at least one qualified object for current thirdparty
401 if (count($listofqualifiedobj) > 0) {
402 $langs->load("commercial");
403
404 $reg = array();
405 $fromtype = GETPOST('fromtype');
406 if ($fromtype === 'user') {
407 $from = dol_string_nospecial($user->getFullName($langs), ' ', array(",")).' <'.$user->email.'>';
408 } elseif ($fromtype === 'company') {
409 $from = $conf->global->MAIN_INFO_SOCIETE_NOM.' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
410 } elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
411 $tmp = explode(',', $user->email_aliases);
412 $from = trim($tmp[($reg[1] - 1)]);
413 } elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
414 $tmp = explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
415 $from = trim($tmp[($reg[1] - 1)]);
416 } elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
417 $sql = "SELECT rowid, label, email FROM ".MAIN_DB_PREFIX."c_email_senderprofile WHERE rowid = ".(int) $reg[1];
418 $resql = $db->query($sql);
419 $obj = $db->fetch_object($resql);
420 if ($obj) {
421 $from = dol_string_nospecial($obj->label, ' ', array(",")).' <'.$obj->email.'>';
422 }
423 } else {
424 $from = GETPOST('fromname').' <'.GETPOST('frommail').'>';
425 }
426
427 $replyto = $from;
428 $subject = GETPOST('subject', 'restricthtml');
429 $message = GETPOST('message', 'restricthtml');
430
431 $sendtobcc = GETPOST('sendtoccc');
432 if ($objectclass == 'Propal') {
433 $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
434 }
435 if ($objectclass == 'Commande') {
436 $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
437 }
438 if ($objectclass == 'Facture') {
439 $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
440 }
441 if ($objectclass == 'Supplier_Proposal') {
442 $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
443 }
444 if ($objectclass == 'CommandeFournisseur') {
445 $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
446 }
447 if ($objectclass == 'FactureFournisseur') {
448 $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
449 }
450 if ($objectclass == 'Project') {
451 $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO));
452 }
453
454 // $listofqualifiedobj is array with key = object id and value is instance of qualified objects, for the current thirdparty (but thirdparty property is not loaded yet)
455 // $looparray will be an array with number of email to send for the current thirdparty (so 1 or n if n object for same thirdparty)
456 $looparray = array();
457 if (!$oneemailperrecipient) {
458 $looparray = $listofqualifiedobj;
459 foreach ($looparray as $key => $objecttmp) {
460 $looparray[$key]->thirdparty = $thirdparty; // Force thirdparty on object
461 }
462 } else {
463 $objectforloop = new $objectclass($db);
464 $objectforloop->thirdparty = $thirdparty; // Force thirdparty on object (even if object was not loaded)
465 $looparray[0] = $objectforloop;
466 }
467 //var_dump($looparray);exit;
468 dol_syslog("We have set an array of ".count($looparray)." emails to send. oneemailperrecipient=".$oneemailperrecipient);
469 //var_dump($oneemailperrecipient); var_dump($listofqualifiedobj); var_dump($listofqualifiedref);
470 foreach ($looparray as $objectid => $objecttmp) { // $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per object
471 // Make substitution in email content
472 if (isModEnabled('project') && method_exists($objecttmp, 'fetch_projet') && is_null($objecttmp->project)) {
473 $objecttmp->fetch_projet();
474 }
475 $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $objecttmp);
476 $substitutionarray['__ID__'] = ($oneemailperrecipient ? join(', ', array_keys($listofqualifiedobj)) : $objecttmp->id);
477 $substitutionarray['__REF__'] = ($oneemailperrecipient ? join(', ', $listofqualifiedref) : $objecttmp->ref);
478 $substitutionarray['__EMAIL__'] = $thirdparty->email;
479 $substitutionarray['__CHECK_READ__'] = '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag=undefined&securitykey='.dol_hash(getDolGlobalString('MAILING_EMAIL_UNSUBSCRIBE_KEY')."-undefined", 'md5').'" width="1" height="1" style="width:1px;height:1px" border="0"/>';
480
481 if ($oneemailperrecipient) {
482 $substitutionarray['__ONLINE_PAYMENT_URL__'] = '';
483 $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = '';
484 }
485
486 $parameters = array('mode'=>'formemail');
487
488 if (!empty($listofobjectthirdparties)) {
489 $parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
490 }
491 if (!empty($listofobjectref)) {
492 $parameters['listofobjectref'] = $listofobjectref;
493 }
494
495 complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
496
497 $subjectreplaced = make_substitutions($subject, $substitutionarray);
498 $messagereplaced = make_substitutions($message, $substitutionarray);
499
500 $attachedfiles = array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
501 if ($oneemailperrecipient) {
502 // if "one email per recipient" is check we must collate $attachedfiles by thirdparty
503 if (is_array($attachedfilesThirdpartyObj[$thirdparty->id]) && count($attachedfilesThirdpartyObj[$thirdparty->id])) {
504 foreach ($attachedfilesThirdpartyObj[$thirdparty->id] as $keyObjId => $objAttachedFiles) {
505 // Create form object
506 $attachedfiles = array(
507 'paths'=>array_merge($attachedfiles['paths'], $objAttachedFiles['paths']),
508 'names'=>array_merge($attachedfiles['names'], $objAttachedFiles['names']),
509 'mimes'=>array_merge($attachedfiles['mimes'], $objAttachedFiles['mimes'])
510 );
511 }
512 }
513 } elseif (!empty($attachedfilesThirdpartyObj[$thirdparty->id][$objectid])) {
514 // Create form object
515 // if "one email per recipient" isn't check we must separate $attachedfiles by object
516 $attachedfiles = $attachedfilesThirdpartyObj[$thirdparty->id][$objectid];
517 }
518
519 $filepath = $attachedfiles['paths'];
520 $filename = $attachedfiles['names'];
521 $mimetype = $attachedfiles['mimes'];
522
523 // Define the trackid when emails sent from the mass action
524 if ($oneemailperrecipient) {
525 $trackid = 'thi'.$thirdparty->id;
526 if ($objecttmp->element == 'expensereport') {
527 $trackid = 'use'.$thirdparty->id;
528 } elseif ($objecttmp->element == 'contact') {
529 $trackid = 'ctc'.$thirdparty->id;
530 } elseif ($objecttmp->element == 'holiday') {
531 $trackid = 'use'.$thirdparty->id;
532 }
533 } else {
534 $trackid = strtolower(get_class($objecttmp));
535 if (get_class($objecttmp) == 'Contact') {
536 $trackid = 'ctc';
537 } elseif (get_class($objecttmp) == 'Contrat') {
538 $trackid = 'con';
539 } elseif (get_class($objecttmp) == 'Propal') {
540 $trackid = 'pro';
541 } elseif (get_class($objecttmp) == 'Commande') {
542 $trackid = 'ord';
543 } elseif (get_class($objecttmp) == 'Facture') {
544 $trackid = 'inv';
545 } elseif (get_class($objecttmp) == 'Supplier_Proposal') {
546 $trackid = 'spr';
547 } elseif (get_class($objecttmp) == 'CommandeFournisseur') {
548 $trackid = 'sor';
549 } elseif (get_class($objecttmp) == 'FactureFournisseur') {
550 $trackid = 'sin';
551 }
552
553 $trackid .= $objecttmp->id;
554 }
555 //var_dump($filepath);
556 //var_dump($trackid);exit;
557 //var_dump($subjectreplaced);
558
559 if (empty($sendcontext)) {
560 $sendcontext = 'standard';
561 }
562
563 // Set tmp user directory (used to convert images embedded as img src=data:image)
564 $vardir = $conf->user->dir_output."/".$user->id;
565 $upload_dir_tmp = $vardir.'/temp'; // TODO Add $keytoavoidconflict in upload_dir path
566
567 // Send mail (substitutionarray must be done just before this)
568 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
569 $mailfile = new CMailFile($subjectreplaced, $sendto, $from, $messagereplaced, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, $deliveryreceipt, -1, '', '', $trackid, '', $sendcontext, '', $upload_dir_tmp);
570 if ($mailfile->error) {
571 $resaction .= '<div class="error">'.$mailfile->error.'</div>';
572 } else {
573 $result = $mailfile->sendfile();
574 if ($result > 0) {
575 $resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($mailfile->addr_from, 2), $mailfile->getValidAddress($mailfile->addr_to, 2)).'<br>'; // Must not contain "
576
577 $error = 0;
578
579 // Insert logs into agenda
580 foreach ($listofqualifiedobj as $objid2 => $objectobj2) {
581 if ((!$oneemailperrecipient) && $objid2 != $objectid) {
582 continue; // We discard this pass to avoid duplicate with other pass in looparray at higher level
583 }
584
585 dol_syslog("Try to insert email event into agenda for objid=".$objid2." => objectobj=".get_class($objectobj2));
586
587 /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
588 if ($objectclass == 'Commande') $actiontypecode='AC_COM';
589 if ($objectclass == 'Facture') $actiontypecode='AC_FAC';
590 if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO';
591 if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
592 if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
593
594 $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
595 if ($message) {
596 if ($sendtocc) {
597 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc);
598 }
599 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subjectreplaced);
600 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
601 $actionmsg = dol_concatdesc($actionmsg, $messagereplaced);
602 }
603 $actionmsg2 = '';
604
605 // Initialisation donnees
606 $objectobj2->sendtoid = (empty($contactidtosend) ? 0 : $contactidtosend);
607 $objectobj2->actionmsg = $actionmsg; // Long text
608 $objectobj2->actionmsg2 = $actionmsg2; // Short text
609 $objectobj2->fk_element = $objid2;
610 $objectobj2->elementtype = $objectobj2->element;
611 if (!empty($conf->global->MAIN_MAIL_REPLACE_EVENT_TITLE_BY_EMAIL_SUBJECT)) {
612 $objectobj2->actionmsg2 = $subjectreplaced; // Short text
613 }
614
615 $triggername = strtoupper(get_class($objectobj2)).'_SENTBYMAIL';
616 if ($triggername == 'SOCIETE_SENTBYMAIL') {
617 $triggername = 'COMPANY_SENTBYMAIL';
618 }
619 if ($triggername == 'CONTRAT_SENTBYMAIL') {
620 $triggername = 'CONTRACT_SENTBYMAIL';
621 }
622 if ($triggername == 'COMMANDE_SENTBYMAIL') {
623 $triggername = 'ORDER_SENTBYMAIL';
624 }
625 if ($triggername == 'FACTURE_SENTBYMAIL') {
626 $triggername = 'BILL_SENTBYMAIL';
627 }
628 if ($triggername == 'EXPEDITION_SENTBYMAIL') {
629 $triggername = 'SHIPPING_SENTBYMAIL';
630 }
631 if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') {
632 $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
633 }
634 if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') {
635 $triggername = 'BILL_SUPPLIER_SENTBYMAIL';
636 }
637 if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') {
638 $triggername = 'PROPOSAL_SUPPLIER_SENTBYMAIL';
639 }
640 if ($triggername == 'PROJET_SENTBYMAIL') {
641 $triggername = 'PROJECT_SENTBYMAIL';
642 }
643
644 if (!empty($triggername)) {
645 // Call trigger
646 $result = $objectobj2->call_trigger($triggername, $user);
647 if ($result < 0) {
648 $error++;
649 }
650 // End call triggers
651
652 if ($error) {
653 setEventMessages($db->lasterror(), $errors, 'errors');
654 dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR);
655 }
656 }
657
658 $nbsent++; // Nb of object sent
659 }
660 } else {
661 $langs->load("other");
662 if ($mailfile->error) {
663 $resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto);
664 $resaction .= '<br><div class="error">'.$mailfile->error.'</div>';
665 } elseif (!empty($conf->global->MAIN_DISABLE_ALL_MAILS)) {
666 $resaction .= '<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
667 } else {
668 $resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto) . '<br><div class="error">(unhandled error)</div>';
669 }
670 }
671 }
672 }
673 }
674 }
675
676 $resaction .= ($resaction ? '<br>' : $resaction);
677 $resaction .= '<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
678 $resaction .= $langs->trans("NbSelected").': '.count($toselect)."\n<br>";
679 $resaction .= $langs->trans("NbIgnored").': '.($nbignored ? $nbignored : 0)."\n<br>";
680 $resaction .= $langs->trans("NbSent").': '.($nbsent ? $nbsent : 0)."\n<br>";
681
682 if ($nbsent) {
683 $action = ''; // Do not show form post if there was at least one successfull sent
684 //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
685 setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
686 setEventMessages($resaction, null, 'mesgs');
687 } else {
688 //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file
689 setEventMessages($resaction, null, 'warnings');
690 }
691
692 $action = 'list';
693 $massaction = '';
694 }
695}
696
697
698if (!$error && $massaction == 'cancelorders') {
699 $db->begin();
700
701 $nbok = 0;
702
703 $orders = GETPOST('toselect', 'array');
704 foreach ($orders as $id_order) {
705 $cmd = new Commande($db);
706 if ($cmd->fetch($id_order) <= 0) {
707 continue;
708 }
709
710 if ($cmd->statut != Commande::STATUS_VALIDATED) {
711 $langs->load('errors');
712 setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
713 $error++;
714 break;
715 } else {
716 // TODO We do not provide warehouse so no stock change here for the moment.
717 $result = $cmd->cancel();
718 }
719
720 if ($result < 0) {
721 setEventMessages($cmd->error, $cmd->errors, 'errors');
722 $error++;
723 break;
724 } else {
725 $nbok++;
726 }
727 }
728 if (!$error) {
729 if ($nbok > 1) {
730 setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
731 } else {
732 setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
733 }
734 $db->commit();
735 } else {
736 $db->rollback();
737 }
738}
739
740
741if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search')) {
742 if (empty($diroutputmassaction)) {
743 dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
744 exit;
745 }
746
747 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
748 require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
749 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
750
751 $objecttmp = new $objectclass($db);
752 $listofobjectid = array();
753 $listofobjectthirdparties = array();
754 $listofobjectref = array();
755 foreach ($toselect as $toselectid) {
756 $objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use
757 $result = $objecttmp->fetch($toselectid);
758 if ($result > 0) {
759 $listofobjectid[$toselectid] = $toselectid;
760 $thirdpartyid = $objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid;
761 $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
762 $listofobjectref[$toselectid] = $objecttmp->ref;
763 }
764 }
765
766 $arrayofinclusion = array();
767 foreach ($listofobjectref as $tmppdf) {
768 $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$';
769 }
770 foreach ($listofobjectref as $tmppdf) {
771 $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[a-zA-Z0-9\-\_\'\&\.]+\.pdf$'; // To include PDF generated from ODX files
772 }
773 $listoffiles = dol_dir_list($uploaddir, 'all', 1, implode('|', $arrayofinclusion), '\.meta$|\.png', 'date', SORT_DESC, 0, true);
774
775 // build list of files with full path
776 $files = array();
777 foreach ($listofobjectref as $basename) {
778 $basename = dol_sanitizeFileName($basename);
779 foreach ($listoffiles as $filefound) {
780 if (strstr($filefound["name"], $basename)) {
781 $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"];
782 break;
783 }
784 }
785 }
786
787 // Define output language (Here it is not used because we do only merging existing PDF)
788 $outputlangs = $langs;
789 $newlang = '';
790 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
791 $newlang = GETPOST('lang_id', 'aZ09');
792 }
793 //elseif (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && is_object($objecttmp->thirdparty)) { // On massaction, we can have several values for $objecttmp->thirdparty
794 // $newlang = $objecttmp->thirdparty->default_lang;
795 //}
796 if (!empty($newlang)) {
797 $outputlangs = new Translate("", $conf);
798 $outputlangs->setDefaultLang($newlang);
799 }
800
801 if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) {
802 // Create output dir if not exists
803 dol_mkdir($diroutputmassaction);
804
805 // Defined name of merged file
806 $filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
807 $filename = preg_replace('/\s/', '_', $filename);
808
809 // Save merged file
810 if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) {
811 if ($option == 'late') {
812 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
813 } else {
814 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
815 }
816 }
817 if ($year) {
818 $filename .= '_'.$year;
819 }
820 if ($month) {
821 $filename .= '_'.$month;
822 }
823
824 if (count($files) > 0) {
825 $now = dol_now();
826 $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
827
828 $input_files = '';
829 foreach ($files as $f) {
830 $input_files .= ' '.escapeshellarg($f);
831 }
832
833 $cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file);
834 exec($cmd);
835
836 // check if pdftk is installed
837 if (file_exists($file)) {
838 dolChmod($file);
839
840 $langs->load("exports");
841 setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
842 } else {
843 setEventMessages($langs->trans('ErrorPDFTkOutputFileNotFound'), null, 'errors');
844 }
845 } else {
846 setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
847 }
848 } else {
849 // Create empty PDF
850 $formatarray = pdf_getFormat();
851 $page_largeur = $formatarray['width'];
852 $page_hauteur = $formatarray['height'];
853 $format = array($page_largeur, $page_hauteur);
854
855 $pdf = pdf_getInstance($format);
856
857 if (class_exists('TCPDF')) {
858 $pdf->setPrintHeader(false);
859 $pdf->setPrintFooter(false);
860 }
861 $pdf->SetFont(pdf_getPDFFont($outputlangs));
862
863 if (getDolGlobalString('MAIN_DISABLE_PDF_COMPRESSION')) {
864 $pdf->SetCompression(false);
865 }
866
867 // Add all others
868 foreach ($files as $file) {
869 // Charge un document PDF depuis un fichier.
870 $pagecount = $pdf->setSourceFile($file);
871 for ($i = 1; $i <= $pagecount; $i++) {
872 $tplidx = $pdf->importPage($i);
873 $s = $pdf->getTemplatesize($tplidx);
874 $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
875 $pdf->useTemplate($tplidx);
876 }
877 }
878
879 // Create output dir if not exists
880 dol_mkdir($diroutputmassaction);
881
882 // Defined name of merged file
883 $filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
884 $filename = preg_replace('/\s/', '_', $filename);
885
886 // Save merged file
887 if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) {
888 if ($option == 'late') {
889 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
890 } else {
891 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
892 }
893 }
894 if ($year) {
895 $filename .= '_'.$year;
896 }
897 if ($month) {
898 $filename .= '_'.$month;
899 }
900 if ($pagecount) {
901 $now = dol_now();
902 $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
903 $pdf->Output($file, 'F');
904 dolChmod($file);
905
906 $langs->load("exports");
907 setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
908 } else {
909 setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
910 }
911 }
912}
913
914// Remove a file from massaction area
915if ($action == 'remove_file') {
916 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
917
918 $langs->load("other");
919 $upload_dir = $diroutputmassaction;
920 $file = $upload_dir.'/'.GETPOST('file');
921 $ret = dol_delete_file($file);
922 if ($ret) {
923 setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
924 } else {
925 setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
926 }
927 $action = '';
928}
929
930
931// Validate records
932if (!$error && $massaction == 'validate' && $permissiontoadd) {
933 $objecttmp = new $objectclass($db);
934
935 if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
936 $langs->load("errors");
937 setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
938 $error++;
939 }
940 if ($objecttmp->element == 'invoice_supplier' && isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
941 $langs->load("errors");
942 setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
943 $error++;
944 }
945 if ($objecttmp->element == 'facture') {
946 if (!empty($toselect) && !empty($conf->global->INVOICE_CHECK_POSTERIOR_DATE)) {
947 // order $toselect by date
948 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture";
949 $sql .= " WHERE rowid IN (".$db->sanitize(implode(",", $toselect)).")";
950 $sql .= " ORDER BY datef";
951
952 $resql = $db->query($sql);
953 if ($resql) {
954 $toselectnew = [];
955 while ( !empty($arr = $db->fetch_row($resql))) {
956 $toselectnew[] = $arr[0];
957 }
958 $toselect = (empty($toselectnew)) ? $toselect : $toselectnew;
959 } else {
960 dol_print_error($db);
961 $error++;
962 }
963 }
964 }
965 if (!$error) {
966 $db->begin();
967
968 $nbok = 0;
969 foreach ($toselect as $toselectid) {
970 $result = $objecttmp->fetch($toselectid);
971 if ($result > 0) {
972 if (method_exists($objecttmp, 'validate')) {
973 $result = $objecttmp->validate($user);
974 } elseif (method_exists($objecttmp, 'setValid')) {
975 $result = $objecttmp->setValid($user);
976 } else {
977 $objecttmp->error = 'No method validate or setValid on this object';
978 $result = -1;
979 }
980 if ($result == 0) {
981 $langs->load("errors");
982 setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
983 $error++;
984 break;
985 } elseif ($result < 0) {
986 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
987 $error++;
988 break;
989 } else {
990 // validate() rename pdf but do not regenerate
991 // Define output language
992 if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
993 $outputlangs = $langs;
994 $newlang = '';
995 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
996 $newlang = GETPOST('lang_id', 'aZ09');
997 }
998 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && property_exists($objecttmp, 'thirdparty')) {
999 if ((property_exists($objecttmp, 'socid') || property_exists($objecttmp, 'fk_soc')) && empty($objecttmp->thirdparty)) {
1000 $objecttmp->fetch_thirdparty();
1001 }
1002 if (!empty($objecttmp->thirdparty)) {
1003 $newlang = $objecttmp->thirdparty->default_lang;
1004 }
1005 }
1006 if (!empty($newlang)) {
1007 $outputlangs = new Translate("", $conf);
1008 $outputlangs->setDefaultLang($newlang);
1009 $outputlangs->load('products');
1010 }
1011 $model = $objecttmp->model_pdf;
1012 $ret = $objecttmp->fetch($objecttmp->id); // Reload to get new records
1013 // To be sure vars is defined
1014 $hidedetails = isset($hidedetails) ? $hidedetails : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
1015 $hidedesc = isset($hidedesc) ? $hidedesc : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
1016 $hideref = isset($hideref) ? $hideref : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
1017 $moreparams = isset($moreparams) ? $moreparams : null;
1018
1019 $result = $objecttmp->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1020 if ($result < 0) {
1021 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1022 }
1023 }
1024 $nbok++;
1025 }
1026 } else {
1027 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1028 $error++;
1029 break;
1030 }
1031 }
1032
1033 if (!$error) {
1034 if ($nbok > 1) {
1035 setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1036 } else {
1037 setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
1038 }
1039 $db->commit();
1040 } else {
1041 $db->rollback();
1042 }
1043 //var_dump($listofobjectthirdparties);exit;
1044 }
1045}
1046
1047//var_dump($_POST);var_dump($massaction);exit;
1048
1049// Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
1050if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) {
1051 $db->begin();
1052
1053 $objecttmp = new $objectclass($db);
1054 $nbok = 0;
1055 $TMsg = array();
1056
1057 //$toselect could contain duplicate entries, cf https://github.com/Dolibarr/dolibarr/issues/26244
1058 $unique_arr = array_unique($toselect);
1059 foreach ($unique_arr as $toselectid) {
1060 $result = $objecttmp->fetch($toselectid);
1061 if ($result > 0) {
1062 // Refuse deletion for some objects/status
1063 if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT) {
1064 $langs->load("errors");
1065 $nbignored++;
1066 $TMsg[] = '<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'</div><br>';
1067 continue;
1068 }
1069
1070 if (method_exists($objecttmp, 'is_erasable') && $objecttmp->is_erasable() <= 0) {
1071 $langs->load("errors");
1072 $nbignored++;
1073 $TMsg[] = '<div class="error">'.$langs->trans('ErrorRecordHasChildren').' '.$objecttmp->ref.'</div><br>';
1074 continue;
1075 }
1076
1077 if ($objectclass == 'Holiday' && ! in_array($objecttmp->statut, array(Holiday::STATUS_DRAFT, Holiday::STATUS_CANCELED, Holiday::STATUS_REFUSED))) {
1078 $langs->load("errors");
1079 $nbignored++;
1080 $TMsg[] = '<div class="error">'.$langs->trans('ErrorLeaveRequestMustBeDraftCanceledOrRefusedToBeDeleted', $objecttmp->ref).'</div><br>';
1081 continue;
1082 }
1083
1084 if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) {
1085 $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".((int) $objecttmp->id);
1086 $res = $db->query($sql);
1087
1088 if (!$res) {
1089 setEventMessage('ErrorRecordParentingNotModified', 'errors');
1090 $error++;
1091 }
1092 }
1093
1094 if (in_array($objecttmp->element, array('societe', 'member'))) {
1095 $result = $objecttmp->delete($objecttmp->id, $user, 1);
1096 } elseif (in_array($objecttmp->element, array('action'))) {
1097 $result = $objecttmp->delete();
1098 } else {
1099 $result = $objecttmp->delete($user);
1100 }
1101
1102 if (empty($result)) { // if delete returns 0, there is at least one object linked
1103 $TMsg = array_merge($objecttmp->errors, $TMsg);
1104 } elseif ($result < 0) { // if delete returns is < 0, there is an error, we break and rollback later
1105 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1106 $error++;
1107 break;
1108 } else {
1109 $nbok++;
1110 }
1111 } else {
1112 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1113 $error++;
1114 break;
1115 }
1116 }
1117
1118 if (empty($error)) {
1119 // Message for elements well deleted
1120 if ($nbok > 1) {
1121 setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1122 } elseif ($nbok > 0) {
1123 setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1124 } else {
1125 setEventMessages($langs->trans("NoRecordDeleted"), null, 'mesgs');
1126 }
1127
1128 // Message for elements which can't be deleted
1129 if (!empty($TMsg)) {
1130 sort($TMsg);
1131 setEventMessages('', array_unique($TMsg), 'warnings');
1132 }
1133
1134 $db->commit();
1135 } else {
1136 $db->rollback();
1137 }
1138
1139 //var_dump($listofobjectthirdparties);exit;
1140}
1141
1142// Generate document foreach object according to model linked to object
1143// @todo : propose model selection
1144if (!$error && $massaction == 'generate_doc' && $permissiontoread) {
1145 $db->begin();
1146 $objecttmp = new $objectclass($db);
1147 $nbok = 0;
1148 foreach ($toselect as $toselectid) {
1149 $result = $objecttmp->fetch($toselectid);
1150 if ($result > 0) {
1151 $outputlangs = $langs;
1152 $newlang = '';
1153
1154 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
1155 $newlang = GETPOST('lang_id', 'aZ09');
1156 }
1157 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) {
1158 $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
1159 }
1160 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->default_lang)) {
1161 $newlang = $objecttmp->default_lang; // for thirdparty
1162 }
1163 if ($conf->global->MAIN_MULTILANGS && empty($newlang) && empty($objecttmp->thirdparty)) { //load lang from thirdparty
1164 $objecttmp->fetch_thirdparty();
1165 $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
1166 }
1167 if (!empty($newlang)) {
1168 $outputlangs = new Translate("", $conf);
1169 $outputlangs->setDefaultLang($newlang);
1170 }
1171
1172 // To be sure vars is defined
1173 $hidedetails = isset($hidedetails) ? $hidedetails : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
1174 $hidedesc = isset($hidedesc) ? $hidedesc : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
1175 $hideref = isset($hideref) ? $hideref : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
1176 $moreparams = isset($moreparams) ? $moreparams : null;
1177
1178 $result = $objecttmp->generateDocument($objecttmp->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1179
1180 if ($result <= 0) {
1181 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1182 $error++;
1183 break;
1184 } else {
1185 $nbok++;
1186 }
1187 } else {
1188 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1189 $error++;
1190 break;
1191 }
1192 }
1193
1194 if (!$error) {
1195 if ($nbok > 1) {
1196 setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1197 } else {
1198 setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
1199 }
1200 $db->commit();
1201 } else {
1202 $db->rollback();
1203 }
1204}
1205
1206if (!$error && ($action == 'affecttag' && $confirm == 'yes') && $permissiontoadd) {
1207 $db->begin();
1208
1209 $affecttag_type=GETPOST('affecttag_type', 'alpha');
1210 if (!empty($affecttag_type)) {
1211 $affecttag_type_array=explode(',', $affecttag_type);
1212 } else {
1213 setEventMessage('CategTypeNotFound', 'errors');
1214 }
1215 if (!empty($affecttag_type_array)) {
1216 //check if tag type submited exists into Tag Map categorie class
1217 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1218 $categ = new Categorie($db);
1219 $to_affecttag_type_array=array();
1220 $categ_type_array=$categ->getMapList();
1221 foreach ($categ_type_array as $categdef) {
1222 if (in_array($categdef['code'], $affecttag_type_array)) {
1223 $to_affecttag_type_array[] = $categdef['code'];
1224 }
1225 }
1226
1227 //For each valid categ type set common categ
1228 $nbok = 0;
1229 if (!empty($to_affecttag_type_array)) {
1230 foreach ($to_affecttag_type_array as $categ_type) {
1231 $contcats = GETPOST('contcats_' . $categ_type, 'array');
1232 //var_dump($toselect);exit;
1233 foreach ($toselect as $toselectid) {
1234 $result = $object->fetch($toselectid);
1235 //var_dump($contcats);exit;
1236 if ($result > 0) {
1237 $result = $object->setCategoriesCommon($contcats, $categ_type, false);
1238 if ($result > 0) {
1239 $nbok++;
1240 } else {
1241 setEventMessages($object->error, $object->errors, 'errors');
1242 }
1243 } else {
1244 setEventMessages($object->error, $object->errors, 'errors');
1245 $error++;
1246 break;
1247 }
1248 }
1249 }
1250 }
1251 }
1252
1253 if (!$error) {
1254 if ($nbok > 1) {
1255 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1256 } else {
1257 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1258 }
1259 $db->commit();
1260 $toselect=array();
1261 } else {
1262 $db->rollback();
1263 }
1264}
1265
1266if (!$error && ($action == 'updateprice' && $confirm == 'yes') && $permissiontoadd) {
1267 $db->begin();
1268 if (GETPOSTISSET('pricerate')) {
1269 $pricepercentage=GETPOST('pricerate', 'int');
1270 if ($pricepercentage == 0) {
1271 setEventMessages($langs->trans("RecordsModified", 0), null);
1272 } else {
1273 foreach ($toselect as $toselectid) {
1274 $result = $object->fetch($toselectid);
1275 //var_dump($contcats);exit;
1276 if ($result > 0) {
1277 if ($obj->price_base_type == 'TTC') {
1278 $newprice = $object->price_ttc * (100 + $pricepercentage) / 100;
1279 $minprice = $object->price_min_ttc;
1280 } else {
1281 $newprice = $object->price * (100 + $pricepercentage) / 100;
1282 $minprice = $object->price_min;
1283 }
1284 $res = $object->updatePrice($newprice, $obj->price_base_type, $user, $object->tva_tx, $minprice, 0, $object->tva_npr, 0, 0, array(), $object->default_vat_code);
1285 if ($res > 0) {
1286 $nbok++;
1287 } else {
1288 setEventMessages($object->error, $object->errors, 'errors');
1289 }
1290 } else {
1291 setEventMessages($object->error, $object->errors, 'errors');
1292 $error++;
1293 break;
1294 }
1295 }
1296 }
1297 }
1298
1299 if (!$error) {
1300 if ($nbok > 0) {
1301 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1302 }
1303 $db->commit();
1304 $toselect=array();
1305 } else {
1306 $db->rollback();
1307 }
1308}
1309
1310if (!$error && ($action == 'setsupervisor' && $confirm == 'yes') && $permissiontoadd) {
1311 $db->begin();
1312 $supervisortoset=GETPOST('supervisortoset');
1313 if (!empty($supervisortoset)) {
1314 foreach ($toselect as $toselectid) {
1315 $result = $object->fetch($toselectid);
1316 //var_dump($contcats);exit;
1317 if ($result > 0) {
1318 $object->fk_user = $supervisortoset;
1319 $res = $object->update($user);
1320 if ($res > 0) {
1321 $nbok++;
1322 } else {
1323 setEventMessages($object->error, $object->errors, 'errors');
1324 }
1325 } else {
1326 setEventMessages($object->error, $object->errors, 'errors');
1327 $error++;
1328 break;
1329 }
1330 }
1331 } else {
1332 setEventMessage('UserNotFound', 'errors');
1333 $error++;
1334 }
1335
1336 if (!$error) {
1337 if ($nbok > 1) {
1338 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1339 } else {
1340 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1341 }
1342 $db->commit();
1343 $toselect=array();
1344 } else {
1345 $db->rollback();
1346 }
1347}
1348
1349if (!$error && ($action == 'affectuser' && $confirm == 'yes') && $permissiontoadd) {
1350 $db->begin();
1351
1352 $usertoaffect=GETPOST('usertoaffect');
1353 $projectrole=GETPOST('projectrole');
1354 $tasksrole=GETPOST('tasksrole');
1355 if (!empty($usertoaffect)) {
1356 foreach ($toselect as $toselectid) {
1357 $result = $object->fetch($toselectid);
1358 //var_dump($contcats);exit;
1359 if ($result > 0) {
1360 $res = $object->add_contact($usertoaffect, $projectrole, 'internal');
1361 if ($res >= 0) {
1362 $taskstatic = new Task($db);
1363 $task_array = $taskstatic->getTasksArray(0, 0, $object->id, 0, 0);
1364
1365 foreach ($task_array as $task) {
1366 $tasksToAffect = new Task($db);
1367 $result = $tasksToAffect->fetch($task->id);
1368 if ($result > 0) {
1369 $res = $tasksToAffect->add_contact($usertoaffect, $tasksrole, 'internal');
1370 if ($res < 0) {
1371 setEventMessages($tasksToAffect->error, $tasksToAffect->errors, 'errors');
1372 }
1373 }
1374 }
1375 $nbok++;
1376 } else {
1377 setEventMessages($object->error, $object->errors, 'errors');
1378 }
1379 } else {
1380 setEventMessages($object->error, $object->errors, 'errors');
1381 $error++;
1382 break;
1383 }
1384 }
1385 } else {
1386 setEventMessage('UserNotFound', 'errors');
1387 $error++;
1388 }
1389
1390 if (!$error) {
1391 if ($nbok > 1) {
1392 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1393 } else {
1394 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1395 }
1396 $db->commit();
1397 $toselect=array();
1398 } else {
1399 $db->rollback();
1400 }
1401}
1402
1403if (!$error && ($massaction == 'enable' || ($action == 'enable' && $confirm == 'yes')) && $permissiontoadd) {
1404 $db->begin();
1405
1406 $objecttmp = new $objectclass($db);
1407 $nbok = 0;
1408 foreach ($toselect as $toselectid) {
1409 $result = $objecttmp->fetch($toselectid);
1410 if ($result>0) {
1411 if (in_array($objecttmp->element, array('societe'))) {
1412 $result =$objecttmp->setStatut(1);
1413 }
1414 if ($result <= 0) {
1415 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1416 $error++;
1417 break;
1418 } else {
1419 $nbok++;
1420 }
1421 } else {
1422 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1423 $error++;
1424 break;
1425 }
1426 }
1427
1428 if (!$error) {
1429 if ($nbok > 1) {
1430 setEventMessages($langs->trans("RecordsEnabled", $nbok), null, 'mesgs');
1431 } else {
1432 setEventMessages($langs->trans("RecordEnabled"), null, 'mesgs');
1433 }
1434 $db->commit();
1435 } else {
1436 $db->rollback();
1437 }
1438}
1439
1440if (!$error && ($massaction == 'disable' || ($action == 'disable' && $confirm == 'yes')) && $permissiontoadd) {
1441 $db->begin();
1442
1443 $objecttmp = new $objectclass($db);
1444 $nbok = 0;
1445 foreach ($toselect as $toselectid) {
1446 $result = $objecttmp->fetch($toselectid);
1447 if ($result>0) {
1448 if (in_array($objecttmp->element, array('societe'))) {
1449 $result =$objecttmp->setStatut(0);
1450 }
1451 if ($result <= 0) {
1452 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1453 $error++;
1454 break;
1455 } else {
1456 $nbok++;
1457 }
1458 } else {
1459 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1460 $error++;
1461 break;
1462 }
1463 }
1464
1465 if (!$error) {
1466 if ($nbok > 1) {
1467 setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
1468 } else {
1469 setEventMessages($langs->trans("RecordDisabled"), null, 'mesgs');
1470 }
1471 $db->commit();
1472 } else {
1473 $db->rollback();
1474 }
1475}
1476
1477if (!$error && $action == 'confirm_edit_value_extrafields' && $confirm == 'yes' && $permissiontoadd) {
1478 $db->begin();
1479
1480 $objecttmp = new $objectclass($db);
1481 $e = new ExtraFields($db);// fetch optionals attributes and labels
1482 $e->fetch_name_optionals_label($objecttmp->table_element);
1483
1484 $nbok = 0;
1485 $extrafieldKeyToUpdate = GETPOST('extrafield-key-to-update');
1486
1487
1488 foreach ($toselect as $toselectid) {
1490 $objecttmp = new $objectclass($db); // to avoid ghost data
1491 $result = $objecttmp->fetch($toselectid);
1492 if ($result>0) {
1493 // Fill array 'array_options' with data from add form
1494 $ret = $e->setOptionalsFromPost(null, $objecttmp, $extrafieldKeyToUpdate);
1495 if ($ret > 0) {
1496 $objecttmp->insertExtraFields();
1497 } else {
1498 $error++;
1499 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1500 }
1501 } else {
1502 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1503 $error++;
1504 break;
1505 }
1506 }
1507
1508 if (!$error) {
1509 if ($nbok > 1) {
1510 setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
1511 } else {
1512 setEventMessages($langs->trans("save"), null, 'mesgs');
1513 }
1514 $db->commit();
1515 } else {
1516 $db->rollback();
1517 }
1518}
1519
1520if (!$error && ($massaction == 'affectcommercial' || ($action == 'affectcommercial' && $confirm == 'yes')) && $permissiontoadd) {
1521 $db->begin();
1522
1523 $objecttmp = new $objectclass($db);
1524 $nbok = 0;
1525
1526 foreach ($toselect as $toselectid) {
1527 $result = $objecttmp->fetch($toselectid);
1528 if ($result>0) {
1529 if (in_array($objecttmp->element, array('societe'))) {
1530 $result = $objecttmp->setSalesRep(GETPOST("commercial", "alpha"));
1531 }
1532 if ($result <= 0) {
1533 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1534 $error++;
1535 break;
1536 } else {
1537 $nbok++;
1538 }
1539 } else {
1540 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1541 $error++;
1542 break;
1543 }
1544 }
1545
1546 if (!$error) {
1547 if ($nbok > 1) {
1548 setEventMessages($langs->trans("CommercialsAffected", $nbok), null, 'mesgs');
1549 } else {
1550 setEventMessages($langs->trans("CommercialAffected"), null, 'mesgs');
1551 }
1552 $db->commit();
1553 } else {
1554 $db->rollback();
1555 }
1556}
1557
1558// Approve for leave only
1559if (!$error && ($massaction == 'approveleave' || ($action == 'approveleave' && $confirm == 'yes')) && $permissiontoapprove) {
1560 $db->begin();
1561
1562 $objecttmp = new $objectclass($db);
1563 $nbok = 0;
1564 foreach ($toselect as $toselectid) {
1565 $result = $objecttmp->fetch($toselectid);
1566 if ($result > 0) {
1567 if ($objecttmp->statut != Holiday::STATUS_VALIDATED) {
1568 setEventMessages($langs->trans('StatusOfRefMustBe', $objecttmp->ref, $langs->transnoentitiesnoconv('Validated')), null, 'warnings');
1569 continue;
1570 }
1571 if ($user->id == $objecttmp->fk_validator) {
1572 $objecttmp->oldcopy = dol_clone($objecttmp);
1573
1574 $objecttmp->date_valid = dol_now();
1575 $objecttmp->fk_user_valid = $user->id;
1576 $objecttmp->statut = Holiday::STATUS_APPROVED;
1577
1578 $verif = $objecttmp->approve($user);
1579
1580 if ($verif <= 0) {
1581 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1582 $error++;
1583 }
1584
1585 // If no SQL error, we redirect to the request form
1586 if (!$error) {
1587 // Calculcate number of days consumed
1588 $nbopenedday = num_open_day($objecttmp->date_debut_gmt, $objecttmp->date_fin_gmt, 0, 1, $objecttmp->halfday);
1589 $soldeActuel = $objecttmp->getCpforUser($objecttmp->fk_user, $objecttmp->fk_type);
1590 $newSolde = ($soldeActuel - $nbopenedday);
1591
1592 // The modification is added to the LOG
1593 $result = $objecttmp->addLogCP($user->id, $objecttmp->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $objecttmp->fk_type);
1594 if ($result < 0) {
1595 $error++;
1596 setEventMessages(null, $objecttmp->errors, 'errors');
1597 }
1598
1599 // Update balance
1600 $result = $objecttmp->updateSoldeCP($objecttmp->fk_user, $newSolde, $objecttmp->fk_type);
1601 if ($result < 0) {
1602 $error++;
1603 setEventMessages(null, $objecttmp->errors, 'errors');
1604 }
1605 }
1606
1607 if (!$error) {
1608 // To
1609 $destinataire = new User($db);
1610 $destinataire->fetch($objecttmp->fk_user);
1611 $emailTo = $destinataire->email;
1612
1613 if (!$emailTo) {
1614 dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email");
1615 } else {
1616 // From
1617 $expediteur = new User($db);
1618 $expediteur->fetch($objecttmp->fk_validator);
1619 //$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
1620 $emailFrom = $conf->global->MAIN_MAIL_EMAIL_FROM;
1621
1622 // Subject
1623 $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
1624 if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
1625 $societeName = $conf->global->MAIN_APPLICATION_TITLE;
1626 }
1627
1628 $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysValidated");
1629
1630 // Content
1631 $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n";
1632 $message .= "\n";
1633
1634 $message .= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($objecttmp->date_debut, 'day'), dol_print_date($objecttmp->date_fin, 'day'))."\n";
1635
1636 $message .= "- ".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n";
1637
1638 $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$objecttmp->id."\n\n";
1639 $message .= "\n";
1640
1641 $trackid = 'leav'.$objecttmp->id;
1642
1643 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1644 $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid);
1645
1646 // Sending email
1647 $result = $mail->sendfile();
1648
1649 if (!$result) {
1650 setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1
1651 $action = '';
1652 }
1653 }
1654 }
1655 } else {
1656 $langs->load("errors");
1657 setEventMessages($langs->trans('ErrorNotApproverForHoliday', $objecttmp->ref), null, 'errors');
1658 }
1659 } else {
1660 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1661 $error++;
1662 break;
1663 }
1664 }
1665
1666 if (!$error) {
1667 if ($nbok > 1) {
1668 setEventMessages($langs->trans("RecordsApproved", $nbok), null, 'mesgs');
1669 } elseif ($nbok == 1) {
1670 setEventMessages($langs->trans("RecordAproved"), null, 'mesgs');
1671 }
1672 $db->commit();
1673 } else {
1674 $db->rollback();
1675 }
1676}
1677
1678if (!$error && ($massaction == 'increaseholiday' || ($action == 'increaseholiday' && $confirm == 'yes')) && $permissiontoapprove) {
1679 $db->begin();
1680 $objecttmp = new $objectclass($db);
1681 $nbok = 0;
1682 $typeholiday = GETPOST('typeholiday', 'alpha');
1683 $nbdaysholidays = GETPOST('nbdaysholidays', 'double');
1684
1685 if ($nbdaysholidays <= 0) {
1686 setEventMessages($langs->trans("WrongAmount"), "", 'errors');
1687 $error++;
1688 }
1689
1690 if (!$error) {
1691 foreach ($toselect as $toselectid) {
1692 $balancecpuser = $objecttmp->getCPforUser($toselectid, $typeholiday);
1693 if (!empty($balancecpuser)) {
1694 $newnbdaysholidays = $nbdaysholidays + $balancecpuser;
1695 } else {
1696 $newnbdaysholidays = $nbdaysholidays;
1697 }
1698 $result = $holiday->addLogCP($user->id, $toselectid, $langs->transnoentitiesnoconv('ManualUpdate'), $newnbdaysholidays, $typeholiday);
1699 if ($result <= 0) {
1700 setEventMessages($holiday->error, $holiday->errors, 'errors');
1701 $error++;
1702 break;
1703 }
1704
1705 $objecttmp->updateSoldeCP($toselectid, $newnbdaysholidays, $typeholiday);
1706 if ($result > 0) {
1707 $nbok++;
1708 } else {
1709 setEventMessages("", $langs->trans("ErrorUpdatingUsersCP"), 'errors');
1710 $error++;
1711 break;
1712 }
1713 }
1714 }
1715
1716 if (!$error) {
1717 if ($nbok > 1) {
1718 setEventMessages($langs->trans("HolidayRecordsIncreased", $nbok), null, 'mesgs');
1719 } elseif ($nbok == 1) {
1720 setEventMessages($langs->trans("HolidayRecordIncreased"), null, 'mesgs');
1721 }
1722 $db->commit();
1723 $toselect=array();
1724 } else {
1725 $db->rollback();
1726 }
1727}
1728
1729//if (!$error && $massaction == 'clonetasks' && $user->rights->projet->creer) {
1730if (!$error && ($massaction == 'clonetasks' || ($action == 'clonetasks' && $confirm == 'yes'))) {
1731 $num = 0;
1732
1733 dol_include_once('/projet/class/task.class.php');
1734
1735 $origin_task = new Task($db);
1736 $clone_task = new Task($db);
1737
1738 foreach (GETPOST('selected') as $task) {
1739 $origin_task->fetch($task, $ref = '', $loadparentdata = 0);
1740
1741 $defaultref = '';
1742 $obj = empty($conf->global->PROJECT_TASK_ADDON) ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON;
1743 if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . $conf->global->PROJECT_TASK_ADDON . ".php")) {
1744 require_once DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . $conf->global->PROJECT_TASK_ADDON . '.php';
1745 $modTask = new $obj;
1746 $defaultref = $modTask->getNextValue(0, $clone_task);
1747 }
1748
1749 if (!$error) {
1750 $clone_task->fk_project = GETPOST('projectid', 'int');
1751 $clone_task->ref = $defaultref;
1752 $clone_task->label = $origin_task->label;
1753 $clone_task->description = $origin_task->description;
1754 $clone_task->planned_workload = $origin_task->planned_workload;
1755 $clone_task->fk_task_parent = $origin_task->fk_task_parent;
1756 $clone_task->date_c = dol_now();
1757 $clone_task->date_start = $origin_task->date_start;
1758 $clone_task->date_end = $origin_task->date_end;
1759 $clone_task->progress = $origin_task->progress;
1760
1761 // Fill array 'array_options' with data from add form
1762 $ret = $extrafields->setOptionalsFromPost(null, $clone_task);
1763
1764 $taskid = $clone_task->create($user);
1765
1766 if ($taskid > 0) {
1767 $result = $clone_task->add_contact(GETPOST("userid", 'int'), 'TASKEXECUTIVE', 'internal');
1768 $num++;
1769 } else {
1770 if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1771 $langs->load("projects");
1772 setEventMessages($langs->trans('NewTaskRefSuggested'), '', 'warnings');
1773 $duplicate_code_error = true;
1774 } else {
1775 setEventMessages($clone_task->error, $clone_task->errors, 'errors');
1776 }
1777 $action = 'list';
1778 $error++;
1779 }
1780 }
1781 }
1782
1783 if (!$error) {
1784 setEventMessage($langs->trans('NumberOfTasksCloned', $num));
1785 header("Refresh: 1;URL=".DOL_URL_ROOT.'/projet/tasks.php?id=' . GETPOST('projectid', 'int'));
1786 }
1787}
1788
1789$parameters['toselect'] = (empty($toselect) ? array() : $toselect);
1790$parameters['uploaddir'] = $uploaddir;
1791$parameters['massaction'] = $massaction;
1792$parameters['diroutputmassaction'] = isset($diroutputmassaction) ? $diroutputmassaction : null;
1793
1794$reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1795if ($reshook < 0) {
1796 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1797}
$object ref
Definition info.php:78
Class to manage members of a foundation.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage categories.
Class to manage customers orders.
const STATUS_DRAFT
Draft status.
const STATUS_VALIDATED
Validated status.
Class for ConferenceOrBoothAttendee.
Class to manage contact/addresses.
Class to manage standard extra fields.
const STATUS_DRAFT
Draft status.
const STATUS_VALIDATED
Validated (need to be paid)
const STATUS_VALIDATED
Validated status.
const STATUS_DRAFT
Draft status.
const STATUS_REFUSED
Refused.
const STATUS_CANCELED
Canceled.
const STATUS_APPROVED
Approved.
const STATUS_DRAFT
Draft status.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage tasks.
Class to manage translations.
Class to manage Dolibarr users.
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $country_code='')
Function to return number of working days (and text of units) between two dates (working days)
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png) $', '^\.'), $nohook=false, $mode='')
Return file(s) into a directory (by default most recent)
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:62
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0)
Set event message in dol_events session object.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null, $include=null)
Return array of possible common substitutions.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
pdf_getFormat(Translate $outputlangs=null, $mode='setup')
Return array with format properties of default PDF format.
Definition pdf.lib.php:85
pdf_getPDFFont($outputlangs)
Return font name to use for PDF generation.
Definition pdf.lib.php:266
pdf_getInstance($format='', $metric='mm', $pagetype='P')
Return a PDF instance object.
Definition pdf.lib.php:127
dol_hash($chain, $type='0')
Returns a hash (non reversible encryption) of a string.