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