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