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