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