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