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