dolibarr 18.0.8
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 = (empty($conf->global->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 (!empty($conf->global->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 = $conf->global->MAIN_INFO_SOCIETE_NOM.' <'.$conf->global->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(',', $conf->global->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 .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
434 }
435 if ($objectclass == 'Commande') {
436 $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
437 }
438 if ($objectclass == 'Facture') {
439 $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
440 }
441 if ($objectclass == 'Supplier_Proposal') {
442 $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
443 }
444 if ($objectclass == 'CommandeFournisseur') {
445 $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
446 }
447 if ($objectclass == 'FactureFournisseur') {
448 $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
449 }
450 if ($objectclass == 'Project') {
451 $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->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) == 'Supplier_Proposal') {
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 == 'Supplier_Proposal') $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 (!empty($conf->global->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 (!empty($conf->global->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 = $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 (!empty($conf->global->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') && !empty($conf->global->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') && !empty($conf->global->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) && !empty($conf->global->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 (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
993 $outputlangs = $langs;
994 $newlang = '';
995 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
996 $newlang = GETPOST('lang_id', 'aZ09');
997 }
998 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && property_exists($objecttmp, 'thirdparty')) {
999 if ((property_exists($objecttmp, 'socid') || property_exists($objecttmp, 'fk_soc')) && empty($objecttmp->thirdparty)) {
1000 $objecttmp->fetch_thirdparty();
1001 }
1002 if (!empty($objecttmp->thirdparty)) {
1003 $newlang = $objecttmp->thirdparty->default_lang;
1004 }
1005 }
1006 if (!empty($newlang)) {
1007 $outputlangs = new Translate("", $conf);
1008 $outputlangs->setDefaultLang($newlang);
1009 $outputlangs->load('products');
1010 }
1011 $model = $objecttmp->model_pdf;
1012 $ret = $objecttmp->fetch($objecttmp->id); // Reload to get new records
1013 // To be sure vars is defined
1014 $hidedetails = isset($hidedetails) ? $hidedetails : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
1015 $hidedesc = isset($hidedesc) ? $hidedesc : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
1016 $hideref = isset($hideref) ? $hideref : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
1017 $moreparams = isset($moreparams) ? $moreparams : null;
1018
1019 $result = $objecttmp->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1020 if ($result < 0) {
1021 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1022 }
1023 }
1024 $nbok++;
1025 }
1026 } else {
1027 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1028 $error++;
1029 break;
1030 }
1031 }
1032
1033 if (!$error) {
1034 if ($nbok > 1) {
1035 setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1036 } else {
1037 setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
1038 }
1039 $db->commit();
1040 } else {
1041 $db->rollback();
1042 }
1043 //var_dump($listofobjectthirdparties);exit;
1044 }
1045}
1046
1047//var_dump($_POST);var_dump($massaction);exit;
1048
1049// Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
1050if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) {
1051 $db->begin();
1052
1053 $objecttmp = new $objectclass($db);
1054 $nbok = 0;
1055 $TMsg = array();
1056
1057 //$toselect could contain duplicate entries, cf https://github.com/Dolibarr/dolibarr/issues/26244
1058 $unique_arr = array_unique($toselect);
1059 foreach ($unique_arr as $toselectid) {
1060 $result = $objecttmp->fetch($toselectid);
1061 if ($result > 0) {
1062 // Refuse deletion for some objects/status
1063 if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT) {
1064 $langs->load("errors");
1065 $nbignored++;
1066 $TMsg[] = '<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'</div><br>';
1067 continue;
1068 }
1069
1070 if (method_exists($objecttmp, 'is_erasable') && $objecttmp->is_erasable() <= 0) {
1071 $langs->load("errors");
1072 $nbignored++;
1073 $TMsg[] = '<div class="error">'.$langs->trans('ErrorRecordHasChildren').' '.$objecttmp->ref.'</div><br>';
1074 continue;
1075 }
1076
1077 if ($objectclass == 'Holiday' && ! in_array($objecttmp->statut, array(Holiday::STATUS_DRAFT, Holiday::STATUS_CANCELED, Holiday::STATUS_REFUSED))) {
1078 $langs->load("errors");
1079 $nbignored++;
1080 $TMsg[] = '<div class="error">'.$langs->trans('ErrorLeaveRequestMustBeDraftCanceledOrRefusedToBeDeleted', $objecttmp->ref).'</div><br>';
1081 continue;
1082 }
1083
1084 if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) {
1085 $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".((int) $objecttmp->id);
1086 $res = $db->query($sql);
1087
1088 if (!$res) {
1089 setEventMessage('ErrorRecordParentingNotModified', 'errors');
1090 $error++;
1091 }
1092 }
1093
1094 if (in_array($objecttmp->element, array('societe', 'member'))) {
1095 $result = $objecttmp->delete($objecttmp->id, $user, 1);
1096 } elseif (in_array($objecttmp->element, array('action'))) {
1097 $result = $objecttmp->delete();
1098 } else {
1099 $result = $objecttmp->delete($user);
1100 }
1101
1102 if (empty($result)) { // if delete returns 0, there is at least one object linked
1103 $TMsg = array_merge($objecttmp->errors, $TMsg);
1104 } elseif ($result < 0) { // if delete returns is < 0, there is an error, we break and rollback later
1105 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1106 $error++;
1107 break;
1108 } else {
1109 $nbok++;
1110 }
1111 } else {
1112 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1113 $error++;
1114 break;
1115 }
1116 }
1117
1118 if (empty($error)) {
1119 // Message for elements well deleted
1120 if ($nbok > 1) {
1121 setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1122 } elseif ($nbok > 0) {
1123 setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1124 } else {
1125 setEventMessages($langs->trans("NoRecordDeleted"), null, 'mesgs');
1126 }
1127
1128 // Message for elements which can't be deleted
1129 if (!empty($TMsg)) {
1130 sort($TMsg);
1131 setEventMessages('', array_unique($TMsg), 'warnings');
1132 }
1133
1134 $db->commit();
1135 } else {
1136 $db->rollback();
1137 }
1138
1139 //var_dump($listofobjectthirdparties);exit;
1140}
1141
1142// Generate document foreach object according to model linked to object
1143// @todo : propose model selection
1144if (!$error && $massaction == 'generate_doc' && $permissiontoread) {
1145 $db->begin();
1146 $objecttmp = new $objectclass($db);
1147 $nbok = 0;
1148 foreach ($toselect as $toselectid) {
1149 $objecttmp->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
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 (getDolGlobalInt('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 ($obj->price_base_type == 'TTC') {
1279 $newprice = $object->price_ttc * (100 + $pricepercentage) / 100;
1280 $minprice = $object->price_min_ttc;
1281 } else {
1282 $newprice = $object->price * (100 + $pricepercentage) / 100;
1283 $minprice = $object->price_min;
1284 }
1285 $res = $object->updatePrice($newprice, $obj->price_base_type, $user, $object->tva_tx, $minprice, 0, $object->tva_npr, 0, 0, array(), $object->default_vat_code);
1286 if ($res > 0) {
1287 $nbok++;
1288 } else {
1289 setEventMessages($object->error, $object->errors, 'errors');
1290 }
1291 } else {
1292 setEventMessages($object->error, $object->errors, 'errors');
1293 $error++;
1294 break;
1295 }
1296 }
1297 }
1298 }
1299
1300 if (!$error) {
1301 if ($nbok > 0) {
1302 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1303 }
1304 $db->commit();
1305 $toselect=array();
1306 } else {
1307 $db->rollback();
1308 }
1309}
1310
1311if (!$error && ($action == 'setsupervisor' && $confirm == 'yes') && $permissiontoadd) {
1312 $db->begin();
1313 $supervisortoset=GETPOST('supervisortoset');
1314 if (!empty($supervisortoset)) {
1315 foreach ($toselect as $toselectid) {
1316 $result = $object->fetch($toselectid);
1317 //var_dump($contcats);exit;
1318 if ($result > 0) {
1319 $object->fk_user = $supervisortoset;
1320 $res = $object->update($user);
1321 if ($res > 0) {
1322 $nbok++;
1323 } else {
1324 setEventMessages($object->error, $object->errors, 'errors');
1325 }
1326 } else {
1327 setEventMessages($object->error, $object->errors, 'errors');
1328 $error++;
1329 break;
1330 }
1331 }
1332 } else {
1333 setEventMessage('UserNotFound', 'errors');
1334 $error++;
1335 }
1336
1337 if (!$error) {
1338 if ($nbok > 1) {
1339 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1340 } else {
1341 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1342 }
1343 $db->commit();
1344 $toselect=array();
1345 } else {
1346 $db->rollback();
1347 }
1348}
1349
1350if (!$error && ($action == 'affectuser' && $confirm == 'yes') && $permissiontoadd) {
1351 $db->begin();
1352
1353 $usertoaffect=GETPOST('usertoaffect');
1354 $projectrole=GETPOST('projectrole');
1355 $tasksrole=GETPOST('tasksrole');
1356 if (!empty($usertoaffect)) {
1357 foreach ($toselect as $toselectid) {
1358 $result = $object->fetch($toselectid);
1359 //var_dump($contcats);exit;
1360 if ($result > 0) {
1361 $res = $object->add_contact($usertoaffect, $projectrole, 'internal');
1362 if ($res >= 0) {
1363 $taskstatic = new Task($db);
1364 $task_array = $taskstatic->getTasksArray(0, 0, $object->id, 0, 0);
1365
1366 foreach ($task_array as $task) {
1367 $tasksToAffect = new Task($db);
1368 $result = $tasksToAffect->fetch($task->id);
1369 if ($result > 0) {
1370 $res = $tasksToAffect->add_contact($usertoaffect, $tasksrole, 'internal');
1371 if ($res < 0) {
1372 setEventMessages($tasksToAffect->error, $tasksToAffect->errors, 'errors');
1373 }
1374 }
1375 }
1376 $nbok++;
1377 } else {
1378 setEventMessages($object->error, $object->errors, 'errors');
1379 }
1380 } else {
1381 setEventMessages($object->error, $object->errors, 'errors');
1382 $error++;
1383 break;
1384 }
1385 }
1386 } else {
1387 setEventMessage('UserNotFound', 'errors');
1388 $error++;
1389 }
1390
1391 if (!$error) {
1392 if ($nbok > 1) {
1393 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1394 } else {
1395 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1396 }
1397 $db->commit();
1398 $toselect=array();
1399 } else {
1400 $db->rollback();
1401 }
1402}
1403
1404if (!$error && ($massaction == 'enable' || ($action == 'enable' && $confirm == 'yes')) && $permissiontoadd) {
1405 $db->begin();
1406
1407 $objecttmp = new $objectclass($db);
1408 $nbok = 0;
1409 foreach ($toselect as $toselectid) {
1410 $result = $objecttmp->fetch($toselectid);
1411 if ($result>0) {
1412 if (in_array($objecttmp->element, array('societe'))) {
1413 $result =$objecttmp->setStatut(1);
1414 }
1415 if ($result <= 0) {
1416 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1417 $error++;
1418 break;
1419 } else {
1420 $nbok++;
1421 }
1422 } else {
1423 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1424 $error++;
1425 break;
1426 }
1427 }
1428
1429 if (!$error) {
1430 if ($nbok > 1) {
1431 setEventMessages($langs->trans("RecordsEnabled", $nbok), null, 'mesgs');
1432 } else {
1433 setEventMessages($langs->trans("RecordEnabled"), null, 'mesgs');
1434 }
1435 $db->commit();
1436 } else {
1437 $db->rollback();
1438 }
1439}
1440
1441if (!$error && ($massaction == 'disable' || ($action == 'disable' && $confirm == 'yes')) && $permissiontoadd) {
1442 $db->begin();
1443
1444 $objecttmp = new $objectclass($db);
1445 $nbok = 0;
1446 foreach ($toselect as $toselectid) {
1447 $result = $objecttmp->fetch($toselectid);
1448 if ($result>0) {
1449 if (in_array($objecttmp->element, array('societe'))) {
1450 $result =$objecttmp->setStatut(0);
1451 }
1452 if ($result <= 0) {
1453 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1454 $error++;
1455 break;
1456 } else {
1457 $nbok++;
1458 }
1459 } else {
1460 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1461 $error++;
1462 break;
1463 }
1464 }
1465
1466 if (!$error) {
1467 if ($nbok > 1) {
1468 setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
1469 } else {
1470 setEventMessages($langs->trans("RecordDisabled"), null, 'mesgs');
1471 }
1472 $db->commit();
1473 } else {
1474 $db->rollback();
1475 }
1476}
1477
1478if (!$error && $action == 'confirm_edit_value_extrafields' && $confirm == 'yes' && $permissiontoadd) {
1479 $db->begin();
1480
1481 $objecttmp = new $objectclass($db);
1482 $e = new ExtraFields($db);// fetch optionals attributes and labels
1483 $e->fetch_name_optionals_label($objecttmp->table_element);
1484
1485 $nbok = 0;
1486 $extrafieldKeyToUpdate = GETPOST('extrafield-key-to-update');
1487
1488
1489 foreach ($toselect as $toselectid) {
1491 $objecttmp = new $objectclass($db); // to avoid ghost data
1492 $result = $objecttmp->fetch($toselectid);
1493 if ($result>0) {
1494 // Fill array 'array_options' with data from add form
1495 $ret = $e->setOptionalsFromPost(null, $objecttmp, $extrafieldKeyToUpdate);
1496 if ($ret > 0) {
1497 $objecttmp->insertExtraFields();
1498 } else {
1499 $error++;
1500 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1501 }
1502 } else {
1503 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1504 $error++;
1505 break;
1506 }
1507 }
1508
1509 if (!$error) {
1510 if ($nbok > 1) {
1511 setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
1512 } else {
1513 setEventMessages($langs->trans("save"), null, 'mesgs');
1514 }
1515 $db->commit();
1516 } else {
1517 $db->rollback();
1518 }
1519}
1520
1521if (!$error && ($massaction == 'affectcommercial' || ($action == 'affectcommercial' && $confirm == 'yes')) && $permissiontoadd) {
1522 $db->begin();
1523
1524 $objecttmp = new $objectclass($db);
1525 $nbok = 0;
1526
1527 foreach ($toselect as $toselectid) {
1528 $result = $objecttmp->fetch($toselectid);
1529 if ($result>0) {
1530 if (in_array($objecttmp->element, array('societe'))) {
1531 $result = $objecttmp->setSalesRep(GETPOST("commercial", "alpha"));
1532 }
1533 if ($result <= 0) {
1534 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1535 $error++;
1536 break;
1537 } else {
1538 $nbok++;
1539 }
1540 } else {
1541 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1542 $error++;
1543 break;
1544 }
1545 }
1546
1547 if (!$error) {
1548 if ($nbok > 1) {
1549 setEventMessages($langs->trans("CommercialsAffected", $nbok), null, 'mesgs');
1550 } else {
1551 setEventMessages($langs->trans("CommercialAffected"), null, 'mesgs');
1552 }
1553 $db->commit();
1554 } else {
1555 $db->rollback();
1556 }
1557}
1558
1559// Approve for leave only
1560if (!$error && ($massaction == 'approveleave' || ($action == 'approveleave' && $confirm == 'yes')) && $permissiontoapprove) {
1561 $db->begin();
1562
1563 $objecttmp = new $objectclass($db);
1564 $nbok = 0;
1565 foreach ($toselect as $toselectid) {
1566 $result = $objecttmp->fetch($toselectid);
1567 if ($result > 0) {
1568 if ($objecttmp->statut != Holiday::STATUS_VALIDATED) {
1569 setEventMessages($langs->trans('StatusOfRefMustBe', $objecttmp->ref, $langs->transnoentitiesnoconv('Validated')), null, 'warnings');
1570 continue;
1571 }
1572 if ($user->id == $objecttmp->fk_validator) {
1573 $objecttmp->oldcopy = dol_clone($objecttmp);
1574
1575 $objecttmp->date_valid = dol_now();
1576 $objecttmp->fk_user_valid = $user->id;
1577 $objecttmp->statut = Holiday::STATUS_APPROVED;
1578
1579 $verif = $objecttmp->approve($user);
1580
1581 if ($verif <= 0) {
1582 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1583 $error++;
1584 }
1585
1586 // If no SQL error, we redirect to the request form
1587 if (!$error) {
1588 // Calculcate number of days consumed
1589 $nbopenedday = num_open_day($objecttmp->date_debut_gmt, $objecttmp->date_fin_gmt, 0, 1, $objecttmp->halfday);
1590 $soldeActuel = $objecttmp->getCpforUser($objecttmp->fk_user, $objecttmp->fk_type);
1591 $newSolde = ($soldeActuel - $nbopenedday);
1592
1593 // The modification is added to the LOG
1594 $result = $objecttmp->addLogCP($user->id, $objecttmp->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $objecttmp->fk_type);
1595 if ($result < 0) {
1596 $error++;
1597 setEventMessages(null, $objecttmp->errors, 'errors');
1598 }
1599
1600 // Update balance
1601 $result = $objecttmp->updateSoldeCP($objecttmp->fk_user, $newSolde, $objecttmp->fk_type);
1602 if ($result < 0) {
1603 $error++;
1604 setEventMessages(null, $objecttmp->errors, 'errors');
1605 }
1606 }
1607
1608 if (!$error) {
1609 // To
1610 $destinataire = new User($db);
1611 $destinataire->fetch($objecttmp->fk_user);
1612 $emailTo = $destinataire->email;
1613
1614 if (!$emailTo) {
1615 dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email");
1616 } else {
1617 // From
1618 $expediteur = new User($db);
1619 $expediteur->fetch($objecttmp->fk_validator);
1620 //$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
1621 $emailFrom = $conf->global->MAIN_MAIL_EMAIL_FROM;
1622
1623 // Subject
1624 $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
1625 if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
1626 $societeName = $conf->global->MAIN_APPLICATION_TITLE;
1627 }
1628
1629 $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysValidated");
1630
1631 // Content
1632 $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n";
1633 $message .= "\n";
1634
1635 $message .= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($objecttmp->date_debut, 'day'), dol_print_date($objecttmp->date_fin, 'day'))."\n";
1636
1637 $message .= "- ".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n";
1638
1639 $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$objecttmp->id."\n\n";
1640 $message .= "\n";
1641
1642 $trackid = 'leav'.$objecttmp->id;
1643
1644 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1645 $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid);
1646
1647 // Sending email
1648 $result = $mail->sendfile();
1649
1650 if (!$result) {
1651 setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1
1652 $action = '';
1653 }
1654 }
1655 }
1656 } else {
1657 $langs->load("errors");
1658 setEventMessages($langs->trans('ErrorNotApproverForHoliday', $objecttmp->ref), null, 'errors');
1659 }
1660 } else {
1661 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1662 $error++;
1663 break;
1664 }
1665 }
1666
1667 if (!$error) {
1668 if ($nbok > 1) {
1669 setEventMessages($langs->trans("RecordsApproved", $nbok), null, 'mesgs');
1670 } elseif ($nbok == 1) {
1671 setEventMessages($langs->trans("RecordAproved"), null, 'mesgs');
1672 }
1673 $db->commit();
1674 } else {
1675 $db->rollback();
1676 }
1677}
1678
1679if (!$error && ($massaction == 'increaseholiday' || ($action == 'increaseholiday' && $confirm == 'yes')) && $permissiontoapprove) {
1680 $db->begin();
1681 $objecttmp = new $objectclass($db);
1682 $nbok = 0;
1683 $typeholiday = GETPOST('typeholiday', 'alpha');
1684 $nbdaysholidays = GETPOST('nbdaysholidays', 'double');
1685
1686 if ($nbdaysholidays <= 0) {
1687 setEventMessages($langs->trans("WrongAmount"), "", 'errors');
1688 $error++;
1689 }
1690
1691 if (!$error) {
1692 foreach ($toselect as $toselectid) {
1693 $balancecpuser = $objecttmp->getCPforUser($toselectid, $typeholiday);
1694 if (!empty($balancecpuser)) {
1695 $newnbdaysholidays = $nbdaysholidays + $balancecpuser;
1696 } else {
1697 $newnbdaysholidays = $nbdaysholidays;
1698 }
1699 $result = $holiday->addLogCP($user->id, $toselectid, $langs->transnoentitiesnoconv('ManualUpdate'), $newnbdaysholidays, $typeholiday);
1700 if ($result <= 0) {
1701 setEventMessages($holiday->error, $holiday->errors, 'errors');
1702 $error++;
1703 break;
1704 }
1705
1706 $objecttmp->updateSoldeCP($toselectid, $newnbdaysholidays, $typeholiday);
1707 if ($result > 0) {
1708 $nbok++;
1709 } else {
1710 setEventMessages("", $langs->trans("ErrorUpdatingUsersCP"), 'errors');
1711 $error++;
1712 break;
1713 }
1714 }
1715 }
1716
1717 if (!$error) {
1718 if ($nbok > 1) {
1719 setEventMessages($langs->trans("HolidayRecordsIncreased", $nbok), null, 'mesgs');
1720 } elseif ($nbok == 1) {
1721 setEventMessages($langs->trans("HolidayRecordIncreased"), null, 'mesgs');
1722 }
1723 $db->commit();
1724 $toselect=array();
1725 } else {
1726 $db->rollback();
1727 }
1728}
1729
1730//if (!$error && $massaction == 'clonetasks' && $user->rights->projet->creer) {
1731if (!$error && ($massaction == 'clonetasks' || ($action == 'clonetasks' && $confirm == 'yes'))) {
1732 $num = 0;
1733
1734 dol_include_once('/projet/class/task.class.php');
1735
1736 $origin_task = new Task($db);
1737 $clone_task = new Task($db);
1738
1739 foreach (GETPOST('selected') as $task) {
1740 $origin_task->fetch($task, $ref = '', $loadparentdata = 0);
1741
1742 $defaultref = '';
1743 $obj = empty($conf->global->PROJECT_TASK_ADDON) ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON;
1744 if (!empty($conf->global->PROJECT_TASK_ADDON) && is_readable(DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . $conf->global->PROJECT_TASK_ADDON . ".php")) {
1745 require_once DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . $conf->global->PROJECT_TASK_ADDON . '.php';
1746 $modTask = new $obj;
1747 $defaultref = $modTask->getNextValue(0, $clone_task);
1748 }
1749
1750 if (!$error) {
1751 $clone_task->fk_project = GETPOST('projectid', 'int');
1752 $clone_task->ref = $defaultref;
1753 $clone_task->label = $origin_task->label;
1754 $clone_task->description = $origin_task->description;
1755 $clone_task->planned_workload = $origin_task->planned_workload;
1756 $clone_task->fk_task_parent = $origin_task->fk_task_parent;
1757 $clone_task->date_c = dol_now();
1758 $clone_task->date_start = $origin_task->date_start;
1759 $clone_task->date_end = $origin_task->date_end;
1760 $clone_task->progress = $origin_task->progress;
1761
1762 // Fill array 'array_options' with data from add form
1763 $ret = $extrafields->setOptionalsFromPost(null, $clone_task);
1764
1765 $taskid = $clone_task->create($user);
1766
1767 if ($taskid > 0) {
1768 $result = $clone_task->add_contact(GETPOST("userid", 'int'), 'TASKEXECUTIVE', 'internal');
1769 $num++;
1770 } else {
1771 if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1772 $langs->load("projects");
1773 setEventMessages($langs->trans('NewTaskRefSuggested'), '', 'warnings');
1774 $duplicate_code_error = true;
1775 } else {
1776 setEventMessages($clone_task->error, $clone_task->errors, 'errors');
1777 }
1778 $action = 'list';
1779 $error++;
1780 }
1781 }
1782 }
1783
1784 if (!$error) {
1785 setEventMessage($langs->trans('NumberOfTasksCloned', $num));
1786 header("Refresh: 1;URL=".DOL_URL_ROOT.'/projet/tasks.php?id=' . GETPOST('projectid', 'int'));
1787 }
1788}
1789
1790$parameters['toselect'] = (empty($toselect) ? array() : $toselect);
1791$parameters['uploaddir'] = $uploaddir;
1792$parameters['massaction'] = $massaction;
1793$parameters['diroutputmassaction'] = isset($diroutputmassaction) ? $diroutputmassaction : null;
1794
1795$reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1796if ($reshook < 0) {
1797 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1798}
$object ref
Definition info.php:78
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_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 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')
Returns a hash (non reversible encryption) of a string.