dolibarr 25.0.0-alpha
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-2026 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2024-2026 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 int $error
78@phan-var-force ?string $permissiontoadd
79@phan-var-force ?string $permissiontoread
80@phan-var-force ?string $permissiontodelete
81@phan-var-force ?string $permissiontoclose
82@phan-var-force ?string $permissiontoapprove
83@phan-var-force ?int[] $toselect
84@phan-var-force ?string $diroutputmassaction
85@phan-var-force ?string $objectlabel
86@phan-var-force ?string $option
87@phan-var-force int $deliveryreceipt
88@phan-var-force string $month
89@phan-var-force string $year
90@phan-var-force ?array<string,mixed> $moreparams
91@phan-var-force ?string $search_status
92@phan-var-force ?int $hidedetails
93@phan-var-force ?int $hidedesc
94@phan-var-force ?int $hideref
95@phan-var-force string $confirm
96';
97
98
99// Protection
100if (empty($objectclass) || empty($uploaddir)) {
101 dol_print_error(null, 'include of actions_massactions.inc.php is done but var $objectclass or $uploaddir was not defined');
102 exit;
103}
104if (empty($massaction)) {
105 $massaction = '';
106}
107
108// Note: list of strings for objectclass could be extended to accepted/expected classes
109'
110@phan-var-force "CommonObject"|"CommandeFournisseur"|"ConferenceOrBoothAttendee"|"Contrat"|"Contact"|"Expedition"|"ExpenseReport"|"Facture"|"FactureFournisseur"|"Fichinter"|"Holiday"|"Partnership"|"Project"|"Propal"|"Societe"|"SupplierProposal" $objectclass
111@phan-var-force string $massaction
112@phan-var-force string $uploaddir
113';
114
116$TMsg = array();
117
118// For backward compatibility
119if (!empty($permtoread) && empty($permissiontoread)) {
120 $permissiontoread = $permtoread;
121}
122if (!empty($permtocreate) && empty($permissiontoadd)) {
123 $permissiontoadd = $permtocreate;
124}
125if (!empty($permtodelete) && empty($permissiontodelete)) {
126 $permissiontodelete = $permtodelete;
127}
128
129// Mass actions. Controls on number of lines checked.
130$maxformassaction = getDolGlobalInt('MAIN_LIMIT_FOR_MASS_ACTIONS', 1000);
131if ($massaction && is_array($toselect) && count($toselect) < 1) {
132 $error++;
133 setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
134}
135if (!$error && isset($toselect) && is_array($toselect) && count($toselect) > $maxformassaction) {
136 setEventMessages($langs->trans('TooManyRecordForMassAction', $maxformassaction), null, 'errors');
137 $error++;
138}
139
140// The ids in $toselect come from the request and not from the list: the list only showed the objects the user can see, the
141// request can contain any id. Refuse the selection if the user can not access one of the objects, with the same rules as the
142// lists and the cards (entity, third parties of the sales representative, projects the user can see...).
143// Note: some mass actions are done on ids that are not ids of $objectclass: users for 'increaseholiday' (holiday/define_holiday.php),
144// lines of invoices or expense reports for 'ventil' and 'set_default_account' (accountancy/.../list.php).
145if (!$error && $massaction && !in_array($massaction, array('increaseholiday', 'ventil', 'set_default_account')) && !empty($toselect) && is_array($toselect)) {
146 $objecttmpforaccesscheck = new $objectclass($db);
147 $refusedids = getObjectIdsRefusedToUser($user, $objecttmpforaccesscheck, $toselect);
148 if (!empty($refusedids)) {
149 $langs->load("errors");
150 setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors');
151 $error++;
152 }
153}
154
155if (!$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
156 $massaction = 'presend';
157}
158
159if (!$error && $massaction == 'confirm_presend') {
160 $resaction = '';
161 $nbsent = 0;
162 $nbignored = 0;
163 $langs->load("mails");
164 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
165 include_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
166
167 $listofobjectid = array();
168 $listofobjectthirdparties = array();
169 $listofobjectcontacts = array();
170 $listofobjectref = array();
171 $contactidtosend = array();
172 $attachedfilesThirdpartyObj = array();
173 $oneemailperrecipient = (GETPOSTINT('oneemailperrecipient') ? 1 : 0);
174 $thirdparty = null;
175
176 if (!$error) {
177 $objecttmp = new $objectclass($db);
178
179 // Define object $thirdparty (Societe or User, Adherent, ConferenceOrBoothAttendee...)
180 $thirdparty = new Societe($db);
181 if ($objecttmp->element == 'expensereport') {
182 $thirdparty = new User($db);
183 } elseif ($objecttmp->element == 'contact') {
184 $thirdparty = new Contact($db);
185 } elseif ($objecttmp->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
186 $thirdparty = new Adherent($db);
187 } elseif ($objecttmp->element == 'holiday') {
188 $thirdparty = new User($db);
189 } elseif ($objecttmp->element == 'conferenceorboothattendee') {
190 $thirdparty = new ConferenceOrBoothAttendee($db);
191 }
192
193 foreach ($toselect as $toselectid) {
194 $objecttmp = new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use
195 '@phan-var-force CommonObject $objecttmp';
197 $result = $objecttmp->fetch($toselectid);
198 if ($result > 0) {
199 $listofobjectid[$toselectid] = $toselectid;
200
201 // Set $tmpobjectid that is ID of parent object (thirdparty or user in most cases)
202 // fk_soc and socid are declared in child classes: @phan-suppress-next-line PhanUndeclaredProperty
203 $tmpobjectid = ($objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid);
204 if ($objecttmp->element == 'societe') {
205 '@phan-var-force Societe $objecttmp';
207 $tmpobjectid = $objecttmp->id;
208 } elseif ($objecttmp->element == 'contact') {
209 '@phan-var-force Contact $objecttmp';
211 $tmpobjectid = $objecttmp->id;
212 } elseif ($objecttmp->element == 'expensereport') {
213 '@phan-var-force ExpenseReport $objecttmp';
215 $tmpobjectid = $objecttmp->fk_user_author;
216 } elseif ($objecttmp->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
217 '@phan-var-force Partnership $objecttmp';
219 $tmpobjectid = $objecttmp->fk_member;
220 } elseif ($objecttmp->element == 'holiday') {
221 '@phan-var-force Holiday $objecttmp';
223 $tmpobjectid = $objecttmp->fk_user;
224 } elseif ($objecttmp->element == 'conferenceorboothattendee') {
225 '@phan-var-force ConferenceOrBoothAttendee $objecttmp';
227 $tmpobjectid = $objecttmp->id;
228 }
229 if (empty($tmpobjectid)) {
230 $tmpobjectid = 0;
231 }
232
233 if ($objectclass == 'Facture') {
234 '@phan-var-force Facture $objecttmp';
236 $tmparraycontact = array();
237 $tmparraycontact = $objecttmp->liste_contact(-1, 'external', 0, 'BILLING');
238 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
239 foreach ($tmparraycontact as $data_email) {
240 $listofobjectcontacts[$toselectid][$data_email['id']] = $data_email['email'];
241 }
242 }
243 } elseif ($objectclass == 'CommandeFournisseur') {
244 '@phan-var-force CommandeFournisseur $objecttmp';
246 $tmparraycontact = array();
247 $tmparraycontact = $objecttmp->liste_contact(-1, 'external', 0, 'CUSTOMER');
248 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
249 foreach ($tmparraycontact as $data_email) {
250 $listofobjectcontacts[$toselectid][$data_email['id']] = $data_email['email'];
251 }
252 }
253 }
254
255 $listofobjectthirdparties[$tmpobjectid] = $tmpobjectid;
256 $listofobjectref[$tmpobjectid][$toselectid] = $objecttmp;
257 }
258 }
259 }
260
261 // Check mandatory parameters
262 if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email)) {
263 $error++;
264 setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
265 $massaction = 'presend';
266 }
267
268 $receiver = GETPOST('receiver', 'alphawithlgt');
269 if (!is_array($receiver)) {
270 if (empty($receiver) || $receiver == '-1') {
271 $receiver = array();
272 } else {
273 $receiver = array($receiver);
274 }
275 }
276 if (!trim(GETPOST('sendto', 'alphawithlgt')) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) { // if only one recipient, receiver is mandatory
277 $error++;
278 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailRecipient")), null, 'warnings');
279 $massaction = 'presend';
280 }
281
282 if (!GETPOST('subject', 'restricthtml')) {
283 $error++;
284 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
285 $massaction = 'presend';
286 }
287
288 // Loop on each recipient (may be a thirdparty but also a user, a conferenceorboothattendee, ...)
289 if (!$error) {
290 foreach ($listofobjectthirdparties as $thirdpartyid) {
291 $result = $thirdparty->fetch($thirdpartyid);
292 if ($result < 0) {
293 dol_print_error($db);
294 exit;
295 }
296
297 $sendto = '';
298 $sendtocc = '';
299 $sendtobcc = '';
300 //$sendtoid = array();
301
302 // Define $sendto
303 $tmparray = array();
304 if (trim(GETPOST('sendto', 'alphawithlgt'))) {
305 // Recipients are provided into free text
306 $tmparray[] = trim(GETPOST('sendto', 'alphawithlgt'));
307 }
308 if (count($receiver) > 0 && is_object($thirdparty)) {
309 foreach ($receiver as $key => $val) {
310 // Recipient was provided from combo list
311 if ($val == 'thirdparty') { // Id of third party or user
312 $tmparray[] = dol_string_nospecial((string) $thirdparty->name, ' ', array(",")).' <'.$thirdparty->email.'>';
313 } elseif ($val && method_exists($thirdparty, 'contact_get_property')) { // Id of contact
314 $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
315 //$sendtoid[] = $val;
316 }
317 }
318 }
319 $sendto = implode(',', $tmparray);
320
321 // Define $sendtocc
322 $receivercc = GETPOST('receivercc', 'alphawithlgt');
323 if (!is_array($receivercc)) {
324 if ($receivercc == '-1') {
325 $receivercc = array();
326 } else {
327 $receivercc = array($receivercc);
328 }
329 }
330 $tmparray = array();
331 if (trim(GETPOST('sendtocc', 'alphawithlgt'))) {
332 $tmparray[] = trim(GETPOST('sendtocc', 'alphawithlgt'));
333 }
334 if (count($receivercc) > 0) {
335 foreach ($receivercc as $key => $val) {
336 // Recipient was provided from combo list
337 if ($val == 'thirdparty') { // Id of third party
338 $tmparray[] = dol_string_nospecial((string) $thirdparty->name, ' ', array(",")).' <'.$thirdparty->email.'>';
339 } elseif ($val) { // Id du contact
340 $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
341 //$sendtoid[] = $val; TODO Add also id of contact in CC ?
342 }
343 }
344 }
345 $sendtocc = implode(',', $tmparray);
346
347 //var_dump($listofobjectref);exit;
348 $listofqualifiedobj = array();
349 $listofqualifiedref = array();
350 $thirdpartywithoutemail = array();
351
352 foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj) {
353 //var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
354 // Honour the same per-object hidden constants used by the "Send by email"
355 // button on the card pages (comm/propal/card.php, commande/card.php,
356 // compta/facture/card.php) so the behaviour is consistent between the
357 // single-object action and the mass action.
358 if ($objectclass == 'Propal' && $objectobj->status == Propal::STATUS_DRAFT && !getDolGlobalString('PROPOSAL_SENDBYEMAIL_FOR_ALL_STATUS')) {
359 $langs->load("errors");
360 $nbignored++;
361 $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
362 continue; // Payment done or started or canceled
363 }
364 if ($objectclass == 'Commande' && $objectobj->status == Commande::STATUS_DRAFT && !getDolGlobalString('COMMANDE_SENDBYEMAIL_FOR_ALL_STATUS')) {
365 $langs->load("errors");
366 $nbignored++;
367 $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
368 continue;
369 }
370 if ($objectclass == 'Facture' && $objectobj->status == Facture::STATUS_DRAFT && !getDolGlobalString('FACTURE_SENDBYEMAIL_FOR_ALL_STATUS')) {
371 $langs->load("errors");
372 $nbignored++;
373 $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction', $objectobj->ref).'</div><br>';
374 continue; // Payment done or started or canceled
375 }
376
377 // Test recipient
378 if (empty($sendto)) { // For the case, no recipient were set (multi thirdparties send)
379 if ($objectobj->element == 'societe') {
380 $sendto = $objectobj->email;
381 } elseif ($objectobj->element == 'expensereport') {
382 $fuser = new User($db);
383 $fuser->fetch($objectobj->fk_user_author);
384 $sendto = $fuser->email;
385 } elseif ($objectobj->element == 'contact') {
386 $fcontact = new Contact($db);
387 $fcontact->fetch($objectobj->id);
388 $sendto = $fcontact->email;
389 } elseif ($objectobj->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
390 $fadherent = new Adherent($db);
391 $fadherent->fetch($objectobj->fk_member);
392 $sendto = $fadherent->email;
393 } elseif ($objectobj->element == 'holiday') {
394 $fuser = new User($db);
395 $fuser->fetch($objectobj->fk_user);
396 $sendto = $fuser->email;
397 } elseif ($objectobj->element == 'facture' && !empty($listofobjectcontacts[$objectid])) {
398 $emails_to_sends = array();
399 $objectobj->fetch_thirdparty();
400 $contactidtosend = array();
401 foreach ($listofobjectcontacts[$objectid] as $contactemailid => $contactemailemail) {
402 $emails_to_sends[] = $objectobj->thirdparty->contact_get_property($contactemailid, 'email');
403 if (!in_array($contactemailid, $contactidtosend)) {
404 $contactidtosend[] = $contactemailid;
405 }
406 }
407 if (count($emails_to_sends) > 0) {
408 $sendto = implode(',', $emails_to_sends);
409 }
410 } elseif ($objectobj->element == 'order_supplier' && !empty($listofobjectcontacts[$objectid])) {
411 $emails_to_sends = array();
412 $objectobj->fetch_thirdparty();
413 $contactidtosend = array();
414 foreach ($listofobjectcontacts[$objectid] as $contactemailid => $contactemailemail) {
415 $emails_to_sends[] = $objectobj->thirdparty->contact_get_property($contactemailid, 'email');
416 if (!in_array($contactemailid, $contactidtosend)) {
417 $contactidtosend[] = $contactemailid;
418 }
419 }
420 if (count($emails_to_sends) > 0) {
421 $sendto = implode(',', $emails_to_sends);
422 }
423 } elseif ($objectobj->element == 'conferenceorboothattendee') {
424 $sendto = $objectobj->email;
425 } else {
426 $objectobj->fetch_thirdparty();
427 $sendto = $objectobj->thirdparty->email;
428 }
429 }
430
431 if (empty($sendto)) {
432 if ($objectobj->element == 'societe') {
434 $objectobj->thirdparty = $objectobj; // Hack so following code is compatible when objectobj is a thirdparty
435 }
436
437 // print "No recipient for thirdparty ".$objectobj->thirdparty->name;
438 $nbignored++;
439 if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id])) {
440 $resaction .= '<div class="error">'.$langs->trans('NoRecipientEmail', $objectobj->thirdparty->name).'</div><br>';
441 }
442 dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
443 $thirdpartywithoutemail[$objectobj->thirdparty->id] = 1;
444 continue;
445 }
446
447 if (GETPOST('addmaindocfile')) {
448 // TODO Use future field $objectobj->fullpathdoc to know where is stored default file
449 // TODO If not defined, use $objectobj->model_pdf (or default invoice config) to know what is template to use to regenerate doc.
450 $filename = dol_sanitizeFileName($objectobj->ref).'.pdf';
451 $subdir = '';
452 // TODO Set subdir to be compatible with multi levels dir trees
453 // $subdir = get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element)
454 $filedir = $uploaddir.'/'.$subdir.dol_sanitizeFileName($objectobj->ref);
455 $filepath = $filedir.'/'.$filename;
456
457 // For supplier invoices, we use the file provided by supplier, not the one we generate
458 if ($objectobj->element == 'invoice_supplier') {
459 $fileparams = dol_most_recent_file($uploaddir.'/'.get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element).$objectobj->ref, preg_quote($objectobj->ref, '/').'([^\-])+');
460 $filepath = $fileparams['fullname'];
461 }
462
463 if (getDolGlobalInt('MAIL_MASS_ACTION_SEARCH_MOST_RECENT_FILE_IF_NOT_FOUND') && isset($filepath) && !dol_is_file($filepath)) {
464 $fileparams = dol_most_recent_file($filedir, preg_quote($objectobj->ref, '/') . '([^\-])+' . (getDolGlobalInt('MAIN_ODT_AS_PDF') ? '\.pdf$' : ''));
465 if (isset($fileparams)) {
466 $filepath = $fileparams['fullname'];
467 $filename = $fileparams['name'];
468 }
469 }
470
471 // try to find other files generated for this object (last_main_doc)
472 $filename_found = '';
473 $filepath_found = '';
474 $file_check_list = array();
475 $file_check_list[] = array(
476 'name' => $filename,
477 'path' => $filepath,
478 );
479 if (getDolGlobalString('MAIL_MASS_ACTION_ADD_LAST_IF_MAIN_DOC_NOT_FOUND') && !empty($objectobj->last_main_doc)) {
480 $file_check_list[] = array(
481 'name' => basename($objectobj->last_main_doc),
482 'path' => DOL_DATA_ROOT . '/' . $objectobj->last_main_doc,
483 );
484 }
485 foreach ($file_check_list as $file_check_arr) {
486 if (dol_is_file($file_check_arr['path'])) {
487 $filename_found = $file_check_arr['name'];
488 $filepath_found = $file_check_arr['path'];
489 break;
490 }
491 }
492
493 if ($filepath_found) {
494 // Create form object
495 $attachedfilesThirdpartyObj[$thirdpartyid][$objectid] = array(
496 'paths' => array($filepath_found),
497 'names' => array($filename_found),
498 'mimes' => array(dol_mimetype($filepath_found))
499 );
500 } else {
501 $nbignored++;
502 $langs->load("errors");
503 foreach ($file_check_list as $file_check_arr) {
504 $resaction .= '<div class="error">'.$langs->trans('ErrorCantReadFile', $file_check_arr['path']).'</div><br>';
505 dol_syslog('Failed to read file: '.$file_check_arr['path'], LOG_WARNING);
506 }
507 continue;
508 }
509 }
510
511 // Object of thirdparty qualified, we add it
512 $listofqualifiedobj[$objectid] = $objectobj;
513 $listofqualifiedref[$objectid] = $objectobj->ref;
514
515
516 //var_dump($listofqualifiedref);
517 }
518
519 // Send email if there is at least one qualified object for current thirdparty
520 if (count($listofqualifiedobj) > 0) {
521 $langs->load("commercial");
522 $email_from = '';
523
524 $reg = array();
525 $fromtype = GETPOST('fromtype');
526 if ($fromtype === 'user') {
527 $email_from = dol_string_nospecial($user->getFullName($langs), ' ', array(",")).' <'.$user->email.'>';
528 } elseif ($fromtype === 'company') {
529 $email_from = getDolGlobalString('MAIN_INFO_SOCIETE_NOM') . ' <' . getDolGlobalString('MAIN_INFO_SOCIETE_MAIL').'>';
530 } elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
531 $tmp = explode(',', getDolGlobalString('MAIN_INFO_SOCIETE_MAIL_ALIASES'));
532 $email_from = trim($tmp[((int) $reg[1] - 1)]);
533 } elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
534 $sql = "SELECT rowid, label, email FROM ".MAIN_DB_PREFIX."c_email_senderprofile WHERE rowid = ".(int) $reg[1];
535 $resql = $db->query($sql);
536 $obj = $db->fetch_object($resql);
537 if ($obj) {
538 $email_from = dol_string_nospecial($obj->label, ' ', array(",")).' <'.$obj->email.'>';
539 }
540 } elseif (preg_match('/from_template_(\d+)/', $fromtype, $reg)) {
541 $sql = "SELECT rowid, email_from FROM ".MAIN_DB_PREFIX."c_email_templates WHERE rowid = ".(int) $reg[1];
542 $resql = $db->query($sql);
543 $obj = $db->fetch_object($resql);
544 if ($obj) {
545 $email_from = $obj->email_from;
546 }
547 } else {
548 $email_from = GETPOST('fromname').' <'.GETPOST('frommail', 'email').'>';
549 }
550
551 $replyto = $email_from;
552 $subject = GETPOST('subject', 'restricthtml');
553 $message = GETPOST('message', 'restricthtml');
554
555 $sendtobcc = GETPOST('sendtoccc');
556 if ($objectclass == 'Propal') {
557 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROPOSAL_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROPOSAL_TO')));
558 }
559 if ($objectclass == 'Commande') {
560 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_ORDER_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_ORDER_TO')));
561 }
562 if ($objectclass == 'Facture') {
563 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_INVOICE_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_INVOICE_TO')));
564 }
565 if ($objectclass == 'SupplierProposal') {
566 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO')));
567 }
568 if ($objectclass == 'CommandeFournisseur') {
569 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO')));
570 }
571 if ($objectclass == 'FactureFournisseur') {
572 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO')));
573 }
574 if ($objectclass == 'Project') {
575 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROJECT_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROJECT_TO')));
576 }
577
578 // $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)
579 // $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)
580 $looparray = array();
581 if (!$oneemailperrecipient) {
582 $looparray = $listofqualifiedobj;
583 foreach ($looparray as $key => $objecttmp) {
584 $looparray[$key]->thirdparty = $thirdparty; // Force thirdparty on object
585 }
586 } else {
587 $objectforloop = new $objectclass($db);
588 $objectforloop->thirdparty = $thirdparty; // Force thirdparty on object (even if object was not loaded)
589 $looparray[0] = $objectforloop;
590 }
591 //var_dump($looparray);exit;
592 dol_syslog("We have set an array of ".count($looparray)." emails to send. oneemailperrecipient=".$oneemailperrecipient);
593 //var_dump($oneemailperrecipient); var_dump($listofqualifiedobj); var_dump($listofqualifiedref);
594 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
595 // Make substitution in email content
596 if (isModEnabled('project') && method_exists($objecttmp, 'fetchProject') && is_null($objecttmp->project)) {
597 $objecttmp->fetchProject();
598 }
599 $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $objecttmp);
600 $substitutionarray['__ID__'] = ($oneemailperrecipient ? implode(', ', array_keys($listofqualifiedobj)) : $objecttmp->id);
601 $substitutionarray['__REF__'] = ($oneemailperrecipient ? implode(', ', $listofqualifiedref) : $objecttmp->ref);
602 $substitutionarray['__EMAIL__'] = $thirdparty->email;
603 $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"/>';
604
605 if ($oneemailperrecipient) {
606 $substitutionarray['__ONLINE_PAYMENT_URL__'] = '';
607 $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = '';
608 }
609
610 $parameters = array('mode' => 'formemail');
611
612 if (!empty($listofobjectthirdparties)) {
613 $parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
614 }
615 if (!empty($listofobjectref)) {
616 $parameters['listofobjectref'] = $listofobjectref;
617 }
618
619 complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
620
621 $subjectreplaced = make_substitutions($subject, $substitutionarray);
622 $messagereplaced = make_substitutions($message, $substitutionarray);
623
624 $attachedfiles = array('paths' => array(), 'names' => array(), 'mimes' => array());
625 if ($oneemailperrecipient) {
626 // if "one email per recipient" is check we must collate $attachedfiles by thirdparty
627 if (is_array($attachedfilesThirdpartyObj[$thirdparty->id]) && count($attachedfilesThirdpartyObj[$thirdparty->id])) { // @phpstan-ignore-line
628 foreach ($attachedfilesThirdpartyObj[$thirdparty->id] as $keyObjId => $objAttachedFiles) {
629 // Create form object
630 $attachedfiles = array(
631 'paths' => array_merge($attachedfiles['paths'], $objAttachedFiles['paths']),
632 'names' => array_merge($attachedfiles['names'], $objAttachedFiles['names']),
633 'mimes' => array_merge($attachedfiles['mimes'], $objAttachedFiles['mimes'])
634 );
635 }
636 }
637 } elseif (!empty($attachedfilesThirdpartyObj[$thirdparty->id][$objectid])) {
638 // Create form object
639 // if "one email per recipient" isn't check we must separate $attachedfiles by object
640 $attachedfiles = $attachedfilesThirdpartyObj[$thirdparty->id][$objectid];
641 }
642
643 $filepath = $attachedfiles['paths'];
644 $filename = $attachedfiles['names'];
645 $mimetype = $attachedfiles['mimes'];
646
647 // Define the trackid when emails sent from the mass action
648 if ($oneemailperrecipient) {
649 $trackid = 'thi'.$thirdparty->id;
650 if ($objecttmp->element == 'expensereport') {
651 $trackid = 'use'.$thirdparty->id;
652 } elseif ($objecttmp->element == 'contact') {
653 $trackid = 'ctc'.$thirdparty->id;
654 } elseif ($objecttmp->element == 'holiday') {
655 $trackid = 'use'.$thirdparty->id;
656 }
657 } else {
658 $trackid = strtolower(get_class($objecttmp));
659 if (get_class($objecttmp) == 'Contact') {
660 $trackid = 'ctc';
661 } elseif (get_class($objecttmp) == 'Contrat') {
662 $trackid = 'con';
663 } elseif (get_class($objecttmp) == 'Propal') {
664 $trackid = 'pro';
665 } elseif (get_class($objecttmp) == 'Commande') {
666 $trackid = 'ord';
667 } elseif (get_class($objecttmp) == 'Facture') {
668 $trackid = 'inv';
669 } elseif (get_class($objecttmp) == 'SupplierProposal') {
670 $trackid = 'spr';
671 } elseif (get_class($objecttmp) == 'CommandeFournisseur') {
672 $trackid = 'sor';
673 } elseif (get_class($objecttmp) == 'FactureFournisseur') {
674 $trackid = 'sin';
675 }
676
677 $trackid .= $objecttmp->id;
678 }
679 //var_dump($filepath);
680 //var_dump($trackid);exit;
681 //var_dump($subjectreplaced);
682
683 if (empty($sendcontext)) {
684 $sendcontext = 'standard';
685 }
686
687 // Set tmp user directory (used to convert images embedded as img src=data:image)
688 $vardir = $conf->user->dir_output."/".$user->id;
689 $upload_dir_tmp = $vardir.'/temp'; // TODO Add $keytoavoidconflict in upload_dir path
690
691 // Send mail (substitutionarray must be done just before this)
692 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
693 $mailfile = new CMailFile($subjectreplaced, (string) $sendto, $email_from, $messagereplaced, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, (int) $deliveryreceipt, -1, '', '', $trackid, '', $sendcontext, '', $upload_dir_tmp);
694 if ($mailfile->error) {
695 $resaction .= '<div class="error">'.$mailfile->error.'</div>';
696 } else {
697 $result = $mailfile->sendfile();
698 if ($result > 0) {
699 $resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($mailfile->addr_from, 2), $mailfile->getValidAddress($mailfile->addr_to, 2)).'<br>'; // Must not contain "
700
701 $error = 0;
702
703 // Insert logs into agenda
704 foreach ($listofqualifiedobj as $objid2 => $objectobj2) {
705 if ((!$oneemailperrecipient) && $objid2 != $objectid) {
706 continue; // We discard this pass to avoid duplicate with other pass in looparray at higher level
707 }
708
709 dol_syslog("Try to insert email event into agenda for objid=".$objid2." => objectobj=".get_class($objectobj2));
710
711 /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
712 if ($objectclass == 'Commande') $actiontypecode='AC_COM';
713 if ($objectclass == 'Facture') $actiontypecode='AC_FAC';
714 if ($objectclass == 'SupplierProposal') $actiontypecode='AC_SUP_PRO';
715 if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
716 if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
717
718 $actionmsg = $langs->transnoentities('MailSentByTo', $email_from, (string) $sendto);
719 if ($message) {
720 if ($sendtocc) {
721 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc);
722 }
723 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subjectreplaced);
724 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
725 $actionmsg = dol_concatdesc($actionmsg, $messagereplaced);
726 }
727 $actionmsg2 = '';
728
729 // Initialisation donnees
730 $objectobj2->sendtoid = (empty($contactidtosend) ? 0 : $contactidtosend);
731 $objectobj2->actionmsg = $actionmsg; // Long text
732 $objectobj2->actionmsg2 = $actionmsg2; // Short text
733 $objectobj2->fk_element = $objid2;
734 $objectobj2->elementtype = $objectobj2->element;
735 if (getDolGlobalString('MAIN_MAIL_REPLACE_EVENT_TITLE_BY_EMAIL_SUBJECT')) {
736 $objectobj2->actionmsg2 = $subjectreplaced; // Short text
737 }
738
739 $triggername = strtoupper(get_class($objectobj2)).'_SENTBYMAIL';
740 if ($triggername == 'SOCIETE_SENTBYMAIL') {
741 $triggername = 'COMPANY_SENTBYMAIL';
742 }
743 if ($triggername == 'CONTRAT_SENTBYMAIL') {
744 $triggername = 'CONTRACT_SENTBYMAIL';
745 }
746 if ($triggername == 'COMMANDE_SENTBYMAIL') {
747 $triggername = 'ORDER_SENTBYMAIL';
748 }
749 if ($triggername == 'FACTURE_SENTBYMAIL') {
750 $triggername = 'BILL_SENTBYMAIL';
751 }
752 if ($triggername == 'EXPEDITION_SENTBYMAIL') {
753 $triggername = 'SHIPPING_SENTBYMAIL';
754 }
755 if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') {
756 $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
757 }
758 if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') {
759 $triggername = 'BILL_SUPPLIER_SENTBYMAIL';
760 }
761 if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') {
762 $triggername = 'PROPOSAL_SUPPLIER_SENTBYMAIL';
763 }
764 if ($triggername == 'PROJET_SENTBYMAIL') {
765 $triggername = 'PROJECT_SENTBYMAIL';
766 }
767
768 if (!empty($triggername)) {
769 // Call trigger
770 $result = $objectobj2->call_trigger($triggername, $user);
771 if ($result < 0) {
772 $error++;
773 }
774 // End call triggers
775
776 if ($error) {
777 setEventMessages($db->lasterror(), null, 'errors');
778 dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR);
779 }
780 }
781
782 $nbsent++; // Nb of object sent
783 }
784 } else {
785 $langs->load("other");
786 if ($mailfile->error) {
787 $resaction .= $langs->trans('ErrorFailedToSendMail', $email_from, (string) $sendto);
788 $resaction .= '<br><div class="error">'.$mailfile->error.'</div>';
789 } elseif (getDolGlobalString('MAIN_DISABLE_ALL_MAILS')) {
790 $resaction .= '<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
791 } else {
792 $resaction .= $langs->trans('ErrorFailedToSendMail', $email_from, (string) $sendto) . '<br><div class="error">(unhandled error)</div>';
793 }
794 }
795 }
796 }
797 }
798 }
799
800 $resaction .= ($resaction ? '<br>' : $resaction);
801 $resaction .= '<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
802 $resaction .= $langs->trans("NbSelected").': '.count($toselect)."\n<br>";
803 $resaction .= $langs->trans("NbIgnored").': '.($nbignored ? $nbignored : 0)."\n<br>";
804 $resaction .= $langs->trans("NbSent").': '.($nbsent ? $nbsent : 0)."\n<br>";
805
806 if ($nbsent) {
807 $action = ''; // Do not show form post if there was at least one successful sent
808 //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
809 setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
810 setEventMessages($resaction, null, 'mesgs');
811 } else {
812 //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file
813 setEventMessages($resaction, null, 'warnings');
814 }
815
816 $action = 'list';
817 $massaction = '';
818 }
819}
820
821
822if (!$error && $massaction == 'cancelorders') {
823 $db->begin();
824
825 $nbok = 0;
826
827 $orders = GETPOST('toselect', 'array:int');
828 foreach ($orders as $id_order) {
829 $cmd = new Commande($db);
830 if ($cmd->fetch($id_order) <= 0) {
831 continue;
832 }
833
834 if ($cmd->status != Commande::STATUS_VALIDATED) {
835 $langs->load('errors');
836 setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
837 $error++;
838 break;
839 } else {
840 // TODO We do not provide warehouse so no stock change here for the moment.
841 $result = $cmd->cancel($user);
842 }
843
844 if ($result < 0) {
845 setEventMessages($cmd->error, $cmd->errors, 'errors');
846 $error++;
847 break;
848 } else {
849 $nbok++;
850 }
851 }
852 if (!$error) {
853 setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
854 $db->commit();
855 } else {
856 $db->rollback();
857 }
858}
859
860
861if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search')) {
862 if (empty($diroutputmassaction)) {
863 dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
864 exit;
865 }
866
867 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
868 require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
869 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
870
871 $objecttmp = new $objectclass($db);
872 $listofobjectid = array();
873 $listofobjectthirdparties = array();
874 $listofobjectref = array();
875 foreach ($toselect as $toselectid) {
876 $objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use
877 $result = $objecttmp->fetch($toselectid);
878 if ($result > 0) {
879 $listofobjectid[$toselectid] = $toselectid;
880 $thirdpartyid = !empty($objecttmp->fk_soc) ? $objecttmp->fk_soc : $objecttmp->socid;
881 $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
882 $listofobjectref[$toselectid] = $objecttmp->ref;
883 }
884 }
885
886 $arrayofinclusion = array();
887 $parameters = array(
888 'listofobjectref' => $listofobjectref,
889 'arrayofinclusion' => &$arrayofinclusion,
890 );
891 $reshook = $hookmanager->executeHooks('updateSearchRegexToMergeDoc', $parameters, $object, $action);
892
893 if (empty($reshook)) {
894 foreach ($listofobjectref as $tmppdf) {
895 $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$';
896 }
897 foreach ($listofobjectref as $tmppdf) {
898 $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[\w\-\'\&\.]+\.pdf$'; // To include PDF generated from ODX files
899 }
900 }
901
902 $listoffiles = dol_dir_list($uploaddir, 'all', 1, $arrayofinclusion, '\.meta$|\.png$', 'date', SORT_DESC, 0, 1);
903
904 dol_syslog("Found ".count($listoffiles)." files");
905
906 // build list of files with full path
907 $files = array();
908
909 foreach ($listofobjectref as $basename) {
910 $basename = dol_sanitizeFileName($basename);
911 foreach ($listoffiles as $filefound) {
912 if (strstr($filefound["name"], $basename)) {
913 $files[] = $filefound['fullname'];
914 break;
915 }
916 }
917 }
918
919 // Define output language (Here it is not used because we do only merging existing PDF)
920 $outputlangs = $langs;
921 $newlang = '';
922 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
923 $newlang = GETPOST('lang_id', 'aZ09');
924 }
925 //elseif (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && is_object($objecttmp->thirdparty)) { // On massaction, we can have several values for $objecttmp->thirdparty
926 // $newlang = $objecttmp->thirdparty->default_lang;
927 //}
928 if (!empty($newlang)) {
929 $outputlangs = new Translate("", $conf);
930 $outputlangs->setDefaultLang($newlang);
931 }
932
933 if (getDolGlobalString('USE_PDFTK_FOR_PDF_CONCAT')) {
934 // Create output dir if not exists
935 dol_mkdir($diroutputmassaction);
936
937 // Defined name of merged file
938 $filename = strtolower(dol_sanitizeFileName($langs->transnoentities((string) $objectlabel)));
939 $filename = preg_replace('/\s/', '_', $filename);
940
941 // Save merged file
942 if (in_array($objecttmp->element, array('facture', 'invoice_supplier')) && $search_status == $objecttmp::STATUS_VALIDATED) {
943 if ($option == 'late') {
944 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
945 } else {
946 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
947 }
948 }
949 if ($year) {
950 $filename .= '_'.$year;
951 }
952 if ($month) {
953 $filename .= '_'.$month;
954 }
955
956 if (count($files) > 0) {
957 $now = dol_now();
958 $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
959
960 $input_files = '';
961 foreach ($files as $f) {
962 $input_files .= ' '.escapeshellarg($f);
963 }
964
965 $cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file);
966 exec($cmd);
967
968 // check if pdftk is installed
969 if (file_exists($file)) {
970 dolChmod($file);
971
972 $langs->load("exports");
973 setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
974 } else {
975 setEventMessages($langs->trans('ErrorPDFTkOutputFileNotFound'), null, 'errors');
976 }
977 } else {
978 setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
979 }
980 } else {
981 // Create empty PDF
982 $formatarray = pdf_getFormat();
983 $page_largeur = $formatarray['width'];
984 $page_hauteur = $formatarray['height'];
985 $format = array($page_largeur, $page_hauteur);
986
987 $pdf = pdf_getInstance($format);
988
989 if (class_exists('TCPDF')) {
990 $pdf->setPrintHeader(false);
991 $pdf->setPrintFooter(false);
992 }
993 $pdf->SetFont(pdf_getPDFFont($outputlangs));
994
995 if (getDolGlobalString('MAIN_DISABLE_PDF_COMPRESSION')) {
996 $pdf->SetCompression(false);
997 }
998
999 $pagecount = 0;
1000 // Add all others
1001 foreach ($files as $file) {
1002 // Load a PDF document from a file.
1003 $pagecount = $pdf->setSourceFile($file);
1004 for ($i = 1; $i <= $pagecount; $i++) {
1005 $tplidx = $pdf->importPage($i);
1006 $s = $pdf->getTemplatesize($tplidx);
1007 $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
1008 $pdf->useTemplate($tplidx);
1009 }
1010 }
1011
1012 // Create output dir if not exists
1013 dol_mkdir($diroutputmassaction);
1014
1015 // Defined name of merged file
1016 $filename = strtolower(dol_sanitizeFileName($langs->transnoentities((string) $objectlabel)));
1017 $filename = preg_replace('/\s/', '_', $filename);
1018
1019
1020 // Save merged file
1021 if (in_array($objecttmp->element, array('facture', 'invoice_supplier')) && $search_status == $objecttmp::STATUS_VALIDATED) {
1022 if ($option == 'late') {
1023 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
1024 } else {
1025 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
1026 }
1027 }
1028 if (!empty($year)) {
1029 $filename .= '_'.$year;
1030 }
1031 if (!empty($month)) {
1032 $filename .= '_'.$month;
1033 }
1034 if ($pagecount) {
1035 $now = dol_now();
1036 $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
1037 $pdf->Output($file, 'F');
1038 dolChmod($file);
1039
1040 $langs->load("exports");
1041 setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
1042 } else {
1043 setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
1044 }
1045 }
1046}
1047
1048// Remove a file from massaction area
1049if ($action == 'remove_file') {
1050 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1051
1052 $langs->load("other");
1053 $upload_dir = $diroutputmassaction;
1054 $file = $upload_dir.'/'.GETPOST('file');
1055 $ret = dol_delete_file($file, 1);
1056 if ($ret) {
1057 setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
1058 } else {
1059 setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
1060 }
1061 $action = '';
1062}
1063
1064
1065// Validate records
1066if (!$error && $massaction == 'validate' && $permissiontoadd) {
1067 $objecttmp = new $objectclass($db);
1068
1069 if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
1070 $langs->load("errors");
1071 setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1072 $error++;
1073 }
1074 if ($objecttmp->element == 'invoice_supplier' && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL')) {
1075 $langs->load("errors");
1076 setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1077 $error++;
1078 }
1079 if ($objecttmp->element == 'facture') {
1080 if (!empty($toselect) && getDolGlobalString('INVOICE_CHECK_POSTERIOR_DATE')) {
1081 // order $toselect by date
1082 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture";
1083 $sql .= " WHERE rowid IN (".$db->sanitize(implode(",", $toselect)).")";
1084 $sql .= " ORDER BY datef";
1085
1086 $resql = $db->query($sql);
1087 if ($resql) {
1088 $toselectnew = [];
1089 while (!empty($arr = $db->fetch_row($resql))) {
1090 $toselectnew[] = $arr[0];
1091 }
1092 $toselect = (empty($toselectnew)) ? $toselect : $toselectnew;
1093 } else {
1094 dol_print_error($db);
1095 $error++;
1096 }
1097 }
1098 }
1099 if (!$error) {
1100 // MAIN_MASSVALIDATE_<OBJECTCLASS>_NO_GLOBAL_TRANSACTION = 1 wraps each
1101 // record in its own transaction instead of all-or-nothing. Modules
1102 // dealing with external systems (e.g. VeriFactu / AEAT for invoices)
1103 // can enable it on the list pages they need so a mid-loop failure does
1104 // not roll back the records already committed-and-pushed outside the
1105 // database. The default remains the secured all-or-nothing mode (#37365).
1106 $perrecordtransaction = (int) getDolGlobalInt('MAIN_MASSVALIDATE_'.strtoupper($objectclass).'_NO_GLOBAL_TRANSACTION');
1107 if (!$perrecordtransaction) {
1108 $db->begin();
1109 }
1110
1111 $nbok = 0;
1112 foreach ($toselect as $toselectid) {
1113 if ($perrecordtransaction) {
1114 $db->begin();
1115 }
1116 $result = $objecttmp->fetch($toselectid);
1117 if ($result > 0) {
1118 if (method_exists($objecttmp, 'validate')) {
1119 $result = $objecttmp->validate($user);
1120 } elseif (method_exists($objecttmp, 'setValid')) {
1121 $result = $objecttmp->setValid($user);
1122 } else {
1123 $objecttmp->error = 'No method validate or setValid on this object';
1124 $result = -1;
1125 }
1126 if ($result == 0) {
1127 $langs->load("errors");
1128 setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
1129 $error++;
1130 if ($perrecordtransaction) {
1131 $db->rollback();
1132 }
1133 break;
1134 } elseif ($result < 0) {
1135 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1136 $error++;
1137 if ($perrecordtransaction) {
1138 $db->rollback();
1139 }
1140 break;
1141 } else {
1142 // validate() rename pdf but do not regenerate
1143 // Define output language
1144 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1145 $outputlangs = $langs;
1146 $newlang = '';
1147 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
1148 $newlang = GETPOST('lang_id', 'aZ09');
1149 }
1150 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && property_exists($objecttmp, 'thirdparty')) {
1151 if ((property_exists($objecttmp, 'socid') || property_exists($objecttmp, 'fk_soc')) && empty($objecttmp->thirdparty)) {
1152 $objecttmp->fetch_thirdparty();
1153 }
1154 if (!empty($objecttmp->thirdparty)) {
1155 $newlang = $objecttmp->thirdparty->default_lang;
1156 }
1157 }
1158 if (!empty($newlang)) {
1159 $outputlangs = new Translate("", $conf);
1160 $outputlangs->setDefaultLang($newlang);
1161 $outputlangs->load('products');
1162 }
1163 $model = $objecttmp->model_pdf;
1164 $ret = $objecttmp->fetch($objecttmp->id); // Reload to get new records
1165
1166 // To be sure vars is defined
1167 $hidedetails = isset($hidedetails) ? $hidedetails : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
1168 $hidedesc = isset($hidedesc) ? $hidedesc : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
1169 $hideref = isset($hideref) ? $hideref : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
1170 $moreparams = isset($moreparams) ? $moreparams : null;
1171
1172 $result = $objecttmp->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1173 if ($result < 0) {
1174 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1175 }
1176 }
1177 $nbok++;
1178 if ($perrecordtransaction) {
1179 $db->commit();
1180 }
1181 }
1182 } else {
1183 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1184 $error++;
1185 if ($perrecordtransaction) {
1186 $db->rollback();
1187 }
1188 break;
1189 }
1190 }
1191
1192 if (!$error) {
1193 if ($nbok > 1) {
1194 setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1195 } else {
1196 setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
1197 }
1198 if (!$perrecordtransaction) {
1199 $db->commit();
1200 }
1201 } elseif (!$perrecordtransaction) {
1202 $db->rollback();
1203 }
1204 }
1205}
1206
1207// Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
1208if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) {
1209 $db->begin();
1210
1211 $objecttmp = new $objectclass($db);
1212 '@phan-var-force CommonObject $objecttmp';
1214 $nbok = 0;
1215 $nbignored = 0;
1217 $TMsg = array();
1218
1219 //$toselect could contain duplicate entries, cf https://github.com/Dolibarr/dolibarr/issues/26244
1220 $unique_arr = array_unique($toselect);
1221 foreach ($unique_arr as $toselectid) {
1222 $result = $objecttmp->fetch($toselectid);
1223 if ($result > 0) {
1224 // Refuse deletion for some objects/status
1225 if ($objectclass == 'Facture' && $objecttmp->status != Facture::STATUS_DRAFT) {
1226 $langs->load("errors");
1227 $nbignored++;
1228 $TMsg[] = '<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'</div><br>';
1229 continue;
1230 }
1231
1232 if (method_exists($objecttmp, 'is_erasable') && $objecttmp->is_erasable() <= 0) {
1233 $langs->load("errors");
1234 $nbignored++;
1235 $TMsg[] = '<div class="error">'.$langs->trans('ErrorRecordHasChildren').' '.$objecttmp->ref.'</div><br>';
1236 continue;
1237 }
1238
1239 if ($objectclass == 'Holiday' && ! in_array($objecttmp->statut, array(Holiday::STATUS_DRAFT, Holiday::STATUS_CANCELED, Holiday::STATUS_REFUSED))) {
1240 $langs->load("errors");
1241 $nbignored++;
1242 $TMsg[] = '<div class="error">'.$langs->trans('ErrorLeaveRequestMustBeDraftCanceledOrRefusedToBeDeleted', $objecttmp->ref).'</div><br>';
1243 continue;
1244 }
1245
1246 if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) {
1247 $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".((int) $objecttmp->id);
1248 $res = $db->query($sql);
1249
1250 if (!$res) {
1251 setEventMessage('ErrorRecordParentingNotModified', 'errors');
1252 $error++;
1253 }
1254 }
1255
1256 if ($objecttmp->element == 'societe') {
1258 '@phan-var-force Societe $objecttmp';
1259 // TODO Change signature of delete for Societe
1260 $result = $objecttmp->delete($objecttmp->id, $user, 1);
1261 } else {
1262 $objecttmp->oldcopy = dol_clone($objecttmp);
1263 $result = $objecttmp->delete($user);
1264 }
1265
1266 if (empty($result)) { // if delete returns 0, there is at least one object linked
1267 $TMsg = array_merge($objecttmp->errors, $TMsg);
1268 } elseif ($result < 0) { // if delete returns is < 0, there is an error, we break and rollback later
1269 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1270 $error++;
1271 break;
1272 } else {
1273 $nbok++;
1274 }
1275 } else {
1276 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1277 $error++;
1278 break;
1279 }
1280 }
1281
1282 if (empty($error)) {
1283 // Message for elements well deleted
1284 if ($nbok > 1) {
1285 setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1286 } elseif ($nbok > 0) {
1287 setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1288 } else {
1289 setEventMessages($langs->trans("NoRecordDeleted"), null, 'mesgs');
1290 }
1291
1292 // Message for elements which can't be deleted
1293 if (!empty($TMsg)) {
1294 sort($TMsg);
1295 setEventMessages('', array_unique($TMsg), 'warnings');
1296 }
1297
1298 $db->commit();
1299 } else {
1300 $db->rollback();
1301 }
1302}
1303
1304// Generate document foreach object according to model linked to object
1305// @todo : propose model selection
1306if (!$error && $massaction == 'generate_doc' && $permissiontoread) {
1307 // Complete with classes that use this massaction
1308 '@phan-var-force \'Commande\'|\'CommandeFournisseur\'|\'Contrat\'|\'Expedition\'|\'ExpenseReport\'|\'Facture\'|\'FactureFournisseur\'|\'Fichinter\'|\'Project\'|\'Propal\'|\'SupplierProposal\' $objectclass';
1309
1310 $db->begin();
1311 $nbok = 0;
1312
1313 $objecttmp = new $objectclass($db);
1314
1315 foreach ($toselect as $toselectid) {
1316 $objecttmp->thirdparty = null; // Clear if another value was already set by fetch_thirdparty later
1317 $result = $objecttmp->fetch($toselectid);
1318
1319 if ($result > 0) {
1320 $outputlangs = $langs;
1321 $newlang = '';
1322
1323 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
1324 $newlang = GETPOST('lang_id', 'aZ09');
1325 }
1326 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) {
1327 $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
1328 }
1329 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->default_lang)) {
1330 $newlang = $objecttmp->default_lang; // for thirdparty @phan-suppress-current-line PhanUndeclaredProperty
1331 }
1332 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && empty($objecttmp->thirdparty)) { //load lang from thirdparty
1333 $objecttmp->fetch_thirdparty();
1334 $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
1335 }
1336 if (!empty($newlang)) {
1337 $outputlangs = new Translate("", $conf);
1338 $outputlangs->setDefaultLang($newlang);
1339 }
1340
1341 // To be sure vars is defined
1342 $hidedetails = isset($hidedetails) ? $hidedetails : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
1343 $hidedesc = isset($hidedesc) ? $hidedesc : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
1344 $hideref = isset($hideref) ? $hideref : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
1345 $moreparams = isset($moreparams) ? $moreparams : null;
1346
1347 $result = $objecttmp->generateDocument($objecttmp->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1348
1349 if ($result <= 0) {
1350 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1351 $error++;
1352 break;
1353 } else {
1354 $nbok++;
1355 }
1356 } else {
1357 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1358 $error++;
1359 break;
1360 }
1361 }
1362
1363 if (!$error) {
1364 if ($nbok > 1) {
1365 setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1366 } else {
1367 setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
1368 }
1369 $db->commit();
1370 } else {
1371 $db->rollback();
1372 }
1373}
1374
1375if (!$error && ($action == 'affecttag' && $confirm == 'yes') && $permissiontoadd) {
1376 $nbok = 0;
1377 $db->begin();
1378
1379 $affecttag_type = GETPOST('affecttag_type', 'alpha');
1380 if (!empty($affecttag_type)) {
1381 $affecttag_type_array = explode(',', $affecttag_type);
1382 } else {
1383 setEventMessage('CategTypeNotFound', 'errors');
1384 }
1385 if (!empty($affecttag_type_array)) {
1386 // check if tag type submitted exists into Tag Map categorie class
1387 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1388 $categ = new Categorie($db);
1389 $to_affecttag_type_array = array();
1390 $categ_type_array = $categ->getMapList();
1391 foreach ($categ_type_array as $categdef) {
1392 if (in_array($categdef['code'], $affecttag_type_array)) {
1393 $to_affecttag_type_array[] = $categdef['code'];
1394 }
1395 }
1396
1397 // For each valid categ type set common categ
1398 if (!empty($to_affecttag_type_array)) {
1399 // The CommonSocialNetworks trait forces $object to its own type on the global $object for phan, which
1400 // makes phan lose the CommonObject methods here (fetch, setCategoriesCommon). Restore the real type.
1401 '@phan-var-force CommonObject $object';
1402 foreach ($to_affecttag_type_array as $categ_type) {
1403 $contcats = GETPOST('contcats_' . $categ_type, 'array');
1404 foreach ($toselect as $toselectid) {
1405 $result = $object->fetch($toselectid);
1406 if ($result > 0) {
1407 $result = $object->setCategoriesCommon($contcats, $categ_type, false);
1408 if ($result > 0) {
1409 $nbok++;
1410 } else {
1411 setEventMessages($object->error, $object->errors, 'errors');
1412 }
1413 } else {
1414 setEventMessages($object->error, $object->errors, 'errors');
1415 $error++;
1416 break;
1417 }
1418 }
1419 }
1420 }
1421 }
1422
1423 if (!$error) {
1424 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1425 $db->commit();
1426 $toselect = array();
1427 } else {
1428 $db->rollback();
1429 }
1430}
1431
1432if (!$error && ($action == 'updateprice' && $confirm == 'yes') && $permissiontoadd) {
1433 '@phan-var-force Product|ProductCustomerPrice $obj';
1434 '@phan-var-force Product|ProductCustomerPrice $object';
1435 $nbok = 0;
1436 $db->begin();
1437 if (GETPOSTISSET('pricerate')) {
1438 $pricepercentage = GETPOSTINT('pricerate');
1439 if ($pricepercentage == 0) {
1440 setEventMessages($langs->trans("RecordsModified", 0), null);
1441 } else {
1442 foreach ($toselect as $toselectid) {
1443 $result = $object->fetch($toselectid);
1444 if ($result > 0) {
1445 if (getDolGlobalString('PRODUCT_PRICE_UNIQ')
1446 || getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
1447 if ($object->price_base_type == 'TTC') {
1448 $newprice = $object->price_ttc * (100 + $pricepercentage) / 100;
1449 $minprice = $object->price_min_ttc;
1450 } else {
1451 $newprice = $object->price * (100 + $pricepercentage) / 100;
1452 $minprice = $object->price_min;
1453 }
1454 $res = $object->updatePrice($newprice, $object->price_base_type, $user, $object->tva_tx, $minprice, 0, $object->tva_npr, 0, 0, array(), $object->default_vat_code);
1455 if ($res > 0) {
1456 $nbok++;
1457 } else {
1458 setEventMessages($object->error, $object->errors, 'errors');
1459 }
1460 } elseif (getDolGlobalString('PRODUIT_MULTIPRICES')) {
1461 $maxlevel = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
1462 for ($level = 1; $level <= $maxlevel; $level++) {
1463 if ($object->price_base_type == 'TTC') {
1464 $newprice = $object->multiprices_ttc[$level] * (100 + $pricepercentage) / 100;
1465 $minprice = $object->multiprices_min_ttc[$level];
1466 } else {
1467 $newprice = $object->multiprices[$level] * (100 + $pricepercentage) / 100;
1468 $minprice = $object->multiprices_min[$level];
1469 }
1470 $res = $object->updatePrice($newprice, $object->price_base_type, $user, $object->tva_tx, $minprice, $level, $object->tva_npr, 0, 0, array(), $object->default_vat_code);
1471 if ($res > 0) {
1472 $nbok++;
1473 }
1474 }
1475 }
1476 } else {
1477 setEventMessages($object->error, $object->errors, 'errors');
1478 $error++;
1479 break;
1480 }
1481 }
1482 }
1483 }
1484
1485 if (!$error) {
1486 if ($nbok > 0) {
1487 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1488 }
1489 $db->commit();
1490 $toselect = array();
1491 } else {
1492 $db->rollback();
1493 }
1494}
1495
1496if (!$error && ($action == 'setsupervisor' && $confirm == 'yes') && $permissiontoadd) {
1497 '@phan-var-force User $object';
1498 $nbok = 0;
1499 $db->begin();
1500 $supervisortoset = GETPOSTINT('supervisortoset');
1501 if (!empty($supervisortoset)) {
1502 foreach ($toselect as $toselectid) {
1503 $result = $object->fetch($toselectid);
1504 if ($result > 0) {
1505 $object->fk_user = $supervisortoset;
1506 $res = $object->update($user);
1507 if ($res > 0) {
1508 $nbok++;
1509 } else {
1510 setEventMessages($object->error, $object->errors, 'errors');
1511 }
1512 } else {
1513 setEventMessages($object->error, $object->errors, 'errors');
1514 $error++;
1515 break;
1516 }
1517 }
1518 } else {
1519 setEventMessage('UserNotFound', 'errors');
1520 $error++;
1521 }
1522
1523 if (!$error) {
1524 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1525 $db->commit();
1526 $toselect = array();
1527 } else {
1528 $db->rollback();
1529 }
1530}
1531
1532if (!$error && ($action == 'affectuser' && $confirm == 'yes') && $permissiontoadd) {
1533 $nbok = 0;
1534 $db->begin();
1535
1536 $usertoaffect = GETPOSTINT('usertoaffect');
1537 $projectrole = GETPOST('projectrole');
1538 $tasksrole = GETPOST('tasksrole');
1539 if (!empty($usertoaffect)) {
1540 foreach ($toselect as $toselectid) {
1541 $result = $object->fetch($toselectid);
1542 if ($result > 0) {
1543 $res = $object->add_contact($usertoaffect, $projectrole, 'internal');
1544 if ($res >= 0) {
1545 $taskstatic = new Task($db);
1546 $task_array = $taskstatic->getTasksArray(null, null, $object->id, 0, 0);
1547
1548 foreach ($task_array as $task) {
1549 $tasksToAffect = new Task($db);
1550 $result = $tasksToAffect->fetch($task->id);
1551 if ($result > 0) {
1552 $res = $tasksToAffect->add_contact($usertoaffect, $tasksrole, 'internal');
1553 if ($res < 0) {
1554 setEventMessages($tasksToAffect->error, $tasksToAffect->errors, 'errors');
1555 }
1556 }
1557 }
1558 $nbok++;
1559 } else {
1560 setEventMessages($object->error, $object->errors, 'errors');
1561 }
1562 } else {
1563 setEventMessages($object->error, $object->errors, 'errors');
1564 $error++;
1565 break;
1566 }
1567 }
1568 } else {
1569 setEventMessage('UserNotFound', 'errors');
1570 $error++;
1571 }
1572
1573 if (!$error) {
1574 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1575 $db->commit();
1576 $toselect = array();
1577 } else {
1578 $db->rollback();
1579 }
1580}
1581
1582if (!$error && ($massaction == 'enable' || ($action == 'enable' && $confirm == 'yes')) && $permissiontoadd) {
1583 $db->begin();
1584
1585 $objecttmp = new $objectclass($db);
1586 $nbok = 0;
1587 foreach ($toselect as $toselectid) {
1588 $result = $objecttmp->fetch($toselectid);
1589 if ($result > 0) {
1590 if (in_array($objecttmp->element, array('societe'))) {
1591 $result = $objecttmp->setStatut(1);
1592 }
1593 if ($result <= 0) {
1594 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1595 $error++;
1596 break;
1597 } else {
1598 $nbok++;
1599 }
1600 } else {
1601 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1602 $error++;
1603 break;
1604 }
1605 }
1606
1607 if (!$error) {
1608 if ($nbok > 1) {
1609 setEventMessages($langs->trans("RecordsEnabled", $nbok), null, 'mesgs');
1610 } else {
1611 setEventMessages($langs->trans("RecordEnabled"), null, 'mesgs');
1612 }
1613 $db->commit();
1614 } else {
1615 $db->rollback();
1616 }
1617}
1618
1619if (!$error && ($massaction == 'disable' || ($action == 'disable' && $confirm == 'yes')) && $permissiontoadd) {
1620 $db->begin();
1621
1622 $objecttmp = new $objectclass($db);
1623 $nbok = 0;
1624 foreach ($toselect as $toselectid) {
1625 $result = $objecttmp->fetch($toselectid);
1626 if ($result > 0) {
1627 if (in_array($objecttmp->element, array('societe'))) {
1628 $result = $objecttmp->setStatut(0);
1629 }
1630 if ($result <= 0) {
1631 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1632 $error++;
1633 break;
1634 } else {
1635 $nbok++;
1636 }
1637 } else {
1638 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1639 $error++;
1640 break;
1641 }
1642 }
1643
1644 if (!$error) {
1645 if ($nbok > 1) {
1646 setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
1647 } else {
1648 setEventMessages($langs->trans("RecordDisabled"), null, 'mesgs');
1649 }
1650 $db->commit();
1651 } else {
1652 $db->rollback();
1653 }
1654}
1655
1656if (!$error && $action == 'confirm_edit_value_extrafields' && $confirm == 'yes' && $permissiontoadd) {
1657 $db->begin();
1658
1659 $objecttmp = new $objectclass($db);
1660 $e = new ExtraFields($db);// fetch optionals attributes and labels
1661 $e->fetch_name_optionals_label($objecttmp->table_element);
1662
1663 $nbok = 0;
1664 $extrafieldKeyToUpdate = GETPOST('extrafield-key-to-update');
1665
1666
1667 foreach ($toselect as $toselectid) {
1669 $objecttmp = new $objectclass($db); // to avoid ghost data
1670 $result = $objecttmp->fetch($toselectid);
1671 if ($result > 0) {
1672 // Fill array 'array_options' with data from add form
1673 $ret = $e->setOptionalsFromPost(null, $objecttmp, $extrafieldKeyToUpdate);
1674 if ($ret > 0) {
1675 $objecttmp->insertExtraFields();
1676 $nbok++;
1677 } else {
1678 $error++;
1679 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1680 }
1681 } else {
1682 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1683 $error++;
1684 break;
1685 }
1686 }
1687
1688 if (!$error) {
1689 if ($nbok > 1) {
1690 setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1691 } elseif ($nbok == 1) {
1692 setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
1693 }
1694 $db->commit();
1695 } else {
1696 $db->rollback();
1697 }
1698}
1699
1700if (!$error && ($massaction == 'assignsalerepresentative' || ($action == 'assignsalerepresentative' && $confirm == 'yes')) && $permissiontoadd) {
1701 $db->begin();
1702
1703 $objecttmp = new $objectclass($db);
1704 $nbok = 0;
1705
1706 foreach ($toselect as $toselectid) {
1707 $result = $objecttmp->fetch($toselectid);
1708 if ($result > 0) {
1709 if (in_array($objecttmp->element, array('societe'))) {
1710 $result = $objecttmp->setSalesRep(GETPOST("commercial", "alpha"));
1711 }
1712 if ($result <= 0) {
1713 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1714 $error++;
1715 break;
1716 } else {
1717 $nbok++;
1718 }
1719 } else {
1720 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1721 $error++;
1722 break;
1723 }
1724 }
1725
1726 if (!$error) {
1727 if ($nbok > 1) {
1728 setEventMessages($langs->trans("CommercialsAffected", $nbok), null, 'mesgs');
1729 } else {
1730 setEventMessages($langs->trans("CommercialAffected"), null, 'mesgs');
1731 }
1732 $db->commit();
1733 } else {
1734 $db->rollback();
1735 }
1736}
1737
1738if (!$error && ($massaction == 'unassigncommercial' || ($action == 'unassigncommercial' && $confirm == 'yes')) && $permissiontoadd) {
1739 $db->begin();
1740
1741 $objecttmp = new $objectclass($db);
1742 $nbok = 0;
1743
1744 foreach ($toselect as $toselectid) {
1745 $result = $objecttmp->fetch($toselectid);
1746 if ($result > 0) {
1747 if (in_array($objecttmp->element, array('societe'))) {
1748 $TCommercial = GETPOST("commercial", "alpha");
1749 if (is_array($TCommercial)) {
1750 foreach ($TCommercial as $commercial) {
1751 $result = $objecttmp->del_commercial($user, $commercial);
1752 }
1753 }
1754 }
1755 if ($result <= 0) {
1756 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1757 $error++;
1758 break;
1759 } else {
1760 $nbok++;
1761 }
1762 } else {
1763 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1764 $error++;
1765 break;
1766 }
1767 }
1768
1769 if (!$error) {
1770 if ($nbok > 1) {
1771 setEventMessages($langs->trans("CommercialsDisaffected", $nbok), null, 'mesgs');
1772 } else {
1773 setEventMessages($langs->trans("CommercialDisaffected"), null, 'mesgs');
1774 }
1775 $db->commit();
1776 } else {
1777 $db->rollback();
1778 }
1779}
1780// Approve for leave only
1781if (!$error && ($massaction == 'approveleave' || ($action == 'approveleave' && $confirm == 'yes')) && $permissiontoapprove) {
1782 $db->begin();
1783
1784 $objecttmp = new $objectclass($db);
1785 '@phan-var-force Holiday $objecttmp';
1786 $nbok = 0;
1787 foreach ($toselect as $toselectid) {
1788 $result = $objecttmp->fetch($toselectid);
1789 if ($result > 0) {
1790 if ($objecttmp->status != Holiday::STATUS_VALIDATED) {
1791 setEventMessages($langs->trans('StatusOfRefMustBe', $objecttmp->ref, $langs->transnoentitiesnoconv('Validated')), null, 'warnings');
1792 continue;
1793 }
1794 if ($user->id == $objecttmp->fk_validator) {
1795 $objecttmp->oldcopy = dol_clone($objecttmp, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
1796
1797 $objecttmp->date_valid = dol_now();
1798 $objecttmp->fk_user_valid = $user->id;
1799 $objecttmp->date_approval = dol_now();
1800 $objecttmp->fk_user_approve = $user->id;
1801 $objecttmp->status = Holiday::STATUS_APPROVED;
1802 $objecttmp->statut = $objecttmp->status; // deprecated
1803
1804 $verif = $objecttmp->approve($user);
1805
1806 if ($verif <= 0) {
1807 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1808 $error++;
1809 } else {
1810 $nbok++;
1811 }
1812
1813 // If no SQL error, we redirect to the request form
1814 if (!$error) {
1815 $tmpUser = new User($db);
1816 $result = $tmpUser->fetch($objecttmp->fk_user);
1817
1818 // Calculate number of days consumed
1819 $nbopenedday = num_open_day($objecttmp->date_debut_gmt, $objecttmp->date_fin_gmt, 0, 1, $objecttmp->halfday, $tmpUser->country_id);
1820 $soldeActuel = $objecttmp->getCpforUser($objecttmp->fk_user, $objecttmp->fk_type);
1821 $newSolde = ($soldeActuel - $nbopenedday);
1822
1823 // 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
1824 if (!getDolGlobalInt('HOLIDAY_DECREASE_AT_END_OF_MONTH')) {
1825 // The modification is added to the LOG
1826 $result = $objecttmp->addLogCP($user->id, $objecttmp->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $objecttmp->fk_type);
1827 if ($result < 0) {
1828 $error++;
1829 setEventMessages(null, $objecttmp->errors, 'errors');
1830 }
1831
1832 // Update balance
1833 $result = $objecttmp->updateSoldeCP($objecttmp->fk_user, $newSolde, $objecttmp->fk_type);
1834 if ($result < 0) {
1835 $error++;
1836 setEventMessages(null, $objecttmp->errors, 'errors');
1837 }
1838 }
1839 }
1840
1841 if (!$error) {
1842 $result = $objecttmp->sendApprovalEmail();
1843 if ($result < 0) {
1844 setEventMessages($objecttmp->error, $objecttmp->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1
1845 $action = '';
1846 }
1847 }
1848 } else {
1849 $langs->load("errors");
1850 setEventMessages($langs->trans('ErrorNotApproverForHoliday', $objecttmp->ref), null, 'errors');
1851 }
1852 } else {
1853 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1854 $error++;
1855 break;
1856 }
1857 }
1858
1859 if (!$error) {
1860 if ($nbok > 1) {
1861 setEventMessages($langs->trans("RecordsApproved", $nbok), null, 'mesgs');
1862 } elseif ($nbok == 1) {
1863 setEventMessages($langs->trans("RecordAproved"), null, 'mesgs');
1864 }
1865 $db->commit();
1866 } else {
1867 $db->rollback();
1868 }
1869}
1870
1871// Changing the balance of users requires the same permission than the single user update (holiday/define_holiday.php)
1872if (!$error && ($massaction == 'increaseholiday' || ($action == 'increaseholiday' && $confirm == 'yes')) && $user->hasRight('holiday', 'define_holiday') && is_array($toselect)) {
1873 '@phan-var-force Holiday $holiday'; // Supposing that $holiday is set, it is needed.
1875 $db->begin();
1876 $objecttmp = new $objectclass($db);
1877 $nbok = 0;
1878 $typeholiday = GETPOSTINT('typeholiday');
1879 $nbdaysholidays = GETPOSTFLOAT('nbdaysholidays'); // May be 1.5
1880
1881 if ($nbdaysholidays <= 0) {
1882 setEventMessages($langs->trans("WrongAmount"), null, 'errors');
1883 $error++;
1884 }
1885
1886 if (!$error) {
1887 foreach ($toselect as $toselectid) {
1888 $balancecpuser = $objecttmp->getCPforUser($toselectid, $typeholiday);
1889 if (!empty($balancecpuser)) {
1890 $newnbdaysholidays = $nbdaysholidays + $balancecpuser;
1891 } else {
1892 $newnbdaysholidays = $nbdaysholidays;
1893 }
1894 $result = $holiday->addLogCP($user->id, $toselectid, $langs->transnoentitiesnoconv('ManualUpdate'), $newnbdaysholidays, $typeholiday);
1895 if ($result <= 0) {
1896 setEventMessages($holiday->error, $holiday->errors, 'errors');
1897 $error++;
1898 break;
1899 }
1900
1901 $objecttmp->updateSoldeCP($toselectid, $newnbdaysholidays, $typeholiday);
1902 if ($result > 0) {
1903 $nbok++;
1904 } else {
1905 setEventMessages($langs->trans("ErrorUpdatingUsersCP"), null, 'errors');
1906 $error++;
1907 break;
1908 }
1909 }
1910 }
1911
1912 if (!$error) {
1913 if ($nbok > 1) {
1914 setEventMessages($langs->trans("HolidayRecordsIncreased", $nbok), null, 'mesgs');
1915 } elseif ($nbok == 1) {
1916 setEventMessages($langs->trans("HolidayRecordIncreased"), null, 'mesgs');
1917 }
1918 $db->commit();
1919 $toselect = array();
1920 } else {
1921 $db->rollback();
1922 }
1923}
1924
1925
1926if (!$error && ($massaction == 'clonetasks' || ($action == 'clonetasks' && $confirm == 'yes'))) { // Test on permission not required here, done later
1927 $num = 0;
1928
1929 include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
1930
1931 $origin_task = new Task($db);
1932 $clone_task = new Task($db);
1933 $newproject = new Project($db);
1934 $newproject->fetch(GETPOSTINT('projectid'));
1935
1936 // Check if current user is contact of the new project (necessary only if project is not public)
1937 $iscontactofnewproject = 0;
1938 if (empty($newproject->public)) {
1939 $tmps = $newproject->getProjectsAuthorizedForUser($user, 0, 1, 0, '(fk_statut:=:1)'); // We check only open project (cloning on closed is not allowed)
1940 $tmparray = explode(',', $tmps);
1941 if (in_array($newproject->id, $tmparray)) {
1942 $iscontactofnewproject = 1;
1943 }
1944 }
1945
1946 // Check permission on new project
1947 $permisstiontoadd = false;
1948 if ($user->hasRight('project', 'all', 'creer') || ($user->hasRight('project', 'creer') && ($newproject->public || $iscontactofnewproject))) {
1949 $permisstiontoadd = true;
1950 }
1951
1952 if ($permisstiontoadd) {
1953 $taskidsmapping = array(); // old task id => new cloned task id
1954 $clonedtaskoldparent = array(); // new cloned task id => old parent task id
1955
1956 // Build the list of projects the current user is allowed to read, used to authorize
1957 // every source task against its actual project before cloning it (the previous fix for
1958 // CVE-2026-77923 only validated the destination project).
1959 $authorizedsourceprojects = null;
1960 if (!$user->hasRight('projet', 'all', 'lire')) {
1961 $sourceprojectstatic = new Project($db);
1962 $tmps = $sourceprojectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
1963 $authorizedsourceprojects = explode(',', $tmps);
1964 }
1965
1966 foreach (GETPOST('selected') as $task) {
1967 if ($origin_task->fetch($task, '', 0) <= 0) {
1968 continue; // Source task not found, skip it
1969 }
1970
1971 // Authorize the source task against its actual project before cloning it
1972 if (is_array($authorizedsourceprojects) && !in_array($origin_task->fk_project, $authorizedsourceprojects)) {
1973 setEventMessages($langs->trans('NotEnoughPermissions'), null, 'errors');
1974 $error++;
1975 break;
1976 }
1977
1978 $defaultref = '';
1979 $classnamemodtask = getDolGlobalString('PROJECT_TASK_ADDON', 'mod_task_simple');
1980 if (getDolGlobalString('PROJECT_TASK_ADDON') && is_readable(DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . getDolGlobalString('PROJECT_TASK_ADDON') . ".php")) {
1981 require_once DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . getDolGlobalString('PROJECT_TASK_ADDON') . '.php';
1982 $modTask = new $classnamemodtask();
1983 '@phan-var-force ModeleNumRefTask $modTask';
1985 $defaultref = $modTask->getNextValue(null, $clone_task);
1986 }
1987
1988 if (!$error) {
1989 $clone_task->fk_project = GETPOSTINT('projectid');
1990 $clone_task->ref = $defaultref;
1991 $clone_task->label = $origin_task->label;
1992 $clone_task->description = $origin_task->description;
1993 $clone_task->planned_workload = $origin_task->planned_workload;
1994 $clone_task->fk_task_parent = $origin_task->fk_task_parent;
1995 $clone_task->date_c = dol_now();
1996 $clone_task->date_start = $origin_task->date_start;
1997 $clone_task->date_end = $origin_task->date_end;
1998 $clone_task->progress = $origin_task->progress;
1999
2000 // Fill array 'array_options' with data from add form
2001 $ret = $extrafields->setOptionalsFromPost(null, $clone_task);
2002
2003 $taskid = $clone_task->create($user);
2004
2005 if ($taskid > 0) {
2006 $result = $clone_task->add_contact(GETPOSTINT("userid"), 'TASKEXECUTIVE', 'internal');
2007 $taskidsmapping[$task] = $taskid; // remember old id => new id
2008 $clonedtaskoldparent[$taskid] = $origin_task->fk_task_parent; // remember new id => old parent id
2009 $num++;
2010 } else {
2011 if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2012 $langs->load("projects");
2013 setEventMessages($langs->trans('NewTaskRefSuggested'), null, 'warnings');
2014 $duplicate_code_error = true;
2015 } else {
2016 setEventMessages($clone_task->error, $clone_task->errors, 'errors');
2017 }
2018 $action = 'list';
2019 $error++;
2020 }
2021 }
2022 }
2023
2024 // Remap the parent of cloned tasks: if a cloned task's original parent was also cloned, point it to the
2025 // new parent instead of the old id, otherwise the cloned sub-task would reference a task from the source
2026 // project and end up orphaned (#39596). If the old parent was not cloned, detach it (set to 0).
2027 if (!$error) {
2028 foreach ($clonedtaskoldparent as $newtaskid => $oldparentid) {
2029 if (empty($oldparentid)) {
2030 continue;
2031 }
2032 $newparentid = isset($taskidsmapping[$oldparentid]) ? $taskidsmapping[$oldparentid] : 0;
2033 $remaptask = new Task($db);
2034 if ($remaptask->fetch($newtaskid) > 0 && $remaptask->fk_task_parent != $newparentid) {
2035 $remaptask->fk_task_parent = $newparentid;
2036 if ($remaptask->update($user) < 0) {
2037 setEventMessages($remaptask->error, $remaptask->errors, 'errors');
2038 $error++;
2039 }
2040 }
2041 }
2042 }
2043
2044 if (!$error) {
2045 setEventMessages($langs->trans('NumberOfTasksCloned', $num), null, 'mesgs');
2046 header("Location: ".DOL_URL_ROOT.'/projet/tasks.php?id='.GETPOSTINT('projectid'));
2047 exit();
2048 }
2049 } else {
2050 setEventMessages($langs->trans('NotEnoughPermissions'), null, 'errors');
2051 }
2052}
2053
2054if (!$error && $action == 'createcreditnote' && $permissiontoadd) {
2055 // Security check to avoid creating credit note if stock calculation on bill is enabled
2056 if (getDolGlobalInt('STOCK_CALCULATE_ON_BILL')) {
2057 setEventMessages($langs->trans('CreditNoteNotCreatedStockCalculateOnBillEnabled'), null, 'errors');
2058 header("Location: ".DOL_URL_ROOT.'/compta/facture/list.php?mainmenu=compta&leftmenu=facture');
2059 exit();
2060 }
2061
2062 $objecttmp = new $objectclass($db);
2063 if ($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') {
2064 $nbok = 0;
2066 $TMsg = array();
2067
2068 $unique_arr = array_unique($toselect);
2069 foreach ($unique_arr as $toselectid) {
2070 $sourceinvoice = $toselectid;
2071 $result = $objecttmp->fetch($sourceinvoice);
2072
2073 // We check if invoice is available.
2074 if ($result <= 0) {
2075 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
2076 $TMsg[] = $langs->trans('CreditNoteNotCreatedSourceInvoiceNotFound', $sourceinvoice);
2077 continue;
2078 }
2079
2080 // We check if invoice type is supported. If not, we refuse to create credit note.
2081 $isSupportedType = false;
2082 if ($objecttmp->type == Facture::TYPE_STANDARD) {
2083 $isSupportedType = true;
2084 }
2085 if ($objecttmp->type == Facture::TYPE_PROFORMA) {
2086 $isSupportedType = true;
2087 }
2088 if ($objecttmp->type == Facture::TYPE_DEPOSIT && !getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
2089 $isSupportedType = true;
2090 }
2091
2092 if (!$isSupportedType) {
2093 $listtype = array(
2094 Facture::TYPE_STANDARD => $langs->trans("InvoiceStandard"),
2095 Facture::TYPE_DEPOSIT => $langs->trans("InvoiceDeposit"),
2096 Facture::TYPE_CREDIT_NOTE => $langs->trans("InvoiceAvoir"),
2097 Facture::TYPE_REPLACEMENT => $langs->trans("InvoiceReplacement"),
2098 Facture::TYPE_SITUATION => $langs->trans("InvoiceSituation")
2099 );
2100
2101 $TMsg[] = $langs->trans('CreditNoteNotCreatedInvoiceTypeNotSupported', $objecttmp->ref, $listtype[$objecttmp->type]);
2102 continue;
2103 }
2104
2105 // We check if invoice is validated. If not, we refuse to create credit note.
2106 if ($objecttmp->status <= Facture::STATUS_DRAFT) {
2107 $TMsg[] = $langs->trans('CreditNoteNotCreatedInvoiceNotValidated', $objecttmp->ref);
2108 continue;
2109 }
2110
2111 // Test if there is at least one payment or credit note or deposit. If yes, we refuse.
2112 $totalpaid = $objecttmp->getSommePaiement();
2113 $totalcreditnotes = $objecttmp->getSumCreditNotesUsed();
2114 $totaldeposits = $objecttmp->getSumDepositsUsed();
2115 if ($totalpaid > 0) {
2116 $TMsg[] = $langs->trans('CreditNoteNotCreatedPaymentAlreadyDone', $objecttmp->ref);
2117 continue;
2118 }
2119 if ($totalcreditnotes > 0) {
2120 $TMsg[] = $langs->trans('CreditNoteNotCreatedCreditNoteAlreadyUsed', $objecttmp->ref);
2121 continue;
2122 }
2123 if ($totaldeposits > 0) {
2124 $TMsg[] = $langs->trans('CreditNoteNotCreatedDepositAlreadyUsed', $objecttmp->ref);
2125 continue;
2126 }
2127
2128 $db->begin();
2129
2130 // Create credit note
2131 $object = new Facture($db);
2132 $object->entity = $objecttmp->entity;
2133 $object->socid = $objecttmp->socid;
2134 $object->subtype = $objecttmp->subtype;
2135 $object->date = dol_now();
2136 // $object->note_public = '';
2137 // $object->note_private = '';
2138 $object->ref_client = $objecttmp->ref_client;
2139 $object->ref_customer = $objecttmp->ref_customer;
2140 $object->fk_project = $objecttmp->fk_project;
2141 $object->cond_reglement_id = 0; // No payment term for a credit note
2142 $object->fk_account = $objecttmp->fk_account;
2143 $object->fk_incoterms = $objecttmp->fk_incoterms;
2144 $object->location_incoterms = $objecttmp->location_incoterms;
2145 $object->multicurrency_code = $objecttmp->multicurrency_code;
2146 $object->multicurrency_tx = $objecttmp->multicurrency_tx;
2147
2148 $object->fk_facture_source = $sourceinvoice;
2150
2151
2152 if ($objecttmp->isSituationInvoice()) {
2153 $object->situation_counter = $objecttmp->situation_counter;
2154 $object->situation_cycle_ref = $objecttmp->situation_cycle_ref;
2155 $objecttmp->fetchPreviousNextSituationInvoice();
2156 }
2157
2158
2159 $id = $object->create($user);
2160 if ($id < 0) {
2161 setEventMessages($object->error, $object->errors, 'errors');
2162 $TMsg[] = $langs->trans('CreditNoteNotCreated', $objecttmp->ref);
2163 $db->rollback();
2164 continue;
2165 } else {
2166 $facture_source = $objecttmp;
2167
2168 // Copy linked contacts
2169 $object->copy_linked_contact($objecttmp, 'internal');
2170 $object->copy_linked_contact($objecttmp, 'external');
2171
2172 // Copy lines
2173 if (!empty($facture_source->lines)) {
2174 $fk_parent_line = 0;
2175
2176 foreach ($facture_source->lines as $line) {
2177 // Extrafields
2178 if (method_exists($line, 'fetch_optionals')) {
2179 // load extrafields
2180 $line->fetch_optionals();
2181 }
2182
2183 // Reset fk_parent_line for no child products and special product
2184 if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
2185 $fk_parent_line = 0;
2186 }
2187
2188 if ($facture_source->isSituationInvoice()) {
2189 $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
2190 $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from
2191
2192 if (!empty($facture_source->tab_previous_situation_invoice)) {
2193 // search the last standard invoice in cycle and the possible credit note between this last and facture_source
2194 // TODO Move this out of loop of $facture_source->lines
2195 $tab_jumped_credit_notes = array();
2196 $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
2197 $searchPreviousInvoice = true;
2198 while ($searchPreviousInvoice) {
2199 if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
2200 $searchPreviousInvoice = false; // find, exit;
2201 break;
2202 } else {
2203 if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_CREDIT_NOTE) {
2204 $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
2205 }
2206 $lineIndex--; // go to previous invoice in cycle
2207 }
2208 }
2209
2210 $maxPrevSituationPercent = 0;
2211 foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
2212 if ($prevLine->id == $source_fk_prev_id) {
2213 $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
2214
2215 //$line->subprice = $line->subprice - $prevLine->subprice;
2216 $line->total_ht -= $prevLine->total_ht;
2217 $line->total_tva -= $prevLine->total_tva;
2218 $line->total_ttc -= $prevLine->total_ttc;
2219 $line->total_localtax1 -= $prevLine->total_localtax1;
2220 $line->total_localtax2 -= $prevLine->total_localtax2;
2221
2222 $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
2223 $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
2224 $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
2225 $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
2226 }
2227 }
2228
2229 // prorata
2230 $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
2231
2232 //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
2233
2234 // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
2235 $maxPrevSituationPercent = 0;
2236 foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
2237 foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
2238 if ($prevLine->fk_prev_id == $source_fk_prev_id) {
2239 $maxPrevSituationPercent = $prevLine->situation_percent;
2240
2241 $line->total_ht -= $prevLine->total_ht;
2242 $line->total_tva -= $prevLine->total_tva;
2243 $line->total_ttc -= $prevLine->total_ttc;
2244 $line->total_localtax1 -= $prevLine->total_localtax1;
2245 $line->total_localtax2 -= $prevLine->total_localtax2;
2246
2247 $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
2248 $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
2249 $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
2250 $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
2251 }
2252 }
2253 }
2254
2255 // prorata
2256 $line->situation_percent += $maxPrevSituationPercent;
2257
2258 //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
2259 }
2260 }
2261
2262 $line->fk_facture = $object->id;
2263 $line->fk_parent_line = $fk_parent_line;
2264
2265 $line->subprice = -$line->subprice; // invert price for object
2266 // $line->pa_ht = $line->pa_ht; // we chose to have buy/cost price always positive, so no revert of sign here
2267 $line->total_ht = -$line->total_ht;
2268 $line->total_tva = -$line->total_tva;
2269 $line->total_ttc = -$line->total_ttc;
2270 $line->total_localtax1 = -$line->total_localtax1;
2271 $line->total_localtax2 = -$line->total_localtax2;
2272
2273 $line->multicurrency_subprice = -$line->multicurrency_subprice;
2274 $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
2275 $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
2276 $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
2277
2278 $line->context['createcreditnotefrominvoice'] = 1;
2279 $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount already linked
2280
2281 $object->lines[] = $line; // insert new line in current object
2282
2283 // Defined the new fk_parent_line
2284 if ($result > 0 && $line->product_type == 9) {
2285 $fk_parent_line = $result;
2286 }
2287 }
2288
2289 $object->update_price(1);
2290 }
2291
2292 // Add link between credit note and origin
2293 if (!empty($object->fk_facture_source) && $id > 0) {
2294 $facture_source->fetch($object->fk_facture_source);
2295 $facture_source->fetchObjectLinked();
2296
2297 if (!empty($facture_source->linkedObjectsIds)) {
2298 foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
2299 $object->add_object_linked($sourcetype, current($TIds));
2300 }
2301 }
2302 }
2303
2304 // We validate credit note
2305 $result = $object->validate($user);
2306 if ($result <= 0) {
2307 setEventMessages($object->error, $object->errors, 'errors');
2308 $TMsg[] = $langs->trans('CreditNoteNotCreatedErrorOnValidation', $objecttmp->ref);
2309 $db->rollback();
2310 continue;
2311 } else {
2312 // We update PDF if not disabled
2313 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
2314 $outputlangs = $langs;
2315 $newlang = '';
2316 if (getDolGlobalInt('MAIN_MULTILANGS') && GETPOST('lang_id', 'aZ09')) {
2317 $newlang = GETPOST('lang_id', 'aZ09');
2318 }
2319 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
2320 $newlang = $object->thirdparty->default_lang;
2321 }
2322 if (!empty($newlang)) {
2323 $outputlangs = new Translate("", $conf);
2324 $outputlangs->setDefaultLang($newlang);
2325 $outputlangs->load('products');
2326 }
2327 $model = $object->model_pdf;
2328
2329 $ret = $object->fetch($id); // Reload to get new records
2330
2331 $result = $object->generateDocument($model, $outputlangs, (int) $hidedetails, (int) $hidedesc, (int) $hideref);
2332 if ($result < 0) {
2333 setEventMessages($object->error, $object->errors, 'errors');
2334 }
2335 }
2336
2337 // Convert to reduction then apply reduction on source invoice
2338 $object->fetch($id);
2339 $object->fetch_thirdparty();
2340
2341 // Check if there is already a discount (protection)
2342 $discountcheck = new DiscountAbsolute($db);
2343 $result = $discountcheck->fetch(0, $object->id);
2344
2345 $canconvert = 0;
2346 if (empty($discountcheck->id)) {
2347 $canconvert = 1; // we can convert credit note into discount if there is no discount already linked to credit note
2348 }
2349
2350 if ($canconvert) {
2351 $amount_ht = $amount_tva = $amount_ttc = array();
2352 $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
2353
2354 // Loop on each vat rate
2355 $i = 0;
2356 foreach ($object->lines as $line) {
2357 if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9 and no need to create discount if amount is null
2358 $keyforvatrate = $line->tva_tx.($line->vat_src_code ? ' ('.$line->vat_src_code.')' : '');
2359
2360 if (!isset($amount_ht[$keyforvatrate])) {
2361 $amount_ht[$keyforvatrate] = 0;
2362 }
2363 $amount_ht[$keyforvatrate] += $line->total_ht;
2364 if (!isset($amount_tva[$keyforvatrate])) {
2365 $amount_tva[$keyforvatrate] = 0;
2366 }
2367 $amount_tva[$keyforvatrate] += $line->total_tva;
2368 if (!isset($amount_ttc[$keyforvatrate])) {
2369 $amount_ttc[$keyforvatrate] = 0;
2370 }
2371 $amount_ttc[$keyforvatrate] += $line->total_ttc;
2372 if (!isset($multicurrency_amount_ht[$keyforvatrate])) {
2373 $multicurrency_amount_ht[$keyforvatrate] = 0;
2374 }
2375 $multicurrency_amount_ht[$keyforvatrate] += $line->multicurrency_total_ht;
2376 if (!isset($multicurrency_amount_tva[$keyforvatrate])) {
2377 $multicurrency_amount_tva[$keyforvatrate] = 0;
2378 }
2379 $multicurrency_amount_tva[$keyforvatrate] += $line->multicurrency_total_tva;
2380 if (!isset($multicurrency_amount_ttc[$keyforvatrate])) {
2381 $multicurrency_amount_ttc[$keyforvatrate] = 0;
2382 }
2383 $multicurrency_amount_ttc[$keyforvatrate] += $line->multicurrency_total_ttc;
2384 $i++;
2385 }
2386 }
2387
2388 // Insert one discount by VAT rate category
2389 $discount = new DiscountAbsolute($db);
2390 $discount->description = '(CREDIT_NOTE)';
2391 $discount->fk_soc = $object->socid;
2392 $discount->socid = $object->socid;
2393 $discount->socid = $object->socid;
2394 $discount->fk_facture_source = $object->id;
2395
2396 $error = 0;
2397 $id_discount = 0;
2398
2399 foreach ($amount_ht as $tva_tx => $xxx) {
2400 $discount->amount_ht = -((float) $amount_ht[$tva_tx]);
2401 $discount->amount_tva = -((float) $amount_tva[$tva_tx]);
2402 $discount->amount_ttc = -((float) $amount_ttc[$tva_tx]);
2403 $discount->total_ht = -((float) $amount_ht[$tva_tx]);
2404 $discount->total_tva = -((float) $amount_tva[$tva_tx]);
2405 $discount->total_ttc = -((float) $amount_ttc[$tva_tx]);
2406 $discount->multicurrency_amount_ht = -((float) $multicurrency_amount_ht[$tva_tx]);
2407 $discount->multicurrency_amount_tva = -((float) $multicurrency_amount_tva[$tva_tx]);
2408 $discount->multicurrency_amount_ttc = -((float) $multicurrency_amount_ttc[$tva_tx]);
2409 $discount->multicurrency_total_ht = -((float) $multicurrency_amount_ht[$tva_tx]);
2410 $discount->multicurrency_total_tva = -((float) $multicurrency_amount_tva[$tva_tx]);
2411 $discount->multicurrency_total_ttc = -((float) $multicurrency_amount_ttc[$tva_tx]);
2412
2413 // Clean vat code
2414 $reg = array();
2415 $vat_src_code = '';
2416 if (preg_match('/\‍((.*)\‍)/', $tva_tx, $reg)) {
2417 $vat_src_code = $reg[1];
2418 $tva_tx = preg_replace('/\s*\‍(.*\‍)/', '', $tva_tx); // Remove code into vatrate.
2419 }
2420
2421 $discount->tva_tx = abs((float) $tva_tx);
2422 $discount->vat_src_code = $vat_src_code;
2423
2424 $id_discount = $discount->create($user);
2425 if ($id_discount < 0) {
2426 $error++;
2427 break;
2428 }
2429 }
2430
2431 if (empty($error) && $id_discount > 0) {
2432 // Set invoice as paid
2433 $result = $object->setPaid($user); // We can close the invoice.
2434 if ($result >= 0) {
2435 $object->fetch($object->id); // Reload properties
2436
2437 // Apply discount on source invoice
2438 $discount = new DiscountAbsolute($db);
2439 $discount->fetch($id_discount);
2440 $result = $discount->link_to_invoice(0, $object->fk_facture_source);
2441 if ($result < 0) {
2442 setEventMessages($discount->error, $discount->errors, 'errors');
2443 $TMsg[] = $langs->trans('CreditNoteNotCreatedErrorOnDiscountLink', $objecttmp->ref);
2444 $db->rollback();
2445 continue;
2446 }
2447
2448 // Set source invoice as paid if amount to pay is 0 after discount application
2449 $objecttmp->fetch($objecttmp->id); // Reload properties
2450 if ($objecttmp->getRemainToPay(0) == 0) {
2451 $result = $objecttmp->setPaid($user);
2452 if ($result < 0) {
2453 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
2454 $TMsg[] = $langs->trans('CreditNoteNotCreatedErrorOnSetPaidSourceInvoice', $objecttmp->ref);
2455 $db->rollback();
2456 continue;
2457 } else {
2458 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
2459 $outputlangs = $langs;
2460 $newlang = '';
2461 if (getDolGlobalInt('MAIN_MULTILANGS') && GETPOST('lang_id', 'aZ09')) {
2462 $newlang = GETPOST('lang_id', 'aZ09');
2463 }
2464 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
2465 $objecttmp->fetch_thirdparty();
2466 $newlang = $objecttmp->thirdparty->default_lang;
2467 }
2468 if (!empty($newlang)) {
2469 $outputlangs = new Translate("", $conf);
2470 $outputlangs->setDefaultLang($newlang);
2471 }
2472 $ret = $objecttmp->fetch($objecttmp->id); // Reload to get new records
2473
2474 $result = $objecttmp->generateDocument($objecttmp->model_pdf, $outputlangs, (int) $hidedetails, (int) $hidedesc, (int) $hideref);
2475 if ($result < 0) {
2476 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
2477 }
2478 }
2479 }
2480 } else {
2481 // We rollback because we want all or nothing.
2482 $TMsg[] = $langs->trans('CreditNoteNotCreatedErrorOnSourceInvoiceNotFullyPaidAfterDiscount', $objecttmp->ref);
2483 $db->rollback();
2484 continue;
2485 }
2486 } else {
2487 setEventMessages($object->error, $object->errors, 'errors');
2488 $TMsg[] = $langs->trans('CreditNoteNotCreatedErrorOnSetPaid', $objecttmp->ref);
2489 $db->rollback();
2490 continue;
2491 }
2492 } else {
2493 setEventMessages($discount->error, $discount->errors, 'errors');
2494 $TMsg[] = $langs->trans('CreditNoteNotCreatedErrorOnDiscount', $objecttmp->ref);
2495 $db->rollback();
2496 continue;
2497 }
2498 } else {
2499 $TMsg[] = $langs->trans('CreditNoteNotCreatedAlreadyConverted', $objecttmp->ref);
2500 $db->rollback();
2501 continue;
2502 }
2503 }
2504
2505 $nbok++;
2506 $db->commit();
2507 $TMsg[] = $langs->trans('CreditNoteCreated', $object->ref, $objecttmp->ref);
2508 }
2509 }
2510
2511 // Show messages
2512 foreach ($TMsg as $msg) {
2513 setEventMessages($msg, null, 'warnings');
2514 }
2515
2516 // Show success message
2517 if ($nbok > 0) {
2518 setEventMessages($langs->trans('CreditNotesCreated', $nbok), null, 'mesgs');
2519 }
2520
2521 $toselect = array();
2522 header("Location: ".DOL_URL_ROOT.'/compta/facture/list.php?mainmenu=compta&leftmenu=facture');
2523 exit();
2524 } else {
2525 setEventMessages($langs->trans('ThisMassActionIsOnlyForInvoices'), null, 'errors');
2526 header("Location: ".DOL_URL_ROOT.'/compta/facture/list.php?mainmenu=compta&leftmenu=facture');
2527 exit();
2528 }
2529}
2530
2531if (empty($toselect)) {
2532 $toselect = [];
2533}
2534$parameters['toselect'] = &$toselect;
2535$parameters['uploaddir'] = $uploaddir;
2536$parameters['massaction'] = $massaction;
2537$parameters['diroutputmassaction'] = isset($diroutputmassaction) ? $diroutputmassaction : null;
2538
2539// @phan-suppress-next-line PhanTypeMismatchArgumentNullable
2540$reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
2541if ($reshook < 0) {
2542 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
2543}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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 absolute discounts.
Class to manage standard extra fields.
Class to manage invoices.
const TYPE_REPLACEMENT
Replacement invoice.
const STATUS_DRAFT
Draft status.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
const TYPE_PROFORMA
Proforma invoice (should not be used.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
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='', $user_id=0)
Function to return number of working days (and text of units) between two dates (working days)
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png) $', '^\.'), $nohook=0, $mode=0, $limit=0)
Return file(s) into a directory (by default most recent)
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($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:66
dol_now($mode='gmt')
Return date for now.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTFLOAT($paramname, $rounding='', $option=2)
Return the value of a $_GET or $_POST supervariable, converted into float.
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...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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).
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
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:275
pdf_getInstance($format='', $metric='mm', $pagetype='P')
Return a PDF instance object.
Definition pdf.lib.php:129
getObjectIdsRefusedToUser(User $user, $object, array $ids)
Return, among a list of ids of objects of the same type, the ids of the objects the user is not allow...
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.