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