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