dolibarr 19.0.4
actions_massactions.inc.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2015-2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2018-2021 Nicolas ZABOURI <info@inovea-conseil.com>
4 * Copyright (C) 2018 Juanjo Menent <jmenent@2byte.es>
5 * Copyright (C) 2019 Ferran Marcet <fmarcet@2byte.es>
6 * Copyright (C) 2019-2021 Frédéric France <frederic.france@netlogic.fr>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 * or see https://www.gnu.org/
21 */
22
29// $massaction must be defined
30// $objectclass and $objectlabel must be defined
31// $parameters, $object, $action must be defined for the hook.
32
33// $permissiontoread, $permissiontoadd, $permissiontodelete, $permissiontoclose may be defined
34// $uploaddir may be defined (example to $conf->project->dir_output."/";)
35// $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 = (!getDolGlobalString('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 (getDolGlobalString('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 = getDolGlobalString('MAIN_INFO_SOCIETE_NOM') . ' <' . getDolGlobalString('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(',', getDolGlobalString('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 .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROPOSAL_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROPOSAL_TO')));
433 }
434 if ($objectclass == 'Commande') {
435 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_ORDER_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_ORDER_TO')));
436 }
437 if ($objectclass == 'Facture') {
438 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_INVOICE_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_INVOICE_TO')));
439 }
440 if ($objectclass == 'SupplierProposal') {
441 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO')));
442 }
443 if ($objectclass == 'CommandeFournisseur') {
444 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO')));
445 }
446 if ($objectclass == 'FactureFournisseur') {
447 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO')));
448 }
449 if ($objectclass == 'Project') {
450 $sendtobcc .= (!getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROJECT_TO') ? '' : (($sendtobcc ? ", " : "") . getDolGlobalString('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) == 'SupplierProposal') {
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 == 'SupplierProposal') $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 (getDolGlobalString('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 (getDolGlobalString('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 = !empty($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 (getDolGlobalString('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') && getDolGlobalString('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') && getDolGlobalString('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) && getDolGlobalString('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 (!getDolGlobalString('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 : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
1014 $hidedesc = !empty($hidedesc) ? $hidedesc : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
1015 $hideref = !empty($hideref) ? $hideref : (getDolGlobalString('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' && !getDolGlobalString('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(); // TODO Add User $user as first param
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 = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
1174 }
1175 if (empty($hidedesc)) {
1176 $hidedesc = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
1177 }
1178 if (empty($hideref)) {
1179 $hideref = (getDolGlobalString('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 (getDolGlobalString('PRODUCT_PRICE_UNIQ')
1285 || getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
1286 if ($object->price_base_type == 'TTC') {
1287 $newprice = $object->price_ttc * (100 + $pricepercentage) / 100;
1288 $minprice = $object->price_min_ttc;
1289 } else {
1290 $newprice = $object->price * (100 + $pricepercentage) / 100;
1291 $minprice = $object->price_min;
1292 }
1293 $res = $object->updatePrice($newprice, $object->price_base_type, $user, $object->tva_tx, $minprice, 0, $object->tva_npr, 0, 0, array(), $object->default_vat_code);
1294 if ($res > 0) {
1295 $nbok++;
1296 } else {
1297 setEventMessages($object->error, $object->errors, 'errors');
1298 }
1299 } elseif (getDolGlobalString('PRODUIT_MULTIPRICES')) {
1300 for ($level = 1; $level <= getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT'); $level++) {
1301 if ($object->price_base_type == 'TTC') {
1302 $newprice = $object->multiprices_ttc[$level] * (100 + $pricepercentage) / 100;
1303 $minprice = $object->multiprices_min_ttc[$level];
1304 } else {
1305 $newprice = $object->multiprices[$level] * (100 + $pricepercentage) / 100;
1306 $minprice = $object->multiprices_min[$level];
1307 }
1308 $res = $object->updatePrice($newprice, $object->price_base_type, $user, $object->tva_tx, $minprice, $level, $object->tva_npr, 0, 0, array(), $object->default_vat_code);
1309 if ($res > 0) {
1310 $nbok++;
1311 }
1312 }
1313 }
1314 } else {
1315 setEventMessages($object->error, $object->errors, 'errors');
1316 $error++;
1317 break;
1318 }
1319 }
1320 }
1321 }
1322
1323 if (!$error) {
1324 if ($nbok > 0) {
1325 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1326 }
1327 $db->commit();
1328 $toselect=array();
1329 } else {
1330 $db->rollback();
1331 }
1332}
1333
1334if (!$error && ($action == 'setsupervisor' && $confirm == 'yes') && $permissiontoadd) {
1335 $db->begin();
1336 $supervisortoset=GETPOST('supervisortoset');
1337 if (!empty($supervisortoset)) {
1338 foreach ($toselect as $toselectid) {
1339 $result = $object->fetch($toselectid);
1340 //var_dump($contcats);exit;
1341 if ($result > 0) {
1342 $object->fk_user = $supervisortoset;
1343 $res = $object->update($user);
1344 if ($res > 0) {
1345 $nbok++;
1346 } else {
1347 setEventMessages($object->error, $object->errors, 'errors');
1348 }
1349 } else {
1350 setEventMessages($object->error, $object->errors, 'errors');
1351 $error++;
1352 break;
1353 }
1354 }
1355 } else {
1356 setEventMessage('UserNotFound', 'errors');
1357 $error++;
1358 }
1359
1360 if (!$error) {
1361 if ($nbok > 1) {
1362 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1363 } else {
1364 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1365 }
1366 $db->commit();
1367 $toselect=array();
1368 } else {
1369 $db->rollback();
1370 }
1371}
1372
1373if (!$error && ($action == 'affectuser' && $confirm == 'yes') && $permissiontoadd) {
1374 $db->begin();
1375
1376 $usertoaffect=GETPOST('usertoaffect');
1377 $projectrole=GETPOST('projectrole');
1378 $tasksrole=GETPOST('tasksrole');
1379 if (!empty($usertoaffect)) {
1380 foreach ($toselect as $toselectid) {
1381 $result = $object->fetch($toselectid);
1382 //var_dump($contcats);exit;
1383 if ($result > 0) {
1384 $res = $object->add_contact($usertoaffect, $projectrole, 'internal');
1385 if ($res >= 0) {
1386 $taskstatic = new Task($db);
1387 $task_array = $taskstatic->getTasksArray(0, 0, $object->id, 0, 0);
1388
1389 foreach ($task_array as $task) {
1390 $tasksToAffect = new Task($db);
1391 $result = $tasksToAffect->fetch($task->id);
1392 if ($result > 0) {
1393 $res = $tasksToAffect->add_contact($usertoaffect, $tasksrole, 'internal');
1394 if ($res < 0) {
1395 setEventMessages($tasksToAffect->error, $tasksToAffect->errors, 'errors');
1396 }
1397 }
1398 }
1399 $nbok++;
1400 } else {
1401 setEventMessages($object->error, $object->errors, 'errors');
1402 }
1403 } else {
1404 setEventMessages($object->error, $object->errors, 'errors');
1405 $error++;
1406 break;
1407 }
1408 }
1409 } else {
1410 setEventMessage('UserNotFound', 'errors');
1411 $error++;
1412 }
1413
1414 if (!$error) {
1415 if ($nbok > 1) {
1416 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1417 } else {
1418 setEventMessages($langs->trans("RecordsModified", $nbok), null);
1419 }
1420 $db->commit();
1421 $toselect=array();
1422 } else {
1423 $db->rollback();
1424 }
1425}
1426
1427if (!$error && ($massaction == 'enable' || ($action == 'enable' && $confirm == 'yes')) && $permissiontoadd) {
1428 $db->begin();
1429
1430 $objecttmp = new $objectclass($db);
1431 $nbok = 0;
1432 foreach ($toselect as $toselectid) {
1433 $result = $objecttmp->fetch($toselectid);
1434 if ($result>0) {
1435 if (in_array($objecttmp->element, array('societe'))) {
1436 $result =$objecttmp->setStatut(1);
1437 }
1438 if ($result <= 0) {
1439 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1440 $error++;
1441 break;
1442 } else {
1443 $nbok++;
1444 }
1445 } else {
1446 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1447 $error++;
1448 break;
1449 }
1450 }
1451
1452 if (!$error) {
1453 if ($nbok > 1) {
1454 setEventMessages($langs->trans("RecordsEnabled", $nbok), null, 'mesgs');
1455 } else {
1456 setEventMessages($langs->trans("RecordEnabled"), null, 'mesgs');
1457 }
1458 $db->commit();
1459 } else {
1460 $db->rollback();
1461 }
1462}
1463
1464if (!$error && ($massaction == 'disable' || ($action == 'disable' && $confirm == 'yes')) && $permissiontoadd) {
1465 $db->begin();
1466
1467 $objecttmp = new $objectclass($db);
1468 $nbok = 0;
1469 foreach ($toselect as $toselectid) {
1470 $result = $objecttmp->fetch($toselectid);
1471 if ($result>0) {
1472 if (in_array($objecttmp->element, array('societe'))) {
1473 $result =$objecttmp->setStatut(0);
1474 }
1475 if ($result <= 0) {
1476 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1477 $error++;
1478 break;
1479 } else {
1480 $nbok++;
1481 }
1482 } else {
1483 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1484 $error++;
1485 break;
1486 }
1487 }
1488
1489 if (!$error) {
1490 if ($nbok > 1) {
1491 setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
1492 } else {
1493 setEventMessages($langs->trans("RecordDisabled"), null, 'mesgs');
1494 }
1495 $db->commit();
1496 } else {
1497 $db->rollback();
1498 }
1499}
1500
1501if (!$error && $action == 'confirm_edit_value_extrafields' && $confirm == 'yes' && $permissiontoadd) {
1502 $db->begin();
1503
1504 $objecttmp = new $objectclass($db);
1505 $e = new ExtraFields($db);// fetch optionals attributes and labels
1506 $e->fetch_name_optionals_label($objecttmp->table_element);
1507
1508 $nbok = 0;
1509 $extrafieldKeyToUpdate = GETPOST('extrafield-key-to-update');
1510
1511
1512 foreach ($toselect as $toselectid) {
1514 $objecttmp = new $objectclass($db); // to avoid ghost data
1515 $result = $objecttmp->fetch($toselectid);
1516 if ($result>0) {
1517 // Fill array 'array_options' with data from add form
1518 $ret = $e->setOptionalsFromPost(null, $objecttmp, $extrafieldKeyToUpdate);
1519 if ($ret > 0) {
1520 $objecttmp->insertExtraFields();
1521 } else {
1522 $error++;
1523 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1524 }
1525 } else {
1526 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1527 $error++;
1528 break;
1529 }
1530 }
1531
1532 if (!$error) {
1533 if ($nbok > 1) {
1534 setEventMessages($langs->trans("RecordsDisabled", $nbok), null, 'mesgs');
1535 } else {
1536 setEventMessages($langs->trans("save"), null, 'mesgs');
1537 }
1538 $db->commit();
1539 } else {
1540 $db->rollback();
1541 }
1542}
1543
1544if (!$error && ($massaction == 'affectcommercial' || ($action == 'affectcommercial' && $confirm == 'yes')) && $permissiontoadd) {
1545 $db->begin();
1546
1547 $objecttmp = new $objectclass($db);
1548 $nbok = 0;
1549
1550 foreach ($toselect as $toselectid) {
1551 $result = $objecttmp->fetch($toselectid);
1552 if ($result>0) {
1553 if (in_array($objecttmp->element, array('societe'))) {
1554 $result = $objecttmp->setSalesRep(GETPOST("commercial", "alpha"));
1555 }
1556 if ($result <= 0) {
1557 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1558 $error++;
1559 break;
1560 } else {
1561 $nbok++;
1562 }
1563 } else {
1564 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1565 $error++;
1566 break;
1567 }
1568 }
1569
1570 if (!$error) {
1571 if ($nbok > 1) {
1572 setEventMessages($langs->trans("CommercialsAffected", $nbok), null, 'mesgs');
1573 } else {
1574 setEventMessages($langs->trans("CommercialAffected"), null, 'mesgs');
1575 }
1576 $db->commit();
1577 } else {
1578 $db->rollback();
1579 }
1580}
1581
1582// Approve for leave only
1583if (!$error && ($massaction == 'approveleave' || ($action == 'approveleave' && $confirm == 'yes')) && $permissiontoapprove) {
1584 $db->begin();
1585
1586 $objecttmp = new $objectclass($db);
1587 $nbok = 0;
1588 foreach ($toselect as $toselectid) {
1589 $result = $objecttmp->fetch($toselectid);
1590 if ($result > 0) {
1591 if ($objecttmp->statut != Holiday::STATUS_VALIDATED) {
1592 setEventMessages($langs->trans('StatusOfRefMustBe', $objecttmp->ref, $langs->transnoentitiesnoconv('Validated')), null, 'warnings');
1593 continue;
1594 }
1595 if ($user->id == $objecttmp->fk_validator) {
1596 $objecttmp->oldcopy = dol_clone($objecttmp);
1597
1598 $objecttmp->date_valid = dol_now();
1599 $objecttmp->fk_user_valid = $user->id;
1600 $objecttmp->statut = Holiday::STATUS_APPROVED;
1601
1602 $verif = $objecttmp->approve($user);
1603
1604 if ($verif <= 0) {
1605 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1606 $error++;
1607 }
1608
1609 // If no SQL error, we redirect to the request form
1610 if (!$error) {
1611 // Calculcate number of days consumed
1612 $nbopenedday = num_open_day($objecttmp->date_debut_gmt, $objecttmp->date_fin_gmt, 0, 1, $objecttmp->halfday);
1613 $soldeActuel = $objecttmp->getCpforUser($objecttmp->fk_user, $objecttmp->fk_type);
1614 $newSolde = ($soldeActuel - $nbopenedday);
1615
1616 // The modification is added to the LOG
1617 $result = $objecttmp->addLogCP($user->id, $objecttmp->fk_user, $langs->transnoentitiesnoconv("Holidays"), $newSolde, $objecttmp->fk_type);
1618 if ($result < 0) {
1619 $error++;
1620 setEventMessages(null, $objecttmp->errors, 'errors');
1621 }
1622
1623 // Update balance
1624 $result = $objecttmp->updateSoldeCP($objecttmp->fk_user, $newSolde, $objecttmp->fk_type);
1625 if ($result < 0) {
1626 $error++;
1627 setEventMessages(null, $objecttmp->errors, 'errors');
1628 }
1629 }
1630
1631 if (!$error) {
1632 // To
1633 $destinataire = new User($db);
1634 $destinataire->fetch($objecttmp->fk_user);
1635 $emailTo = $destinataire->email;
1636
1637 if (!$emailTo) {
1638 dol_syslog("User that request leave has no email, so we redirect directly to finished page without sending email");
1639 } else {
1640 // From
1641 $expediteur = new User($db);
1642 $expediteur->fetch($objecttmp->fk_validator);
1643 //$emailFrom = $expediteur->email; Email of user can be an email into another company. Sending will fails, we must use the generic email.
1644 $emailFrom = $conf->global->MAIN_MAIL_EMAIL_FROM;
1645
1646 // Subject
1647 $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
1648 if (getDolGlobalString('MAIN_APPLICATION_TITLE')) {
1649 $societeName = $conf->global->MAIN_APPLICATION_TITLE;
1650 }
1651
1652 $subject = $societeName." - ".$langs->transnoentitiesnoconv("HolidaysValidated");
1653
1654 // Content
1655 $message = $langs->transnoentitiesnoconv("Hello")." ".$destinataire->firstname.",\n";
1656 $message .= "\n";
1657
1658 $message .= $langs->transnoentities("HolidaysValidatedBody", dol_print_date($objecttmp->date_debut, 'day'), dol_print_date($objecttmp->date_fin, 'day'))."\n";
1659
1660 $message .= "- ".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n";
1661
1662 $message .= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$objecttmp->id."\n\n";
1663 $message .= "\n";
1664
1665 $trackid = 'leav'.$objecttmp->id;
1666
1667 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1668 $mail = new CMailFile($subject, $emailTo, $emailFrom, $message, array(), array(), array(), '', '', 0, 0, '', '', $trackid);
1669
1670 // Sending email
1671 $result = $mail->sendfile();
1672
1673 if (!$result) {
1674 setEventMessages($mail->error, $mail->errors, 'warnings'); // Show error, but do no make rollback, so $error is not set to 1
1675 $action = '';
1676 }
1677 }
1678 }
1679 } else {
1680 $langs->load("errors");
1681 setEventMessages($langs->trans('ErrorNotApproverForHoliday', $objecttmp->ref), null, 'errors');
1682 }
1683 } else {
1684 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1685 $error++;
1686 break;
1687 }
1688 }
1689
1690 if (!$error) {
1691 if ($nbok > 1) {
1692 setEventMessages($langs->trans("RecordsApproved", $nbok), null, 'mesgs');
1693 } elseif ($nbok == 1) {
1694 setEventMessages($langs->trans("RecordAproved"), null, 'mesgs');
1695 }
1696 $db->commit();
1697 } else {
1698 $db->rollback();
1699 }
1700}
1701
1702if (!$error && ($massaction == 'increaseholiday' || ($action == 'increaseholiday' && $confirm == 'yes')) && $permissiontoapprove) {
1703 $db->begin();
1704 $objecttmp = new $objectclass($db);
1705 $nbok = 0;
1706 $typeholiday = GETPOST('typeholiday', 'alpha');
1707 $nbdaysholidays = GETPOST('nbdaysholidays', 'double');
1708
1709 if ($nbdaysholidays <= 0) {
1710 setEventMessages($langs->trans("WrongAmount"), "", 'errors');
1711 $error++;
1712 }
1713
1714 if (!$error) {
1715 foreach ($toselect as $toselectid) {
1716 $balancecpuser = $objecttmp->getCPforUser($toselectid, $typeholiday);
1717 if (!empty($balancecpuser)) {
1718 $newnbdaysholidays = $nbdaysholidays + $balancecpuser;
1719 } else {
1720 $newnbdaysholidays = $nbdaysholidays;
1721 }
1722 $result = $holiday->addLogCP($user->id, $toselectid, $langs->transnoentitiesnoconv('ManualUpdate'), $newnbdaysholidays, $typeholiday);
1723 if ($result <= 0) {
1724 setEventMessages($holiday->error, $holiday->errors, 'errors');
1725 $error++;
1726 break;
1727 }
1728
1729 $objecttmp->updateSoldeCP($toselectid, $newnbdaysholidays, $typeholiday);
1730 if ($result > 0) {
1731 $nbok++;
1732 } else {
1733 setEventMessages("", $langs->trans("ErrorUpdatingUsersCP"), 'errors');
1734 $error++;
1735 break;
1736 }
1737 }
1738 }
1739
1740 if (!$error) {
1741 if ($nbok > 1) {
1742 setEventMessages($langs->trans("HolidayRecordsIncreased", $nbok), null, 'mesgs');
1743 } elseif ($nbok == 1) {
1744 setEventMessages($langs->trans("HolidayRecordIncreased"), null, 'mesgs');
1745 }
1746 $db->commit();
1747 $toselect=array();
1748 } else {
1749 $db->rollback();
1750 }
1751}
1752
1753//if (!$error && $massaction == 'clonetasks' && $user->rights->projet->creer) {
1754if (!$error && ($massaction == 'clonetasks' || ($action == 'clonetasks' && $confirm == 'yes'))) {
1755 $num = 0;
1756
1757 dol_include_once('/projet/class/task.class.php');
1758
1759 $origin_task = new Task($db);
1760 $clone_task = new Task($db);
1761
1762 foreach (GETPOST('selected') as $task) {
1763 $origin_task->fetch($task, $ref = '', $loadparentdata = 0);
1764
1765 $defaultref = '';
1766 $obj = !getDolGlobalString('PROJECT_TASK_ADDON') ? 'mod_task_simple' : $conf->global->PROJECT_TASK_ADDON;
1767 if (getDolGlobalString('PROJECT_TASK_ADDON') && is_readable(DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . getDolGlobalString('PROJECT_TASK_ADDON') . ".php")) {
1768 require_once DOL_DOCUMENT_ROOT . "/core/modules/project/task/" . getDolGlobalString('PROJECT_TASK_ADDON') . '.php';
1769 $modTask = new $obj();
1770 $defaultref = $modTask->getNextValue(0, $clone_task);
1771 }
1772
1773 if (!$error) {
1774 $clone_task->fk_project = GETPOST('projectid', 'int');
1775 $clone_task->ref = $defaultref;
1776 $clone_task->label = $origin_task->label;
1777 $clone_task->description = $origin_task->description;
1778 $clone_task->planned_workload = $origin_task->planned_workload;
1779 $clone_task->fk_task_parent = $origin_task->fk_task_parent;
1780 $clone_task->date_c = dol_now();
1781 $clone_task->date_start = $origin_task->date_start;
1782 $clone_task->date_end = $origin_task->date_end;
1783 $clone_task->progress = $origin_task->progress;
1784
1785 // Fill array 'array_options' with data from add form
1786 $ret = $extrafields->setOptionalsFromPost(null, $clone_task);
1787
1788 $taskid = $clone_task->create($user);
1789
1790 if ($taskid > 0) {
1791 $result = $clone_task->add_contact(GETPOST("userid", 'int'), 'TASKEXECUTIVE', 'internal');
1792 $num++;
1793 } else {
1794 if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1795 $langs->load("projects");
1796 setEventMessages($langs->trans('NewTaskRefSuggested'), '', 'warnings');
1797 $duplicate_code_error = true;
1798 } else {
1799 setEventMessages($clone_task->error, $clone_task->errors, 'errors');
1800 }
1801 $action = 'list';
1802 $error++;
1803 }
1804 }
1805 }
1806
1807 if (!$error) {
1808 setEventMessage($langs->trans('NumberOfTasksCloned', $num));
1809 header("Refresh: 1;URL=".DOL_URL_ROOT.'/projet/tasks.php?id=' . GETPOST('projectid', 'int'));
1810 }
1811}
1812
1813$parameters['toselect'] = (empty($toselect) ? array() : $toselect);
1814$parameters['uploaddir'] = $uploaddir;
1815$parameters['massaction'] = $massaction;
1816$parameters['diroutputmassaction'] = isset($diroutputmassaction) ? $diroutputmassaction : null;
1817
1818$reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1819if ($reshook < 0) {
1820 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1821}
$object ref
Definition info.php:79
Class to manage members of a foundation.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage categories.
Class to manage customers orders.
const STATUS_DRAFT
Draft status.
const STATUS_VALIDATED
Validated status.
Class for ConferenceOrBoothAttendee.
Class to manage standard extra fields.
const STATUS_DRAFT
Draft status.
const STATUS_VALIDATED
Validated (need to be paid)
const STATUS_VALIDATED
Validated status.
const STATUS_DRAFT
Draft status.
const STATUS_REFUSED
Refused.
const STATUS_CANCELED
Canceled.
const STATUS_APPROVED
Approved.
const STATUS_DRAFT
Draft status.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage tasks.
Class to manage translations.
Class to manage Dolibarr users.
num_open_day($timestampStart, $timestampEnd, $inhour=0, $lastday=0, $halfday=0, $country_code='')
Function to return number of working days (and text of units) between two dates (working days)
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png) $', '^\.'), $nohook=false, $mode='')
Return file(s) into a directory (by default most recent)
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_is_file($pathoffile)
Return if path is a file.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:62
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0)
Set event message in dol_events session object.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null, $include=null)
Return array of possible common substitutions.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
pdf_getFormat(Translate $outputlangs=null, $mode='setup')
Return array with format properties of default PDF format.
Definition pdf.lib.php:85
pdf_getPDFFont($outputlangs)
Return font name to use for PDF generation.
Definition pdf.lib.php:266
pdf_getInstance($format='', $metric='mm', $pagetype='P')
Return a PDF instance object.
Definition pdf.lib.php:127
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.
Contact()
Old copy.
Definition index.php:572