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