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