dolibarr 23.0.3
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 } else {
509 $from = GETPOST('fromname').' <'.GETPOST('frommail').'>';
510 }
511
512 $replyto = $from;
513 $subject = GETPOST('subject', 'restricthtml');
514 $message = GETPOST('message', 'restricthtml');
515
516 $sendtobcc = GETPOST('sendtoccc');
517 if ($objectclass == 'Propal') {
518 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROPOSAL_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROPOSAL_TO')));
519 }
520 if ($objectclass == 'Commande') {
521 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_ORDER_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_ORDER_TO')));
522 }
523 if ($objectclass == 'Facture') {
524 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_INVOICE_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_INVOICE_TO')));
525 }
526 if ($objectclass == 'SupplierProposal') {
527 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO')));
528 }
529 if ($objectclass == 'CommandeFournisseur') {
530 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO')));
531 }
532 if ($objectclass == 'FactureFournisseur') {
533 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO')));
534 }
535 if ($objectclass == 'Project') {
536 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROJECT_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROJECT_TO')));
537 }
538
539 // $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)
540 // $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)
541 $looparray = array();
542 if (!$oneemailperrecipient) {
543 $looparray = $listofqualifiedobj;
544 foreach ($looparray as $key => $objecttmp) {
545 $looparray[$key]->thirdparty = $thirdparty; // Force thirdparty on object
546 }
547 } else {
548 $objectforloop = new $objectclass($db);
549 $objectforloop->thirdparty = $thirdparty; // Force thirdparty on object (even if object was not loaded)
550 $looparray[0] = $objectforloop;
551 }
552 //var_dump($looparray);exit;
553 dol_syslog("We have set an array of ".count($looparray)." emails to send. oneemailperrecipient=".$oneemailperrecipient);
554 //var_dump($oneemailperrecipient); var_dump($listofqualifiedobj); var_dump($listofqualifiedref);
555 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
556 // Make substitution in email content
557 if (isModEnabled('project') && method_exists($objecttmp, 'fetchProject') && is_null($objecttmp->project)) {
558 $objecttmp->fetchProject();
559 }
560 $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $objecttmp);
561 $substitutionarray['__ID__'] = ($oneemailperrecipient ? implode(', ', array_keys($listofqualifiedobj)) : $objecttmp->id);
562 $substitutionarray['__REF__'] = ($oneemailperrecipient ? implode(', ', $listofqualifiedref) : $objecttmp->ref);
563 $substitutionarray['__EMAIL__'] = $thirdparty->email;
564 $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"/>';
565
566 if ($oneemailperrecipient) {
567 $substitutionarray['__ONLINE_PAYMENT_URL__'] = '';
568 $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = '';
569 }
570
571 $parameters = array('mode' => 'formemail');
572
573 if (!empty($listofobjectthirdparties)) {
574 $parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
575 }
576 if (!empty($listofobjectref)) {
577 $parameters['listofobjectref'] = $listofobjectref;
578 }
579
580 complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
581
582 $subjectreplaced = make_substitutions($subject, $substitutionarray);
583 $messagereplaced = make_substitutions($message, $substitutionarray);
584
585 $attachedfiles = array('paths' => array(), 'names' => array(), 'mimes' => array());
586 if ($oneemailperrecipient) {
587 // if "one email per recipient" is check we must collate $attachedfiles by thirdparty
588 if (is_array($attachedfilesThirdpartyObj[$thirdparty->id]) && count($attachedfilesThirdpartyObj[$thirdparty->id])) { // @phpstan-ignore-line
589 foreach ($attachedfilesThirdpartyObj[$thirdparty->id] as $keyObjId => $objAttachedFiles) {
590 // Create form object
591 $attachedfiles = array(
592 'paths' => array_merge($attachedfiles['paths'], $objAttachedFiles['paths']),
593 'names' => array_merge($attachedfiles['names'], $objAttachedFiles['names']),
594 'mimes' => array_merge($attachedfiles['mimes'], $objAttachedFiles['mimes'])
595 );
596 }
597 }
598 } elseif (!empty($attachedfilesThirdpartyObj[$thirdparty->id][$objectid])) {
599 // Create form object
600 // if "one email per recipient" isn't check we must separate $attachedfiles by object
601 $attachedfiles = $attachedfilesThirdpartyObj[$thirdparty->id][$objectid];
602 }
603
604 $filepath = $attachedfiles['paths'];
605 $filename = $attachedfiles['names'];
606 $mimetype = $attachedfiles['mimes'];
607
608 // Define the trackid when emails sent from the mass action
609 if ($oneemailperrecipient) {
610 $trackid = 'thi'.$thirdparty->id;
611 if ($objecttmp->element == 'expensereport') {
612 $trackid = 'use'.$thirdparty->id;
613 } elseif ($objecttmp->element == 'contact') {
614 $trackid = 'ctc'.$thirdparty->id;
615 } elseif ($objecttmp->element == 'holiday') {
616 $trackid = 'use'.$thirdparty->id;
617 }
618 } else {
619 $trackid = strtolower(get_class($objecttmp));
620 if (get_class($objecttmp) == 'Contact') {
621 $trackid = 'ctc';
622 } elseif (get_class($objecttmp) == 'Contrat') {
623 $trackid = 'con';
624 } elseif (get_class($objecttmp) == 'Propal') {
625 $trackid = 'pro';
626 } elseif (get_class($objecttmp) == 'Commande') {
627 $trackid = 'ord';
628 } elseif (get_class($objecttmp) == 'Facture') {
629 $trackid = 'inv';
630 } elseif (get_class($objecttmp) == 'SupplierProposal') {
631 $trackid = 'spr';
632 } elseif (get_class($objecttmp) == 'CommandeFournisseur') {
633 $trackid = 'sor';
634 } elseif (get_class($objecttmp) == 'FactureFournisseur') {
635 $trackid = 'sin';
636 }
637
638 $trackid .= $objecttmp->id;
639 }
640 //var_dump($filepath);
641 //var_dump($trackid);exit;
642 //var_dump($subjectreplaced);
643
644 if (empty($sendcontext)) {
645 $sendcontext = 'standard';
646 }
647
648 // Set tmp user directory (used to convert images embedded as img src=data:image)
649 $vardir = $conf->user->dir_output."/".$user->id;
650 $upload_dir_tmp = $vardir.'/temp'; // TODO Add $keytoavoidconflict in upload_dir path
651
652 // Send mail (substitutionarray must be done just before this)
653 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
654 $mailfile = new CMailFile($subjectreplaced, (string) $sendto, $from, $messagereplaced, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, (int) $deliveryreceipt, -1, '', '', $trackid, '', $sendcontext, '', $upload_dir_tmp);
655 if ($mailfile->error) {
656 $resaction .= '<div class="error">'.$mailfile->error.'</div>';
657 } else {
658 $result = $mailfile->sendfile();
659 if ($result > 0) {
660 $resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($mailfile->addr_from, 2), $mailfile->getValidAddress($mailfile->addr_to, 2)).'<br>'; // Must not contain "
661
662 $error = 0;
663
664 // Insert logs into agenda
665 foreach ($listofqualifiedobj as $objid2 => $objectobj2) {
666 if ((!$oneemailperrecipient) && $objid2 != $objectid) {
667 continue; // We discard this pass to avoid duplicate with other pass in looparray at higher level
668 }
669
670 dol_syslog("Try to insert email event into agenda for objid=".$objid2." => objectobj=".get_class($objectobj2));
671
672 /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
673 if ($objectclass == 'Commande') $actiontypecode='AC_COM';
674 if ($objectclass == 'Facture') $actiontypecode='AC_FAC';
675 if ($objectclass == 'SupplierProposal') $actiontypecode='AC_SUP_PRO';
676 if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
677 if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
678
679 $actionmsg = $langs->transnoentities('MailSentByTo', $from, (string) $sendto);
680 if ($message) {
681 if ($sendtocc) {
682 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc);
683 }
684 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subjectreplaced);
685 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
686 $actionmsg = dol_concatdesc($actionmsg, $messagereplaced);
687 }
688 $actionmsg2 = '';
689
690 // Initialisation donnees
691 $objectobj2->sendtoid = (empty($contactidtosend) ? 0 : $contactidtosend);
692 $objectobj2->actionmsg = $actionmsg; // Long text
693 $objectobj2->actionmsg2 = $actionmsg2; // Short text
694 $objectobj2->fk_element = $objid2;
695 $objectobj2->elementtype = $objectobj2->element;
696 if (getDolGlobalString('MAIN_MAIL_REPLACE_EVENT_TITLE_BY_EMAIL_SUBJECT')) {
697 $objectobj2->actionmsg2 = $subjectreplaced; // Short text
698 }
699
700 $triggername = strtoupper(get_class($objectobj2)).'_SENTBYMAIL';
701 if ($triggername == 'SOCIETE_SENTBYMAIL') {
702 $triggername = 'COMPANY_SENTBYMAIL';
703 }
704 if ($triggername == 'CONTRAT_SENTBYMAIL') {
705 $triggername = 'CONTRACT_SENTBYMAIL';
706 }
707 if ($triggername == 'COMMANDE_SENTBYMAIL') {
708 $triggername = 'ORDER_SENTBYMAIL';
709 }
710 if ($triggername == 'FACTURE_SENTBYMAIL') {
711 $triggername = 'BILL_SENTBYMAIL';
712 }
713 if ($triggername == 'EXPEDITION_SENTBYMAIL') {
714 $triggername = 'SHIPPING_SENTBYMAIL';
715 }
716 if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') {
717 $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
718 }
719 if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') {
720 $triggername = 'BILL_SUPPLIER_SENTBYMAIL';
721 }
722 if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') {
723 $triggername = 'PROPOSAL_SUPPLIER_SENTBYMAIL';
724 }
725 if ($triggername == 'PROJET_SENTBYMAIL') {
726 $triggername = 'PROJECT_SENTBYMAIL';
727 }
728
729 if (!empty($triggername)) {
730 // Call trigger
731 $result = $objectobj2->call_trigger($triggername, $user);
732 if ($result < 0) {
733 $error++;
734 }
735 // End call triggers
736
737 if ($error) {
738 setEventMessages($db->lasterror(), null, 'errors');
739 dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR);
740 }
741 }
742
743 $nbsent++; // Nb of object sent
744 }
745 } else {
746 $langs->load("other");
747 if ($mailfile->error) {
748 $resaction .= $langs->trans('ErrorFailedToSendMail', $from, (string) $sendto);
749 $resaction .= '<br><div class="error">'.$mailfile->error.'</div>';
750 } elseif (getDolGlobalString('MAIN_DISABLE_ALL_MAILS')) {
751 $resaction .= '<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
752 } else {
753 $resaction .= $langs->trans('ErrorFailedToSendMail', $from, (string) $sendto) . '<br><div class="error">(unhandled error)</div>';
754 }
755 }
756 }
757 }
758 }
759 }
760
761 $resaction .= ($resaction ? '<br>' : $resaction);
762 $resaction .= '<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
763 $resaction .= $langs->trans("NbSelected").': '.count($toselect)."\n<br>";
764 $resaction .= $langs->trans("NbIgnored").': '.($nbignored ? $nbignored : 0)."\n<br>";
765 $resaction .= $langs->trans("NbSent").': '.($nbsent ? $nbsent : 0)."\n<br>";
766
767 if ($nbsent) {
768 $action = ''; // Do not show form post if there was at least one successful sent
769 //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
770 setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
771 setEventMessages($resaction, null, 'mesgs');
772 } else {
773 //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file
774 setEventMessages($resaction, null, 'warnings');
775 }
776
777 $action = 'list';
778 $massaction = '';
779 }
780}
781
782
783if (!$error && $massaction == 'cancelorders') {
784 $db->begin();
785
786 $nbok = 0;
787
788 $orders = GETPOST('toselect', 'array:int');
789 foreach ($orders as $id_order) {
790 $cmd = new Commande($db);
791 if ($cmd->fetch($id_order) <= 0) {
792 continue;
793 }
794
795 if ($cmd->status != Commande::STATUS_VALIDATED) {
796 $langs->load('errors');
797 setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
798 $error++;
799 break;
800 } else {
801 // TODO We do not provide warehouse so no stock change here for the moment.
802 $result = $cmd->cancel($user);
803 }
804
805 if ($result < 0) {
806 setEventMessages($cmd->error, $cmd->errors, 'errors');
807 $error++;
808 break;
809 } else {
810 $nbok++;
811 }
812 }
813 if (!$error) {
814 setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
815 $db->commit();
816 } else {
817 $db->rollback();
818 }
819}
820
821
822if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search')) {
823 if (empty($diroutputmassaction)) {
824 dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
825 exit;
826 }
827
828 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
829 require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
830 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
831
832 $objecttmp = new $objectclass($db);
833 $listofobjectid = array();
834 $listofobjectthirdparties = array();
835 $listofobjectref = array();
836 foreach ($toselect as $toselectid) {
837 $objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use
838 $result = $objecttmp->fetch($toselectid);
839 if ($result > 0) {
840 $listofobjectid[$toselectid] = $toselectid;
841 $thirdpartyid = !empty($objecttmp->fk_soc) ? $objecttmp->fk_soc : $objecttmp->socid;
842 $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
843 $listofobjectref[$toselectid] = $objecttmp->ref;
844 }
845 }
846
847 $arrayofinclusion = array();
848 $parameters = array(
849 'listofobjectref' => $listofobjectref,
850 'arrayofinclusion' => &$arrayofinclusion,
851 );
852 $reshook = $hookmanager->executeHooks('updateSearchRegexToMergeDoc', $parameters, $object, $action);
853
854 if (empty($reshook)) {
855 foreach ($listofobjectref as $tmppdf) {
856 $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$';
857 }
858 foreach ($listofobjectref as $tmppdf) {
859 $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[\w\-\'\&\.]+\.pdf$'; // To include PDF generated from ODX files
860 }
861 }
862
863 $listoffiles = dol_dir_list($uploaddir, 'all', 1, $arrayofinclusion, '\.meta$|\.png$', 'date', SORT_DESC, 0, 1);
864
865 dol_syslog("Found ".count($listoffiles)." files");
866
867 // build list of files with full path
868 $files = array();
869
870 foreach ($listofobjectref as $basename) {
871 $basename = dol_sanitizeFileName($basename);
872 foreach ($listoffiles as $filefound) {
873 if (strstr($filefound["name"], $basename)) {
874 $files[] = $filefound['fullname'];
875 break;
876 }
877 }
878 }
879
880 // Define output language (Here it is not used because we do only merging existing PDF)
881 $outputlangs = $langs;
882 $newlang = '';
883 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
884 $newlang = GETPOST('lang_id', 'aZ09');
885 }
886 //elseif (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && is_object($objecttmp->thirdparty)) { // On massaction, we can have several values for $objecttmp->thirdparty
887 // $newlang = $objecttmp->thirdparty->default_lang;
888 //}
889 if (!empty($newlang)) {
890 $outputlangs = new Translate("", $conf);
891 $outputlangs->setDefaultLang($newlang);
892 }
893
894 if (getDolGlobalString('USE_PDFTK_FOR_PDF_CONCAT')) {
895 // Create output dir if not exists
896 dol_mkdir($diroutputmassaction);
897
898 // Defined name of merged file
899 $filename = strtolower(dol_sanitizeFileName($langs->transnoentities((string) $objectlabel)));
900 $filename = preg_replace('/\s/', '_', $filename);
901
902 // Save merged file
903 if (in_array($objecttmp->element, array('facture', 'invoice_supplier')) && $search_status == Facture::STATUS_VALIDATED) {
904 if ($option == 'late') {
905 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
906 } else {
907 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
908 }
909 }
910 if ($year) {
911 $filename .= '_'.$year;
912 }
913 if ($month) {
914 $filename .= '_'.$month;
915 }
916
917 if (count($files) > 0) {
918 $now = dol_now();
919 $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
920
921 $input_files = '';
922 foreach ($files as $f) {
923 $input_files .= ' '.escapeshellarg($f);
924 }
925
926 $cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file);
927 exec($cmd);
928
929 // check if pdftk is installed
930 if (file_exists($file)) {
931 dolChmod($file);
932
933 $langs->load("exports");
934 setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
935 } else {
936 setEventMessages($langs->trans('ErrorPDFTkOutputFileNotFound'), null, 'errors');
937 }
938 } else {
939 setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
940 }
941 } else {
942 // Create empty PDF
943 $formatarray = pdf_getFormat();
944 $page_largeur = $formatarray['width'];
945 $page_hauteur = $formatarray['height'];
946 $format = array($page_largeur, $page_hauteur);
947
948 $pdf = pdf_getInstance($format);
949
950 if (class_exists('TCPDF')) {
951 $pdf->setPrintHeader(false);
952 $pdf->setPrintFooter(false);
953 }
954 $pdf->SetFont(pdf_getPDFFont($outputlangs));
955
956 if (getDolGlobalString('MAIN_DISABLE_PDF_COMPRESSION')) {
957 $pdf->SetCompression(false);
958 }
959
960 $pagecount = 0;
961 // Add all others
962 foreach ($files as $file) {
963 // Charge un document PDF depuis un fichier.
964 $pagecount = $pdf->setSourceFile($file);
965 for ($i = 1; $i <= $pagecount; $i++) {
966 $tplidx = $pdf->importPage($i);
967 $s = $pdf->getTemplatesize($tplidx);
968 $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
969 $pdf->useTemplate($tplidx);
970 }
971 }
972
973 // Create output dir if not exists
974 dol_mkdir($diroutputmassaction);
975
976 // Defined name of merged file
977 $filename = strtolower(dol_sanitizeFileName($langs->transnoentities((string) $objectlabel)));
978 $filename = preg_replace('/\s/', '_', $filename);
979
980
981 // Save merged file
982 if (in_array($objecttmp->element, array('facture', 'invoice_supplier')) && $search_status == Facture::STATUS_VALIDATED) {
983 if ($option == 'late') {
984 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
985 } else {
986 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
987 }
988 }
989 if (!empty($year)) {
990 $filename .= '_'.$year;
991 }
992 if (!empty($month)) {
993 $filename .= '_'.$month;
994 }
995 if ($pagecount) {
996 $now = dol_now();
997 $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
998 $pdf->Output($file, 'F');
999 dolChmod($file);
1000
1001 $langs->load("exports");
1002 setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
1003 } else {
1004 setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
1005 }
1006 }
1007}
1008
1009// Remove a file from massaction area
1010if ($action == 'remove_file') {
1011 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1012
1013 $langs->load("other");
1014 $upload_dir = $diroutputmassaction;
1015 $file = $upload_dir.'/'.GETPOST('file');
1016 $ret = dol_delete_file($file);
1017 if ($ret) {
1018 setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
1019 } else {
1020 setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
1021 }
1022 $action = '';
1023}
1024
1025
1026// Validate records
1027if (!$error && $massaction == 'validate' && $permissiontoadd) {
1028 $objecttmp = new $objectclass($db);
1029
1030 if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
1031 $langs->load("errors");
1032 setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1033 $error++;
1034 }
1035 if ($objecttmp->element == 'invoice_supplier' && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL')) {
1036 $langs->load("errors");
1037 setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1038 $error++;
1039 }
1040 if ($objecttmp->element == 'facture') {
1041 if (!empty($toselect) && getDolGlobalString('INVOICE_CHECK_POSTERIOR_DATE')) {
1042 // order $toselect by date
1043 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture";
1044 $sql .= " WHERE rowid IN (".$db->sanitize(implode(",", $toselect)).")";
1045 $sql .= " ORDER BY datef";
1046
1047 $resql = $db->query($sql);
1048 if ($resql) {
1049 $toselectnew = [];
1050 while (!empty($arr = $db->fetch_row($resql))) {
1051 $toselectnew[] = $arr[0];
1052 }
1053 $toselect = (empty($toselectnew)) ? $toselect : $toselectnew;
1054 } else {
1055 dol_print_error($db);
1056 $error++;
1057 }
1058 }
1059 }
1060 if (!$error) {
1061 // MAIN_MASSVALIDATE_<OBJECTCLASS>_NO_GLOBAL_TRANSACTION = 1 wraps each
1062 // record in its own transaction instead of all-or-nothing. Modules
1063 // dealing with external systems (e.g. VeriFactu / AEAT for invoices)
1064 // can enable it on the list pages they need so a mid-loop failure does
1065 // not roll back the records already committed-and-pushed outside the
1066 // database. The default remains the secured all-or-nothing mode (#37365).
1067 $perrecordtransaction = (int) getDolGlobalInt('MAIN_MASSVALIDATE_'.strtoupper($objectclass).'_NO_GLOBAL_TRANSACTION');
1068 if (!$perrecordtransaction) {
1069 $db->begin();
1070 }
1071
1072 $nbok = 0;
1073 foreach ($toselect as $toselectid) {
1074 if ($perrecordtransaction) {
1075 $db->begin();
1076 }
1077 $result = $objecttmp->fetch($toselectid);
1078 if ($result > 0) {
1079 if (method_exists($objecttmp, 'validate')) {
1080 $result = $objecttmp->validate($user);
1081 } elseif (method_exists($objecttmp, 'setValid')) {
1082 $result = $objecttmp->setValid($user);
1083 } else {
1084 $objecttmp->error = 'No method validate or setValid on this object';
1085 $result = -1;
1086 }
1087 if ($result == 0) {
1088 $langs->load("errors");
1089 setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
1090 $error++;
1091 if ($perrecordtransaction) {
1092 $db->rollback();
1093 }
1094 break;
1095 } elseif ($result < 0) {
1096 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1097 $error++;
1098 if ($perrecordtransaction) {
1099 $db->rollback();
1100 }
1101 break;
1102 } else {
1103 // validate() rename pdf but do not regenerate
1104 // Define output language
1105 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1106 $outputlangs = $langs;
1107 $newlang = '';
1108 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
1109 $newlang = GETPOST('lang_id', 'aZ09');
1110 }
1111 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && property_exists($objecttmp, 'thirdparty')) {
1112 if ((property_exists($objecttmp, 'socid') || property_exists($objecttmp, 'fk_soc')) && empty($objecttmp->thirdparty)) {
1113 $objecttmp->fetch_thirdparty();
1114 }
1115 if (!empty($objecttmp->thirdparty)) {
1116 $newlang = $objecttmp->thirdparty->default_lang;
1117 }
1118 }
1119 if (!empty($newlang)) {
1120 $outputlangs = new Translate("", $conf);
1121 $outputlangs->setDefaultLang($newlang);
1122 $outputlangs->load('products');
1123 }
1124 $model = $objecttmp->model_pdf;
1125 $ret = $objecttmp->fetch($objecttmp->id); // Reload to get new records
1126
1127 // To be sure vars is defined
1128 $hidedetails = isset($hidedetails) ? $hidedetails : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
1129 $hidedesc = isset($hidedesc) ? $hidedesc : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
1130 $hideref = isset($hideref) ? $hideref : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
1131 $moreparams = isset($moreparams) ? $moreparams : null;
1132
1133 $result = $objecttmp->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1134 if ($result < 0) {
1135 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1136 }
1137 }
1138 $nbok++;
1139 if ($perrecordtransaction) {
1140 $db->commit();
1141 }
1142 }
1143 } else {
1144 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1145 $error++;
1146 if ($perrecordtransaction) {
1147 $db->rollback();
1148 }
1149 break;
1150 }
1151 }
1152
1153 if (!$error) {
1154 if ($nbok > 1) {
1155 setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1156 } else {
1157 setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
1158 }
1159 if (!$perrecordtransaction) {
1160 $db->commit();
1161 }
1162 } elseif (!$perrecordtransaction) {
1163 $db->rollback();
1164 }
1165 }
1166}
1167
1168// Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
1169if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) {
1170 $db->begin();
1171
1172 $objecttmp = new $objectclass($db);
1173 $nbok = 0;
1174 $nbignored = 0;
1175 $TMsg = array();
1176
1177 //$toselect could contain duplicate entries, cf https://github.com/Dolibarr/dolibarr/issues/26244
1178 $unique_arr = array_unique($toselect);
1179 foreach ($unique_arr as $toselectid) {
1180 $result = $objecttmp->fetch($toselectid);
1181 if ($result > 0) {
1182 // Refuse deletion for some objects/status
1183 if ($objectclass == 'Facture' && $objecttmp->status != Facture::STATUS_DRAFT) {
1184 $langs->load("errors");
1185 $nbignored++;
1186 $TMsg[] = '<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'</div><br>';
1187 continue;
1188 }
1189
1190 if (method_exists($objecttmp, 'is_erasable') && $objecttmp->is_erasable() <= 0) {
1191 $langs->load("errors");
1192 $nbignored++;
1193 $TMsg[] = '<div class="error">'.$langs->trans('ErrorRecordHasChildren').' '.$objecttmp->ref.'</div><br>';
1194 continue;
1195 }
1196
1197 if ($objectclass == 'Holiday' && ! in_array($objecttmp->statut, array(Holiday::STATUS_DRAFT, Holiday::STATUS_CANCELED, Holiday::STATUS_REFUSED))) {
1198 $langs->load("errors");
1199 $nbignored++;
1200 $TMsg[] = '<div class="error">'.$langs->trans('ErrorLeaveRequestMustBeDraftCanceledOrRefusedToBeDeleted', $objecttmp->ref).'</div><br>';
1201 continue;
1202 }
1203
1204 if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) {
1205 $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".((int) $objecttmp->id);
1206 $res = $db->query($sql);
1207
1208 if (!$res) {
1209 setEventMessage('ErrorRecordParentingNotModified', 'errors');
1210 $error++;
1211 }
1212 }
1213
1214 if ($objecttmp->element == 'societe') {
1216 '@phan-var-force Societe $objecttmp';
1217 // TODO Change signature of delete for Societe
1218 $result = $objecttmp->delete($objecttmp->id, $user, 1);
1219 } else {
1220 $objecttmp->oldcopy = dol_clone($objecttmp);
1221 $result = $objecttmp->delete($user);
1222 }
1223
1224 if (empty($result)) { // if delete returns 0, there is at least one object linked
1225 $TMsg = array_merge($objecttmp->errors, $TMsg);
1226 } elseif ($result < 0) { // if delete returns is < 0, there is an error, we break and rollback later
1227 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1228 $error++;
1229 break;
1230 } else {
1231 $nbok++;
1232 }
1233 } else {
1234 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1235 $error++;
1236 break;
1237 }
1238 }
1239
1240 if (empty($error)) {
1241 // Message for elements well deleted
1242 if ($nbok > 1) {
1243 setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1244 } elseif ($nbok > 0) {
1245 setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1246 } else {
1247 setEventMessages($langs->trans("NoRecordDeleted"), null, 'mesgs');
1248 }
1249
1250 // Message for elements which can't be deleted
1251 if (!empty($TMsg)) {
1252 sort($TMsg);
1253 setEventMessages('', array_unique($TMsg), 'warnings');
1254 }
1255
1256 $db->commit();
1257 } else {
1258 $db->rollback();
1259 }
1260
1261 //var_dump($listofobjectthirdparties);exit;
1262}
1263
1264// Generate document foreach object according to model linked to object
1265// @todo : propose model selection
1266if (!$error && $massaction == 'generate_doc' && $permissiontoread) {
1267 // Complete with classes that use this massaction
1268 <<<'EOPHAN'
1269@phan-var-force 'Commande'|'CommandeFournisseur'|'Contrat'|'Expedition'|'ExpenseReport'|'Facture'|'FactureFournisseur'|'Fichinter'|'Project'|'Propal'|'SupplierProposal' $objectclass
1270EOPHAN;
1271
1272 $db->begin();
1273 $nbok = 0;
1274
1275 $objecttmp = new $objectclass($db);
1276
1277 foreach ($toselect as $toselectid) {
1278 $objecttmp->thirdparty = null; // Clear if another value was already set by fetch_thirdparty later
1279 $result = $objecttmp->fetch($toselectid);
1280
1281 if ($result > 0) {
1282 $outputlangs = $langs;
1283 $newlang = '';
1284
1285 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
1286 $newlang = GETPOST('lang_id', 'aZ09');
1287 }
1288 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) {
1289 $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
1290 }
1291 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->default_lang)) {
1292 $newlang = $objecttmp->default_lang; // for thirdparty @phan-suppress-current-line PhanUndeclaredProperty
1293 }
1294 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && empty($objecttmp->thirdparty)) { //load lang from thirdparty
1295 $objecttmp->fetch_thirdparty();
1296 $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
1297 }
1298 if (!empty($newlang)) {
1299 $outputlangs = new Translate("", $conf);
1300 $outputlangs->setDefaultLang($newlang);
1301 }
1302
1303 // To be sure vars is defined
1304 $hidedetails = isset($hidedetails) ? $hidedetails : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
1305 $hidedesc = isset($hidedesc) ? $hidedesc : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
1306 $hideref = isset($hideref) ? $hideref : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
1307 $moreparams = isset($moreparams) ? $moreparams : null;
1308
1309 $result = $objecttmp->generateDocument($objecttmp->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1310
1311 if ($result <= 0) {
1312 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1313 $error++;
1314 break;
1315 } else {
1316 $nbok++;
1317 }
1318 } else {
1319 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1320 $error++;
1321 break;
1322 }
1323 }
1324
1325 if (!$error) {
1326 if ($nbok > 1) {
1327 setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1328 } else {
1329 setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
1330 }
1331 $db->commit();
1332 } else {
1333 $db->rollback();
1334 }
1335}
1336
1337if (!$error && ($action == 'affecttag' && $confirm == 'yes') && $permissiontoadd) {
1338 $nbok = 0;
1339 $db->begin();
1340
1341 $affecttag_type = GETPOST('affecttag_type', 'alpha');
1342 if (!empty($affecttag_type)) {
1343 $affecttag_type_array = explode(',', $affecttag_type);
1344 } else {
1345 setEventMessage('CategTypeNotFound', 'errors');
1346 }
1347 if (!empty($affecttag_type_array)) {
1348 //check if tag type submitted exists into Tag Map categorie class
1349 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1350 $categ = new Categorie($db);
1351 $to_affecttag_type_array = array();
1352 $categ_type_array = $categ->getMapList();
1353 foreach ($categ_type_array as $categdef) {
1354 if (in_array($categdef['code'], $affecttag_type_array)) {
1355 $to_affecttag_type_array[] = $categdef['code'];
1356 }
1357 }
1358
1359 //For each valid categ type set common categ
1360 if (!empty($to_affecttag_type_array)) {
1361 foreach ($to_affecttag_type_array as $categ_type) {
1362 $contcats = GETPOST('contcats_' . $categ_type, 'array');
1363 //var_dump($toselect);exit;
1364 foreach ($toselect as $toselectid) {
1365 $result = $object->fetch($toselectid);
1366 //var_dump($contcats);exit;
1367 if ($result > 0) {
1368 $result = $object->setCategoriesCommon($contcats, $categ_type, false);
1369 if ($result > 0) {
1370 $nbok++;
1371 } else {
1372 setEventMessages($object->error, $object->errors, 'errors');
1373 }
1374 } else {
1375 setEventMessages($object->error, $object->errors, 'errors');
1376 $error++;
1377 break;
1378 }
1379 }
1380 }
1381 }
1382 }
1383
1384 if (!$error) {
1385 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1386 $db->commit();
1387 $toselect = array();
1388 } else {
1389 $db->rollback();
1390 }
1391}
1392
1393if (!$error && ($action == 'updateprice' && $confirm == 'yes') && $permissiontoadd) {
1394 '@phan-var-force Product|ProductCustomerPrice $obj';
1395 '@phan-var-force Product|ProductCustomerPrice $object';
1396 $nbok = 0;
1397 $db->begin();
1398 if (GETPOSTISSET('pricerate')) {
1399 $pricepercentage = GETPOSTINT('pricerate');
1400 if ($pricepercentage == 0) {
1401 setEventMessages($langs->trans("RecordsModified", 0), null);
1402 } else {
1403 foreach ($toselect as $toselectid) {
1404 $result = $object->fetch($toselectid);
1405 //var_dump($contcats);exit;
1406 if ($result > 0) {
1407 if (getDolGlobalString('PRODUCT_PRICE_UNIQ')
1408 || getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
1409 if ($object->price_base_type == 'TTC') {
1410 $newprice = $object->price_ttc * (100 + $pricepercentage) / 100;
1411 $minprice = $object->price_min_ttc;
1412 } else {
1413 $newprice = $object->price * (100 + $pricepercentage) / 100;
1414 $minprice = $object->price_min;
1415 }
1416 $res = $object->updatePrice($newprice, $object->price_base_type, $user, $object->tva_tx, $minprice, 0, $object->tva_npr, 0, 0, array(), $object->default_vat_code);
1417 if ($res > 0) {
1418 $nbok++;
1419 } else {
1420 setEventMessages($object->error, $object->errors, 'errors');
1421 }
1422 } elseif (getDolGlobalString('PRODUIT_MULTIPRICES')) {
1423 $maxlevel = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
1424 for ($level = 1; $level <= $maxlevel; $level++) {
1425 if ($object->price_base_type == 'TTC') {
1426 $newprice = $object->multiprices_ttc[$level] * (100 + $pricepercentage) / 100;
1427 $minprice = $object->multiprices_min_ttc[$level];
1428 } else {
1429 $newprice = $object->multiprices[$level] * (100 + $pricepercentage) / 100;
1430 $minprice = $object->multiprices_min[$level];
1431 }
1432 $res = $object->updatePrice($newprice, $object->price_base_type, $user, $object->tva_tx, $minprice, $level, $object->tva_npr, 0, 0, array(), $object->default_vat_code);
1433 if ($res > 0) {
1434 $nbok++;
1435 }
1436 }
1437 }
1438 } else {
1439 setEventMessages($object->error, $object->errors, 'errors');
1440 $error++;
1441 break;
1442 }
1443 }
1444 }
1445 }
1446
1447 if (!$error) {
1448 if ($nbok > 0) {
1449 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1450 }
1451 $db->commit();
1452 $toselect = array();
1453 } else {
1454 $db->rollback();
1455 }
1456}
1457
1458if (!$error && ($action == 'setsupervisor' && $confirm == 'yes') && $permissiontoadd) {
1459 '@phan-var-force User $object';
1460 $nbok = 0;
1461 $db->begin();
1462 $supervisortoset = GETPOSTINT('supervisortoset');
1463 if (!empty($supervisortoset)) {
1464 foreach ($toselect as $toselectid) {
1465 $result = $object->fetch($toselectid);
1466 //var_dump($contcats);exit;
1467 if ($result > 0) {
1468 $object->fk_user = $supervisortoset;
1469 $res = $object->update($user);
1470 if ($res > 0) {
1471 $nbok++;
1472 } else {
1473 setEventMessages($object->error, $object->errors, 'errors');
1474 }
1475 } else {
1476 setEventMessages($object->error, $object->errors, 'errors');
1477 $error++;
1478 break;
1479 }
1480 }
1481 } else {
1482 setEventMessage('UserNotFound', 'errors');
1483 $error++;
1484 }
1485
1486 if (!$error) {
1487 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1488 $db->commit();
1489 $toselect = array();
1490 } else {
1491 $db->rollback();
1492 }
1493}
1494
1495if (!$error && ($action == 'affectuser' && $confirm == 'yes') && $permissiontoadd) {
1496 $nbok = 0;
1497 $db->begin();
1498
1499 $usertoaffect = GETPOSTINT('usertoaffect');
1500 $projectrole = GETPOST('projectrole');
1501 $tasksrole = GETPOST('tasksrole');
1502 if (!empty($usertoaffect)) {
1503 foreach ($toselect as $toselectid) {
1504 $result = $object->fetch($toselectid);
1505 //var_dump($contcats);exit;
1506 if ($result > 0) {
1507 $res = $object->add_contact($usertoaffect, $projectrole, 'internal');
1508 if ($res >= 0) {
1509 $taskstatic = new Task($db);
1510 $task_array = $taskstatic->getTasksArray(null, null, $object->id, 0, 0);
1511
1512 foreach ($task_array as $task) {
1513 $tasksToAffect = new Task($db);
1514 $result = $tasksToAffect->fetch($task->id);
1515 if ($result > 0) {
1516 $res = $tasksToAffect->add_contact($usertoaffect, $tasksrole, 'internal');
1517 if ($res < 0) {
1518 setEventMessages($tasksToAffect->error, $tasksToAffect->errors, 'errors');
1519 }
1520 }
1521 }
1522 $nbok++;
1523 } else {
1524 setEventMessages($object->error, $object->errors, 'errors');
1525 }
1526 } else {
1527 setEventMessages($object->error, $object->errors, 'errors');
1528 $error++;
1529 break;
1530 }
1531 }
1532 } else {
1533 setEventMessage('UserNotFound', 'errors');
1534 $error++;
1535 }
1536
1537 if (!$error) {
1538 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1539 $db->commit();
1540 $toselect = array();
1541 } else {
1542 $db->rollback();
1543 }
1544}
1545
1546if (!$error && ($massaction == 'enable' || ($action == 'enable' && $confirm == 'yes')) && $permissiontoadd) {
1547 $db->begin();
1548
1549 $objecttmp = new $objectclass($db);
1550 $nbok = 0;
1551 foreach ($toselect as $toselectid) {
1552 $result = $objecttmp->fetch($toselectid);
1553 if ($result > 0) {
1554 if (in_array($objecttmp->element, array('societe'))) {
1555 $result = $objecttmp->setStatut(1);
1556 }
1557 if ($result <= 0) {
1558 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1559 $error++;
1560 break;
1561 } else {
1562 $nbok++;
1563 }
1564 } else {
1565 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1566 $error++;
1567 break;
1568 }
1569 }
1570
1571 if (!$error) {
1572 if ($nbok > 1) {
1573 setEventMessages($langs->trans("RecordsEnabled", $nbok), null, 'mesgs');
1574 } else {
1575 setEventMessages($langs->trans("RecordEnabled"), null, 'mesgs');
1576 }
1577 $db->commit();
1578 } else {
1579 $db->rollback();
1580 }
1581}
1582
1583if (!$error && ($massaction == 'disable' || ($action == 'disable' && $confirm == 'yes')) && $permissiontoadd) {
1584 $db->begin();
1585
1586 $objecttmp = new $objectclass($db);
1587 $nbok = 0;
1588 foreach ($toselect as $toselectid) {
1589 $result = $objecttmp->fetch($toselectid);
1590 if ($result > 0) {
1591 if (in_array($objecttmp->element, array('societe'))) {
1592 $result = $objecttmp->setStatut(0);
1593 }
1594 if ($result <= 0) {
1595 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1596 $error++;
1597 break;
1598 } else {
1599 $nbok++;
1600 }
1601 } else {
1602 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1603 $error++;
1604 break;
1605 }
1606 }
1607
1608 if (!$error) {
1609 if ($nbok > 1) {
1610 setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
1611 } else {
1612 setEventMessages($langs->trans("RecordDisabled"), null, 'mesgs');
1613 }
1614 $db->commit();
1615 } else {
1616 $db->rollback();
1617 }
1618}
1619
1620if (!$error && $action == 'confirm_edit_value_extrafields' && $confirm == 'yes' && $permissiontoadd) {
1621 $db->begin();
1622
1623 $objecttmp = new $objectclass($db);
1624 $e = new ExtraFields($db);// fetch optionals attributes and labels
1625 $e->fetch_name_optionals_label($objecttmp->table_element);
1626
1627 $nbok = 0;
1628 $extrafieldKeyToUpdate = GETPOST('extrafield-key-to-update');
1629
1630
1631 foreach ($toselect as $toselectid) {
1633 $objecttmp = new $objectclass($db); // to avoid ghost data
1634 $result = $objecttmp->fetch($toselectid);
1635 if ($result > 0) {
1636 // Fill array 'array_options' with data from add form
1637 $ret = $e->setOptionalsFromPost(null, $objecttmp, $extrafieldKeyToUpdate);
1638 if ($ret > 0) {
1639 $objecttmp->insertExtraFields();
1640 } else {
1641 $error++;
1642 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1643 }
1644 } else {
1645 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1646 $error++;
1647 break;
1648 }
1649 }
1650
1651 if (!$error) {
1652 if ($nbok > 1) {
1653 setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
1654 } else {
1655 setEventMessages($langs->trans("save"), null, 'mesgs');
1656 }
1657 $db->commit();
1658 } else {
1659 $db->rollback();
1660 }
1661}
1662
1663if (!$error && ($massaction == 'assignsalerepresentative' || ($action == 'assignsalerepresentative' && $confirm == 'yes')) && $permissiontoadd) {
1664 $db->begin();
1665
1666 $objecttmp = new $objectclass($db);
1667 $nbok = 0;
1668
1669 foreach ($toselect as $toselectid) {
1670 $result = $objecttmp->fetch($toselectid);
1671 if ($result > 0) {
1672 if (in_array($objecttmp->element, array('societe'))) {
1673 $result = $objecttmp->setSalesRep(GETPOST("commercial", "alpha"));
1674 }
1675 if ($result <= 0) {
1676 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1677 $error++;
1678 break;
1679 } else {
1680 $nbok++;
1681 }
1682 } else {
1683 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1684 $error++;
1685 break;
1686 }
1687 }
1688
1689 if (!$error) {
1690 if ($nbok > 1) {
1691 setEventMessages($langs->trans("CommercialsAffected", $nbok), null, 'mesgs');
1692 } else {
1693 setEventMessages($langs->trans("CommercialAffected"), null, 'mesgs');
1694 }
1695 $db->commit();
1696 } else {
1697 $db->rollback();
1698 }
1699}
1700
1701if (!$error && ($massaction == 'unassigncommercial' || ($action == 'unassigncommercial' && $confirm == 'yes')) && $permissiontoadd) {
1702 $db->begin();
1703
1704 $objecttmp = new $objectclass($db);
1705 $nbok = 0;
1706
1707 foreach ($toselect as $toselectid) {
1708 $result = $objecttmp->fetch($toselectid);
1709 if ($result > 0) {
1710 if (in_array($objecttmp->element, array('societe'))) {
1711 $TCommercial = GETPOST("commercial", "alpha");
1712 if (is_array($TCommercial)) {
1713 foreach ($TCommercial as $commercial) {
1714 $result = $objecttmp->del_commercial($user, $commercial);
1715 }
1716 }
1717 }
1718 if ($result <= 0) {
1719 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1720 $error++;
1721 break;
1722 } else {
1723 $nbok++;
1724 }
1725 } else {
1726 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1727 $error++;
1728 break;
1729 }
1730 }
1731
1732 if (!$error) {
1733 if ($nbok > 1) {
1734 setEventMessages($langs->trans("CommercialsDisaffected", $nbok), null, 'mesgs');
1735 } else {
1736 setEventMessages($langs->trans("CommercialDisaffected"), null, 'mesgs');
1737 }
1738 $db->commit();
1739 } else {
1740 $db->rollback();
1741 }
1742}
1743// Approve for leave only
1744if (!$error && ($massaction == 'approveleave' || ($action == 'approveleave' && $confirm == 'yes')) && $permissiontoapprove) {
1745 $db->begin();
1746
1747 $objecttmp = new $objectclass($db);
1748 '@phan-var-force Holiday $objecttmp';
1749 $nbok = 0;
1750 foreach ($toselect as $toselectid) {
1751 $result = $objecttmp->fetch($toselectid);
1752 if ($result > 0) {
1753 if ($objecttmp->status != Holiday::STATUS_VALIDATED) {
1754 setEventMessages($langs->trans('StatusOfRefMustBe', $objecttmp->ref, $langs->transnoentitiesnoconv('Validated')), null, 'warnings');
1755 continue;
1756 }
1757 if ($user->id == $objecttmp->fk_validator) {
1758 $objecttmp->oldcopy = dol_clone($objecttmp, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
1759
1760 $objecttmp->date_valid = dol_now();
1761 $objecttmp->fk_user_valid = $user->id;
1762 $objecttmp->date_approval = dol_now();
1763 $objecttmp->fk_user_approve = $user->id;
1764 $objecttmp->status = Holiday::STATUS_APPROVED;
1765 $objecttmp->statut = $objecttmp->status; // deprecated
1766
1767 $verif = $objecttmp->approve($user);
1768
1769 if ($verif <= 0) {
1770 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1771 $error++;
1772 }
1773
1774 // If no SQL error, we redirect to the request form
1775 if (!$error) {
1776 $tmpUser = new User($db);
1777 $result = $tmpUser->fetch($objecttmp->fk_user);
1778
1779 // Calculate number of days consumed
1780 $nbopenedday = num_open_day($objecttmp->date_debut_gmt, $objecttmp->date_fin_gmt, 0, 1, $objecttmp->halfday, $tmpUser->country_id);
1781 $soldeActuel = $objecttmp->getCpforUser($objecttmp->fk_user, $objecttmp->fk_type);
1782 $newSolde = ($soldeActuel - $nbopenedday);
1783
1784 // The modification is added to the LOG
1785 $result = $objecttmp->addLogCP($user->id, $objecttmp->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $objecttmp->fk_type);
1786 if ($result < 0) {
1787 $error++;
1788 setEventMessages(null, $objecttmp->errors, 'errors');
1789 }
1790
1791 // Update balance
1792 $result = $objecttmp->updateSoldeCP($objecttmp->fk_user, $newSolde, $objecttmp->fk_type);
1793 if ($result < 0) {
1794 $error++;
1795 setEventMessages(null, $objecttmp->errors, 'errors');
1796 }
1797 }
1798
1799 if (!$error) {
1800 // To
1801 $destinataire = new User($db);
1802 $destinataire->fetch($objecttmp->fk_user);
1803 $emailTo = $destinataire->email;
1804
1805 if (!$emailTo) {
1806 dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email");
1807 } else {
1808 // From
1809 $expediteur = new User($db);
1810 $expediteur->fetch($objecttmp->fk_validator);
1811 //$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
1812 $emailFrom = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
1813
1814 // Subject
1815 $societeName = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
1816 if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
1817 $societeName = getDolGlobalString('MAIN_APPLICATION_TITLE');
1818 }
1819
1820 $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysValidated");
1821
1822 // Content
1823 $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n";
1824 $message .= "\n";
1825
1826 $message .= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($objecttmp->date_debut, 'day'), dol_print_date($objecttmp->date_fin, 'day'))."\n";
1827
1828 $message .= "- ".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n";
1829
1830 $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$objecttmp->id."\n\n";
1831 $message .= "\n";
1832
1833 $trackid = 'leav'.$objecttmp->id;
1834
1835 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1836 $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid);
1837
1838 // Sending email
1839 $result = $mail->sendfile();
1840
1841 if (!$result) {
1842 setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1
1843 $action = '';
1844 }
1845 }
1846 }
1847 } else {
1848 $langs->load("errors");
1849 setEventMessages($langs->trans('ErrorNotApproverForHoliday', $objecttmp->ref), null, 'errors');
1850 }
1851 } else {
1852 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1853 $error++;
1854 break;
1855 }
1856 }
1857
1858 if (!$error) {
1859 if ($nbok > 1) {
1860 setEventMessages($langs->trans("RecordsApproved", $nbok), null, 'mesgs');
1861 } elseif ($nbok == 1) {
1862 setEventMessages($langs->trans("RecordAproved"), null, 'mesgs');
1863 }
1864 $db->commit();
1865 } else {
1866 $db->rollback();
1867 }
1868}
1869
1870if (!$error && ($massaction == 'increaseholiday' || ($action == 'increaseholiday' && $confirm == 'yes')) && $permissiontoapprove && is_array($toselect)) {
1871 '@phan-var-force Holiday $holiday'; // Supposing that $holiday is set, it is needed.
1873 $db->begin();
1874 $objecttmp = new $objectclass($db);
1875 $nbok = 0;
1876 $typeholiday = GETPOSTINT('typeholiday');
1877 $nbdaysholidays = GETPOSTFLOAT('nbdaysholidays'); // May be 1.5
1878
1879 if ($nbdaysholidays <= 0) {
1880 setEventMessages($langs->trans("WrongAmount"), null, 'errors');
1881 $error++;
1882 }
1883
1884 if (!$error) {
1885 foreach ($toselect as $toselectid) {
1886 $balancecpuser = $objecttmp->getCPforUser($toselectid, $typeholiday);
1887 if (!empty($balancecpuser)) {
1888 $newnbdaysholidays = $nbdaysholidays + $balancecpuser;
1889 } else {
1890 $newnbdaysholidays = $nbdaysholidays;
1891 }
1892 $result = $holiday->addLogCP($user->id, $toselectid, $langs->transnoentitiesnoconv('ManualUpdate'), $newnbdaysholidays, $typeholiday);
1893 if ($result <= 0) {
1894 setEventMessages($holiday->error, $holiday->errors, 'errors');
1895 $error++;
1896 break;
1897 }
1898
1899 $objecttmp->updateSoldeCP($toselectid, $newnbdaysholidays, $typeholiday);
1900 if ($result > 0) {
1901 $nbok++;
1902 } else {
1903 setEventMessages($langs->trans("ErrorUpdatingUsersCP"), null, 'errors');
1904 $error++;
1905 break;
1906 }
1907 }
1908 }
1909
1910 if (!$error) {
1911 if ($nbok > 1) {
1912 setEventMessages($langs->trans("HolidayRecordsIncreased", $nbok), null, 'mesgs');
1913 } elseif ($nbok == 1) {
1914 setEventMessages($langs->trans("HolidayRecordIncreased"), null, 'mesgs');
1915 }
1916 $db->commit();
1917 $toselect = array();
1918 } else {
1919 $db->rollback();
1920 }
1921}
1922
1923
1924if (!$error && ($massaction == 'clonetasks' || ($action == 'clonetasks' && $confirm == 'yes'))) { // Test on permission not required here, done later
1925 $num = 0;
1926
1927 include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
1928
1929 $origin_task = new Task($db);
1930 $clone_task = new Task($db);
1931 $newproject = new Project($db);
1932 $newproject->fetch(GETPOSTINT('projectid'));
1933
1934 // Check if current user is contact of the new project (necessary only if project is not public)
1935 $iscontactofnewproject = 0;
1936 if (empty($newproject->public)) {
1937 $tmps = $newproject->getProjectsAuthorizedForUser($user, 0, 1, 0, '(fk_statut:=:1)'); // We check only open project (cloning on closed is not allowed)
1938 $tmparray = explode(',', $tmps);
1939 if (!in_array($newproject->id, $tmparray)) {
1940 $iscontactofnewproject = 1;
1941 }
1942 }
1943
1944 // Check permission on new project
1945 $permisstiontoadd = false;
1946 if ($user->hasRight('project', 'all', 'creer') || ($user->hasRight('project', 'creer') && ($newproject->public || $iscontactofnewproject))) {
1947 $permisstiontoadd = true;
1948 }
1949
1950 if ($permisstiontoadd) {
1951 foreach (GETPOST('selected') as $task) {
1952 $origin_task->fetch($task, '', 0);
1953
1954 $defaultref = '';
1955 $classnamemodtask = getDolGlobalString('PROJECT_TASK_ADDON', 'mod_task_simple');
1956 if (getDolGlobalString('PROJECT_TASK_ADDON') && is_readable(DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . getDolGlobalString('PROJECT_TASK_ADDON') . ".php")) {
1957 require_once DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . getDolGlobalString('PROJECT_TASK_ADDON') . '.php';
1958 $modTask = new $classnamemodtask();
1959 '@phan-var-force ModeleNumRefTask $modTask';
1961 $defaultref = $modTask->getNextValue(null, $clone_task);
1962 }
1963
1964 if (!$error) {
1965 $clone_task->fk_project = GETPOSTINT('projectid');
1966 $clone_task->ref = $defaultref;
1967 $clone_task->label = $origin_task->label;
1968 $clone_task->description = $origin_task->description;
1969 $clone_task->planned_workload = $origin_task->planned_workload;
1970 $clone_task->fk_task_parent = $origin_task->fk_task_parent;
1971 $clone_task->date_c = dol_now();
1972 $clone_task->date_start = $origin_task->date_start;
1973 $clone_task->date_end = $origin_task->date_end;
1974 $clone_task->progress = $origin_task->progress;
1975
1976 // Fill array 'array_options' with data from add form
1977 $ret = $extrafields->setOptionalsFromPost(null, $clone_task);
1978
1979 $taskid = $clone_task->create($user);
1980
1981 if ($taskid > 0) {
1982 $result = $clone_task->add_contact(GETPOSTINT("userid"), 'TASKEXECUTIVE', 'internal');
1983 $num++;
1984 } else {
1985 if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1986 $langs->load("projects");
1987 setEventMessages($langs->trans('NewTaskRefSuggested'), null, 'warnings');
1988 $duplicate_code_error = true;
1989 } else {
1990 setEventMessages($clone_task->error, $clone_task->errors, 'errors');
1991 }
1992 $action = 'list';
1993 $error++;
1994 }
1995 }
1996 }
1997
1998 if (!$error) {
1999 setEventMessages($langs->trans('NumberOfTasksCloned', $num), null, 'mesgs');
2000 header("Location: ".DOL_URL_ROOT.'/projet/tasks.php?id='.GETPOSTINT('projectid'));
2001 exit();
2002 }
2003 } else {
2004 setEventMessages($langs->trans('NotEnoughPermissions'), null, 'errors');
2005 }
2006}
2007
2008if (empty($toselect)) {
2009 $toselect = [];
2010}
2011$parameters['toselect'] = &$toselect;
2012$parameters['uploaddir'] = $uploaddir;
2013$parameters['massaction'] = $massaction;
2014$parameters['diroutputmassaction'] = isset($diroutputmassaction) ? $diroutputmassaction : null;
2015
2016// @phan-suppress-next-line PhanTypeMismatchArgumentNullable
2017$reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
2018if ($reshook < 0) {
2019 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
2020}
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.