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