dolibarr 22.0.5
actions_massactions.inc.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2015-2025 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2018-2021 Nicolas ZABOURI <info@inovea-conseil.com>
4 * Copyright (C) 2018 Juanjo Menent <jmenent@2byte.es>
5 * Copyright (C) 2019 Ferran Marcet <fmarcet@2byte.es>
6 * Copyright (C) 2019-2025 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 * or see https://www.gnu.org/
22 */
23
30// $massaction must be defined
31// $objectclass and $objectlabel must be defined
32// $parameters, $object, $action must be defined for the hook.
33
34// $permissiontoread, $permissiontoadd, $permissiontodelete, $permissiontoclose may be defined
35// $uploaddir may be defined (example to $conf->project->dir_output."/";)
36// $hidedetails, $hidedesc, $hideref and $moreparams may have been set or not.
37// $toselect may be defined
38// $diroutputmassaction may be defined
39// $confirm
76'
77@phan-var-force ?string $permissiontoread
78@phan-var-force ?string $permissiontodelete
79@phan-var-force ?string $permissiontoclose
80@phan-var-force ?string $permissiontoapprove
81@phan-var-force ?int[] $toselect
82@phan-var-force ?string $diroutputmassaction
83@phan-var-force ?string $objectlabel
84@phan-var-force ?string $option
85@phan-var-force int $deliveryreceipt
86@phan-var-force ?array<string,mixed> $moreparams
87';
88
89
90// Protection
91if (empty($objectclass) || empty($uploaddir)) {
92 dol_print_error(null, 'include of actions_massactions.inc.php is done but var $objectclass or $uploaddir was not defined');
93 exit;
94}
95if (empty($massaction)) {
96 $massaction = '';
97}
98
99// Note: list of strings for objectclass could be extended to accepted/expected classes
100'
101@phan-var-force "CommonObject"|"CommandeFournisseur"|"ConferenceOrBoothAttendee"|"Contrat"|"Contact"|"Expedition"|"ExpenseReport"|"Facture"|"FactureFournisseur"|"Fichinter"|"Holiday"|"Partnership"|"Project"|"Propal"|"Societe"|"SupplierProposal" $objectclass
102@phan-var-force string $massaction
103@phan-var-force string $uploaddir
104';
105
106
107// For backward compatibility
108if (!empty($permtoread) && empty($permissiontoread)) {
109 $permissiontoread = $permtoread;
110}
111if (!empty($permtocreate) && empty($permissiontoadd)) {
112 $permissiontoadd = $permtocreate;
113}
114if (!empty($permtodelete) && empty($permissiontodelete)) {
115 $permissiontodelete = $permtodelete;
116}
117
118// Mass actions. Controls on number of lines checked.
119$maxformassaction = getDolGlobalInt('MAIN_LIMIT_FOR_MASS_ACTIONS', 1000);
120if ($massaction && is_array($toselect) && count($toselect) < 1) {
121 $error++;
122 setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
123}
124if (!$error && isset($toselect) && is_array($toselect) && count($toselect) > $maxformassaction) {
125 setEventMessages($langs->trans('TooManyRecordForMassAction', $maxformassaction), null, 'errors');
126 $error++;
127}
128
129if (!$error && $massaction == 'confirm_presend' && !GETPOST('sendmail')) { // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
130 $massaction = 'presend';
131}
132
133if (!$error && $massaction == 'confirm_presend') {
134 $resaction = '';
135 $nbsent = 0;
136 $nbignored = 0;
137 $langs->load("mails");
138 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
139 include_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
140
141 $listofobjectid = array();
142 $listofobjectthirdparties = array();
143 $listofobjectcontacts = array();
144 $listofobjectref = array();
145 $contactidtosend = array();
146 $attachedfilesThirdpartyObj = array();
147 $oneemailperrecipient = (GETPOSTINT('oneemailperrecipient') ? 1 : 0);
148 $thirdparty = null;
149
150 if (!$error) {
151 $objecttmp = new $objectclass($db);
152
153 // Define object $thirdparty (Societe or User, Adherent, ConferenceOrBoothAttendee...)
154 $thirdparty = new Societe($db);
155 if ($objecttmp->element == 'expensereport') {
156 $thirdparty = new User($db);
157 } elseif ($objecttmp->element == 'contact') {
158 $thirdparty = new Contact($db);
159 } elseif ($objecttmp->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
160 $thirdparty = new Adherent($db);
161 } elseif ($objecttmp->element == 'holiday') {
162 $thirdparty = new User($db);
163 } elseif ($objecttmp->element == 'conferenceorboothattendee') {
164 $thirdparty = new ConferenceOrBoothAttendee($db);
165 }
166
167 foreach ($toselect as $toselectid) {
168 $objecttmp = new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use
169 '@phan-var-force CommonObject $objecttmp';
171 $result = $objecttmp->fetch($toselectid);
172 if ($result > 0) {
173 $listofobjectid[$toselectid] = $toselectid;
174
175 // Set $tmpobjectid that is ID of parent object (thirdparty or user in most cases)
176 $tmpobjectid = ($objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid);
177 if ($objecttmp->element == 'societe') {
178 '@phan-var-force Societe $objecttmp';
180 $tmpobjectid = $objecttmp->id;
181 } elseif ($objecttmp->element == 'contact') {
182 '@phan-var-force Contact $objecttmp';
184 $tmpobjectid = $objecttmp->id;
185 } elseif ($objecttmp->element == 'expensereport') {
186 '@phan-var-force ExpenseReport $objecttmp';
188 $tmpobjectid = $objecttmp->fk_user_author;
189 } elseif ($objecttmp->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
190 '@phan-var-force Partnership $objecttmp';
192 $tmpobjectid = $objecttmp->fk_member;
193 } elseif ($objecttmp->element == 'holiday') {
194 '@phan-var-force Holiday $objecttmp';
196 $tmpobjectid = $objecttmp->fk_user;
197 } elseif ($objecttmp->element == 'conferenceorboothattendee') {
198 '@phan-var-force ConferenceOrBoothAttendee $objecttmp';
200 $tmpobjectid = $objecttmp->id;
201 }
202 if (empty($tmpobjectid)) {
203 $tmpobjectid = 0;
204 }
205
206 if ($objectclass == 'Facture') {
207 '@phan-var-force Facture $objecttmp';
209 $tmparraycontact = array();
210 $tmparraycontact = $objecttmp->liste_contact(-1, 'external', 0, 'BILLING');
211 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
212 foreach ($tmparraycontact as $data_email) {
213 $listofobjectcontacts[$toselectid][$data_email['id']] = $data_email['email'];
214 }
215 }
216 } elseif ($objectclass == 'CommandeFournisseur') {
217 '@phan-var-force CommandeFournisseur $objecttmp';
219 $tmparraycontact = array();
220 $tmparraycontact = $objecttmp->liste_contact(-1, 'external', 0, 'CUSTOMER');
221 if (is_array($tmparraycontact) && count($tmparraycontact) > 0) {
222 foreach ($tmparraycontact as $data_email) {
223 $listofobjectcontacts[$toselectid][$data_email['id']] = $data_email['email'];
224 }
225 }
226 }
227
228 $listofobjectthirdparties[$tmpobjectid] = $tmpobjectid;
229 $listofobjectref[$tmpobjectid][$toselectid] = $objecttmp;
230 }
231 }
232 }
233
234 // Check mandatory parameters
235 if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email)) {
236 $error++;
237 setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
238 $massaction = 'presend';
239 }
240
241 $receiver = GETPOST('receiver', 'alphawithlgt');
242 if (!is_array($receiver)) {
243 if (empty($receiver) || $receiver == '-1') {
244 $receiver = array();
245 } else {
246 $receiver = array($receiver);
247 }
248 }
249 if (!trim(GETPOST('sendto', 'alphawithlgt')) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) { // if only one recipient, receiver is mandatory
250 $error++;
251 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
252 $massaction = 'presend';
253 }
254
255 if (!GETPOST('subject', 'restricthtml')) {
256 $error++;
257 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
258 $massaction = 'presend';
259 }
260
261 // Loop on each recipient (may be a thirdparty but also a user, a conferenceorboothattendee, ...)
262 if (!$error) {
263 foreach ($listofobjectthirdparties as $thirdpartyid) {
264 $result = $thirdparty->fetch($thirdpartyid);
265 if ($result < 0) {
266 dol_print_error($db);
267 exit;
268 }
269
270 $sendto = '';
271 $sendtocc = '';
272 $sendtobcc = '';
273 //$sendtoid = array();
274
275 // Define $sendto
276 $tmparray = array();
277 if (trim(GETPOST('sendto', 'alphawithlgt'))) {
278 // Recipients are provided into free text
279 $tmparray[] = trim(GETPOST('sendto', 'alphawithlgt'));
280 }
281 if (count($receiver) > 0 && is_object($thirdparty)) {
282 foreach ($receiver as $key => $val) {
283 // Recipient was provided from combo list
284 if ($val == 'thirdparty') { // Id of third party or user
285 $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
286 } elseif ($val && method_exists($thirdparty, 'contact_get_property')) { // Id of contact
287 $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
288 //$sendtoid[] = $val;
289 }
290 }
291 }
292 $sendto = implode(',', $tmparray);
293
294 // Define $sendtocc
295 $receivercc = GETPOST('receivercc', 'alphawithlgt');
296 if (!is_array($receivercc)) {
297 if ($receivercc == '-1') {
298 $receivercc = array();
299 } else {
300 $receivercc = array($receivercc);
301 }
302 }
303 $tmparray = array();
304 if (trim(GETPOST('sendtocc', 'alphawithlgt'))) {
305 $tmparray[] = trim(GETPOST('sendtocc', 'alphawithlgt'));
306 }
307 if (count($receivercc) > 0) {
308 foreach ($receivercc as $key => $val) {
309 // Recipient was provided from combo list
310 if ($val == 'thirdparty') { // Id of third party
311 $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
312 } elseif ($val) { // Id du contact
313 $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
314 //$sendtoid[] = $val; TODO Add also id of contact in CC ?
315 }
316 }
317 }
318 $sendtocc = implode(',', $tmparray);
319
320 //var_dump($listofobjectref);exit;
321 $listofqualifiedobj = array();
322 $listofqualifiedref = array();
323 $thirdpartywithoutemail = array();
324
325 foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj) {
326 //var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
327 // Honour the same per-object hidden constants used by the "Send by email"
328 // button on the card pages (comm/propal/card.php, commande/card.php,
329 // compta/facture/card.php) so the behaviour is consistent between the
330 // single-object action and the mass action.
331 if ($objectclass == 'Propal' && $objectobj->status == Propal::STATUS_DRAFT && !getDolGlobalString('PROPOSAL_SENDBYEMAIL_FOR_ALL_STATUS')) {
332 $langs->load("errors");
333 $nbignored++;
334 $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
335 continue; // Payment done or started or canceled
336 }
337 if ($objectclass == 'Commande' && $objectobj->status == Commande::STATUS_DRAFT && !getDolGlobalString('COMMANDE_SENDBYEMAIL_FOR_ALL_STATUS')) {
338 $langs->load("errors");
339 $nbignored++;
340 $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
341 continue;
342 }
343 if ($objectclass == 'Facture' && $objectobj->status == Facture::STATUS_DRAFT && !getDolGlobalString('FACTURE_SENDBYEMAIL_FOR_ALL_STATUS')) {
344 $langs->load("errors");
345 $nbignored++;
346 $resaction .= '<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction', $objectobj->ref).'</div><br>';
347 continue; // Payment done or started or canceled
348 }
349
350 // Test recipient
351 if (empty($sendto)) { // For the case, no recipient were set (multi thirdparties send)
352 if ($objectobj->element == 'societe') {
353 $sendto = $objectobj->email;
354 } elseif ($objectobj->element == 'expensereport') {
355 $fuser = new User($db);
356 $fuser->fetch($objectobj->fk_user_author);
357 $sendto = $fuser->email;
358 } elseif ($objectobj->element == 'contact') {
359 $fcontact = new Contact($db);
360 $fcontact->fetch($objectobj->id);
361 $sendto = $fcontact->email;
362 } elseif ($objectobj->element == 'partnership' && getDolGlobalString('PARTNERSHIP_IS_MANAGED_FOR') == 'member') {
363 $fadherent = new Adherent($db);
364 $fadherent->fetch($objectobj->fk_member);
365 $sendto = $fadherent->email;
366 } elseif ($objectobj->element == 'holiday') {
367 $fuser = new User($db);
368 $fuser->fetch($objectobj->fk_user);
369 $sendto = $fuser->email;
370 } elseif ($objectobj->element == 'facture' && !empty($listofobjectcontacts[$objectid])) {
371 $emails_to_sends = array();
372 $objectobj->fetch_thirdparty();
373 $contactidtosend = array();
374 foreach ($listofobjectcontacts[$objectid] as $contactemailid => $contactemailemail) {
375 $emails_to_sends[] = $objectobj->thirdparty->contact_get_property($contactemailid, 'email');
376 if (!in_array($contactemailid, $contactidtosend)) {
377 $contactidtosend[] = $contactemailid;
378 }
379 }
380 if (count($emails_to_sends) > 0) {
381 $sendto = implode(',', $emails_to_sends);
382 }
383 } elseif ($objectobj->element == 'order_supplier' && !empty($listofobjectcontacts[$objectid])) {
384 $emails_to_sends = array();
385 $objectobj->fetch_thirdparty();
386 $contactidtosend = array();
387 foreach ($listofobjectcontacts[$objectid] as $contactemailid => $contactemailemail) {
388 $emails_to_sends[] = $objectobj->thirdparty->contact_get_property($contactemailid, 'email');
389 if (!in_array($contactemailid, $contactidtosend)) {
390 $contactidtosend[] = $contactemailid;
391 }
392 }
393 if (count($emails_to_sends) > 0) {
394 $sendto = implode(',', $emails_to_sends);
395 }
396 } elseif ($objectobj->element == 'conferenceorboothattendee') {
397 $sendto = $objectobj->email;
398 } else {
399 $objectobj->fetch_thirdparty();
400 $sendto = $objectobj->thirdparty->email;
401 }
402 }
403
404 if (empty($sendto)) {
405 if ($objectobj->element == 'societe') {
407 $objectobj->thirdparty = $objectobj; // Hack so following code is compatible when objectobj is a thirdparty
408 }
409
410 // print "No recipient for thirdparty ".$objectobj->thirdparty->name;
411 $nbignored++;
412 if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id])) {
413 $resaction .= '<div class="error">'.$langs->trans('NoRecipientEmail', $objectobj->thirdparty->name).'</div><br>';
414 }
415 dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
416 $thirdpartywithoutemail[$objectobj->thirdparty->id] = 1;
417 continue;
418 }
419
420 if (GETPOST('addmaindocfile')) {
421 // TODO Use future field $objectobj->fullpathdoc to know where is stored default file
422 // TODO If not defined, use $objectobj->model_pdf (or default invoice config) to know what is template to use to regenerate doc.
423 $filename = dol_sanitizeFileName($objectobj->ref).'.pdf';
424 $subdir = '';
425 // TODO Set subdir to be compatible with multi levels dir trees
426 // $subdir = get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element)
427 $filedir = $uploaddir.'/'.$subdir.dol_sanitizeFileName($objectobj->ref);
428 $filepath = $filedir.'/'.$filename;
429
430 // For supplier invoices, we use the file provided by supplier, not the one we generate
431 if ($objectobj->element == 'invoice_supplier') {
432 $fileparams = dol_most_recent_file($uploaddir.'/'.get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element).$objectobj->ref, preg_quote($objectobj->ref, '/').'([^\-])+');
433 $filepath = $fileparams['fullname'];
434 }
435
436 // try to find other files generated for this object (last_main_doc)
437 $filename_found = '';
438 $filepath_found = '';
439 $file_check_list = array();
440 $file_check_list[] = array(
441 'name' => $filename,
442 'path' => $filepath,
443 );
444 if (getDolGlobalString('MAIL_MASS_ACTION_ADD_LAST_IF_MAIN_DOC_NOT_FOUND') && !empty($objectobj->last_main_doc)) {
445 $file_check_list[] = array(
446 'name' => basename($objectobj->last_main_doc),
447 'path' => DOL_DATA_ROOT . '/' . $objectobj->last_main_doc,
448 );
449 }
450 foreach ($file_check_list as $file_check_arr) {
451 if (dol_is_file($file_check_arr['path'])) {
452 $filename_found = $file_check_arr['name'];
453 $filepath_found = $file_check_arr['path'];
454 break;
455 }
456 }
457
458 if ($filepath_found) {
459 // Create form object
460 $attachedfilesThirdpartyObj[$thirdpartyid][$objectid] = array(
461 'paths' => array($filepath_found),
462 'names' => array($filename_found),
463 'mimes' => array(dol_mimetype($filepath_found))
464 );
465 } else {
466 $nbignored++;
467 $langs->load("errors");
468 foreach ($file_check_list as $file_check_arr) {
469 $resaction .= '<div class="error">'.$langs->trans('ErrorCantReadFile', $file_check_arr['path']).'</div><br>';
470 dol_syslog('Failed to read file: '.$file_check_arr['path'], LOG_WARNING);
471 }
472 continue;
473 }
474 }
475
476 // Object of thirdparty qualified, we add it
477 $listofqualifiedobj[$objectid] = $objectobj;
478 $listofqualifiedref[$objectid] = $objectobj->ref;
479
480
481 //var_dump($listofqualifiedref);
482 }
483
484 // Send email if there is at least one qualified object for current thirdparty
485 if (count($listofqualifiedobj) > 0) {
486 $langs->load("commercial");
487
488 $reg = array();
489 $fromtype = GETPOST('fromtype');
490 if ($fromtype === 'user') {
491 $from = dol_string_nospecial($user->getFullName($langs), ' ', array(",")).' <'.$user->email.'>';
492 } elseif ($fromtype === 'company') {
493 $from = getDolGlobalString('MAIN_INFO_SOCIETE_NOM') . ' <' . getDolGlobalString('MAIN_INFO_SOCIETE_MAIL').'>';
494 } elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
495 $tmp = explode(',', $user->email_aliases);
496 $from = trim($tmp[((int) $reg[1] - 1)]);
497 } elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
498 $tmp = explode(',', getDolGlobalString('MAIN_INFO_SOCIETE_MAIL_ALIASES'));
499 $from = trim($tmp[((int) $reg[1] - 1)]);
500 } elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
501 $sql = "SELECT rowid, label, email FROM ".MAIN_DB_PREFIX."c_email_senderprofile WHERE rowid = ".(int) $reg[1];
502 $resql = $db->query($sql);
503 $obj = $db->fetch_object($resql);
504 if ($obj) {
505 $from = dol_string_nospecial($obj->label, ' ', array(",")).' <'.$obj->email.'>';
506 }
507 } else {
508 $from = GETPOST('fromname').' <'.GETPOST('frommail').'>';
509 }
510
511 $replyto = $from;
512 $subject = GETPOST('subject', 'restricthtml');
513 $message = GETPOST('message', 'restricthtml');
514
515 $sendtobcc = GETPOST('sendtoccc');
516 if ($objectclass == 'Propal') {
517 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROPOSAL_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROPOSAL_TO')));
518 }
519 if ($objectclass == 'Commande') {
520 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_ORDER_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_ORDER_TO')));
521 }
522 if ($objectclass == 'Facture') {
523 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_INVOICE_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_INVOICE_TO')));
524 }
525 if ($objectclass == 'SupplierProposal') {
526 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO')));
527 }
528 if ($objectclass == 'CommandeFournisseur') {
529 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO')));
530 }
531 if ($objectclass == 'FactureFournisseur') {
532 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO')));
533 }
534 if ($objectclass == 'Project') {
535 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROJECT_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROJECT_TO')));
536 }
537
538 // $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)
539 // $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)
540 $looparray = array();
541 if (!$oneemailperrecipient) {
542 $looparray = $listofqualifiedobj;
543 foreach ($looparray as $key => $objecttmp) {
544 $looparray[$key]->thirdparty = $thirdparty; // Force thirdparty on object
545 }
546 } else {
547 $objectforloop = new $objectclass($db);
548 $objectforloop->thirdparty = $thirdparty; // Force thirdparty on object (even if object was not loaded)
549 $looparray[0] = $objectforloop;
550 }
551 //var_dump($looparray);exit;
552 dol_syslog("We have set an array of ".count($looparray)." emails to send. oneemailperrecipient=".$oneemailperrecipient);
553 //var_dump($oneemailperrecipient); var_dump($listofqualifiedobj); var_dump($listofqualifiedref);
554 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
555 // Make substitution in email content
556 if (isModEnabled('project') && method_exists($objecttmp, 'fetchProject') && is_null($objecttmp->project)) {
557 $objecttmp->fetchProject();
558 }
559 $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $objecttmp);
560 $substitutionarray['__ID__'] = ($oneemailperrecipient ? implode(', ', array_keys($listofqualifiedobj)) : $objecttmp->id);
561 $substitutionarray['__REF__'] = ($oneemailperrecipient ? implode(', ', $listofqualifiedref) : $objecttmp->ref);
562 $substitutionarray['__EMAIL__'] = $thirdparty->email;
563 $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"/>';
564
565 if ($oneemailperrecipient) {
566 $substitutionarray['__ONLINE_PAYMENT_URL__'] = '';
567 $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = '';
568 }
569
570 $parameters = array('mode' => 'formemail');
571
572 if (!empty($listofobjectthirdparties)) {
573 $parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
574 }
575 if (!empty($listofobjectref)) {
576 $parameters['listofobjectref'] = $listofobjectref;
577 }
578
579 complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
580
581 $subjectreplaced = make_substitutions($subject, $substitutionarray);
582 $messagereplaced = make_substitutions($message, $substitutionarray);
583
584 $attachedfiles = array('paths' => array(), 'names' => array(), 'mimes' => array());
585 if ($oneemailperrecipient) {
586 // if "one email per recipient" is check we must collate $attachedfiles by thirdparty
587 if (is_array($attachedfilesThirdpartyObj[$thirdparty->id]) && count($attachedfilesThirdpartyObj[$thirdparty->id])) { // @phpstan-ignore-line
588 foreach ($attachedfilesThirdpartyObj[$thirdparty->id] as $keyObjId => $objAttachedFiles) {
589 // Create form object
590 $attachedfiles = array(
591 'paths' => array_merge($attachedfiles['paths'], $objAttachedFiles['paths']),
592 'names' => array_merge($attachedfiles['names'], $objAttachedFiles['names']),
593 'mimes' => array_merge($attachedfiles['mimes'], $objAttachedFiles['mimes'])
594 );
595 }
596 }
597 } elseif (!empty($attachedfilesThirdpartyObj[$thirdparty->id][$objectid])) {
598 // Create form object
599 // if "one email per recipient" isn't check we must separate $attachedfiles by object
600 $attachedfiles = $attachedfilesThirdpartyObj[$thirdparty->id][$objectid];
601 }
602
603 $filepath = $attachedfiles['paths'];
604 $filename = $attachedfiles['names'];
605 $mimetype = $attachedfiles['mimes'];
606
607 // Define the trackid when emails sent from the mass action
608 if ($oneemailperrecipient) {
609 $trackid = 'thi'.$thirdparty->id;
610 if ($objecttmp->element == 'expensereport') {
611 $trackid = 'use'.$thirdparty->id;
612 } elseif ($objecttmp->element == 'contact') {
613 $trackid = 'ctc'.$thirdparty->id;
614 } elseif ($objecttmp->element == 'holiday') {
615 $trackid = 'use'.$thirdparty->id;
616 }
617 } else {
618 $trackid = strtolower(get_class($objecttmp));
619 if (get_class($objecttmp) == 'Contact') {
620 $trackid = 'ctc';
621 } elseif (get_class($objecttmp) == 'Contrat') {
622 $trackid = 'con';
623 } elseif (get_class($objecttmp) == 'Propal') {
624 $trackid = 'pro';
625 } elseif (get_class($objecttmp) == 'Commande') {
626 $trackid = 'ord';
627 } elseif (get_class($objecttmp) == 'Facture') {
628 $trackid = 'inv';
629 } elseif (get_class($objecttmp) == 'SupplierProposal') {
630 $trackid = 'spr';
631 } elseif (get_class($objecttmp) == 'CommandeFournisseur') {
632 $trackid = 'sor';
633 } elseif (get_class($objecttmp) == 'FactureFournisseur') {
634 $trackid = 'sin';
635 }
636
637 $trackid .= $objecttmp->id;
638 }
639 //var_dump($filepath);
640 //var_dump($trackid);exit;
641 //var_dump($subjectreplaced);
642
643 if (empty($sendcontext)) {
644 $sendcontext = 'standard';
645 }
646
647 // Set tmp user directory (used to convert images embedded as img src=data:image)
648 $vardir = $conf->user->dir_output."/".$user->id;
649 $upload_dir_tmp = $vardir.'/temp'; // TODO Add $keytoavoidconflict in upload_dir path
650
651 // Send mail (substitutionarray must be done just before this)
652 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
653 $mailfile = new CMailFile($subjectreplaced, (string) $sendto, $from, $messagereplaced, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, (int) $deliveryreceipt, -1, '', '', $trackid, '', $sendcontext, '', $upload_dir_tmp);
654 if ($mailfile->error) {
655 $resaction .= '<div class="error">'.$mailfile->error.'</div>';
656 } else {
657 $result = $mailfile->sendfile();
658 if ($result > 0) {
659 $resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($mailfile->addr_from, 2), $mailfile->getValidAddress($mailfile->addr_to, 2)).'<br>'; // Must not contain "
660
661 $error = 0;
662
663 // Insert logs into agenda
664 foreach ($listofqualifiedobj as $objid2 => $objectobj2) {
665 if ((!$oneemailperrecipient) && $objid2 != $objectid) {
666 continue; // We discard this pass to avoid duplicate with other pass in looparray at higher level
667 }
668
669 dol_syslog("Try to insert email event into agenda for objid=".$objid2." => objectobj=".get_class($objectobj2));
670
671 /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
672 if ($objectclass == 'Commande') $actiontypecode='AC_COM';
673 if ($objectclass == 'Facture') $actiontypecode='AC_FAC';
674 if ($objectclass == 'SupplierProposal') $actiontypecode='AC_SUP_PRO';
675 if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
676 if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
677
678 $actionmsg = $langs->transnoentities('MailSentByTo', $from, (string) $sendto);
679 if ($message) {
680 if ($sendtocc) {
681 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc);
682 }
683 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subjectreplaced);
684 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
685 $actionmsg = dol_concatdesc($actionmsg, $messagereplaced);
686 }
687 $actionmsg2 = '';
688
689 // Initialisation donnees
690 $objectobj2->sendtoid = (empty($contactidtosend) ? 0 : $contactidtosend);
691 $objectobj2->actionmsg = $actionmsg; // Long text
692 $objectobj2->actionmsg2 = $actionmsg2; // Short text
693 $objectobj2->fk_element = $objid2;
694 $objectobj2->elementtype = $objectobj2->element;
695 if (getDolGlobalString('MAIN_MAIL_REPLACE_EVENT_TITLE_BY_EMAIL_SUBJECT')) {
696 $objectobj2->actionmsg2 = $subjectreplaced; // Short text
697 }
698
699 $triggername = strtoupper(get_class($objectobj2)).'_SENTBYMAIL';
700 if ($triggername == 'SOCIETE_SENTBYMAIL') {
701 $triggername = 'COMPANY_SENTBYMAIL';
702 }
703 if ($triggername == 'CONTRAT_SENTBYMAIL') {
704 $triggername = 'CONTRACT_SENTBYMAIL';
705 }
706 if ($triggername == 'COMMANDE_SENTBYMAIL') {
707 $triggername = 'ORDER_SENTBYMAIL';
708 }
709 if ($triggername == 'FACTURE_SENTBYMAIL') {
710 $triggername = 'BILL_SENTBYMAIL';
711 }
712 if ($triggername == 'EXPEDITION_SENTBYMAIL') {
713 $triggername = 'SHIPPING_SENTBYMAIL';
714 }
715 if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') {
716 $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
717 }
718 if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') {
719 $triggername = 'BILL_SUPPLIER_SENTBYMAIL';
720 }
721 if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') {
722 $triggername = 'PROPOSAL_SUPPLIER_SENTBYMAIL';
723 }
724 if ($triggername == 'PROJET_SENTBYMAIL') {
725 $triggername = 'PROJECT_SENTBYMAIL';
726 }
727
728 if (!empty($triggername)) {
729 // Call trigger
730 $result = $objectobj2->call_trigger($triggername, $user);
731 if ($result < 0) {
732 $error++;
733 }
734 // End call triggers
735
736 if ($error) {
737 setEventMessages($db->lasterror(), null, 'errors');
738 dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR);
739 }
740 }
741
742 $nbsent++; // Nb of object sent
743 }
744 } else {
745 $langs->load("other");
746 if ($mailfile->error) {
747 $resaction .= $langs->trans('ErrorFailedToSendMail', $from, (string) $sendto);
748 $resaction .= '<br><div class="error">'.$mailfile->error.'</div>';
749 } elseif (getDolGlobalString('MAIN_DISABLE_ALL_MAILS')) {
750 $resaction .= '<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
751 } else {
752 $resaction .= $langs->trans('ErrorFailedToSendMail', $from, (string) $sendto) . '<br><div class="error">(unhandled error)</div>';
753 }
754 }
755 }
756 }
757 }
758 }
759
760 $resaction .= ($resaction ? '<br>' : $resaction);
761 $resaction .= '<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
762 $resaction .= $langs->trans("NbSelected").': '.count($toselect)."\n<br>";
763 $resaction .= $langs->trans("NbIgnored").': '.($nbignored ? $nbignored : 0)."\n<br>";
764 $resaction .= $langs->trans("NbSent").': '.($nbsent ? $nbsent : 0)."\n<br>";
765
766 if ($nbsent) {
767 $action = ''; // Do not show form post if there was at least one successful sent
768 //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
769 setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
770 setEventMessages($resaction, null, 'mesgs');
771 } else {
772 //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings'); // May be object has no generated PDF file
773 setEventMessages($resaction, null, 'warnings');
774 }
775
776 $action = 'list';
777 $massaction = '';
778 }
779}
780
781
782if (!$error && $massaction == 'cancelorders') {
783 $db->begin();
784
785 $nbok = 0;
786
787 $orders = GETPOST('toselect', 'array');
788 foreach ($orders as $id_order) {
789 $cmd = new Commande($db);
790 if ($cmd->fetch($id_order) <= 0) {
791 continue;
792 }
793
794 if ($cmd->status != Commande::STATUS_VALIDATED) {
795 $langs->load('errors');
796 setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
797 $error++;
798 break;
799 } else {
800 // TODO We do not provide warehouse so no stock change here for the moment.
801 $result = $cmd->cancel();
802 }
803
804 if ($result < 0) {
805 setEventMessages($cmd->error, $cmd->errors, 'errors');
806 $error++;
807 break;
808 } else {
809 $nbok++;
810 }
811 }
812 if (!$error) {
813 setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
814 $db->commit();
815 } else {
816 $db->rollback();
817 }
818}
819
820
821if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search')) {
822 if (empty($diroutputmassaction)) {
823 dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
824 exit;
825 }
826
827 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
828 require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
829 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
830
831 $objecttmp = new $objectclass($db);
832 $listofobjectid = array();
833 $listofobjectthirdparties = array();
834 $listofobjectref = array();
835 foreach ($toselect as $toselectid) {
836 $objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use
837 $result = $objecttmp->fetch($toselectid);
838 if ($result > 0) {
839 $listofobjectid[$toselectid] = $toselectid;
840 $thirdpartyid = !empty($objecttmp->fk_soc) ? $objecttmp->fk_soc : $objecttmp->socid;
841 $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
842 $listofobjectref[$toselectid] = $objecttmp->ref;
843 }
844 }
845
846 $arrayofinclusion = array();
847 foreach ($listofobjectref as $tmppdf) {
848 $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$';
849 }
850 foreach ($listofobjectref as $tmppdf) {
851 $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[a-zA-Z0-9\-\_\'\&\.]+\.pdf$'; // To include PDF generated from ODX files
852 }
853
854 $listoffiles = dol_dir_list($uploaddir, 'all', 1, $arrayofinclusion, '\.meta$|\.png$', 'date', SORT_DESC, 0, 1);
855
856 dol_syslog("Found ".count($listoffiles)." files");
857
858 // build list of files with full path
859 $files = array();
860
861 foreach ($listofobjectref as $basename) {
862 $basename = dol_sanitizeFileName($basename);
863 foreach ($listoffiles as $filefound) {
864 if (strstr($filefound["name"], $basename)) {
865 $files[] = $filefound['fullname'];
866 break;
867 }
868 }
869 }
870
871 // Define output language (Here it is not used because we do only merging existing PDF)
872 $outputlangs = $langs;
873 $newlang = '';
874 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
875 $newlang = GETPOST('lang_id', 'aZ09');
876 }
877 //elseif (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && is_object($objecttmp->thirdparty)) { // On massaction, we can have several values for $objecttmp->thirdparty
878 // $newlang = $objecttmp->thirdparty->default_lang;
879 //}
880 if (!empty($newlang)) {
881 $outputlangs = new Translate("", $conf);
882 $outputlangs->setDefaultLang($newlang);
883 }
884
885 if (getDolGlobalString('USE_PDFTK_FOR_PDF_CONCAT')) {
886 // Create output dir if not exists
887 dol_mkdir($diroutputmassaction);
888
889 // Defined name of merged file
890 $filename = strtolower(dol_sanitizeFileName($langs->transnoentities((string) $objectlabel)));
891 $filename = preg_replace('/\s/', '_', $filename);
892
893 // Save merged file
894 if (in_array($objecttmp->element, array('facture', 'invoice_supplier')) && $search_status == Facture::STATUS_VALIDATED) {
895 if ($option == 'late') {
896 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
897 } else {
898 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
899 }
900 }
901 if ($year) {
902 $filename .= '_'.$year;
903 }
904 if ($month) {
905 $filename .= '_'.$month;
906 }
907
908 if (count($files) > 0) {
909 $now = dol_now();
910 $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
911
912 $input_files = '';
913 foreach ($files as $f) {
914 $input_files .= ' '.escapeshellarg($f);
915 }
916
917 $cmd = 'pdftk '.$input_files.' cat output '.escapeshellarg($file);
918 exec($cmd);
919
920 // check if pdftk is installed
921 if (file_exists($file)) {
922 dolChmod($file);
923
924 $langs->load("exports");
925 setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
926 } else {
927 setEventMessages($langs->trans('ErrorPDFTkOutputFileNotFound'), null, 'errors');
928 }
929 } else {
930 setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
931 }
932 } else {
933 // Create empty PDF
934 $formatarray = pdf_getFormat();
935 $page_largeur = $formatarray['width'];
936 $page_hauteur = $formatarray['height'];
937 $format = array($page_largeur, $page_hauteur);
938
939 $pdf = pdf_getInstance($format);
940
941 if (class_exists('TCPDF')) {
942 $pdf->setPrintHeader(false);
943 $pdf->setPrintFooter(false);
944 }
945 $pdf->SetFont(pdf_getPDFFont($outputlangs));
946
947 if (getDolGlobalString('MAIN_DISABLE_PDF_COMPRESSION')) {
948 $pdf->SetCompression(false);
949 }
950
951 $pagecount = 0;
952 // Add all others
953 foreach ($files as $file) {
954 // Charge un document PDF depuis un fichier.
955 $pagecount = $pdf->setSourceFile($file);
956 for ($i = 1; $i <= $pagecount; $i++) {
957 $tplidx = $pdf->importPage($i);
958 $s = $pdf->getTemplatesize($tplidx);
959 $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
960 $pdf->useTemplate($tplidx);
961 }
962 }
963
964 // Create output dir if not exists
965 dol_mkdir($diroutputmassaction);
966
967 // Defined name of merged file
968 $filename = strtolower(dol_sanitizeFileName($langs->transnoentities((string) $objectlabel)));
969 $filename = preg_replace('/\s/', '_', $filename);
970
971
972 // Save merged file
973 if (in_array($objecttmp->element, array('facture', 'invoice_supplier')) && $search_status == Facture::STATUS_VALIDATED) {
974 if ($option == 'late') {
975 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
976 } else {
977 $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
978 }
979 }
980 if (!empty($year)) {
981 $filename .= '_'.$year;
982 }
983 if (!empty($month)) {
984 $filename .= '_'.$month;
985 }
986 if ($pagecount) {
987 $now = dol_now();
988 $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
989 $pdf->Output($file, 'F');
990 dolChmod($file);
991
992 $langs->load("exports");
993 setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
994 } else {
995 setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
996 }
997 }
998}
999
1000// Remove a file from massaction area
1001if ($action == 'remove_file') {
1002 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1003
1004 $langs->load("other");
1005 $upload_dir = $diroutputmassaction;
1006 $file = $upload_dir.'/'.GETPOST('file');
1007 $ret = dol_delete_file($file);
1008 if ($ret) {
1009 setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
1010 } else {
1011 setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
1012 }
1013 $action = '';
1014}
1015
1016
1017// Validate records
1018if (!$error && $massaction == 'validate' && $permissiontoadd) {
1019 $objecttmp = new $objectclass($db);
1020
1021 if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_BILL')) {
1022 $langs->load("errors");
1023 setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1024 $error++;
1025 }
1026 if ($objecttmp->element == 'invoice_supplier' && isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL')) {
1027 $langs->load("errors");
1028 setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1029 $error++;
1030 }
1031 if ($objecttmp->element == 'facture') {
1032 if (!empty($toselect) && getDolGlobalString('INVOICE_CHECK_POSTERIOR_DATE')) {
1033 // order $toselect by date
1034 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture";
1035 $sql .= " WHERE rowid IN (".$db->sanitize(implode(",", $toselect)).")";
1036 $sql .= " ORDER BY datef";
1037
1038 $resql = $db->query($sql);
1039 if ($resql) {
1040 $toselectnew = [];
1041 while (!empty($arr = $db->fetch_row($resql))) {
1042 $toselectnew[] = $arr[0];
1043 }
1044 $toselect = (empty($toselectnew)) ? $toselect : $toselectnew;
1045 } else {
1046 dol_print_error($db);
1047 $error++;
1048 }
1049 }
1050 }
1051 if (!$error) {
1052 $db->begin();
1053
1054 $nbok = 0;
1055 foreach ($toselect as $toselectid) {
1056 $result = $objecttmp->fetch($toselectid);
1057 if ($result > 0) {
1058 if (method_exists($objecttmp, 'validate')) {
1059 $result = $objecttmp->validate($user);
1060 } elseif (method_exists($objecttmp, 'setValid')) {
1061 $result = $objecttmp->setValid($user);
1062 } else {
1063 $objecttmp->error = 'No method validate or setValid on this object';
1064 $result = -1;
1065 }
1066 if ($result == 0) {
1067 $langs->load("errors");
1068 setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
1069 $error++;
1070 break;
1071 } elseif ($result < 0) {
1072 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1073 $error++;
1074 break;
1075 } else {
1076 // validate() rename pdf but do not regenerate
1077 // Define output language
1078 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1079 $outputlangs = $langs;
1080 $newlang = '';
1081 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
1082 $newlang = GETPOST('lang_id', 'aZ09');
1083 }
1084 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && property_exists($objecttmp, 'thirdparty')) {
1085 if ((property_exists($objecttmp, 'socid') || property_exists($objecttmp, 'fk_soc')) && empty($objecttmp->thirdparty)) {
1086 $objecttmp->fetch_thirdparty();
1087 }
1088 if (!empty($objecttmp->thirdparty)) {
1089 $newlang = $objecttmp->thirdparty->default_lang;
1090 }
1091 }
1092 if (!empty($newlang)) {
1093 $outputlangs = new Translate("", $conf);
1094 $outputlangs->setDefaultLang($newlang);
1095 $outputlangs->load('products');
1096 }
1097 $model = $objecttmp->model_pdf;
1098 $ret = $objecttmp->fetch($objecttmp->id); // Reload to get new records
1099
1100 // To be sure vars is defined
1101 $hidedetails = isset($hidedetails) ? $hidedetails : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
1102 $hidedesc = isset($hidedesc) ? $hidedesc : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
1103 $hideref = isset($hideref) ? $hideref : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
1104 $moreparams = isset($moreparams) ? $moreparams : null;
1105
1106 $result = $objecttmp->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1107 if ($result < 0) {
1108 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1109 }
1110 }
1111 $nbok++;
1112 }
1113 } else {
1114 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1115 $error++;
1116 break;
1117 }
1118 }
1119
1120 if (!$error) {
1121 if ($nbok > 1) {
1122 setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1123 } else {
1124 setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
1125 }
1126 $db->commit();
1127 } else {
1128 $db->rollback();
1129 }
1130 }
1131}
1132
1133// Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
1134if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) {
1135 $db->begin();
1136
1137 $objecttmp = new $objectclass($db);
1138 $nbok = 0;
1139 $nbignored = 0;
1140 $TMsg = array();
1141
1142 //$toselect could contain duplicate entries, cf https://github.com/Dolibarr/dolibarr/issues/26244
1143 $unique_arr = array_unique($toselect);
1144 foreach ($unique_arr as $toselectid) {
1145 $result = $objecttmp->fetch($toselectid);
1146 if ($result > 0) {
1147 // Refuse deletion for some objects/status
1148 if ($objectclass == 'Facture' && !getDolGlobalString('INVOICE_CAN_ALWAYS_BE_REMOVED') && $objecttmp->status != Facture::STATUS_DRAFT) {
1149 $langs->load("errors");
1150 $nbignored++;
1151 $TMsg[] = '<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'</div><br>';
1152 continue;
1153 }
1154
1155 if (method_exists($objecttmp, 'is_erasable') && $objecttmp->is_erasable() <= 0) {
1156 $langs->load("errors");
1157 $nbignored++;
1158 $TMsg[] = '<div class="error">'.$langs->trans('ErrorRecordHasChildren').' '.$objecttmp->ref.'</div><br>';
1159 continue;
1160 }
1161
1162 if ($objectclass == 'Holiday' && ! in_array($objecttmp->statut, array(Holiday::STATUS_DRAFT, Holiday::STATUS_CANCELED, Holiday::STATUS_REFUSED))) {
1163 $langs->load("errors");
1164 $nbignored++;
1165 $TMsg[] = '<div class="error">'.$langs->trans('ErrorLeaveRequestMustBeDraftCanceledOrRefusedToBeDeleted', $objecttmp->ref).'</div><br>';
1166 continue;
1167 }
1168
1169 if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) {
1170 $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".((int) $objecttmp->id);
1171 $res = $db->query($sql);
1172
1173 if (!$res) {
1174 setEventMessage('ErrorRecordParentingNotModified', 'errors');
1175 $error++;
1176 }
1177 }
1178
1179 if ($objecttmp->element == 'societe') {
1181 '@phan-var-force Societe $objecttmp';
1182 // TODO Change signature of delete for Societe
1183 $result = $objecttmp->delete($objecttmp->id, $user, 1);
1184 } else {
1185 $result = $objecttmp->delete($user);
1186 }
1187
1188 if (empty($result)) { // if delete returns 0, there is at least one object linked
1189 $TMsg = array_merge($objecttmp->errors, $TMsg);
1190 } elseif ($result < 0) { // if delete returns is < 0, there is an error, we break and rollback later
1191 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1192 $error++;
1193 break;
1194 } else {
1195 $nbok++;
1196 }
1197 } else {
1198 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1199 $error++;
1200 break;
1201 }
1202 }
1203
1204 if (empty($error)) {
1205 // Message for elements well deleted
1206 if ($nbok > 1) {
1207 setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1208 } elseif ($nbok > 0) {
1209 setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1210 } else {
1211 setEventMessages($langs->trans("NoRecordDeleted"), null, 'mesgs');
1212 }
1213
1214 // Message for elements which can't be deleted
1215 if (!empty($TMsg)) {
1216 sort($TMsg);
1217 setEventMessages('', array_unique($TMsg), 'warnings');
1218 }
1219
1220 $db->commit();
1221 } else {
1222 $db->rollback();
1223 }
1224
1225 //var_dump($listofobjectthirdparties);exit;
1226}
1227
1228// Generate document foreach object according to model linked to object
1229// @todo : propose model selection
1230if (!$error && $massaction == 'generate_doc' && $permissiontoread) {
1231 // Complete with classes that use this massaction
1232 <<<'EOPHAN'
1233@phan-var-force 'Commande'|'CommandeFournisseur'|'Contrat'|'Expedition'|'ExpenseReport'|'Facture'|'FactureFournisseur'|'Fichinter'|'Project'|'Propal'|'SupplierProposal' $objectclass
1234EOPHAN;
1235
1236 $db->begin();
1237 $nbok = 0;
1238
1239 $objecttmp = new $objectclass($db);
1240
1241 foreach ($toselect as $toselectid) {
1242 $objecttmp->thirdparty = null; // Clear if another value was already set by fetch_thirdparty later
1243 $result = $objecttmp->fetch($toselectid);
1244
1245 if ($result > 0) {
1246 $outputlangs = $langs;
1247 $newlang = '';
1248
1249 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
1250 $newlang = GETPOST('lang_id', 'aZ09');
1251 }
1252 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) {
1253 $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
1254 }
1255 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && isset($objecttmp->default_lang)) {
1256 $newlang = $objecttmp->default_lang; // for thirdparty @phan-suppress-current-line PhanUndeclaredProperty
1257 }
1258 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && empty($objecttmp->thirdparty)) { //load lang from thirdparty
1259 $objecttmp->fetch_thirdparty();
1260 $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
1261 }
1262 if (!empty($newlang)) {
1263 $outputlangs = new Translate("", $conf);
1264 $outputlangs->setDefaultLang($newlang);
1265 }
1266
1267 // To be sure vars is defined
1268 $hidedetails = isset($hidedetails) ? $hidedetails : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
1269 $hidedesc = isset($hidedesc) ? $hidedesc : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
1270 $hideref = isset($hideref) ? $hideref : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
1271 $moreparams = isset($moreparams) ? $moreparams : null;
1272
1273 $result = $objecttmp->generateDocument($objecttmp->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1274
1275 if ($result <= 0) {
1276 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1277 $error++;
1278 break;
1279 } else {
1280 $nbok++;
1281 }
1282 } else {
1283 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1284 $error++;
1285 break;
1286 }
1287 }
1288
1289 if (!$error) {
1290 if ($nbok > 1) {
1291 setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1292 } else {
1293 setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
1294 }
1295 $db->commit();
1296 } else {
1297 $db->rollback();
1298 }
1299}
1300
1301if (!$error && ($action == 'affecttag' && $confirm == 'yes') && $permissiontoadd) {
1302 $nbok = 0;
1303 $db->begin();
1304
1305 $affecttag_type = GETPOST('affecttag_type', 'alpha');
1306 if (!empty($affecttag_type)) {
1307 $affecttag_type_array = explode(',', $affecttag_type);
1308 } else {
1309 setEventMessage('CategTypeNotFound', 'errors');
1310 }
1311 if (!empty($affecttag_type_array)) {
1312 //check if tag type submitted exists into Tag Map categorie class
1313 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1314 $categ = new Categorie($db);
1315 $to_affecttag_type_array = array();
1316 $categ_type_array = $categ->getMapList();
1317 foreach ($categ_type_array as $categdef) {
1318 if (in_array($categdef['code'], $affecttag_type_array)) {
1319 $to_affecttag_type_array[] = $categdef['code'];
1320 }
1321 }
1322
1323 //For each valid categ type set common categ
1324 if (!empty($to_affecttag_type_array)) {
1325 foreach ($to_affecttag_type_array as $categ_type) {
1326 $contcats = GETPOST('contcats_' . $categ_type, 'array');
1327 //var_dump($toselect);exit;
1328 foreach ($toselect as $toselectid) {
1329 $result = $object->fetch($toselectid);
1330 //var_dump($contcats);exit;
1331 if ($result > 0) {
1332 $result = $object->setCategoriesCommon($contcats, $categ_type, false);
1333 if ($result > 0) {
1334 $nbok++;
1335 } else {
1336 setEventMessages($object->error, $object->errors, 'errors');
1337 }
1338 } else {
1339 setEventMessages($object->error, $object->errors, 'errors');
1340 $error++;
1341 break;
1342 }
1343 }
1344 }
1345 }
1346 }
1347
1348 if (!$error) {
1349 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1350 $db->commit();
1351 $toselect = array();
1352 } else {
1353 $db->rollback();
1354 }
1355}
1356
1357if (!$error && ($action == 'updateprice' && $confirm == 'yes') && $permissiontoadd) {
1358 '@phan-var-force Product|ProductCustomerPrice $obj';
1359 '@phan-var-force Product|ProductCustomerPrice $object';
1360 $nbok = 0;
1361 $db->begin();
1362 if (GETPOSTISSET('pricerate')) {
1363 $pricepercentage = GETPOSTINT('pricerate');
1364 if ($pricepercentage == 0) {
1365 setEventMessages($langs->trans("RecordsModified", 0), null);
1366 } else {
1367 foreach ($toselect as $toselectid) {
1368 $result = $object->fetch($toselectid);
1369 //var_dump($contcats);exit;
1370 if ($result > 0) {
1371 if (getDolGlobalString('PRODUCT_PRICE_UNIQ')
1372 || getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
1373 if ($object->price_base_type == 'TTC') {
1374 $newprice = $object->price_ttc * (100 + $pricepercentage) / 100;
1375 $minprice = $object->price_min_ttc;
1376 } else {
1377 $newprice = $object->price * (100 + $pricepercentage) / 100;
1378 $minprice = $object->price_min;
1379 }
1380 $res = $object->updatePrice($newprice, $object->price_base_type, $user, $object->tva_tx, $minprice, 0, $object->tva_npr, 0, 0, array(), $object->default_vat_code);
1381 if ($res > 0) {
1382 $nbok++;
1383 } else {
1384 setEventMessages($object->error, $object->errors, 'errors');
1385 }
1386 } elseif (getDolGlobalString('PRODUIT_MULTIPRICES')) {
1387 $maxlevel = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
1388 for ($level = 1; $level <= $maxlevel; $level++) {
1389 if ($object->price_base_type == 'TTC') {
1390 $newprice = $object->multiprices_ttc[$level] * (100 + $pricepercentage) / 100;
1391 $minprice = $object->multiprices_min_ttc[$level];
1392 } else {
1393 $newprice = $object->multiprices[$level] * (100 + $pricepercentage) / 100;
1394 $minprice = $object->multiprices_min[$level];
1395 }
1396 $res = $object->updatePrice($newprice, $object->price_base_type, $user, $object->tva_tx, $minprice, $level, $object->tva_npr, 0, 0, array(), $object->default_vat_code);
1397 if ($res > 0) {
1398 $nbok++;
1399 }
1400 }
1401 }
1402 } else {
1403 setEventMessages($object->error, $object->errors, 'errors');
1404 $error++;
1405 break;
1406 }
1407 }
1408 }
1409 }
1410
1411 if (!$error) {
1412 if ($nbok > 0) {
1413 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1414 }
1415 $db->commit();
1416 $toselect = array();
1417 } else {
1418 $db->rollback();
1419 }
1420}
1421
1422if (!$error && ($action == 'setsupervisor' && $confirm == 'yes') && $permissiontoadd) {
1423 '@phan-var-force User $object';
1424 $nbok = 0;
1425 $db->begin();
1426 $supervisortoset = GETPOSTINT('supervisortoset');
1427 if (!empty($supervisortoset)) {
1428 foreach ($toselect as $toselectid) {
1429 $result = $object->fetch($toselectid);
1430 //var_dump($contcats);exit;
1431 if ($result > 0) {
1432 $object->fk_user = $supervisortoset;
1433 $res = $object->update($user);
1434 if ($res > 0) {
1435 $nbok++;
1436 } else {
1437 setEventMessages($object->error, $object->errors, 'errors');
1438 }
1439 } else {
1440 setEventMessages($object->error, $object->errors, 'errors');
1441 $error++;
1442 break;
1443 }
1444 }
1445 } else {
1446 setEventMessage('UserNotFound', 'errors');
1447 $error++;
1448 }
1449
1450 if (!$error) {
1451 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1452 $db->commit();
1453 $toselect = array();
1454 } else {
1455 $db->rollback();
1456 }
1457}
1458
1459if (!$error && ($action == 'affectuser' && $confirm == 'yes') && $permissiontoadd) {
1460 $nbok = 0;
1461 $db->begin();
1462
1463 $usertoaffect = GETPOSTINT('usertoaffect');
1464 $projectrole = GETPOST('projectrole');
1465 $tasksrole = GETPOST('tasksrole');
1466 if (!empty($usertoaffect)) {
1467 foreach ($toselect as $toselectid) {
1468 $result = $object->fetch($toselectid);
1469 //var_dump($contcats);exit;
1470 if ($result > 0) {
1471 $res = $object->add_contact($usertoaffect, $projectrole, 'internal');
1472 if ($res >= 0) {
1473 $taskstatic = new Task($db);
1474 $task_array = $taskstatic->getTasksArray(null, null, $object->id, 0, 0);
1475
1476 foreach ($task_array as $task) {
1477 $tasksToAffect = new Task($db);
1478 $result = $tasksToAffect->fetch($task->id);
1479 if ($result > 0) {
1480 $res = $tasksToAffect->add_contact($usertoaffect, $tasksrole, 'internal');
1481 if ($res < 0) {
1482 setEventMessages($tasksToAffect->error, $tasksToAffect->errors, 'errors');
1483 }
1484 }
1485 }
1486 $nbok++;
1487 } else {
1488 setEventMessages($object->error, $object->errors, 'errors');
1489 }
1490 } else {
1491 setEventMessages($object->error, $object->errors, 'errors');
1492 $error++;
1493 break;
1494 }
1495 }
1496 } else {
1497 setEventMessage('UserNotFound', 'errors');
1498 $error++;
1499 }
1500
1501 if (!$error) {
1502 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1503 $db->commit();
1504 $toselect = array();
1505 } else {
1506 $db->rollback();
1507 }
1508}
1509
1510if (!$error && ($massaction == 'enable' || ($action == 'enable' && $confirm == 'yes')) && $permissiontoadd) {
1511 $db->begin();
1512
1513 $objecttmp = new $objectclass($db);
1514 $nbok = 0;
1515 foreach ($toselect as $toselectid) {
1516 $result = $objecttmp->fetch($toselectid);
1517 if ($result > 0) {
1518 if (in_array($objecttmp->element, array('societe'))) {
1519 $result = $objecttmp->setStatut(1);
1520 }
1521 if ($result <= 0) {
1522 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1523 $error++;
1524 break;
1525 } else {
1526 $nbok++;
1527 }
1528 } else {
1529 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1530 $error++;
1531 break;
1532 }
1533 }
1534
1535 if (!$error) {
1536 if ($nbok > 1) {
1537 setEventMessages($langs->trans("RecordsEnabled", $nbok), null, 'mesgs');
1538 } else {
1539 setEventMessages($langs->trans("RecordEnabled"), null, 'mesgs');
1540 }
1541 $db->commit();
1542 } else {
1543 $db->rollback();
1544 }
1545}
1546
1547if (!$error && ($massaction == 'disable' || ($action == 'disable' && $confirm == 'yes')) && $permissiontoadd) {
1548 $db->begin();
1549
1550 $objecttmp = new $objectclass($db);
1551 $nbok = 0;
1552 foreach ($toselect as $toselectid) {
1553 $result = $objecttmp->fetch($toselectid);
1554 if ($result > 0) {
1555 if (in_array($objecttmp->element, array('societe'))) {
1556 $result = $objecttmp->setStatut(0);
1557 }
1558 if ($result <= 0) {
1559 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1560 $error++;
1561 break;
1562 } else {
1563 $nbok++;
1564 }
1565 } else {
1566 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1567 $error++;
1568 break;
1569 }
1570 }
1571
1572 if (!$error) {
1573 if ($nbok > 1) {
1574 setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
1575 } else {
1576 setEventMessages($langs->trans("RecordDisabled"), null, 'mesgs');
1577 }
1578 $db->commit();
1579 } else {
1580 $db->rollback();
1581 }
1582}
1583
1584if (!$error && $action == 'confirm_edit_value_extrafields' && $confirm == 'yes' && $permissiontoadd) {
1585 $db->begin();
1586
1587 $objecttmp = new $objectclass($db);
1588 $e = new ExtraFields($db);// fetch optionals attributes and labels
1589 $e->fetch_name_optionals_label($objecttmp->table_element);
1590
1591 $nbok = 0;
1592 $extrafieldKeyToUpdate = GETPOST('extrafield-key-to-update');
1593
1594
1595 foreach ($toselect as $toselectid) {
1597 $objecttmp = new $objectclass($db); // to avoid ghost data
1598 $result = $objecttmp->fetch($toselectid);
1599 if ($result > 0) {
1600 // Fill array 'array_options' with data from add form
1601 $ret = $e->setOptionalsFromPost(null, $objecttmp, $extrafieldKeyToUpdate);
1602 if ($ret > 0) {
1603 $objecttmp->insertExtraFields();
1604 } else {
1605 $error++;
1606 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1607 }
1608 } else {
1609 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1610 $error++;
1611 break;
1612 }
1613 }
1614
1615 if (!$error) {
1616 if ($nbok > 1) {
1617 setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
1618 } else {
1619 setEventMessages($langs->trans("save"), null, 'mesgs');
1620 }
1621 $db->commit();
1622 } else {
1623 $db->rollback();
1624 }
1625}
1626
1627if (!$error && ($massaction == 'assignsalerepresentative' || ($action == 'assignsalerepresentative' && $confirm == 'yes')) && $permissiontoadd) {
1628 $db->begin();
1629
1630 $objecttmp = new $objectclass($db);
1631 $nbok = 0;
1632
1633 foreach ($toselect as $toselectid) {
1634 $result = $objecttmp->fetch($toselectid);
1635 if ($result > 0) {
1636 if (in_array($objecttmp->element, array('societe'))) {
1637 $result = $objecttmp->setSalesRep(GETPOST("commercial", "alpha"));
1638 }
1639 if ($result <= 0) {
1640 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1641 $error++;
1642 break;
1643 } else {
1644 $nbok++;
1645 }
1646 } else {
1647 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1648 $error++;
1649 break;
1650 }
1651 }
1652
1653 if (!$error) {
1654 if ($nbok > 1) {
1655 setEventMessages($langs->trans("CommercialsAffected", $nbok), null, 'mesgs');
1656 } else {
1657 setEventMessages($langs->trans("CommercialAffected"), null, 'mesgs');
1658 }
1659 $db->commit();
1660 } else {
1661 $db->rollback();
1662 }
1663}
1664
1665if (!$error && ($massaction == 'unassigncommercial' || ($action == 'unassigncommercial' && $confirm == 'yes')) && $permissiontoadd) {
1666 $db->begin();
1667
1668 $objecttmp = new $objectclass($db);
1669 $nbok = 0;
1670
1671 foreach ($toselect as $toselectid) {
1672 $result = $objecttmp->fetch($toselectid);
1673 if ($result > 0) {
1674 if (in_array($objecttmp->element, array('societe'))) {
1675 $TCommercial = GETPOST("commercial", "alpha");
1676 if (is_array($TCommercial)) {
1677 foreach ($TCommercial as $commercial) {
1678 $result = $objecttmp->del_commercial($user, $commercial);
1679 }
1680 }
1681 }
1682 if ($result <= 0) {
1683 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1684 $error++;
1685 break;
1686 } else {
1687 $nbok++;
1688 }
1689 } else {
1690 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1691 $error++;
1692 break;
1693 }
1694 }
1695
1696 if (!$error) {
1697 if ($nbok > 1) {
1698 setEventMessages($langs->trans("CommercialsDisaffected", $nbok), null, 'mesgs');
1699 } else {
1700 setEventMessages($langs->trans("CommercialDisaffected"), null, 'mesgs');
1701 }
1702 $db->commit();
1703 } else {
1704 $db->rollback();
1705 }
1706}
1707// Approve for leave only
1708if (!$error && ($massaction == 'approveleave' || ($action == 'approveleave' && $confirm == 'yes')) && $permissiontoapprove) {
1709 $db->begin();
1710
1711 $objecttmp = new $objectclass($db);
1712 '@phan-var-force Holiday $objecttmp';
1713 $nbok = 0;
1714 foreach ($toselect as $toselectid) {
1715 $result = $objecttmp->fetch($toselectid);
1716 if ($result > 0) {
1717 if ($objecttmp->status != Holiday::STATUS_VALIDATED) {
1718 setEventMessages($langs->trans('StatusOfRefMustBe', $objecttmp->ref, $langs->transnoentitiesnoconv('Validated')), null, 'warnings');
1719 continue;
1720 }
1721 if ($user->id == $objecttmp->fk_validator) {
1722 $objecttmp->oldcopy = dol_clone($objecttmp, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
1723
1724 $objecttmp->date_valid = dol_now();
1725 $objecttmp->fk_user_valid = $user->id;
1726 $objecttmp->date_approval = dol_now();
1727 $objecttmp->fk_user_approve = $user->id;
1728 $objecttmp->status = Holiday::STATUS_APPROVED;
1729 $objecttmp->statut = $objecttmp->status; // deprecated
1730
1731 $verif = $objecttmp->approve($user);
1732
1733 if ($verif <= 0) {
1734 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1735 $error++;
1736 }
1737
1738 // If no SQL error, we redirect to the request form
1739 if (!$error) {
1740 // Calculate number of days consumed
1741 $nbopenedday = num_open_day($objecttmp->date_debut_gmt, $objecttmp->date_fin_gmt, 0, 1, $objecttmp->halfday);
1742 $soldeActuel = $objecttmp->getCpforUser($objecttmp->fk_user, $objecttmp->fk_type);
1743 $newSolde = ($soldeActuel - $nbopenedday);
1744
1745 // The modification is added to the LOG
1746 $result = $objecttmp->addLogCP($user->id, $objecttmp->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $objecttmp->fk_type);
1747 if ($result < 0) {
1748 $error++;
1749 setEventMessages(null, $objecttmp->errors, 'errors');
1750 }
1751
1752 // Update balance
1753 $result = $objecttmp->updateSoldeCP($objecttmp->fk_user, $newSolde, $objecttmp->fk_type);
1754 if ($result < 0) {
1755 $error++;
1756 setEventMessages(null, $objecttmp->errors, 'errors');
1757 }
1758 }
1759
1760 if (!$error) {
1761 // To
1762 $destinataire = new User($db);
1763 $destinataire->fetch($objecttmp->fk_user);
1764 $emailTo = $destinataire->email;
1765
1766 if (!$emailTo) {
1767 dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email");
1768 } else {
1769 // From
1770 $expediteur = new User($db);
1771 $expediteur->fetch($objecttmp->fk_validator);
1772 //$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
1773 $emailFrom = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
1774
1775 // Subject
1776 $societeName = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
1777 if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
1778 $societeName = getDolGlobalString('MAIN_APPLICATION_TITLE');
1779 }
1780
1781 $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysValidated");
1782
1783 // Content
1784 $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n";
1785 $message .= "\n";
1786
1787 $message .= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($objecttmp->date_debut, 'day'), dol_print_date($objecttmp->date_fin, 'day'))."\n";
1788
1789 $message .= "- ".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n";
1790
1791 $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$objecttmp->id."\n\n";
1792 $message .= "\n";
1793
1794 $trackid = 'leav'.$objecttmp->id;
1795
1796 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1797 $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid);
1798
1799 // Sending email
1800 $result = $mail->sendfile();
1801
1802 if (!$result) {
1803 setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1
1804 $action = '';
1805 }
1806 }
1807 }
1808 } else {
1809 $langs->load("errors");
1810 setEventMessages($langs->trans('ErrorNotApproverForHoliday', $objecttmp->ref), null, 'errors');
1811 }
1812 } else {
1813 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1814 $error++;
1815 break;
1816 }
1817 }
1818
1819 if (!$error) {
1820 if ($nbok > 1) {
1821 setEventMessages($langs->trans("RecordsApproved", $nbok), null, 'mesgs');
1822 } elseif ($nbok == 1) {
1823 setEventMessages($langs->trans("RecordAproved"), null, 'mesgs');
1824 }
1825 $db->commit();
1826 } else {
1827 $db->rollback();
1828 }
1829}
1830
1831if (!$error && ($massaction == 'increaseholiday' || ($action == 'increaseholiday' && $confirm == 'yes')) && $permissiontoapprove && is_array($toselect)) {
1832 '@phan-var-force Holiday $holiday'; // Supposing that $holiday is set, it is needed.
1833 $db->begin();
1834 $objecttmp = new $objectclass($db);
1835 $nbok = 0;
1836 $typeholiday = GETPOSTINT('typeholiday');
1837 $nbdaysholidays = GETPOSTFLOAT('nbdaysholidays'); // May be 1.5
1838
1839 if ($nbdaysholidays <= 0) {
1840 setEventMessages($langs->trans("WrongAmount"), null, 'errors');
1841 $error++;
1842 }
1843
1844 if (!$error) {
1845 foreach ($toselect as $toselectid) {
1846 $balancecpuser = $objecttmp->getCPforUser($toselectid, $typeholiday);
1847 if (!empty($balancecpuser)) {
1848 $newnbdaysholidays = $nbdaysholidays + $balancecpuser;
1849 } else {
1850 $newnbdaysholidays = $nbdaysholidays;
1851 }
1852 $result = $holiday->addLogCP($user->id, $toselectid, $langs->transnoentitiesnoconv('ManualUpdate'), $newnbdaysholidays, $typeholiday);
1853 if ($result <= 0) {
1854 setEventMessages($holiday->error, $holiday->errors, 'errors');
1855 $error++;
1856 break;
1857 }
1858
1859 $objecttmp->updateSoldeCP($toselectid, $newnbdaysholidays, $typeholiday);
1860 if ($result > 0) {
1861 $nbok++;
1862 } else {
1863 setEventMessages($langs->trans("ErrorUpdatingUsersCP"), null, 'errors');
1864 $error++;
1865 break;
1866 }
1867 }
1868 }
1869
1870 if (!$error) {
1871 if ($nbok > 1) {
1872 setEventMessages($langs->trans("HolidayRecordsIncreased", $nbok), null, 'mesgs');
1873 } elseif ($nbok == 1) {
1874 setEventMessages($langs->trans("HolidayRecordIncreased"), null, 'mesgs');
1875 }
1876 $db->commit();
1877 $toselect = array();
1878 } else {
1879 $db->rollback();
1880 }
1881}
1882
1883
1884if (!$error && ($massaction == 'clonetasks' || ($action == 'clonetasks' && $confirm == 'yes'))) { // Test on permission not required here, done later
1885 $num = 0;
1886
1887 include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
1888
1889 $origin_task = new Task($db);
1890 $clone_task = new Task($db);
1891 $newproject = new Project($db);
1892 $newproject->fetch(GETPOSTINT('projectid'));
1893
1894 // Check if current user is contact of the new project (necessary only if project is not public)
1895 $iscontactofnewproject = 0;
1896 if (empty($newproject->public)) {
1897 $tmps = $newproject->getProjectsAuthorizedForUser($user, 0, 1, 0, '(fk_statut:=:1)'); // We check only open project (cloning on closed is not allowed)
1898 $tmparray = explode(',', $tmps);
1899 if (!in_array($newproject->id, $tmparray)) {
1900 $iscontactofnewproject = 1;
1901 }
1902 }
1903
1904 // Check permission on new project
1905 $permisstiontoadd = false;
1906 if ($user->hasRight('project', 'all', 'creer') || ($user->hasRight('project', 'creer') && ($newproject->public || $iscontactofnewproject))) {
1907 $permisstiontoadd = true;
1908 }
1909
1910 if ($permisstiontoadd) {
1911 foreach (GETPOST('selected') as $task) {
1912 $origin_task->fetch($task, '', 0);
1913
1914 $defaultref = '';
1915 $classnamemodtask = getDolGlobalString('PROJECT_TASK_ADDON', 'mod_task_simple');
1916 if (getDolGlobalString('PROJECT_TASK_ADDON') && is_readable(DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . getDolGlobalString('PROJECT_TASK_ADDON') . ".php")) {
1917 require_once DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . getDolGlobalString('PROJECT_TASK_ADDON') . '.php';
1918 $modTask = new $classnamemodtask();
1919 '@phan-var-force ModeleNumRefTask $modTask';
1920 $defaultref = $modTask->getNextValue(null, $clone_task);
1921 }
1922
1923 if (!$error) {
1924 $clone_task->fk_project = GETPOSTINT('projectid');
1925 $clone_task->ref = $defaultref;
1926 $clone_task->label = $origin_task->label;
1927 $clone_task->description = $origin_task->description;
1928 $clone_task->planned_workload = $origin_task->planned_workload;
1929 $clone_task->fk_task_parent = $origin_task->fk_task_parent;
1930 $clone_task->date_c = dol_now();
1931 $clone_task->date_start = $origin_task->date_start;
1932 $clone_task->date_end = $origin_task->date_end;
1933 $clone_task->progress = $origin_task->progress;
1934
1935 // Fill array 'array_options' with data from add form
1936 $ret = $extrafields->setOptionalsFromPost(null, $clone_task);
1937
1938 $taskid = $clone_task->create($user);
1939
1940 if ($taskid > 0) {
1941 $result = $clone_task->add_contact(GETPOSTINT("userid"), 'TASKEXECUTIVE', 'internal');
1942 $num++;
1943 } else {
1944 if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1945 $langs->load("projects");
1946 setEventMessages($langs->trans('NewTaskRefSuggested'), null, 'warnings');
1947 $duplicate_code_error = true;
1948 } else {
1949 setEventMessages($clone_task->error, $clone_task->errors, 'errors');
1950 }
1951 $action = 'list';
1952 $error++;
1953 }
1954 }
1955 }
1956
1957 if (!$error) {
1958 setEventMessages($langs->trans('NumberOfTasksCloned', $num), null, 'mesgs');
1959 header("Location: ".DOL_URL_ROOT.'/projet/tasks.php?id='.GETPOSTINT('projectid'));
1960 exit();
1961 }
1962 } else {
1963 setEventMessages($langs->trans('NotEnoughPermissions'), null, 'errors');
1964 }
1965}
1966
1967if (empty($toselect)) {
1968 $toselect = [];
1969}
1970$parameters['toselect'] = &$toselect;
1971$parameters['uploaddir'] = $uploaddir;
1972$parameters['massaction'] = $massaction;
1973$parameters['diroutputmassaction'] = isset($diroutputmassaction) ? $diroutputmassaction : null;
1974
1975// @phan-suppress-next-line PhanTypeMismatchArgumentNullable
1976$reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1977if ($reshook < 0) {
1978 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1979}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
global $dolibarr_main_url_root
$object ref
Definition info.php:90
Class to manage members of a foundation.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage categories.
Class to manage customers orders.
const STATUS_DRAFT
Draft status.
const STATUS_VALIDATED
Validated status.
Class for ConferenceOrBoothAttendee.
Class to manage contact/addresses.
Class to manage standard extra fields.
const STATUS_DRAFT
Draft status.
const STATUS_VALIDATED
Validated (need to be paid)
const STATUS_VALIDATED
Validated status.
const STATUS_DRAFT
Draft status.
const STATUS_REFUSED
Refused.
const STATUS_CANCELED
Canceled.
const STATUS_APPROVED
Approved.
Class to manage projects.
const STATUS_DRAFT
Draft status.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage tasks.
Class to manage translations.
Class to manage Dolibarr users.
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $country_code='')
Function to return number of working days (and text of units) between two dates (working days)
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:63
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)
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
GETPOSTFLOAT($paramname, $rounding='')
Return the value of a $_GET or $_POST supervariable, converted into float.
dol_clone($object, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0)
Clean a string to use it as a file name.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
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)
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
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:266
pdf_getInstance($format='', $metric='mm', $pagetype='P')
Return a PDF instance object.
Definition pdf.lib.php:129
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.