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