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