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